Skip to content

perf: stop copying prompts and journal payloads on principle - #380

Merged
github-actions[bot] merged 1 commit into
mainfrom
perf/measured-wins
Aug 17, 2026
Merged

github-actions[bot] merged 1 commit into
mainfrom
perf/measured-wins

Conversation

@mohitranka

Copy link
Copy Markdown
Contributor

Two independent redundancies removed, both measured before and after. ~50 lines of production change plus 550 lines of allocation-count regression harness.

Method note: assertions are on allocation counts, not wall-clock, following the existing render_perf.rs convention — identical unmodified code has timed 3.6ms and 9.0ms across two runs on this hardware, so timings here are noise.

Journal replay — the user-visible win

Journal::replay runs on every session resume and its cost scales with the entire session history, so a redundant copy is re-paid on every restart. Three redundancies:

  1. payload: payload.clone() when building JournalEvent — ev is pushed onto state.events unconditionally, so the clone was pure waste. Payload is now moved in; match arms project out of &ev.payload.
  2. Five arms called serde_json::from_value::<T>(payload.clone()), deep-copying the payload again just to hand serde an owned Value. Now T::deserialize(&payload). For ContextCompacted/ContextReset that clone copied the entire replacement conversation.
  3. The event-type tag was resolved via serde_json::from_str(&format!("\"{et_s}\"")) — an allocation plus a full JSON parse per event to select a unit variant. Now deserialised straight off the column string.

Measured (debug, crates/forge-durable/tests/replay_perf.rs --ignored), verified by running the same harness against unmodified main:

journal before after delta
961 events 36,971 allocs / 5,479 KiB (38.5/event) 20,880 / 3,362 (21.7/event) −43.5% allocs, −38.6% bytes
ContextCompacted w/ 800 msgs (marginal) 28.0 allocs/msg 11.0/msg −60.7%

Three guards added (per-event budget, linearity, compaction marginal cost) plus an #[ignore]d report.

Prompt snapshot — redundant work, explicitly not a perf win

This runs once per model step next to a multi-second network call. It is not a bottleneck and no performance claim is made for it. It is changed because four passes over the whole prompt to produce a debug log and a hash is the wrong shape:

  • snapshot_prompt no longer builds a stripped deep copy before encoding — a Stripped<'a>(&Value) Serialize wrapper drops cache_control during serialisation.
  • PromptSnapshot no longer carries the stripped Value; only the rare CACHE PREFIX INVALIDATED branch wants it, and it now builds it on demand.
  • prompt_object_from_body takes the body by value and moves fields out instead of deep-cloning five subtrees from a body the caller immediately drops.
  • The re-parse and tree diff in turn_ops.rs that feed only tracing::debug! are gated on tracing::enabled!(Level::DEBUG).

Snapshotting an already-built wire goes from ~12.6 allocs/message to constant: 9 → 16 allocations across 1 → 601 messages.

Behavior is unchanged — output bytes and the journaled sha256 are byte-identical, covered by inline_stripping_matches_stripping_into_a_copy, which diffs the new encoder against the old strip-into-a-copy path at every nesting depth.

The only dependency added is serde from the workspace (for Deserialize/Serialize impls). No new external crates.

Measured and rejected

forge_connect::loaded_registry() rebuilds the builtin registry and re-reads ~/.config/forge/providers.toml on every call, 3–4x per model step. Measured at 119 allocations / 6.6 KiB per call — ~475 allocs per turn against ~8,500 for the wire build alone, with the file read normally an ENOENT. Not worth touching, and caching it would change observable behavior (an edited providers.toml would require a restart). Not in this diff.

Unfixed, raised deliberately

In record_prompt_snapshot, previous_value is serde_json::from_slice(previous) — but previous is the append-only concatenated encoding (tools\nsystem\nmsg0\nmsg1\n…), which is not a single JSON document. That parse always fails and falls back to json!({}), so first_json_pointer compares {} against the current prompt and the first_difference field in the CACHE PREFIX INVALIDATED log has never named a real mutation site. This is a diagnostic-correctness bug, not a performance one, and fixing it changes logged output — so it is flagged here rather than bundled in.

Verification

cargo fmt --all -- --check, cargo clippy --workspace --all-targets --locked -- -D warnings, and cargo test --workspace --all-targets --locked all green, rebased onto f3a624b. Before/after numbers above were reproduced independently by running the harness against unmodified main.

Two measured redundancies, both found by counting allocations rather than
guessing from file size. Guards are added in the style of
forge-tui/tests/render_perf.rs: allocation counts, never wall-clock.

Journal replay (crates/forge-durable) — the real win. Replay runs on every
session resume and its cost is proportional to the whole history, so a
redundant copy is paid again on every restart. The loop deep-cloned each
row's payload to build the JournalEvent it always pushes, then several arms
cloned it a second time to hand an owned Value to serde_json::from_value.
The payload is now moved into the event and the arms deserialise out of it
by reference; the event-type tag is deserialised from the column string
instead of being re-quoted and pushed back through the JSON parser.
Debug profile, 961-event journal: 38.5 -> 21.8 allocations per event,
5480 -> 3365 KiB. A ContextCompacted event carrying 800 messages: 28.0 ->
11.0 allocations per message.

Prompt snapshots (crates/forge-model, forge-core) — clarity first. This is
NOT a user-visible perf fix: record_prompt_snapshot runs once per model
step, right next to a multi-second network call. It is fixed because doing
four passes over the prompt to produce a debug log and a hash is the wrong
shape. snapshot_prompt no longer strips cache_control into a full copy
before encoding (it drops the key during serialisation instead) and no
longer carries the stripped Value that only one rare diagnostic branch
wants; prompt_object_from_body moves fields out of the body its caller just
built rather than cloning them; and the re-parse plus tree-diff feeding the
CACHE PREFIX INVALIDATED log is skipped when DEBUG is filtered out.
Snapshotting an already-built wire is now constant in transcript length:
3807 -> 15 allocations at 300 messages. Byte output and the journaled
sha256 are unchanged, covered by a new byte-equality test.

Ruled out, measured, not changed: TUI render steady state (flat in history
already), forge-transcript cache-miss rebuild (~30x under its budget),
git_status polling (already off the render path).
@github-actions
github-actions Bot enabled auto-merge (squash) August 17, 2026 01:48
@github-actions
github-actions Bot merged commit 19efceb into main Aug 17, 2026
7 checks passed
mohitranka added a commit that referenced this pull request Aug 21, 2026
Two measured redundancies, both found by counting allocations rather than
guessing from file size. Guards are added in the style of
forge-tui/tests/render_perf.rs: allocation counts, never wall-clock.

Journal replay (crates/forge-durable) — the real win. Replay runs on every
session resume and its cost is proportional to the whole history, so a
redundant copy is paid again on every restart. The loop deep-cloned each
row's payload to build the JournalEvent it always pushes, then several arms
cloned it a second time to hand an owned Value to serde_json::from_value.
The payload is now moved into the event and the arms deserialise out of it
by reference; the event-type tag is deserialised from the column string
instead of being re-quoted and pushed back through the JSON parser.
Debug profile, 961-event journal: 38.5 -> 21.8 allocations per event,
5480 -> 3365 KiB. A ContextCompacted event carrying 800 messages: 28.0 ->
11.0 allocations per message.

Prompt snapshots (crates/forge-model, forge-core) — clarity first. This is
NOT a user-visible perf fix: record_prompt_snapshot runs once per model
step, right next to a multi-second network call. It is fixed because doing
four passes over the prompt to produce a debug log and a hash is the wrong
shape. snapshot_prompt no longer strips cache_control into a full copy
before encoding (it drops the key during serialisation instead) and no
longer carries the stripped Value that only one rare diagnostic branch
wants; prompt_object_from_body moves fields out of the body its caller just
built rather than cloning them; and the re-parse plus tree-diff feeding the
CACHE PREFIX INVALIDATED log is skipped when DEBUG is filtered out.
Snapshotting an already-built wire is now constant in transcript length:
3807 -> 15 allocations at 300 messages. Byte output and the journaled
sha256 are unchanged, covered by a new byte-equality test.

Ruled out, measured, not changed: TUI render steady state (flat in history
already), forge-transcript cache-miss rebuild (~30x under its budget),
git_status polling (already off the render path).
mohitranka added a commit that referenced this pull request Sep 11, 2026
Two measured redundancies, both found by counting allocations rather than
guessing from file size. Guards are added in the style of
forge-tui/tests/render_perf.rs: allocation counts, never wall-clock.

Journal replay (crates/forge-durable) — the real win. Replay runs on every
session resume and its cost is proportional to the whole history, so a
redundant copy is paid again on every restart. The loop deep-cloned each
row's payload to build the JournalEvent it always pushes, then several arms
cloned it a second time to hand an owned Value to serde_json::from_value.
The payload is now moved into the event and the arms deserialise out of it
by reference; the event-type tag is deserialised from the column string
instead of being re-quoted and pushed back through the JSON parser.
Debug profile, 961-event journal: 38.5 -> 21.8 allocations per event,
5480 -> 3365 KiB. A ContextCompacted event carrying 800 messages: 28.0 ->
11.0 allocations per message.

Prompt snapshots (crates/forge-model, forge-core) — clarity first. This is
NOT a user-visible perf fix: record_prompt_snapshot runs once per model
step, right next to a multi-second network call. It is fixed because doing
four passes over the prompt to produce a debug log and a hash is the wrong
shape. snapshot_prompt no longer strips cache_control into a full copy
before encoding (it drops the key during serialisation instead) and no
longer carries the stripped Value that only one rare diagnostic branch
wants; prompt_object_from_body moves fields out of the body its caller just
built rather than cloning them; and the re-parse plus tree-diff feeding the
CACHE PREFIX INVALIDATED log is skipped when DEBUG is filtered out.
Snapshotting an already-built wire is now constant in transcript length:
3807 -> 15 allocations at 300 messages. Byte output and the journaled
sha256 are unchanged, covered by a new byte-equality test.

Ruled out, measured, not changed: TUI render steady state (flat in history
already), forge-transcript cache-miss rebuild (~30x under its budget),
git_status polling (already off the render path).
mohitranka added a commit that referenced this pull request Sep 11, 2026
Two measured redundancies, both found by counting allocations rather than
guessing from file size. Guards are added in the style of
forge-tui/tests/render_perf.rs: allocation counts, never wall-clock.

Journal replay (crates/forge-durable) — the real win. Replay runs on every
session resume and its cost is proportional to the whole history, so a
redundant copy is paid again on every restart. The loop deep-cloned each
row's payload to build the JournalEvent it always pushes, then several arms
cloned it a second time to hand an owned Value to serde_json::from_value.
The payload is now moved into the event and the arms deserialise out of it
by reference; the event-type tag is deserialised from the column string
instead of being re-quoted and pushed back through the JSON parser.
Debug profile, 961-event journal: 38.5 -> 21.8 allocations per event,
5480 -> 3365 KiB. A ContextCompacted event carrying 800 messages: 28.0 ->
11.0 allocations per message.

Prompt snapshots (crates/forge-model, forge-core) — clarity first. This is
NOT a user-visible perf fix: record_prompt_snapshot runs once per model
step, right next to a multi-second network call. It is fixed because doing
four passes over the prompt to produce a debug log and a hash is the wrong
shape. snapshot_prompt no longer strips cache_control into a full copy
before encoding (it drops the key during serialisation instead) and no
longer carries the stripped Value that only one rare diagnostic branch
wants; prompt_object_from_body moves fields out of the body its caller just
built rather than cloning them; and the re-parse plus tree-diff feeding the
CACHE PREFIX INVALIDATED log is skipped when DEBUG is filtered out.
Snapshotting an already-built wire is now constant in transcript length:
3807 -> 15 allocations at 300 messages. Byte output and the journaled
sha256 are unchanged, covered by a new byte-equality test.

Ruled out, measured, not changed: TUI render steady state (flat in history
already), forge-transcript cache-miss rebuild (~30x under its budget),
git_status polling (already off the render path).
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant