Skip to content

The agent that grows with you

fix(agent): make compression stall fallback deterministic

Mark DiPietroaabb7a609d13
diff --git a/agent/conversation_compression.py b/agent/conversation_compression.py
index 34c0eac45c2..ef84032aadb 100644
--- a/agent/conversation_compression.py
+++ b/agent/conversation_compression.py
@@ -1256,6 +1256,29 @@ def run_compress_context_with_progress_timeout(
)
if settled:
handled_exit = True
+ # The deadline is visible to the worker as well as the host. A cooperative summary call can
+ # observe it, unwind, and return the unchanged snapshot just BEFORE future.result() times out.
+ # Treat that settled no-op exactly like the host-side stall path; otherwise whether the
+ # deterministic fallback runs depends on a thread-scheduling race at the deadline.
+ result_messages = result[0] if isinstance(result, tuple) and result else None
+ if stall_fallback and fence.deadline_exceeded and result_messages is messages:
+ if on_timeout_cause is not None:
+ with _swallow('compress_context timeout-cause callback failed', exc_info=True):
+ on_timeout_cause(True, fence.progress_observed)
+ recovered = _retry_compression_on_fallback_chain(
+ worker=fallback_worker or worker, messages=messages,
+ system_prompt_fallback=system_prompt_fallback,
+ idle_timeout_seconds=idle, total_ceiling_seconds=ceiling,
+ on_commit_overrun=on_commit_overrun, on_timeout_cause=on_timeout_cause,
+ telemetry_agent=telemetry_agent, new_fence=new_fence,
+ escalate_deterministic=escalate_deterministic,
+ )
+ if recovered is not None:
+ return recovered
+ if on_timeout is not None:
+ waited = time.monotonic() - wait_started
+ with _swallow('compress_context timeout callback failed', exc_info=True):
+ on_timeout(idle, waited, fence.seconds_since_progress())
return result
# F6: a not-yet-started future must not linger as a stale queued job.
@@ -1282,6 +1305,27 @@ def run_compress_context_with_progress_timeout(
future, ceiling=ceiling, wait_started=wait_started, on_commit_overrun=on_commit_overrun
)
handled_exit = True
+ # The cancelled worker can race the host into its commit section while unwinding a stalled
+ # summary. When that commit is only the unchanged snapshot, returning it here skips the
+ # stall-fallback ladder entirely (the over-window first-stall test then flakes). The worker is
+ # settled and its lease is free at this point, so retry exactly as the pre-commit cancel path
+ # does. A real compression result remains authoritative and returns immediately.
+ result_messages = result[0] if isinstance(result, tuple) and result else None
+ if stall_fallback and result_messages is messages:
+ recovered = _retry_compression_on_fallback_chain(
+ worker=fallback_worker or worker, messages=messages,
+ system_prompt_fallback=system_prompt_fallback,
+ idle_timeout_seconds=idle, total_ceiling_seconds=ceiling,
+ on_commit_overrun=on_commit_overrun, on_timeout_cause=on_timeout_cause,
+ telemetry_agent=telemetry_agent, new_fence=new_fence,
+ escalate_deterministic=escalate_deterministic,
+ )
+ if recovered is not None:
+ return recovered
+ if on_timeout is not None:
+ waited = time.monotonic() - wait_started
+ with _swallow('compress_context timeout callback failed', exc_info=True):
+ on_timeout(idle, waited, fence.seconds_since_progress())
return result
# Idle-timeout: cancel won pre-commit. Also free the worker's durable lease via
diff --git a/tests/agent/test_compression_attempt_lifecycle.py b/tests/agent/test_compression_attempt_lifecycle.py
index ff90698235d..cbc042dbd94 100644
--- a/tests/agent/test_compression_attempt_lifecycle.py
+++ b/tests/agent/test_compression_attempt_lifecycle.py
@@ -26,6 +26,7 @@ import time
from pathlib import Path
from unittest.mock import patch
+import agent.conversation_compression as cc
from agent.conversation_compression import (
CompressionCommitFence,
@@ -126,12 +127,13 @@ class TestWorkerTeardownOnCeiling:
does NOT fire while the worker is alive (no overlap window)."""
original = [{"role": "user", "content": "keep"}]
release = threading.Event()
+ worker_started = threading.Event()
worker_finished = threading.Event()
lock_released: list[float] = []
def stuck_worker(fence: CompressionCommitFence):
- # Continuous progress so only the TOTAL ceiling can expire
- # (the #97488 'last progress 0.0s ago' shape).
+ fence.touch_progress()
+ worker_started.set()
while not release.wait(timeout=0.02):
fence.touch_progress()
worker_finished.set()
@@ -146,26 +148,37 @@ class TestWorkerTeardownOnCeiling:
fence.register_cancelled_lock_release(
lambda: lock_released.append(time.monotonic())
)
- msgs, prompt = run_compress_context_with_progress_timeout(
- worker=stuck_worker,
- messages=original,
- system_prompt_fallback="fallback",
- idle_timeout_seconds=0.1,
- total_ceiling_seconds=0.3,
- fence=fence,
- stall_fallback=False,
- )
- # Precondition: the worker is genuinely still running.
- assert not worker_finished.is_set()
- assert msgs is original and prompt == "fallback"
- # Total-ceiling path: lease retained until the worker exits, so no
- # new attempt can overlap the unchanged session.
- assert not lock_released, (
- "durable lease released while the timed-out worker was still "
- "alive — overlap window reopened (#97488)"
- )
- release.set()
- assert worker_finished.wait(timeout=2)
+ real_await = cc._await_worker_within_budget
+
+ def await_after_worker_start(future, worker_fence, **kwargs):
+ assert worker_started.wait(timeout=1.0)
+ return real_await(future, worker_fence, **kwargs)
+
+ try:
+ with patch.object(
+ cc,
+ "_await_worker_within_budget",
+ side_effect=await_after_worker_start,
+ ):
+ msgs, prompt = run_compress_context_with_progress_timeout(
+ worker=stuck_worker,
+ messages=original,
+ system_prompt_fallback="fallback",
+ idle_timeout_seconds=2.0,
+ total_ceiling_seconds=0.3,
+ fence=fence,
+ stall_fallback=False,
+ )
+ assert not worker_finished.is_set()
+ assert msgs is original and prompt == "fallback"
+ assert not lock_released, (
+ "durable lease released while the timed-out worker was still "
+ "alive — overlap window reopened (#97488)"
+ )
+ finally:
+ release.set()
+
+ assert worker_finished.wait(timeout=1.0)
# Late result was fence-poisoned, never adopted.
assert msgs == [{"role": "user", "content": "keep"}]
diff --git a/tests/agent/test_compression_stall_deterministic_fallback.py b/tests/agent/test_compression_stall_deterministic_fallback.py
index 71895bfd64a..ab1d6fd889d 100644
--- a/tests/agent/test_compression_stall_deterministic_fallback.py
+++ b/tests/agent/test_compression_stall_deterministic_fallback.py
@@ -175,6 +175,108 @@ def test_fence_level_retry_ladder_is_unchanged_without_a_prior_timeout():
release.set()
+def test_deadline_observed_by_worker_still_runs_first_stall_fallback():
+ """A cooperative worker can return its no-op result at the same deadline the host is waiting on.
+ That settled result must not win the race and bypass the deterministic over-window fallback."""
+ original = [{"role": "user", "content": "keep-me"}]
+ recovered = [{"role": "assistant", "content": "compressed"}]
+ attempts = []
+ timeout_causes = []
+ timeout_callbacks = []
+
+ def primary_worker(fence: CompressionCommitFence):
+ attempts.append("primary")
+ while not fence.deadline_exceeded:
+ time.sleep(0.001)
+ return original, "unchanged"
+
+ def fallback_worker(_fence: CompressionCommitFence):
+ attempts.append("fallback")
+ return recovered, "compressed-prompt"
+
+ with patch("agent.auxiliary_client._get_auxiliary_task_config", return_value={"fallback_chain": []}):
+ msgs, prompt = run_compress_context_with_progress_timeout(
+ worker=primary_worker, fallback_worker=fallback_worker, messages=original,
+ system_prompt_fallback="degraded-prompt", idle_timeout_seconds=0.05,
+ total_ceiling_seconds=2.0, request_exceeds_window=True,
+ on_timeout_cause=lambda *cause: timeout_causes.append(cause),
+ on_timeout=lambda *args: timeout_callbacks.append(args),
+ )
+
+ assert msgs is recovered and prompt == "compressed-prompt"
+ assert attempts == ["primary", "fallback"]
+ assert timeout_causes == [(True, False)]
+ assert timeout_callbacks == []
+
+
+def test_admitted_unchanged_commit_at_deadline_retries_without_overlap():
+ """If a worker enters its commit section at the deadline, the host must wait for that commit to
+ settle before minting a fresh retry fence. An unchanged commit is still a stalled attempt, not a
+ successful compression, so an over-window request must take the deterministic fallback rung."""
+ original = [{"role": "user", "content": "keep-me"}]
+ recovered = [{"role": "assistant", "content": "compressed"}]
+ primary_fence = CompressionCommitFence()
+ commit_started = threading.Event()
+ primary_finished = threading.Event()
+ release_commit = threading.Event()
+ attempts = []
+ timeout_causes = []
+ timeout_callbacks = []
+ retry_fences = []
+ real_await = cc._await_worker_within_budget
+
+ def primary_worker(fence: CompressionCommitFence):
+ attempts.append(("primary", fence))
+ assert fence.begin_commit()
+ commit_started.set()
+ try:
+ assert release_commit.wait(timeout=2)
+ return original, "unchanged"
+ finally:
+ fence.finish_commit()
+ primary_finished.set()
+
+ def fallback_worker(fence: CompressionCommitFence):
+ assert primary_finished.is_set(), "retry overlapped the admitted primary commit"
+ attempts.append(("fallback", fence))
+ return recovered, "compressed-prompt"
+
+ def await_at_deadline(future, fence, *, idle, ceiling, wait_started):
+ if fence is not primary_fence:
+ return real_await(
+ future, fence, idle=idle, ceiling=ceiling, wait_started=wait_started
+ )
+ assert commit_started.wait(timeout=1)
+ # Hold the admitted commit through the deadline, then let it finish while
+ # _await_in_flight_commit owns the host-side wait.
+ time.sleep(ceiling + 0.01)
+ threading.Timer(0.02, release_commit.set).start()
+ return False, None
+
+ def new_fence():
+ fence = CompressionCommitFence()
+ retry_fences.append(fence)
+ return fence
+
+ with patch.object(cc, "_await_worker_within_budget", side_effect=await_at_deadline), patch(
+ "agent.auxiliary_client._get_auxiliary_task_config", return_value={"fallback_chain": []}
+ ):
+ msgs, prompt = run_compress_context_with_progress_timeout(
+ worker=primary_worker, fallback_worker=fallback_worker, messages=original,
+ system_prompt_fallback="degraded-prompt", idle_timeout_seconds=0.05,
+ total_ceiling_seconds=0.05, request_exceeds_window=True, fence=primary_fence,
+ new_fence=new_fence, on_timeout_cause=lambda *cause: timeout_causes.append(cause),
+ on_timeout=lambda *args: timeout_callbacks.append(args),
+ )
+
+ assert msgs is recovered and prompt == "compressed-prompt"
+ assert primary_finished.is_set()
+ assert retry_fences and retry_fences[0] is not primary_fence
+ assert attempts == [("primary", primary_fence), ("fallback", retry_fences[0])]
+ assert timeout_causes == [(True, False)]
+ assert timeout_callbacks == []
+
+
def test_over_window_request_commits_the_deterministic_fallback_on_the_first_stall(tmp_path, fast_timeouts):
"""A request above the model's context window cannot be sent unchanged, so waiting for a SECOND stall
(which on the messaging gateway never comes — the first one auto-reset the session) is a dead end: