Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions docs/ARCHITECTURE.md
Original file line number Diff line number Diff line change
Expand Up @@ -74,8 +74,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.
Expand Down
52 changes: 51 additions & 1 deletion src/loopzero/_proc.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,10 @@

from __future__ import annotations

import codecs
import io
import os
import selectors
import signal
import subprocess
import time
Expand Down Expand Up @@ -55,6 +58,45 @@ def build_env(
return env


def _read_output_tail(proc: subprocess.Popen[str], limit: int, timeout: float) -> str:

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

suggestion: Document _read_output_tail's trailing-newline contract next to _check_tail

_read_output_tail holds trailing newlines separately. It drops them on success and keeps them, capped at limit, on timeout. This matches what _check_tail produces from the full text, which does rstrip("\n") and then slices the last 16 KiB. The equivalence depends on the min(limit, ...) cap and on _check_tail running rstrip first, and neither function mentions the other. A one-line docstring saying the result equals text.rstrip('\n')[-limit:] on success and text[-limit:] on timeout would stop the two from drifting apart in a later edit. Non-blocking.

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],
*,
Expand All @@ -65,14 +107,19 @@ def run(
merge_output: bool = False,
input: str | None = None,
encoding: str | None = None,
tail_chars: int | None = None,
) -> Completed:
"""Run `argv` (never through a shell) with an environment stripped to the allowlist.

`merge_output=True` sends stderr into stdout so interleaving is preserved.
`input` is written to the child's stdin; without it stdin is /dev/null.
`encoding` overrides the parent locale for text I/O; None retains subprocess defaults.
`tail_chars` bounds capture for a merged stream 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 input is not None or tail_chars <= 0):
raise ValueError("bounded tails require merged output, no input and a positive length")
argv = [str(part) for part in argv]
started = time.monotonic()
try:
Expand All @@ -89,7 +136,10 @@ def run(
start_new_session=os.name == "posix",
) as proc:
try:
stdout, stderr = proc.communicate(input, timeout=timeout)
if tail_chars is None:
stdout, stderr = proc.communicate(input, timeout=timeout)
else:
stdout, stderr = _read_output_tail(proc, tail_chars, timeout), ""
except BaseException:
if os.name == "posix":
with suppress(ProcessLookupError):
Expand Down
1 change: 1 addition & 0 deletions src/loopzero/sandbox.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
61 changes: 51 additions & 10 deletions tests/test_sandbox.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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()
Expand All @@ -119,6 +122,33 @@ def test_tail_merges_streams_and_truncates(git_repo, bwrap_log, command, exit_co
assert len(result.tail.encode("utf-8")) <= 16 * 1024


def test_verbose_stage_bounds_parent_memory(git_repo):
command = shlex.join([sys.executable, "-c", """
import os
import sys

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


@pytest.mark.parametrize(
("command", "stage_exit"),
[
Expand Down Expand Up @@ -231,16 +261,27 @@ 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:])

monkeypatch.setattr(sandbox._proc, "_read_output_tail", read_output_tail)


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)
def test_local_stage_timeout_retains_drained_output(git_repo):
command = shlex.join([sys.executable, "-c", """
import os
import signal

monkeypatch.setattr(subprocess.Popen, "communicate", communicate_with_timeout)
os.write(1, b"x" * 20_000)
os.write(2, b"\\nlast available diagnostic\\n")
signal.pause()
"""])
result = sandbox._run_one(make_config(), git_repo, [], command, 1)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

suggestion: Real-timeout test depends on the child writing its output within 1s

test_local_stage_timeout_retains_drained_output runs a real Python child under prlimit with a 1s timeout. It asserts that the tail ends with the diagnostic and is exactly 16 KiB. On a loaded CI host, interpreter startup can take longer than 1s. The child is then killed before it writes anything, the tail is just the timeout marker, and both assertions fail. This is a test flake, not a product defect. Smallest fix: have the child print a ready marker after its writes, and wait for it before the deadline matters. Alternatively, raise the timeout to a few seconds; signal.pause() keeps the test deterministic either way.

assert result.exit_code == sandbox.TIMEOUT_EXIT
assert result.tail.endswith("\nlast available diagnostic\n\n[loopzero] timed out after 1s")
assert len(result.tail.encode()) == 16 * 1024


def test_timeout_is_recorded_not_raised(git_repo, bwrap_log, monkeypatch):
Expand Down
Loading