Skip to content

Add active-loop full compaction for long benchmark runs #327

Closed

Description

@likun666661

Background

Recent Claude Code compact analysis shows a stronger mechanism than a passive transcript summary. Claude Code treats compact as provider-visible history replacement layered on top of durable transcript/session state.

The important distinction for Maka is active-loop replacement: in Claude Code, each query() loop derives a provider-facing messagesForQuery before the next model call. That derived view can be sliced after a compact boundary, tool-budgeted, snipped, microcompacted, context-collapsed, or fully compacted before the provider request is sent.

For long Terminal-Bench tasks such as qemu-alpine-ssh, Maka currently needs this active-loop behavior, not only replay-time/prior-history pruning.

Claude Code mechanism to copy

The effective Claude Code pipeline is roughly:

  1. Start from durable/in-memory history.
  2. Slice after latest compact boundary.
  3. Strip UI-only tool payloads.
  4. Apply tool-result budgeting.
  5. Apply snip/microcompact/context-collapse projections.
  6. Optionally run proactive/predictive/reactive full compact.
  7. Replace the provider-facing request with compact output before the next model call.
  8. Persist durable boundary/summary/restored context for resume and transcript integrity.

Full compact output is installed as:

compact boundary -> compact summary -> kept messages -> restored attachments -> hook results

The summary/restored context are model-visible replacement content. The compact boundary is mostly durable/session structure plus UI/SDK signal.

Current Maka gap

Maka has active/current-turn tool-result prune, which is the right family of mechanism because AI SDK prepareStep can replace messages before the next model step.

But active tool-result prune is intentionally narrow:

  • It replaces oversized current tool result payloads with archive placeholders.
  • It does not summarize a long active attempt or contiguous runtime-event span.
  • It does not create a durable active-loop compaction boundary covering raw RuntimeEvent IDs.
  • It does not produce a benchmark/process-state summary that replaces the hot same-attempt transcript.

For qemu-alpine-ssh style runs, the token growth is not just one huge tool result. It is a chain of shell observations, VM state, file edits, failed hypotheses, retries, public/self-check output, and process state. That needs an active full-compact mode.

Proposal

Add a provider-visible active-loop full compaction mode for long benchmark/task runs.

At a high level:

  1. Detect a compact trigger before the next provider step in the same active run.
  2. Select a contiguous RuntimeEvent range or semantic phase to compact.
  3. Archive raw command output and other raw evidence outside the hot prompt.
  4. Generate a model-visible compact replacement summary.
  5. Persist a durable compaction event/boundary that covers the raw event IDs.
  6. Make the next provider request use the compact replacement instead of raw covered payloads.
  7. On replay/resume, project through the compaction event by default, with raw archive retrieval available on demand.

This should complement, not replace, current active tool-result prune:

  • activeToolResultPrune: cheap, local, single oversized tool-result defense.
  • activeFullCompact: summarize and replace a larger active-loop span.
  • staleReplayPrune: shrink prior/replayed history.
  • replaySummaryCompact: summarize older completed turns/attempts.

Durable event shape

The compaction event should record enough to debug and replay the provider-visible truth:

  • trigger and threshold reason
  • task/attempt/turn/phase identifiers
  • covered RuntimeEvent IDs
  • archive refs for raw evidence
  • compact summary message ID/ref
  • preserved head/tail anchors, if any raw messages stay visible
  • pre-active-context token estimate
  • post-replacement token estimate
  • next provider actual usage when available
  • request-shape hash for the post-compact provider request
  • whether the next step would immediately retrigger compaction
  • compact-call usage if a summarizer model is used

Benchmark summary schema

For Terminal-Bench and especially QEMU-like tasks, the model-visible compact summary should be structured, not freeform only. It should preserve:

  • current process and port state
  • VM/guest boot state
  • important artifact paths and files changed
  • commands already tried and their outcomes
  • latest public verifier or self-check failure
  • known constraints from task prompt
  • abandoned paths / failed hypotheses
  • current hypothesis
  • exact next action candidates
  • archive refs for raw logs/output that can be reopened by tool

Acceptance criteria

  • A long same-attempt run can compact before the next model step, not only between top-level attempts.
  • The next provider-visible message list contains the compact summary/replacement and does not include raw covered oversized payloads by default.
  • The raw evidence remains available through archive refs and can be retrieved explicitly.
  • Resume/replay uses the compaction event to reconstruct compacted provider-visible history.
  • Runtime trace/export shows covered RuntimeEvent IDs, archive refs, summary ref, and token estimates.
  • Telemetry includes pre estimate, post estimate, compact-call usage, next provider actual usage, and saved-token/economic fields.
  • A regression test proves current active tool-result prune and active full compact can compose in one AI SDK multi-step loop.
  • A benchmark-style fixture, ideally modeled after qemu-alpine-ssh, proves compaction preserves process/task state while removing raw high-volume output from the next provider request.

Notes

This issue is based on a Rive/Codex read of Claude Code compact behavior. The key lesson is not to copy every Claude-specific feature such as cached microcompact or Anthropic cache edits. The product requirement for Maka is provider-neutral active-loop replacement with durable evidence boundaries and clear token economics.

Activity

  1. added
    enhancement
    on Jun 27, 2026
  2. likun666661 commented on Jun 27, 2026

    @likun666661
    MemberAuthor

    Design framing update after comparing current Maka compaction with the #327 target:

    The next design should not treat active full compact as a one-off special case. A cleaner framing is:

    • Fact layer remains append-only: RuntimeEvents/messages stay durable and full-fidelity. Compaction should not delete or mutate covered raw facts.
    • Provider input is projection: Maka has at least two projection stages over the same fact layer:
      • priorReplay projection: builds the next large-turn/retry/resume provider history from persisted RuntimeEvents.
      • activeStep projection: reshapes the in-flight same-turn provider messages before a later model step.
    • Compaction is a shared boundary contract: prior compaction and active compaction should both produce/consume validated boundaries with coverage, preserved anchors, archive refs, source hashes, diagnostics, token estimates, and fail-open behavior.
    • Active boundaries must feed prior replay: if active full compact writes a durable boundary, future prior replay should keep that boundary model-visible and skip covered raw events by default. Raw evidence remains available through explicit archive inspection/hydration.

    Suggested abstraction names for the implementation:

    • CompactionSource: prior history or active same-turn source.
    • CompactionStage: priorReplay or activeStep.
    • CompactionPlan: selected coverage, preserved head/tail anchors, target token budget, and trigger reason.
    • CompactionBoundary: rendered model-visible block plus coverage ids, archive refs, hashes, schema version, and validation status.
    • CompactionProjection: the provider-visible messages/events after applying the boundary.
    • CompactionDecision: unchanged | replaced | failedOpen, with diagnostics and token economics.

    This keeps existing prior-history mechanisms useful while making #327 the missing active projection stage. Stale prune, history compact, synthesis cache, archive retrieval, and active full compact can then converge toward one explainable coverage/boundary/diagnostic contract instead of remaining separate ad hoc prompt-shaping paths.

    Proposed upstream PR sequence for #327 after reviewing the active full compact design:

    1. Data model, ledger boundary, archive refs, and replay projection skeleton

      • Scope: add the durable active full compact block contract; render/validate helpers; source archive refs; same-turn active event index; compact boundary RuntimeEvent persistence; replay/resume projection that can replace covered raw events with validated active compact boundary events. Frame this as the first implementation of the shared compaction boundary contract, not just an active-only helper.
      • Key files: packages/core/src/runtime-event.ts, packages/runtime/src/context-budget.ts, packages/runtime/src/model-history.ts, packages/runtime/src/ai-sdk-backend.ts, plus focused runtime helper/tests.
      • Tests: block validation/rendering, invalid-block fail-open behavior, coverage/source-hash checks, boundary RuntimeEvent shape, and replay projection with covered/uncovered events.
      • Acceptance criteria: active compact blocks have stable kind/version/session/turn/coverage/archive fields; boundary events are durable and model-visible; covered raw RuntimeEvents are not mutated; replay ignores invalid blocks with diagnostics.
    2. Provider-visible active full compact in the AI SDK step builder

      • Scope: wire active full compact into prepareStep after tool availability and active tool-result prune; compose with active prune archive placeholders; preserve the current user task, incomplete tool continuity tail, and at least the latest complete tool-call/result pair; add anti-spiral gates and deterministic writer support.
      • Key files: packages/runtime/src/ai-sdk-backend.ts, packages/runtime/src/model-adapter.ts, packages/runtime/src/active-tool-result-prune.ts, and a new active-full-compact runtime module.
      • Tests: multi-step AI SDK tests showing active prune plus active full compact in one run; threshold skip cases; archive-required fail-open; incomplete tool-call/result preservation; repeated failure circuit breaker.
      • Acceptance criteria: the next provider request receives the compacted current-turn projection when thresholds are met; active prune still runs first; raw evidence remains archive-backed; failures leave messages unchanged.
    3. Benchmark/process-state summary builder and QEMU-style fixture

      • Scope: add a structured summary writer for long benchmark runs that captures task, preserved state, process state, artifacts, commands tried, verifier state, failed hypotheses, current hypothesis, next actions, limitations, and raw evidence refs.
      • Key files: active compact writer module, runtime fixture/test files, and benchmark/smoke fixtures under the existing layout.
      • Tests: deterministic long shell/process-output fixtures, verifier retry loops, process/cwd/env/port state preservation, and summary token-limit checks.
      • Acceptance criteria: summaries preserve enough state for the model to continue after compaction; the fixture proves large process output is replaced by a compact block without losing archive-backed evidence.
    4. Replay/resume/export/inspection and telemetry economics

      • Scope: finish inspection/export paths for active compact blocks and archive refs; report before/after estimates, saved estimated tokens, compact-call usage, next-provider actual usage, request-shape hashes, failures, and loaded/written block counts.
      • Key files: runtime diagnostics/context budget plumbing, replay/export/inspection utilities, and existing trace/telemetry modules.
      • Tests: resume/export tests for block loading and raw evidence hydration; telemetry tests proving compact-call usage is not mislabeled as post-compact provider usage; diagnostics snapshots for success and fail-open cases.
      • Acceptance criteria: resume uses validated active compact boundaries by default; export/inspection explains coverage and archive refs; token economics separate compact writer usage from next provider usage.
    5. Optional follow-up: trigger policy and operational tuning

      • Scope: tune defaults for minStepNumber, high-water thresholds, target tokens, minCoveredEstimatedTokens, recent-tail preservation, failure limits, and Harbor/headless env flags after fixture data exists.
      • Key files: context budget policy definitions, runtime configuration, Harbor/headless flag wiring, and operational docs or smoke scripts if present.
      • Tests: policy matrix tests plus smoke runs using the PR 3 fixture.
      • Acceptance criteria: defaults avoid compaction loops and premature small compacts while keeping long benchmark runs inside provider context.

    Out of scope for the first sequence: Anthropic cache edits/cache references, Claude context_management, UI transcript affordances, mutation of old RuntimeEvents, and replacement of the existing replay-only history compact/archive retrieval/synthesis cache paths. Those existing paths should be preserved, then gradually aligned behind the shared compaction boundary/projection contract where it actually reduces duplication.

  3. likun666661 commented on Jun 28, 2026

    @likun666661
    MemberAuthor

    Follow-up source read after the QEMU active-full-compact run hit the max_block_tokens cliff.

    I used a separate Rive workflow to read the latest issue framing, the QEMU notes, the local Claude Code compact source, and the current Maka active-full-compact implementation. The important correction is that Claude Code does not appear to put exhaustive audit/source/coverage metadata into the provider-visible compact summary.

    Source-backed conclusion:

    • Claude Code full compact is a provider-visible replacement boundary, not a growing provider-visible audit envelope.
    • The post-compact provider history is shaped as: compact boundary marker, compact summary user message, optional kept messages, bounded restoration attachments, and hook/session-start results.
    • The compact boundary marker is structural metadata. It is used as the slice point, then filtered before provider API normalization.
    • Each active query iteration derives provider history from the latest compact boundary. On a successful autocompact, the same active loop switches its next model call to the post-compact replacement messages.
    • Raw transcript, parent/logical-parent chain, file history, attribution/content-replacement records, SDK/UI compact events, telemetry, and resume data live in transcript/session side channels. They are not rendered as exhaustive source ids, body hashes, coverage arrays, or one source ref per covered message in the provider-visible summary.

    Implication for Maka:

    The QEMU max_block_tokens failure is likely Maka-specific. Our current active compact block format carries summary text plus growing provider-visible coverage/source/hash/sourceRef metadata, and subsequent active high-water attempts are not yet folding the provider projection onto the latest accepted active boundary/replacement. That combination makes the candidate compact block grow until validation fails open.

    Design update for this issue:

    1. Accepted active full compact should persist a durable active boundary/replacement.
    2. Subsequent prepareStep / active provider projection should start from the latest accepted active boundary and skip covered raw active entries before making high-water and candidate-block decisions.
    3. Full source coverage, body hashes, source refs, archive provenance, and validation diagnostics should move out of the provider-visible compact block into durable audit/diagnostic/archive side-channel records.
    4. The provider-visible replacement validator should measure only what will actually be sent to the model. Audit-envelope validation should be separate.
    5. Keep only bounded continuation context provider-visible: summary, explicit preserved tail if needed, and small stable archive handles if they are required for task continuation.
    6. Add recompaction telemetry and a retry brake for repeated failed-open candidates, so we can detect “accepted compact still above threshold” and “candidate block rebuilt into the same doomed payload.”

    This slightly changes the PR ordering I would take from here: first implement boundary-aware active projection and off-prompt audit storage, then tune visible block budget/trigger policy. The old shared boundary/projection framing still holds; the sharper lesson is that provider projection and audit/provenance must be separated.

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