The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(compression): let prompt reading in a waited-on pass extend the deadline
kshitijk4poorcc940eeb6a95
diff --git a/agent/prepared_compaction.py b/agent/prepared_compaction.pyindex 6aa1e7f3e9b..661e241af1a 100644--- a/agent/prepared_compaction.py+++ b/agent/prepared_compaction.py@@ -19,8 +19,9 @@ exactly as without the flag.When no completed candidate fits but a running pass would, compaction waits forthat pass instead of starting the same summary over: the pass's streamed-progress feeds the waiting compaction's progress hook, so the host's idle-watchdog sees a live summary exactly as it would inline, and the wait ends at+progress and local prompt reading feed the waiting compaction's hooks, so the+host's idle watchdog and deadline extension see a live summary exactly as they+would inline, and the wait ends atthe host's deadline (the compression aux timeout without one) or oncancellation. A pass that is not waited on loses the right to publish oncecompaction runs.@@ -79,18 +80,24 @@ class PreparedSummary(_Window):class _PendingPass:"""The one running pass allowed to publish: its planned window, a completion event, and the- progress hook of a compaction waiting on it."""+ progress and prompt-reading hooks of a compaction waiting on it."""def __init__(self, window: _Window) -> None:self.window = windowself.done = threading.Event()self.on_progress: Optional[Callable[[], None]] = None+ self.on_reading: Optional[Callable[[float], None]] = Nonedef touch(self) -> None:hook = self.on_progressif hook is not None:hook()+ def read(self, seconds: float) -> None:+ hook = self.on_reading+ if hook is not None:+ hook(seconds)+def _text_of(content: Any) -> str:if content is None:@@ -228,26 +235,33 @@ class PreparedCompaction:def _await(self, pending: _PendingPass) -> Optional[PreparedSummary]:"""Wait on the compacting thread for *pending* and return what it published; None at the host'sdeadline (the compression aux timeout without one) or when the host cancels. Meanwhile the pass's- streamed progress feeds this thread's aux progress hook, so the host's idle watchdog sees a live- summary exactly as it would inline."""+ streamed progress and local prompt reading feed this thread's hooks, so the host's idle watchdog+ and deadline extension see a live summary exactly as they would inline; the deadline is re-read+ on every poll because prompt reading pushes it back."""from agent.auxiliary_client import (_aux_progress, _capture_aux_cancel_check, _captured_aux_cancel_requested, _current_aux_stream_deadline,_effective_aux_timeout,)+ from agent.local_prompt_progress import current_prompt_reading_hookcancel_check = _capture_aux_cancel_check()- deadline = _current_aux_stream_deadline() or time.monotonic() + float(_effective_aux_timeout("compression", None))+ fallback = time.monotonic() + float(_effective_aux_timeout("compression", None))pending.on_progress = getattr(_aux_progress, "hook", None)+ pending.on_reading = current_prompt_reading_hook()logger.info("prepared compaction: waiting for the running pass window=%d-%d",pending.window.compress_start, pending.window.compress_end,)try:- while not pending.done.wait(max(0.0, min(_WAIT_POLL_SECONDS, deadline - time.monotonic()))):- if time.monotonic() >= deadline or (cancel_check is not None and _captured_aux_cancel_requested(cancel_check)):+ while not pending.done.wait(+ max(0.0, min(_WAIT_POLL_SECONDS, (_current_aux_stream_deadline() or fallback) - time.monotonic())),+ ):+ if time.monotonic() >= (_current_aux_stream_deadline() or fallback) or (+ cancel_check is not None and _captured_aux_cancel_requested(cancel_check)+ ):return Nonefinally:- pending.on_progress = None+ pending.on_progress = pending.on_reading = Nonewith self._lock:entry, self._entry = self._entry, Nonereturn entry if entry is not None and entry.fingerprint == pending.window.fingerprint else None@@ -341,6 +355,7 @@ class PreparedCompaction:extend: Optional[PreparedSummary],) -> None:from agent.auxiliary_client import aux_progress_hook+ from agent.local_prompt_progress import prompt_reading_hookfrom agent.thread_scoped_output import thread_scoped_silencestart, end, window_fingerprint = token.window.compress_start, token.window.compress_end, token.window.fingerprint@@ -351,7 +366,7 @@ class PreparedCompaction:"prepared compaction: pass started origin=%s window=%d-%d turns=%d extends=%s",origin, start, end, len(turns), extend is not None,)- with thread_scoped_silence(), aux_progress_hook(token.touch):+ with thread_scoped_silence(), aux_progress_hook(token.touch), prompt_reading_hook(token.read):summary = worker._generate_summary(turns, focus_topic=focus)if summary:entry = PreparedSummary(start, end, window_fingerprint, summary, worker._previous_summary)diff --git a/tests/agent/test_prepared_compaction.py b/tests/agent/test_prepared_compaction.pyindex 98e09c013a1..8ee0d2d9914 100644--- a/tests/agent/test_prepared_compaction.py+++ b/tests/agent/test_prepared_compaction.py@@ -27,6 +27,7 @@ from agent import prepared_compaction as pcfrom agent.context_compressor import COMPRESSED_SUMMARY_METADATA_KEY, ContextCompressorfrom agent.model_metadata import estimate_messages_tokens_roughfrom agent.prepared_compaction import PreparedCompaction+from tests.waiting import wait_untilclass _StubCompressor(ContextCompressor):@@ -36,6 +37,13 @@ class _StubCompressor(ContextCompressor):from hermes_constants import get_hermes_homeworker = threading.current_thread().name == "compaction-prepare"+ if worker and self.read_seconds:+ from agent.local_prompt_progress import current_prompt_reading_hook++ pending = self.prepared_compaction._pending+ assert _wait_until(lambda: pending.on_reading is not None), "compaction never started waiting"+ current_prompt_reading_hook()(self.read_seconds) # a local server reading the prompt+ self.after_read()if worker and self.gate is not None:assert self.gate.wait(5.0), "pass never released"if worker and self.stream_progress:@@ -61,7 +69,7 @@ def _compressor(*, enabled: bool = True, session_id: str = "S1") -> _StubComprescc.context_length = 40960cc.threshold_tokens = 20000cc.tail_token_budget = 2500- cc.calls, cc.gate, cc.stream_progress = [], None, False+ cc.calls, cc.gate, cc.stream_progress, cc.read_seconds, cc.after_read = [], None, False, 0.0, Nonecc._session_id = session_idif enabled:cc.prepared_compaction = PreparedCompaction()@@ -349,7 +357,9 @@ def test_compaction_waits_for_a_running_pass_and_forwards_its_progress():running = pc.maybe_prepare(_agent(cc), msgs, origin="test")assert running is not Nonehost_progress = []- threading.Timer(0.3, cc.gate.set).start()+ pending = cc.prepared_compaction._pending+ # Release the pass only once the compaction is waiting on it.+ threading.Thread(target=lambda: _wait_until(lambda: pending.on_progress is not None) and cc.gate.set()).start()with aux_progress_hook(lambda: host_progress.append(threading.current_thread().name)):compressed = cc.compress(msgs, current_tokens=cc.threshold_tokens + 1)running.join(5.0)@@ -379,6 +389,28 @@ def test_wait_ends_at_the_host_deadline_then_summarises_inline_and_the_pass_cannassert cc.prepared_compaction._entry is None+def test_prompt_reading_in_the_pass_extends_the_deadline_the_wait_honours():+ """A local server still reading the pass's prompt pushes the host deadline back exactly as it would+ inline, and the wait follows the live deadline instead of the one it started with."""+ from agent.auxiliary_client import aux_stream_deadline+ from agent.local_prompt_progress import prompt_reading_hook++ cc = _compressor()+ deadline = [time.monotonic() + 1.0]+ initial = deadline[0]+ # The pass finishes only after the deadline the wait started with has passed.+ cc.read_seconds, cc.after_read = 5.0, lambda: wait_until(lambda: time.monotonic() > initial + 0.3)+ msgs = _messages(30)+ running = pc.maybe_prepare(_agent(cc), msgs, origin="test")+ assert running is not None+ with aux_stream_deadline(lambda: deadline[0]), prompt_reading_hook(lambda s: deadline.__setitem__(0, deadline[0] + s)):+ compressed = cc.compress(msgs, current_tokens=cc.threshold_tokens + 1)+ running.join(5.0)++ assert [c["worker"] for c in cc.calls] == [True], "the extended wait outlived the initial deadline"+ assert "Summary v1" in _summary_row(compressed)["content"]++@pytest.mark.parametrize("boundary", ["reset", "end", "rebind"])def test_session_boundary_discards_candidate_and_running_pass(boundary):cc = _compressor()diff --git a/website/docs/developer-guide/context-compression-and-caching.md b/website/docs/developer-guide/context-compression-and-caching.mdindex 8a4ce13d024..1c5c0733480 100644--- a/website/docs/developer-guide/context-compression-and-caching.md+++ b/website/docs/developer-guide/context-compression-and-caching.md@@ -694,7 +694,8 @@ Phase 4 assembly.When no completed candidate fits but the pass still running would, compaction waits for that passinstead of writing the same summary again. Each streamed chunk of the pass touches the waitingcompaction's progress hook, so the host's idle watchdog treats the wait like an inline summary-stream. The wait ends at the host's deadline (the compression aux timeout when there is none) or on+stream, and time a llama.cpp server spends reading the pass's prompt pushes the host's deadline back+as it would inline. The wait ends at the host's deadline (the compression aux timeout when there is none) or oncancellation, and compaction then summarizes inline.Everything else runs inline exactly as without the flag: no candidate, a candidate or running pass