Skip to content

The agent that grows with you

fix(compression): fence the durable cooldown rollback per compressor; one stale-attempt helper

teknium10765099ff4e8
diff --git a/agent/context_compressor.py b/agent/context_compressor.py
index e273d7cae1c..d63434ec623 100644
--- a/agent/context_compressor.py
+++ b/agent/context_compressor.py
@@ -3619,12 +3619,9 @@ Summary generation was unavailable, so this is a best-effort deterministic fallb
# candidate itself is discarded downstream by the working-attempt check; bail here so the
# attribute writes never land. Entry-generation claims (lock sit-outs) do not count; the
# working marker is the ownership boundary for summary state.
- from agent.conversation_compression import (
- _COMPRESSOR_ATTEMPT_GENERATION,
- _working_attempt_is_current,
- )
- if not _working_attempt_is_current(self, _COMPRESSOR_ATTEMPT_GENERATION.get()):
- raise AuxiliaryExplicitCancellation()
+ from agent.conversation_compression import _raise_if_stale_attempt
+
+ _raise_if_stale_attempt(self)
self._previous_summary = summary
self._clear_compression_failure_cooldown()
self._summary_model_fallen_back = False
@@ -3774,12 +3771,9 @@ Write only the summary body. Do not include any preamble or prefix."""
"""Classify a summary-call failure; retry once on the main model (returning its result) or arm a cooldown (None)."""
# A detached stale attempt must not arm a failure cooldown or stamp error state the fallback
# attempt owns; unwind as a cancellation so none of the shared-state writes below can land.
- from agent.conversation_compression import (
- _COMPRESSOR_ATTEMPT_GENERATION,
- _working_attempt_is_current,
- )
- if not _working_attempt_is_current(self, _COMPRESSOR_ATTEMPT_GENERATION.get()):
- raise AuxiliaryExplicitCancellation()
+ from agent.conversation_compression import _raise_if_stale_attempt
+
+ _raise_if_stale_attempt(self)
# Only a genuine no-provider RuntimeError gets the long cooldown; empty/invalid-response
# RuntimeErrors are transient and must get the main-model retry below first.
# ``call_llm`` raises ``RuntimeError`` for two very different cases: 1. 2. An empty/invalid response
@@ -4823,11 +4817,9 @@ Write only the summary body. Do not include any preamble or prefix."""
# Roll back the self-heal rehydration so the aborted attempt is a true no-op (#57835). Only the
# attempt still owning summary work may roll back: a detached stale attempt (reachable here via
# the deterministic summary pin) must not revert the fallback's _previous_summary.
- from agent.conversation_compression import (
- _COMPRESSOR_ATTEMPT_GENERATION,
- _working_attempt_is_current,
- )
- if _working_attempt_is_current(self, _COMPRESSOR_ATTEMPT_GENERATION.get()):
+ from agent.conversation_compression import _caller_attempt_is_current
+
+ if _caller_attempt_is_current(self):
self._previous_summary = previous_summary_before_scan
if not self.quiet_mode:
logger.warning(message, n_skipped)
@@ -5023,12 +5015,9 @@ Write only the summary body. Do not include any preamble or prefix."""
"""
# A detached stale attempt must not even reset per-call state the fallback owns. Staleness that
# arises mid-compress is caught by the write-point gates below; this covers stale-at-entry.
- from agent.conversation_compression import (
- _COMPRESSOR_ATTEMPT_GENERATION,
- _working_attempt_is_current,
- )
- if not _working_attempt_is_current(self, _COMPRESSOR_ATTEMPT_GENERATION.get()):
- raise AuxiliaryExplicitCancellation()
+ from agent.conversation_compression import _raise_if_stale_attempt
+
+ _raise_if_stale_attempt(self)
telemetry = self._begin_compress_attempt(current_tokens, force)
n_messages = len(messages)
# Only need head + 3 tail messages minimum (token budget decides the real tail size)
@@ -5085,12 +5074,9 @@ Write only the summary body. Do not include any preamble or prefix."""
# Choke point for staleness that arose during phases 1-2: everything below writes shared state
# (feasibility counters, fallback diagnostics, finalize's cursor/rearm resets), and the inner
# _summarize_window/_generate_summary gates cover staleness arising during the LLM call itself.
- from agent.conversation_compression import (
- _COMPRESSOR_ATTEMPT_GENERATION,
- _working_attempt_is_current,
- )
- if not _working_attempt_is_current(self, _COMPRESSOR_ATTEMPT_GENERATION.get()):
- raise AuxiliaryExplicitCancellation()
+ from agent.conversation_compression import _raise_if_stale_attempt
+
+ _raise_if_stale_attempt(self)
feasibility_skip = not force and self._feasibility_skip(telemetry, turns_to_summarize, compress_start, compress_end)
summary = None # feasibility skip: no LLM call; Phase 4 inserts the deterministic fallback
if not feasibility_skip:
diff --git a/agent/context_compressor_summary.py b/agent/context_compressor_summary.py
index 49a978a1e06..b0e38f1ded0 100644
--- a/agent/context_compressor_summary.py
+++ b/agent/context_compressor_summary.py
@@ -38,12 +38,9 @@ class SummaryDispatchMixin:
if take_deterministic_summary_pin():
# A detached stale attempt must not stamp error state or mutate the shared telemetry dict
# the fallback owns; unwind as a cancellation before any write lands.
- from agent.conversation_compression import (
- _COMPRESSOR_ATTEMPT_GENERATION,
- _working_attempt_is_current,
- )
- if not _working_attempt_is_current(self, _COMPRESSOR_ATTEMPT_GENERATION.get()):
- raise AuxiliaryExplicitCancellation()
+ from agent.conversation_compression import _raise_if_stale_attempt
+
+ _raise_if_stale_attempt(self)
# Surfaces through the fallback summary's reason line and the host's one-shot user warning.
self._last_summary_error = (
"summary model stalled on every route; deterministic fallback summary inserted"
@@ -68,11 +65,9 @@ class SummaryDispatchMixin:
# The caller's own generation rides a ContextVar because shared compressor attributes can
# only name the current owner, never the caller's attempt. Working-attempt comparison (not
# the entry generation) so a no-op claim does not suppress the owning attempt's rollback.
- from agent.conversation_compression import (
- _COMPRESSOR_ATTEMPT_GENERATION,
- _working_attempt_is_current,
- )
- if _working_attempt_is_current(self, _COMPRESSOR_ATTEMPT_GENERATION.get()):
+ from agent.conversation_compression import _caller_attempt_is_current
+
+ if _caller_attempt_is_current(self):
self._previous_summary = scan.previous_summary_before
self._summary_has_user_turn = scan.has_user_turn_before
raise
diff --git a/agent/conversation_compression.py b/agent/conversation_compression.py
index d136f867697..f424327e5fa 100644
--- a/agent/conversation_compression.py
+++ b/agent/conversation_compression.py
@@ -226,11 +226,28 @@ _COMPRESSOR_ATTEMPT_GENERATION: contextvars.ContextVar[Any] = contextvars.Contex
)
+def _compressor_attempt_serial_lock(compressor: Any) -> Any:
+ """Per-compressor lock serializing the durable cooldown rollback against claims. The process-wide
+ claim lock must stay cheap (every compressor in a gateway shares it), so the slow SQLite write in
+ ``_restore_compressor_attempt_state`` is fenced by THIS lock instead; ``_claim_compressor_attempt``
+ takes it first so a claim on that compressor waits for the restore while other compressors proceed.
+ A slotted/frozen compressor that cannot hold the attribute gets a no-op (its guard is off anyway)."""
+ with _COMPRESSOR_ATTEMPT_LOCK:
+ lock = getattr(compressor, "_compression_attempt_serial_lock", None)
+ if lock is None:
+ lock = threading.Lock()
+ try:
+ compressor._compression_attempt_serial_lock = lock
+ except Exception:
+ return contextlib.nullcontext()
+ return lock
+
+
def _claim_compressor_attempt(compressor: Any) -> int:
"""Claim the compressor for a new attempt; return its monotonic generation id.
Restores or cancelled-check mutations stamped with an OLDER generation no-op, so a detached late attempt
cannot clobber its successor's state."""
- with _COMPRESSOR_ATTEMPT_LOCK:
+ with _compressor_attempt_serial_lock(compressor), _COMPRESSOR_ATTEMPT_LOCK:
generation = int(getattr(compressor, "_compression_attempt_generation", 0) or 0) + 1
try:
compressor._compression_attempt_generation = generation
@@ -262,6 +279,19 @@ def _mark_compressor_working_attempt(compressor: Any, generation: int) -> None:
compressor._compression_working_attempt_generation = generation
+def _raise_if_stale_attempt(compressor: Any) -> None:
+ """Unwind the CALLING attempt (its generation rides the ContextVar) as a cancellation when a newer
+ attempt has since begun summary work on *compressor*, so none of the shared-state writes that
+ follow the call site can land."""
+ if not _caller_attempt_is_current(compressor):
+ raise AuxiliaryExplicitCancellation()
+
+
+def _caller_attempt_is_current(compressor: Any) -> bool:
+ """Working-attempt check for the calling attempt's own generation (ContextVar; None → unguarded)."""
+ return _working_attempt_is_current(compressor, _COMPRESSOR_ATTEMPT_GENERATION.get())
+
+
def _working_attempt_is_current(compressor: Any, generation: Any) -> bool:
"""True when *generation* is still the last attempt that began summary work.
@@ -345,14 +375,17 @@ def _restore_compressor_attempt_state(
)
return
restored = copy.deepcopy(snapshot)
- # Re-validate under the claim lock AND run the durable rollback inside it: the slow DB
+ # Re-validate AND run the durable rollback under this compressor's serial lock: the slow DB
# write used to sit between the first ownership check and this re-check, so a fallback
# claiming mid-restore could have its freshly written cooldown row overwritten by this
- # attempt's stale snapshot row. Holding the lock across the durable write serializes
- # it against _claim_compressor_attempt. The row still lands BEFORE the in-memory
- # restore so the next refresh cannot overwrite the rollback.
- with _COMPRESSOR_ATTEMPT_LOCK:
- if attempt_generation and int(getattr(compressor, "_compression_attempt_generation", 0) or 0) != attempt_generation:
+ # attempt's stale snapshot row. _claim_compressor_attempt takes the same per-compressor
+ # lock, so the write is serialized against claims on THIS compressor without stalling
+ # every other compressor behind the process-wide claim lock. The row still lands BEFORE
+ # the in-memory restore so the next refresh cannot overwrite the rollback.
+ with _compressor_attempt_serial_lock(compressor):
+ with _COMPRESSOR_ATTEMPT_LOCK:
+ lost = attempt_generation and int(getattr(compressor, "_compression_attempt_generation", 0) or 0) != attempt_generation
+ if lost:
logger.warning(
"Skipping stale compressor attempt-state restore at write "
"time: attempt generation %s lost the compressor mid-restore.", attempt_generation,
diff --git a/tests/agent/test_compression_attempt_ownership.py b/tests/agent/test_compression_attempt_ownership.py
index b86d12819a8..4d6a68d04d1 100644
--- a/tests/agent/test_compression_attempt_ownership.py
+++ b/tests/agent/test_compression_attempt_ownership.py
@@ -244,21 +244,6 @@ class TestMidRestoreClaimRace:
assert compressor._previous_summary == "FALLBACK STATE"
-def _run_as_attempt(generation, fn):
- """Run ``fn`` with the attempt-generation ContextVar bound, exactly as
- ``_run_summary_dispatch`` does around ``compress_fn``. Tolerates the var
- being absent so the tests still exercise behavior on pre-fix revisions."""
- from agent import conversation_compression as _cc
-
- var = getattr(_cc, "_COMPRESSOR_ATTEMPT_GENERATION", None)
- token = var.set(generation) if var is not None else None
- try:
- return fn()
- finally:
- if token is not None:
- var.reset(token)
-
-
class TestStaleAttemptEndToEnd:
"""E2E: two real attempts through ``_run_summary_dispatch`` on a shared
real ``ContextCompressor``. The detached primary's late completion must
@@ -428,8 +413,9 @@ class TestDurableRollbackAtomicity:
"""Gap: the durable cooldown DB write ran BETWEEN the two ownership
checks, so a fallback claiming mid-restore had its cooldown row
overwritten by the primary's stale snapshot row. The write now sits
- inside the claim-lock critical section: durable row + in-memory
- restore are an atomic pair against ``_claim_compressor_attempt``."""
+ under the compressor's own serial lock, which ``_claim_compressor_attempt``
+ takes too: durable row + in-memory restore are an atomic pair against
+ claims on THAT compressor, while other compressors' claims never wait."""
def test_durable_write_and_restore_are_atomic_against_claims(self):
import threading
@@ -475,3 +461,37 @@ class TestDurableRollbackAtomicity:
assert written == ["s1"]
assert compressor._previous_summary == "primary-era"
assert claims == [2]
+
+ def test_durable_write_does_not_stall_other_compressors(self):
+ import threading
+ import time
+
+ compressor, other = _compressor(), _compressor()
+ gen = _claim_compressor_attempt(compressor)
+ snapshot = {
+ "_summary_failure_cooldown_until": time.monotonic() + 100.0,
+ "_previous_summary": "primary-era",
+ "_cooldown_persist_failed": False,
+ }
+ other_claims_during_write = []
+
+ class _DB:
+ def record_compression_failure_cooldown(self, sid, until, err):
+ # A busy state.db write on THIS compressor must not block a claim on an
+ # unrelated compressor (gateway: N sessions share the module lock).
+ t = threading.Thread(
+ target=lambda: other_claims_during_write.append(_claim_compressor_attempt(other)),
+ daemon=True,
+ )
+ t.start()
+ t.join(timeout=2.0)
+
+ compressor._session_db = _DB()
+ compressor._session_id = "s1"
+
+ _restore_compressor_attempt_state(
+ compressor, snapshot, durable_cooldown_authoritative=None, attempt_generation=gen,
+ )
+
+ assert other_claims_during_write == [1]
+ assert compressor._previous_summary == "primary-era"