Skip to content

The agent that grows with you

refactor(compression): extract preflight seed predicate onto ContextCompressor

kshitijk4poor29d4c0ebfde8
diff --git a/agent/context_compressor.py b/agent/context_compressor.py
index 10fa08bec33..be38dae5f9a 100644
--- a/agent/context_compressor.py
+++ b/agent/context_compressor.py
@@ -3682,6 +3682,26 @@ class ContextCompressor(ContextEngine):
self._verify_compaction_cleared_threshold = False
self.awaiting_real_usage_after_compression = False
+ def maybe_seed_preflight_display_tokens(self, preflight_tokens: int) -> None:
+ """Seed ``last_prompt_tokens`` from a rough preflight estimate, display-only.
+
+ Policy (co-located with the rest of the speculative-seed lifecycle —
+ see ``snapshot_preflight_display_tokens`` /
+ ``rollback_interrupted_preflight_display_tokens``): seed ONLY from
+ the 0 state ("no reading yet", #34282). Any non-zero value is
+ preserved — the -1 post-compression sentinel (#36718) AND any real
+ provider reading (#81481: the rough estimate intentionally
+ over-counts CJK / reasoning replay, 1.4-2.5x on heavy sessions, and
+ must never overwrite a real measurement).
+
+ Accepted trade-off: a provider reporting partial usage (e.g.
+ excluding cache-discounted tokens) pins the meter low until its next
+ report — preferred over estimator inflation.
+ """
+ _last = self.last_prompt_tokens
+ if _last == 0 and preflight_tokens > _last:
+ self.last_prompt_tokens = preflight_tokens
+
def snapshot_preflight_display_tokens(self) -> int:
"""Capture the display token count before a speculative preflight seed."""
return self.last_prompt_tokens
diff --git a/agent/turn_context.py b/agent/turn_context.py
index e664034db78..d14d5845534 100644
--- a/agent/turn_context.py
+++ b/agent/turn_context.py
@@ -1066,24 +1066,18 @@ def build_turn_context(
)
if not _preflight_deferred:
- _last = _compressor.last_prompt_tokens
- # The seed exists so the status bar shows current occupancy when a
- # provider reports no usage (#34282's motivation). But
- # ``last_prompt_tokens`` is also the post-response compression
- # gate's "real tokens" input (conversation_loop) and the CLI
- # context meter's source (cli.py). Overwriting a REAL provider
- # reading with the rough preflight estimate makes the bar jump to
- # an inflated number and can push the real-usage gate over the
- # threshold on estimator noise — compression then fires at far
- # below the user-configured threshold (observed: 492K real vs
- # ~685K rough on a 1M window; reasoning-heavy sessions inflate
- # the rough estimate 1.4-2.5x, see #81481).
- #
- # Policy: a real provider reading (>0) always wins. Seed only
- # from the 0 state ("no reading yet"); -1 stays protected as the
- # post-compression sentinel (#36718).
- if _last == 0 and _preflight_tokens > _last:
- _compressor.last_prompt_tokens = _preflight_tokens
+ # Display-only seed (see
+ # ContextCompressor.maybe_seed_preflight_display_tokens): a real
+ # provider reading always wins over the rough estimate, and the
+ # -1 post-compression sentinel (#36718) stays protected. On
+ # usage-less responses the seed also feeds the tool-loop
+ # compression gate — the one live path where an inflated seed
+ # could push compression below the user threshold.
+ _maybe_seed = getattr(
+ _compressor, "maybe_seed_preflight_display_tokens", None
+ )
+ if callable(_maybe_seed):
+ _maybe_seed(_preflight_tokens)
_compression_cooldown = getattr(
_compressor,
diff --git a/tests/agent/test_context_compressor.py b/tests/agent/test_context_compressor.py
index ae87008e04a..7e373f209e7 100644
--- a/tests/agent/test_context_compressor.py
+++ b/tests/agent/test_context_compressor.py
@@ -2451,46 +2451,39 @@ class TestLazyContextResolution:
class TestPreflightSentinelGuard:
- """Regression for #36718: the preflight token-display seed in
- run_conversation must NOT overwrite the -1 sentinel that
- compress_context() sets immediately after compression.
-
- The old guard `_preflight_tokens > (last_prompt_tokens or 0)` evaluated
- `(-1 or 0)` -> -1 (truthy), so any positive preflight estimate was > -1
- and clobbered the sentinel with a schema-inflated rough count, re-firing
- compression on the next turn. The fix treats any negative value as
- "no real usage yet" and skips the seed.
+ """Regression guards for the preflight token-display seed
+ (ContextCompressor.maybe_seed_preflight_display_tokens, called from
+ build_turn_context).
+
+ Policy: seed ONLY from the 0 state ("no reading yet", #34282 — the seed
+ keeps the status bar live when a provider reports no usage). Any
+ non-zero value is preserved: the -1 post-compression sentinel (#36718 —
+ compress_context parks it while awaiting real usage, and the seed must
+ not clobber it) AND any positive real provider reading (#81481 — the
+ rough estimate intentionally over-counts CJK / reasoning replay, so it
+ must never overwrite a real measurement).
"""
- def _seed(self, last_prompt_tokens, preflight_tokens):
- # Mirror the exact guard in agent/turn_context.py build_turn_context.
- _last = last_prompt_tokens
- if _last == 0 and preflight_tokens > _last:
- return preflight_tokens # would overwrite
- return last_prompt_tokens # preserved
-
def test_sentinel_preserved_after_compression(self, compressor):
compressor.last_prompt_tokens = -1
# A large schema-inflated preflight estimate must NOT overwrite -1.
- result = self._seed(compressor.last_prompt_tokens, 250_000)
- assert result == -1
+ compressor.maybe_seed_preflight_display_tokens(250_000)
+ assert compressor.last_prompt_tokens == -1
def test_zero_state_still_seeded(self, compressor):
# 0 means "no reading yet" — the seed keeps the status bar live when
# providers report no usage.
compressor.last_prompt_tokens = 0
- result = self._seed(compressor.last_prompt_tokens, 50_000)
- assert result == 50_000
+ compressor.maybe_seed_preflight_display_tokens(50_000)
+ assert compressor.last_prompt_tokens == 50_000
def test_real_provider_reading_wins_over_rough_estimate(self, compressor):
# Regression for the 492K-vs-685K display jump: a real provider
# reading must never be replaced by the schema/reasoning-inflated
# rough preflight estimate (#81481 class inflation).
compressor.last_prompt_tokens = 492_000
- result = self._seed(compressor.last_prompt_tokens, 685_344)
- assert result == 492_000
-
-
+ compressor.maybe_seed_preflight_display_tokens(685_344)
+ assert compressor.last_prompt_tokens == 492_000
class TestTurnPairPreservation:
"""Causal Coupling guard (#22523): compaction must never orphan a user turn.