Skip to content

The agent that grows with you

feat(agent): per-turn micro-compaction to amortize context compression

Michael Jordan186cad02f9cf
diff --git a/agent/agent_init.py b/agent/agent_init.py
index 407f9a6c7b4..5972b849817 100644
--- a/agent/agent_init.py
+++ b/agent/agent_init.py
@@ -1963,6 +1963,9 @@ def init_agent(
compression_in_place = is_truthy_value(
_compression_cfg.get("in_place"), default=True
)
+ compression_micro_compact = is_truthy_value(
+ _compression_cfg.get("micro_compact"), default=True
+ )
codex_app_server_auto_compaction = str(
_compression_cfg.get("codex_app_server_auto", "native") or "native"
).lower()
@@ -2418,6 +2421,10 @@ def init_agent(
pass
agent.compression_enabled = compression_enabled
agent.compression_in_place = compression_in_place
+ # Apply micro-compaction flag to the compressor (enabled by default)
+ _cc = getattr(agent, "context_compressor", None)
+ if _cc is not None and hasattr(_cc, "_micro_compact_enabled"):
+ _cc._micro_compact_enabled = compression_micro_compact
agent.codex_app_server_auto_compaction = codex_app_server_auto_compaction
agent.max_compression_attempts = compression_max_attempts
agent.compression_idle_compact_after_seconds = (
diff --git a/agent/context_compressor.py b/agent/context_compressor.py
index 209253335b6..a42e9d374b8 100644
--- a/agent/context_compressor.py
+++ b/agent/context_compressor.py
@@ -364,6 +364,11 @@ _SUMMARY_RATIO = 0.20
# itself a context-pressure source and slows every compaction.
_SUMMARY_TOKENS_CEILING = 10_000
+# Micro-compaction failure guard: after this many consecutive failures on the
+# same cursor position, skip the stuck exchange and advance the cursor so the
+# system doesn't busy-loop on an unsummarizable exchange every turn.
+_MICRO_COMPACT_MAX_CONSECUTIVE_FAILURES = 3
+
# Aggregate cap on the serialized turn block fed to the summarizer prompt
# (chars). Per-message truncation (_CONTENT_MAX / _TOOL_ARGS_MAX) alone is
# not enough: a compression window with hundreds of already-truncated turns
@@ -1290,6 +1295,12 @@ class ContextCompressor(ContextEngine):
self._active_compression_telemetry = None
self._compression_telemetry_seed = None
+ # Micro-compaction state reset
+ self._micro_compact_cursor = 0
+ self._micro_compact_rolling_summary = ""
+ self._micro_compact_consecutive_failures = 0
+ self._micro_compact_last_failure_cursor = -1
+
def _begin_compression_telemetry(
self,
*,
@@ -2136,6 +2147,15 @@ class ContextCompressor(ContextEngine):
# deterministic "summary unavailable" handoff and drop the middle window.
self.abort_on_summary_failure = abort_on_summary_failure
+ # ── Micro-compaction (per-turn rolling compaction) ─────────
+ # Default: enabled when not explicitly disabled (backward compatible).
+ self._micro_compact_enabled: bool = True
+ self._micro_compact_cursor: int = 0
+ self._micro_compact_rolling_summary: str = ""
+ self._micro_compact_consecutive_failures: int = 0
+ self._micro_compact_last_failure_cursor: int = -1
+ self._micro_compact_defrag_threshold_tokens: int = 2000
+
# Defer context-length resolution to first access (#32221):
# get_model_context_length() can issue a synchronous /models HTTP
# probe, which must not block AIAgent construction. The small-context
@@ -4987,6 +5007,448 @@ This compaction should PRIORITISE preserving all information related to the focu
# Main compression entry point
# ------------------------------------------------------------------
+ def _resolve_compact_cursor(
+ self,
+ messages: List[Dict[str, Any]],
+ head_end: int,
+ tail_start: int,
+ ) -> int:
+ """Derive the micro-compaction cursor from in-memory state or transcript scan.
+
+ Returns the index of the first message that has NOT yet been absorbed
+ into the rolling summary. If the in-memory cursor ``_micro_compact_cursor``
+ is valid (non-zero and within the compressible window), use it directly.
+ Otherwise scan from *head_end* through *tail_start* for the last context
+ summary marker and set the cursor past it.
+ """
+ if self._micro_compact_cursor > head_end and self._micro_compact_cursor < tail_start:
+ return self._micro_compact_cursor
+ # Scan transcript for the last summary marker
+ last_summary_idx = -1
+ for idx in range(head_end, tail_start):
+ if self._is_context_summary_message(messages[idx]):
+ last_summary_idx = idx
+ if last_summary_idx >= head_end:
+ cursor = last_summary_idx + 1
+ else:
+ cursor = head_end
+ self._micro_compact_cursor = cursor
+ return cursor
+
+ def _find_one_exchange(
+ self,
+ messages: List[Dict[str, Any]],
+ start: int,
+ tail_start: int,
+ ) -> Optional[tuple[int, int]]:
+ """Find the next complete exchange starting at *start*.
+
+ An exchange is: (optional) user message + assistant message + its tool
+ results. Returns ``(exchange_start, exchange_end)`` indices into
+ *messages*, or ``None`` if no complete exchange is available before
+ *tail_start*.
+
+ Tool results are consumed as a group following the assistant message
+ (consecutive ``tool``-role messages). The assistant message itself must
+ exist; without one there is nothing to summarise.
+ """
+ idx = start
+ n = len(messages)
+ if idx >= n or idx >= tail_start:
+ return None
+
+ # Walk past any user messages or summary markers until we hit an
+ # assistant message with actual output (content or tool_calls).
+ while idx < tail_start and idx < n:
+ msg = messages[idx]
+ role = msg.get("role")
+ if role == "assistant":
+ break
+ idx += 1
+
+ if idx >= tail_start or idx >= n:
+ return None
+
+ exchange_start = idx
+
+ # Advance past the assistant message
+ idx += 1
+
+ # Consume following tool results as part of the same exchange
+ while idx < tail_start and idx < n:
+ if messages[idx].get("role") == "tool":
+ idx += 1
+ else:
+ break
+
+ if idx <= exchange_start:
+ return None
+ return (exchange_start, idx)
+
+ def _serialize_one_exchange(
+ self,
+ messages: List[Dict[str, Any]],
+ start: int,
+ end: int,
+ ) -> str:
+ """Serialize a single exchange for the micro-summarizer.
+
+ Uses the same content-max truncation and redaction as the batch
+ ``_serialize_for_summary`` method, but scoped to one exchange.
+ """
+ from agent.agent_runtime_helpers import strip_think_blocks
+
+ parts = []
+ for msg in messages[start:end]:
+ role = msg.get("role", "unknown")
+ content = msg.get("content")
+ if isinstance(content, list):
+ text_parts: list[str] = []
+ for part in content:
+ if isinstance(part, dict):
+ ptype = part.get("type")
+ if ptype == "text":
+ text_parts.append(part.get("text", ""))
+ elif ptype in {"image", "image_url", "input_image"}:
+ text_parts.append(_image_part_label(part))
+ else:
+ text_parts.append(f"[{ptype or 'attachment'}]")
+ elif isinstance(part, str):
+ text_parts.append(part)
+ content = "\n".join(text_parts)
+ content = _redact_compaction_text(content or "")
+ content = _MEDIA_DIRECTIVE_RE.sub("[media attachment]", content)
+ if role == "assistant" and content:
+ content = strip_think_blocks(None, content)
+
+ if role == "tool":
+ tool_id = msg.get("tool_call_id", "")
+ if len(content) > self._CONTENT_MAX:
+ content = content[:self._CONTENT_HEAD] + "\n...[truncated]...\n" + content[-self._CONTENT_TAIL:]
+ parts.append(f"[TOOL RESULT {tool_id}]: {content}")
+ continue
+
+ if role == "assistant":
+ if len(content) > self._CONTENT_MAX:
+ content = content[:self._CONTENT_HEAD] + "\n...[truncated]...\n" + content[-self._CONTENT_TAIL:]
+ tool_calls = msg.get("tool_calls", [])
+ if tool_calls:
+ tc_parts = []
+ for tc in tool_calls:
+ if isinstance(tc, dict):
+ fn = tc.get("function", {})
+ name = fn.get("name", "?")
+ args = _redact_compaction_text(fn.get("arguments", ""))
+ if len(args) > self._TOOL_ARGS_MAX:
+ args = args[:self._TOOL_ARGS_HEAD] + "..."
+ tc_parts.append(f" {name}({args})")
+ else:
+ fn = getattr(tc, "function", None)
+ name = getattr(fn, "name", "?") if fn else "?"
+ tc_parts.append(f" {name}(...)")
+ content += "\n[Tool calls:\n" + "\n".join(tc_parts) + "\n]"
+ parts.append(f"[ASSISTANT]: {content}")
+ continue
+
+ if role == "user":
+ if len(content) > self._CONTENT_MAX:
+ content = content[:self._CONTENT_HEAD] + "\n...[truncated]...\n" + content[-self._CONTENT_TAIL:]
+ parts.append(f"[USER]: {content}")
+ continue
+
+ parts.append(f"[{role.upper()}]: {content}")
+
+ return "\n---\n".join(parts)
+
+ def _build_micro_summary_prompt(
+ self,
+ existing_summary: str,
+ exchange_text: str,
+ ) -> List[Dict[str, str]]:
+ """Build the prompt messages for a single-exchange micro-summary."""
+ if existing_summary.strip():
+ summary_block = existing_summary
+ else:
+ summary_block = "(No previous summary yet.)"
+
+ user_prompt = (
+ "You are a summarization agent creating a compact record of an "
+ "ongoing conversation. You are given a running summary and the "
+ "next exchange from the conversation. Merge the exchange's key "
+ "decisions, requirements, file paths, and open questions into the "
+ "summary. Preserve the summary's structure. Drop resolved details "
+ "that are no longer relevant. Add new decisions, file paths, and "
+ "open questions.\n\n"
+ "NEVER include API keys, tokens, passwords, secrets, credentials, "
+ "or connection strings in the summary \u2014 replace any that appear "
+ f"with [REDACTED].\n\n"
+ f"## Current Running Summary\n{summary_block}\n\n"
+ f"## Next Exchange to Merge\n{exchange_text}\n\n"
+ "Return ONLY the updated summary text, no preamble or explanation. "
+ "Do not include this instruction block in your output."
+ )
+
+ return [
+ {"role": "system", "content": "You are a conversation summarization assistant."},
+ {"role": "user", "content": user_prompt},
+ ]
+
+ def _micro_summarize_one(
+ self,
+ exchange_text: str,
+ ) -> Optional[str]:
+ """Micro-summarize one exchange into the rolling summary via aux LLM.
+
+ Calls the same auxiliary compression model as the batch path, with
+ a focused prompt that merges one exchange into the running summary.
+ Returns the updated summary text, or ``None`` on failure.
+ """
+ from agent.auxiliary_client import call_llm, aux_interrupt_protection
+
+ messages = self._build_micro_summary_prompt(
+ self._micro_compact_rolling_summary,
+ exchange_text,
+ )
+
+ call_kwargs = {
+ "task": "compression",
+ "messages": messages,
+ "max_tokens": min(1500, self.max_summary_tokens or 1500),
+ "temperature": 0.1,
+ }
+ if self.summary_model:
+ call_kwargs["model"] = self.summary_model
+ if self.model:
+ call_kwargs.setdefault("main_runtime", {
+ "model": self.model,
+ "provider": self.provider or "",
+ "base_url": self.base_url or "",
+ "api_key": self.api_key or "",
+ "api_mode": getattr(self, "api_mode", "") or "",
+ })
+
+ try:
+ with aux_interrupt_protection():
+ response = call_llm(**call_kwargs)
+ except Exception as exc:
+ logger.info("micro-summarization call failed: %s", exc)
+ return None
+
+ message = response.choices[0].message
+ if isinstance(message, dict):
+ content = message.get("content")
+ else:
+ content = getattr(message, "content", message)
+ if not isinstance(content, str):
+ content = str(content) if content else ""
+ content = content.strip()
+ if not content:
+ logger.info("micro-summarization returned empty content")
+ return None
+
+ from agent.agent_runtime_helpers import strip_think_blocks
+ stripped = strip_think_blocks(None, content).strip()
+ return stripped if stripped else None
+
+ def _needs_defrag(self) -> bool:
+ """Return True when the rolling summary is large enough to defrag."""
+ content_tokens = estimate_tokens_rough(self._micro_compact_rolling_summary)
+ return content_tokens >= self._micro_compact_defrag_threshold_tokens
+
+ def _defrag_rolling_summary(
+ self,
+ messages: List[Dict[str, Any]],
+ head_end: int,
+ tail_start: int,
+ ) -> None:
+ """Re-summarize the rolling summary + remaining middle in one shot.
+
+ This is a lightweight batch compaction on just the summary and the
+ remaining un-compacted region \u2014 NOT the full transcript. It replaces
+ the rolling summary with a fresh, compact version and advances the
+ cursor to *tail_start*.
+ """
+ middle_content = self._serialize_one_exchange(messages, head_end, tail_start)
+ fresh_summary = self._micro_summarize_one(middle_content)
+ if fresh_summary:
+ self._micro_compact_rolling_summary = fresh_summary
+ self._micro_compact_cursor = tail_start
+ logger.info(
+ "Micro-compaction defrag: rolling summary re-summarized "
+ "(%d chars)", len(fresh_summary),
+ )
+
+ def _micro_compact(
+ self,
+ messages: List[Dict[str, Any]],
+ ) -> List[Dict[str, Any]]:
+ """Run one round of micro-compaction on the conversation.
+
+ Absorbs the oldest uncompacted exchange into the rolling summary,
+ advancing the in-memory cursor. Runs in post-turn idle time.
+
+ This is the public entry point called from ``finalize_turn()``.
+ Returns the (possibly modified) message list.
+
+ NOTE: the in-memory splice alone is not persisted — the subsequent
+ ``_persist_session`` flush is append-only, so old DB rows stay
+ ``active=1`` and a session resume double-loads both the summary and
+ the original exchanges (#82483). This method therefore also calls
+ ``archive_and_compact`` on the session DB to soft-archive old rows
+ and insert the compacted set atomically.
+ """
+ if not self._micro_compact_enabled:
+ return messages
+
+ n_messages = len(messages)
+ if n_messages < 4:
+ return messages
+
+ head_size = self._protect_head_size(messages)
+ compress_start = self._align_boundary_forward(messages, head_size)
+ compress_end = self._find_tail_cut_by_tokens(messages, compress_start)
+
+ if compress_start >= compress_end:
+ return messages
+
+ cursor = self._resolve_compact_cursor(messages, compress_start, compress_end)
+ if cursor >= compress_end:
+ return messages
+
+ # Find the next exchange
+ exchange = self._find_one_exchange(messages, cursor, compress_end)
+ if exchange is None:
+ return messages
+
+ exchange_start, exchange_end = exchange
+
+ # Check for defrag trigger
+ if self._needs_defrag():
+ self._defrag_rolling_summary(messages, exchange_start, compress_end)
+ result = self._splice_micro_compact_result(messages, exchange_start, compress_end)
+ self._sync_micro_compact_to_db(result)
+ self._micro_compact_consecutive_failures = 0
+ self._micro_compact_last_failure_cursor = -1
+ return result
+
+ # Micro-summarize one exchange
+ exchange_text = self._serialize_one_exchange(messages, exchange_start, exchange_end)
+ updated_summary = self._micro_summarize_one(exchange_text)
+ if updated_summary is None:
+ # Track consecutive failures on the same cursor position so we
+ # don't busy-loop on an unsummarizable exchange every turn.
+ if exchange_start == self._micro_compact_last_failure_cursor:
+ self._micro_compact_consecutive_failures += 1
+ else:
+ self._micro_compact_consecutive_failures = 1
+ self._micro_compact_last_failure_cursor = exchange_start
+
+ if self._micro_compact_consecutive_failures >= _MICRO_COMPACT_MAX_CONSECUTIVE_FAILURES:
+ logger.info(
+ "Micro-compaction: skipping exchange at cursor %d "
+ "after %d consecutive failures",
+ exchange_start, self._micro_compact_consecutive_failures,
+ )
+ # Advance the cursor past the stuck exchange so we don't
+ # retry it every turn. The skipped messages remain in the
+ # transcript and will be absorbed by the next batch
+ # compression or defrag.
+ self._micro_compact_cursor = exchange_end
+ self._micro_compact_consecutive_failures = 0
+ self._micro_compact_last_failure_cursor = -1
+ return messages
+
+ self._micro_compact_rolling_summary = updated_summary
+ self._micro_compact_cursor = exchange_end
+ self._micro_compact_consecutive_failures = 0
+ self._micro_compact_last_failure_cursor = -1
+
+ result = self._splice_micro_compact_result(messages, exchange_start, exchange_end)
+ self._sync_micro_compact_to_db(result)
+ return result
+
+ def _sync_micro_compact_to_db(
+ self,
+ compacted_messages: List[Dict[str, Any]],
+ ) -> None:
+ """Persist the micro-compacted message set to the session DB.
+
+ Soft-archives every currently-active message row (``active = 0``)
+ and inserts *compacted_messages* as fresh active rows — atomically,
+ via ``archive_and_compact``. Then stamps ``_DB_PERSISTED_MARKER`` on
+ every dict so the upcoming append-only flush (``_persist_session`` →
+ ``_flush_messages_to_session_db_unlocked``) skips them: they are
+ already correctly stored.
+
+ Without this, the in-memory-only splice leaves old exchange rows at
+ ``active=1``, and a session resume double-loads both the summary and
+ the original messages — blowing past the model's context limit.
+ """
+ session_db = getattr(self, "_session_db", None)
+ session_id = getattr(self, "_session_id", "")
+ if not session_db or not session_id:
+ return
+ try:
+ session_db.archive_and_compact(session_id, compacted_messages)
+ for msg in compacted_messages:
+ if isinstance(msg, dict):
+ msg[_DB_PERSISTED_MARKER] = True
+ except Exception:
+ logger.info(
+ "Micro-compaction DB sync failed — resume will double-load "
+ "compacted messages until the next batch compression"
+ )
+
+ def _splice_micro_compact_result(
+ self,
+ messages: List[Dict[str, Any]],
+ splice_start: int,
+ splice_end: int,
+ ) -> List[Dict[str, Any]]:
+ """Replace *messages[splice_start:splice_end]* with a summary marker.
+
+ The summary marker carries the rolling summary text and the
+ ``_compressed_summary`` metadata flag so downstream consumers
+ (resume, handoff, /compress) handle it identically to batch
+ compaction summaries.
+ """
+ summary_text = self._micro_compact_rolling_summary
+ if not summary_text.strip():
+ return messages
+
+ content = (
+ f"{SUMMARY_PREFIX}\n\n"
+ f"{HISTORICAL_TASK_HEADING}\n"
+ )
+ content += summary_text.strip()
+ content += f"\n\n{_SUMMARY_END_MARKER}"
+
+ summary_msg = {
+ "role": "user",
+ "content": content,
+ COMPRESSED_SUMMARY_METADATA_KEY: True,
+ COMPRESSED_SUMMARY_HAS_USER_TURN_KEY: True,
+ }
+
+ result = messages[:splice_start] + [summary_msg] + messages[splice_end:]
+
+ # The rolling summary is cumulative: this marker already contains
+ # everything every earlier micro-compaction marker held. Leaving those
+ # in place stacks near-duplicate copies of the same text — each with
+ # its own prefix/heading/end-marker scaffolding — so the transcript
+ # grows with every turn instead of shrinking, which defeats the point.
+ # Keep only the newest marker.
+ marker_idxs = [
+ i for i, m in enumerate(result)
+ if isinstance(m, dict) and m.get(COMPRESSED_SUMMARY_METADATA_KEY)
+ ]
+ if len(marker_idxs) > 1:
+ superseded = set(marker_idxs[:-1])
+ result = [m for i, m in enumerate(result) if i not in superseded]
+
+ _strip_persistence_markers(result)
+ return result
+
def compress(
self,
messages: List[Dict[str, Any]],
diff --git a/agent/turn_finalizer.py b/agent/turn_finalizer.py
index 0f636c1dd24..110a104c46c 100644
--- a/agent/turn_finalizer.py
+++ b/agent/turn_finalizer.py
@@ -349,6 +349,31 @@ def finalize_turn(
_apply_override = getattr(agent, "_apply_persist_user_message_override", None)
if callable(_apply_override):
_apply_override(messages)
+
+ # ── Post-turn micro-compaction ────────────────────────────
+ # After the assistant response is finalized but before the session is
+ # persisted, run micro-compaction to absorb the oldest uncompacted
+ # exchange into the rolling summary. This amortizes compression
+ # across turns rather than batching it into one big pause.
+ if not interrupted and not failed:
+ try:
+ _compressor = getattr(agent, "context_compressor", None)
+ if (
+ _compressor
+ and getattr(_compressor, '_micro_compact_enabled', False)
+ and final_response
+ ):
+ _before = len(messages)
+ messages[:] = _compressor._micro_compact(messages) or messages
+ _after = len(messages)
+ if _before != _after:
+ logger.info(
+ "Micro-compaction: %d -> %d messages",
+ _before, _after,
+ )
+ except Exception as _mc_err:
+ logger.info("Micro-compaction failed: %s", _mc_err)
+
agent._persist_session(messages, conversation_history)
except Exception as _persist_err:
_cleanup_errors.append(f"persist_session: {_persist_err}")
diff --git a/tests/agent/test_micro_compaction.py b/tests/agent/test_micro_compaction.py
new file mode 100644
index 00000000000..3bfcdceccbf
--- /dev/null
+++ b/tests/agent/test_micro_compaction.py
@@ -0,0 +1,179 @@
+"""Tests for per-turn micro-compaction in ``ContextCompressor``.
+
+Micro-compaction amortizes the cost of context compression: instead of one
+long pause when the window fills, each turn folds the single oldest
+un-absorbed exchange into a rolling summary.
+
+The invariants that matter:
+
+* one call absorbs exactly one exchange (assistant + its tool results), so
+ the per-turn cost stays bounded;
+* the absorbed span is replaced by a summary marker carrying the usual
+ ``_compressed_summary`` metadata, so resume/handoff treat it like a batch
+ summary;
+* the cursor advances, so successive calls walk forward rather than
+ re-summarising the same exchange;
+* protected head and tail messages are never touched;
+* an exchange the summarizer cannot handle is retried a bounded number of
+ times and then skipped, so a poison exchange can't stall every turn.
+"""
+
+import pytest
+
+from agent.context_compressor import (
+ COMPRESSED_SUMMARY_METADATA_KEY,
+ ContextCompressor,
+ _MICRO_COMPACT_MAX_CONSECUTIVE_FAILURES,
+)
+
+
+def _compressor(summary="ROLLING SUMMARY") -> ContextCompressor:
+ cc = ContextCompressor(
+ model="test-model",
+ threshold_percent=0.75,
+ protect_first_n=1,
+ protect_last_n=2,
+ quiet_mode=True,
+ config_context_length=40960,
+ provider="test",
+ )
+ cc._micro_compact_enabled = True
+ # Stand in for the auxiliary summarizer LLM.
+ cc._micro_summarize_one = lambda _text: summary
+ return cc
+
+
+def _conversation(exchanges: int = 6) -> list:
+ msgs = [{"role": "system", "content": "system prompt"}]
+ for i in range(exchanges):
+ msgs.append({"role": "user", "content": f"question {i}"})
+ msgs.append({"role": "assistant", "content": f"answer {i} " + "z" * 400})
+ return msgs
+
+
+def _summary_markers(messages: list) -> list:
+ return [m for m in messages if m.get(COMPRESSED_SUMMARY_METADATA_KEY)]
+
+
+class TestMicroCompaction:
+ def test_absorbs_one_exchange_and_leaves_a_summary_marker(self):
+ cc = _compressor()
+ messages = _conversation()
+
+ result = cc._micro_compact(list(messages))
+
+ # The absorbed assistant turn is gone from the transcript.
+ assert any("answer 0" in str(m.get("content")) for m in messages)
+ assert not any("answer 0" in str(m.get("content")) for m in result)
+ markers = _summary_markers(result)
+ assert len(markers) == 1
+ assert "ROLLING SUMMARY" in markers[0]["content"]
+ # The marker stands in for a user turn, like batch compaction's does.
+ assert markers[0]["role"] == "user"
+
+ def test_disabled_is_a_no_op(self):
+ cc = _compressor()
+ cc._micro_compact_enabled = False
+ messages = _conversation()
+
+ assert cc._micro_compact(list(messages)) == messages
+
+ def test_cursor_advances_across_successive_turns(self):
+ cc = _compressor()
+ messages = _conversation(exchanges=8)
+
+ first = cc._micro_compact(list(messages))
+ cursor_after_first = cc._micro_compact_cursor
+ second = cc._micro_compact(list(first))
+
+ assert cursor_after_first > 0
+ assert cc._micro_compact_cursor >= cursor_after_first
+ # Still exactly one marker: the second pass merges into the rolling
+ # summary rather than stacking a second summary block.
+ assert len(_summary_markers(second)) == 1
+
+ def test_protected_head_and_tail_survive(self):
+ cc = _compressor()
+ messages = _conversation()
+
+ result = cc._micro_compact(list(messages))
+
+ assert result[0] == messages[0], "system prompt must be preserved"
+ assert result[-1] == messages[-1], "most recent turn must be preserved"
+
+ def test_short_conversation_is_untouched(self):
+ cc = _compressor()
+ messages = [
+ {"role": "system", "content": "sys"},
+ {"role": "user", "content": "hi"},
+ {"role": "assistant", "content": "hello"},
+ ]
+
+ assert cc._micro_compact(list(messages)) == messages
+
+ def test_summarizer_failure_leaves_conversation_intact(self):
+ cc = _compressor()
+ cc._micro_summarize_one = lambda _text: None
+ messages = _conversation()
+
+ result = cc._micro_compact(list(messages))
+
+ assert result == messages
+ assert cc._micro_compact_consecutive_failures == 1
+
+ def test_poison_exchange_is_skipped_after_repeated_failures(self):
+ """A repeatedly unsummarizable exchange must not stall every turn."""
+ cc = _compressor()
+ cc._micro_summarize_one = lambda _text: None
+ messages = _conversation()
+
+ for _ in range(_MICRO_COMPACT_MAX_CONSECUTIVE_FAILURES):
+ cc._micro_compact(list(messages))
+
+ # The cursor has moved past the stuck exchange and the strike count
+ # is reset, so the next turn attempts new material.
+ assert cc._micro_compact_cursor > 0
+ assert cc._micro_compact_consecutive_failures == 0
+
+ def test_repeated_compaction_shrinks_context_and_keeps_one_marker(self):
+ """The whole point: successive turns must reduce the transcript.
+
+ The rolling summary is cumulative, so an earlier marker's text is a
+ subset of the current one. Keeping the earlier markers stacked
+ near-duplicate copies (each with its own heading/end-marker
+ scaffolding) and made the transcript grow every turn — the opposite
+ of what compaction is for.
+ """
+ from agent.model_metadata import estimate_messages_tokens_rough
+
+ cc = _compressor()
+ # Cumulative summary, like the real summarizer produces.
+ state = {"n": 0}
+
+ def growing(_text):
+ state["n"] += 1
+ return "SUMMARY " + " ".join(f"ex{i}" for i in range(state["n"]))
+
+ cc._micro_summarize_one = growing
+
+ messages = _conversation(exchanges=12)
+ before = estimate_messages_tokens_rough(messages)
+ for _ in range(6):
+ messages = cc._micro_compact(messages)
+ after = estimate_messages_tokens_rough(messages)
+
+ assert len(_summary_markers(messages)) == 1
+ assert after < before, f"context grew: {before} -> {after}"
+
+ def test_defrag_triggers_once_the_rolling_summary_grows(self):
+ cc = _compressor(summary="FRESH DEFRAGGED SUMMARY")
+ cc._micro_compact_rolling_summary = "x" * 40_000 # far over the threshold
+ messages = _conversation(exchanges=8)
+
+ assert cc._needs_defrag() is True
+ result = cc._micro_compact(list(messages))
+
+ assert cc._micro_compact_rolling_summary == "FRESH DEFRAGGED SUMMARY"
+ markers = _summary_markers(result)
+ assert len(markers) == 1
+ assert "FRESH DEFRAGGED SUMMARY" in markers[0]["content"]