Repository navigation
refactor(runtime): extract LateBound<T> primitive + migrate 6 modules (task #239) - #1583
Merged
Merged
Conversation
… (task #239) PR #1582's architectural reviewer flagged the `OnceLock<Arc<CommandExecutor>>` install pattern as the next audit-cluster extraction. Post-#224 (GLOBAL_EXECUTOR deletion), every module that needs the executor declares an identical: executor: std::sync::OnceLock<Arc<crate::runtime::CommandExecutor>> with identical install: fn install_executor(&self, executor: Arc<CommandExecutor>) { let _ = self.executor.set(executor); } and identical accessor: self.executor.get().ok_or_else(|| "X: not installed yet".to_string()) Six modules did this verbatim. This commit collapses them. ## The primitive `runtime::LateBound<T>` is a typed wrapper around `OnceLock<Arc<T>>` with three improvements over raw OnceLock: 1. Type compression — `LateBound<CommandExecutor>` not `OnceLock<Arc<CommandExecutor>>`; the Arc is implicit. 2. Uniform error message — `.require()` produces "{name}: dependency not installed yet" so operators grepping logs see one shape across every module. 3. `.cloned()` convenience for the spawn-into-task pattern (`let exec = self.executor.cloned(); tokio::spawn(...)`) without `.get().cloned()` boilerplate. API: - `LateBound::new(name)` — const constructor with diagnostic name - `install(value)` — boot-time install; silently no-ops on second call (matches existing `let _ = .set()` semantics) - `require()` — Result<&Arc<T>, String> with uniform error - `get()` — Option<&Arc<T>> for soft sites - `cloned()` — Option<Arc<T>> for moves into spawn - `is_installed()` / `name()` — observability 5 unit tests pin: empty-slot diagnostic, install+ptr_eq accessors, second-install-is-noop, name-preservation, Debug-includes-name. ## Migrations (6 modules) - training_trigger - cognition (vision-describe accessor) - ai_provider (TS fallthrough accessor) - channel (executor_or_err helper) - sentinel (executor_or_err + 4 spawn-into-task .cloned() sites) - persona_instance_manager Each migration: - Field: `OnceLock<Arc<CommandExecutor>>` → `LateBound<CommandExecutor>` - Constructor: `OnceLock::new()` → `LateBound::new("module::executor")` - Install: `let _ = self.executor.set(x)` → `self.executor.install(x)` - Accessors using `.get().ok_or_else(...)`: → `self.executor.require()` (saves the per-module custom error string) - Accessors using `.get().cloned()`: → `self.executor.cloned()` All 169 tests across the 6 migrated modules pass unchanged. ## Out-of-scope (honest scoping) - `service_module.rs` (the trait) keeps the raw signature `install_executor(&self, executor: Arc<CommandExecutor>)` — that's the substrate-wide CONTRACT. The `LateBound<T>` is per-module state, not part of the contract. - The architectural reviewer's PerKeyResource<K, T> recommendation remains deferred — the three call sites (data cursors, probe streams, channel.rs SelfTaskGenerator) have explicit close or lifetime persistence, so the structural-eviction discipline that justified PerKeyGate doesn't transfer. PerKeyResource would be typed-convenience-only. Will revisit if a fourth call site with genuine eviction needs surfaces. Doctrine alignment: - `[[no-fallbacks-ever]]` — uniform error message surfaces boot- ordering bugs the same way across every module - `[[rust-is-the-core-node-is-the-shell]]` — substrate primitive lives in Rust; nothing to wire in TS - Reduces KLOC by ~12 lines per module while improving type clarity Co-Authored-By: Claude Opus 4.7 <[email protected]>
…d+Sync pin Adversarial reviewer's two non-blocking nits on PR #1583: 1. service_module.rs:402 trait docstring still referenced OnceLock<Arc<CommandExecutor>> as the canonical pattern. Updated to point at LateBound<CommandExecutor> + self.executor.install, which is now the canonical seam. 2. No compile-time pin on LateBound<T>: Send + Sync. Substrate modules are shared across dispatch tasks, so a regression that broke Send/Sync would surface as cryptic trait-bound errors at every call site. Added a const _: fn() block that asserts Send + Sync for both LateBound<()> (T-agnostic) and LateBound<CommandExecutor> (the production T). Compile-time defense against future refactors (e.g. swapping OnceLock for a non-Sync cell). Skipping reviewer nit #2 (preserve command-specific error context in cognition vision-describe accessor) per their own scoping note: fixable in a follow-up if anyone wires alerting on the old strings, which grep shows no such wiring today. Will revisit if alerting lands. Co-Authored-By: Claude Opus 4.7 <[email protected]>
This was referenced Jun 9, 2026
joelteply
added a commit
that referenced
this pull request
Jun 10, 2026
…t (task #240) (#1591) * test(arch): ban static `OnceLock<Arc<T>>` singletons via shape-5 ratchet (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]> * test(arch): harden singleton scanner per #1591 review nits (pub-prefix + 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]> --------- Co-authored-by: Claude Opus 4.7 <[email protected]>
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Summary
PR #1582's architectural reviewer flagged
OnceLock<Arc<CommandExecutor>>as the next audit-cluster extraction. Post-#224 (GLOBAL_EXECUTOR deletion), 6 modules declare an identical executor slot with identical install + accessor boilerplate. This PR collapses them.The primitive
runtime::LateBound<T>— typed wrapper aroundOnceLock<Arc<T>>with three improvements:LateBound<CommandExecutor>instead ofOnceLock<Arc<CommandExecutor>>; the Arc is implicit..require()produces"{name}: dependency not installed yet"so operators see one shape across every module..cloned()convenience for spawn-into-task without.get().cloned()boilerplate.API:
LateBound::new(name)— const constructor with diagnostic nameinstall(value)— boot-time install; silently no-ops on second call (matches existinglet _ = .set()semantics)require()→Result<&Arc<T>, String>with uniform errorget()→Option<&Arc<T>>for soft sitescloned()→Option<Arc<T>>for moves into spawnis_installed()/name()— observability5 unit tests pin: empty-slot diagnostic, install+ptr_eq, second-install-is-noop, name preservation, Debug includes name.
Migrations (6 modules)
"training-trigger::executor"require()"cognition::executor"require()(vision-describe)"ai-provider::executor".get()"channel::executor"executor_or_err→.cloned()"sentinel::executor"executor_or_err+ 4.cloned()for spawns"persona-instance-manager::executor"All 169 tests across the 6 migrated modules pass unchanged.
Out-of-scope (honest scoping)
service_module.rs(the trait) keeps the raw signatureinstall_executor(&self, executor: Arc<CommandExecutor>). That's the substrate-wide contract;LateBound<T>is per-module state.PerKeyResource<K, T>recommendation remains deferred — the three call sites (data cursors, probe streams, channel.rs SelfTaskGenerator) have explicit close or lifetime persistence already, so the structural-eviction discipline that justified PerKeyGate doesn't transfer. PerKeyResource would be typed-convenience-only. Will revisit if a fourth call site with genuine eviction needs surfaces.Doctrine alignment
[[no-fallbacks-ever]]— uniform error message surfaces boot-ordering bugs the same way everywhere[[rust-is-the-core-node-is-the-shell]]— substrate primitive, nothing to wire in TSTest plan
cargo check -p continuum-core --lib --features metal,acceleratecleancargo test runtime::late_bound— 5/5 passcargo teston all 6 migrated modules — 169/169 passRelated
🤖 Generated with Claude Code
Co-Authored-By: Claude Opus 4.7 [email protected]