Skip to content

feat(runtime): compact active turns before context exhaustion #882

Closed

Description

@Astro-Han

Problem

historyCompact only compacts prior RuntimeEvents at a turn boundary. During one long active turn, provider-visible messages can exceed the selected model's context window before another boundary exists.

activeToolResultPrune bounds individual large tool results but does not bound aggregate message growth. semanticCompact covers part of this path, but it is invocation-local and is not enabled consistently across Desktop, TUI, and headless. The runtime therefore has no surface-independent guarantee that a long turn will compact and continue before the provider rejects it for context length.

Direction

Establish one runtime-owned active-turn context invariant:

  • measure the next provider request against the selected model context window and reserve;
  • compact a safe completed prefix before crossing the high-water threshold;
  • preserve the exact recent tail and complete tool call/result pairs;
  • continue the same turn automatically after compaction;
  • prevent the replaced raw span from being re-injected on later steps or recovery;
  • reuse or merge the existing semantic and history compaction seams instead of adding a parallel implementation.

Record the trigger, replacement, token savings, auxiliary model usage, continuation, and fail-open reason in existing context-budget diagnostics.

Done when

  • A deterministic long single-turn test triggers compaction before provider context exhaustion.
  • The same turn and run continue without another user message.
  • Completed tool calls are not executed again.
  • Replaced raw messages are not re-injected after compaction.
  • The next provider request remains within the configured model budget.
  • Desktop, TUI, and headless use the same runtime invariant, with surface policy limited to explicit thresholds or opt-outs.
  • If no safe compact span can be produced, the runtime reports an explicit context-budget outcome instead of relying on a provider context-length error.

Non-goals

  • Benchmark-specific threshold tuning.
  • A second compaction storage or replay protocol.
  • Changing verifier or task-completion authority.

Follow-up to #398, #677, and #729.

Activity

  1. added
    enhancement
    good first issue
    and removed
    good first issue
    on Jul 13, 2026
  2. Astro-Han commented on Jul 14, 2026

    @Astro-Han
    ContributorAuthor

    Implementation plan

    Scoping this issue against the boundary reached in #981 discussion: this issue owns the standard Context compaction capacity invariant, extended to phase=mid_turn. It is fully decoupled from the attention-first experiment line (#981 / #986); neither blocks the other, and nothing here touches the semanticCompact / activeFullCompact experiment surfaces.

    Mechanism. Reuse the existing historyCompact V2 HistoryCompactCheckpoint protocol for mid-turn capacity compaction. The protocol is already turn-agnostic (pure event-prefix cursor + digest math); what actually changes:

    • lift the caller-side filter that excludes the current turn's events from the compaction pool (ai-sdk-backend.ts, event.turnId !== input.turnId);
    • add event-level safe-boundary selection: coverage must end on the last immutable non-partial event, never split a tool call/result pair, and never cover the current-turn user message;
    • durably append the checkpoint before replacing the projection (same order as pre_turn), so replaced raw spans are not re-injected on later steps or recovery;
    • summaries come from the existing summarizeHistoryCompact LLM seam; no deterministic fallback — if the summarizer fails or no safe boundary exists, report an explicit outcome instead.

    Triggering — two lines of defense.

    1. Proactive (reason: context_limit): at prepareStep, compare last step's real provider usage plus a tail-delta estimate against contextWindow − reserve; compact before sending. char/4 estimation remains only as cold-start fallback. (All surveyed peers — Codex, opencode, gemini-cli, pi — anchor on real usage rather than pure character estimates.)
    2. Reactive (reason: overflow): classify provider context-length errors in classifyError (currently bucketed as Other), compact once, resend once — a pi-style single-retry latch. A second failure terminates with the explicit outcome.

    Explicit outcome. When compaction cannot produce a provider-safe request, the turn ends with a first-class context_budget_exhausted outcome (with detail such as no_safe_completed_span / summarizer_failed) instead of a raw provider error.

    Defaults. The invariant becomes runtime-owned: a backend that receives no explicit policy derives it from the selected model's contextWindow − reserve, including mid_turn. All three surfaces get it by default; surface policy is limited to explicit thresholds or opt-outs (MAKA_CONTEXT_HISTORY_COMPACT_MID_TURN=off). Desktop's semanticCompact default flips to off (it is the #981 experiment, not the standard mechanism). Headless benchmark baselines that need the old behavior opt out explicitly.

    Naming. Existing identifiers are untouched. New dimensions: phase: 'pre_turn' | 'mid_turn' on checkpoints/diagnostics (absent = pre_turn), reason: 'context_limit' | 'overflow', outcome context_budget_exhausted. No trigger dimension for now; reason already covers a future user_requested. The declared-but-unwired reactive_prompt_too_long on the experiment types stays untouched.

    Delivery — three PRs.

    1. feat(runtime): mid-turn capacity compaction — event-level boundary selection, mid_turn V2 checkpoints, proactive real-usage trigger, context_budget_exhausted outcome, same-turn continuation, deterministic long-turn tests.
    2. feat(runtime): reactive recovery — context-length error classification + single compact-and-retry latch.
    3. feat: runtime-owned defaults + three-surface alignment + Desktop semanticCompact default off + headless opt-out, with cross-surface E2E covering the done-when list.

    Non-goals unchanged from the issue body; additionally out of scope here: any change to #986, deterministic summary fallback, benchmark threshold tuning, new compaction storage or replay protocols.

  3. Astro-Han commented on Jul 15, 2026

    @Astro-Han
    ContributorAuthor

    Closing as completed by #996, #1017, and #1018.

    The runtime now owns the active-turn context invariant:

    • proactive compaction triggers at contextWindow - reserve;
    • a safe completed prefix is persisted as a mid_turn checkpoint before the projection is replaced;
    • the same turn continues automatically on [compact block, verbatim head anchor, preserved tail];
    • completed tool calls are not executed again;
    • covered raw events are not re-injected during later steps or recovery;
    • the final outgoing request is measured after all shaping, and requests exceeding the model context window terminate with context_budget_exhausted;
    • provider context-length errors receive one compact-and-retry recovery attempt;
    • Desktop and TUI consume the shared runtime policy; headless benchmark policies remain an explicit deterministic opt-out.

    Acceptance is covered at the runtime boundary that owns prepareStep:

    • deterministic long single-turn streaming journeys;
    • immediate and deliberately slow durable-ledger consumers;
    • durable checkpoint-before-continuation assertions;
    • exact raw-span removal and tail preservation;
    • no repeated tool execution;
    • recovery re-projection without raw-span reinjection;
    • proactive and reactive overflow paths;
    • explicit unrescuable outcomes.

    A Desktop Playwright test was intentionally not added because its fake backend bypasses prepareStep and would only simulate the mechanism under test. The runtime streaming integration suite exercises the real AiSdkBackend pipeline.

    Final verification on current main: npm --workspace @maka/runtime test — 1936 tests, 1929 passed, 7 skipped, 0 failed.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    enhancement

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions