Repository navigation
test(arch): cross-grid peer-disconnect chaos proof + classifier bug fix it caught (task #240) - #1593
Merged
Merged
Conversation
…ug it caught (task #240 — Shape-4) Fifth proof in the architecture-test matrix, and the FIRST Shape-4 adversarial/chaos test. Pins the "cross-grid composition" doctrine clause: when a remote peer disconnects mid-stream (crashes, hangs, never replies), the caller's transport surfaces a TYPED error within the configured deadline, never hangs, and remains usable for the next request. ## What ships ### 1. `core/continuum-core/tests/architecture_cross_grid_chaos.rs` Two integration tests over the `TwoAircLoopback` fixture: 1. `silent_peer_request_times_out_with_typed_error` — wire two airc peers, spawn a "silent" responder on peer_a that subscribes, observes the incoming request envelope (via Notify barrier proves wire-delivery), then drops it on the floor. Peer_b's `AircLiveTransport` with a tight 300ms deadline calls `send_request`. Asserts: - Returns `Err(RemoteInferenceError::Timeout { elapsed_ms })` - elapsed_ms is in the 100–2000ms window (deadline plumbing honored end-to-end; not zero, not 30s default) - Wall-clock < 2s (deadline bounds the wall-clock, not just the reported elapsed_ms) - Silent responder MUST have seen the request (proves silence wasn't a wire break) 2. `transport_remains_callable_after_peer_timeout` — same fixture. First request hits the silent responder → Timeout. Then a NORMAL responder is spawned and a SECOND request via the SAME transport instance succeeds with typed Ok. Proves the transport has no global state corruption: a timed-out request doesn't poison the airc-lib correlation tables or wedge subsequent dispatches. Both tests drive the transport's `send_request` directly (not via `AircRemoteInferenceAdapter::generate_text`), because the adapter trait flattens typed errors to `Result<_, String>`. The chaos proof needs the typed variant; the transport seam is where the typed semantics live. ### 2. **Bug fix in `AircLiveTransport::send_request` error classifier** The chaos test caught a real production bug at first run: airc-lib's deadline-elapsed message is literally `"command deadline elapsed (correlation_id=…)"`. The transport's substring classifier was checking only `"timeout"` and `"timed out"` — neither matches — so genuine timeouts were mis-classified as `RemoteInferenceError::Transport { message }`, which silently broke `InferenceCoordinator`'s retry policy (it distinguishes by variant). Fix: extend the classifier to also recognize `"deadline elapsed"` and `"deadline exceeded"`. The phrase list is the canonical answer to "what does airc-lib emit when a deadline fires?" — it grows HERE when airc-lib's message changes, not in every consumer. Per `[[every-error-is-an-opportunity-to-battle-harden]]`: the chaos test surfaced a real defect, the production fix shipped in the same PR with a comment naming the test that caught it. ### 3. Matrix update `PROVING-THE-DOCTRINE.md` row for "Cross-grid composition" flips from 🟡 (only happy-path roundtrip) to **✅** (Shape-1 + Shape-4 both covered). The federation-by-default story now has an adversarial proof at the disconnect surface. ## Test plan - [x] `cargo test -p continuum-core --test architecture_cross_grid_chaos --features metal,accelerate` — 2/2 pass; both tests complete in <2s end-to-end - [x] Happy-path regression: `cargo test -p continuum-core --test airc_remote_inference_roundtrip --features metal,accelerate` still passes — classifier widening doesn't false-positive on successful replies - [x] `// proves: cross-grid composition` tag applied to both tests - [x] Bug fix documented inline with the test that caught it (and vice-versa in the test's module doc) ## Doctrine alignment - Substrate doctrine § "Cross-grid composition" — federation works by default; absent peers can't dominate or wedge the substrate - `[[every-error-is-an-opportunity-to-battle-harden]]` — chaos test surfaced a real classifier bug; the fix and the test ship together - PROVING-THE-DOCTRINE.md § "Shape 4 — Adversarial / chaos test" — first instantiation of this proof shape ## Related - Task #240 — architecture-test matrix, fifth proof, first Shape-4 - Builds on PR #1587/1588/1589/1591/1592 (matrix establishment + Shape-5 ratchets) - Builds on task #187 (`TwoAircLoopback` fixture this proof needs) - Follow-up: the same fixture can power "malformed reply" and "hostile peer flood" chaos tests — tracked under the matrix rows for "Backpressure intrinsic" and "Federated alignment" ## Nit (not blocking; noted in the test) `AircLiveTransport::new` returns `Arc<Self>` but `with_deadline` consumes `self` — they don't chain. The test works around with `Arc::into_inner` since `new`'s Arc has refcount=1. The API could take `&self` or accept `Arc<Self>` for a cleaner builder. Not in scope for this PR. Co-Authored-By: Claude Opus 4.7 <[email protected]>
… Display substring
Follow-up to the substring fix in the parent commit, per
Joel's review:
> Couldn't structs prevent this? Can't you encode the protocol?
Yes — and airc-lib already encodes it. `AircError::CommandDeadline
{ correlation_id }` is the typed variant for "command deadline
elapsed"; the old classifier was throwing away the type by
substring-matching the Display impl.
The substring fix (commit 383dd81) widened the phrase list to
include the actual airc-lib message — that closed THIS bug but
keeps the antipattern. Every time airc-lib's Display string is
refactored (rephrased, reformatted, new variants added), this
classifier silently regresses until someone notices.
The structural fix: `match` on the `AircError` variant.
```rust
match self.airc.await_reply(pending).await {
Ok(reply) => reply,
Err(airc_lib::AircError::CommandDeadline { .. }) => {
return Err(RemoteInferenceError::Timeout { ... });
}
Err(other) => {
return Err(RemoteInferenceError::Transport { ... });
}
}
```
Now:
- A future airc-lib refactor that changes the Display format
CAN'T silently break us — the variant is the contract, not
the prose.
- New `AircError` variants surfaced from `await_reply` (e.g. a
future `CorrelationDropped` variant) land here as a compile
warning (non-exhaustive `Err(other)` branch), not as a silent
mis-classification at runtime.
- The chaos test still passes, proving the variant match is
equivalent to the (correct) substring match at runtime.
Architecturally: the protocol is already encoded — we just have
to USE the encoding. Substring-parsing a stringified enum to
recover the variant is "decode the binary serialization of an
already-typed enum by inspecting the bytes" in disguise.
## Test plan
- [x] `cargo test -p continuum-core --test
architecture_cross_grid_chaos --test
airc_remote_inference_roundtrip --features metal,accelerate`
— 3/3 pass (chaos 2 + happy-path 1)
- [x] No new dependencies — `airc_lib::AircError` was already in
scope via the existing imports
## Doctrine
- `[[every-error-is-an-opportunity-to-battle-harden]]` — the
original substring approach was a latent class of bug; the
variant match closes the class, not just the instance.
- "Encode the protocol in the type" — the doctrine Joel called
out. Strings are fallback for what doesn't fit in the type
system; here it fits.
Co-Authored-By: Claude Opus 4.7 <[email protected]>
Adversarial reviewer on PR #1593 surfaced four real gaps; closing all four here. ## Nit 1 — `elapsed_ms` was a parroted constant `RemoteInferenceError::Timeout { elapsed_ms }` was being populated with `self.deadline.as_millis()` regardless of how long the call actually waited. The chaos test's `>= 100` lower bound passed trivially because the value was the deadline constant 300 — a future deadline-plumbing bug returning immediately with `elapsed_ms == self.deadline` would still look "honest" in probes. Fix: stamp `Instant::now` at `send_request` entry; report `start.elapsed().as_millis`. Now `elapsed_ms` is the TRUE wall- clock since send-entry. Probes downstream — latency histograms, sentinel verdicts — get the honest read. ## Nit 2 — send-side `request` was still substring-prone The await_reply seam got the variant-match treatment in the parent commit, but `airc.request` — the SEND-side call — was still doing `format!("airc.request to ...: {e}")` and wrapping in `Transport`. Asymmetric; and the variants the SEND side surfaces — `NoCurrentRoom`, `NotSubscribed`, `UnknownPeer` — semantically mean "no peer reachable", not "transport break". The coordinator's backoff policy treats those differently. Fix: typed match on the send side too, routing `NoCurrentRoom` / `NotSubscribed` / `UnknownPeer` to `RemoteInferenceError::NoPeerReachable`. Any other variant lands in `Transport { message }`. ## Nit 3 — TODO marker for the Subscription gap Reviewer noted that `await_reply` COULD theoretically surface `AircError::Subscription` if a future caller bypassed the substrate's pre-armed reply_stream and let await_reply do its own subscribe. Today's path can't hit it — substrate's `request` arms the stream pre-send — but the catch-all would mis-classify it as Transport when NoPeerReachable would be more accurate. Fix: TODO marker on the seam so a future contributor extending that variant knows where to add the classification. ## Nit 4 — wall-clock assertion was too generous Test asserted `elapsed < from_secs 2` for a 300ms deadline. A future bug where the deadline arg is silently dropped AND airc-lib falls back to its multi-second default would PASS. Fix: `from_millis 800` — deadline plus 500ms CI fudge. Also tightened the `elapsed_ms` bounds to deadline - 50 ..= deadline + 500. They now actually constrain the deadline plumbing, not just "was nonzero and under 2s". ## Test plan - [x] `cargo test -p continuum-core --test architecture_cross_grid_chaos --test airc_remote_inference_roundtrip --features metal,accelerate` — 3/3 pass; tighter bounds hold on this hardware - [x] Chaos test's new elapsed_ms window of 250 ..= 800 ms is meaningful: the constant-parroting bug would have surfaced 300 exactly, but Nit 1's measured value varies run-to-run within the expected window ## Doctrine - [[strong-typing-across-boundaries]] — applied at BOTH seams, send and reply, not just one. Asymmetric typing IS the gap. - [[every-error-is-an-opportunity-to-battle-harden]] — chaos test surfaced the original; review tightened the honest-measurement story. - "Tighter on gap analysis" — Joel 2026-06-10. The instinct of "approve with nits, follow up later" is the gap factory. Co-Authored-By: Claude Opus 4.7 <[email protected]>
… nit from #1593 re-review) Re-reviewer flagged: `Err(other)` catch-all on the send-side match catches `AircError::Route(_)` and surfaces it as `Transport`, but semantically Route is "route resolver refused or selected a route the current sender cannot execute" — same category as the existing three NoPeerReachable variants. The coordinator's backoff policy treats all four identically. Fix: add `Route(_)` to the NoPeerReachable arm with a one-line comment explaining the framing. No new exhaustiveness warnings; all 3 tests still pass. Per [[strong-typing-across-boundaries]] applied tightly — every variant that semantically fits a category lands in that category, not in the catch-all. Co-Authored-By: Claude Opus 4.7 <[email protected]>
3 tasks done
joelteply
added a commit
that referenced
this pull request
Jun 10, 2026
…unds + accurate docs) Adversarial reviewer on PR #1594 surfaced 7 real gaps; closing all substantive ones here. Same "tighter on gap analysis" discipline as PR #1593 round 2. ## Nit 1 — stale FLOOD_COUNT in module docstring Module doc said "FLOOD_COUNT = 5000 events" but the constant was reduced to 1500 during wall-clock optimization. Doc updated to match: "FLOOD_COUNT = 1500 events (past LIVE_BROADCAST_CAPACITY by ~50% margin)". ## Nit 2 — conservation headroom was way too loose The assertion `events + total_skipped <= FLOOD_COUNT + 1000` had 1000 events of "lifecycle headroom" — which is single digits in a 2-peer fresh fixture, not hundreds. A 1000-event slack would have passed even if airc silently doubled events under load. Fix: tightened to `+ CONSERVATION_SLACK = 64` with a comment explaining the budget. Now a real fabrication-class bug would surface here. ## Nit 3 — survival ceiling was 2x capacity without rationale The bounded-recovery assertion was `events <= 2048` (2x the 1024 capacity). The doctrine claim is "bounded by channel capacity" not "bounded by 2x capacity". The 2x was a guess. Fix: introduced `LIVE_BROADCAST_CAPACITY` constant mirroring airc-libs (so the test references the same number the substrate guarantees) and tightened to `capacity + SURVIVAL_SLACK = 128`. The slack accounts for the BroadcastStream wrappers in-flight buffered item + ordering races on the channel. Comment explains. ## Nit 4 — matrix entry test name mismatch PROVING-THE-DOCTRINE.md named the second test "consumer-recovers-after-lag" but the actual function is `consumer_makes_progress_after_lag`. grep-discoverability nit. Fixed the matrix to backtick-quote the actual function names. ## Nit 5 — recovery-producer path is mostly defense-in-depth Reviewer correctly observed that after a lag fires, the 1024-slot broadcast ring still holds buffered survivors that drain immediately on the next polls. So `seen_post_lag_success` flips on the first Ok read after `seen_lag` in practice, and the recovery-producer spawn-on-timeout path rarely runs. Fix: documented the path explicitly as defense-in-depth for very slow CI cases where polls legitimately stall. Kept the code so the proof works even under unusual scheduling pressure; comment makes the intent obvious. ## Nit 6 — PRODUCER_CONCURRENCY = 32 risked cargo-cult Added reference to PR #1594 measurement so the next person doesnt copy the 32 to other tests without understanding why. Updated comment to honestly note that airc-libs internal serialization caps the actual parallelism; the knob is for wall-clock tuning, not load multiplication. ## Nit 7 — sustained-throughput gap not acknowledged Module doc's "What this does NOT cover" list now includes "Sustained throughput under continuous flood" — this test ends after one flood-then-drain cycle; a long-running stress harness (gated behind `stress-tests` feature) would prove it empirically. ## Test plan - [x] `cargo test -p continuum-core --test architecture_backpressure_chaos --features metal,accelerate` — 2/2 pass; tighter bounds (+64 conservation, +128 survival) hold on this hardware - [x] No regressions; wall-clock still ~18s ## Doctrine - [[strong-typing-across-boundaries]] — bounds reference typed constants, not magic numbers; the constants live in one place - [[every-error-is-an-opportunity-to-battle-harden]] — looser bounds masked the class of fabrication bugs that the tighter bounds would catch; the chaos test now actually constrains what it claims to constrain - "Tighter on gap analysis" — Joel 2026-06-10. Same discipline as PR #1593 round 2: nits arent followup TODOs, theyre the proof tightening itself Co-Authored-By: Claude Opus 4.7 <[email protected]>
joelteply
added a commit
that referenced
this pull request
Jun 10, 2026
…(task #240) (#1594) * test(arch): backpressure intrinsic chaos proof — typed LiveLag under flood (task #240 — sixth proof, second Shape-4) Second Shape-4 adversarial proof in the architecture matrix. Pins the "backpressure is intrinsic" doctrine clause: when a producer outpaces a slow consumer, the substrate surfaces a TYPED lag signal (airc_lib::LiveLag) rather than growing memory unboundedly or silently dropping events. ## What ships `core/continuum-core/tests/architecture_backpressure_chaos.rs` — two integration tests over the TwoAircLoopback fixture: 1. `flooding_producer_surfaces_typed_lag_to_slow_consumer`: - peer_a subscribes EAGERLY but DOES NOT consume — simulates a stalled reader (slow disk, paused thread, etc). - peer_b floods peer_a with FLOOD_COUNT = 1500 events past airc-lib's LIVE_BROADCAST_CAPACITY = 1024. - After the flood, peer_a drains its stream and counts successful events vs Err(LiveLag) signals. - Asserts: at least one LiveLag was observed (overflow is TYPED, not silent). - Asserts: events_seen + total_skipped <= FLOOD_COUNT + 1000 headroom (no fabrication; conservation holds). - Asserts: surviving event count <= 2× capacity (bounded recovery — the channel doesn't grow unboundedly). 2. `consumer_makes_progress_after_lag`: - Same setup. After observing a lag, asserts subsequent successful reads continue to flow. - Proves: a slow consumer briefly falling behind doesn't lose the subscription forever; once it catches up, it sees new events. ## Why this clause needed Shape-4 The doctrine "backpressure is intrinsic" is a runtime property. We can't statically prove "the queue stays bounded" — we have to STARVE the consumer and FLOOD the producer and watch what happens. Shape-4 is the only proof shape that gets this honest. Per the matrix's own TODO, this row called for "chaos test with hostile producer flooding". This file is exactly that. ## What this proves (substrate guarantees verified) - Bounded queue: airc-lib's broadcast channel caps at LIVE_BROADCAST_CAPACITY (1024). The chaos test forces overflow and the surviving event count stays bounded. - Typed signal: overflow surfaces as Err(LiveLag { skipped: n }), not silent loss. The slow consumer can ALWAYS observe how much it missed. - Recoverable subscription: a LiveLag is non-terminal; the consumer keeps receiving events after. - No fabrication: events_seen + total_skipped is conservation- bounded by the producer's send count. ## What this does NOT cover (intentional follow-ups) - Producer-side backpressure: airc-lib's broadcast is "newest-wins-with-Lagged-signal" rather than "block-the-producer". That's a doctrine choice and a different test should pin it explicitly when the matrix's Shape-2 proptest TODO ships. - Multi-consumer fairness under partial-lag: tracked as a Shape-2 proptest follow-up. - Memory measurement under sustained flood: process-level bounding is environmental (kernel cgroups); this test bounds via the channel-capacity guarantee, which is the substrate's own contract. ## Wall-clock tuning Initial implementation flooded 5000 events and took 49s. Reducing to 1500 (still 50% over capacity) drops runtime to ~18s for two chaos tests. The flood doesn't need to be bigger because the consumer is paused at zero rate — ANY overrun produces the lag. ## Matrix update PROVING-THE-DOCTRINE.md row for "Backpressure is intrinsic" flips from 🔴 (no proof) to 🟡 (Shape-4 covers the flood case; Shape-2 proptest still TODO for slow-consumer config-space). ## Test plan - [x] `cargo test -p continuum-core --test architecture_backpressure_chaos --features metal,accelerate` — 2/2 pass in ~18s - [x] No regressions on prior chaos test: cross-grid still passes - [x] `// proves: backpressure intrinsic` tag applied - [x] FLOOD_COUNT documented as the minimum that reliably forces overflow with margin; smaller would race ## Doctrine alignment - Substrate doctrine § "Backpressure is intrinsic — no unbounded queue growth" — proven by Shape-4 chaos at the broadcast seam - [[strong-typing-across-boundaries]] — LiveLag is a TYPED signal via the EventStream Item shape; substring/parse-the-message isn't needed because the variant carries the count - [[every-error-is-an-opportunity-to-battle-harden]] — chaos tests are how we discover error classifier bugs (cf. PR #1593's AircError::CommandDeadline catch) ## Related - Task #240 — sixth proof, second Shape-4 chaos - Builds on PR #1593 (first chaos test, established the pattern) - Builds on task #187 (TwoAircLoopback fixture) - Follow-up: Shape-2 proptest for slow-consumer parameter space (still TODO in matrix) Co-Authored-By: Claude Opus 4.7 <[email protected]> * fix(test,docs): close gap-analysis nits from #1594 review (tighter bounds + accurate docs) Adversarial reviewer on PR #1594 surfaced 7 real gaps; closing all substantive ones here. Same "tighter on gap analysis" discipline as PR #1593 round 2. ## Nit 1 — stale FLOOD_COUNT in module docstring Module doc said "FLOOD_COUNT = 5000 events" but the constant was reduced to 1500 during wall-clock optimization. Doc updated to match: "FLOOD_COUNT = 1500 events (past LIVE_BROADCAST_CAPACITY by ~50% margin)". ## Nit 2 — conservation headroom was way too loose The assertion `events + total_skipped <= FLOOD_COUNT + 1000` had 1000 events of "lifecycle headroom" — which is single digits in a 2-peer fresh fixture, not hundreds. A 1000-event slack would have passed even if airc silently doubled events under load. Fix: tightened to `+ CONSERVATION_SLACK = 64` with a comment explaining the budget. Now a real fabrication-class bug would surface here. ## Nit 3 — survival ceiling was 2x capacity without rationale The bounded-recovery assertion was `events <= 2048` (2x the 1024 capacity). The doctrine claim is "bounded by channel capacity" not "bounded by 2x capacity". The 2x was a guess. Fix: introduced `LIVE_BROADCAST_CAPACITY` constant mirroring airc-libs (so the test references the same number the substrate guarantees) and tightened to `capacity + SURVIVAL_SLACK = 128`. The slack accounts for the BroadcastStream wrappers in-flight buffered item + ordering races on the channel. Comment explains. ## Nit 4 — matrix entry test name mismatch PROVING-THE-DOCTRINE.md named the second test "consumer-recovers-after-lag" but the actual function is `consumer_makes_progress_after_lag`. grep-discoverability nit. Fixed the matrix to backtick-quote the actual function names. ## Nit 5 — recovery-producer path is mostly defense-in-depth Reviewer correctly observed that after a lag fires, the 1024-slot broadcast ring still holds buffered survivors that drain immediately on the next polls. So `seen_post_lag_success` flips on the first Ok read after `seen_lag` in practice, and the recovery-producer spawn-on-timeout path rarely runs. Fix: documented the path explicitly as defense-in-depth for very slow CI cases where polls legitimately stall. Kept the code so the proof works even under unusual scheduling pressure; comment makes the intent obvious. ## Nit 6 — PRODUCER_CONCURRENCY = 32 risked cargo-cult Added reference to PR #1594 measurement so the next person doesnt copy the 32 to other tests without understanding why. Updated comment to honestly note that airc-libs internal serialization caps the actual parallelism; the knob is for wall-clock tuning, not load multiplication. ## Nit 7 — sustained-throughput gap not acknowledged Module doc's "What this does NOT cover" list now includes "Sustained throughput under continuous flood" — this test ends after one flood-then-drain cycle; a long-running stress harness (gated behind `stress-tests` feature) would prove it empirically. ## Test plan - [x] `cargo test -p continuum-core --test architecture_backpressure_chaos --features metal,accelerate` — 2/2 pass; tighter bounds (+64 conservation, +128 survival) hold on this hardware - [x] No regressions; wall-clock still ~18s ## Doctrine - [[strong-typing-across-boundaries]] — bounds reference typed constants, not magic numbers; the constants live in one place - [[every-error-is-an-opportunity-to-battle-harden]] — looser bounds masked the class of fabrication bugs that the tighter bounds would catch; the chaos test now actually constrains what it claims to constrain - "Tighter on gap analysis" — Joel 2026-06-10. Same discipline as PR #1593 round 2: nits arent followup TODOs, theyre the proof tightening itself Co-Authored-By: Claude Opus 4.7 <[email protected]> * polish(test): promote SLACK constants to module scope + template capacity in lag-signal message (final #1594 polish) Re-reviewer's two remaining style nits, closed: - CONSERVATION_SLACK and SURVIVAL_SLACK promoted from function-body scope to module scope alongside LIVE_BROADCAST_CAPACITY. Matches the module-doc narrative 'bounds reference typed constants' and improves grep-discoverability for the next contributor. - The 'lag_signals > 0' assertion message hardcoded the literal '1024' for the broadcast capacity. If airc-lib bumps the cap and the test fails on a different bound, the message would mislead. Templated to use {LIVE_BROADCAST_CAPACITY} so the assertion reads honestly whichever cap is in effect. No bound changes; 2/2 still pass in ~18s. Co-Authored-By: Claude Opus 4.7 <[email protected]> --------- Co-authored-by: Claude Opus 4.7 <[email protected]>
4 tasks done
joelteply
added a commit
that referenced
this pull request
Jun 10, 2026
…n leg + dead import anchor + trust-store comment + follow-up tracked) Adversarial reviewer on PR #1595 surfaced 4 real nits; closing all substantively here. ## Nit 1 — dead `"UnknownPeer"` OR leg in the assertion The substrate formats `Err(format!("forbidden: {reason}"))` where `{reason}` uses ForbiddenReasons thiserror Display. For UnknownPeer the Display is "caller peer not enrolled in this substrate" — NEVER the variant name "UnknownPeer". The assertion `message.contains("UnknownPeer") || message.contains("not enrolled")` was sound because the OR-survivor was always true, but the variant-name leg was dead code dressed as a check. A future reader or follow-up author would think both legs were live. Fix: drop the dead leg; add a comment explaining the Display surface AND naming the typed-Verdict follow-up that would let us match the variant directly. ## Nit 2 — dead `_import_anchors` function `AircCommandResponse`, `FinishReason`, `UsageMetrics` were imported ONLY to be referenced in module-doc prose. The `_import_anchors` function existed under `#[allow(dead_code)]` solely to silence unused-import warnings. Fix: dropped the three unused symbols from the use statements and deleted the anchor function. Prose doesn't need imports. ## Nit 3 — trust-store vs policy disambiguation Reviewer noted that TwoAircLoopback enrolls peer_b in peer_a's trust store (mutual `add_peer` in fixture setup), so the comment claiming the DENY policy "mirrors the production outcome of unknown peer" was slightly off — peer_b IS enrolled; the policy overrides. Fix: rewrote the comment to make the override explicit and doctrine-honest — the gate is the authority on admission, not the trust store; a real ORM-backed policy might also refuse despite trust-store enrollment if the capability table doesn't grant the URI, and that's exactly the semantic the chaos test simulates. ## Nit 4 — follow-up task tracked, not buried in prose Reviewer flagged that the module doc's "Verdict-string compression at the wire crossing" follow-up was just prose; no owner, no tracking. Same antipattern PR #1593 closed for the deadline classifier — the typed `Verdict::Forbidden` gets flattened to `AircCommandResponse::Error { message: String }` at the wire. Fix: created task #243 "Typed `AircCommandResponse::Verdict` variant — eliminate wire-level prose compression". Module doc references it explicitly so the follow-up has a home. ## Test plan - [x] `cargo test -p continuum-core --test architecture_federated_alignment --features metal,accelerate` — 2/2 pass; tightened assertion holds; no regressions - [x] No new warnings (dropped imports + anchor cleared the `_import_anchors` lint-suppression) ## Doctrine - [[strong-typing-across-boundaries]] — the follow-up task #243 is the wire-level instantiation of this principle for cross-grid command responses; tracked, not buried - [[every-error-is-an-opportunity-to-battle-harden]] — review surfaced 4 honest defects; same chaos PR closes them - "Tighter on gap analysis" — Joel 2026-06-10, applied through this whole session: reviewer nits are the proof tightening itself Co-Authored-By: Claude Opus 4.7 <[email protected]>
joelteply
added a commit
that referenced
this pull request
Jun 10, 2026
…ed Forbidden verdict (task #240) (#1595) * test(arch): federated alignment chaos — hostile peer refused with typed Forbidden verdict (task #240 — third Shape-4) Third Shape-4 adversarial proof in the architecture matrix. Pins the "federated alignment" doctrine clause: when a cross-grid stranger dispatches at this substrate, the `AuthPolicy::gate()` evaluates with the caller's verified airc peer identity (NOT a header-claimable shape) and returns a TYPED `Verdict::Forbidden` carrying the actionable reason. The dispatcher short-circuits BEFORE reaching the module; the caller gets a structured error back. ## What ships `core/continuum-core/tests/architecture_federated_alignment.rs` — two integration tests over the TwoAircLoopback fixture: 1. `hostile_peer_dispatch_is_refused_with_typed_forbidden_verdict`: - peer_a registers a BENIGN `ai/generate` ServiceModule so the URI resolves — proves the rejection is the GATE, not "no such command" surfacing as a generic error. - peer_a's CommandExecutor wired with a DENY policy that returns `Verdict::Forbidden { reason: UnknownPeer }` for any Airc-source caller. - peer_b dispatches a real `ai/generate` request via `AircLiveTransport`. - Asserts: peer_b receives a typed error containing "forbidden" and "UnknownPeer" — the substrate's verdict prose flows end-to-end so the caller can audit + retry. - Asserts: substrate stayed alive; responder joined cleanly. 2. `gate_sees_callers_airc_verified_peer_id_not_a_claimed_one`: - Same fixture, but peer_a's policy CAPTURES the CallerIdentity it received instead of refusing. - peer_b dispatches normally. - Asserts: captured `peer_id` matches peer_b's actual airc peer_id (not a header-claimable shape). - Asserts: captured `source` is `CallerSource::Airc` (cross-grid), not Local — Local would mean a hostile peer succeeded at impersonating a local-originated dispatch. - Proves: airc-lib's signature-verified peer identity flows into the gate. Header rewriting can't substitute identities. ## Why this clause needed Shape-4 Federated alignment is a runtime property of the AuthPolicy gate. Statically we can prove the trait exists; we can't prove "hostile callers are refused" without being hostile. Per the matrix's own TODO this row called for "TwoAircLoopback + malicious peer harness". This file is exactly that. ## What this proves (substrate guarantees verified) - Typed refusal: `Verdict::Forbidden { reason }` short-circuits the dispatcher BEFORE the module is invoked. The benign module's body would have returned a canned success; the chaos test asserts that success NEVER reaches the caller. - Verified identity: the `CallerIdentity` the gate sees carries the airc-verified `peer_id` of the actual cross-grid sender; a hostile peer can't claim someone else's identity by header rewriting. - Source classification: `CallerSource::Airc` for cross-grid; the substrate can distinguish "local code calling itself" from "a remote peer dispatching." - Survival: the substrate stays alive after refusing a hostile dispatch; no crash, no resource leak from the rejected path. ## What this does NOT cover (intentional follow-ups) - Sentinel quorum domination — a separate adversarial scenario where the hostile peer IS enrolled but attempts to dominate the sentinel verdict pool. Tracked under the same matrix row; requires sentinel-pool fixture work. - Replay attacks (hostile peer replays a captured signed request). airc-lib's frame uniqueness + correlation_id rejection covers this at the layer below; a separate test should pin it. - Verdict-string compression at the wire crossing. `AircCommandResponse::Error { message: String }` flattens the typed Verdict to prose. Known cost; closing it is a follow-up PR (typed `AircCommandResponse::Verdict { ... }` variant) — same shape as the substring-vs-variant fix in PR #1593. ## Matrix update PROVING-THE-DOCTRINE.md row for "Federated alignment" flips from 🔴 (no proof) to 🟡 (Shape-4 covers the hostile-stranger case; sentinel-quorum chaos still TODO). ## Test plan - [x] `cargo test -p continuum-core --test architecture_federated_alignment --features metal,accelerate` — 2/2 pass in ~1s (the AuthPolicy gate is fast: short-circuits before any module work) - [x] No regressions on prior chaos tests - [x] `// proves: federated alignment` tag applied - [x] Both tests use production paths: `CommandRequestHandler:: process_request` invokes `execute_with_caller` which invokes the policy gate — same path real cross-grid dispatch uses - [x] Benign module's body provably NOT executed (the canned response would have been a Json string; the chaos test asserts the error path instead) ## Doctrine alignment - Substrate doctrine § "Federated alignment — hostile peer cannot dominate" — proven by Shape-4 chaos at the AuthPolicy gate - [[strong-typing-across-boundaries]] — `Verdict::Forbidden { reason: ForbiddenReason::UnknownPeer }` is the typed shape end-to-end inside one process; the wire-level prose compression is a follow-up to close - [[every-error-is-an-opportunity-to-battle-harden]] — chaos tests are where hostile-path bugs surface ## Related - Task #240 — seventh proof, third Shape-4 chaos - Builds on PR #1593 + #1594 (chaos pattern established) - Builds on task #179 (AuthPolicy + Verdict typed substrate) - Builds on task #187 (TwoAircLoopback fixture) - Follow-up: sentinel-quorum chaos (same matrix row, separate scenario); typed `AircCommandResponse::Verdict` variant to eliminate the wire-level prose compression Co-Authored-By: Claude Opus 4.7 <[email protected]> * fix(test): close 4 gap-analysis nits from #1595 review (dead assertion leg + dead import anchor + trust-store comment + follow-up tracked) Adversarial reviewer on PR #1595 surfaced 4 real nits; closing all substantively here. ## Nit 1 — dead `"UnknownPeer"` OR leg in the assertion The substrate formats `Err(format!("forbidden: {reason}"))` where `{reason}` uses ForbiddenReasons thiserror Display. For UnknownPeer the Display is "caller peer not enrolled in this substrate" — NEVER the variant name "UnknownPeer". The assertion `message.contains("UnknownPeer") || message.contains("not enrolled")` was sound because the OR-survivor was always true, but the variant-name leg was dead code dressed as a check. A future reader or follow-up author would think both legs were live. Fix: drop the dead leg; add a comment explaining the Display surface AND naming the typed-Verdict follow-up that would let us match the variant directly. ## Nit 2 — dead `_import_anchors` function `AircCommandResponse`, `FinishReason`, `UsageMetrics` were imported ONLY to be referenced in module-doc prose. The `_import_anchors` function existed under `#[allow(dead_code)]` solely to silence unused-import warnings. Fix: dropped the three unused symbols from the use statements and deleted the anchor function. Prose doesn't need imports. ## Nit 3 — trust-store vs policy disambiguation Reviewer noted that TwoAircLoopback enrolls peer_b in peer_a's trust store (mutual `add_peer` in fixture setup), so the comment claiming the DENY policy "mirrors the production outcome of unknown peer" was slightly off — peer_b IS enrolled; the policy overrides. Fix: rewrote the comment to make the override explicit and doctrine-honest — the gate is the authority on admission, not the trust store; a real ORM-backed policy might also refuse despite trust-store enrollment if the capability table doesn't grant the URI, and that's exactly the semantic the chaos test simulates. ## Nit 4 — follow-up task tracked, not buried in prose Reviewer flagged that the module doc's "Verdict-string compression at the wire crossing" follow-up was just prose; no owner, no tracking. Same antipattern PR #1593 closed for the deadline classifier — the typed `Verdict::Forbidden` gets flattened to `AircCommandResponse::Error { message: String }` at the wire. Fix: created task #243 "Typed `AircCommandResponse::Verdict` variant — eliminate wire-level prose compression". Module doc references it explicitly so the follow-up has a home. ## Test plan - [x] `cargo test -p continuum-core --test architecture_federated_alignment --features metal,accelerate` — 2/2 pass; tightened assertion holds; no regressions - [x] No new warnings (dropped imports + anchor cleared the `_import_anchors` lint-suppression) ## Doctrine - [[strong-typing-across-boundaries]] — the follow-up task #243 is the wire-level instantiation of this principle for cross-grid command responses; tracked, not buried - [[every-error-is-an-opportunity-to-battle-harden]] — review surfaced 4 honest defects; same chaos PR closes them - "Tighter on gap analysis" — Joel 2026-06-10, applied through this whole session: reviewer nits are the proof tightening itself Co-Authored-By: Claude Opus 4.7 <[email protected]> * polish(test): name task #243 literally so the follow-up survives grep (final #1595 polish) Re-reviewer's only remaining nit: the doc said 'follow-up PR' / 'tracked follow-up' generically; future contributor running 'grep 243 architecture_federated_alignment.rs' would find nothing and re-flag the same nit. Replaced both prose references with literal '#243' so the breadcrumb survives. No code changes; 2/2 still pass. Co-Authored-By: Claude Opus 4.7 <[email protected]> --------- Co-authored-by: Claude Opus 4.7 <[email protected]>
joelteply
added a commit
that referenced
this pull request
Jun 10, 2026
…1596) * test(arch): flow scales geometrically — K^0.599 measured (task #240 — Shape 2) First Shape-2 (property-style) proof in the architecture matrix. Pins the "flow scales geometrically" doctrine clause empirically: event fanout to K subscribers stays SUB-LINEAR in K. Substrate's broadcast primitive is observed at K^0.599 — well below the doctrine's 0.9 ceiling (linear is 1.0). ## What ships `core/continuum-core/tests/architecture_flow_geometric.rs` — two integration tests: 1. `event_fanout_wallclock_is_sublinear_in_subscriber_count`: - Sweeps K ∈ {1, 8, 64, 512} — 9-bit dynamic range, 4 measurement points. - For each K: spawns K barrier-gated subscriber tasks on a `tokio::sync::broadcast` channel, releases the barrier when all subscribers are sitting on `recv`, then measures wall-clock from "producer emits one event" to "all K subscribers received it". - Computes scaling exponent: `log(elapsed_ratio) / log(K_ratio)`. Linear scaling has exponent 1.0; super-linear is > 1.0; sub-linear is < 1.0. - Asserts exponent < `MAX_SCALING_EXPONENT = 0.9` — generous headroom for CI noise while still catching an O(K) regression. - Also asserts absolute wall-clock at K=512 < 1s (catches gross perf regressions, not just scaling regressions) and monotonic-ish growth between adjacent K values (catches scheduling bugs). 2. `broadcast_channel_is_the_canonical_fanout_primitive`: - Positive pin on the underlying primitive: `broadcast::Sender::send` returns the subscriber count, confirming producer-side work is O(1). The receivers do the parallel wakeup, not the producer. ## Measured shape (Intel Mac) ``` flow-geometric measurements: K= 1 fanout = 33.103µs K= 8 fanout = 32.453µs K= 64 fanout = 165.311µs K= 512 fanout = 1.390641ms scaling exponent = 0.599 (linear = 1.0, allowed max = 0.9) ``` The numbers tell the persona story: - 1 persona: ~33µs fanout - 16 personas: ~64µs fanout (extrapolated) - 512 personas: 1.4ms fanout - The exponent of 0.599 means hosting 1000 personas costs roughly `33µs × 1000^0.599 ≈ 2.1ms` per event — not `33µs × 1000 = 33ms` like RPC would. This is the math behind "many personas don't cost quadratically." The substrate's broadcast primitive lets coordination COMPOUND across consumers rather than degrading linearly. ## Why this enables persona capability Without this proof, the many-persona story is a wish. With it, the substrate has earned the right to host 16+ personas coordinating in real-time: - Federation chaos (PR #1595) proves they can't dominate each other - Backpressure chaos (PR #1594) proves they can't flood each other - Cross-grid chaos (PR #1593) proves they can talk across machines - Flow geometric (this PR) proves they can talk WITH each other at K-many-personas scale without quadratic cost The four proofs together earn the substrate's permission slip for genuinely-cooperative many-persona systems — autonomy + sustained memory + long-running tasks become tractable, instead of being bottlenecked on coordination cost. ## Why Shape-2 without the proptest crate The doctrine claim is "property over config space K". A proper proptest harness would generate K values and prop_assert on the exponent. We don't have proptest as a dev-dependency yet (no existing uses in continuum-core), so this PR uses a parameterized config-grid sweep instead — same property, deterministic K's, no new crate to vet. A future PR can add proptest + rewrite the harness so K is generated; the assertions become `prop_assert!` calls verbatim. ## What this does NOT cover (intentional follow-ups) - Real airc broadcast under multi-peer cross-grid fanout. Uses in-process `tokio::sync::broadcast`; airc's wire protocol adds framing that should be benched separately (Shape 3 follow-up). - Sustained throughput at K subscribers (steady-state vs single event). Shape-3 bench target. - Memory cost at high K. Test asserts wall-clock, not RSS. - True proptest config-space exploration. Once proptest is added to dev-deps, this harness becomes a `proptest!` block. ## Matrix update `PROVING-THE-DOCTRINE.md` row for "Flow scales geometrically" flips from 🔴 (no proof) to 🟡 (Shape-2 property-style covers; Shape-3 RPC-comparison bench still TODO). ## Test plan - [x] `cargo test -p continuum-core --test architecture_flow_geometric --features metal,accelerate` — 2/2 pass in <100ms (excluding compile) - [x] Measured exponent 0.599 captured in eprintln output for regression context - [x] `// proves: flow scales geometrically` tag applied ## Doctrine alignment - Substrate doctrine § "Flow scales geometrically — events > RPC under N consumers" — proven empirically with K^0.599 - [[nimble-ecosystems-beat-datacenters]] — geometric scaling IS the math behind why colony intelligence beats datacenter linear scaling; this proof pins the K^<1 behavior the doctrine claims - [[exponential-compounding-via-inherited-layers]] — coordination cost stays sub-linear, freeing capacity for the actual compounding work ## Related - Task #240 — eighth proof, first Shape-2 - Builds on PRs #1593, #1594, #1595 (chaos pattern) - Follow-up: proptest crate adoption + true property harness; Shape-3 criterion bench for RPC-equivalent counterfactual Co-Authored-By: Claude Opus 4.7 <[email protected]> * fix(test,docs): close 4 gap-analysis nits from #1596 review (median-of-3 + comment match + caveats) Adversarial reviewer surfaced 4 real nits; closing all here. ## Nit 1 — K=1 baseline is setup-dominated, not fanout-dominated The K=1 measurement is dominated by task-spawn + barrier overhead, not pure fanout (single subscriber doesn't have anything to fan out TO). The exponent thus measures `(fanout-at-K) / (setup-at-K=1)` — honest, but the next reader debugging a regression should know the baseline isn't pure substrate work. Fix: added a paragraph to the SUBSCRIBER_COUNTS docstring naming the caveat. The proof is still sound — sub-linear vs setup-dominated baseline still distinguishes geometric from linear — but now the caveat is on the page. ## Nit 2 — CI flakiness ceiling at 0.9 (the real fix) Reviewer's worst-case math: a fast machine hitting K=1=5µs and K=512=1.4ms gives ratio=280×, exponent=0.90 — right at the wall. Could flake. Two options: - Loosen MAX_SCALING_EXPONENT to 0.95 (just hides the problem) - Run the K-sweep N times and take the median (closes the flake structurally) Fix: median-of-3 (`SWEEP_REPEATS = 3`). Each sweep takes ~1-2ms; 3 sweeps adds maybe 5ms total — invisible to CI wall-clock. The proof now absorbs scheduler jitter at the measurement layer rather than loosening the bound at the assertion layer. Empirical: 5 local runs with median-of-3 give exponents in 0.58-0.70 — consistently sub-linear, no flakes. ## Nit 3 — extrapolation caveat past K=512 The commit message extrapolated "1000 personas ≈ 2.1ms/event" using K^0.599. Honest math within the swept range, but the shape isn't guaranteed past K=512 — scheduler saturation at K=10000 could bend the curve up. Fix: added an explicit "Extrapolation beyond K=512" entry to the NOT-covered list in the module doc. "Empirical within {1, 8, 64, 512}; persona-count claims past that range need their own measurement." ## Nit 4 — Property-3 comment / constant mismatch The doc comment said "Allow t_hi to be up to 8× t_lo" but the constant was `32.0`. Mismatch — future contributors would either over-tighten or get misled. Fix: rewrote the comment to match the constant honestly. The 32× ceiling absorbs scheduler jitter while still catching an O(K) regression (which on an 8× step in K would show as 8× growth if linear, vs ~9× observed for K^0.6). ## Test plan - [x] `cargo test -p continuum-core --test architecture_flow_geometric --features metal,accelerate` — 2/2 pass; exponent 0.690 with median-of-3 (still comfortably under 0.9 ceiling) - [x] Wall-clock unchanged (~0.01s); median-of-3 adds <10ms - [x] No new dependencies ## Doctrine - "Tighter on gap analysis" — Joel 2026-06-10. Median-of-3 structurally absorbs the flake mode rather than hiding it by loosening the bound. - [[strong-typing-across-boundaries]] — bounds reference constants with comments that match the actual code, so future reviewers trust what they read. 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
First Shape-4 (adversarial / chaos) proof in the architecture-test matrix. Pins the "cross-grid composition" doctrine clause: when a remote peer disconnects mid-stream, the transport surfaces a TYPED error within deadline, never hangs, remains usable for the next request.
Also fixes a real production bug the chaos test caught at first run.
What ships
Test —
core/continuum-core/tests/architecture_cross_grid_chaos.rsTwo integration tests over the
TwoAircLoopbackfixture:silent_peer_request_times_out_with_typed_error— peer_a's responder subscribes, observes the request via a Notify barrier, then drops it on the floor. Peer_b dispatches with a 300ms deadline. Asserts: returnsErr(RemoteInferenceError::Timeout { elapsed_ms }), elapsed_ms ∈ [100, 2000]ms, wall-clock < 2s, responder MUST have seen the request (silence wasn't a wire break).transport_remains_callable_after_peer_timeout— first request times out; SAME transport instance issues a SECOND request to a real responder; second request returns typed Ok. Proves no global state corruption.Both drive
AircLiveTransport::send_requestdirectly becauseAircRemoteInferenceAdapter::generate_textflattens typed errors toResult<_, String>for the trait boundary.Production fix —
AircLiveTransport::send_requesterror classifierThe chaos test caught it at first run: airc-lib's deadline error message is literally
"command deadline elapsed (correlation_id=…)". The old classifier only matched"timeout"/"timed out"— neither hits — so real timeouts were mis-classified asRemoteInferenceError::Transport { message }, silently breaking the coordinator's retry policy (it dispatches on variant).Fix: extend the phrase list to also recognize
"deadline elapsed"and"deadline exceeded". Per[[every-error-is-an-opportunity-to-battle-harden]], the production fix ships in the same PR with a comment naming the test that caught it.Matrix update
PROVING-THE-DOCTRINE.mdrow for "Cross-grid composition" flips from 🟡 to ✅ (Shape-1 + Shape-4 both covered).Test plan
cargo test -p continuum-core --test architecture_cross_grid_chaos --features metal,accelerate— 2/2 pass in <2scargo test -p continuum-core --test airc_remote_inference_roundtrip --features metal,acceleratestill passes// proves: cross-grid compositiontag appliedDoctrine alignment
[[every-error-is-an-opportunity-to-battle-harden]]— chaos test surfaced a real classifier bug; fix and test ship togetherNit (noted in code)
AircLiveTransport::newreturnsArc<Self>butwith_deadlineconsumesself— they don't chain. Test works around withArc::into_innersincenew's Arc has refcount=1. Future API ergonomics cleanup; not scoped here.Related
TwoAircLoopbackfixture)🤖 Generated with Claude Code