Skip to content

feat(context): compaction as a controlled cache-epoch transition - #374

Merged
github-actions[bot] merged 1 commit into
mainfrom
feat/context-compaction
Aug 16, 2026
Merged

github-actions[bot] merged 1 commit into
mainfrom
feat/context-compaction

Conversation

@mohitranka

Copy link
Copy Markdown
Contributor

What

Replaces the old handoff_reset context reset with real context compaction: a transactional transformation from one valid cacheable context state into the next.

During normal operation the model-visible context stays append-only, so the provider's cached prefix keeps growing. When pressure gets high, compaction collapses the conversation into a structured state checkpoint + a recent raw tail, opens one new cache epoch, and append-only behaviour resumes on top of it.

EPOCH 0                        EPOCH 1
stable prefix                  stable prefix
+ conversation      COMPACT    + checkpoint
+ turn         ───────────►    + recent raw tail
+ turn                         + turn …

The governing invariant: compaction is the only normal operation allowed to intentionally replace historical model-visible context, and canonical session history is never touched.

Where it integrates

The audit found a single projection point, so there is no second context-building path:

canonical journal (forge-durable)
        ↓ replay
AgentSession.messages          ← model-visible projection
        ↓ prepare_model_step   ← compaction happens here, and only here
build_model_request
        ↓
provider adapter → LLM

prepare_model_step is what both the TurnCoordinator and the TUI's own turn loop call, so one hook covers both.

Cache behaviour

Before — append-only; each request is a byte-prefix of the next, verified by the existing prompt_wire snapshot diagnostics.

During — the compaction request is [exact current model-visible context] + [one appended user message]. Nothing earlier is rewritten, so the provider serves the entire conversation from cache rather than re-reading a second copy of it. Same provider, same model, same serialization, same caching path — no cheap secondary summarizer. the_compaction_request_is_the_live_context_plus_one_appended_message asserts this byte-for-byte.

After — one begin_cache_epoch("compaction"), then append-only resumes. The checkpoint installs as a system message, so on Anthropic it folds into the hoisted system block alongside the base prompt — i.e. the new stable prefix ends exactly where it should. compaction_opens_a_new_cache_epoch_and_appending_resumes_after_it checks both halves.

Trigger

Sized from the model's real window rather than a hard-coded constant:

usable  = window − max_output_reserve − safety_reserve
trigger = min(window × 0.85, usable)
compact when current_tokens + expected_next_turn ≥ trigger

forge-connect now ingests models.dev limit.context / limit.output (mirroring the existing cost/effort ingestion) and set_context_window is wired through session assembly and every model switch. An id the registry doesn't publish keeps the conservative default rather than inventing a window.

Retention

  • Tail: clamp(window × 0.12, 16K, 64K), capped at a third of the window. Selection walks backward to the target, then snaps to the nearest structurally valid boundary — never opening on an orphaned tool result, never splitting a call from its result, and pulling in a user request one message back rather than opening on the reply to it. Overshooting the target beats emitting invalid context.
  • User constraints get the highest priority. Repository state can be rediscovered; a constraint the user stated exists nowhere else. Every canonical user turn becomes a ProtectedFact, the recent window is supplied to the prompt verbatim, and a checkpoint that drops <user_constraints> when facts exist is rejected.
  • Repeated compaction merges. A previous checkpoint is replaced, never stacked, and the prompt gains an explicit preserve/update/remove/add clause — no summary(summary(...)).

Failure semantics

Transactional. Nothing mutates until every check passes; the journal write happens before the in-memory swap so a write failure can't leave a projection resume couldn't reproduce. Provider error, malformed/truncated checkpoint, dropped constraints, oversized result → context, epoch, and canonical history all unchanged, one telemetry record with a failure category. Automatic compaction additionally never fails the user's turn: the old context is still valid, so the step proceeds on it.

Tests

cargo test --workspace green (the one pre-existing forge-config::tests::defaults_workspace_to_cwd failure on this machine is unrelated and reproduces on a clean checkout). cargo fmt --all and cargo clippy --all-targets clean.

  • forge-context (~25 new): policy arithmetic and the documented window→tail examples; checkpoint parse/render round-trip and every rejection path; tail boundary preservation across a sweep of targets; candidate validation, checkpoint replacement, oversize handling.
  • forge-core (20 new, compaction_tests.rs): automatic trigger fires / doesn't fire prematurely; /compact below threshold; manual and automatic produce identical results; the cache-prefix assertion; epoch + append-only resumption; canonical history intact after compaction; verbatim tail; tool pairs never split; constraint supply and enforcement; repeated compaction merging; five rollback tests (provider, malformed, truncated, dropped constraints, oversized); failed auto-compaction still lets the turn proceed; resume reconstructs the identical context.
  • forge-connect: limits ingestion, route aliasing, TOML round-trip, None for unpublished ids.
  • forge-tui: /compact reports before→after and the surviving objective; failure says "context unchanged".

Superseded tests for handoff_reset were removed rather than left asserting deleted behaviour.

Out of scope

No retrieval, no embeddings, no vector or BM25 search, no cross-session memory, no long-term memory, no alternate compaction algorithms or models, no user-configurable thresholds or tail sizes, no checkpoint editing UI. No placeholder abstractions for any of them.

Known limitations

  • Token counts are the existing ~4-chars/token estimate, not a real tokenizer — the trigger has reserve headroom to absorb the error.
  • Protected-fact verification is structural (<user_constraints> present when facts exist), not semantic; it cannot prove a specific constraint survived.
  • Candidate structural validation is provider-independent (system-first, tool-call pairing). A provider with requirements beyond that would need its own check.
  • A conversation whose entire body is one unbroken tool exchange has no interior boundary to cut at; compaction fails cleanly and keeps the old context.

Forge's model-visible context is append-only during normal operation, so
the provider's cached prefix keeps growing and every turn reuses it. There
was no way out of that when the window filled except `handoff_reset`: a
non-model "progress document" that threw the conversation away and
restarted from two synthetic messages.

This replaces it with real compaction. Under context pressure — or on
`/compact` — Forge asks the *active* model for a structured state
checkpoint, validates it, selects a recent raw tail, builds a candidate
context, and installs it only if every check passes. That is the one
operation allowed to replace historical model-visible context; canonical
session history in the journal is never touched.

Cache behaviour is the point of the request shape. The compaction call is
the exact current context plus one appended user message, so the whole
conversation is served from the provider's cached prefix instead of
being paid for twice. Installing the result opens a new cache epoch once,
and append-only caching resumes on top of it.

- forge-context: new `compaction` module — pressure policy sized from the
  model's real window, checkpoint schema/parse/validate, boundary-aware
  tail selection, candidate validation, protected facts. All pure.
- forge-core: the transactional install. Journals before swapping, so a
  write failure cannot leave a projection resume could not reproduce.
  Any failure leaves context, epoch, and history exactly as they were.
- forge-durable: additive `ContextCompacted` event; replay rebuilds the
  same projection while every earlier event stays intact.
- forge-connect: ingest models.dev `limit.context`/`limit.output` so the
  trigger and tail target come from metadata, not a hard-coded 200K.
- forge-tui: `/compact` reports one line — `Context compacted · 109K → 36K`
  — and says "context unchanged" when it fails, never claiming success.

Removes `handoff_reset` and the ratio-based reset it served.
@github-actions
github-actions Bot enabled auto-merge (squash) August 16, 2026 21:12
@github-actions
github-actions Bot merged commit e153025 into main Aug 16, 2026
7 checks passed
mohitranka added a commit that referenced this pull request Aug 21, 2026
Forge's model-visible context is append-only during normal operation, so
the provider's cached prefix keeps growing and every turn reuses it. There
was no way out of that when the window filled except `handoff_reset`: a
non-model "progress document" that threw the conversation away and
restarted from two synthetic messages.

This replaces it with real compaction. Under context pressure — or on
`/compact` — Forge asks the *active* model for a structured state
checkpoint, validates it, selects a recent raw tail, builds a candidate
context, and installs it only if every check passes. That is the one
operation allowed to replace historical model-visible context; canonical
session history in the journal is never touched.

Cache behaviour is the point of the request shape. The compaction call is
the exact current context plus one appended user message, so the whole
conversation is served from the provider's cached prefix instead of
being paid for twice. Installing the result opens a new cache epoch once,
and append-only caching resumes on top of it.

- forge-context: new `compaction` module — pressure policy sized from the
  model's real window, checkpoint schema/parse/validate, boundary-aware
  tail selection, candidate validation, protected facts. All pure.
- forge-core: the transactional install. Journals before swapping, so a
  write failure cannot leave a projection resume could not reproduce.
  Any failure leaves context, epoch, and history exactly as they were.
- forge-durable: additive `ContextCompacted` event; replay rebuilds the
  same projection while every earlier event stays intact.
- forge-connect: ingest models.dev `limit.context`/`limit.output` so the
  trigger and tail target come from metadata, not a hard-coded 200K.
- forge-tui: `/compact` reports one line — `Context compacted · 109K → 36K`
  — and says "context unchanged" when it fails, never claiming success.

Removes `handoff_reset` and the ratio-based reset it served.
mohitranka added a commit that referenced this pull request Sep 11, 2026
Forge's model-visible context is append-only during normal operation, so
the provider's cached prefix keeps growing and every turn reuses it. There
was no way out of that when the window filled except `handoff_reset`: a
non-model "progress document" that threw the conversation away and
restarted from two synthetic messages.

This replaces it with real compaction. Under context pressure — or on
`/compact` — Forge asks the *active* model for a structured state
checkpoint, validates it, selects a recent raw tail, builds a candidate
context, and installs it only if every check passes. That is the one
operation allowed to replace historical model-visible context; canonical
session history in the journal is never touched.

Cache behaviour is the point of the request shape. The compaction call is
the exact current context plus one appended user message, so the whole
conversation is served from the provider's cached prefix instead of
being paid for twice. Installing the result opens a new cache epoch once,
and append-only caching resumes on top of it.

- forge-context: new `compaction` module — pressure policy sized from the
  model's real window, checkpoint schema/parse/validate, boundary-aware
  tail selection, candidate validation, protected facts. All pure.
- forge-core: the transactional install. Journals before swapping, so a
  write failure cannot leave a projection resume could not reproduce.
  Any failure leaves context, epoch, and history exactly as they were.
- forge-durable: additive `ContextCompacted` event; replay rebuilds the
  same projection while every earlier event stays intact.
- forge-connect: ingest models.dev `limit.context`/`limit.output` so the
  trigger and tail target come from metadata, not a hard-coded 200K.
- forge-tui: `/compact` reports one line — `Context compacted · 109K → 36K`
  — and says "context unchanged" when it fails, never claiming success.

Removes `handoff_reset` and the ratio-based reset it served.
mohitranka added a commit that referenced this pull request Sep 11, 2026
Forge's model-visible context is append-only during normal operation, so
the provider's cached prefix keeps growing and every turn reuses it. There
was no way out of that when the window filled except `handoff_reset`: a
non-model "progress document" that threw the conversation away and
restarted from two synthetic messages.

This replaces it with real compaction. Under context pressure — or on
`/compact` — Forge asks the *active* model for a structured state
checkpoint, validates it, selects a recent raw tail, builds a candidate
context, and installs it only if every check passes. That is the one
operation allowed to replace historical model-visible context; canonical
session history in the journal is never touched.

Cache behaviour is the point of the request shape. The compaction call is
the exact current context plus one appended user message, so the whole
conversation is served from the provider's cached prefix instead of
being paid for twice. Installing the result opens a new cache epoch once,
and append-only caching resumes on top of it.

- forge-context: new `compaction` module — pressure policy sized from the
  model's real window, checkpoint schema/parse/validate, boundary-aware
  tail selection, candidate validation, protected facts. All pure.
- forge-core: the transactional install. Journals before swapping, so a
  write failure cannot leave a projection resume could not reproduce.
  Any failure leaves context, epoch, and history exactly as they were.
- forge-durable: additive `ContextCompacted` event; replay rebuilds the
  same projection while every earlier event stays intact.
- forge-connect: ingest models.dev `limit.context`/`limit.output` so the
  trigger and tail target come from metadata, not a hard-coded 200K.
- forge-tui: `/compact` reports one line — `Context compacted · 109K → 36K`
  — and says "context unchanged" when it fails, never claiming success.

Removes `handoff_reset` and the ratio-based reset it served.
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