From 3b649d6fe937c2c1b6fc51f2bf3cee543c44999a Mon Sep 17 00:00:00 2001 From: eowca <4008965+eowca@users.noreply.github.com> Date: Thu, 26 Nov 2026 03:35:21 +0100 Subject: [PATCH 1/3] Stream local check output into a bounded diagnostic tail Co-Authored-By: Codex --- docs/ARCHITECTURE.md | 4 +-- src/loopzero/_proc.py | 52 +++++++++++++++++++++++++++++++++++- src/loopzero/sandbox.py | 1 + tests/test_sandbox.py | 59 ++++++++++++++++++++++++++++++----------- 4 files changed, 97 insertions(+), 19 deletions(-) diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index bfe286f2..0d0471bc 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -76,8 +76,8 @@ The [CLI](../src/loopzero/cli.py) implements the contract's prepares recognized uv dependency groups offline in that sandbox and prints progress before each command, metadata-only stage heartbeats every 30 seconds (including silent children), and exit code/duration immediately after each stage. - Heartbeats stop on completion or cancellation and never supply a verdict; child - streams remain captured for the existing final report and failing output tail. + Heartbeats stop on completion or cancellation and never supply a verdict. + Local stages drain merged child output and retain a bounded diagnostic tail. Trusted-base commands remain authoritative; stale task trees need integration only when prerequisites are missing, preserving source-preserving queue eligibility for behind branches. diff --git a/src/loopzero/_proc.py b/src/loopzero/_proc.py index 31e63dfa..31b3dfe3 100644 --- a/src/loopzero/_proc.py +++ b/src/loopzero/_proc.py @@ -2,7 +2,10 @@ from __future__ import annotations +import codecs +import io import os +import selectors import signal import subprocess import time @@ -55,6 +58,45 @@ def build_env( return env +def _read_output_tail(proc: subprocess.Popen[str], limit: int, timeout: float) -> str: + stream = proc.stdout + assert stream is not None + decode = io.IncrementalNewlineDecoder( + codecs.getincrementaldecoder(stream.encoding)(errors="replace"), translate=True, + ).decode + deadline = time.monotonic() + timeout + suffix = "" + newlines = 0 + + def append(chunk: str) -> None: + nonlocal suffix, newlines + content = chunk.rstrip("\n") + if content: + suffix = (suffix + "\n" * newlines + content)[-limit:] + newlines = 0 + newlines = min(limit, newlines + len(chunk) - len(content)) + + try: + with selectors.DefaultSelector() as selector: + selector.register(stream, selectors.EVENT_READ) + while True: + remaining = deadline - time.monotonic() + if remaining <= 0 or not selector.select(remaining): + raise subprocess.TimeoutExpired(proc.args, timeout) + chunk = os.read(stream.fileno(), 64 * 1024) + if not chunk: + break + append(decode(chunk)) + proc.wait(timeout=max(0, deadline - time.monotonic())) + except subprocess.TimeoutExpired as exc: + append(decode(b"", final=True)) + exc.output = (suffix + "\n" * newlines)[-limit:] + raise + append(decode(b"", final=True)) + # Check tails strip trailing newlines on success, even when there are many. + return suffix + + def run( argv: Sequence[str], *, @@ -66,6 +108,7 @@ def run( input: str | None = None, encoding: str | None = None, preserve_newlines: bool = False, + tail_chars: int | None = None, ) -> Completed: """Run `argv` (never through a shell) with an environment stripped to the allowlist. @@ -74,8 +117,12 @@ def run( `encoding` overrides the parent locale for text I/O; None retains subprocess defaults. With `preserve_newlines`, decode without newline translation (UTF-8 by default) and preserve undecodable stdout bytes via surrogateescape. + `tail_chars` bounds merged text output without input, stripping trailing + newlines on completion and retaining them for timeout diagnostics. Nonzero exit is reported in `Completed.exit_code`; callers decide whether to raise. """ + if tail_chars is not None and (not merge_output or preserve_newlines or input is not None or tail_chars <= 0): + raise ValueError("bounded tails require merged text output, no input and a positive length") argv = [str(part) for part in argv] started = time.monotonic() raw_encoding = encoding or "utf-8" @@ -94,7 +141,10 @@ def run( start_new_session=os.name == "posix", ) as proc: try: - stdout, stderr = proc.communicate(stdin, timeout=timeout) + if tail_chars is None: + stdout, stderr = proc.communicate(stdin, timeout=timeout) + else: + stdout, stderr = _read_output_tail(proc, tail_chars, timeout), "" except BaseException: if os.name == "posix": with suppress(ProcessLookupError): diff --git a/src/loopzero/sandbox.py b/src/loopzero/sandbox.py index a358d56f..6fd7b21d 100644 --- a/src/loopzero/sandbox.py +++ b/src/loopzero/sandbox.py @@ -460,6 +460,7 @@ def _run_one( env_allowlist=config.env_allowlist, timeout=timeout, merge_output=True, + tail_chars=CHECK_TAIL_BYTES, ) except _proc.ProcTimeout as exc: return CheckResult(command, TIMEOUT_EXIT, timeout, diff --git a/tests/test_sandbox.py b/tests/test_sandbox.py index 5e805278..d558ed5d 100644 --- a/tests/test_sandbox.py +++ b/tests/test_sandbox.py @@ -5,11 +5,13 @@ import json import os import resource +import shlex import shutil import signal import subprocess import sys import tempfile +import tracemalloc import traceback from contextlib import ExitStack from dataclasses import replace @@ -108,9 +110,10 @@ def test_report_fails_when_head_changes_during_run(git_repo, bwrap_log): @pytest.mark.parametrize("command,exit_code,line_count,start,end", [ ("for i in $(seq 1 50); do echo $i; done; echo err >&2", 0, 40, "12", "err"), - ("""python3 -c 'print("x" * 16777216 + " Ω end")'""", 0, 1, "x", " Ω end"), + ("""python3 -c 'print("x" * 20000 + " Ω end")'""", 0, 1, "x", " Ω end"), + ("""python3 -c 'print("terminal line" + "\\n" * 20_000)'""", 0, 1, "terminal line", "terminal line"), ("./" * 8_200 + "absent/file", 1, 1, "", "otherwise restore the required file."), -], ids=["lines", "oversized-line", "missing-file"]) +], ids=["lines", "oversized-line", "trailing-newlines", "missing-file"]) def test_tail_merges_streams_and_truncates(git_repo, bwrap_log, command, exit_code, line_count, start, end): (result,) = sandbox.run_checks(make_config(checks=(command,)), git_repo).results lines = result.tail.splitlines() @@ -231,26 +234,50 @@ def test_temp_parent_cannot_be_exposed(git_repo, bwrap_log): def inject_check_timeout(monkeypatch, output, before_timeout=None): - communicate = subprocess.Popen.communicate + def read_output_tail(process, limit, timeout): + if before_timeout is not None: + before_timeout() + raise subprocess.TimeoutExpired(process.args, timeout, output=output[-limit:]) - def communicate_with_timeout(process, input=None, timeout=None): - if tuple(process.args[-6:-1]) == sandbox.CHECK_SHELL: - if before_timeout is not None: - before_timeout() - raise subprocess.TimeoutExpired(process.args, timeout, output=output) - return communicate(process, input, timeout) + monkeypatch.setattr(sandbox._proc, "_read_output_tail", read_output_tail) - monkeypatch.setattr(subprocess.Popen, "communicate", communicate_with_timeout) +def test_verbose_stage_bounds_parent_memory(git_repo): + command = shlex.join([sys.executable, "-c", """ +import os +import sys -def test_timeout_is_recorded_not_raised(git_repo, bwrap_log, monkeypatch): - inject_check_timeout(monkeypatch, b"x" * 20_000 + b"partial") +block = b"x" * (1024 * 1024) +for _ in range(50): + sys.stdout.buffer.write(block) +sys.stdout.flush() +os.write(1, b"\\r\\nlast stdout\\r\\n") +os.write(2, "final Ω diagnostic\\r\\n".encode()) +sys.exit(7) +"""]) + tracemalloc.start() + try: + tracemalloc.reset_peak() + baseline, _ = tracemalloc.get_traced_memory() + result = sandbox._run_one(make_config(), git_repo, [], command, 30) + _, peak = tracemalloc.get_traced_memory() + finally: + tracemalloc.stop() + assert result.exit_code == 7 + assert result.tail.endswith("\nlast stdout\nfinal Ω diagnostic") + assert len(result.tail.encode()) == 16 * 1024 + assert peak - baseline < 4 * 1024 * 1024 + + +def test_timeout_is_recorded_with_drained_output(git_repo, bwrap_log): + command = "printf '%20000s\\n' ''; echo last diagnostic >&2; exec sleep 30" report = sandbox.run_checks( - make_config(checks=("echo partial", "echo after")), git_repo, timeout=0.3 + make_config(checks=(command, "echo after")), git_repo, timeout=1 ) - (first,) = report.results - assert (first.exit_code, len(first.tail.encode("utf-8"))) == (sandbox.TIMEOUT_EXIT, 16 * 1024) - assert "partial\n[loopzero] timed out" in first.tail and not report.ok + (result,) = report.results + assert result.exit_code == sandbox.TIMEOUT_EXIT and not report.ok + assert result.tail.endswith("\nlast diagnostic\n\n[loopzero] timed out after 1s") + assert len(result.tail.encode()) == 16 * 1024 def test_configured_resource_limits_are_converted_to_bytes(git_repo, bwrap_log, monkeypatch): From 974d3893e7fc82bb47e006216c7dac9cacc6ee14 Mon Sep 17 00:00:00 2001 From: eowca <4008965+eowca@users.noreply.github.com> Date: Thu, 26 Nov 2026 08:11:14 +0100 Subject: [PATCH 2/3] State verified merge cleanup once Architecture-Review: unchanged; contract prose is deduplicated without changing delivery behavior. Co-Authored-By: Codex --- core/CONTRACT.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/core/CONTRACT.md b/core/CONTRACT.md index c9d164e7..14582bd2 100644 --- a/core/CONTRACT.md +++ b/core/CONTRACT.md @@ -38,8 +38,8 @@ own delivery state; `.loopzero/` holds task text and local receipts. Merge rechecks readiness, uses the configured strategy, verifies the landed SHA, and deletes the branch and worktree. If cleanup warns, the merge landed. Follow the recovery step it names. A queue initially enqueues; - `--wait` shares a budget across source-check and landing waits. Cleanup follows - verified landing. Enqueueing without `--wait` returns 0 without cleanup. + `--wait` shares a budget across source-check and landing waits. Enqueueing + without `--wait` returns 0 without cleanup. Merge is authorized by default under [merge authority](#merge-authority). From ad6d104bc498669a5b15fe3cfeb2b9817cb0334d Mon Sep 17 00:00:00 2001 From: eowca <4008965+eowca@users.noreply.github.com> Date: Thu, 26 Nov 2026 08:11:14 +0100 Subject: [PATCH 3/3] State review attribution preservation once Architecture-Review: unchanged; contract prose is deduplicated without changing delivery behavior. Co-Authored-By: Codex --- core/CONTRACT.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/core/CONTRACT.md b/core/CONTRACT.md index c9d164e7..71d4c331 100644 --- a/core/CONTRACT.md +++ b/core/CONTRACT.md @@ -211,9 +211,9 @@ Freeze new work on Codex evidence projections. Simplify or delete them when they another may advise read-only and review independently. Before committing imported work, record every actual writing delegate in truthful `Co-Authored-By` trailers; the committer does not replace the writer. - Preserve all actual contributors through squash/amend except under the - authorized disclosure route below; otherwise retain every writer's - truthful trailers. Missing attribution stays unknown; never invent it. + Preserve every actual contributor's truthful trailers through squash/amend + except under the authorized disclosure route below. Missing attribution + stays unknown; never invent it. - Primary and delta prefer families absent from recognized trailers across all commits/trailers from configured-base merge-base through HEAD, including repairs. Narrower diffs, prose and a main-author-only HEAD cannot