Skip to content

fix(state): preserve compression state across native compaction (compress-only guard) - #693

Open
Jj202307 wants to merge 1 commit into
Tarquinen:masterfrom
Jj202307:fix/compress-only-guard
Open

Jj202307 wants to merge 1 commit into
Tarquinen:masterfrom
Jj202307:fix/compress-only-guard

Conversation

@Jj202307

Copy link
Copy Markdown

fix(state): preserve compression state across native compaction (compress-only guard)

Problem

Two compounding failures around native opencode compaction:

  1. Orphaned compaction summary. When a user message lands while compaction is in flight, opencode's retention rule (filterCompacted) parents the successful summary to the newer user message instead of the compaction marker. The parent mismatches, so all messages are retained — nothing is compacted away.
  2. DCP wipes valid state on any summary. DCP's resetOnCompaction fired on ANY successful compaction summary event and wiped all compression blocks. Combined with (1), the raw, uncompressed history was sent on the next request.

Incident: a 1,352,175-token request against a 1,048,576-token cap → ContextOverflowError → retry re-compacts → wipe again → raw history again → compaction-retry deadlock.

Fix

Design: compress-only by construction. The event-triggered wipe is gone; the summary event is a log-only hint; the sole state-reduction mechanism is a per-block reconciliation at transform entry that fires only when a block's target messages are actually absent from the outbound payload.

  1. lib/state/state.ts:46-62 — the compaction event handler keeps the lastCompaction timestamp update but no longer resets state. It sets lastCompactionAnomaly and logs Native compaction summary detected — state preserved (with timestamp and summaryMessageId). The summary id comes from a new findLastCompactionSummary(messages); findLastCompactionTimestamp delegates to it, so TUI and session-init callers are untouched.
  2. lib/state/utils.ts:336-350 — resetOnCompaction is deleted (deletion prevents reuse). No lib/ reference remains.
  3. lib/state/types.ts:111 — optional lastCompactionAnomaly?: { detectedAt: number; summaryMessageId: string } on SessionState, next to lastCompaction. Not added to PersistedSessionState — no state-format change, no migration.
  4. lib/messages/sync.ts:126-184 — new exported reconcileCompressionBlocks(state, logger, presentMessageIds: ReadonlySet<string>): number. Walks blocksById; drops a block iff any id in its effectiveMessageIds is absent from the outbound message list (all-or-nothing, so ranges straddling a compaction boundary drop; empty/missing effectiveMessageIds keep the block). On drop it fully cleans blocksById, activeBlockIds, activeByAnchorMessageId (only when mapped to the dropped id), and filters the id out of every byMessageId entry's allBlockIds/activeBlockIds. Returns the drop count. compressMessageId absence is not a drop criterion — the existing deactivate behavior in syncCompressionBlocks is untouched, so reconciliation is a new function, not a sync tweak.
  5. lib/hooks.ts:128-139 (V1 transform) — reconcile immediately after checkSession and before syncCompressionBlocks, against the post-shape-filter outbound ids; dirty-save only when dropped > 0 (zero drops = zero new writes, matching the current write cadence). Reconciling before sync means sync rebuilds the active maps from survivors only.
  6. lib/v2/index.ts:205-218 (V2, separate call site) — reconcile only when kind === "context", against view.messages ids, before syncCompressionBlocks. Never on the "compaction" hook: its message list is the compaction input, not the outbound payload — dropping blocks there could destroy state for a summary that never lands, recreating the bug class.

Monotone safety: a kept block whose targets are gone is a no-op; a wiped block whose targets are present is the incident. Real compactions self-heal block-by-block (fully-covered blocks drop, surviving ranges stay valid); orphaned summaries change nothing.

Evidence

Unit tests: main suite 132/132 pass, logger workspace 8/8 pass, typecheck clean.

Isolated runtime proof (real host opencode driving the patched plugin against a scripted OpenAI-compatible mock; unpatched master control over the identical scenario): the anomaly WARN is logged and state is preserved; wire differential at the orphan moment: −3 messages / −12,033 B — the patched build sent the substituted fold block while the control sent the folded range raw.

Incident-scale end-to-end proof (same harness, incident-sized scenario): the fold covered 223 messages. At the orphan moment the patched request was 87 msgs / 255,865 est tokens — under the 260,096 usable-token limit with the block substituted: no second compaction, no ContextOverflowError, exit 0. The unpatched control at the identical moment sent 309 msgs / 455,643 est tokens raw and triggered a second compaction — the deadlock loop. Differential: −222 msgs / −199,778 est tokens.

Incident replay: the real 1089-message incident export replayed through the reconciliation path: blocks 30 → 30, 0 drops.

Relation to existing work

Test plan

  • New tests/block-reconcile.test.ts (8 cases): identity (0 drops); all-missing drop; straddling drop; cleanup of blocksById/activeBlockIds/activeByAnchorMessageId/byMessageId; idempotent repeat returns 0; empty/missing effectiveMessageIds kept; fold-in-flight (block added, then identity reconcile) survives; empty blocksById (fork) no-op.
  • tests/message-ids.test.ts: the reset assertion flipped to preservation — aliases intact, lastCompaction advanced, one anomaly recorded, no re-record on a second event.
  • Replay harness over the real 1089-message incident export: 30→30 blocks, 0 drops.
  • Manual verification gates (runtime + scale proofs above).

No changes to tests/v2-messages.test.ts; PR #682 semantics remain untouched.

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