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
8 changes: 5 additions & 3 deletions docs/ARCHITECTURE.md
Original file line number Diff line number Diff line change
Expand Up @@ -74,10 +74,12 @@ The [CLI](../src/loopzero/cli.py) implements the contract's
focused tests start early. `check` runs deterministic checks in a read-only
source sandbox. Its simple-command preflight catches missing local scripts,
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.
progress before each command, metadata-only stage heartbeats after 30 seconds
and every five minutes thereafter (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.
streams remain captured for the final report. Oversized failure output gets a
terminal preview and keeps its diagnostic tail in the check receipt.
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
38 changes: 25 additions & 13 deletions src/loopzero/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -588,6 +588,20 @@ def cmd_start(args: argparse.Namespace) -> int:
return 0


def _check_failure_preview(tail: str, limit: int = 1536) -> 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.

important: Failure preview silently drops long lines, including the final error, and adds no omission marker

When the tail is over 1536 bytes, _check_failure_preview removes every line longer than 768 bytes, wherever it is, then keeps the last 1536 bytes. Nothing in the output shows where lines were removed. Many real failures end in one long line, such as a pytest AssertionError: assert {...} == {...}, a compiler diagnostic or a JSON error. That line is dropped, and the terminal shows the earlier lines as if they were a continuous tail. Only the fixture's short final line survives. The only pointer to the full text is the Full diagnostic tail line. That line is not printed when the head moved or the receipt write fails, which happens after printing. In those cases the dropped text is lost from the transcript, whereas before the change all 40 lines were printed. The byte slice can also start partway through a line.

Smallest fix: keep the lines in order and shorten each long line in place, keeping its start and end around a [... N bytes omitted] marker, instead of deleting it. Always keep the last non-empty line. When the cut-off is not at a line boundary, start the preview with a marker. Add a test where the oversized line is the final error line.

if len(tail.encode()) <= limit:
return tail
edge = limit // 8
lines = (line.encode() for line in tail.splitlines())
preview = b"\n".join(
line if len(line) <= 2 * edge else line[:edge] + b" [...] " + line[-edge:]
for line in lines
)
if len(preview) > limit:
preview = b"[...]\n" + preview[6 - limit:]
return preview.decode(errors="ignore")


def cmd_check(args: argparse.Namespace) -> int:
wt, config = _context(args, pin_checks=True)
if not config.checks:
Expand All @@ -601,32 +615,30 @@ def cmd_check(args: argparse.Namespace) -> int:
except sandbox.SandboxUnavailable as exc:
print(f"sandbox unavailable: {exc}", file=sys.stderr)
return 2
shortened = False
for result in report.results:
if result.exit_code != 0:
print(f"--- {result.command} (exit {result.exit_code}) ---", file=sys.stderr)
tail = _proc.tail(result.tail)
print(tail, file=sys.stderr)
preview = _check_failure_preview(tail)
shortened |= preview != tail
print(preview, file=sys.stderr)
if not config.network and (result.command.startswith("uv sync --offline --locked")
or OFFLINE_FAILURE_RE.search(tail)):
env = {
**sandbox.SANDBOX_ENV,
**_proc.build_env(config.env_allowlist),
**dict(config.env),
}
env = sandbox.SANDBOX_ENV | _proc.build_env(config.env_allowlist) | dict(config.env)
print(
"\nThe sandbox has no network because `[checks] network = false`; "
f"the effective UV_CACHE_DIR inside the sandbox is {env['UV_CACHE_DIR']}. "
"To prepare offline, run UV_CACHE_DIR=<effective-cache> uv sync --group dev "
"(use the groups your checks require) on the host, or the same commands, so the cache "
"under `[checks] writable` is warm, or set `[checks] env` UV_CACHE_DIR to "
"that cache.",
file=sys.stderr,
"Run UV_CACHE_DIR=<effective-cache> uv sync --group dev on the host "
"(use the required groups) so the cache under `[checks] writable` is warm, "
"or set `[checks] env` UV_CACHE_DIR to a warm cache.", file=sys.stderr,
)
current_head = _save_report(wt, report)
if current_head is not None:
if (current_head := _save_report(wt, report)) is not None:
print(f"check result discarded: checked HEAD {report.head}, current HEAD {current_head}",
file=sys.stderr)
return 1
if shortened:
print(f"Full diagnostic tail: {CHECKS_FILE} (head {report.head})", file=sys.stderr)
if report.ok and report.settings_sha256 is None:
print("check stages passed but the receipt is unverified; rerun loopzero check from the task "
"worktree with a stable, readable configured runner before running ready", file=sys.stderr)
Expand Down
7 changes: 5 additions & 2 deletions src/loopzero/sandbox.py
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,8 @@
TIMEOUT_EXIT = 124
CHECK_SHELL = ("/bin/bash", "--posix", "-o", "pipefail", "-c")
CHECK_TAIL_BYTES = 16 * 1024
HEARTBEAT_INTERVAL = 30.0
FIRST_HEARTBEAT_DELAY = 30.0
HEARTBEAT_INTERVAL = 300.0
SANDBOX_HOME = "/tmp/home"
# Only these system directories are exposed read-only by default; home tool paths
# require explicit `[checks] ro_paths`. Host homes, sockets and processes stay hidden.
Expand Down Expand Up @@ -319,9 +320,11 @@ def _stage_status(status: Callable[[str], None] | None, ordinal: int, total: int
started = time.monotonic()

def heartbeat():
while not stopped.wait(HEARTBEAT_INTERVAL):
delay = FIRST_HEARTBEAT_DELAY
while not stopped.wait(delay):
status(f"stage {ordinal}/{total}: running "
f"({time.monotonic() - started:.1f}s elapsed)")
delay = HEARTBEAT_INTERVAL

reporter = threading.Thread(target=heartbeat, daemon=True) if status else None
if reporter:
Expand Down
64 changes: 64 additions & 0 deletions tests/test_cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -307,6 +307,70 @@ def run(capsys, *argv: str) -> tuple[int, str, str]:
return code, captured.out, captured.err


# Transcript size regressions
@pytest.mark.parametrize("receipt", ["saved", "head moved", "write failed"])
def test_check_bounds_large_failure_and_preserves_receipt(wt, head, capsys, monkeypatch, receipt):
tail = 'TEST_FAILURES={"detail":"' + "é" * 7500 + '","error":"Failed to fetch package"}\n'
tail += "migration failed: relation widgets already exists\nAssertionError: assert " + "x" * 1000
monkeypatch.setattr(cli.sandbox, "run_checks", lambda *a, **k: CheckReport(
"a" * 40 if receipt == "head moved" else head, False,
(CheckResult("apply migrations", 7, 0.1, tail),),
))
if receipt == "write failed":
monkeypatch.setattr(cli, "_save_report", Mock(side_effect=PermissionError("receipt write denied")))
code, out, err = run(capsys, "check")
assert len((out + err).encode()) < 2500
assert code == 1 and "apply migrations (exit 7)" in err
assert all(text in err for text in ("migration failed: relation widgets already exists", "AssertionError: assert", "[...]"))
assert "uv sync --group dev" in err
if receipt == "saved":
assert out.endswith("FAIL\n") and ".loopzero/checks.json" in err and head in err
assert json.loads((wt / ".loopzero/checks.json").read_text())["results"][0]["tail"] == tail
else:
assert ".loopzero/checks.json" not in err
assert ("current HEAD" if receipt == "head moved" else "receipt write denied") in err


def test_check_hour_long_stage_transcript(wt, head, gh, capsys, monkeypatch):
sandbox = cli.sandbox
clock = [0.0]
limit = [0.0]

def wait(seconds):
clock[0] += seconds
return clock[0] >= limit[0]

monkeypatch.setattr(sandbox, "threading", SimpleNamespace(
Event=lambda: SimpleNamespace(wait=wait, set=lambda: None),
Thread=lambda *, target, daemon: SimpleNamespace(start=target, join=lambda: None),
))
monkeypatch.setattr(sandbox, "time", SimpleNamespace(monotonic=lambda: clock[0]))

def run_checks(cfg, path, *, progress, status, checkpoint, workflow):
results = []
for ordinal in range(1, 25):
command = f"run tool {ordinal:02d}"
duration = 3600.0 if ordinal == 1 else 0.1
limit[0] = clock[0] + duration
progress(command)
with sandbox._stage_status(status, ordinal, 24):
pass
status(f"stage {ordinal}/24: exit 0 ({duration:.1f}s)")
results.append(CheckResult(command, 0, duration, ""))
return CheckReport(head, False, tuple(results), sandbox.settings_fingerprint(cfg, path))

monkeypatch.setattr(sandbox, "run_checks", run_checks)
code, out, err = run(capsys, "check")
assert len((out + err).encode()) < 2400
assert (code, err, gh.calls) == (0, "", []) and out.endswith("PASS\n")
assert f"receipt produced: head={head}" in out and "stage 24/24: exit 0" in out
assert out.count("running: run tool") == 24
assert [float(seconds) for seconds in re.findall(r"running \(([\d.]+)s elapsed\)", out)] == list(
range(30, 3600, 300)
)
assert out.rindex("s elapsed)") < out.index("stage 1/24: exit 0 (3600.0s)")


# --- start / check --------------------------------------------------------------------


Expand Down
10 changes: 5 additions & 5 deletions tests/test_sandbox.py
Original file line number Diff line number Diff line change
Expand Up @@ -519,7 +519,7 @@ def test_silent_stage_reports_live_metadata_then_completion(
import re
import threading

monkeypatch.setattr(sandbox, "HEARTBEAT_INTERVAL", 0.03)
monkeypatch.setattr(sandbox, "FIRST_HEARTBEAT_DELAY", 0.03)
observed, events, reporters = threading.Event(), [], set()
monkeypatch.setenv("LZ_KEEP", "credential-value")
command = f'echo "$LZ_KEEP"; echo private-stderr >&2; exit {exit_code}'
Expand Down Expand Up @@ -563,7 +563,7 @@ def status(event):


def test_early_failure_reports_actual_exit_without_heartbeat(git_repo, bwrap_log, monkeypatch):
monkeypatch.setattr(sandbox, "HEARTBEAT_INTERVAL", 30.0)
monkeypatch.setattr(sandbox, "FIRST_HEARTBEAT_DELAY", 30.0)
events = []
report = sandbox.run_checks(
make_config(checks=("echo secret; exit 17", "echo never")), git_repo,
Expand All @@ -577,7 +577,7 @@ def test_early_failure_reports_actual_exit_without_heartbeat(git_repo, bwrap_log
def test_timeout_stops_heartbeat_and_retains_failure_tail(git_repo, bwrap_log, monkeypatch):
import threading

monkeypatch.setattr(sandbox, "HEARTBEAT_INTERVAL", 0.03)
monkeypatch.setattr(sandbox, "FIRST_HEARTBEAT_DELAY", 0.03)
observed, events, reporters = threading.Event(), [], []

def status(message):
Expand Down Expand Up @@ -605,7 +605,7 @@ def wait_for_heartbeat():

def test_cancellation_stops_heartbeat_without_reporting_verdict(git_repo, bwrap_log, monkeypatch):
import threading
monkeypatch.setattr(sandbox, "HEARTBEAT_INTERVAL", 0.03)
monkeypatch.setattr(sandbox, "FIRST_HEARTBEAT_DELAY", 0.03)
observed, events, reporters = threading.Event(), [], []

def heartbeat(message):
Expand Down Expand Up @@ -677,7 +677,7 @@ def status(message):
if mode == "blocked-heartbeat":
threading.Event().wait()

sandbox.HEARTBEAT_INTERVAL = 0.03
sandbox.FIRST_HEARTBEAT_DELAY = 0.03
repo = Path.cwd()
command = "echo complete" if mode in {"dispatch", "removal"} else "exec sleep 30"
report = sandbox.run_checks(make_config(checks=(command,)), repo, status=status)
Expand Down
Loading