Skip to content

test(arch): ban static OnceLock<Arc<T>> singletons via shape-5 ratchet (task #240) - #1591

Merged
joelteply merged 2 commits into
canaryfrom
chore/arch-test-singleton-ban
Jun 10, 2026
Merged

joelteply merged 2 commits into
canaryfrom
chore/arch-test-singleton-ban

Conversation

@joelteply

Copy link
Copy Markdown
Contributor

Summary

Third proof in the architecture-test matrix. Shape-5 build-graph ratchet pinning the "localized state per citizen" doctrine clause — bans new module-scope static OnceLock<Arc<T>> (and OnceCell<Arc<T>>) singletons.

  • Test ships at: core/continuum-core/tests/architecture_no_singleton_state.rs
  • Grandfathered budget: 12 existing singletons (mostly in live/* audio/video/avatar and modules/embedding.rs + modules/sentinel/mod.rs::GLOBAL_SENTINEL)
  • Ratchet only moves down. NEW singletons BLOCK; existing ones tracked for follow-up migration to LateBound<T> per PR refactor(runtime): extract LateBound<T> primitive + migrate 6 modules (task #239) #1583's pattern.
  • Positive pin: late_bound_remains_the_canonical_primitive asserts runtime/late_bound.rs exists, declares pub struct LateBound, and wraps OnceLock<Arc<...>>. Rename / deletion is loud, not silent.
  • Test mods are exempt via brace-depth counter so test fixtures can have whatever statics they need.

Why ratchet (not strict)

Same reason as the engine-OS layering ratchet (PR #1589): the 12 existing singletons need considered per-module migration (signal-handler plumbing for GLOBAL_SENTINEL, GPU manager threading for the live/* ones), not a blanket sweep.

Matrix update

PROVING-THE-DOCTRINE.md row for "Localized state per citizen" flips from 🟡 (TODO placeholder) to 🟡 (ratchet active, target ✅ at count 0).

Test plan

  • cargo test -p continuum-core --test architecture_no_singleton_state --features metal,accelerate — 2/2 pass
  • All 3 architecture-test integration files pass together: no-fallbacks (3) + engine-OS layering (3) + singleton ban (2) = 8/8
  • // proves: localized state per citizen tag applied

Doctrine alignment

  • Substrate doctrine § "Localized state per citizen"
  • [[late-bound-primitive]] — the install-once primitive that singletons migrate to

Related

🤖 Generated with Claude Code

…het (task #240 — third proof shape)

Third proof in the architecture-test matrix. Pins the
"localized state per citizen" doctrine clause — the substrate is
multi-citizen by design; module-scope `static OnceLock<Arc<T>>` is
the doctrine violation because it pretends substrate state is
process-global when in practice each peer / persona / citizen needs
its own runtime.

## What ships

`core/continuum-core/tests/architecture_no_singleton_state.rs` —
two integration tests:

1. `static_singleton_state_ratchet` — scans every `.rs` file under
   `core/continuum-core/src/`, finds lines matching
   `static NAME: <forbidden-type-shape>`, asserts the count doesn't
   grow beyond the current grandfathered budget of **12**. NEW
   singletons BLOCK; existing ones are tracked for follow-up
   migrations to `LateBound<T>` per PR #1583's pattern.

   Forbidden type shapes: `OnceLock<Arc<T>>`, `OnceCell<Arc<T>>`,
   `std::sync::OnceLock<Arc<T>>`, `once_cell::sync::OnceCell<Arc<T>>`.
   `OnceLock<T>` without `Arc` is a value primitive (allowed);
   per-instance struct fields are install-once DI (allowed —
   migrate to `LateBound<T>` for ergonomics over time).

   Test mods (`#[cfg(test)] mod tests { ... }`) are exempted via a
   simple brace-depth counter so fixture statics in tests don't
   trip the ratchet. Today's count is zero in test mods, but the
   exemption keeps the rule future-proof.

2. `late_bound_remains_the_canonical_primitive` — positive pin:
   `runtime/late_bound.rs` exists, declares `pub struct LateBound`,
   and wraps `OnceLock<Arc<...>>` internally. If the canonical
   primitive ever moves or its underlying type changes, the test
   is loud, not silent.

## The 12 grandfathered violations

All in `live/*` or `modules/*` — they predate `LateBound<T>` and
need per-module migration:

- `live/video/capture.rs::instance()` — VideoFrameCapture singleton
- `live/video/bevy_renderer/api.rs::RENDERER_GPU_MANAGER`
- `live/audio/tts/mod.rs::{TTS_GPU_MANAGER, TTS_REGISTRY}`
- `live/audio/vad/silero.rs::SILERO_SESSION` (+ raw variant in
  `silero_raw.rs`)
- `live/audio/stt/mod.rs::STT_REGISTRY`
- `live/avatar/registry.rs::AVATAR_REGISTRY`
- `modules/embedding.rs::{MODEL_CACHE, EMBEDDING_GPU_MANAGER, EMBEDDING_POOL}`
- `modules/sentinel/mod.rs::GLOBAL_SENTINEL` (read by signal
  handlers — needs different shutdown plumbing; trickiest one)

## Why ratchet (not strict)

Same reason as the engine-OS layering ratchet (PR #1589): the
existing violations require considered per-module migration
decisions, not a blanket sed sweep. The ratchet pattern: NEW ones
BLOCK, the count only goes DOWN, each cleanup PR rebaselines.
When 0 is reached, the clause graduates to strict enforcement.

This matches the proof-discipline doc's discipline: ship the
abstract recipe (the test) AND the literal first state (the
grandfathered count) together. Every subsequent PR ratchets down.

## Matrix update

`PROVING-THE-DOCTRINE.md` row for "Localized state per citizen"
flips from 🟡 (TODO placeholder) to 🟡 (ratchet active, target is
full ✅ when count = 0).

## What this catches going forward

- A new module that does `static GLOBAL_X: OnceLock<Arc<X>> = ...`
  instead of installing X on a per-instance `LateBound<X>` field
  will fail the test.
- A regression that reintroduces a `static GLOBAL_EXECUTOR` shape
  (the exact pattern PR #1583 closed for `CommandExecutor`) will
  fail the test BEFORE it reaches review.
- Forgotten `once_cell::sync::OnceCell<Arc<T>>` patterns (older
  spelling) are caught by the same scanner — qualified-path
  variants are in the forbidden list.

## Doctrine alignment

- Substrate doctrine § "Localized state per citizen" — each peer's
  runtime is its own state; no process-global Arc'd cells
- [[late-bound-primitive]] — the canonical install-once primitive
  for per-instance install-once DI

## Test plan

- [x] `cargo test -p continuum-core --test
      architecture_no_singleton_state --features metal,accelerate`
      — 2/2 pass; grandfathered count = 12 (exact match)
- [x] All 3 architecture-test integration files pass together:
      no-fallbacks (3) + engine-OS layering (3) + singleton ban (2)
      = 8/8
- [x] `// proves: localized state per citizen` tag convention
      applied
- [x] Ratchet logic verified (both grow-detection and
      shrink-detection paths via inspection of the panic branches)

## Related

- Task #240 (this PR adds the third proof to the matrix)
- Builds on PR #1583 (LateBound<T> primitive — the migration target)
- Builds on PR #1589 (ratchet pattern established)
- Follow-up: dedicated per-module cleanup PRs migrate the 12
  singletons to `LateBound<T>` or `ModuleContext`-threaded deps

Co-Authored-By: Claude Opus 4.7 <[email protected]>
…x + inline cfg-test + tokio OnceCell)

Reviewer on PR #1591 returned APPROVE-WITH-NITS with three trivial
forward-defense holes. Folding them in keeps the ratchet PR
self-complete instead of trailing a no-op-today follow-up.

## Hardening 1 — `pub static` / `pub(crate) static` / `pub(super) static`

The previous scanner required `trimmed.starts_with("static ")` — it
would silently skip `pub static FOO: OnceLock<Arc<X>>`. Verified zero
such patterns exist in tree today (the few `pub static`s all wrap
non-Arc types and would have been excluded by the type-pattern check
anyway), but a future contributor adding a visibility prefix to a
singleton declaration shouldn't slip past the ratchet.

Fix: strip the visibility modifier before the `starts_with("static ")`
check, same chained `trim_start_matches` order as the engine-OS
layering scanner.

## Hardening 2 — inline `#[cfg(test)] mod tests { ... }`

The previous test-mod-exemption parser handled the two-line form
(attribute on one line, `mod NAME {` on the next) but missed the
single-line collapsed form. Verified zero occurrences in `src/`
today (the inline shape appears only in docstrings inside
`generator/templates.rs`), but the parser should match the patterns
the compiler accepts.

Fix: detect the inline shape on the same line as `#[cfg(test)]` and
open the brace-depth scope immediately; also handle the
single-line balanced case (`#[cfg(test)] mod x {}`) by checking
test_mod_depth after the line's `{`/`}` count.

## Hardening 3 — `tokio::sync::OnceCell<Arc<T>>`

The previous forbidden-type list covered `std::sync::OnceLock`,
`OnceCell` (from `once_cell::sync`), but not the qualified
`tokio::sync::OnceCell` spelling. Currently used as a struct field
in `runtime/shared_compute.rs` (legitimate per-instance install-once)
but not as a static — adding the pattern closes the qualified-path
hole proactively.

## What this doesn't fix (deferred to follow-up)

- Reviewer nit 4 (raw brace counter could miscount on `{`/`}` inside
  string literals or block comments within a test mod). Realistic
  exposure near-zero — tests don't usually embed `{` in raw strings
  around statics. A real fix needs a tiny tokenizer; not worth the
  complexity until it bites. Tracked under #240.
- Reviewer nit 5 (tighten `late_bound_remains_the_canonical_primitive`
  to assert presence of `name:` / `slot:` fields). Optional polish;
  current assertions on the type and the underlying `OnceLock<Arc<`
  are sufficient for catching rename/deletion.

## Test plan

- [x] `cargo test -p continuum-core --test
      architecture_no_singleton_state --features metal,accelerate`
      — 2/2 pass (ratchet count still 12, unchanged behavior on
      today's tree)
- [x] Manually verified: no `pub static.*: OnceLock<Arc<` or
      inline `#[cfg(test)] mod tests {` patterns in tree today, so
      "no behavior change from these hardenings" claim is honest

Co-Authored-By: Claude Opus 4.7 <[email protected]>
@joelteply
joelteply merged commit 395130a into canary Jun 10, 2026
2 checks passed
@joelteply
joelteply deleted the chore/arch-test-singleton-ban branch June 10, 2026 00:43
joelteply added a commit that referenced this pull request Jun 10, 2026
…ratchet (task #240 — fourth proof shape) (#1592)

Fourth proof in the architecture-test matrix. Pins the "module
compose-by-event" doctrine clause — substrate-internal modules
compose via the event substrate (MessageBus subscribe/emit) or via
pre-bound handles, not by imperative `CommandExecutor::execute_*`
round-trips through the outer command interface inside the
cognition hot path.

## What ships

`core/continuum-core/tests/architecture_compose_by_event.rs` — two
integration tests:

1. `cognition_command_executor_calls_ratchet` — scans every `.rs`
   file under `core/continuum-core/src/cognition/`, finds lines
   matching `.execute_json(`, `.execute_with_caller(`,
   `.execute_ts(`, `.execute_ts_json(`, asserts the count doesn't
   grow beyond the current grandfathered budget of **1**. NEW
   calls BLOCK; the existing one is tracked under #112-#114
   (route persona response / should_respond / validate through
   inference handle).

   Bare `.execute(` is intentionally NOT in the forbidden list —
   it would generate false positives across futures, queues, and
   other APIs. If a typed `executor.execute(typed_args)` pattern
   appears inside cognition in a future refactor, extend the list.

   Test mods (`#[cfg(test)] mod ... { ... }`) are exempted via
   the same brace-depth parser as the singleton-ban test, with
   inline `#[cfg(test)] mod tests {` handling.

   Line comments (`//` lines) are skipped so doc comments quoting
   the very pattern being banned don't trip the scanner — this
   matters for cognition module top-of-file docs that reference
   `Commands.execute('cognition/...')` as the TS-side caller
   contract.

2. `command_executor_remains_the_outer_boundary` — positive pin:
   `runtime/command_executor.rs` exists, declares
   `pub struct CommandExecutor`, exposes `pub async fn execute_json`.
   If the type is renamed or `execute_json` moves, the test is
   loud, not silent — and the FORBIDDEN list in this test file
   needs updating to match.

## The 1 grandfathered violation

`cognition/vision_describe.rs::describe_image_via_ai_generate` calls
`executor.execute_json("ai/generate", ...)`. The clean fix is a
pre-bound `InferenceHandle` (cf. tasks #107-#108), called directly
the same way `airc_chat_demo` already does. Migration tracked under
#112-#114 (the inference-command-routing campaign) and #106
(ai/* namespace consolidation).

## Why ratchet (not strict)

Same reason as engine-OS layering and singleton-ban: the single
existing violation needs a considered migration (which `InferenceHandle`
to pre-bind, where to wire the lifecycle), not a sed sweep. NEW
violations BLOCK at PR time; the ratchet count graduates to ✅ when
#112-#114 land.

## Matrix update

`PROVING-THE-DOCTRINE.md` row for "Module compose-by-event" flips
from 🔴 (no proof) to 🟡 (ratchet active, target ✅ when count = 0).

## Test plan

- [x] `cargo test -p continuum-core --test
      architecture_compose_by_event --features metal,accelerate`
      — 2/2 pass; grandfathered count = 1 (exact match)
- [x] `// proves: module compose-by-event` tag applied
- [x] Ratchet logic verified (both grow-detection and
      shrink-detection paths via inspection)
- [x] Line-comment skip verified — the two pre-existing
      `Commands.execute(...)` doc references in
      `vision_describe.rs` and `rate_proposals/mod.rs` do NOT
      trip the scanner

## Doctrine alignment

- Substrate doctrine § "Module compose-by-event" — cognition
  composes via event substrate or pre-bound handles, not
  imperative request-response round-trips
- [[no-fallbacks-ever]] — the ratchet IS the no-fallback
  equivalent for the cognition→command-executor coupling at
  build-graph layer

## Related

- Task #240 — architecture-test matrix, fourth proof
- Builds on PR #1589 (ratchet pattern) and PR #1591 (singleton ban —
  same scanner shape)
- Migration follow-up: tasks #112-#114 (#113 is currently
  in_progress) → ratchet count goes 1 → 0 → strict

Co-authored-by: Claude Opus 4.7 <[email protected]>
joelteply added a commit that referenced this pull request Oct 19, 2026
…n it starts (card 573cc58a)

Fable's live receipt from the M5 deploy of #5132 (build 91ea7dba9,
04:10-05:10Z): card.checkout.migrated fired 0 times in an hour. All three
held checkouts (cc2db61d, 1b232595, e710ed0f) were linked, clean and
pushed, so all were eligible. Two defects, both mine:
1. stage_for_card returned any existing checkout before reaching
   ensure_card_clone, so the migration was unreachable for exactly the
   checkouts it was written for. A linked worktree now falls through to
   the clone path, which migrates it.
2. Staging ran only on a new claim, and residents keep their claims.
   card_staging::restage_held_linked_checkout runs from bind_card, as her
   turn on a held card starts and before her hands are rooted, so nothing
   of hers is running in the tree that may move. A card clone is
   untouched. If migration cannot happen, the old tree stays hers.

Also:
- The airc pin moves to 44478afa6 (#1591): a migrated clone borrows its
  llama.cpp submodule (453 MB) from a node mirror, instead of downloading
  it inside her turn. 51f7869 is an ancestor.
- persona_workspace.rs's 1,995-line test module moves, unchanged except a
  leading blank line, to cognition/persona_workspace/tests.rs
  (#![cfg(test)]). The higher-ring items it uses are imported once in the
  parent under #[cfg(test)], so upward imports stay at 256.
  BASELINE_LINES_OVER goes from 159,277 to 158,283.

Not compiled here (IntelMac rule): every edited file parses and
source-hygiene is 37/0. CI is the compile check, and Fable's next M5
deploy is the live check.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01FRQWzgSfo79JtnwZywHKrE
joelteply added a commit that referenced this pull request Oct 19, 2026
…n it starts (card 573cc58a)

Fable's live receipt from the M5 deploy of #5132 (build 91ea7dba9,
04:10-05:10Z): card.checkout.migrated fired 0 times in an hour. All three
held checkouts (cc2db61d, 1b232595, e710ed0f) were linked, clean and
pushed, so all were eligible. Two defects, both mine:
1. stage_for_card returned any existing checkout before reaching
   ensure_card_clone, so the migration was unreachable for exactly the
   checkouts it was written for. A linked worktree now falls through to
   the clone path, which migrates it.
2. Staging ran only on a new claim, and residents keep their claims.
   card_staging::restage_held_linked_checkout runs from bind_card, as her
   turn on a held card starts and before her hands are rooted, so nothing
   of hers is running in the tree that may move. A card clone is
   untouched. If migration cannot happen, the old tree stays hers.

Also:
- The airc pin moves to 44478afa6 (#1591): a migrated clone borrows its
  llama.cpp submodule (453 MB) from a node mirror, instead of downloading
  it inside her turn. 51f7869 is an ancestor.
- persona_workspace.rs's 1,995-line test module moves, unchanged except a
  leading blank line, to cognition/persona_workspace/tests.rs
  (#![cfg(test)]). The higher-ring items it uses are imported once in the
  parent under #[cfg(test)], so upward imports stay at 256.
  BASELINE_LINES_OVER goes from 159,277 to 158,283.

Not compiled here (IntelMac rule): every edited file parses and
source-hygiene is 37/0. CI is the compile check, and Fable's next M5
deploy is the live check.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01FRQWzgSfo79JtnwZywHKrE
joelteply added a commit that referenced this pull request Oct 19, 2026
…onfinement reads only the mirror's objects (card 573cc58a) (#5132)

* feat(work,code): a resident's card checkout is its own clone from a precious mirror (card 573cc58a)

Rebased onto canary 769df97 as one commit: the net change of the four
reviewed commits (e39d996..f0981c0), because #5080 moved
disk_eviction's tests to their own file.
- card_staging: a card's checkout is a standalone clone with alternates
  from ~/.airc/mirrors (airc #1581). A held linked worktree migrates when
  nothing can be lost (airc #1582), with a card.checkout.migrated probe.
  The airc pin moves to 51f7869 (old pin 27a12d7 is an ancestor).
- confinement: each mirror's objects/ is a read-only root for a
  workspace-reach caller.
- disk: airc-mirrors is a TrackedDir, and its eviction is deferred with a
  named owner.
- The cache-class eviction decisions (OWNED, DEFERRED) move out of
  disk_eviction/tests.rs into disk_eviction/eviction_decisions.rs, which
  their test reads. tests.rs goes from 1,145 to 930 lines; file_size
  baseline 159,447 to 159,305.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01FRQWzgSfo79JtnwZywHKrE

* fix(work): a resident's HELD linked checkout migrates when her turn on it starts (card 573cc58a)

Fable's live receipt from the M5 deploy of #5132 (build 91ea7dba9,
04:10-05:10Z): card.checkout.migrated fired 0 times in an hour. All three
held checkouts (cc2db61d, 1b232595, e710ed0f) were linked, clean and
pushed, so all were eligible. Two defects, both mine:
1. stage_for_card returned any existing checkout before reaching
   ensure_card_clone, so the migration was unreachable for exactly the
   checkouts it was written for. A linked worktree now falls through to
   the clone path, which migrates it.
2. Staging ran only on a new claim, and residents keep their claims.
   card_staging::restage_held_linked_checkout runs from bind_card, as her
   turn on a held card starts and before her hands are rooted, so nothing
   of hers is running in the tree that may move. A card clone is
   untouched. If migration cannot happen, the old tree stays hers.

Also:
- The airc pin moves to 44478afa6 (#1591): a migrated clone borrows its
  llama.cpp submodule (453 MB) from a node mirror, instead of downloading
  it inside her turn. 51f7869 is an ancestor.
- persona_workspace.rs's 1,995-line test module moves, unchanged except a
  leading blank line, to cognition/persona_workspace/tests.rs
  (#![cfg(test)]). The higher-ring items it uses are imported once in the
  parent under #[cfg(test)], so upward imports stay at 256.
  BASELINE_LINES_OVER goes from 159,277 to 158,283.

Not compiled here (IntelMac rule): every edited file parses and
source-hygiene is 37/0. CI is the compile check, and Fable's next M5
deploy is the live check.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01FRQWzgSfo79JtnwZywHKrE

* fix(work): a held linked tree that cannot migrate is not restaged on every turn (card 573cc58a)

Fable on #5132 at 5d2f157: a held linked tree that can never migrate
(dirty, detached, unpushed) was restaged at every turn start, each time
an ensure_mirror GitHub fetch, a submodule pass and an arrival, until she
committed.

restage_held_linked_checkout now tries only when the local checks the
migration itself needs already pass: clean (is_dirty), on a branch
(current_branch) and nothing unpushed (has_unpushed_work). These use
local git only, no network. It also tries at most once per carry interval
(card_carry::CARRY_SWEEP, 300 s) per (resident, card). The carry is what
pushes her commits, so that is when an unpushed tree can become
migratable. is_dirty and CARRY_SWEEP become pub(crate) for this.

Not compiled here (IntelMac rule): files parse; source-hygiene 37/0.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01FRQWzgSfo79JtnwZywHKrE

* hygiene: file_size baseline 158,255, card 573cc58a's splits measured on canary 16a075c

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01FRQWzgSfo79JtnwZywHKrE

---------

Co-authored-by: Claude Opus 5.5 (1M context) <[email protected]>
joelteply added a commit that referenced this pull request Oct 19, 2026
…5181)

airc's ensure_card_clone (pinned 44478af, #1591) initialises submodules on
every clone it creates or migrates: bounded by run_bounded, borrowing each
submodule's objects from its own mirror. stage_for_card then ran a second
`git submodule update --init --recursive` under a tokio timeout that
abandoned the child instead of killing it.

The second pass reached only those two outcomes plus a linked worktree that
migration kept (initialised when it was made): an existing card clone
returns Ready earlier, through checkout_path_for. So it was duplicate work
with an unkillable child. An airc init failure already arrives as stage
"worktree"; nothing matches on stage "submodules" (git grep).

source-hygiene: BASELINE_SPAWN_SITES 125 -> 124, measured by its ratchet.


Claude-Session: https://claude.ai/code/session_01FRQWzgSfo79JtnwZywHKrE

Co-authored-by: Claude Opus 5.5 (1M context) <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant