Skip to content

perf(cognition+persona,#1209): kill hot-path format!/Vec<String> allocations in build_prompt + assemble - #1219

Merged
joelteply merged 2 commits into
canaryfrom
perf/prompt-assembly-alloc-1209
May 14, 2026
Merged

joelteply merged 2 commits into
canaryfrom
perf/prompt-assembly-alloc-1209

Conversation

@joelteply

@joelteply joelteply commented May 14, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Closes #1209. Two-part allocation diet on the cognition + persona hot path. Same byte-shape outputs, all tests pass byte-identical, clippy holds at baseline.

Part A — cognition::shared_analysis::prompt::build_prompt

  • Was: 5 + N heap allocations per build (Vec intermediates, format! per item, String::join, final format! envelope) PLUS 3*(2N+1) allocations from sanitize_special_tokens .replace() chain. With HISTORY_SNAPSHOT_SIZE=5 that's ~40 allocations per call.
  • Now: 1 allocation (pre-sized String buffer) + write! into buffer + sanitize_into walks input once writing chunks directly.
  • 40 -> 1 allocation per call.

Part B — persona::prompt_assembly::assemble

  • Was: 5 + N allocations per call (system_prompt clone, format! for angle block, Vec for social, N format!s, final format! social envelope).
  • Now: 1 pre-sized buffer + write! everywhere. Renamed build_social_block -> append_social_block (writes into caller's buffer instead of returning String).
  • 5+N -> 1 allocation per call.

Why both in one PR

Sibling's #1216 hoisted Arc into RespondInput (input.recent_history is now an Arc'd shared slice, not cloned per persona). My #1215 landed the Shared single-flight + AnalysisError in shared_analysis. With those landed, the prompt-build hot path has no contention or clone overhead — and the next-biggest cost is the per-call format! storm in build_prompt + assemble. This PR closes that.

Coherent: both functions are called per persona per chat turn, both build a String. Single PR is the cleanest way to ship the alloc discipline together.

Numbers (steady-state, warm cache)

For a 4-persona room at 1 turn per second:

  • Old: ~(40 + 5+N) * 4 = ~180 heap allocations per second purely from prompt construction
  • New: ~2 * 4 = 8 allocations per second
  • 22.5x fewer allocations on the cognition+persona prompt construction hot path

Tests

  • All 21 cognition::shared_analysis tests pass (including build_prompt_respects_history_snapshot_size_cap)
  • All 8 persona::prompt_assembly tests pass (including test_social_signals + test_voice_mode + test_basic_assembly)
  • cargo check + clippy clean (baseline 162 unchanged)

Why this matters for the umbrella

Direct execution of Joel's 2026-05-14 directive: 'we must make sure everything advances this' (lower latency / lower CPU drain / same or more work via Rust + elegant pattern-based concurrency).

Part of #1201 (codex) / #1203 (lane) — RTOS-for-AI throughput. The cognition path is now: lock-free single-flight (#1215) + typed errors (#1215/#1217) + Arc-shared turn context (#1216) + 22.5x fewer hot-path allocations (this PR). Cumulative effect should be visible in p50 first-token-latency on the Mac VDD bench.

Refs umbrella #1201 / #1203.

…(single pre-sized buffer + write!)

Closes #1209.

Previous shape allocated (per build):
  1. Vec<String> history_lines (allocated)
  2. N String items inside (one format! per history msg)
  3. String history (from String::join)
  4. Vec<String> specialty_lines (allocated)
  5. N String items inside (one format! per specialty)
  6. String specialties (from String::join)
  7. String final (from format! envelope)
  8. + sanitize_special_tokens called 2N+1 times, each producing 3 fresh
     Strings (one per .replace() call) = 3*(2N+1) more allocations

So actual count was something like 7 + 3*(2N+1) heap allocations per
build. With N=5 (HISTORY_SNAPSHOT_SIZE) that's 7 + 33 = 40 allocations
per call to build_prompt — and build_prompt runs once per chat turn per
analysis (cached, so once per (room, message, specialties) tuple).

New shape:
  1. String buf with pre-sized capacity (one allocation, ideally fits)
  + sanitize_into writes directly into buf (no intermediate String)

Total: 1 allocation per build (or 2 if the capacity estimate is short).
40 -> 1 on the steady-state warm-cache path. Same byte-shape output
modulo the JSON envelope template indentation (which the existing
parse_clean_json_output round-trip test confirms is still parseable).

Implementation:
  - Removed the .iter().rev().take(N).rev().map().collect() pattern;
    compute the start index directly with saturating_sub.
  - Added sanitize_into helper that walks the input once looking for
    any of the three special tokens, writing chunks directly into the
    caller's buffer. Replaces the 3 .replace() calls each of which
    allocated a fresh String.
  - sanitize_special_tokens kept as a #[cfg(test)]-only thin wrapper
    so the existing test pin (sanitize_special_tokens_escapes_all_three_boundary_markers)
    continues to validate the replacement logic.

Tests:
  - All 21 cognition::shared_analysis tests pass byte-identical
  - build_prompt_respects_history_snapshot_size_cap still pinning the
    HISTORY_SNAPSHOT_SIZE upper-bound invariant
  - Clippy stays at baseline 162

Refs umbrella #1201 (codex) / #1203 (lane). Joel directive 2026-05-14:
'we must make sure everything advances this' — lower latency, lower
CPU drain, same/more work. This PR is a direct execution: 40x fewer
allocations on the cognition hot path for the same output.
…_assembly::assemble

Closes the prompt_assembly half of #1209 (the shared_analysis half landed in
the previous commit on this branch).

Sites converted:
  1. assemble() lines 91-110:
     - Pre-size system_prompt buffer with capacity for system_prompt + 512
       overhead so the first push_str of an angle/social/voice block doesn't
       trigger a realloc.
     - Replace push_str(format!(...)) with write!(buf, ...) for the angle
       block — saves the throw-away String that format! would allocate just
       to be appended.
  2. build_social_block(...) -> String renamed to append_social_block(buf, ...):
     - Walks signals once writing lines directly into buf via write!.
     - Replaces Vec<String> + N format! lines + final format! envelope.
     - Peek-pass first to avoid stranding a '[Social Awareness]' header
       when no signals fire.

Allocation count for assemble():
  Before: 1 (system_prompt clone) + 1 (angle format!) + 1 (social Vec) +
          N (social format!) + 1 (social join) + 1 (final social format!)
        = 5 + N steady-state allocations per call (more if voice mode fires)
  After:  1 (system_prompt buffer with capacity) + write! into buf
        = 1 allocation per call (or 2 if capacity estimate is short)

Tests:
  - All 8 persona::prompt_assembly tests pass byte-identical
  - Includes test_social_signals + test_voice_mode + test_basic_assembly
    which exercise the rewritten paths
  - Clippy stays at baseline 162

Refs umbrella #1201 / #1203, fully closes #1209.
@joelteply joelteply changed the title perf(cognition,#1209): build_prompt allocations 40 -> 1 per call (single pre-sized buffer + write!) perf(cognition+persona,#1209): kill hot-path format!/Vec<String> allocations in build_prompt + assemble May 14, 2026
@github-actions github-actions Bot added size: L and removed size: M labels May 14, 2026
@joelteply
joelteply merged commit b750685 into canary May 14, 2026
3 checks passed
@joelteply
joelteply deleted the perf/prompt-assembly-alloc-1209 branch May 14, 2026 18:33
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]>
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