Skip to content

The agent that grows with you

fix(compaction): retain oversized typed user text at checkpoint boundary

Xipong5af47ddcd24d
diff --git a/agent/native_compaction.py b/agent/native_compaction.py
index f0f44fab8ac..606f4c08fa2 100644
--- a/agent/native_compaction.py
+++ b/agent/native_compaction.py
@@ -175,6 +175,42 @@ def _extract_item_text(item: Any) -> Optional[str]:
return text if text.strip() else None
+def _input_text_parts_cost(content: Any) -> Optional[int]:
+ """Measure only the adapter-owned text-only shape, including whitespace and empty parts."""
+ if not isinstance(content, list) or not content or not all(
+ isinstance(part, dict) and part.get("type") == "input_text"
+ and isinstance(part.get("text"), str) for part in content
+ ):
+ return None
+ return sum(_approx_tokens(part["text"]) for part in content)
+
+
+def _truncate_input_text_parts(content: List[Dict[str, Any]], budget: int) -> List[Dict[str, Any]]:
+ """Copy the head of validated input_text parts without flattening their metadata."""
+ head = []
+ for part in content:
+ if budget <= 0:
+ break
+ text = part["text"]
+ cost = _approx_tokens(text)
+ if cost > budget:
+ # Use the same estimator as retention: four characters per token is
+ # not a safe head bound for CJK or multibyte non-ASCII text.
+ lo, hi = 0, len(text)
+ while lo < hi:
+ mid = (lo + hi + 1) // 2
+ if _approx_tokens(text[:mid]) <= budget:
+ lo = mid
+ else:
+ hi = mid - 1
+ if lo:
+ head.append({**part, "text": text[:lo]})
+ break
+ head.append({**part})
+ budget -= cost
+ return head
+
+
def _has_retainable_image_content(item: Any) -> bool:
"""True for a converted Responses message with a valid ``input_image`` part (only the
adapter-owned shape counts, so empty multipart placeholders never become durable history)."""
@@ -209,8 +245,12 @@ def prune_pre_checkpoint_items(
- The NEWEST contiguous run of checkpoints wins; relative order is preserved.
- User messages are kept verbatim within ``retained_user_token_budget``; the boundary
- message is head-truncated when it only partially fits (string content only). A
- recognized image-only user message is retained whole at one-token cost.
+ message is head-truncated when it only partially fits (strings or text-only typed
+ ``input_text`` parts, preserving part metadata). An oversized unsupported/mixed-content
+ boundary stops older user retention rather than substituting an older ask. A recognized
+ image-only user message is retained whole at one-token cost.
+ Head truncation can still omit a trailing internal provenance footer; no footer recovery
+ or semantic classification is attempted.
- Summaries are retained whole within ``retained_summary_token_budget``, never sliced
(framing would corrupt) and never duplicated.
- ``item_sources`` (parallel to ``items``) is the raw chat message each item came from.
@@ -291,7 +331,8 @@ def prune_pre_checkpoint_items(
if is_summary:
_retain_summary(text, item)
elif user_remaining > 0:
- cost = _approx_tokens(text)
+ parts_cost = _input_text_parts_cost(item.get("content"))
+ cost = parts_cost if parts_cost is not None else _approx_tokens(text)
if cost <= user_remaining:
retained_reversed.append(item)
user_remaining -= cost
@@ -300,6 +341,14 @@ def prune_pre_checkpoint_items(
if truncated["content"].strip():
retained_reversed.append(truncated)
user_remaining = 0
+ else:
+ if parts_cost is not None:
+ head = _truncate_input_text_parts(item["content"], user_remaining)
+ if any(part["text"].strip() for part in head):
+ retained_reversed.append({**item, "content": head})
+ # A non-truncatable boundary (e.g. text + image) must not let
+ # an older completed ask replace the newer oversized ask.
+ user_remaining = 0
result = items[first_cp : last_cp + 1] + list(reversed(retained_reversed)) + items[last_cp + 1 :]
logger.debug("Pruned pre-checkpoint items: %d input -> %d retained (user_rem=%d, summary_rem=%d)",
diff --git a/tests/agent/test_native_compaction_typed_user_retention.py b/tests/agent/test_native_compaction_typed_user_retention.py
new file mode 100644
index 00000000000..7dbba1db8fa
--- /dev/null
+++ b/tests/agent/test_native_compaction_typed_user_retention.py
@@ -0,0 +1,137 @@
+"""Retain the newest plaintext ask on the actual Codex typed-content path.
+
+These synthetic oversized asks require a native checkpoint; they do not model
+normal bounded tool receipts or establish a historical session failure.
+"""
+
+from copy import deepcopy
+
+import pytest
+
+from agent.codex_responses_adapter import _chat_messages_to_responses_input
+from agent.model_metadata import estimate_tokens_rough
+from agent.native_compaction import (
+ RETAINED_USER_MESSAGE_TOKEN_BUDGET,
+ prune_pre_checkpoint_items,
+)
+
+
+_CHECKPOINT = {"type": "compaction", "encrypted_content": "synthetic_checkpoint"}
+
+
[email protected]("issuer", ["codex_backend", None], ids=["typed-codex", "string-control"])
[email protected]("checkpoint", [True, False], ids=["checkpoint", "no-checkpoint"])
[email protected]("multipart", [False, True], ids=["single-text", "multipart"])
+def test_converter_retains_newest_oversized_ask_not_completed_older_ask(issuer, checkpoint, multipart):
+ prefix = "CURRENT ASK: inspect this input. "
+ body = "x" * (RETAINED_USER_MESSAGE_TOKEN_BUDGET * 4)
+ current = prefix + body
+ content = [{"type": "text", "text": prefix}, {"type": "text", "text": body}] if multipart else current
+ messages = [
+ {"role": "user", "content": "OLDER ASK: already completed"},
+ {"role": "assistant", "content": "Completed the older ask."},
+ {"role": "user", "content": content},
+ {
+ "role": "assistant",
+ "content": "Continuing the current ask.",
+ **({"codex_reasoning_items": [_CHECKPOINT]} if checkpoint else {}),
+ },
+ ]
+ original = deepcopy(messages)
+
+ converted = _chat_messages_to_responses_input(
+ messages, current_issuer_kind=issuer, native_compaction_eligible=True,
+ )
+ users = [item for item in converted if item.get("role") == "user"]
+ texts = [
+ "".join(part["text"] for part in item["content"])
+ if isinstance(item["content"], list) else item["content"]
+ for item in users
+ ]
+
+ if checkpoint:
+ assert converted[0] == _CHECKPOINT
+ assert len(users) == 1 # An older completed ask must not become the sole anchor.
+ assert texts[0].startswith("CURRENT ASK:")
+ assert current.startswith(texts[0]) and texts[0] != current
+ assert 0 < estimate_tokens_rough(texts[0]) <= RETAINED_USER_MESSAGE_TOKEN_BUDGET
+ assert converted[-1]["role"] == "assistant"
+ else:
+ assert texts == [messages[0]["content"], current]
+ for item, text in zip(users, texts):
+ if issuer == "codex_backend" or (multipart and text.startswith("CURRENT ASK:")):
+ assert isinstance(item["content"], list)
+ assert all(part["type"] == "input_text" for part in item["content"])
+ else:
+ assert isinstance(item["content"], str)
+ assert messages == original
+
+
+ "content,budget,expected",
+ [
+ ([{"type": "input_text", "text": "abcd"}], 2, "whole"),
+ ([{"type": "input_text", "text": "abcdefgh"}], 1, ("abcd",)),
+ ([{"type": "input_text", "text": "abcd"},
+ {"type": "input_text", "text": "efghijkl"},
+ {"type": "input_text", "text": "trailing"}], 2, ("abcd", "efgh")),
+ ([{"type": "input_text", "text": "你好世界"}], 2, ("你好",)),
+ ([{"type": "input_text", "text": "абвгдежз"}], 2, ("абвг",)),
+ ([{"type": "input_text", "text": "🌍🌍🌍"}], 2, ("🌍🌍",)),
+ ([{"type": "input_text", "text": "abcd" + " " * 40}], 2, ("abcd ",)),
+ ([{"type": "input_text", "text": "a"},
+ {"type": "input_text", "text": "b"},
+ {"type": "input_text", "text": "c"}], 2, ("a", "b")),
+ ([{"type": "input_text", "text": ""},
+ {"type": "input_text", "text": "abcdefgh"}], 2, ("", "abcd")),
+ ([], 1, "older"),
+ ([{"type": "input_text", "text": ""}], 1, "older"),
+ ([{"type": "input_text", "text": None}], 1, "older"),
+ ([{"type": "unknown", "value": "not text"}], 1, "older"),
+ ([{"type": "unknown", "text": "CURRENT" * 20}], 2, "none"),
+ ([{"type": "input_text", "text": "CURRENT" * 20},
+ {"type": "input_image", "image_url": "data:image/png;base64,AAAA"}], 2, "none"),
+ ([{"type": "input_text", "text": "abcd"},
+ {"type": "input_image", "image_url": "data:image/png;base64,AAAA"}], 1, "whole"),
+ ([{"type": "input_text", "text": "CURRENT"}], 0, "none"),
+ ],
+ ids=[
+ "fits-whole", "single-boundary", "multipart-boundary", "cjk", "cyrillic", "emoji",
+ "whitespace-budget", "part-rounding", "empty-leading-part", "empty-list", "empty-text",
+ "malformed-text", "unknown-part", "oversized-unsupported", "oversized-mixed-image",
+ "mixed-image-fits", "zero-budget",
+ ],
+)
+def test_typed_retention_is_budgeted_copy_safe_and_conservative(content, budget, expected):
+ older = {"role": "user", "content": "old"}
+ current = {
+ "type": "message", "role": "user", "id": "current-user",
+ "metadata": {"source": "synthetic"}, "content": deepcopy(content),
+ }
+ for index, part in enumerate(current["content"]):
+ part["metadata"] = {"index": index, "annotations": ["preserve"]}
+ tail = {"role": "assistant", "content": "untouched tail"}
+ items = [older, current, _CHECKPOINT, tail]
+ original = deepcopy(items)
+
+ pruned = prune_pre_checkpoint_items(items, retained_user_token_budget=budget)
+
+ assert pruned[0] is _CHECKPOINT and pruned[-1] is tail
+ users = [item for item in pruned if item.get("role") == "user"]
+ if expected == "older":
+ assert users == [older] # Unmeasurable placeholders retain the existing skip policy.
+ elif expected == "none":
+ assert users == [] # Never substitute an older ask for an oversized unsupported one.
+ else:
+ assert users and users[-1].get("id") == current["id"]
+ if expected == "whole":
+ assert users[-1] is current
+ else:
+ assert users == [{**current, "content": [
+ {**current["content"][index], "text": text}
+ for index, text in enumerate(expected)
+ ]}]
+ assert users[0] is not current
+ assert sum(max(1, estimate_tokens_rough(part["text"]))
+ for part in users[0]["content"]) <= budget
+ assert items == original