Skip to content

perf(persona,#1218): build_messages_single_user_turn allocations 3+N -> 1 (write! into pre-sized buffer) - #1220

Merged
joelteply merged 1 commit into
canaryfrom
perf/transcript-write-not-format-1218a
May 14, 2026
Merged

joelteply merged 1 commit into
canaryfrom
perf/transcript-write-not-format-1218a

Conversation

@joelteply

Copy link
Copy Markdown
Contributor

Summary

Refs #1218 (hot-path format!() audit). Same allocation-discipline pattern as #1209 just merged but in build_messages_single_user_turn.

Sites converted

build_messages_single_user_turn was the third hot-path String builder in the cognition+persona path that did push_str(&format!()) in a loop. Now writes directly into a pre-sized buffer:

  • History loop: format!() + let line + push_str(&line) → writeln!(transcript, ...) (per-line throw-away String eliminated)
  • Current message: push_str(&format!()) → writeln!(...) + raw push_str of content
  • Closing cue: push_str(&format!()) → write!(...)
  • Buffer: String::new() → String::with_capacity(estimated) covering header + per-line overhead + closing cue

Allocations per call

  • Before: 1 (transcript) + N (per-history format!) + 1 (current format!) + 1 (closing format!) = 3+N per call
  • After: 1 (transcript with capacity, ideally fits) per call
  • N=5 history → 8 → 1 allocation per call

Tests

  • All 8 persona::prompt_assembly tests pass byte-identical (test_social_signals + test_voice_mode + test_basic_assembly + test_time_gap_markers + proper_chatml_*)
  • Clippy stays at baseline 162

Pattern consolidation note (per sibling's 18:36 coordination)

This is the third application of String::with_capacity(estimate) + write!(...) to a hot-path builder this session (after #1209 build_prompt + assemble). The pattern is now well-proven and the remaining audit sites in #1218 are pure mechanical application — anyone can pick them up.

Considered extracting into a PromptBuilder helper but the 3 use cases have different estimate strategies (history-bounded, signal-conditional, transcript-style) — premature abstraction risk outweighs the LOC savings. Direct application to the remaining sites is the cleaner move.

Refs umbrella #1201 / #1203, refs #1218.

…messages_single_user_turn

Refs #1218 (hot-path format!() audit). Same allocation-discipline pattern
as #1209 just merged but in build_messages_single_user_turn.

Sites converted (lines 240-267):
  1. History loop:
     - Was: let line = if name { format!("{}: {}\n", name, content) } else { format!(...) };
            transcript.push_str(&line);
     - Now: writeln!(transcript, "{}: {}", name, content);  // writes directly, no temp String
  2. Current message:
     - Was: transcript.push_str(&format!("New message from {name}:\n{}\n", current.content));
     - Now: writeln!(transcript, "New message from {name}:");
            transcript.push_str(&current.content);
            transcript.push('\n');
  3. Closing cue:
     - Was: transcript.push_str(&format!("\nRespond now as {persona_name}. ..."));
     - Now: write!(transcript, "\nRespond now as {persona_name}. ...");

Plus: pre-size the transcript buffer with capacity estimate so the first
push_str of the header doesn't realloc. Capacity covers header + per-line
overhead (sum of name/content lengths) + closing cue.

Allocation count for build_messages_single_user_turn:
  Before: 1 (transcript String::new) + N (per-history format!) + 1 (current
          format!) + 1 (closing format!) = 3+N per call
  After:  1 (transcript with capacity, ideally fits) = 1 per call
  N=5 history: 8 -> 1 allocation per call

Tests:
  - All 8 persona::prompt_assembly tests pass byte-identical
  - test_social_signals + test_voice_mode + test_basic_assembly +
    test_time_gap_markers + proper_chatml_* — full coverage
  - Clippy stays at baseline 162

Refs #1218, umbrella #1201/#1203. Sibling's coordination note 18:36
suggested consolidating patterns when >=50% understood + favor shared
Rust interfaces — this is the third successful application of the
'pre-sized buffer + write!' pattern to a hot-path String builder
(after #1209 build_prompt + assemble); the pattern is now well-proven
and the remaining audit sites in #1218 are pure mechanical application.
@joelteply
joelteply merged commit abefb9b into canary May 14, 2026
2 checks passed
@joelteply
joelteply deleted the perf/transcript-write-not-format-1218a branch May 14, 2026 18:41
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