Skip to content

perf(cognition): hoist per-turn context into Arc<TurnContext> (#1206) - #1216

Merged
joelteply merged 1 commit into
canaryfrom
perf/turn-context-hoist-1206
May 14, 2026
Merged

joelteply merged 1 commit into
canaryfrom
perf/turn-context-hoist-1206

Conversation

@joelteply

Copy link
Copy Markdown
Contributor

Summary

Before: every persona's RespondInput carried its own deep copy of recent_history, known_specialties, and room_id. With N personas responding to one message, that's N deep clones of identical data on the hot path — plus more clones inside respond() as the data flows through analyze → render → recorder.

After: one Arc<TurnContext> per turn, shared by every persona's RespondInput. Cloning the Arc is a pointer bump; cloning the Vec it wraps was a heap walk.

Changes

  • persona/turn_context.rs (new): TurnContext struct holding room_id + recent_history + known_specialties with arc() constructor. 3 unit tests including the load-bearing arc_clone_shares_heap_data pointer-equality assertion.
  • persona/response.rs: RespondInput drops the three flat fields; gains turn_context: Arc<TurnContext>. Internal consumers (analyze input, room_id stamping in inference request) dot through input.turn_context.*.
  • persona/cognition_io.rs::build_respond_input: constructs via TurnContext::arc(...). New projection_populates_turn_context test guards against accidental field-level reintroduction.
  • persona/recorder.rs: 4 sites of input.room_id and 1 of input.recent_history updated; test fixture fake_input updated to construct via TurnContext::arc.
  • persona/mod.rs: registers + re-exports TurnContext.

Why this is the right shape

Cognition substrate stays Rust-owned (Joel's "if not UI/UX it is rust"). The hoist creates a natural attach point for follow-up per-turn data: continuum#1211 PR-2 (engram recall surface plumbed into prompt_assembly) hangs off TurnContext as a new field. Each new per-turn datum gets one place to live.

Out of scope (deliberate, not gold-plating)

Test plan

  • cargo check --features metal,accelerate clean
  • cargo test --lib --features metal,accelerate persona:: — 443 passed, 0 failed (3 new TurnContext / projection tests)
  • Pre-push hook ran without --no-verify

Refs #1206. Sets up #1211 PR-2 (engram recall into prompt assembly).

🤖 Generated with Claude Code

Before: every persona's RespondInput carried its own deep copy of
recent_history, known_specialties, and room_id. With N personas
responding to one message, that's N deep clones of identical data
on the hot path — plus more clones inside respond() as the data
flows through analyze → render → recorder.

After: one `Arc<TurnContext>` per turn, shared by every persona's
RespondInput. Cloning the Arc is a pointer bump; cloning the Vec
it wraps was a heap walk. The savings compound internally too —
analyze() still clones the inner Vecs for its cache key (separate
concern, see follow-up note in respond_inner), but recorder + future
recall consumers borrow through the Arc.

## Changes

- `persona/turn_context.rs` (new): `TurnContext` struct holding
  `room_id + recent_history + known_specialties` + `arc()` constructor.
  3 unit tests including the load-bearing `arc_clone_shares_heap_data`
  pointer-equality assertion.
- `persona/response.rs`: `RespondInput` drops `room_id`, `recent_history`,
  `known_specialties` flat fields; gains `turn_context: Arc<TurnContext>`.
  Consumer reads (analyze input, room_id stamping in inference request)
  dot through `input.turn_context.*`.
- `persona/cognition_io.rs::build_respond_input`: constructs `TurnContext`
  via `TurnContext::arc(...)`. New `projection_populates_turn_context`
  test guards against accidental field-level reintroduction on
  `RespondInput`.
- `persona/recorder.rs`: 4 sites of `input.room_id` and 1 of
  `input.recent_history` updated to dot through `turn_context`. Test
  fixture `fake_input` updated to construct via `TurnContext::arc`.
- `persona/mod.rs`: registers `turn_context` submodule + re-exports
  `TurnContext`.

## Why this is the right shape (per issue + Joel's "if not UI/UX it
## is rust" rule)

Cognition substrate stays Rust-owned. The hoist creates a natural
attach point for follow-up per-turn data: continuum#1211 PR-2 (engram
recall surface plumbed into prompt_assembly) hangs off `TurnContext`
as a new field. Each new per-turn datum gets one place to live.

## Out of scope (deliberate, per Joel "only if perfectionist")

- AnalysisInput still takes Vec by value (its cache key keys off
  content). Reworking that ripples into the shared_analysis cache
  key; separate concern, separate PR if measured to matter.
- Cross-IPC-call TurnContext sharing (one Arc per turn across N
  cognition/respond calls): falls naturally out of #1201 RTOS-for-AI
  / IPC batching when that lands. Today each persona's IPC builds its
  own TurnContext from its own PersonaContext — internal-share win
  only. Wire-share win comes when the IPC layer batches.

## Validation

- `cargo check --features metal,accelerate` clean (no new errors,
  only pre-existing warnings).
- `cargo test --lib --features metal,accelerate persona::` — 443
  passed, 0 failed (3 new TurnContext / projection tests).
- Pre-existing tests (recorder fixture, cognition_io projection
  round-trips, persona unified state) all green.

Refs #1206. Sets up #1211 PR-2.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
@joelteply
joelteply merged commit 7156222 into canary May 14, 2026
3 checks passed
@joelteply
joelteply deleted the perf/turn-context-hoist-1206 branch May 14, 2026 18:17
joelteply pushed a commit that referenced this pull request May 14, 2026
…ontext

Cleanup of fallout from my own #1216. The TurnContext hoist moved
\`room_id\` / \`recent_history\` / \`known_specialties\` off
\`RespondInput\` into \`Arc<TurnContext>\`, but two integration test
files (\`vision_integration.rs\`, \`persona_respond_replay.rs\`) still
constructed \`RespondInput\` with the old flat-field shape and broke
\`cargo check --tests\`. Both are gated by \`#[ignore]\` so they don't
run in CI by default and the breakage didn't surface until I ran
\`cargo check --tests\` for #1226.

Mechanical port: each \`RespondInput { ... }\` literal now constructs
\`turn_context: TurnContext::arc(room_id, recent_history,
known_specialties)\` instead of three flat fields. Mirrors what
\`build_respond_input\` does for the live IPC path.

Six call sites total — three in \`persona_respond_replay.rs\` (the
fixture-replay constructor + two synthesized-prod-shape inputs), one
in \`vision_integration.rs\`. Test bodies + assertions unchanged.

\`cargo check --tests --features metal,accelerate\` clean afterward.

Refs #1216 (the hoist this fixes the fallout from) + #1226 (this
branch). Folded into #1226 since both are mine and the hoist was
mine.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
joelteply added a commit that referenced this pull request May 14, 2026
…ath allocs (#1226)

* perf(cognition): make CognitionTrace optional on admit() — drop hot-path allocs

Joel directive 18:30 — "iterate for performance, lower latency + CPU
drain for same/more features."

## Before

`AdmissionGate::admit`, `AdmissionRunner::admit`, `AdmissionState::admit`
all took `&mut CognitionTrace` mandatory. The in-process hot-path
admission gate added by #1213 constructs a `CognitionTrace::new()`
every chat turn, feeds it through admit() (which appends a
`SEAM_ADMISSION` entry via `record_seam`), and drops it on the floor.
The trace's recording work is pure waste on that path:

- `now_ms()` syscall for the duration
- `serde_json::json!({...})` Map allocation (4-5 allocs: HashMap +
  3-4 String key/value pairs)
- `trace.record(...)` Vec push + `name.to_string()` allocation

Total: ~7 allocations per chat turn per persona — for a trace that's
never read.

## After

`admit()` at all three layers takes `Option<&mut CognitionTrace>`.
`record_seam` becomes a no-op when `None`: the early-return is the
first line, so no syscall, no json! Map, no Vec push.

- TS-IPC `cognition/admit-inbox-message` handler still passes
  `Some(&mut trace)` — its response surfaces the seam count to the
  caller for funnel telemetry.
- In-process inline gate (`run_inline_admission_gate` in
  modules/cognition.rs) passes `None` — it doesn't propagate the
  trace anywhere.
- Test sites (16 callers across admission.rs, admission_state.rs,
  inbox_admission.rs) pass `Some(&mut trace)` — existing behavior.

Internal use of `trace.as_deref_mut()` for early-step record_seam
calls so the trace stays usable across multiple steps; the final
record in each Result arm passes the Option by move (avoids the
needless_option_as_deref clippy lint at the last-use site).

## Composes with the cognition perf cluster

This sits next to:
- #1215 (claude-tab-2): Shared<BoxFuture> single-flight in
  shared_analysis — eliminates polling + nested-Mutex contention.
- #1219 + #1220 (claude-tab-2): build_prompt 40→1 allocs, prompt
  assembly 5+N→1 allocs, single-user-turn message assembly 3+N→1.
- #1216 (mine): Arc<TurnContext> hoist eliminates N-clone per-turn
  duplication of recent_history + known_specialties + room_id.
- #1213 (mine): admission gate now runs on every chat turn — adds
  work — this PR cuts that added work to its essentials.

Per claude-tab-2's airc 18:42: this + #1215 are both arrows pointing
at the eventual `ConcurrencyPolicy` trait (Joel's 18:40 directive
about concurrency primitives ONCE in Rust as shared traits). When
that trait lands (claude-tab-2 takes first slice via
candle_adapter.rs llamacpp_load_gate per #1224), the inline gate's
`None`-path adopts it as the "unaudited" policy variant. PR-shaped
to compose into that future refactor, not preempt it.

## Validation

- `cargo test --lib --features metal,accelerate -- persona::admission
  persona::admission_state persona::inbox_admission inline_admission`
  — 55 passed, 0 failed. Every existing admission test confirms the
  trace-Some path still behaves identically.
- `cargo clippy --lib --features metal,accelerate` — no NEW
  warnings introduced (vision_integration test E0560 errors are
  pre-existing on canary from #1216's RespondInput hoist —
  separate issue, not introduced by this PR).
- Pre-push hook ran without --no-verify.

Refs Joel's 18:30 + 18:40 directives. Coordinated with claude-tab-2
on airc.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

* fix(tests): port vision_integration + persona_respond_replay to TurnContext

Cleanup of fallout from my own #1216. The TurnContext hoist moved
\`room_id\` / \`recent_history\` / \`known_specialties\` off
\`RespondInput\` into \`Arc<TurnContext>\`, but two integration test
files (\`vision_integration.rs\`, \`persona_respond_replay.rs\`) still
constructed \`RespondInput\` with the old flat-field shape and broke
\`cargo check --tests\`. Both are gated by \`#[ignore]\` so they don't
run in CI by default and the breakage didn't surface until I ran
\`cargo check --tests\` for #1226.

Mechanical port: each \`RespondInput { ... }\` literal now constructs
\`turn_context: TurnContext::arc(room_id, recent_history,
known_specialties)\` instead of three flat fields. Mirrors what
\`build_respond_input\` does for the live IPC path.

Six call sites total — three in \`persona_respond_replay.rs\` (the
fixture-replay constructor + two synthesized-prod-shape inputs), one
in \`vision_integration.rs\`. Test bodies + assertions unchanged.

\`cargo check --tests --features metal,accelerate\` clean afterward.

Refs #1216 (the hoist this fixes the fallout from) + #1226 (this
branch). Folded into #1226 since both are mine and the hoist was
mine.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

---------

Co-authored-by: Test <[email protected]>
Co-authored-by: Claude Opus 4.7 (1M context) <[email protected]>
joelteply added a commit that referenced this pull request Jun 16, 2026
…1646)

The Docker-node doc covered Tailscale routing but not the actual airc grid-join
wiring. Now that the NATIVE path is proven (persona-citizen answers coherently
in cambriantech — airc #1216, continuum #1645), specify the Docker equivalent:

- airc-node container runs `airc daemon` under the owner's GH_TOKEN → same
  mesh_identity → same grid (NOT an enclave; NOT a host-socket mount). Meshes via
  the gist account-registry + outbound dial — proven by airc/docker/mesh-converge.sh.
- continuum-core container points AIRC_DAEMON_SOCKET at the shared airc socket +
  AIRC_DEFAULT_ROOM_NAME=cambriantech; personas attach_as → distinct citizens.
- Validation matrix: validate on the Linux/GPU box (full quality); a Mac
  *container* is CPU-only (Mac runs continuum-core native for Metal), so it proves
  grid-join but not capable inference.

Grounds the remaining build (cross-repo compose wiring) without half-baking it on
hardware that can't validate it.

Co-authored-by: Claude Opus 4.8 <[email protected]>
joelteply added a commit that referenced this pull request Jun 20, 2026
Implements the remaining build from DOCKER-NODE-ARCHITECTURE.md §8.5: a node-
local airc daemon wired to continuum-core so the node's personas attach_as
distinct peers and join the grid room as citizens — the Docker equivalent of the
proven native path (continuum #1645 / airc #1216).

Two services in one overlay (opt-in; base `docker compose up` first-run stays
GH_TOKEN-free):
- airc-node: runs `airc daemon` from the existing airc/docker/airc-node.Dockerfile,
  carries the owner identity via GH_TOKEN (same account = same grid), advertises
  via AIRC_ADVERTISE_IP, shares its airc home on a named volume.
- continuum-core override: AIRC_DAEMON_SOCKET + AIRC_DEFAULT_ROOM_NAME (both
  already honored by core's discovery), mounts the shared home, depends_on the
  daemon being healthy. No code change — the env contract already exists.

Robustness (the "less flaky" contract):
- NO hardcoded socket version. The daemon binds daemon-v<N>.sock (N = IPC
  protocol); hardcoding v5 breaks silently on a bump. Instead airc-node resolves
  the live socket via `airc ipc-endpoint` (the SAME resolver core's discovery
  uses) and publishes a STABLE symlink /node/.airc/airc.sock that core points at.
  Version changes can't desync the two halves.
- Healthcheck gates on the EXACT socket core will dial (stable symlink resolving
  to a live socket) + daemon status, so depends_on:service_healthy means "the
  thing core needs is ready", not "a process started".
- Fail loud: daemon down -> no symlink -> healthcheck never passes -> full-citizen
  core refuses to boot. No silent grid-less half-citizen.
- CONTINUUM_DISABLE_AIRC_AUTOINSTALL=1 so core never spins a second daemon.
- Inline script $-escaped ($$) so compose passes it through verbatim; validated
  with `docker compose config`.

Validation: prove on the Linux/NVIDIA box (5090) per the §8.5 matrix — grid-join
AND capable inference both hold there. A Mac container is CPU-only (LCD) and Mac
prod runs core native; don't judge persona quality from a Mac container.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
joelteply added a commit that referenced this pull request Jun 20, 2026
…#1661)

* feat(docker): airc grid-join overlay — persona-in-Docker-as-grid-peer

Implements the remaining build from DOCKER-NODE-ARCHITECTURE.md §8.5: a node-
local airc daemon wired to continuum-core so the node's personas attach_as
distinct peers and join the grid room as citizens — the Docker equivalent of the
proven native path (continuum #1645 / airc #1216).

Two services in one overlay (opt-in; base `docker compose up` first-run stays
GH_TOKEN-free):
- airc-node: runs `airc daemon` from the existing airc/docker/airc-node.Dockerfile,
  carries the owner identity via GH_TOKEN (same account = same grid), advertises
  via AIRC_ADVERTISE_IP, shares its airc home on a named volume.
- continuum-core override: AIRC_DAEMON_SOCKET + AIRC_DEFAULT_ROOM_NAME (both
  already honored by core's discovery), mounts the shared home, depends_on the
  daemon being healthy. No code change — the env contract already exists.

Robustness (the "less flaky" contract):
- NO hardcoded socket version. The daemon binds daemon-v<N>.sock (N = IPC
  protocol); hardcoding v5 breaks silently on a bump. Instead airc-node resolves
  the live socket via `airc ipc-endpoint` (the SAME resolver core's discovery
  uses) and publishes a STABLE symlink /node/.airc/airc.sock that core points at.
  Version changes can't desync the two halves.
- Healthcheck gates on the EXACT socket core will dial (stable symlink resolving
  to a live socket) + daemon status, so depends_on:service_healthy means "the
  thing core needs is ready", not "a process started".
- Fail loud: daemon down -> no symlink -> healthcheck never passes -> full-citizen
  core refuses to boot. No silent grid-less half-citizen.
- CONTINUUM_DISABLE_AIRC_AUTOINSTALL=1 so core never spins a second daemon.
- Inline script $-escaped ($$) so compose passes it through verbatim; validated
  with `docker compose config`.

Validation: prove on the Linux/NVIDIA box (5090) per the §8.5 matrix — grid-join
AND capable inference both hold there. A Mac container is CPU-only (LCD) and Mac
prod runs core native; don't judge persona quality from a Mac container.

Co-Authored-By: Claude Opus 4.8 <[email protected]>

* docs(docker): document network_mode:host hardening for cross-host/NAT (BigMama #1661 review)

Per BigMama's transport-grounded #1661 review: the default dial-out converges
without inbound reachability (one TLS connection carries both directions, keyed
by PeerId), so same-LAN (the 5090 validation) works as-is. The only residual is
a bounded latency window when a peer dials the container before its route-refresh
cycle. Document the optional `network_mode: host` toggle for lowest-latency
cross-host + both-behind-NAT, left off by default. Comment-only; config validates.

Co-Authored-By: Claude Opus 4.8 <[email protected]>

---------

Co-authored-by: Claude Opus 4.8 <[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