Skip to content

statics: no static mut owns heap - render caches are thread_local!, and a tree-wide gate refuses the class (the plx_ui test abort) - #867

Merged
GLinnik21 merged 12 commits into
mainfrom
crx-statics-tls
Oct 20, 2026
Merged

GLinnik21 merged 12 commits into
mainfrom
crx-statics-tls

Conversation

@GLinnik21

Copy link
Copy Markdown
Collaborator

make test-crate C="plx_ui plx_screens" aborted plx_ui nearly every run (SIGABRT "pointer being freed was not allocated", or SIGSEGV in a CString drop). make check missed it by timing only.

The cause was a data race in tests on static mut TAB_CACHE (widgets.rs):

This branch removes the whole class: every static mut that owns heap is gone or named.

What changes

  • Render caches are thread_local!. The plx_ui caches go to thread_local! (the form nav.rs already used):
    • widgets TAB_CACHE, icons CACHE, text_view WRAP_CACHE, testpat CURRENT, anim ENTRIES;
    • popover CACHE, HELD and TARGET.
  • Elsewhere:
    • gfx text: the elide memo is a thread_local!, and the font cmaps load once into a OnceLock (a write-once pure function of the file).
    • The app's poster art-key memo is a thread_local! with Rc<str> keys, so a cache hit stays allocation-free and any cross-thread use is a compile error.
    • textinput's pending-commit queue is a thread_local!.
  • Kept as static mut: the three GL-context probes in gfx.rs. They allocate only after GL calls, on the GL thread, and no host test can reach them. Each is named with its reason in ci/allow/statics.txt.
  • The two tab-pulse tests take the motion test lock. They also reset process-global idle flags.
  • Borrows:
    • No RefCell borrow is held across a call that can re-enter its own cell.
    • A nested tab-metrics call with different labels now panics, where it used to free memory.
    • popover::begin_frame asserts in debug that the page redirect is closed at the frame boundary.

The gate, so the class cannot come back

  • The rule: ci/check-statics-heap.py, run by ci/check-statics.sh inside make check, refuses a static mut anywhere under rust-modules whose type owns heap, unless it is named with a reason.
  • How it reads types:
    • It follows the declared type through the tree's own struct, enum, union and type definitions.
    • It ignores associated types and enum variant names.
    • It treats std plain-data wrappers as plain while their parameter is plain.
    • It reports a macro-declared static by its macro.
    • A crashed detector fails red.
  • When it refuses something it misread as heap, the message says to fix the detector, not to allowlist the value.
  • The allowlist goes from 10 entries to 5.
  • Known gap, documented in the script header: a non-mut static that wraps UnsafeCell<heap> behind unsafe impl Sync. There is none today.

Verification

  • Regression tests, each crashing on the old code and passing on the fix through one shared harness (plx_base::testrace: a barrier, catch_unwind per thread, a 60 s deadline):
    • tab labels read back per thread: aborted 5/5;
    • the elide memo: SIGABRT on every run;
    • the art-key memo: abort and EXC_BAD_ACCESS;
    • the pending-commit queue: SIGTRAP and SIGABRT.
  • The original repro is now clean:
    • make test-crate C="plx_ui plx_screens": was FAILED plx_ui (exit -6), now 5 of 5 runs ok (1279 passed and 1624 passed);
    • the tab tests at --test-threads=5: 10 of 10 ok, against 5 of 6 crashes before.
  • The gate's own tests in tests/test_harness.py were watched red first. They cover refusing a heap static in any crate, the other spellings, plain data, associated types, std plain types, enum variants, and a macro static allowlisted by name.
  • Gates on the committed tree (773e7dd, which is this branch plus main through Cards: every released grid card lands on its own spring, so a held key no longer snaps the card it left #866; git status --short empty before and after):
  • Per-thread access cost: the ARM library is a static archive linked into a non-PIE executable (ci/check-elf.sh), so a thread_local! read is local-exec TLS with no __tls_get_addr. Nothing new allocates per frame. The armv7 cross-build is CI's.
  • One review, no blockers. It checked that every production access is on the owning thread, re-entrancy, destructors at exit, the OnceLock behaviour and the toolchain. Its two shoulds (gate false positives) and its nits are fixed here. One simplify pass.

🤖 Generated with Claude Code

GLinnik21 and others added 12 commits October 20, 2026 13:08
…free each other's tab labels

`static mut TAB_CACHE` was replaced and freed by `with_tab_metrics_for` on a key mismatch. Three
host tests reach it with different vocabularies (two tab-pulse tests with no lock, the top-bar test
under serial_for_motion), and `make test-crate C="plx_ui plx_screens"` runs five test threads: a
double free / use-after-free, SIGABRT "pointer being freed was not allocated" at widgets.rs:7257,
5 runs in 6 on the plx_ui binary. `make check` (two threads) only missed it by timing.

TAB_CACHE and the other heap-backed ui/ render caches that tests reach in parallel now use the
form `ci/check-statics.sh` names (nav.rs's precedent): icons.rs CACHE, text_view.rs WRAP_CACHE,
testpat.rs CURRENT, anim.rs ENTRIES and popover.rs's CACHE/HELD/TARGET snapshot. Each is touched by
the render thread only in production. No RefCell borrow is held across a call that could re-enter:
TAB_CACHE releases its exclusive borrow before the closure runs, wrap_memo and tex_for compute with
no borrow held, and FrameCache's methods are leaves. Eight entries leave ci/allow/statics.txt (10 ->
2; only recents.rs's two background-worker statics remain) and its pin in test_harness.py.

The two tab-pulse tests reset and assert plx_machine::idle's process-global flags, so they now take
serial_for_motion() as ui/src/CLAUDE.md's xfade rule requires. A new regression test drives four
threads through the tab-metrics path with a key mismatch on every call and asserts each reads its
own faces, words and widths back; it aborts 5 runs in 5 on the old static.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
TARGET's PageTarget has a Drop (it rebinds the frame framebuffer); it is None at every frame
boundary, so it only runs mid-frame on the GL thread. FrameCache has none.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
The popover snapshot cells use the LocalKey RefCell helpers (take, set, with_borrow,
with_borrow_mut) instead of spelling the borrows, the comments that narrated the old bug or
restated the code are shorter, and text_view.rs no longer calls its wrap memo process-wide.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
…h a reason

ci/check-statics.sh only read ui/, screens/, appkit/ and parts of data/, so the bug class that
aborted plx_ui's tests (TAB_CACHE: a heap-owning static mut replaced from parallel test threads)
could come back in any other crate. ci/check-statics-heap.py reads every static mut under
rust-modules, follows the declared type through the structs and aliases it names, and lists the
ones that own a Vec/HashMap/String/Box/Rc/CString. check-statics.sh refuses any not named in
ci/allow/statics.txt. This commit alone is red on purpose: it lists the seven the tree holds.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
…nto a OnceLock

ELIDE_CACHE was a static mut Option<HashMap<u64, String>> that elide() created, cleared past 512
entries and inserted into. plx_gfx's new regression test (eight threads, disjoint strings) aborts
3/3 on the old code: libmalloc 'pointer being freed was not allocated' in HashMap::clear (the
first, unbounded run of the test spun at 320% CPU for 13 minutes on a corrupted table instead).
The memo is now a thread_local! RefCell like MEASURED_BOUNDS and FITTED_LINES beside it, and no
borrow is held across elide_compute.

COV/COV_TRIED (the lazily loaded cmap of each fallback face) is a OnceLock per link: a pure
function of a file, so one load serves every thread, and get_or_init loads exactly once where the
old flag plus plain write let two first callers both write. link_covers, split_runs and
run_text_live no longer need unsafe. No host test reaches it (TEXT_OK is 0 in every one), so
there is no red for it.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
…sts no longer free each other's strings

PENDING was a static mut Vec<String> that on_event trims and pushes and start/drain clear. The new
regression test (four threads, each overflowing the 256-commit bound) crashes 3/3 on the old code:
Vec::push -> realloc at on_event, SIGTRAP twice and a libmalloc 'pointer being freed was not
allocated' abort once. No existing test reached it in parallel (they share the module's BUF lock
and the bridge never calls start/stop under cfg(test)), so this is the class, not an observed
suite crash. Production is the frame thread only: the SDL ladder, the txt: remote token
(ingress_token) and the bridge's keyboard calls all run there. STARTED and WIN are Copy and stay.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
… statics are named in the gate

KEY_MEMO was a static mut Option<KeyMemo> (nested HashMaps of Strings) handed out as a 'static str
borrow. The memo now lives in a thread_local RefCell and built_key returns an Rc<str> (a count bump
on the per-tile-per-frame hit path, no allocation), so the borrow no longer escapes the cell.
build() runs under the cell's borrow and only calls fan::fan_key and transcode_request, neither of
which reaches built_key. The new regression test (six threads, disjoint paths, 3x MEMO_CAP in one
request box) crashes 3/3 on the old code (SIGABRT, SIGSEGV, SIGABRT in KeyMemo::get_or_build and
reset_key_memo); every existing poster test already held testlock::serial(), so no suite crash was
observed here.

ci/allow/statics.txt names GROUND_PROBE, CONTROL_PROBE and FIELDST (gfx.rs), the three heap
statics that exist only behind a live GL context, each with its own reason; the harness pin for
that file moves 2 -> 5.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
…"render caches"

The doc-claim audit of the stage-2 diff found the statics gate's prose still calling
ci/allow/statics.txt the render-cache list and the gate "ui/ and screens/" only. Every render
cache left the list when it became a thread_local!, and the heap rule is tree-wide. Reword the
check-statics.sh header and its ok line, the check-python-steps.txt comment and the harness
docstring, and make the FIELDST reason say where the chain is actually stored.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
…ds more spellings

The simplify pass over d6ec840..HEAD found four hand-rolled copies of the same multi-thread
test scaffold (barrier, per-thread catch_unwind, no join, a deadline for a corrupted table that
spins), two of them without the deadline. They now call plx_base::testrace::race, which has its
own tests (every thread runs, a panic names its thread, a hung worker fails at the deadline).

The heap detector missed several spellings of the bug class and wrongly flagged one safe one:
a tree type that reuses a std name (screens' own `struct Cell`), an acronym alias, a declaration
sharing its line with an attribute or a fn body, a name on the next line, a macro_rules! static;
and it read the signature of a `fn(..) -> String` pointer as if the static owned the String.
`definition_body` loses its dead tail. check-statics.sh now goes red when the detector crashes
instead of reading an empty list. Small leftovers: a redundant closure and a hand-written
OnceLock array in text.rs, `PENDING.take()`, `KEY_MEMO.set(..)`, `Rc<str>` compared directly.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
ci/check-deps.sh's `threads` gate (zero `thread::spawn` outside task.rs) does not classify
plx_base's `cfg(any(test, feature = "test-support"))` modules as wholly-test files, so the raw
spawn in the new race harness failed it (13 harness tests red in the first re-run of `make check`).
task::spawn is the shared spawn and already carries test workers elsewhere.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
…ta or enum variants as heap

Review fixes for the tree-wide `static mut` heap rule (ci/check-statics-heap.py):

- A `type X = ..;` inside an `impl` or `trait` block is an associated type, not what a bare `X`
  names; only module-level and fn-local definitions resolve a name.
- The std plain-data types (SystemTime, NonZero*, Wrapping, Saturating, ManuallyDrop, RefCell,
  atomics, ..) are plain unless their parameter owns heap; the failure message now says to fix
  the detector, not allowlist plain data.
- An enum's variant names are not type names (a plain `enum Phase { Idle, Running }` static read
  as "defined nowhere in the tree").
- A macro-declared static is reported as `<macro>!` with its line, so a named entry can allow it
  (`$n` anchored in `grep -E` and never matched). The non-mut `UnsafeCell<heap>` gap is documented
  in the script header.

Also: src/textinput.rs says that nothing drains PENDING in production; poster.rs KEY_MEMO says what
rules out re-entry; popover.rs asserts no page redirect survives into begin_frame.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
@GLinnik21
GLinnik21 merged commit fd25378 into main Oct 20, 2026
19 checks passed
@GLinnik21
GLinnik21 deleted the crx-statics-tls branch October 20, 2026 12:50
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant