Repository navigation
feat(modules/chat): ChatModule — chat/poll + chat/send migrate to Rust (first dual-write composition) - #1489
Merged
Merged
Conversation
joelteply
added a commit
that referenced
this pull request
May 30, 2026
…position handler
Per Joel:
> "Yes please do." (re: chat/send next, the dual-write composition
> stress-test)
chat/send is the chat module's first multi-cross-module-call handler:
chat → data (persist) then chat → airc (publish). The migration forces
the substrate to commit on partial-failure semantics that the
single-call handlers (chat/poll, data/query cursors) never had to face.
# Why this PR pushes the envelope
Two effects across two modules with no kernel-level transaction:
| data | airc | handler returns |
|------|------|----------------------------------------------------------|
| ok | ok | `Ok(result with message_id + event_id)` |
| ok | fail | `Ok(result with message_id, event_id=None, warning=...)` |
| fail | — | `Err(...)` — no airc publish attempted |
The (ok, fail) cell is the substrate-shaped kink the design needed
proof of. An airc-only failure is NOT command-level failure: the
message IS in the local store, consumers see it via chat/poll, a
future retry/sync mechanism heals the broadcast. Surfacing this as
`Err` would tell the caller "your write didn't happen" — which is
wrong; half of the write did. The `warning` field is the right shape:
**degraded success**.
# Design decisions this PR locks in
## Ordering: data first, airc second
Local persistence is the ground truth. The reverse order would risk
publishing a message to peers that this node doesn't know about — a
peer reading back that message would find no local record. With
data-first, the worst case is *we have the message but peers don't* —
a degradation, not a divergence.
A test (`send_calls_data_before_airc`) pins the order via a shared
call-log Mutex. If the ordering ever flips, the bad-divergence case
becomes reachable; the test catches it.
## airc-fail returns Ok+warning, not Err
The `warning` field names the failing surface, surfaces the
underlying error (so callers can diagnose), confirms the message
wasn't lost ("stored locally"), and includes the message id (so
callers can correlate logs). Tested:
- `send_with_airc_failure_returns_warning_and_null_event_id`
## data-fail short-circuits — airc NEVER called
A test tracks airc invocations via `AtomicUsize` and asserts ZERO
calls when data failed. Same invariant for the subtle
data-returns-success=false path:
- `send_with_data_executor_failure_propagates_as_err_and_skips_airc`
- `send_with_data_success_false_propagates_as_err_and_skips_airc`
## Wire contracts pinned by tests, not just docs
Two tests pin the on-the-wire shape chat hands to data + airc. If
either downstream module changes its parse expectations, these tests
catch the drift even though chat doesn't import their typed structs
(coupling lives at the command/wire surface, not at the Rust type
level — the substrate's whole point):
- `send_writes_chat_messages_collection_with_canonical_entity_shape`
→ pins ChatMessageEntity layout (id/roomId/senderId/timestamp/
content/replyToId/metadata.source/status, ISO-8601 UTC timestamps)
- `send_envelope_matches_airc_publish_wire_shape`
→ pins AircRealtimeEnvelope layout (eventId/roomId/sourceId/
createdAtMs/delivery, tagged payload variant with
schema=chat_transcript and inline message data)
# What this PR explicitly does NOT do
- **Does NOT migrate** chat/analyze or chat/export (still fail-loud
stubs naming issue #57).
- **Does NOT register `ChatModule` at runtime startup.** Same reasoning
as #1489 — until ALL chat commands are migrated, registration would
break the remaining stubs at runtime.
- **Does NOT do sender/room name resolution.** Kernel command takes
pre-resolved UUIDs; resolution stays in TS browser/CLI (or a future
channel/resolve + user/resolve pair). Same compositional principle
chat/poll established.
- **Does NOT externalize media.** Text-only for this migration; media
paths (base64 → blob storage via MediaBlobService) are their own
kink-finder.
- **Does NOT do vision pre-warming.** Fire-and-forget visual descriptor
generation is deferred to vision-module migration.
- **Does NOT thread reply-to into threading metadata fully.** The
`replyToId` field flows through to the stored entity + the airc
payload, but the richer thread { threadId, replyCount, lastReplyAt }
shape is deferred until the thread-tracking design is its own scope.
- **Does NOT solve idempotency.** A retried chat/send (network glitch
on the caller side) currently produces two stored messages —
matches today's TS behavior. Future PR can add a `client_dedup_id`
param + TTL'd dedup map; the substrate is ready for it but the
design is its own scope.
# Substrate kinks this PR surfaced
(For potential future refinement — none blocking, all annotated):
1. **No envelope construction helpers for cross-module calls.** Chat
hand-rolls `json!({ "envelope": {...} })` for airc. If many
modules call airc/realtime-publish from Rust, an
`airc::realtime_publish_envelope(builder...) -> Value` helper in
the airc-shared module would distill this. Out of scope here; flag
for if a second consumer appears.
2. **No typed cross-module command call.** Chat calls
`executor.execute_json("data/create", json!({...}))` with raw JSON
and parses the response back via `.get("success")`. A typed
`executor.execute_typed::<DataCreateParams, DataCreateResult>(...)`
would catch wire-shape drift at compile time. Same kink the
handle_id_or_legacy refinement (#1491) solved for a different
surface — flag for potential future refinement after we see if it
reappears with a second consumer.
3. **No transaction primitive across modules.** Today: chat hand-codes
the data-first / airc-best-effort ordering inline. If many modules
need similar dual-write composition, a substrate-level
`dual_write!(primary => ..., best_effort => ...)` macro could
centralize the partial-failure pattern (warning construction,
ordering enforcement, etc.). Flag for if/when a second consumer
appears.
# Tests (28/28 pass)
Pre-existing chat/poll (17, all unchanged behavior):
- StubDataModule extended to dispatch by command — back-compat
`query_only` constructor preserves chat/poll's existing tests
verbatim
- All 17 chat/poll tests still pass through the refactored stub
New chat/send (11):
- `send_happy_path_returns_message_id_and_event_id`
- `send_with_airc_failure_returns_warning_and_null_event_id` ←
partial-failure cell
- `send_with_data_executor_failure_propagates_as_err_and_skips_airc`
← hard-failure + ordering invariant
- `send_with_data_success_false_propagates_as_err_and_skips_airc` ←
the subtle data-success-false path
- `send_calls_data_before_airc` ← ordering invariant via call log
- `send_writes_chat_messages_collection_with_canonical_entity_shape`
← wire contract to data
- `send_envelope_matches_airc_publish_wire_shape` ← wire contract to
airc
- `handle_command_routes_chat_send_through_typed_envelope` ← typed
envelope round-trip end-to-end
- `handle_command_chat_send_accepts_legacy_collaboration_prefix` ←
back-compat
- `unmigrated_commands_fail_loud_and_name_followup` (updated to
exclude chat/send now that it's migrated)
ts-rs bindings (2):
- `export_bindings_chatsendparams`
- `export_bindings_chatsendresult`
# Wire output
```
shared/generated/chat/
├── ChatPollParams.ts
├── ChatPollResult.ts
├── ChatSendParams.ts // { roomId, senderId, text, replyToId? }
├── ChatSendResult.ts // { messageId, eventId?, warning? }
└── index.ts
```
# References
- [docs/architecture/MODULE-ARCHITECTURE.md](docs/architecture/MODULE-ARCHITECTURE.md)
§5 (composition: commands call commands)
- PR #1489 (ChatModule + chat/poll — the first migration)
- PR #1490 (data/query cursors — single-call HandleRef stress test)
- PR #1491 (substrate refinements distilled from #1490)
- Issue #57 (migration tracker)
- Issue #64 (this migration)
Co-Authored-By: Claude Opus 4.7 <[email protected]>
This was referenced May 30, 2026
joelteply
added a commit
that referenced
this pull request
May 31, 2026
…nditions pinned (#1492) 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
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]>
joelteply
force-pushed
the
feat/chat-service-module
branch
from
May 31, 2026 00:25
613aeaa to
a64465a
Compare
joelteply
added a commit
that referenced
this pull request
May 31, 2026
…position handler
Per Joel:
> "Yes please do." (re: chat/send next, the dual-write composition
> stress-test)
chat/send is the chat module's first multi-cross-module-call handler:
chat → data (persist) then chat → airc (publish). The migration forces
the substrate to commit on partial-failure semantics that the
single-call handlers (chat/poll, data/query cursors) never had to face.
# Why this PR pushes the envelope
Two effects across two modules with no kernel-level transaction:
| data | airc | handler returns |
|------|------|----------------------------------------------------------|
| ok | ok | `Ok(result with message_id + event_id)` |
| ok | fail | `Ok(result with message_id, event_id=None, warning=...)` |
| fail | — | `Err(...)` — no airc publish attempted |
The (ok, fail) cell is the substrate-shaped kink the design needed
proof of. An airc-only failure is NOT command-level failure: the
message IS in the local store, consumers see it via chat/poll, a
future retry/sync mechanism heals the broadcast. Surfacing this as
`Err` would tell the caller "your write didn't happen" — which is
wrong; half of the write did. The `warning` field is the right shape:
**degraded success**.
# Design decisions this PR locks in
## Ordering: data first, airc second
Local persistence is the ground truth. The reverse order would risk
publishing a message to peers that this node doesn't know about — a
peer reading back that message would find no local record. With
data-first, the worst case is *we have the message but peers don't* —
a degradation, not a divergence.
A test (`send_calls_data_before_airc`) pins the order via a shared
call-log Mutex. If the ordering ever flips, the bad-divergence case
becomes reachable; the test catches it.
## airc-fail returns Ok+warning, not Err
The `warning` field names the failing surface, surfaces the
underlying error (so callers can diagnose), confirms the message
wasn't lost ("stored locally"), and includes the message id (so
callers can correlate logs). Tested:
- `send_with_airc_failure_returns_warning_and_null_event_id`
## data-fail short-circuits — airc NEVER called
A test tracks airc invocations via `AtomicUsize` and asserts ZERO
calls when data failed. Same invariant for the subtle
data-returns-success=false path:
- `send_with_data_executor_failure_propagates_as_err_and_skips_airc`
- `send_with_data_success_false_propagates_as_err_and_skips_airc`
## Wire contracts pinned by tests, not just docs
Two tests pin the on-the-wire shape chat hands to data + airc. If
either downstream module changes its parse expectations, these tests
catch the drift even though chat doesn't import their typed structs
(coupling lives at the command/wire surface, not at the Rust type
level — the substrate's whole point):
- `send_writes_chat_messages_collection_with_canonical_entity_shape`
→ pins ChatMessageEntity layout (id/roomId/senderId/timestamp/
content/replyToId/metadata.source/status, ISO-8601 UTC timestamps)
- `send_envelope_matches_airc_publish_wire_shape`
→ pins AircRealtimeEnvelope layout (eventId/roomId/sourceId/
createdAtMs/delivery, tagged payload variant with
schema=chat_transcript and inline message data)
# What this PR explicitly does NOT do
- **Does NOT migrate** chat/analyze or chat/export (still fail-loud
stubs naming issue #57).
- **Does NOT register `ChatModule` at runtime startup.** Same reasoning
as #1489 — until ALL chat commands are migrated, registration would
break the remaining stubs at runtime.
- **Does NOT do sender/room name resolution.** Kernel command takes
pre-resolved UUIDs; resolution stays in TS browser/CLI (or a future
channel/resolve + user/resolve pair). Same compositional principle
chat/poll established.
- **Does NOT externalize media.** Text-only for this migration; media
paths (base64 → blob storage via MediaBlobService) are their own
kink-finder.
- **Does NOT do vision pre-warming.** Fire-and-forget visual descriptor
generation is deferred to vision-module migration.
- **Does NOT thread reply-to into threading metadata fully.** The
`replyToId` field flows through to the stored entity + the airc
payload, but the richer thread { threadId, replyCount, lastReplyAt }
shape is deferred until the thread-tracking design is its own scope.
- **Does NOT solve idempotency.** A retried chat/send (network glitch
on the caller side) currently produces two stored messages —
matches today's TS behavior. Future PR can add a `client_dedup_id`
param + TTL'd dedup map; the substrate is ready for it but the
design is its own scope.
# Substrate kinks this PR surfaced
(For potential future refinement — none blocking, all annotated):
1. **No envelope construction helpers for cross-module calls.** Chat
hand-rolls `json!({ "envelope": {...} })` for airc. If many
modules call airc/realtime-publish from Rust, an
`airc::realtime_publish_envelope(builder...) -> Value` helper in
the airc-shared module would distill this. Out of scope here; flag
for if a second consumer appears.
2. **No typed cross-module command call.** Chat calls
`executor.execute_json("data/create", json!({...}))` with raw JSON
and parses the response back via `.get("success")`. A typed
`executor.execute_typed::<DataCreateParams, DataCreateResult>(...)`
would catch wire-shape drift at compile time. Same kink the
handle_id_or_legacy refinement (#1491) solved for a different
surface — flag for potential future refinement after we see if it
reappears with a second consumer.
3. **No transaction primitive across modules.** Today: chat hand-codes
the data-first / airc-best-effort ordering inline. If many modules
need similar dual-write composition, a substrate-level
`dual_write!(primary => ..., best_effort => ...)` macro could
centralize the partial-failure pattern (warning construction,
ordering enforcement, etc.). Flag for if/when a second consumer
appears.
# Tests (28/28 pass)
Pre-existing chat/poll (17, all unchanged behavior):
- StubDataModule extended to dispatch by command — back-compat
`query_only` constructor preserves chat/poll's existing tests
verbatim
- All 17 chat/poll tests still pass through the refactored stub
New chat/send (11):
- `send_happy_path_returns_message_id_and_event_id`
- `send_with_airc_failure_returns_warning_and_null_event_id` ←
partial-failure cell
- `send_with_data_executor_failure_propagates_as_err_and_skips_airc`
← hard-failure + ordering invariant
- `send_with_data_success_false_propagates_as_err_and_skips_airc` ←
the subtle data-success-false path
- `send_calls_data_before_airc` ← ordering invariant via call log
- `send_writes_chat_messages_collection_with_canonical_entity_shape`
← wire contract to data
- `send_envelope_matches_airc_publish_wire_shape` ← wire contract to
airc
- `handle_command_routes_chat_send_through_typed_envelope` ← typed
envelope round-trip end-to-end
- `handle_command_chat_send_accepts_legacy_collaboration_prefix` ←
back-compat
- `unmigrated_commands_fail_loud_and_name_followup` (updated to
exclude chat/send now that it's migrated)
ts-rs bindings (2):
- `export_bindings_chatsendparams`
- `export_bindings_chatsendresult`
# Wire output
```
shared/generated/chat/
├── ChatPollParams.ts
├── ChatPollResult.ts
├── ChatSendParams.ts // { roomId, senderId, text, replyToId? }
├── ChatSendResult.ts // { messageId, eventId?, warning? }
└── index.ts
```
# References
- [docs/architecture/MODULE-ARCHITECTURE.md](docs/architecture/MODULE-ARCHITECTURE.md)
§5 (composition: commands call commands)
- PR #1489 (ChatModule + chat/poll — the first migration)
- PR #1490 (data/query cursors — single-call HandleRef stress test)
- PR #1491 (substrate refinements distilled from #1490)
- Issue #57 (migration tracker)
- Issue #64 (this migration)
Co-Authored-By: Claude Opus 4.7 <[email protected]>
…ll in Rust) Per Joel: > "Chat is gonna be airc man. So that's extracted period. Chat is of > course a bonafide command though. Do not cheapen it. So the > commands need to be or at least some to start, entirely rust." The split: - **Substrate** (delivery, pub/sub, peers, signing) → airc - **Commands** (chat/send, chat/poll, chat/analyze, chat/export) → Continuum kernel-level ServiceModule, this PR This is the FIRST real module migration from a TS command to a Rust `ServiceModule`. The chat module exercises every pattern the substrate floor PRs established: - `ServiceModule` trait - `CommandResult` cell shapes (PR #1485) - `CommandRequest<P>` / `CommandResponse<T>` envelopes (PR #1486) - Cross-module dispatch via the kernel executor (chat calls `data/query` — neither knows the other beyond the command surface) - Scaffold shape that GeneratorModule (PR #1487) produces - ts-rs typed wire boundary # Scope of THIS PR Only `chat/poll` ships in Rust. The other three commands (`chat/send`, `chat/analyze`, `chat/export`) are wired into the dispatch table as fail-loud stubs that name issue #57 as the migration tracker. Their TS implementations stay live on canary — consumers see no regression. Why staged: `chat/poll` is the cleanest outlier (pure read, no airc, no media side-effects) which lets us validate the cross-module call pattern (chat → data via the kernel executor) without dragging substrate + media into the first migration. Subsequent commands fold in real behavior incrementally. # Module structure ``` src/workers/continuum-core/src/modules/chat/ ├── mod.rs // ChatModule, ServiceModule impl, poll handler └── types.rs // ChatPollParams, ChatPollResult (ts-rs exports) ``` `mod.rs` follows the GeneratorModule template exactly — `pub struct ChatModule`, `impl ServiceModule`, `ModuleConfig` declaring both `chat/` and `collaboration/chat/` prefixes (legacy back-compat), the `handle_command` dispatch arms, the typed envelope pattern. `types.rs` carries `#[derive(TS)]` on both param + result types, exporting to `shared/generated/chat/`. Wire shape: camelCase, optional fields elided when absent. `CHAT_MESSAGES_COLLECTION` constant + `DEFAULT_POLL_LIMIT` constant centralized here. # Cross-module call pattern `chat/poll` doesn't open a database connection — it calls `data/query` via the kernel executor. Chat is blind to which adapter implements the storage; the data module routes per its own resolution rules. This is exactly MODULE-ARCHITECTURE.md §5: commands call commands; modules don't know about each other beyond the command surface. The chat module accepts an optional executor override at construction (`with_executor(...)`) — production uses the kernel-global, tests inject their own. That lets every test in this module spin up a fresh registry with a `StubDataModule` and exercise the full cross-module path without trampling the global `OnceLock`. # Tests (17/17 pass) types.rs (5): - `poll_params_defaults_to_all_none` - `poll_params_round_trip_through_json_with_camel_case` - `poll_params_accepts_missing_fields` - `poll_result_omits_after_message_id_when_none` - `poll_result_includes_after_message_id_when_set` mod.rs (10): - `config_advertises_both_command_prefixes` - `unknown_command_returns_loud_error_naming_supported_commands` - `unmigrated_commands_fail_loud_and_name_followup` (all 6 stub surfaces: chat/send, chat/analyze, chat/export, + collaboration/ prefixed versions) - `poll_returns_empty_result_when_data_module_returns_no_messages` - `poll_without_anchor_queries_data_desc_and_returns_chronological` - `poll_with_room_id_passes_filter_to_data_module` - `poll_with_anchor_looks_up_timestamp_then_filters_gt` - `poll_with_anchor_returns_err_when_anchor_missing` - `handle_command_routes_chat_poll_through_typed_envelope` - `handle_command_accepts_legacy_collaboration_prefix` ts-rs exports (2): - `export_bindings_chatpollparams` - `export_bindings_chatpollresult` # Wire output ``` shared/generated/chat/ ├── ChatPollParams.ts // { roomId?, afterMessageId?, limit? } ├── ChatPollResult.ts // { messages, count, afterMessageId? } └── index.ts // barrel ``` The master barrel (`shared/generated/index.ts`) gains `export * from './chat'`. Other barrel drift (runtime, persona) is PR #1488's territory — left untouched here so the two PRs don't fight over the same lines. # What this PR explicitly does NOT do - Does NOT migrate `chat/send`, `chat/analyze`, `chat/export`. Stubs name issue #57. Each is a future PR. - Does NOT register `ChatModule` at runtime startup. Adding `runtime.register(Arc::new(ChatModule::new()))` in `ipc::start_server` would route ALL `chat/*` traffic through this module — including the stubbed commands which would then break. Registration happens in the same PR that fills in the first real `chat/send` so consumers see one atomic change. Today: chat module exists, is tested, but the legacy TS path still owns every chat command at runtime. - Does NOT do room-name resolution. The kernel command takes an already-resolved `roomId`; name → id stays in TS browser/CLI callsites (or a future `channel/resolve` command). Keeps the kernel command compositional with the future channel module. - Does NOT auto-rebuild the master barrel from outside the chat directory — that drift was already on canary and is PR #1488's job. This PR only adds the `chat` entry. # References - [docs/architecture/MODULE-ARCHITECTURE.md](docs/architecture/MODULE-ARCHITECTURE.md) §5 (composition: commands call commands) - PR #1486 (CommandRequest/Response envelopes — used here) - PR #1487 (GeneratorModule — chat follows its template) - Issue #57 (migration tracker — stubs name it) Co-Authored-By: Claude Opus 4.7 <[email protected]>
…position handler
Per Joel:
> "Yes please do." (re: chat/send next, the dual-write composition
> stress-test)
chat/send is the chat module's first multi-cross-module-call handler:
chat → data (persist) then chat → airc (publish). The migration forces
the substrate to commit on partial-failure semantics that the
single-call handlers (chat/poll, data/query cursors) never had to face.
# Why this PR pushes the envelope
Two effects across two modules with no kernel-level transaction:
| data | airc | handler returns |
|------|------|----------------------------------------------------------|
| ok | ok | `Ok(result with message_id + event_id)` |
| ok | fail | `Ok(result with message_id, event_id=None, warning=...)` |
| fail | — | `Err(...)` — no airc publish attempted |
The (ok, fail) cell is the substrate-shaped kink the design needed
proof of. An airc-only failure is NOT command-level failure: the
message IS in the local store, consumers see it via chat/poll, a
future retry/sync mechanism heals the broadcast. Surfacing this as
`Err` would tell the caller "your write didn't happen" — which is
wrong; half of the write did. The `warning` field is the right shape:
**degraded success**.
# Design decisions this PR locks in
## Ordering: data first, airc second
Local persistence is the ground truth. The reverse order would risk
publishing a message to peers that this node doesn't know about — a
peer reading back that message would find no local record. With
data-first, the worst case is *we have the message but peers don't* —
a degradation, not a divergence.
A test (`send_calls_data_before_airc`) pins the order via a shared
call-log Mutex. If the ordering ever flips, the bad-divergence case
becomes reachable; the test catches it.
## airc-fail returns Ok+warning, not Err
The `warning` field names the failing surface, surfaces the
underlying error (so callers can diagnose), confirms the message
wasn't lost ("stored locally"), and includes the message id (so
callers can correlate logs). Tested:
- `send_with_airc_failure_returns_warning_and_null_event_id`
## data-fail short-circuits — airc NEVER called
A test tracks airc invocations via `AtomicUsize` and asserts ZERO
calls when data failed. Same invariant for the subtle
data-returns-success=false path:
- `send_with_data_executor_failure_propagates_as_err_and_skips_airc`
- `send_with_data_success_false_propagates_as_err_and_skips_airc`
## Wire contracts pinned by tests, not just docs
Two tests pin the on-the-wire shape chat hands to data + airc. If
either downstream module changes its parse expectations, these tests
catch the drift even though chat doesn't import their typed structs
(coupling lives at the command/wire surface, not at the Rust type
level — the substrate's whole point):
- `send_writes_chat_messages_collection_with_canonical_entity_shape`
→ pins ChatMessageEntity layout (id/roomId/senderId/timestamp/
content/replyToId/metadata.source/status, ISO-8601 UTC timestamps)
- `send_envelope_matches_airc_publish_wire_shape`
→ pins AircRealtimeEnvelope layout (eventId/roomId/sourceId/
createdAtMs/delivery, tagged payload variant with
schema=chat_transcript and inline message data)
# What this PR explicitly does NOT do
- **Does NOT migrate** chat/analyze or chat/export (still fail-loud
stubs naming issue #57).
- **Does NOT register `ChatModule` at runtime startup.** Same reasoning
as #1489 — until ALL chat commands are migrated, registration would
break the remaining stubs at runtime.
- **Does NOT do sender/room name resolution.** Kernel command takes
pre-resolved UUIDs; resolution stays in TS browser/CLI (or a future
channel/resolve + user/resolve pair). Same compositional principle
chat/poll established.
- **Does NOT externalize media.** Text-only for this migration; media
paths (base64 → blob storage via MediaBlobService) are their own
kink-finder.
- **Does NOT do vision pre-warming.** Fire-and-forget visual descriptor
generation is deferred to vision-module migration.
- **Does NOT thread reply-to into threading metadata fully.** The
`replyToId` field flows through to the stored entity + the airc
payload, but the richer thread { threadId, replyCount, lastReplyAt }
shape is deferred until the thread-tracking design is its own scope.
- **Does NOT solve idempotency.** A retried chat/send (network glitch
on the caller side) currently produces two stored messages —
matches today's TS behavior. Future PR can add a `client_dedup_id`
param + TTL'd dedup map; the substrate is ready for it but the
design is its own scope.
# Substrate kinks this PR surfaced
(For potential future refinement — none blocking, all annotated):
1. **No envelope construction helpers for cross-module calls.** Chat
hand-rolls `json!({ "envelope": {...} })` for airc. If many
modules call airc/realtime-publish from Rust, an
`airc::realtime_publish_envelope(builder...) -> Value` helper in
the airc-shared module would distill this. Out of scope here; flag
for if a second consumer appears.
2. **No typed cross-module command call.** Chat calls
`executor.execute_json("data/create", json!({...}))` with raw JSON
and parses the response back via `.get("success")`. A typed
`executor.execute_typed::<DataCreateParams, DataCreateResult>(...)`
would catch wire-shape drift at compile time. Same kink the
handle_id_or_legacy refinement (#1491) solved for a different
surface — flag for potential future refinement after we see if it
reappears with a second consumer.
3. **No transaction primitive across modules.** Today: chat hand-codes
the data-first / airc-best-effort ordering inline. If many modules
need similar dual-write composition, a substrate-level
`dual_write!(primary => ..., best_effort => ...)` macro could
centralize the partial-failure pattern (warning construction,
ordering enforcement, etc.). Flag for if/when a second consumer
appears.
# Tests (28/28 pass)
Pre-existing chat/poll (17, all unchanged behavior):
- StubDataModule extended to dispatch by command — back-compat
`query_only` constructor preserves chat/poll's existing tests
verbatim
- All 17 chat/poll tests still pass through the refactored stub
New chat/send (11):
- `send_happy_path_returns_message_id_and_event_id`
- `send_with_airc_failure_returns_warning_and_null_event_id` ←
partial-failure cell
- `send_with_data_executor_failure_propagates_as_err_and_skips_airc`
← hard-failure + ordering invariant
- `send_with_data_success_false_propagates_as_err_and_skips_airc` ←
the subtle data-success-false path
- `send_calls_data_before_airc` ← ordering invariant via call log
- `send_writes_chat_messages_collection_with_canonical_entity_shape`
← wire contract to data
- `send_envelope_matches_airc_publish_wire_shape` ← wire contract to
airc
- `handle_command_routes_chat_send_through_typed_envelope` ← typed
envelope round-trip end-to-end
- `handle_command_chat_send_accepts_legacy_collaboration_prefix` ←
back-compat
- `unmigrated_commands_fail_loud_and_name_followup` (updated to
exclude chat/send now that it's migrated)
ts-rs bindings (2):
- `export_bindings_chatsendparams`
- `export_bindings_chatsendresult`
# Wire output
```
shared/generated/chat/
├── ChatPollParams.ts
├── ChatPollResult.ts
├── ChatSendParams.ts // { roomId, senderId, text, replyToId? }
├── ChatSendResult.ts // { messageId, eventId?, warning? }
└── index.ts
```
# References
- [docs/architecture/MODULE-ARCHITECTURE.md](docs/architecture/MODULE-ARCHITECTURE.md)
§5 (composition: commands call commands)
- PR #1489 (ChatModule + chat/poll — the first migration)
- PR #1490 (data/query cursors — single-call HandleRef stress test)
- PR #1491 (substrate refinements distilled from #1490)
- Issue #57 (migration tracker)
- Issue #64 (this migration)
Co-Authored-By: Claude Opus 4.7 <[email protected]>
…ts pinned Per Joel 2026-05-30: "Each persona exists in its own threads." The kernel registers ONE ChatModule instance; every persona's thread invokes its `&self` methods concurrently against the same executor. The substrate is designed to be safe under that load — but until now no test PROVED it. Single-threaded `#[tokio::test]` runs serialize even genuinely racy code and would pass a substrate with a data race. This commit adds 4 concurrency stress tests pinning the invariants the dual-write / single-call composition designs depend on. Every test uses `flavor = "multi_thread", worker_threads = 4` so tasks actually preempt each other on distinct OS threads rather than cooperatively interleaving on one. # What's pinned 1. **`send_under_concurrent_load_stores_all_messages_with_distinct_ids`** 50 concurrent personas all call `chat/send` through the same ChatModule. Asserts: every send completes, every send writes exactly once, every returned `message_id` is distinct (no UUID collision, no shared mutable state holding the id), and the SET of stored ids equals the SET of returned ids (no lost writes, no phantom writes). 2. **`send_preserves_per_call_ordering_under_concurrent_load`** 25 concurrent sends interleave globally — but per-call `data/create` MUST still precede per-call `airc/realtime-publish`. The dual-write design's bad-divergence safety net (peers don't see a message the node hasn't stored) depends on this invariant holding under load. Tagging each observation with its `message_id` lets the test reconstruct per-call timelines from the interleaved global log. 3. **`send_isolates_mixed_outcomes_under_concurrent_load`** 30 concurrent sends with half airc-failing (text flag tells the stub to fail). Each call's `warning` must reference THIS call's `message_id`, not a concurrent sibling's. Cross-contamination between concurrent results would mean shared mutable state in the handler — this catches it. 4. **`poll_isolates_results_under_concurrent_load`** 30 concurrent `chat/poll` calls each polling a DIFFERENT room. The stub echoes the requested `roomId` in the synthetic result; the test asserts every task receives ITS OWN room's result. Catches result-swap bugs that would never appear single-threaded. # Why this discipline matters Concurrency tests aren't exercising rare paths — they're the production scenario. A test suite full of single-threaded `#[tokio::test]`s can sign off on a substrate that silently miscomputes under multi-persona load. Pinning the invariants here means the next refactor (e.g., adding a `dual_write!` macro or typed cross-module command call) is held to the same bar. The pattern goes into every future module that consumes the kernel: when you add a new handler that touches shared state, add a matching concurrency stress test. # Tests (23/23 pass — 19 pre-existing + 4 new concurrency) All previously-passing tests still pass. The new ones use real multi-threaded tokio runtime + `Arc<Mutex>` + atomic tracking to observe interleavings the substrate must handle. Co-Authored-By: Claude Opus 4.7 <[email protected]>
joelteply
force-pushed
the
feat/chat-service-module
branch
from
May 31, 2026 00:28
a64465a to
d2d3d7c
Compare
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
The first real module migration from a TS command to a Rust
ServiceModule. Per Joel:The split this PR establishes:
chat/send,chat/poll,chat/analyze,chat/export) → continuum-core kernel-level ServiceModuleWhat this PR ships
chat/polllives in Rust. The other three commands are wired into the dispatch table as fail-loud stubs that name issue #57; the TS implementations stay live so consumers see no regression.Why staged:
chat/pollis the cleanest outlier (pure read, no airc, no media side-effects) — lets us validate the cross-module call pattern (chat → data via the kernel executor) without dragging substrate + media into the first migration.Module structure
mod.rsfollows the GeneratorModule (PR #1487) template exactly. Bothchat/(canonical) andcollaboration/chat/(legacy back-compat) route to this module — consumers migrate at their own pace.types.rsuses#[derive(TS)]on both params + result, exporting toshared/generated/chat/. Wire shape is camelCase, optional fields elided when absent.CHAT_MESSAGES_COLLECTION+DEFAULT_POLL_LIMITconstants centralized here.Cross-module call pattern (the proof-of-pattern part)
chat/polldoesn't open a database connection — it callsdata/queryvia the kernel executor. Chat is blind to which adapter implements storage; the data module routes per its own rules.This is exactly MODULE-ARCHITECTURE.md §5: commands call commands; modules don't know about each other beyond the command surface.
The chat module accepts an optional executor override at construction (
with_executor(...)) — production uses the kernel-global, tests inject their own. That lets every test spin up a fresh registry with aStubDataModuleand exercise the full cross-module path without trampling the globalOnceLock.Test plan (17/17 pass)
Tests cover: config shape, dispatch routing (both prefixes), all 6 stub surfaces fail loud and name issue #57, empty result path, latest-N path with query-shape assertions, room-filtered path, anchored-after path (both queries observable in the same closure), missing-anchor error path, typed envelope round-trip end-to-end through
handle_command, ts-rs binding exports.What this PR explicitly does NOT do
chat/send,chat/analyze,chat/export. Stubs name issue Build(deps): Bump yaml from 2.7.1 to 2.8.0 #57. Each is a future PR.ChatModuleat runtime startup. Addingruntime.register(Arc::new(ChatModule::new()))inipc::start_serverwould route ALLchat/*traffic through this module — including the stubbed commands which would then break. Registration happens in the same PR that fills in the first realchat/sendso consumers see one atomic change. Today: chat module exists, is tested, but the legacy TS path still owns every chat command at runtime.roomId; name → id stays in TS browser/CLI callsites (or a futurechannel/resolvecommand). Keeps the kernel command compositional with the future channel module.Wire output
The master barrel gains
export * from './chat'.Stacks on
References