Repository navigation
perf: stop copying prompts and journal payloads on principle - #380
Merged
Merged
Conversation
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).
This was referenced Aug 17, 2026
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).
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
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.rsconvention — 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::replayruns 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:payload: payload.clone()when buildingJournalEvent—evis pushed ontostate.eventsunconditionally, so the clone was pure waste. Payload is now moved in; match arms project out of&ev.payload.serde_json::from_value::<T>(payload.clone()), deep-copying the payload again just to hand serde an ownedValue. NowT::deserialize(&payload). ForContextCompacted/ContextResetthat clone copied the entire replacement conversation.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 unmodifiedmain:ContextCompactedw/ 800 msgs (marginal)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_promptno longer builds a stripped deep copy before encoding — aStripped<'a>(&Value)Serializewrapper dropscache_controlduring serialisation.PromptSnapshotno longer carries the strippedValue; only the rareCACHE PREFIX INVALIDATEDbranch wants it, and it now builds it on demand.prompt_object_from_bodytakes the body by value and moves fields out instead of deep-cloning five subtrees from a body the caller immediately drops.turn_ops.rsthat feed onlytracing::debug!are gated ontracing::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
sha256are byte-identical, covered byinline_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
serdefrom the workspace (forDeserialize/Serializeimpls). No new external crates.Measured and rejected
forge_connect::loaded_registry()rebuilds the builtin registry and re-reads~/.config/forge/providers.tomlon 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 editedproviders.tomlwould require a restart). Not in this diff.Unfixed, raised deliberately
In
record_prompt_snapshot,previous_valueisserde_json::from_slice(previous)— butpreviousis the append-only concatenated encoding (tools\nsystem\nmsg0\nmsg1\n…), which is not a single JSON document. That parse always fails and falls back tojson!({}), sofirst_json_pointercompares{}against the current prompt and thefirst_differencefield in theCACHE PREFIX INVALIDATEDlog 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, andcargo test --workspace --all-targets --lockedall green, rebased ontof3a624b. Before/after numbers above were reproduced independently by running the harness against unmodifiedmain.