Repository navigation
refactor(runtime): extract PerKeyGate<K> as substrate primitive (task #238) - #1582
Conversation
…238) The per-bucket serialization gate that landed in Fix-1 (#236) was a pattern, not a one-off. Reviewer-1 architectural audit flagged it as the #1 highest-leverage extraction: an exact-shape collision-free gate keyed by an arbitrary K, with structural eviction via Arc::strong_count. This commit: 1. Promotes the pattern to runtime::PerKeyGate<K> — Arc<DashMap<K, Arc<tokio::sync::Mutex<()>>>> wrapper with acquire(&K) -> Arc<Mutex<()>> (DashMap entry().or_insert_with() shard-locked atomic create-or-observe) and try_evict(&K) (DashMap remove_if + Arc::strong_count == 1 — only the map slot remains, no waiter queued, no holder racing). 2. Migrates TrainingTriggerModule::submit_gates from inline Arc<DashMap<BucketKey, SubmitGate>> + inline acquire_gate() + try_evict_gate() to PerKeyGate<BucketKey>. Net: -79 LOC on the module, all 13 module tests + 1 stress test still pass. 3. Ships 6 default TDD tests + 2 stress tests on the primitive: - same-key acquires return the same Arc (collision-free) - different-key acquires return distinct Arcs (no false sharing) - try_evict drops the slot iff strong_count == 1 - try_evict on missing key is a no-op - try_evict while a waiter is queued is a no-op (structural safety) - re-acquire after eviction creates a fresh gate (no zombie reuse) - stress: concurrent acquire/evict cycles preserve serialization - stress: different keys proceed in parallel without corruption Honest scoping note for follow-ups (NOT in this PR): The audit recommended migrating four other call sites (generator/mod.rs, data/cursors, probe_stream, channel.rs). Closer inspection shows they are a DIFFERENT shape: - generator/mod.rs:99 uses std::sync::Mutex (not tokio's), because its critical section is sync (no await). PerKeyGate uses tokio::sync::Mutex. A PerKeyStdGate<K> variant would be honest. - data/cursors, probe_stream, channel.rs wrap REAL state (Arc<Mutex<Cursor>>, Arc<Mutex<Channel>>) rather than the pure-coordination Mutex<()> that PerKeyGate ships. They need a PerKeyResource<K, T> primitive — same eviction discipline, different payload. Separate PR, separate primitive. This PR ships the canonical pure-gate + the one exact-shape call site. The two follow-up primitives land in their own PRs once the use case ratifies their shape. Co-Authored-By: Claude Opus 4.7 <[email protected]>
…tgun (PR #1582 review fix) Reviewer-2's BLOCK on PR #1582 found the obvious footgun in v1: the caller's local `gate` binding from `acquire()` is still in scope when they call `try_evict(&key)`, so `Arc::strong_count >= 2` and eviction silently no-ops. The training_trigger migration replicated the leak inline — exactly the `[[auto-clean-is-structural-not-operational]]` failure the primitive was supposed to close. Reviewer-2 also flagged the docstring example as demonstrating the leak, and called out that no test caught the bug because production- shaped tests didn't assert on `submit_gates.len()`. This commit redesigns the API to make the leak structurally impossible: 1. `acquire(&K) -> Lease<K>` is now async and returns an RAII guard that owns BOTH the OwnedMutexGuard AND the gate Arc. 2. `Drop for Lease`: drops the guard (releases lock + guard's internal Arc clone), drops the lease's gate Arc, then runs `remove_if(strong_count == 1)`. The user CANNOT skip the eviction step and CANNOT hold an extra Arc clone outside the lease — the Arc is no longer exposed. 3. `try_evict` is REMOVED from the public API. There's nothing to misuse. 4. Lease is `#[must_use]` so callers can't accidentally drop it immediately (which would make the gate pointless). Migration of training_trigger: - `let gate = self.submit_gates.acquire(&key); let _lease = gate.lock().await;` → `let _lease = self.submit_gates.acquire(&key).await;` - All four explicit `drop(_lease); self.submit_gates.try_evict(&key);` pairs deleted — eviction is automatic on lease drop. Regression tests added to pin the structural-eviction invariant in production-shaped tests (not just unit tests on the primitive): - `submit_at_threshold_dispatches_and_clears` now asserts `trigger.submit_gates.len() == 0` after dispatch. - `flush_dispatches_partial_bucket` same. Test rigor improvements per PR #1582 test-rigor reviewer: - Renamed `concurrent_acquires_for_same_key_return_same_arc` (which was sequential, not concurrent) to `repeated_acquires_for_same_key_serialize`. Now uses `tokio::time::timeout` to prove the second acquire BLOCKS while the first lease is held — the real serialization invariant. - `try_evict_while_waiter_queued_is_noop` (which exercised only "a holder of the Arc who hasn't called lock yet") is now `gate_survives_first_lease_drop_while_second_holds`. Spawns a real second task that parks on `.lock().await` via `tokio::time::sleep` ordering. - Stress tests now use a read-yield-write witness on AtomicUsize instead of a HashSet::insert witness. A HashSet::insert would pass even with broken serialization (each task inserts a unique id regardless of mutual exclusion). The new witness: let prev = counter.load(Acquire); yield_now().await; counter.store(prev + 1, Release); A broken serialization produces lost updates → final value < N. All tests pass: - 5 PerKeyGate default - 2 PerKeyGate stress (with new genuine serialization witness) - 13 training_trigger module (including 2 new gate-leak regression assertions) - 1 training_trigger stress Doctrine alignment: - `[[auto-clean-is-structural-not-operational]]` — now actually structural, not "operational + reviewer-2-found-the-bug" - `[[no-fallbacks-ever]]` — no leak, no zombie gate, no orphan slot - `[[matrix-dojo-layer-loading-as-substrate-primitive]]` — gate primitive is now genuinely safe for use across the substrate Co-Authored-By: Claude Opus 4.7 <[email protected]>
v2 — RAII Lease (review fix)Reviewer-2's BLOCK was correct and the fix is structural. v1's What changed:
Production call sites simplified: // before (v1, with the footgun)
let gate = self.submit_gates.acquire(&key);
let _lease = gate.lock().await;
// ... work ...
drop(_lease);
self.submit_gates.try_evict(&key); // SILENT NO-OP because `gate` still in scope
// after (v2)
let _lease = self.submit_gates.acquire(&key).await;
// ... work ...
// _lease drops at scope end → lock released → gate evicted structurallyRegression tests pin the invariant in production-shaped code:
Test rigor improvements per the test-rigor reviewer's nits:
Test results (all pass):
Diff: +357/-224. The new file is longer because the design is more careful, the docs explain why, and the tests actually prove the invariants. |
…() doc Adversarial reviewer's two non-blocking nits on v2: 1. `Lease` was not re-exported from `runtime/mod.rs`, only `PerKeyGate`. Asymmetric — downstream callers wanting to type-annotate `let lease: Lease<K> = ...` would have to reach into the module path. Re-export both. 2. `len()` doc said "non-zero len() implies there ARE active leases". Strictly true only in steady state — between a Lease's gate.take() and remove_if running on another thread, the window briefly shows an entry with no active lease. Doc tightened to call out the caveat AND the typical case (synchronous Drop on owning task makes the caveat moot for production assertions). Both are doc/export polish, not behavior changes. Tests unchanged. Co-Authored-By: Claude Opus 4.7 <[email protected]>
v2 review-cleared — nits addressedAdversarial reviewer on v2 (4f37c53): APPROVE WITH NITS. Both nits now addressed in be615ed:
Reviewer-confirmed that v2 closes the v1 BLOCK:
Walkthroughs verified:
Final test matrix:
Ready for canary merge. |
… (task #239) (#1583) * refactor(runtime): extract LateBound<T> primitive + migrate 6 modules (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]> * docs(runtime): LateBound review nits — service_module docstring + Send+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]> --------- Co-authored-by: Claude Opus 4.7 <[email protected]>
…rd clones airc #1582 makes ensure_card_clone replace a held linked worktree with a card clone when nothing can be lost (a clean tree whose HEAD is on the remote). The old tree is moved aside whole, never deleted. Opus measured 93 linked checkouts on the M5, which would otherwise keep their gitdir in the deploy repo's .git. card_staging now probes each migration (card.checkout.migrated, with where the old tree went). 27a12d7 is an ancestor of 51f7869, so the pin move drops nothing. Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_01FRQWzgSfo79JtnwZywHKrE
…rd clones airc #1582 makes ensure_card_clone replace a held linked worktree with a card clone when nothing can be lost (a clean tree whose HEAD is on the remote). The old tree is moved aside whole, never deleted. Opus measured 93 linked checkouts on the M5, which would otherwise keep their gitdir in the deploy repo's .git. card_staging now probes each migration (card.checkout.migrated, with where the old tree went). 27a12d7 is an ancestor of 51f7869, so the pin move drops nothing. Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_01FRQWzgSfo79JtnwZywHKrE
…recious 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
…recious 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
…recious 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
…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]>
…anchored clone holding nothing unpublished is re-allocated (card 7f824214) (#5873) * Every held card checkout goes through airc's ensure_card_clone: an unanchored clone holding nothing unpublished is re-allocated (card 7f824214) Kimi on the Windows node, 2026-11-08: a clean, weeks-old card clone (e5fe473) with no allocation evidence was handed back to her as-is by stage_for_card's early return, so her hands sat on old code and work/submit could never name a base. airc e05c44d (#1668) makes ensure_card_clone re-allocate such a clone when nothing in it is unpublished (HEAD and every branch tip on the remote, clean tree, no stash) and refuse naming what it holds otherwise. The early return is deleted, so every existing checkout reaches it (the linked-worktree migration of #1582 needed the same path), and a re-allocation is probed as card.checkout.reallocated. Bumps the airc pin 22c9c0e -> e05c44d (6 commits; IPC_PROTOCOL_VERSION unchanged at 6). Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_01FRQWzgSfo79JtnwZywHKrE * A held turn and a submit route a checkout without allocation evidence through the stager too (Codex on #5873) Two more paths handed an existing checkout back as-is, so Kimi's anchorless clone never reached ensure_card_clone: restage_held_linked_checkout returned early for any present non-linked checkout, and next_after_submission submitted from any found path. One predicate, card_checkout::lacks_allocation_evidence (airc's allocation_evidence, off the runtime threads), is true unless evidence decodes against its creation anchor; both paths now send such a checkout to the stager (re-allocate, or refuse naming what it holds). A checkout with its evidence keeps the fast path. Test: none, valid, then the anchor deleted. continuum-mind card_checkout + card_staging: 12 passed (IntelMac, --features metal). Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_01FRQWzgSfo79JtnwZywHKrE * Only a checkout with no creation anchor goes to airc's stager; an anchored one predating the full allocation record keeps working (#5873 CI) 32ea routed any checkout without airc's full allocation record to ensure_card_clone, which refuses one holding unpushed work: a checkout with its creation anchor but from before airc wrote the record (continuum-core's a_checkout_derived_submit_publishes_her_patch_and_records_its_issuer) could no longer submit. Submit needs only the anchor. The predicate is now card_checkout::lacks_creation_anchor: Kimi's clone has none and still goes to the stager; an anchored one is reused. stage_for_card keeps its early return for an anchored, non-linked clone, so a claim never sends old anchored work to that refusal. Tests: none / anchor only / anchor gone; card_checkout + card_staging 12 passed, the failing continuum-core test passes (IntelMac, --features metal). 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]>
Summary
Promotes the per-bucket serialization gate that landed in Fix-1 (#236)
to a canonical substrate primitive:
runtime::PerKeyGate<K>.Reviewer-1's architectural audit (post-Fix-2 conversation) flagged this
as the #1 highest-leverage extraction: an exact-shape collision-free
gate keyed by an arbitrary
K, with structural eviction viaArc::strong_count == 1.What lands
New primitive —
core/continuum-core/src/runtime/per_key_gate.rsArc<DashMap<K, Arc<tokio::sync::Mutex<()>>>>wrapperacquire(&K) -> Arc<Mutex<()>>— DashMapentry().or_insert_with()gives shard-locked atomic create-or-observe (no double-insert race)
try_evict(&K)— DashMapremove_if+Arc::strong_count == 1(only the map slot remains, no waiter queued, no holder racing —
structural safety, not a heuristic)
len()/is_empty()for observabilityOne migration —
TrainingTriggerModuleSubmitGatetype alias + inlineacquire_gate()+inline
try_evict_gate()methodssubmit_gates: Arc<DashMap<BucketKey, SubmitGate>>withsubmit_gates: PerKeyGate<BucketKey>8 tests on the primitive:
concurrent_acquires_for_same_key_return_same_arc— collision-freeacquires_for_different_keys_return_distinct_arcs— no false sharingtry_evict_removes_gate_when_no_other_holders— happy pathtry_evict_on_missing_key_is_noop— defensivetry_evict_while_waiter_queued_is_noop— structural safetyre_acquire_after_eviction_creates_fresh_gate— no zombie reuseconcurrent_acquire_evict_cycles_preserve_serializationdifferent_keys_proceed_in_parallel_without_corruptionHonest scoping note (read before requesting wider migration)
The audit recommended migrating four other call sites
(
generator/mod.rs,data/cursors,probe_stream,channel.rs).Closer inspection shows they're a different shape:
generator/mod.rs:99usesstd::sync::Mutex(not tokio's), becauseits critical section is sync (no await).
PerKeyGateusestokio::sync::Mutex. APerKeyStdGate<K>variant would be honest —separate PR.
data/cursors,probe_stream,channel.rswrap real state(
Arc<Mutex<Cursor>>,Arc<Mutex<Channel>>) rather than thepure-coordination
Mutex<()>thatPerKeyGateships. They need aPerKeyResource<K, T>primitive — same eviction discipline, differentpayload. Separate PR, separate primitive.
This PR ships the canonical pure-gate + the one exact-shape call
site. The two follow-up primitives land in their own PRs once the use
case ratifies their shape (and a real second consumer appears for each).
Why structural eviction matters
The naive eviction pattern (
if no_one_holds_it { remove }) isracy — between the check and the remove, a new acquirer can register.
remove_if + Arc::strong_count == 1is single-atomic-on-the-shard andchecks holder count under the lock. Zero-coordination, zero-overhead
when there's no contention.
Doctrine alignment
no-fallbacks-ever— no "best effort" eviction, no orphan slots,no zombie gates
rust-is-the-core-node-is-the-shell— substrate primitive livesin Rust; no TS equivalent needed
auto-clean-is-structural-not-operational— eviction is part ofthe API, not an operator's responsibility
Test plan
cargo check -p continuum-core --lib --features metal,accelerate— cleancargo test -p continuum-core --lib --features metal,accelerate runtime::per_key_gate— 6/6 passcargo test -p continuum-core --lib --features metal,accelerate modules::training_trigger— 13/13 passcargo test -p continuum-core --lib --features metal,accelerate,stress-tests runtime::per_key_gate::stress— 2/2 passRelated
landed there
PerKeyStdGate,PerKeyResource) are NOT inthis PR
Co-Authored-By: Claude Opus 4.7 [email protected]
🤖 Generated with Claude Code