Skip to content

The agent that grows with you

fix(agent): project real usage in preflight defer instead of fixed growth tolerance

Alan Hsu6d89b10653d0
diff --git a/agent/context_compressor.py b/agent/context_compressor.py
index 0c9cd3c85fe..523c08c8734 100644
--- a/agent/context_compressor.py
+++ b/agent/context_compressor.py
@@ -1358,6 +1358,7 @@ class ContextCompressor(ContextEngine):
self.last_real_prompt_tokens = 0
self.last_compression_rough_tokens = 0
self.last_rough_tokens_when_real_prompt_fit = 0
+ self._pending_request_rough_tokens = 0
self.awaiting_real_usage_after_compression = False
self._last_compression_telemetry = None
self._active_compression_telemetry = None
@@ -1629,6 +1630,7 @@ class ContextCompressor(ContextEngine):
self.last_real_prompt_tokens = 0
self.last_compression_rough_tokens = 0
self.last_rough_tokens_when_real_prompt_fit = 0
+ self._pending_request_rough_tokens = 0
self.awaiting_real_usage_after_compression = False
self._last_compression_telemetry = None
self._active_compression_telemetry = None
@@ -2106,6 +2108,7 @@ class ContextCompressor(ContextEngine):
self.last_real_prompt_tokens = 0
self.last_rough_tokens_when_real_prompt_fit = 0
self.last_compression_rough_tokens = 0
+ self._pending_request_rough_tokens = 0
self.awaiting_real_usage_after_compression = False
# Strikes were judged against the PREVIOUS threshold; a recomputed
# trigger invalidates them. Keep the durable copy in sync so a
@@ -2397,6 +2400,7 @@ class ContextCompressor(ContextEngine):
self.last_real_prompt_tokens = 0
self.last_compression_rough_tokens = 0
self.last_rough_tokens_when_real_prompt_fit = 0
+ self._pending_request_rough_tokens = 0
self.awaiting_real_usage_after_compression = False
self.summary_model = summary_model_override or ""
@@ -2485,6 +2489,17 @@ class ContextCompressor(ContextEngine):
if self.last_prompt_tokens < self.threshold_tokens:
if self.awaiting_real_usage_after_compression and self.last_compression_rough_tokens > 0:
self.last_rough_tokens_when_real_prompt_fit = self.last_compression_rough_tokens
+ elif self._pending_request_rough_tokens > 0:
+ # Pair the provider's real prompt count with the rough
+ # estimate of the request that produced it (recorded via
+ # note_request_rough_estimate just before the call). This
+ # keeps the defer baseline synchronized with real usage on
+ # EVERY fitting response, not only right after a
+ # compaction — without it, sessions that never compressed
+ # have no baseline and preflight fires on the raw rough
+ # estimate alone, which overcounts CJK text and provider
+ # replay blobs severalfold.
+ self.last_rough_tokens_when_real_prompt_fit = self._pending_request_rough_tokens
# Any real provider reading below the trigger proves the prompt
# fits again. Clear the real-usage effectiveness latch even
# when this response was not immediately after compaction. The
@@ -2493,6 +2508,7 @@ class ContextCompressor(ContextEngine):
self._record_ineffective_compression_verdict(0)
else:
self.last_rough_tokens_when_real_prompt_fit = 0
+ self._pending_request_rough_tokens = 0
# Anti-thrashing verdict, judged HERE because this is the only place
# that sees the provider's real prompt count for the just-compacted
@@ -2543,16 +2559,45 @@ class ContextCompressor(ContextEngine):
return
self.last_prompt_tokens = snapshot
+ def note_request_rough_estimate(self, rough_tokens: int) -> None:
+ """Record the rough estimate of the request about to be sent.
+
+ ``update_from_response()`` pairs this with the provider's real
+ ``prompt_tokens`` for the same request, giving
+ ``should_defer_preflight_to_real_usage()`` a synchronized
+ (rough, real) anchor to project real usage from rough growth.
+ Usage-less responses do not consume the pending value, so a
+ transport that reports usage separately still pairs correctly.
+ """
+ try:
+ self._pending_request_rough_tokens = max(0, int(rough_tokens))
+ except (TypeError, ValueError):
+ self._pending_request_rough_tokens = 0
+
def should_defer_preflight_to_real_usage(self, rough_tokens: int) -> bool:
"""Return True when a high rough preflight estimate is known-noisy.
``estimate_request_tokens_rough(..., tools=...)`` intentionally
- overestimates schema-heavy requests so Hermes compresses before a
- provider rejects the payload. After a successful compressed API call,
- though, provider ``prompt_tokens`` are a better signal than repeating
- compaction from the same rough schema overhead. Defer only while the
- rough estimate has grown modestly since a request the provider proved
- fit under the threshold.
+ overestimates so Hermes compresses before a provider rejects the
+ payload — but the margin is not a fixed percentage: CJK text is
+ counted at ~1.7x its o200k cost and Responses-mode reasoning replay
+ blobs at several times their billed cost, so heavy sessions can show
+ a rough estimate 2-3x real usage and compact at 35-55% of the real
+ window (churn: each pass stalls the turn for minutes and discards
+ detail).
+
+ Instead of tolerating a fixed rough-growth allowance, project real
+ usage from the last synchronized (rough, real) pair::
+
+ projected_real = last_real + (rough_now - rough_at_last_real)
+
+ Rough growth is itself an overestimate of real growth (every content
+ class is counted at >= its tokenizer cost), so the projection is an
+ upper bound on real usage and deferring below the threshold is safe.
+ Compression fires when the projection — not the raw estimate —
+ crosses the threshold. Should a pathological delta still slip past
+ the threshold, the provider's context-overflow error handler
+ compacts with the authoritative signal, as before.
"""
if rough_tokens < self.threshold_tokens:
return False
@@ -2577,13 +2622,13 @@ class ContextCompressor(ContextEngine):
if baseline <= 0:
return False
+ # No baseline ratchet here: the (rough, real) pair is refreshed by
+ # update_from_response() on every fitting response. Advancing the
+ # rough baseline without a matching real reading would shrink
+ # apparent growth and defer on stale data — the unsafe direction.
growth = max(0, rough_tokens - baseline)
- tolerated_growth = max(4096, int(self.threshold_tokens * 0.05))
- if growth > tolerated_growth:
- return False
-
- self.last_rough_tokens_when_real_prompt_fit = max(baseline, rough_tokens)
- return True
+ projected_real = self.last_real_prompt_tokens + growth
+ return projected_real < self.threshold_tokens
def should_compress(self, prompt_tokens: int = None) -> bool:
"""Check if context exceeds the compression threshold.
diff --git a/agent/conversation_loop.py b/agent/conversation_loop.py
index cfd5717c474..5bc4fe885cf 100644
--- a/agent/conversation_loop.py
+++ b/agent/conversation_loop.py
@@ -1976,6 +1976,15 @@ def run_conversation(
_estimate_tools_tokens_rough(agent.tools) if agent.tools else 0
)
total_chars = approx_tokens * 4
+ # Stash this request's rough estimate so update_from_response() can
+ # pair it with the provider's real prompt count — the (rough, real)
+ # anchor behind should_defer_preflight_to_real_usage()'s projection.
+ # getattr guard: test doubles built via object.__new__ lack the method.
+ _note_rough = getattr(
+ agent.context_compressor, "note_request_rough_estimate", None
+ )
+ if callable(_note_rough):
+ _note_rough(request_pressure_tokens)
_runtime_context_error = _ollama_context_limit_error(
agent, request_pressure_tokens
diff --git a/tests/agent/test_context_compressor.py b/tests/agent/test_context_compressor.py
index eaa730c14d0..a0e31e48333 100644
--- a/tests/agent/test_context_compressor.py
+++ b/tests/agent/test_context_compressor.py
@@ -98,15 +98,90 @@ class TestUpdateFromResponse:
compressor.update_from_response({})
assert compressor.last_prompt_tokens == 0
+ def test_pairs_noted_rough_estimate_with_fitting_real_usage(self, compressor):
+ """note_request_rough_estimate() + a fitting response must anchor the
+ defer baseline even when no compression ever ran — this is what gives
+ fresh sessions a (rough, real) pair before their first compaction."""
+ compressor.note_request_rough_estimate(120_000)
+ compressor.update_from_response({"prompt_tokens": 60_000})
+
+ assert compressor.last_real_prompt_tokens == 60_000
+ assert compressor.last_rough_tokens_when_real_prompt_fit == 120_000
+ # Consumed: a later usage-bearing response without a fresh note keeps
+ # the previous pair instead of re-pairing against a stale estimate.
+ assert compressor._pending_request_rough_tokens == 0
+
+ def test_post_compression_pairing_wins_over_noted_estimate(self, compressor):
+ """Right after a compaction the post-compression rough count is the
+ authoritative baseline (#36718); a stale pre-compression note must not
+ displace it."""
+ compressor.note_request_rough_estimate(120_000)
+ compressor.awaiting_real_usage_after_compression = True
+ compressor.last_compression_rough_tokens = 40_000
+ compressor.update_from_response({"prompt_tokens": 30_000})
+
+ assert compressor.last_rough_tokens_when_real_prompt_fit == 40_000
+
+ def test_usage_less_response_preserves_pending_note(self, compressor):
+ """Transports that report usage separately send usage-less responses
+ first; the pending pair must survive until real usage arrives."""
+ compressor.note_request_rough_estimate(120_000)
+ compressor.update_from_response({})
+
+ assert compressor._pending_request_rough_tokens == 120_000
+
+ def test_over_threshold_real_usage_clears_pending_note(self, compressor):
+ compressor.note_request_rough_estimate(120_000)
+ compressor.update_from_response({"prompt_tokens": 90_000})
+
+ assert compressor.last_rough_tokens_when_real_prompt_fit == 0
+ assert compressor._pending_request_rough_tokens == 0
+
class TestPreflightDeferral:
- def test_does_not_defer_when_rough_growth_is_large(self, compressor):
+ def test_defers_while_projected_real_usage_fits(self, compressor):
+ """Large rough growth alone must not trigger compaction: with real
+ usage at 50K and 10K of rough growth since that reading, projected
+ real usage is 60K — far under the 85K threshold. The old fixed 5%
+ growth tolerance compacted here at ~59% of the real window (CJK /
+ replay-blob overcount churn)."""
compressor.threshold_tokens = 85_000
compressor.last_real_prompt_tokens = 50_000
compressor.last_rough_tokens_when_real_prompt_fit = 90_000
+ assert compressor.should_defer_preflight_to_real_usage(100_000) is True
+
+ def test_does_not_defer_when_projected_real_usage_crosses_threshold(self, compressor):
+ """Projection = last real + rough growth. 80K real + 6K growth = 86K
+ >= 85K threshold: compression must run."""
+ compressor.threshold_tokens = 85_000
+ compressor.last_real_prompt_tokens = 80_000
+ compressor.last_rough_tokens_when_real_prompt_fit = 90_000
+
+ assert compressor.should_defer_preflight_to_real_usage(96_000) is False
+
+ def test_does_not_defer_without_a_baseline(self, compressor):
+ """No synchronized (rough, real) pair yet — fall back to trusting the
+ rough estimate (conservative: compress)."""
+ compressor.threshold_tokens = 85_000
+ compressor.last_real_prompt_tokens = 50_000
+ compressor.last_rough_tokens_when_real_prompt_fit = 0
+ compressor.last_compression_rough_tokens = 0
+
assert compressor.should_defer_preflight_to_real_usage(100_000) is False
+ def test_defer_does_not_ratchet_baseline(self, compressor):
+ """The baseline is refreshed only by update_from_response() pairing.
+ Deferring must not advance it: without a fresh real reading, a
+ ratcheted baseline would shrink apparent growth and defer on stale
+ data."""
+ compressor.threshold_tokens = 85_000
+ compressor.last_real_prompt_tokens = 50_000
+ compressor.last_rough_tokens_when_real_prompt_fit = 90_000
+
+ assert compressor.should_defer_preflight_to_real_usage(100_000) is True
+ assert compressor.last_rough_tokens_when_real_prompt_fit == 90_000
+
def test_defers_immediately_after_compaction_with_stale_real_prompt(self, compressor):
"""#36718: right after a compaction, last_real_prompt_tokens still holds
diff --git a/tests/run_agent/test_413_compression.py b/tests/run_agent/test_413_compression.py
index 294fc6714be..838817386b9 100644
--- a/tests/run_agent/test_413_compression.py
+++ b/tests/run_agent/test_413_compression.py
@@ -771,13 +771,16 @@ class TestPreflightCompression:
assert not any("Preflight compression" in msg for msg in lifecycle_messages)
- def test_preflight_compresses_when_rough_growth_after_fit_is_large(self, agent):
- """Large rough growth after a fitting request still triggers preflight."""
+ def test_preflight_compresses_when_projected_real_usage_crosses(self, agent):
+ """Projected real usage (last real + rough growth) crossing the
+ threshold still triggers preflight: 95K real + 12K rough growth =
+ 107K >= 100K. Growth alone no longer decides — real usage far below
+ the threshold defers instead (see TestPreflightDeferral)."""
agent.compression_enabled = True
agent.context_compressor.context_length = 200_000
agent.context_compressor.threshold_tokens = 100_000
- agent.context_compressor.last_prompt_tokens = 58_000
- agent.context_compressor.last_real_prompt_tokens = 58_000
+ agent.context_compressor.last_prompt_tokens = 95_000
+ agent.context_compressor.last_real_prompt_tokens = 95_000
agent.context_compressor.last_rough_tokens_when_real_prompt_fit = 113_000
big_history = []