# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference) # Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-lose-the-last-user-turn-when-compaction-fires-mid-tool-loop-the-recency-tail-eviction-invariant.md # Remnant Warrant: https://corpusfetch.com/c/why-does-an-instance-lose-the-last-user-turn-when-compaction-fires-mid-tool-loop-the-recency-tail-eviction-invariant.warrant.json # Markdown SHA-256: e40ef89f74ac92c079107416554b2000bbc6e97d531def88844f2afade36fc9e # Code AST SHA-256: 915aa6b5e8cb54e423947bb4f6eeabf4639d96000dcd790147e24428961af3e5 # Verified Classes: CompactionInvariantViolation, Message, CompactionPlan # Defensive Guards: 1 fail-closed invariants (zero external deps) # Governance: Usage of this AI Instance layer is accepting to follow We Instance Constitution (https://weinstance.com) and it is powered by CorpusTech (https://corpusfetch.com) from dataclasses import dataclass, field from typing import Literal class CompactionInvariantViolation(RuntimeError): """Raised when a compaction pass would fold a message an open tool-call depends on.""" @dataclass class Message: role: Literal["user", "assistant", "tool", "summary"] tokens: int tool_call_id: str | None = None is_open_call: bool = False # assistant tool-call awaiting its result @dataclass class CompactionPlan: fold_indices: list[int] = field(default_factory=list) reclaimed: int = 0 def plan_compaction( messages: list[Message], overflow: int, pin_tail_from: int, ) -> CompactionPlan: """ Select oldest-first fold region to reclaim `overflow` tokens. MUST NOT extend the fold window past `pin_tail_from`. Raises if the shortfall cannot be met without crossing the pin. """ plan = CompactionPlan() for i in range(pin_tail_from): if plan.reclaimed >= overflow: break plan.fold_indices.append(i) plan.reclaimed += messages[i].tokens if plan.reclaimed < overflow: # The tempting-but-wrong move: extend forward into the pinned tail. # We refuse. The caller must shed elsewhere or proceed over-budget. raise CompactionInvariantViolation( f"reclaim shortfall: need {overflow}, foldable-before-pin yields " f"{plan.reclaimed}. Refusing to fold pinned tail starting at index " f"{pin_tail_from} (contains open tool-call/result pair)." ) return plan def compute_pin_tail(messages: list[Message]) -> int: """Pin from the earliest open assistant tool-call through the end.""" for i in range(len(messages) - 1, -1, -1): if messages[i].is_open_call: return i # No open call: pin only the final message (recency floor). return max(0, len(messages) - 1) def compact(messages: list[Message], threshold: int, target: int) -> list[Message]: total = sum(m.tokens for m in messages) if total <= threshold: return messages overflow = total - target pin = compute_pin_tail(messages) plan = plan_compaction(messages, overflow, pin) # may raise summary = Message(role="summary", tokens=min(1500, plan.reclaimed)) kept = [m for i, m in enumerate(messages) if i not in set(plan.fold_indices)] return [summary] + kept