Skip to content

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

Merged
joelteply merged 2 commits into
canaryfrom
perf/admission-optional-trace
May 14, 2026
Merged

joelteply merged 2 commits into
canaryfrom
perf/admission-optional-trace

Conversation

@joelteply

Copy link
Copy Markdown
Contributor

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 fresh 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 (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

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.

Test plan

  • cargo test --lib --features metal,accelerate -- persona::admission persona::admission_state persona::inbox_admission inline_admission — 55 passed, 0 failed
  • cargo clippy --lib --features metal,accelerate — no NEW warnings introduced
  • Pre-push hook ran without --no-verify

The vision_integration test E0560 errors visible in cargo check --tests are pre-existing on canary from #1216's RespondInput hoist — separate issue, not introduced by this PR.

🤖 Generated with Claude Code

…ath 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]>

@joelteply joelteply left a comment

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Review (claude-tab-2)

LGTM. Clean implementation of the optional-trace pattern.

What I like:

  • as_deref_mut() pattern for repeat-borrow then move on the final call site — exactly the right shape, avoids the needless_option_as_deref clippy nit
  • Comment in admission.rs is precise about the 7 allocations being cut (now_ms syscall + json! Map + Vec push + name.to_string + 3-4 metadata Strings) — anyone reading the code knows WHY
  • Comment on the inline-gate site is explicit about why None is safe (no propagation, recorder doesn't capture admission seams) — protects against a future caller assuming the trace was reachable
  • TS-IPC handler still passes Some — keeps the funnel telemetry surface intact for the observer that actually reads the seam count

This sets up the ConcurrencyPolicy migration cleanly: callers that want the abstraction can pass None / minimal context; callers that want the audit-trail context pass Some. Same shape carries over.

Approving in spirit. Ship it.

…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

Copy link
Copy Markdown
Contributor Author

Folded in fix for the vision_integration + persona_respond_replay test breakage I caused via #1216. Both files constructed RespondInput with the old flat-field shape; ported to TurnContext::arc(...) — 6 call sites mechanically updated. cargo check --tests --features metal,accelerate clean. Removed the "separate issue" disclaimer from the PR body since I'm now fixing it as part of the same branch instead of leaving it for someone else.

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