Skip to content

The agent that grows with you

fix(process): a reconcile during the reader's final drain no longer truncates the output

John Paul Soliva35076536905a
diff --git a/tests/tools/test_process_registry_list_exit.py b/tests/tools/test_process_registry_list_exit.py
index 0d5d7243a02..45e79e25355 100644
--- a/tests/tools/test_process_registry_list_exit.py
+++ b/tests/tools/test_process_registry_list_exit.py
@@ -51,6 +51,42 @@ def test_list_leaves_live_reader_as_completion_owner():
)
+def test_poll_during_the_readers_final_drain_keeps_the_whole_output(tmp_path):
+ """A child that ends on a burst exits with its tail still in the pipe. A poll landing while the reader
+ is behind must report, and leave in the completion, the whole output — not the chunk read so far."""
+ import threading
+
+ import tools.process_registry as module
+
+ module._SYSTEMD_SCOPE_AVAILABLE = False
+ registry = module.ProcessRegistry()
+ stalled, release = threading.Event(), threading.Event()
+
+ def slow_sink(_session, _chunk): # a live-output consumer that falls behind for a moment
+ if not stalled.is_set():
+ stalled.set()
+ release.wait(10)
+
+ registry.on_output = slow_sink
+ burst = "import sys; sys.stdout.write('x' * 99 + '\\n'); sys.stdout.write(('y' * 99 + '\\n') * 100 + 'FINAL\\n')"
+ session = registry.spawn_local(f"{shlex.quote(sys.executable)} -c {shlex.quote(burst)}", cwd=str(tmp_path))
+ session.notify_on_complete = True
+ try:
+ assert stalled.wait(10)
+ assert session.process.wait(timeout=10) == 0
+ threading.Timer(0.3, release.set).start()
+ polled = registry.poll(session.id)
+ assert session._completion_event.wait(10)
+ assert polled["status"] == "exited"
+ assert polled["output_preview"].rstrip().endswith("FINAL"), polled["output_preview"][-80:]
+ event = registry.completion_queue.get(timeout=2)
+ assert event["output"].rstrip().endswith("FINAL"), event["output"][-80:]
+ finally:
+ release.set()
+ registry.kill_all(source="test")
+
+
@pytest.mark.platforms("linux")
def test_list_reconciles_real_exit_without_consuming_owned_result(tmp_path):
# A disposable subreaper owns even the orphaned writer; no global pytest
diff --git a/tools/process_registry.py b/tools/process_registry.py
index d5bdd5e6595..da31d829ec4 100644
--- a/tools/process_registry.py
+++ b/tools/process_registry.py
@@ -82,6 +82,11 @@ WATCH_LIFETIME_MAX_HITS = 8
HEARTBEAT_MIN_SECONDS = 60
HEARTBEAT_OUTPUT_CHARS = 2000
HEARTBEAT_TICK_SECONDS = 5
+# Reader final drain after a reconcile saw the direct child exit: the exited child's unread tail is at
+# most one pipe buffer (Linux pipe-max-size default 1 MiB), and the reader publishes within one select
+# interval plus that drain.
+_FINAL_DRAIN_MAX_CHARS = 1 << 20
+_READER_FINAL_DRAIN_WAIT_SECONDS = 1.0
# Global circuit breaker across all sessions so concurrent siblings can't collectively
# flood the user even when each is under its own cap.
WATCH_GLOBAL_MAX_PER_WINDOW = 15
@@ -1545,10 +1550,14 @@ class ProcessRegistry(ProcessCheckpointMixin):
import select as _select
session._reader_selectable = True
idle_after_exit = 0
+ drained_after_request = 0
while True:
if fd is not None:
try:
- ready, _, _ = _select.select([fd], [], [], 0.2)
+ # Once a finish is requested, read only what is already buffered: the exited
+ # child's tail, never an orphaned grandchild's future writes.
+ wait_s = 0 if session._reader_finish_requested.is_set() else 0.2
+ ready, _, _ = _select.select([fd], [], [], wait_s)
except (ValueError, OSError):
break # fd already closed
if not ready:
@@ -1569,7 +1578,11 @@ class ProcessRegistry(ProcessCheckpointMixin):
if chunk:
_append_chunk(chunk)
if session._reader_finish_requested.is_set():
- break
+ # A single chunk is not the tail: the child can exit with a whole pipe buffer
+ # unread. The cap only stops a grandchild that never lets the pipe go empty.
+ drained_after_request += len(chunk)
+ if drained_after_request >= _FINAL_DRAIN_MAX_CHARS:
+ break
idle_after_exit = 0
except Exception as e:
logger.debug("Process stdout reader ended: %s", e)
@@ -2138,8 +2151,12 @@ class ProcessRegistry(ProcessCheckpointMixin):
# finish avoids a competing TextIOWrapper read here racing the
# reader, publishing an empty owner-stamped result, then closing
# the pipe before the buffered tail is ingested. It wakes within
- # the reader's bounded select interval (or after one final chunk).
+ # the reader's bounded select interval and drains what is buffered.
session._reader_finish_requested.set()
+ # Flipping ``exited`` before that drain lands would hand poll()/wait() a truncated
+ # snapshot (and wait() marks it consumed), so give the reader a moment to publish.
+ if session._completion_event.wait(_READER_FINAL_DRAIN_WAIT_SECONDS):
+ return
with session._lock:
session.mark_exited(rc)
logger.info(