diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index 3e5a69c5..462bb23c 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -189,7 +189,10 @@ commit identity stays in the JSON material header. Explicit UTF-8 stdin carries that header, a newline and the Git patch, including carriage returns and the final newline. UTF-8 patches are supplied verbatim. For other patches, the prompt escapes invalid bytes and literal backslashes so the changes stay -visible. The native inspection digest always binds the original Git bytes. +visible. The native inspection digest always binds the original Git bytes. Git forces +text hunks for every file (overriding `-diff`, `binary` and NUL detection) and +runs no external diff command or text conversion, so changed lines stay visible. +Chunked review summarizes only files whose Git header reports a deletion. The runner probes the selected Codex binary with `--version` and records its stdout in runner provenance and the saved review receipt. A failed probe uses RunnerBadOutput and existing family fallback before model input. Successful diff --git a/src/loopzero/cli.py b/src/loopzero/cli.py index e58359c3..a0890dd2 100644 --- a/src/loopzero/cli.py +++ b/src/loopzero/cli.py @@ -1463,7 +1463,12 @@ def _mergify_timeout_detail( ) detail = f"still queued in {queue}. {location}" if state.unmet_conditions: - detail += ". Unmet candidate conditions: " + "; ".join(state.unmet_conditions) + labels = [label.encode() for label in state.unmet_conditions[:4]] + shown = [label[:160].decode(errors="ignore") + ("…" if len(label) > 160 else "") + for label in labels] + detail += ". Unmet candidate conditions: " + "; ".join(shown) + if omitted := len(state.unmet_conditions) - len(shown): + detail += f"; {omitted} more" return detail diff --git a/src/loopzero/runners.py b/src/loopzero/runners.py index 29bd50fc..da743ea5 100644 --- a/src/loopzero/runners.py +++ b/src/loopzero/runners.py @@ -813,7 +813,8 @@ def _inspection_commands(command, cwd): args = [ part for part in group[1:] - if part not in {"--no-color", "--no-ext-diff", "--no-textconv"} + if part not in {"--no-color", "--no-ext-diff", "--no-textconv", "--text", + "--ignore-submodules=none", "--submodule=short"} ] if len(args) != 2 or not all(_hex(part, 40) for part in args): return [] @@ -1384,7 +1385,8 @@ def split_diff(diff: str, budget: int) -> list[str]: def _summarize_deleted(block: str) -> str: - if "\ndeleted file mode " not in block and "\n+++ /dev/null" not in block: + # Judge deletion from git's header lines only; hunk lines are the PR's own text. + if not re.search(r"(?m)^deleted file mode [0-7]{6}$", block.partition("\n@@")[0]): return block header = block.partition("\n")[0] match = re.fullmatch(r'diff --git ("?)a/(.*)\1 \1b/\2\1', header) diff --git a/src/loopzero/worktree.py b/src/loopzero/worktree.py index 7bf653e3..720e78b8 100644 --- a/src/loopzero/worktree.py +++ b/src/loopzero/worktree.py @@ -247,7 +247,10 @@ def is_dirty(wt: Path) -> bool: def diff_since(wt: Path, sha: str) -> bytes: - diff = _git(Path(wt), "diff", "--no-color", sha, "HEAD", preserve_newlines=True) + # Show every file as text, whatever attributes or NUL bytes the reviewed head adds, + # without diff drivers, and keep submodule pointers even if .gitmodules ignores them. + diff = _git(Path(wt), "diff", "--no-color", "--no-ext-diff", "--no-textconv", "--text", + "--ignore-submodules=none", "--submodule=short", sha, "HEAD", preserve_newlines=True) return diff.encode("utf-8", errors="surrogateescape") diff --git a/tests/test_candidate.py b/tests/test_candidate.py index 1b228c55..c72eb281 100644 --- a/tests/test_candidate.py +++ b/tests/test_candidate.py @@ -105,21 +105,24 @@ def payloads(candidate_event: dict) -> dict[str, object]: def run_attestation( - *, candidate_event: dict | None = None, + *, status_reads: list[dict] | None = None, github_payloads: dict[str, object] | None = None, + github_get=None, + mergify_status=None, source_policy=lambda _number, _source: None, + run=attest_candidate, ): candidate_event = candidate_event or event() reads, values = ( cycle(status_reads or [status(), status()]), github_payloads or payloads(candidate_event), ) - return attest_candidate( + return run( candidate_event, - github_get=lambda path: deepcopy(values[path]), - mergify_status=lambda *_: deepcopy(next(reads)), + github_get=github_get or (lambda path: deepcopy(values[path])), + mergify_status=mergify_status or (lambda *_: deepcopy(next(reads))), source_policy=source_policy, ) @@ -187,10 +190,8 @@ def github_get(path: str): reads = iter([status(), status()]) with pytest.raises(CandidateError, match=diagnostic): - attest_candidate( - candidate_event, github_get=github_get, - mergify_status=lambda *_: deepcopy(next(reads)), source_policy=lambda *_: None, - ) + run_attestation(candidate_event, github_get=github_get, + mergify_status=lambda *_: deepcopy(next(reads))) def test_same_head_still_obeys_source_policy() -> None: @@ -286,8 +287,8 @@ def get(path): return deepcopy(values[path]) return {"object": {"sha": sha}} if (sha := next(reads)) else {} - return run(candidate_event, github_get=get, mergify_status=lambda *_: deepcopy(queue), - source_policy=policy) + return run_attestation(candidate_event, github_get=get, status_reads=[queue], + source_policy=policy, run=run) return attest, git, commit, base, parent, source, candidate_sha @@ -520,7 +521,8 @@ def verify_tree(repo, main_sha, candidate_sha, sources): monkeypatch.setattr(candidate, "_retry_sleep", sleeps.append) monkeypatch.setattr(candidate, "_verify_tree", verify_tree) - assert attest_candidate(candidate_event, github_get=get, mergify_status=lineage, source_policy=policy) == [{"number": 102, "head_sha": source}] + assert run_attestation(candidate_event, github_get=get, mergify_status=lineage, + source_policy=policy) == [{"number": 102, "head_sha": source}] assert seen == {"metadata": [101, 102, 102], "policy": [101, 102], "initial": [102]}[timing] assert candidate_reads == (4 if timing == "metadata" else 3) assert verified == [(main, head, [source])] and sleeps == [2] @@ -545,12 +547,7 @@ def policy(number, source): raise CandidateError("fresh policy rejects drift") with pytest.raises(CandidateError, match="fresh policy rejects drift"): - attest_candidate( - event(), - github_get=get, - mergify_status=lambda *_: status(), - source_policy=policy, - ) + run_attestation(github_get=get, source_policy=policy) assert snapshots == [ ("source 101", False), (value if field == "body" else "source 101", field == "draft"), @@ -598,12 +595,7 @@ def policy(*_): monkeypatch.setattr(candidate, "_retry_sleep", sleeps.append) with pytest.raises((CandidateError, LoopZeroError)) as caught: - attest_candidate( - event(), - github_get=get, - mergify_status=lambda *_: deepcopy(live), - source_policy=policy, - ) + run_attestation(github_get=get, status_reads=[live], source_policy=policy) assert not isinstance(caught.value, CandidateRaceError) and len(attempts) == 1 and sleeps == [] if failure == "policy": assert caught.value is expected and len(source_reads) == 2 @@ -632,12 +624,7 @@ def sleep(seconds): monkeypatch.setattr(candidate, "_retry_clock", lambda: clock[0]) monkeypatch.setattr(candidate, "_retry_sleep", sleep) with pytest.raises(CandidateRaceError, match="membership changed") as caught: - attest_candidate( - event(), - github_get=lambda _: None, - mergify_status=lambda *_: None, - source_policy=lambda *_: None, - ) + run_attestation(github_get=lambda _: None, status_reads=[None]) assert len(attempts) == attempt_count and caught.value is attempts[-1] assert sum(sleeps) <= 4 @@ -673,7 +660,8 @@ def read_status(*_): monkeypatch.setattr(candidate, "_retry_clock", lambda: clock[0]) monkeypatch.setattr(candidate, "_retry_sleep", sleep) def run(): - return attest_candidate(event(), github_get=lambda p: deepcopy(values[p]), mergify_status=read_status, source_policy=lambda n, _: seen.append(n)) + return run_attestation(github_payloads=values, mergify_status=read_status, + source_policy=lambda n, _: seen.append(n)) if stop in {"settled", "changed"}: assert run() == [{"number": 101, "head_sha": "1" * 40}, {"number": 102, "head_sha": "2" * 40}] assert seen == [101, 102] * (2 if stop == "changed" and second else 1) diff --git a/tests/test_cli.py b/tests/test_cli.py index 6eb6edd0..81376235 100644 --- a/tests/test_cli.py +++ b/tests/test_cli.py @@ -4452,22 +4452,22 @@ def test_mergify_reports_current_queue_attempt(wt, gh, capsys, monkeypatch, conf assert (f"{URL}#issuecomment-43" in out) is (kind == "current") -@pytest.mark.parametrize("result", ["blocking", "neutral", "skipped", None]) +@pytest.mark.parametrize("result", ["blocking", "neutral", "skipped", None, "long", "many"]) def test_mergify_timeout_reports_evaluated_candidate_conditions(wt, gh, capsys, monkeypatch, result): head = commit_mergify_configuration(wt) arm_approved_ready_pr(gh, head, wt, isDraft=False) monkeypatch.setattr(mergify, "configured", lambda *_: True) - monkeypatch.setattr(mergify, "markers", lambda *_: (True, False)) - monkeypatch.setattr(mergify, "mark_confirmed", lambda *_: None) - responses = iter([None, MERGIFY_QUEUE_FIXTURE["candidate_responses"][result or "missing"]]) - monkeypatch.setattr(mergify, "api_get", lambda *_: next(responses)) - + monkeypatch.setattr(mergify, "markers", lambda *_: (True, True)) + payload = MERGIFY_QUEUE_FIXTURE["candidate_responses"]["blocking" if result in {"long", "many"} else result or "missing"] + if extra := {"long": 1, "many": 30}.get(result, 0): + conditions = payload["mergeability_check"]["conditions_evaluation"] + monkeypatch.setitem(conditions, "subconditions", conditions["subconditions"] + [{"match": False, "label": "界" * 3000}] * extra) + monkeypatch.setattr(mergify, "api_get", lambda *_: payload) code, out, err = run(capsys, "merge", "--wait=0") - - assert (code, err) == (3, "") - assert f"https://github.com/{REPO}/pull/42" in out - assert (MERGIFY_QUEUE_FIXTURE["candidate_condition"] in out) is (result == "blocking") + assert (code, err) == (3, "") and f"https://github.com/{REPO}/pull/42" in out + assert (MERGIFY_QUEUE_FIXTURE["candidate_condition"] in out) == (result in {"blocking", "long", "many"}) assert "failed" not in out and "check-success = checks" not in out + assert len(out.encode()) < 2048 and ("27 more" in out) == (extra == 30) @pytest.mark.parametrize("queue_state", ["unsafe", "error", "safe", "becomes_unsafe"]) diff --git a/tests/test_config.py b/tests/test_config.py index a877a3db..2ed48a21 100644 --- a/tests/test_config.py +++ b/tests/test_config.py @@ -102,14 +102,10 @@ def test_missing_file(tmp_path): config.load(tmp_path / "nope.toml") -def test_invalid_toml(tmp_path): - with pytest.raises(config.ConfigError, match="invalid TOML"): - config.load(write(tmp_path, "[repo\n")) - - @pytest.mark.parametrize( ("text", "message"), [ + ("[repo\n", "invalid TOML"), ("[checks]\ncommands = []\n", "missing required key repo.name"), ('[repo]\nname = "noslash"\n', 'must look like "owner/name"'), ('[repo]\nname = 3\n', "repo.name must be a str"), @@ -148,6 +144,13 @@ def test_invalid_toml(tmp_path): "checks.limits.memory_mb must be a positive int"), ('[repo]\nname = "o/n"\n[checks]\nlimits = { cpu = 1 }\n', "unknown key\\(s\\) in checks.limits: cpu"), + ('[repo]\nname = "o/n"\n[checks]\ncommands = ["echo ok"]\n' + '[checks.inputs]\n"echo okay" = ["."]\n', r'checks\.inputs\."echo okay".*exact'), + *[ + ('[repo]\nname = "o/n"\n[checks]\nrunner = ["runner"]\ncommands = ["true"]\n' + f"[checks.limits]\n{limit} = 1\n", rf"checks\.limits\.{limit}.*local") + for limit in ("file_mb", "memory_mb") + ], ], ) def test_invalid_content(tmp_path, text, message): @@ -160,17 +163,17 @@ def test_invalid_content(tmp_path, text, message): FORBIDDEN += ["/var/run/docker.sock", "/sys/fs", "/tmp/../run"] -@pytest.mark.parametrize("path", FORBIDDEN) -def test_ro_paths_reject_host_secrets(tmp_path, path): - text = f'[repo]\nname = "o/n"\n[checks]\nro_paths = ["{path}"]\n' - with pytest.raises(config.ConfigError, match="must not expose"): - config.load(write(tmp_path, text)) - - -@pytest.mark.parametrize("path", ["/home/me/.local/bin", "/opt/tool", "/tmp/x"]) -def test_ro_paths_accept_explicit_subpaths(tmp_path, path): - text = f'[repo]\nname = "o/n"\n[checks]\nro_paths = ["{path}"]\n' - assert config.load(write(tmp_path, text)).sandbox_ro == (path,) +@pytest.mark.parametrize("path,allowed", [ + *((path, False) for path in FORBIDDEN), + *((path, True) for path in ("/home/me/.local/bin", "/opt/tool", "/tmp/x")), +]) +def test_ro_path_boundary(tmp_path, path, allowed): + cfg = write(tmp_path, f'[repo]\nname = "o/n"\n[checks]\nro_paths = ["{path}"]\n') + if allowed: + assert config.load(cfg).sandbox_ro == (path,) + else: + with pytest.raises(config.ConfigError, match="must not expose"): + config.load(cfg) def test_check_inputs(tmp_path): @@ -180,24 +183,9 @@ def test_check_inputs(tmp_path): config.load(write(tmp_path, FULL + '\n[checks.inputs]\n"uv run pytest -q" = "src"\n')) -def test_check_inputs_reject_unmatched_command(tmp_path): - text = '[repo]\nname = "o/n"\n[checks]\ncommands = ["echo ok"]\n' - text += '[checks.inputs]\n"echo okay" = ["."]\n' - with pytest.raises(config.ConfigError, match=r'checks\.inputs\."echo okay".*exact'): - config.load(write(tmp_path, text)) - - @pytest.mark.parametrize("strategy", ["", 'merge = "squash"\n', 'merge = "queue"\n']) def test_mergify_queue_rejects_other_strategies(tmp_path, strategy): selected = "queue" if "queue" in strategy else "squash" text = '[repo]\nname = "o/n"\n[delivery]\n' + strategy + 'mergify_queue = "main"\n' with pytest.raises(config.ConfigError, match=rf"delivery\.mergify_queue.*delivery\.merge.*{selected}"): config.load(write(tmp_path, text)) - - -@pytest.mark.parametrize("limit", ["file_mb", "memory_mb"]) -def test_delegated_runner_rejects_local_limit_overrides(tmp_path, limit): - text = '[repo]\nname = "o/n"\n[checks]\nrunner = ["runner"]\ncommands = ["true"]\n' - text += f"[checks.limits]\n{limit} = 1\n" - with pytest.raises(config.ConfigError, match=rf"checks\.limits\.{limit}.*local"): - config.load(write(tmp_path, text)) diff --git a/tests/test_mergify.py b/tests/test_mergify.py index 518c6002..ff3b70e0 100644 --- a/tests/test_mergify.py +++ b/tests/test_mergify.py @@ -13,16 +13,8 @@ from loopzero import mergify -class Response(io.BytesIO): - def __enter__(self): - return self - - def __exit__(self, *_args): - self.close() - - -def response(payload: object) -> Response: - return Response(json.dumps(payload).encode()) +def response(payload: object) -> io.BytesIO: + return io.BytesIO(json.dumps(payload).encode()) def test_membership_uses_bearer_and_validates_queue(monkeypatch): @@ -86,7 +78,7 @@ def queue_api(monkeypatch): {"batches": [], "mode": "serial"} if suffix.startswith("/merge-queue/status") else {"configuration": [{"name": "main", "config": {"allow_inplace_checks": True}}]} )) - def github_config(text, *, default="main", changed=False): + def github_config(text, *, default="main", changed=False, file_overrides=None): reads = 0 def get(path): nonlocal reads @@ -95,7 +87,7 @@ def get(path): assert path == "repos/acme/widgets/contents/.mergify.yml?ref=refs%2Fheads%2Fmain" reads += 1 return {"type": "file", "encoding": "base64", "sha": str(reads if changed else 1)*40, - "content": base64.b64encode(text.encode()).decode()} + "content": base64.b64encode(text.encode()).decode(), **(file_overrides or {})} monkeypatch.setattr(mergify.github, "api_get", get) return github_config @@ -104,13 +96,7 @@ def get(path): ONE_CHECK = SAFE_CONFIG.replace("checks: 3", "checks: 1") # in place unless batches are explicit -@pytest.mark.parametrize("text", [SAFE_CONFIG, ONE_CHECK.replace("main}", "main, batch_size: 8}")]) -def test_configured_accepts_documented_speculation_despite_raw_inplace_default(queue_api, text): - queue_api(text) - assert mergify.configured("acme/widgets", "main", "main") - - -@pytest.mark.parametrize("text", [ +UNSAFE_CONFIGS = [ SAFE_CONFIG.replace("checks: 3", f"checks: {value}") for value in ["1", "0", "-1", "true", '"3"', "null"] ] + [ @@ -120,16 +106,22 @@ def test_configured_accepts_documented_speculation_despite_raw_inplace_default(q SAFE_CONFIG + "merge_queue: {max_parallel_checks: 1}\n", "[]", "!!python/object:object {}", "merge_queue: [", ] + [ONE_CHECK.replace("main}", r) for r in ["main, batch_size: 1}", "main, batch_size: true}", - 'main, batch_size: "8"}', "main, batch_size: null}", "main}, {name: o, batch_size: 8}"]]) -def test_configured_rejects_unsafe_or_ambiguous_canonical_config(queue_api, text): - queue_api(text) - assert not mergify.configured("acme/widgets", "main", "main") - - -@pytest.mark.parametrize("options", [{"default": "other"}, {"changed": True}]) -def test_configured_rejects_wrong_default_branch_or_config_change(queue_api, options): - queue_api(SAFE_CONFIG, **options) - assert not mergify.configured("acme/widgets", "main", "main") + 'main, batch_size: "8"}', "main, batch_size: null}", "main}, {name: o, batch_size: 8}"]] + + +@pytest.mark.parametrize("text,options,accepted", [ + (SAFE_CONFIG, {}, True), + (ONE_CHECK.replace("main}", "main, batch_size: 8}"), {}, True), + *((text, {}, False) for text in UNSAFE_CONFIGS), + (SAFE_CONFIG, {"default": "other"}, False), + (SAFE_CONFIG, {"changed": True}, False), + *((SAFE_CONFIG, {"file_overrides": {key: value}}, False) + for key, value in (("encoding", "none"), ("type", "symlink"), ("sha", None), + ("sha", "z" * 40), ("content", None), ("content", "!"))), +]) +def test_configured_validates_canonical_github_config(queue_api, text, options, accepted): + queue_api(text, **options) + assert mergify.configured("acme/widgets", "main", "main") == accepted def test_configured_still_requires_vendor_queue_identity(queue_api, monkeypatch): @@ -138,20 +130,6 @@ def test_configured_still_requires_vendor_queue_identity(queue_api, monkeypatch) assert not mergify.configured("acme/widgets", "main", "main") -@pytest.mark.parametrize("field,value", [("encoding", "none"), ("type", "symlink"), - ("sha", None), ("sha", "z"*40), ("content", None), ("content", "!")]) -def test_configured_rejects_malformed_github_file(queue_api, monkeypatch, field, value): - queue_api(SAFE_CONFIG) - original = mergify.github.api_get - def malformed(path): - data = original(path) - if "/contents/" in path: - data[field] = value - return data - monkeypatch.setattr(mergify.github, "api_get", malformed) - assert not mergify.configured("acme/widgets", "main", "main") - - def test_legacy_false_does_not_license_single_check_source_updates(queue_api, monkeypatch): queue_api(SAFE_CONFIG.replace("checks: 3", "checks: 1")) monkeypatch.setattr(mergify, "api_get", lambda _repo, suffix: ( diff --git a/tests/test_runners.py b/tests/test_runners.py index 2cfa34e8..25760c30 100644 --- a/tests/test_runners.py +++ b/tests/test_runners.py @@ -1270,6 +1270,12 @@ def timeout(*args, **kwargs): assert len(detail.encode()) < 450 and ("…" in detail) == bool(size) +def test_inspection_accepts_the_reviewer_patch_command() -> None: + command = (f"git -C /repo diff --no-color --no-ext-diff --no-textconv --text " + f"--ignore-submodules=none --submodule=short {'a' * 40} {'b' * 40}") + assert runners._inspection_commands(command, "/repo") == [("diff", "a" * 40, "b" * 40)] + + def test_split_diff_respects_budget_and_summarizes_deleted_file() -> None: deleted = ( "diff --git a/gone.py b/gone.py\n" diff --git a/tests/test_sandbox.py b/tests/test_sandbox.py index a21e2783..355fc0fb 100644 --- a/tests/test_sandbox.py +++ b/tests/test_sandbox.py @@ -15,6 +15,7 @@ from dataclasses import replace from pathlib import Path from select import select +from threading import Event, current_thread from unittest.mock import Mock import pytest @@ -512,15 +513,32 @@ def _pairs(argv: list[str], flag: str) -> list[tuple[str, str]]: return [(argv[i + 1], argv[i + 2]) for i, a in enumerate(argv) if a == flag] +@pytest.fixture +def heartbeat_log(monkeypatch): + monkeypatch.setattr(sandbox, "HEARTBEAT_INTERVAL", 0.03) + observed, events, reporters = Event(), [], set() + + def status(message): + events.append(message) + if ": running " in message: + reporters.add(current_thread()) + observed.set() + else: + assert reporters and all(not reporter.is_alive() for reporter in reporters) + + def wait(): + assert observed.wait(5), "no running heartbeat" + + return events, reporters, status, wait + + @pytest.mark.parametrize("exit_code", [0, 7]) def test_silent_stage_reports_live_metadata_then_completion( - git_repo, bwrap_log, monkeypatch, exit_code + git_repo, bwrap_log, monkeypatch, heartbeat_log, exit_code ): import re - import threading - monkeypatch.setattr(sandbox, "HEARTBEAT_INTERVAL", 0.03) - observed, events, reporters = threading.Event(), [], set() + events, _, status, wait_for_heartbeat = heartbeat_log monkeypatch.setenv("LZ_KEEP", "credential-value") command = f'echo "$LZ_KEEP"; echo private-stderr >&2; exit {exit_code}' cfg = make_config(checks=(command, "echo next")) @@ -528,17 +546,9 @@ def test_silent_stage_reports_live_metadata_then_completion( def run_stage(config, worktree, prefix, stage_command, timeout): if stage_command == command: - assert observed.wait(5), "no running heartbeat for first stage" + wait_for_heartbeat() return run_one(config, worktree, prefix, stage_command, timeout) - def status(event): - events.append(event) - if "running" in event: - reporters.add(threading.current_thread()) - observed.set() - else: - assert all(not reporter.is_alive() for reporter in reporters) - monkeypatch.setattr(sandbox, "_run_one", run_stage) report = sandbox.run_checks(cfg, git_repo, progress=events.append, status=status) assert report.results[0].exit_code == exit_code @@ -574,23 +584,8 @@ def test_early_failure_reports_actual_exit_without_heartbeat(git_repo, bwrap_log assert not report.ok -def test_timeout_stops_heartbeat_and_retains_failure_tail(git_repo, bwrap_log, monkeypatch): - import threading - - monkeypatch.setattr(sandbox, "HEARTBEAT_INTERVAL", 0.03) - observed, events, reporters = threading.Event(), [], [] - - def status(message): - events.append(message) - if message.startswith("stage 1/2: running"): - reporters.append(threading.current_thread()) - observed.set() - else: - assert reporters and all(not reporter.is_alive() for reporter in reporters) - - def wait_for_heartbeat(): - assert observed.wait(5), "no running heartbeat before timeout" - +def test_timeout_stops_heartbeat_and_retains_failure_tail(git_repo, bwrap_log, monkeypatch, heartbeat_log): + events, _, status, wait_for_heartbeat = heartbeat_log inject_check_timeout(monkeypatch, b"private\n", wait_for_heartbeat) report = sandbox.run_checks( make_config(checks=("echo private", "echo never")), git_repo, @@ -603,22 +598,14 @@ def wait_for_heartbeat(): assert report.results[0].tail == "private\n\n[loopzero] timed out after 0.2s" -def test_cancellation_stops_heartbeat_without_reporting_verdict(git_repo, bwrap_log, monkeypatch): - import threading - monkeypatch.setattr(sandbox, "HEARTBEAT_INTERVAL", 0.03) - observed, events, reporters = threading.Event(), [], [] - - def heartbeat(message): - events.append(message) - reporters.append(threading.current_thread()) - observed.set() - +def test_cancellation_stops_heartbeat_without_reporting_verdict(git_repo, bwrap_log, monkeypatch, heartbeat_log): + events, reporters, status, wait_for_heartbeat = heartbeat_log def cancel(*args): - assert observed.wait(5), "no running heartbeat before cancellation" + wait_for_heartbeat() raise KeyboardInterrupt monkeypatch.setattr(sandbox, "_run_one", cancel) with pytest.raises(KeyboardInterrupt): - sandbox.run_checks(make_config(), git_repo, status=heartbeat) + sandbox.run_checks(make_config(), git_repo, status=status) assert events and all("running" in event for event in events) assert all(not reporter.is_alive() for reporter in reporters) @@ -635,34 +622,28 @@ def test_sigterm_cleans_only_the_cancelled_checks_private_directories( from tests.test_sandbox import _save_report, make_config, sandbox mode = sys.argv[1] -if mode == "creation": - mkdtemp = tempfile.mkdtemp +def interrupt(): + print(mode, flush=True) + signal.raise_signal(signal.SIGTERM) - def create(*args, **kwargs): - path = mkdtemp(*args, **kwargs) - print("creation", flush=True) - signal.raise_signal(signal.SIGTERM) - return path +def interrupt_after(call): + def wrapped(*args, **kwargs): + result = call(*args, **kwargs) + interrupt() + return result + return wrapped - tempfile.mkdtemp = create - -if mode == "removal": +if mode == "creation": + tempfile.mkdtemp = interrupt_after(tempfile.mkdtemp) +elif mode == "removal": rmtree = shutil.rmtree - def remove(path, **kwargs): - print("removal", flush=True) - signal.raise_signal(signal.SIGTERM) + interrupt() rmtree(path, **kwargs) - shutil.rmtree = remove - -if mode == "dispatch": +elif mode == "dispatch": class Callbacks(deque): - def pop(self): - callback = super().pop() - print("dispatch", flush=True) - signal.raise_signal(signal.SIGTERM) - return callback + pop = interrupt_after(deque.pop) class Stack(ExitStack): def __init__(self): @@ -720,6 +701,25 @@ def fetched_base(git_repo): return head +@pytest.fixture +def cache_check(git_repo): + exclude = git_repo / ".git/info/exclude" + with exclude.open("a") as stream: + stream.write("\n.loopzero/\n") + + def cache(config, *, clean=False, verify_reuse=False): + report = sandbox.run_checks(config, git_repo) + assert report.ok + if clean: + assert not report.dirty + _save_report(git_repo, report) + if verify_reuse: + assert sandbox.run_checks(config, git_repo).results[0].reused_from == report.head + return report + + return cache + + @pytest.mark.parametrize('change', ['other', 'input', 'shared', 'command', 'network', 'environment', 'version', 'failed', 'boolean_exit_code', 'dirty_receipt', 'keyless', 'dirty_tree', 'legacy']) @@ -772,14 +772,11 @@ def test_declared_input_reuse(git_repo, bwrap_log, monkeypatch, fetched_base, ch @pytest.mark.parametrize("case", ["typo", "empty", "dirty", "no_base"]) -def test_unmatched_inputs_run_fresh(git_repo, bwrap_log, fetched_base, case): - (git_repo / ".git/info/exclude").write_text(".loopzero/\n") +def test_unmatched_inputs_run_fresh(git_repo, bwrap_log, fetched_base, case, cache_check): command = 'test "$(cat README.md)" = hello' paths = () if case == "empty" else ("ipnut.txt",) config = make_config(checks=(command,), inputs={command: paths}) - first = sandbox.run_checks(config, git_repo) - assert first.ok - _save_report(git_repo, first) + cache_check(config) (git_repo / "README.md").write_text("fail\n") if case != "dirty": git(git_repo, "commit", "-qam", "change actual input") @@ -808,16 +805,12 @@ def timed_out(*args): assert report.ok and report.dirty and report.results[0].command == command -def test_local_check_reuse_tracks_checkout_bytes(git_repo, bwrap_log, fetched_base): - (git_repo / ".git/info/exclude").write_text(".loopzero/\n") +def test_local_check_reuse_tracks_checkout_bytes(git_repo, bwrap_log, fetched_base, cache_check): path = git_repo / "README.md" command = "python3 -c 'from pathlib import Path; exit(13 in Path(\"README.md\").read_bytes())'" config = make_config(checks=(command,), inputs={command: ("README.md",)}) assert path.read_bytes() == b"hello\n" - report = sandbox.run_checks(config, git_repo) - assert report.ok and not report.dirty - _save_report(git_repo, report) - assert sandbox.run_checks(config, git_repo).results[0].reused_from == fetched_base + assert cache_check(config, clean=True, verify_reuse=True).head == fetched_base git(git_repo, "config", "core.autocrlf", "true") path.unlink() @@ -877,15 +870,12 @@ def test_reused_check_preserves_integration_shard_output(git_repo, bwrap_log, fe @pytest.mark.parametrize("error", [errno.E2BIG, errno.ENOENT]) -def test_cache_fingerprint_spawn_error(git_repo, bwrap_log, fetched_base, monkeypatch, error): +def test_cache_fingerprint_spawn_error(git_repo, bwrap_log, fetched_base, monkeypatch, error, cache_check): command = "echo stage ran" config = make_config(checks=(command,), inputs={command: ("README.md",)}) - (git_repo / ".git/info/exclude").write_text(".loopzero/\n") - original = sandbox.run_checks(config, git_repo) - assert original.ok and not original.dirty + original = cache_check(config, clean=True, verify_reuse=True) assert original.results[0].input_key - _save_report(git_repo, original) - assert sandbox.run_checks(config, git_repo).results[0].reused_from == fetched_base + assert original.head == fetched_base run = sandbox._proc.run @@ -912,12 +902,9 @@ def fail_fingerprint(argv, **kwargs): assert saved.get("input_key") is None and saved.get("reused_from") is None -def test_local_checks_run_fresh_without_a_base(git_repo, bwrap_log): - (git_repo / ".git/info/exclude").write_text(".loopzero/\n") +def test_local_checks_run_fresh_without_a_base(git_repo, bwrap_log, cache_check): config = make_config(inputs={"*": (".",)}) - first = sandbox.run_checks(config, git_repo) - assert first.ok - _save_report(git_repo, first) + cache_check(config) second = sandbox.run_checks(config, git_repo) assert second.ok @@ -984,7 +971,7 @@ def test_receipt_settings_distinguish_runner_paths(git_repo, monkeypatch, tmp_pa @pytest.mark.parametrize("change", ["target", "content"]) -def test_runner_upgrade_invalidates_pass(git_repo, fetched_base, tmp_path, change): +def test_runner_upgrade_invalidates_pass(git_repo, fetched_base, tmp_path, change, cache_check): def write_runner(path, exit_code): path.write_text( f"#!{sys.executable}\n" @@ -996,15 +983,12 @@ def write_runner(path, exit_code): ) path.chmod(0o755) - (git_repo / ".git/info/exclude").write_text(".loopzero/\n") runner = tmp_path / "runner" original = tmp_path / "runner-a" write_runner(original, 0) runner.symlink_to(original) config = make_config(check_runner=(str(runner),), inputs={"echo hello": (".",)}) - report = sandbox.run_checks(config, git_repo) - assert report.ok - _save_report(git_repo, report) + report = cache_check(config) assert _current_check_report(git_repo, config, report.head) assert sandbox.run_checks(config, git_repo).results[0].reused_from == report.head diff --git a/tests/test_stage_runner.py b/tests/test_stage_runner.py index 6fe18983..ddc88774 100644 --- a/tests/test_stage_runner.py +++ b/tests/test_stage_runner.py @@ -9,7 +9,7 @@ from loopzero.config import ConfigError, load from .conftest import git -from .test_sandbox import bwrap_log, make_config # noqa: F401 +from .test_sandbox import bwrap_log, fetched_base, make_config # noqa: F401 @pytest.mark.parametrize('base_ref,body,verdict,tails', [ @@ -82,14 +82,18 @@ def test_runner(git_repo, tmp_path, bwrap_log, body, verdict, tails, base_ref): assert receipt.keys() == {'head', 'dirty', 'results', 'settings_sha256'} +FALLBACK_RUNNER = (sys.executable, '-c', ( + 'import json,sys;r=json.load(sys.stdin);r.pop("env");' + 'r.update(exit_code=0,duration_s=0,not_started=True,tail="");print(json.dumps(r))' +)) + + @pytest.mark.parametrize('dirty', [True, False]) -def test_runner_unavailable(git_repo, monkeypatch, dirty): +def test_runner_unavailable(git_repo, monkeypatch, dirty, fetched_base): # noqa: F811 if dirty: (git_repo / 'dirty').write_text('x') - git(git_repo, 'update-ref', 'refs/remotes/origin/main', 'HEAD') monkeypatch.setattr(sandbox.shutil, 'which', lambda name: None) - prefix = (sys.executable, '-c', 'import json,sys;r=json.load(sys.stdin);r.pop("env");r.update(exit_code=0,duration_s=0,not_started=True,tail="");print(json.dumps(r))') - report = sandbox.run_checks(make_config(check_runner=prefix), git_repo) + report = sandbox.run_checks(make_config(check_runner=FALLBACK_RUNNER), git_repo) assert not report.ok and report.dirty is dirty assert ('bwrap binary missing' in report.results[0].tail) is not dirty @@ -144,8 +148,7 @@ def test_runner_preserves_executable_symlink(git_repo, tmp_path, monkeypatch, ba assert report.ok, report.results[0].tail -def test_runner_timeout(git_repo, monkeypatch): - git(git_repo, 'update-ref', 'refs/remotes/origin/main', 'HEAD') +def test_runner_timeout(git_repo, monkeypatch, fetched_base): # noqa: F811 original = sandbox._proc.run def run(argv, **kwargs): if argv[0] == sys.executable: @@ -160,21 +163,17 @@ def run(argv, **kwargs): @pytest.mark.parametrize('change', ['fallback', 'base']) -def test_runner_reuse_binds_execution_context(git_repo, bwrap_log, change): # noqa: F811 +def test_runner_reuse_binds_execution_context(git_repo, bwrap_log, fetched_base, change): # noqa: F811 from dataclasses import replace (git_repo / '.git/info/exclude').write_text('.loopzero/\n') - base = git(git_repo, 'rev-parse', 'HEAD').strip() - git(git_repo, 'update-ref', 'refs/remotes/origin/main', base) command = 'echo stage-ran; exit 7' if change == 'fallback' else 'echo one' cfg = make_config(checks=(command,), inputs={command: ('README.md',)}) - body = ('import json,sys;r=json.load(sys.stdin);r.pop("env");' - 'r.update(exit_code=0,duration_s=0,not_started=True,tail="");print(json.dumps(r))') - runner = (sys.executable, '-c', body) + runner = FALLBACK_RUNNER if change == 'fallback': passing = sandbox.run_checks(replace(cfg, checks=('echo seed',)), git_repo) result = replace(passing.results[0], command=command, - input_key=sandbox._input_key(cfg, git_repo, command, base)) + input_key=sandbox._input_key(cfg, git_repo, command, fetched_base)) _save_report(git_repo, replace(passing, results=(result,))) else: cfg = replace(cfg, check_runner=runner) diff --git a/tests/test_worktree.py b/tests/test_worktree.py index 230adc02..d4c30478 100644 --- a/tests/test_worktree.py +++ b/tests/test_worktree.py @@ -203,6 +203,37 @@ def test_start_reports_git_failure_with_command(repo: Path) -> None: assert info.value.tail +def _commit_files(repo: Path, files: dict[str, bytes | None]) -> str: + for name, content in files.items(): + (repo / name).write_bytes(content) if content is not None else (repo / name).unlink() + git(repo, "add", "-A", "--", *files) + git(repo, "commit", "-q", "-m", "change") + return git(repo, "rev-parse", "HEAD").strip() + + +def test_diff_since_shows_changes_the_reviewed_files_try_to_hide(git_repo: Path) -> None: + base = _commit_files(git_repo, {"attr.py": b"old\n", "nul.py": b"old\n"}) + git(git_repo, "update-index", "--add", "--cacheinfo", f"160000,{base},a-sub") + _commit_files(git_repo, { + ".gitattributes": b"attr.py -diff\nnul.py binary\n", "attr.py": b"new = 'attr hunk'\n", + "nul.py": b"new = 'nul hunk'\x00\n", "image.png": b"\x89PNG\r\n\x1a\n\x00\xff\xfe", + ".gitmodules": b'[submodule "a-sub"]\n\tpath = a-sub\n\tignore = all\n'}) + diff = worktree.diff_since(git_repo, base) + assert b"Binary files" not in diff and f"+Subproject commit {base}".encode() in diff + assert b"+new = 'attr hunk'" in diff and b"+new = 'nul hunk'\x00" in diff and b"+\x89PNG\r" in diff + + +def test_split_diff_summarizes_only_files_git_reports_deleted(git_repo: Path) -> None: + from loopzero.runners import render_patch, split_diff # keeps the shared import block untouched + base = _commit_files(git_repo, {"gone.py": b"old\n", "padded.py": b"old\n", "carriage.py": b"old\n"}) + _commit_files(git_repo, {"gone.py": None, "padded.py": b"new = 'padded hunk'\n++ /dev/null\n" + b"x\n" * 300, + "carriage.py": b"new \rdiff --git a/carriage.py b/carriage.py\rdeleted file mode 100644\r" + + b"y\n" * 300}) + joined = "".join(split_diff(render_patch(worktree.diff_since(git_repo, base)), 1_000)) + assert "+++ /dev/null" in joined and "+new = 'padded hunk'" in joined and "+new \r" in joined + assert "gone.py: deleted, 1 lines" in joined and joined.count(": deleted, ") == 1 + + def test_dirty_head_and_diff(repo: Path) -> None: wt = worktree.start(repo, "work", "main") base = worktree.base_sha(wt)