Skip to content

feat(runtime): compact a run's own turns at a tool boundary and continue (F03) - #92

Merged
lg2m merged 2 commits into
fix/compaction-summary-validationfrom
feat/eng-793-f03-midrun-compaction
Sep 21, 2026
Merged

lg2m merged 2 commits into
fix/compaction-summary-validationfrom
feat/eng-793-f03-midrun-compaction

Conversation

@lg2m

@lg2m lg2m commented Sep 21, 2026 •

Copy link
Copy Markdown
Collaborator

feat(runtime): compact a run's own turns at a tool boundary and continue (F03)

Linear: ENG-793 · audit F03 (P1 · S/G), the largest remaining continuity gap (README § Priority). Schema 32 → 33 (two nullable columns on session_compactions); no protocol/wire change.

The gap

A run whose transcript outgrew the window at turn N>1 stubbed its stale read-only results (C2) and, if that still didn't fit, failed: "compaction runs only between prompts". Mutating results (shell, edits) can't be stubbed, so a task with many such turns could not complete in one run regardless of window size. The audit called the fix "a deliberate design change".

Design

Where. Top of the loop, after the C2 prune still overflows (lib.rs ~1450). This is already a safe boundary: every tool result of the previous turn is durable and in context, no approval is pending, steering was applied.

What. The loop hands its prompt + every turn except the last CONTEXT_PRUNE_KEEP_TURNS (4) to a new RunCapabilities slot, runtime::InRunCompactor. Session prompt runs install SessionInRunCompactor; direct qq ask and internal runs have none and behave as before.

Durability — the real choice. Between-run markers cut at a prompt ordinal and cannot fall inside a run. Rather than bend that, an in-run marker is a session_compactions row with scope_run_id + turn_cutoff. Assembly (append_run_turns) renders such a run as prompt → summary → later turns verbatim, dropping the replaced turns' results and steering. A between-run marker supersedes in-run markers behind its cutoff (the summarizer simply reads the already-summarized shape); rollback pops the newest marker of either kind. Replay after restart matches what the live run last saw — the reference oracle is extended and asserts it.

Who runs it. SessionInRunCompactor starts an internal compaction run owned by the prompt run (auto_compaction_for_run_id) without taking the session's active-run slot — the prompt run holds it. It sends the summarizer request with no tools (Runtime::summarize: text only, reasoning tolerated, a tool call or refusal is an error; a reply cut at the output limit is continued up to MAX_OUTPUT_CONTINUATIONS and joined verbatim, as the between-run path does), records usage/cost on its own row, and commits the marker in the same transaction as its settlement, shrinkage-checked like a between-run step. Each step counts against the same MAX_COMPACTION_STEPS (32) on the prompt run.

Loop after success. Splice the summary in where the replaced turns stood, invalidate the measured-token chain (next usage re-seeds it), track compacted_turns so the next cutoff is the durable turn ordinal, continue. A later overflow folds the previous summary with the next turns.

Failure paths. Rejected/malformed/non-shrinking summary → compaction run settles failed, no marker, prompt run fails closed naming the reason; the overflowing request is never sent. Cancel of the prompt run cascades (cascade_in_run_compaction_cancel, keyed on ownership since there's no slot to key on). If the prompt run's task is torn down mid-summary (deadline, runtime failure), a drop guard settles the compaction Cancelled.

Relationship to docs/plans/mid-run-compaction.md (#91)

That plan was merged while this was being built and proposes a different protocol (a compaction_resume_turn state machine, a RunCompacting event, cutoff_turn_ordinal on the between-run marker). Per direction, this PR is the design: ADR-0039 (the number the plan reserved) is written as Accepted describing what was built and recording the plan's protocol as considered-and-rejected — no crash window exists to recover from when the marker commits atomically with the owned run's settlement, so no resume state or protocol bump is needed. The plan file is marked superseded-in-part; MRC-4 (TUI/headless surfaces) and MRC-5 (live evidence) stay open and are why it remains.

Rebased onto F23 (#89) and F11 (#90); append_run_turns now applies both the F23 projection and the scoped marker.

Stacked on #97 (fix/compaction-summary-validation)

#97 fixes what a summary may look like (heading-style sections, verbatim join of truncated turns, 8 192-token summarizer reserve); this PR adds when compaction may happen. They compose:

Retarget to main once #97 merges.

Verification

  • one_run_spanning_several_windows_compacts_its_own_turns_and_completes — 48 shell turns (~26k tokens) in a 16k window: one user-visible run completes, ≥2 in-run compactions each Completed + SessionCompacted, every provider request under the window (system + schemas counted), all 48 calls durable exactly once, final request = prompt + summary + recent turns, replay equals it, oracle agrees.
  • a_rejected_in_run_summary_fails_the_run_closed_without_resending_the_overflow
  • cancelling_during_in_run_compaction_settles_both_runs_once
  • an_in_run_marker_survives_restart_and_folds_into_a_later_between_run_compaction — reopen, follow-up sees the summary; manual /compact folds it; between-run marker supersedes; rollback restores it.
  • in_run_compaction_boundary_keeps_the_recent_turns_with_their_results (unit)
  • an_in_run_summary_cut_at_the_output_limit_is_continued_and_joined_verbatim
  • Migration tests bumped to 33; a v13 fixture without the table is handled.
  • cargo test --workspace 1,637 pass on the stacked branch (load 2.6); fmt; clippy --workspace --all-targets --all-features -D warnings; build. (Under load 18–20 from concurrent agent builds, a rotating handful of deadlines::/delegation:: timing tests flake on any branch including main; two further clean full qq-core runs at that load on this branch.)

Docs

architecture.md run-loop step 3 and the compaction paragraph; ADR-0039 + index; mid-run-compaction.md status; plans/README.md; ledger row in progress/root.md.

Not in scope

Checkpoint context (Jev) and audit state are untouched by design — the summary replaces messages, not run state. Estimator calibration from observed usage (F04 deferral) still open.

@lg2m
lg2m force-pushed the feat/eng-793-f03-midrun-compaction branch from 9136d54 to c7fd0d2 Compare September 21, 2026 03:26
…nue (F03)

A run whose transcript outgrew the model window at a later turn failed with
"compaction runs only between prompts" once stubbing stale read-only results
no longer fit. Mutating results cannot be stubbed, so a long task with many
shell/edit turns could not complete in one run no matter how large the
window.

The loop now compacts itself. At the top of a turn, after the C2 prune still
overflows, it hands its prompt and every turn but the last
CONTEXT_PRUNE_KEEP_TURNS to an InRunCompactor (a RunCapabilities slot;
session prompt runs install SessionInRunCompactor, direct runs none). The
boundary is safe: every tool result is durable and in context, nothing is in
flight, steering was applied. The compactor runs one summarizer turn under
an internal compaction run owned by the prompt run — its own usage, cost,
RunStarted/RunFinished/SessionCompacted — without taking the session's
active-run slot, and commits a marker scoped to the prompt run
(session_compactions.scope_run_id, turn_cutoff; schema 32 -> 33) atomically
with its settlement, shrinkage-checked like a between-run marker. The loop
splices the summary where the replaced turns stood and continues; a later
overflow folds the previous summary with the next turns. Each step counts
against MAX_COMPACTION_STEPS.

Assembly (append_run_turns) renders a run with a scoped marker as prompt,
summary, then its later turns and steering verbatim. A between-run marker
supersedes in-run markers behind its cutoff; rollback pops the newest of
either kind. Replay after restart matches what the live run last saw.

Failure paths: a rejected, malformed, or non-shrinking summary settles the
compaction run failed, writes no marker, and the prompt run fails closed
naming the reason — the overflowing request is never sent. Cancelling the
prompt run cascades to its in-run compaction (cascade_in_run_compaction_cancel
keys on ownership, not the session slot). A drop guard settles the compaction
Cancelled if the prompt run's task is torn down mid-summary.

Tests: a 48-turn shell run in a 16k window completes in one run with >= 2
in-run compactions, every request under the window, all 48 calls durable
once, replay identical to the last live request; rejected summary fails
closed without resending; cancel during summarization settles both runs once;
marker survives restart and folds into a later between-run compaction, then
reappears on rollback; boundary unit test; reference oracle extended.

Closes ENG-793.
The in-run summarizer treated a reply cut at the output limit as a hard
failure. The between-run path (fix/compaction-summary-validation) shows
real summaries routinely run past the old 2 048-token reserve, so
`Runtime::summarize` now continues a truncated reply up to
`MAX_OUTPUT_CONTINUATIONS`, appending each continuation verbatim because
the provider cuts mid-token, and sums the reported usage across turns. A
reply still truncated after the last continuation fails the compaction
run with the limit named.

Regression test: a summary cut mid-heading across two turns is joined
without an inserted separator and validates.
@lg2m
lg2m force-pushed the feat/eng-793-f03-midrun-compaction branch from c7fd0d2 to a263bf7 Compare September 21, 2026 04:44
@lg2m
lg2m changed the base branch from main to fix/compaction-summary-validation September 21, 2026 04:44
@lg2m
lg2m added this pull request to stack #98 September 21, 2026 04:49
@lg2m
lg2m merged commit 322aa94 into main Sep 21, 2026
4 checks passed
@lg2m
lg2m deleted the feat/eng-793-f03-midrun-compaction branch September 21, 2026 04:50
lg2m added a commit that referenced this pull request Sep 22, 2026
…107)

Read-only audit of the operator's live session store (190 runs: 27 % of
prompt runs failed, 73 % of those by harness policy on recoverable
situations) plus mechanism traces of Codex, OpenCode, Pi, and fx. Records
findings R01-R12 with anchors and SQL, opens plan RR1-RR12 with a ledger,
sets it as priority 0, and reserves ADR-0040 (two-phase retry ownership,
supersedes ADR-0005). RR6 is narrowed to reactive overflow and admission
un-wedging because #92 shipped in-run compaction.
lg2m added a commit that referenced this pull request Sep 22, 2026
…sted prompts from the summary alone (RR6) (#126)

Two ways a session could still wedge after in-run compaction shipped
(#92). First, the estimate is provider-neutral and 30-40 % high or low on
real transcripts; when it said a request fit and the provider said it did
not, the run failed with provider_context_exceeded on the first such
rejection and the next prompt inherited the known-overflow basis. Second,
once the between-run fold had spent its steps and the retained transcript
still did not fit, admission refused every later prompt with "automatic
compaction ran N summarizer steps ... start a new session" (9 runs, 3
sessions wedged in the audit).

The provider's verdict now overrides the estimate in both directions. In
the run loop, a ContextExceeded stream error before anything streamed, on a
run with a compactor and a compaction boundary, re-plans the turn once with
in-run compaction forced and re-issues it; a second rejection of the same
turn fails as before. At admission, an Exhausted(Attempted) rejection, or a
known-overflow repeat the fold cannot help, no longer fails the prompt: the
run starts once from the latest between-run summary alone, opened by a
notice, and the planner judges that smaller request on its own. Nothing is
deleted; the next prompt reassembles from the store as usual.

New informational RuntimeEvent::ProviderOverflow (not published) clears the
measured occupancy basis. Store gains latest_compaction_summary. No schema
or protocol change.

Tests: a_provider_window_rejection_compacts_the_run_and_continues (scripted
413 under a 200k window: one in-run compaction, 12 calls once, next prompt
normal); an_exhausted_fold_admits_the_prompt_with_summary_only_history
(step one commits, prompt rejected, step two rejected, retry runs from the
summary with every row retained). Five fixtures that asserted the old
refusal now assert summary-only admission.

Closes ENG-868.
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