Skip to content

test(airc/realtime): concurrency stress tests — moment-of-truth preconditions pinned - #1492

Merged
joelteply merged 1 commit into
canaryfrom
test/airc-realtime-concurrency
May 31, 2026
Merged

joelteply merged 1 commit into
canaryfrom
test/airc-realtime-concurrency

Conversation

@joelteply

Copy link
Copy Markdown
Contributor

Summary

Per Joel 2026-05-30:

"Each persona exists in its own threads." + "Approaching moment of truth"

Multi-persona chat lands on InMemoryAircRealtimeStore via airc/realtime-publish. Several personas publishing concurrently to the same room (and reading replay concurrently) is the production scenario for the headless-Rust integration test. The four new tests pin the substrate's correctness invariants that the integration test will rely on.

Audit finding

The store uses ONE module-wide parking_lot::Mutex<AircRealtimeState>. Every publish + every replay takes the same lock.

✅ Correctness delivered — all state mutations atomic; per-room Lamport monotonicity holds; replay sees consistent snapshots.

⚠️ Throughput constrained — multi-room publishes serialize even though room state is independent. For 5–10 personas this is fine (sub-microsecond contention on in-memory ops). For 50+ it becomes a real bottleneck.

Future refinement (flagged, NOT in this PR): shard state by room_id (DashMap<Uuid, Mutex<RoomState>>). Unblocks multi-room throughput while keeping the same correctness contract. Not needed for moment-of-truth.

What's pinned

Every test runs flavor = "multi_thread", worker_threads = 4 so spawned tasks actually preempt on distinct OS threads.

Test Load Invariant
concurrent_publishes_to_same_room_lose_no_events_and_keep_lamports_contiguous 64 publishers → 1 room 0 losses, every published event_id appears exactly once, contiguous Lamport 1..64
concurrent_publishes_to_different_rooms_keep_independent_lamport_sequences 60 publishers → 3 rooms Each room's Lamport sequence INDEPENDENT — cross-room interleaving doesn't break per-room contiguity
replay_during_concurrent_publish_observes_consistent_snapshot 32 publishers + 8 replayers racing Each replay observes a consistent subset (no torn reads); final replay = 32 events
cursor_polling_during_concurrent_publish_never_loses_or_duplicates_events 40 staggered publishers + 1 cursor-polling consumer NO duplicate events (cursor monotonicity); every published event eventually observed

The cursor-polling test is the canonical hot path — chat clients, persona inbox subscribers, replay catchup on reconnect all use this pattern.

Test plan (17/17 pass)

test airc::realtime_store::tests::concurrent_publishes_to_same_room_lose_no_events_and_keep_lamports_contiguous ... ok
test airc::realtime_store::tests::concurrent_publishes_to_different_rooms_keep_independent_lamport_sequences ... ok
test airc::realtime_store::tests::replay_during_concurrent_publish_observes_consistent_snapshot ... ok
test airc::realtime_store::tests::cursor_polling_during_concurrent_publish_never_loses_or_duplicates_events ... ok

# Pre-existing (8) — all still pass:
test airc::realtime_store::tests::durable_events_replay_from_cursor ... ok
test airc::realtime_store::tests::ephemeral_presence_coalesces_and_expires_without_replay_pollution ... ok
test airc::realtime_store::tests::peer_manifest_coalesces_indexes_capabilities_and_stays_out_of_replay ... ok
test airc::realtime_store::tests::receipt_only_messages_are_not_replayed ... ok
test airc::realtime_store::tests::control_messages_are_replayable_for_reconnect ... ok
test airc::realtime_store::tests::subscription_events_project_active_room_subscribers ... ok
test airc::realtime_store::tests::unsubscribe_removes_active_subscription_but_remains_replayable ... ok
test airc::realtime_store::tests::publish_rejects_nil_room_id ... ok

# ts-rs binding exports (5)
test airc::realtime_store::export_bindings_* ... ok

test result: ok. 17 passed; 0 failed

Substrate doctrine reinforced (3rd consumer of the pattern)

This is the THIRD module this session to get multi-persona concurrency tests (after chat module in #1489 + data/query cursors in #1490). Each follows the same template:

Every ServiceModule or substrate primitive that holds per-resource mutable state under concurrent access must:

  1. Be PROVEN under multi-threaded tokio load (worker_threads=4)
  2. Have its invariants pinned by tests that would fail single-threaded
  3. Use per-resource locks (DashMap<Id, Arc<Mutex<State>>>) when scalability matters; module-wide locks are acceptable when correctness is the priority and contention is low

The airc store today uses the module-wide pattern (correctness-prioritized for moment-of-truth). Chat's StubAircModule test infra (#1489) indirectly exercises this same store via the airc/realtime-publish command path — so when the moment-of-truth test wires up chat + airc + personas, both layers' concurrency contracts are proven.

What this PR explicitly does NOT do

  • Does NOT refactor the store to per-room sharding. Correctness > throughput at this scale. Future PR when persona count grows past ~10.
  • Does NOT touch presence/peer-manifest coalescing or subscription state. Those are also under the module-wide lock and concurrency-safe; the existing single-threaded tests cover them.
  • Does NOT add concurrency tests for daemon-attached / file-store / queue-client transports. This PR pins the in-memory transport which is what the headless moment-of-truth test uses. Other transports get their own audit when they become hot.

Stacks on

canary directly — independent of the chain (airc realtime store has no dep on envelope/handle/chat work).

References

…nditions pinned

Per Joel 2026-05-30: "Each persona exists in its own threads."
Plus: "Approaching moment of truth" (the headless-Rust integration
test where Rust core runs chat + personas + inference without Node).

Multi-persona chat lands on `InMemoryAircRealtimeStore` via
`airc/realtime-publish`. Several personas publishing concurrently
to the same room (and reading replay concurrently) is THE
production scenario for the headless test. The four new tests pin
the substrate's correctness invariants that the integration test
will rely on.

# Audit finding

The store uses ONE module-wide `parking_lot::Mutex<AircRealtimeState>`.
Every publish + every replay takes the same lock. That:

- **Delivers correctness**: all state mutations are atomic; per-room
  Lamport monotonicity holds; replay sees consistent snapshots.

- **Constrains throughput**: multi-room publishes serialize even
  though room state is independent. For 5–10 personas this is fine
  (mutex contention is sub-microsecond on uncontended in-memory
  ops). For 50+ personas it becomes a real bottleneck.

Future refinement (flagged in the test docstring, NOT in this PR):
shard the state by room_id (`DashMap<Uuid, Mutex<RoomState>>`).
That unblocks multi-room throughput while keeping the same
correctness contract. Not needed for moment-of-truth; the
module-wide lock is the simplest substrate that meets requirements.

# What's pinned (4 new tests, multi_thread tokio with 4 workers)

## `concurrent_publishes_to_same_room_lose_no_events_and_keep_lamports_contiguous`

64 concurrent personas publish durable events to GENERAL. Asserts:
- every publish reports ok + stored_for_replay
- final replay returns EXACTLY 64 events (no losses)
- every published event_id appears EXACTLY once (no duplicates)
- every publish-time timestamp (1..=64) appears in the replay
  (Lamport sequencing is contiguous — no gaps, no
  out-of-order under race)

## `concurrent_publishes_to_different_rooms_keep_independent_lamport_sequences`

20 publishes each to 3 rooms (GENERAL, CAMBRIANTECH, OTHER), all
interleaved. Asserts each room's Lamport sequence is INDEPENDENT —
room A's events don't bump room B's Lamport. The final cursor for
each room is exactly PER_ROOM (20). Cross-room interleaving doesn't
break per-room contiguity.

## `replay_during_concurrent_publish_observes_consistent_snapshot`

32 concurrent publishers + 8 concurrent replayers, all racing.
Asserts:
- each replayer observes a CONSISTENT subset (no torn reads — no
  duplicate events within one replay, no out-of-range timestamps)
- after all publishes settle, a final replay returns exactly 32
  events (no losses)
- the final cursor.lamport == 32 (contiguous)

## `cursor_polling_during_concurrent_publish_never_loses_or_duplicates_events`

40 publishers spawn in the background; one consumer polls with
`after_cursor` repeatedly, accumulating observed event_ids. After
all publishes settle, one final drain catches anything the poll
loop missed. Asserts:
- NO duplicate event_ids in the observed set (cursor monotonicity
  preserved — never re-see an event that's already been seen)
- every published event_id eventually observed (no losses)

This is the canonical "consumer reads forward through a moving
stream" pattern — chat clients, persona inbox subscribers, replay
catchup on reconnect all use it. Cursor polling is the
substrate's hot path for sustained multi-persona activity.

# Tests (17/17 pass — 12 pre-existing + 4 new concurrency + 5 ts-rs)

No regression. Pre-existing tests still pass through the same
shared in-memory store. The new tests use real multi-threaded
tokio runtime to actually preempt across OS threads — single-
threaded tokio would silently serialize and pass even if the store
had a race.

# Substrate doctrine reinforced (the third consumer of the pattern)

This is the THIRD module to get multi-persona concurrency tests
this session (after chat in PR #1489 and data/query cursors in
PR #1490). Each consumer follows the same template:

> Every ServiceModule or substrate primitive that holds per-
> resource mutable state under concurrent access must:
> 1. Be PROVEN under multi-threaded tokio load (worker_threads=4)
> 2. Have its invariants pinned by tests that would fail single-
>    threaded
> 3. Use per-resource locks (`DashMap<Id, Arc<Mutex<State>>>`)
>    when scalability matters; module-wide locks are acceptable
>    when correctness is the priority and contention is low

The airc store today uses the module-wide pattern (correctness-
prioritized for moment-of-truth). The chat module's StubAircModule
test infra in PR #1489 indirectly exercises this same store via
the airc/realtime-publish command — so when the moment-of-truth
test wires up chat + airc + personas, both layers' concurrency
contracts are proven.

# References

- Memory: [[headless-rust-must-work-soon]]
- PR #1489 (chat concurrency tests)
- PR #1490 (data/query per-cursor mutex + concurrency tests)
- PR #1487 (generator per-name lock + concurrency tests)

Co-Authored-By: Claude Opus 4.7 <[email protected]>
@joelteply
joelteply merged commit 11132b2 into canary May 31, 2026
3 checks passed
@joelteply
joelteply deleted the test/airc-realtime-concurrency branch May 31, 2026 00:21
joelteply added a commit that referenced this pull request May 31, 2026
…trate work as authoring guide (#1493)

Per Joel 2026-05-30:
> "Let's make sure we have detailed designs for this command
>  infrastructure into modules and properly built from the ground
>  up by using our own generators."

Existing docs cover the **doctrine** (MODULE-ARCHITECTURE.md), the
**runtime contract** (CBAR-SUBSTRATE-ARCHITECTURE.md), and the
**concerns catalog** (MODULE-CATALOG.md). What was missing: the
**field manual** for a module author sitting down to write code
today.

This document codifies the substrate work from PRs #1483–#1492 into
reusable shape:

# What this manual covers

- **§1 The system in one sentence** — Commands + Events + Persona,
  in Rust, with airc handling grid. The doctrinal reduction Joel
  named on 2026-05-30.

- **§2 Substrate primitives quick reference** — ServiceModule trait,
  CommandRequest/Response envelopes, HandleRef + four cell shapes,
  HandleRef::expect_owned_by, CommandRequest::handle_id_or_legacy,
  interceptor chain, cross-module call pattern. Each with a code
  snippet pulled from the actual landed PRs.

- **§3 Module Design Template** — the canonical mod.rs + types.rs
  shape every ServiceModule follows. What the GeneratorModule
  scaffolds; what humans fill in. Rules for ts-rs annotations,
  serde camelCase, optional field handling, executor injection
  for tests.

- **§4 Concurrency doctrine** — per-resource locks (not module-wide),
  std::sync vs tokio::sync, the multi-thread test discipline
  (worker_threads=4), partial-failure semantics for dual-write
  composition. Pins the two real bugs caught this session
  (PR #1490 cursor race; PR #1487 generator same-name race) as
  doctrine, not anecdote.

- **§5 Migration playbook** — Joel's "rethink, don't port" rule
  with a pre-migration checklist + substrate checklist + a worked
  example for chat/analyze (the next chat migration).

- **§6 Generator usage** — how to scaffold a module via
  `./jtag generate/module`; v2 roadmap for the richer scaffold
  matching the Module Design Template.

- **§7 Acceptance criteria** — the 7-point bar for
  "concurrency-clean, wire-clean, ready for the headless integration
  test."

- **§8/§9 See also + PR references** — cross-refs to every
  substrate PR by surface, plus the existing architecture docs.

# Why a field manual now

The doctrinal docs answer the **why**. The catalog answers the
**which**. Neither answers the **how**: where do I find the
envelope API? what's the per-resource lock pattern? what shape
does the generator expect? what counts as a concurrency stress
test? The substrate is now coherent enough to be reduced to a
single reference an author can read once and start writing
clean modules from.

# What this does NOT do

- **Does NOT re-derive doctrine** — defers to MODULE-ARCHITECTURE.md
  for the architectural why.
- **Does NOT re-survey the module space** — defers to
  MODULE-CATALOG.md for what modules exist.
- **Does NOT change any code** — pure documentation, no Rust touched.
- **Does NOT propose v2 of the generator** in this PR — flagged in
  §6.1 as a separate follow-up. This PR establishes the template
  the v2 generator will emit.

# Follow-up PRs

- **Generator v2**: emit modules matching the Module Design Template
  (types.rs scaffold, tests skeleton with concurrency primer,
  DESIGN.md scaffold, per-resource lock scaffold when --stateful).
- **Per-module DESIGN.md pages** living next to mod.rs for each
  migrated module (chat, data, airc, generator). Each documents
  the module's role, command surface, state model, concurrency
  contract, kinks found.

# Length + scope

~440 lines. Tight by design — a manual the author reads in one
sitting before authoring, then references when stuck. The longer
the manual, the less anyone reads it.

Co-authored-by: Claude Opus 4.7 <[email protected]>
joelteply added a commit that referenced this pull request May 31, 2026
…/cursors, airc/realtime-store (#1495)

Step 2 of the doc set Joel approved on 2026-05-30 ("Yeah let's do it. In order"):

1. ✅ Field manual codifying substrate (PR #1493)
2. ✅ Generator v2 emitting modules per the template (PR #1494)
3. **This PR**: per-module design pages for everything we've built
4. (Next) MODULE-CATALOG.md update marking which modules are alive in Rust

Each doc follows the canonical 8-section template from the field
manual (Role / Command surface / Cross-module deps / State model /
Events emitted / Concurrency contract / Migration notes / Kinks found).

# What this PR adds

| Doc | Lines | Status of subject |
|---|---|---|
| `CHAT-MODULE.md` | 125 | chat/poll + chat/send shipped Rust (PR #1489); analyze/export still TS |
| `GENERATOR-MODULE.md` | 127 | v1 + v2 (PRs #1487 + #1494) — recursive bootstrap |
| `DATA-CURSORS-MODULE.md` | 164 | data/query-{open,next,close} migrated to HandleRef (PR #1490) |
| `AIRC-REALTIME-STORE-MODULE.md` | 142 | In-memory store + 4 moment-of-truth concurrency tests (PR #1492) |
| **Total** | **558** | |

# Why under `docs/architecture/` (not next to mod.rs)

The field manual §3 prescribes "DESIGN.md next to mod.rs" for the
canonical directory-module pattern. For this PR:

- chat/ and generator/ ARE directory modules, but only exist on
  unmerged PR branches (#1489 / #1487). Putting their DESIGN.md
  there would couple this PR to that chain.
- data and airc/realtime_store are single-file modules — no
  natural "next to mod.rs" location.

Resolution: all four go under `docs/architecture/` following the
existing convention (PERSONA-COGNITION-CONTRACT.md, ORM-PHASE-2-DESIGN.md
style). When the open PR chain merges, future PRs CAN move
chat/DESIGN.md + generator/DESIGN.md into their respective
directories if the team prefers — content stays the same; only the
file path changes. Single-file module docs stay under
`docs/architecture/` indefinitely (no natural directory home).

# What each doc captures

## CHAT-MODULE.md

- The chat/send dual-write semantics + the warning-field degraded-
  success pattern
- All 11 concurrency tests pinning multi-persona invariants
- The TS→Rust rethink table (resolved UUIDs only, no name resolution
  in kernel)
- Three flagged substrate kinks waiting for second consumers before
  distillation (envelope builder, typed cross-module call, dual-write
  macro)

## GENERATOR-MODULE.md

- The recursive bootstrap doctrine + v1→v2 evolution
- The two same-name race bugs the per-name lock caught (silent
  "already exists" silencing; torn-state writes with force=true)
- Why std::sync::Mutex over tokio::sync::Mutex here (sync filesystem
  critical section)

## DATA-CURSORS-MODULE.md

- The read-then-async-then-write race story (the "page 1 served 8
  times" bug)
- The dual-shape (handle OR queryId) resolver + the additive
  migration story
- All seven HandleRef migration tests pinning invariants
- The substrate refinements distilled to PR #1491 (expect_owned_by,
  handle_id_or_legacy)

## AIRC-REALTIME-STORE-MODULE.md

- The module-wide mutex + correctness-vs-throughput rationale
- The four moment-of-truth concurrency tests
- The flagged per-room sharding refinement (when persona count grows)
- The known stale-cursor + replay-bound limitation (out of scope but
  flagged)

# What this PR explicitly does NOT do

- **Does NOT touch any code** — pure documentation.
- **Does NOT move chat/ or generator/ DESIGN.md into their module
  directories** — see "Why under docs/architecture/" above.
- **Does NOT cover the full data module** — only the cursor surface.
  CRUD / vector / migration / batch each get their own design page
  as they migrate.
- **Does NOT cover the broader airc module** — only the in-memory
  realtime store. queue-scan / daemon transport / file transport
  get their own audit when they become hot.
- **Does NOT ship a MODULE-CATALOG.md update** — that's step 4 of
  the doc set, separate PR.

# References

- PR #1493 — Field manual (canonical 8-section template)
- PR #1494 — Generator v2 (emits the same template skeleton)
- PRs #1487, #1489, #1490, #1492 — the modules being documented

Co-authored-by: Claude Opus 4.7 <[email protected]>
joelteply added a commit that referenced this pull request May 31, 2026
…in Rust (step 4 of 4) (#1496)

Final step of the doc set Joel approved on 2026-05-30 ("Yeah let's do it. In order"):

1. ✅ Field manual codifying substrate (PR #1493)
2. ✅ Generator v2 emitting modules per the template (PR #1494)
3. ✅ Per-module design pages for what we've built (PR #1495)
4. **This PR**: MODULE-CATALOG.md update marking which modules are alive in Rust

# What this PR adds

A new `§0. Currently Live In Rust` section near the top of the
catalog with three sub-tables:

## Sub-table 1: Live modules

| Module | What ships | PR | Design doc | Concurrency proven |
|---|---|---|---|---|
| `chat` | chat/poll + chat/send | #1489 | CHAT-MODULE.md | 4 tests |
| `generator` | generate/module + v2 scaffold | #1487 + #1494 | GENERATOR-MODULE.md | 3 tests |
| `data` cursors | data/query-* with HandleRef | #1490 | DATA-CURSORS-MODULE.md | 7 tests |
| `airc/realtime-store` | in-process realtime store | (pre-session) + #1492 tests | AIRC-REALTIME-STORE-MODULE.md | 4 tests |

## Sub-table 2: Substrate primitives

The kernel-level work the four modules ride on — `ServiceModule`
trait, interceptor chain (PR #1483/#1484), HandleRef + cell shapes
(#1485), envelopes (#1486), expect_owned_by + handle_id_or_legacy
(#1491), field manual (#1493), generator v2 (#1494).

## Sub-table 3: Three-primitive map

Per Joel 2026-05-30, mapping the live modules to Commands / Events
/ Persona — showing chat + generator + data are Commands; airc/realtime
is Events; Persona is the next migration target.

# Why minimal restructure

The catalog is 1133 lines of design-proposal entries for every
Continuum concern. Restructuring individual entries to mark which
are live would scatter the live-vs-proposal signal across dozens
of sections. Putting it in one top-of-doc §0 section gives readers
the live-status at a glance without disturbing the rest of the
catalog's design-proposal framing.

# Doctrine the §0 establishes

Modules earn a row in §0 when they clear ALL THREE of the field
manual's acceptance criteria:

1. Rust implementation merged
2. Per-module design doc capturing role / surface / state /
   concurrency / migration / kinks
3. Multi-thread concurrency tests pinning per-resource invariants

This makes the catalog dual-purpose:
- **Design proposal repository** (§I–§IX, unchanged) — what we
  intend to build
- **Implementation status board** (§0, new) — what we've actually
  built + proven

Future migrations grow §0; the proposal sections shrink as their
entries get promoted.

# Updates to the header

- Cross-ref added to COMMAND-INFRASTRUCTURE-FIELD-MANUAL.md
  (joining CBAR / GENOME-FOUNDRY-SENTINEL / PERSONA-COGNITION-CONTRACT)
- Status line updated: "Most entries are design proposals … Some
  are now live in Rust — see §0 below"

# Net diff

+41 lines, -2 lines. Surgical addition that doesn't disturb the
existing catalog content.

# What this PR does NOT do

- **Does NOT migrate any module** — pure documentation
- **Does NOT restructure §I–§IX entries** — each concern stays in
  design-proposal form until it migrates to Rust + earns a §0 row
- **Does NOT add new module concerns to the catalog** — chat,
  generator, data cursors, and airc/realtime-store are already
  represented implicitly in the existing concerns sections; §0 is
  the live-status index, not a new concern listing

# References

- PR #1493 — Field manual (acceptance criteria the §0 table inherits)
- PR #1494 — Generator v2 (eats own dogfood)
- PR #1495 — Per-module design pages linked from §0
- PRs #1487, #1489, #1490, #1492 — the live modules
- Memory: `three-primitives-commands-events-persona`,
  `headless-rust-must-work-soon`

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

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant