fix(tailwind): stop the dev server rewriting a tracked file (#911) (#918)

The runtime stylesheet moves to CONFIG_DIR. static/tailwind.min.css is never written again.

━━━ TWO DIFFERENT THINGS WERE SHARING ONE PATH ━━━

    static/tailwind.min.css   a BUILD ARTEFACT. Committed, image-baked, generated by scanning
                              the in-tree plugins only. CI's tailwind-fresh check verifies it.
    the RUNTIME sheet         PER-INSTALL STATE. Additionally scans whatever the user installed
                              into FEEDBACK_PLUGINS_DIR, so it differs machine to machine.

Writing the second over the first meant that MERELY RUNNING THE DEV SERVER from a git checkout
silently modified a tracked file. `git add -A` then swept a 100KB reshuffle of minified CSS
into the commit and ci/tailwind-fresh went red with a diff that explains nothing — on a PR
whose real change touched no Tailwind classes at all. It also wrote app state into the app
directory, which is read-only in some deploys.

A new route serves the runtime sheet when there is one and falls back to the committed one
otherwise. It is registered BEFORE the /static mount, which would otherwise swallow the path.

━━━ A PERSISTED SHEET MUST NOT OUTLIVE ITS REASON (Codex [P2] x2) ━━━

1. THE USER REMOVES THEIR PLUGINS. Startup only rebuilds when user plugins exist, so nothing
   would ever overwrite the stale sheet — and it still carries classes for plugins that are
   gone. With no user plugins the COMMITTED sheet is complete by definition. Guarded.

2. THE APP IS UPGRADED, and my first guard for this was WRONG. I compared mtimes. Codex: that
   is not a freshness signal across install methods — archives and container images routinely
   PRESERVE SOURCE MTIMES, so a just-shipped stylesheet can carry an OLDER timestamp than a
   runtime sheet a user built days ago. The mtime check then calls the stale one FRESH and it
   masks the new core CSS indefinitely — permanently, if no Tailwind toolchain is present to
   trigger a rebuild.

   Freshness is decided by CONTENT now. Each runtime build stamps a sidecar with the sha256 of
   the committed sheet it was made from. Core ships new CSS -> that file changes -> the hash
   changes -> the runtime sheet is correctly judged stale. Timestamps only gesture at the
   question that hashing answers.

Falling back to the committed sheet is always safe: at worst it lacks a just-installed plugin's
classes for the seconds until the async rebuild lands.

VERIFIED END TO END. Ran the real dev server with 3 plugins installed: it rebuilt Tailwind over
them (123,291 bytes), wrote the sheet + sidecar to CONFIG_DIR, still served /static/
tailwind.min.css at 200 — and `git diff` on the tracked file came back CLEAN.

8 tests. Bite-tested: reverting to the shared path fails 3, dropping the staleness guards fails
2 more.

pytest 2425, pyflakes 0, Codex 0.

Closes #911

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
This commit is contained in:
Byron Gamatos
2026-07-12 13:25:16 +02:00
committed by GitHub
co-authored by Claude Opus 4.8
parent 36cf77dc44
commit 0a6e0309e5
3 changed files with 303 additions and 4 deletions
+89 -3
View File
@@ -1,4 +1,4 @@
"""Regenerate ``static/tailwind.min.css`` over the full installed-plugin set.
"""Regenerate the runtime stylesheet over the full installed-plugin set.
Core's committed (and image-baked) stylesheet is built scanning only the
in-tree plugins. A plugin installed at runtime — into ``FEEDBACK_PLUGINS_DIR``
@@ -15,6 +15,7 @@ on a missing optional engine.
from __future__ import annotations
import hashlib
import json
import logging
import os
@@ -40,12 +41,84 @@ _lock = threading.Lock()
# in-flight build re-runs once more to pick up the newer plugin set instead of
# every concurrent trigger stacking its own redundant build.
_rerun = threading.Event()
_fingerprint_cache: dict = {}
# lib/ lives at ``<app>/lib``; the app root (static/, tailwind.config.js) is its
# grandparent.
APP_DIR = Path(__file__).resolve().parent.parent
def _committed_css_fingerprint() -> str:
"""Content hash of the SHIPPED stylesheet, cached on (mtime, size).
This is the marker that says WHICH CORE the runtime sheet was built against. Any change to
core's CSS regenerates static/tailwind.min.css, which changes this hash.
"""
committed = APP_DIR / "static" / "tailwind.min.css"
try:
st = committed.stat()
except OSError:
return ""
key = (st.st_mtime_ns, st.st_size)
cached = _fingerprint_cache.get("k")
if cached == key:
return _fingerprint_cache["v"]
h = hashlib.sha256(committed.read_bytes()).hexdigest()
_fingerprint_cache["k"] = key
_fingerprint_cache["v"] = h
return h
def runtime_meta_path() -> Path:
"""Sidecar recording which core the runtime sheet was built against."""
return runtime_css_path().with_suffix(".meta.json")
def runtime_css_is_current() -> bool:
"""True when the runtime sheet was built against the core we are running NOW.
WHY NOT mtime. Codex [P2] on the second cut of #911, and it was right: filesystem
timestamps are not a freshness signal across install methods. Archives and container images
routinely PRESERVE SOURCE MTIMES, so a just-shipped stylesheet can carry an OLDER mtime than
a runtime sheet a user built days ago. The mtime comparison then reports the stale sheet as
fresh and it masks the new core CSS indefinitely — permanently, if no Tailwind toolchain is
present to trigger a rebuild.
Content answers the question timestamps only gesture at: the sidecar records the hash of the
committed sheet this runtime build was made from. Core ships new CSS -> that file changes ->
the hash changes -> the runtime sheet is correctly judged stale.
"""
try:
meta = json.loads(runtime_meta_path().read_text())
except (OSError, ValueError):
return False
return bool(meta.get("committed_sha256")) and meta["committed_sha256"] == _committed_css_fingerprint()
def runtime_css_path() -> Path:
"""Where the RUNTIME-augmented stylesheet is written.
NOT ``static/tailwind.min.css``. That file is a BUILD ARTEFACT: committed, image-baked,
and generated by scanning only the in-tree plugins. This one is PER-INSTALL STATE — it
additionally scans whatever the user has installed into FEEDBACK_PLUGINS_DIR, so it differs
from machine to machine. They are different things and must not share a path.
Writing the runtime sheet over the committed one had two costs:
* IN A GIT CHECKOUT it silently modifies a TRACKED file. `git add -A` then sweeps a
100KB reshuffle of minified CSS into the commit and `ci/tailwind-fresh` goes red with a
diff that explains nothing. That is issue #911, and it cost a red run on a PR whose
real diff touched no Tailwind classes at all.
* IN A DEPLOY the app directory may be read-only. Writing app state into it is wrong on
principle and fatal in practice.
CONFIG_DIR is where per-install state already lives.
"""
cfg = (getenv_compat("CONFIG_DIR", "") or "").strip()
base = Path(cfg) if cfg else (Path.home() / ".local" / "share" / "feedback")
return base / "tailwind.min.css"
def _user_plugins_dir() -> Path | None:
raw = (getenv_compat("FEEDBACK_PLUGINS_DIR", "") or "").strip()
if not raw:
@@ -136,6 +209,14 @@ def _run_build(cmd_prefix: list[str], out: Path, src: Path) -> bool:
cwd=str(APP_DIR), timeout=120,
)
os.replace(staged, out)
# Stamp WHICH CORE this was built against. Without it, an upgraded app cannot tell a
# current runtime sheet from one that predates its new CSS.
try:
runtime_meta_path().write_text(json.dumps({
"committed_sha256": _committed_css_fingerprint(),
}))
except OSError:
log.warning("tailwind: could not write the runtime sheet's meta sidecar")
return True
except (subprocess.CalledProcessError, subprocess.TimeoutExpired) as e:
stderr = (getattr(e, "stderr", "") or "")[-500:]
@@ -153,7 +234,7 @@ def _run_build(cmd_prefix: list[str], out: Path, src: Path) -> bool:
def rebuild(reason: str = "") -> bool:
"""Regenerate ``static/tailwind.min.css`` over baked-in + user plugins.
"""Regenerate the RUNTIME stylesheet (see runtime_css_path) over baked-in + user plugins.
Returns ``True`` on a successful rebuild, ``False`` on any skip/failure.
Never raises — callers treat CSS freshness as best-effort. Concurrent
@@ -166,8 +247,13 @@ def rebuild(reason: str = "") -> bool:
log.info("tailwind rebuild skipped — engine/inputs unavailable%s", tag)
return False
out = APP_DIR / "static" / "tailwind.min.css"
out = runtime_css_path()
src = APP_DIR / "static" / "_tailwind.src.css"
try:
out.parent.mkdir(parents=True, exist_ok=True)
except OSError:
log.warning("tailwind rebuild skipped — cannot create %s%s", out.parent, tag)
return False
# If a rebuild is already running, flag a rerun and return instead of
# queueing a redundant build behind it.