Skip to content
Python

fix(compaction): attachment token estimate, O(n) boundary search

Oskar Austegard83cde617530a
diff --git a/coworker/compaction.py b/coworker/compaction.py
index bb6653aa..69ed56f8 100644
--- a/coworker/compaction.py
+++ b/coworker/compaction.py
@@ -65,21 +65,54 @@ _USER_BUDGET_FRACTION = 0.08 # of the compaction trigger, so a lowered trigger
_USER_BUDGET_MIN = 2_000
_USER_BUDGET_MAX = 20_000 # what 8% comes to at the default trigger
_TRIM_FRACTION = 0.10
+# Flat token estimates for non-text content parts, whose base64 length is unrelated to what
+# the provider bills. Order-of-magnitude figures for a full-resolution image / a short PDF —
+# the point is not to be exact but to stop a data URL from dominating the whole signal.
+_IMAGE_PART_TOKENS = 1_500
+_FILE_PART_TOKENS = 3_000
# -- token math ---------------------------------------------------------------
+def _serialized_len(value: Any) -> int:
+ try:
+ return len(json.dumps(value, default=str))
+ except (TypeError, ValueError):
+ return len(str(value))
+
+
+def _message_chars(msg: Any) -> int:
+ """Serialized size of one message, with attachment parts charged at their real
+ token cost rather than their base64 length.
+
+ Images and PDFs ride in `content` as `data:` URLs (attachments.py caps them at 12 M
+ and 15 M characters). chars/4 reads a 1.5 MB screenshot as ~375 k tokens when a vision
+ model charges it closer to 1.5 k — enough, on its own, to sit permanently above
+ `cap_tokens` and re-trigger compaction on every iteration of the turn loop.
+ """
+ if not isinstance(msg, dict):
+ return _serialized_len(msg)
+ content = msg.get("content")
+ if not isinstance(content, list):
+ return _serialized_len(msg)
+ chars = _serialized_len({k: v for k, v in msg.items() if k != "content"})
+ for part in content:
+ kind = part.get("type") if isinstance(part, dict) else None
+ if kind == "image_url":
+ chars += _IMAGE_PART_TOKENS * 4
+ elif kind == "file":
+ chars += _FILE_PART_TOKENS * 4
+ else:
+ chars += _serialized_len(part)
+ return chars
+
+
def estimate_tokens(messages: list[dict[str, Any]]) -> int:
"""chars/4 over the serialized messages — the fallback signal for providers that
- never report usage (documented in the metering code)."""
- total = 0
- for msg in messages:
- try:
- total += len(json.dumps(msg, default=str))
- except (TypeError, ValueError):
- total += len(str(msg))
- return total // 4
+ never report usage (documented in the metering code). Attachment parts are charged a
+ flat per-part estimate; see `_message_chars`."""
+ return sum(_message_chars(msg) for msg in messages) // 4
def trigger_tokens(
@@ -183,9 +216,17 @@ def pick_boundary(messages: list[dict[str, Any]], *, keep_tokens: int) -> Option
start = 1 if messages and messages[0].get("role") == "system" else 0
users, assistants = _turn_starts(messages, start=start)
+ # suffix[i] = serialized chars of messages[i:], built in one backward pass. Measuring
+ # each candidate with `estimate_tokens(messages[i:])` instead re-serializes the whole
+ # tail per candidate — O(n²), and ~1 s of blocking CPU on a 1 200-message session,
+ # paid on the turn loop every time the trigger fires.
+ suffix = [0] * (len(messages) + 1)
+ for i in range(len(messages) - 1, -1, -1):
+ suffix[i] = suffix[i + 1] + _message_chars(messages[i])
+
def _fit(candidates: list[int]) -> Optional[int]:
for i in candidates: # earliest-first: keep as much verbatim as fits
- if estimate_tokens(messages[i:]) <= keep_tokens:
+ if suffix[i] // 4 <= keep_tokens:
return i
return None
@@ -198,7 +239,10 @@ def pick_boundary(messages: list[dict[str, Any]], *, keep_tokens: int) -> Option
if boundary is None:
boundary = inside[-1] if inside else users[-1]
if boundary is None:
- boundary = _fit(assistants) or (assistants[-1] if assistants else None)
+ fitted = _fit(assistants)
+ # `or` here would discard a legitimate index 0 (a history with no system message
+ # that opens on an assistant turn); it is filtered by the `<= start` check below.
+ boundary = fitted if fitted is not None else (assistants[-1] if assistants else None)
# A boundary at (or before) the first real message summarizes nothing — skip.
if boundary is None or boundary <= start:
return None
diff --git a/tests/test_compaction.py b/tests/test_compaction.py
index 6c937555..9a2814f3 100644
--- a/tests/test_compaction.py
+++ b/tests/test_compaction.py
@@ -2,6 +2,7 @@
extraction, summarizer seam, trim fallback, outbound view. No engine involved."""
import json
+import time
import pytest
@@ -429,3 +430,75 @@ def test_user_message_budget_scales_with_the_trigger():
assert C.user_message_budget(60_000) == 4_800 # a lowered trigger keeps its saving
assert C.user_message_budget(1_000) == C._USER_BUDGET_MIN # floor
assert C.user_message_budget(10_000_000) == C._USER_BUDGET_MAX # ceiling
+
+
+# -- attachments --------------------------------------------------------------
+
+
+def _image_turn(chars: int = 1_500_000) -> dict:
+ return {
+ "role": "user",
+ "content": [
+ {"type": "text", "text": "what's in this screenshot?"},
+ {
+ "type": "image_url",
+ "image_url": {"url": "data:image/png;base64," + "A" * chars},
+ },
+ ],
+ }
+
+
+def test_image_part_is_not_charged_its_base64_length():
+ """A data-URL image must not dominate the signal: chars/4 read a 1.5 MB screenshot as
+ ~375k tokens, so a single attachment sat permanently above cap_tokens and re-triggered
+ compaction on every iteration of the turn loop."""
+ msgs = [{"role": "system", "content": "s"}, _image_turn()]
+ est = estimate_tokens(msgs)
+ assert est < 5_000
+ assert not should_compact(est, 200_000)
+
+
+def test_pdf_part_is_not_charged_its_base64_length():
+ msgs = [
+ {"role": "system", "content": "s"},
+ {
+ "role": "user",
+ "content": [
+ {"type": "text", "text": "summarize this"},
+ {
+ "type": "file",
+ "file": {
+ "filename": "report.pdf",
+ "file_data": "data:application/pdf;base64," + "B" * 2_000_000,
+ },
+ },
+ ],
+ },
+ ]
+ assert estimate_tokens(msgs) < 10_000
+
+
+def test_text_only_estimate_is_unchanged_by_part_handling():
+ """Text-only histories must measure exactly as before — the whole trigger threshold is
+ calibrated against that number."""
+ msgs = convo(turns=6)
+ assert estimate_tokens(msgs) == sum(len(json.dumps(m, default=str)) for m in msgs) // 4
+
+
+def test_boundary_search_is_linear_in_history_length():
+ """Measuring each candidate with estimate_tokens(messages[i:]) re-serialized the whole
+ tail per candidate — ~1 s of blocking CPU on a 1 200-message session, on the turn loop."""
+ msgs = [{"role": "system", "content": "s"}]
+ for i in range(300):
+ a = assistant("done " + "z" * 300, tool_calls=[("read_file", {"path": "a.py"})])
+ msgs += [
+ user(f"task {i} " + "x" * 400),
+ a,
+ tool(a["tool_calls"][0]["id"], {"exit_code": 0, "out": "y" * 4000}),
+ ]
+ started = time.perf_counter()
+ boundary = pick_boundary(msgs, keep_tokens=40_000)
+ elapsed = time.perf_counter() - started
+ assert boundary is not None
+ assert estimate_tokens(msgs[boundary:]) <= 40_000
+ assert elapsed < 0.25 # linear lands ~7 ms here; the quadratic version took ~950 ms