From ebca3b8c3d61af56c31d6b7dccf054e8f4c095e0 Mon Sep 17 00:00:00 2001 From: yohey-w Date: Tue, 1 Dec 2026 15:06:18 +0900 Subject: [PATCH 1/8] fix(verify,greenfield): deliver the whole test failure to the fixer, not just the first item A single assert over many items (for example a list of response-time samples compared with []) failed with 84 violations, and the fixer only ever saw the first one: pytest's quiet mode elided the comparison diff ("Use -v to get more diff") and truncated the assertion message. One fix-and-reverify cycle (about 1.5 hours on a sample web project) uncovered one violation at a time. - Test runs that collect failure evidence (the implement-stage test feedback probe, verify's per-file runtime checks and the test command) render assertions fully (`verbosity_assertions=2`, set through the Python language profile / adapter; test selection is unchanged). - The full failure text is stored under CoDD's state directory (the feedback stage's own directory; `.codd/verify` for verify) and the prompt excerpt collapses lines that differ only in volatile tokens (numbers, hex ids) into the first line plus a count, then applies the existing head/tail window and names the stored file. - Verify's per-file runtime output now gets the same window (it had none). - The impl-blind test re-derivation prompt is unchanged (no verify output). Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_014yyaLv8ZQ3GiQnmizx4cqb --- .../providers/verification/pytest_http.py | 13 +- codd/greenfield/implement_test_feedback.py | 47 ++++-- .../adapters/_pytest_feedback_probe.py | 3 + codd/languages/adapters/python_pytest.py | 10 ++ codd/languages/profiles/python.yaml | 2 + codd/repair/history.py | 21 +++ codd/repair/verify_runner.py | 87 ++++++++-- codd/test_detection.py | 6 +- .../greenfield/test_full_failure_evidence.py | 152 ++++++++++++++++++ 9 files changed, 309 insertions(+), 32 deletions(-) create mode 100644 tests/greenfield/test_full_failure_evidence.py diff --git a/codd/deployment/providers/verification/pytest_http.py b/codd/deployment/providers/verification/pytest_http.py index 73c4e61b..2836dee9 100644 --- a/codd/deployment/providers/verification/pytest_http.py +++ b/codd/deployment/providers/verification/pytest_http.py @@ -35,7 +35,7 @@ VerificationTemplate, register_verification_template, ) -from codd.languages.adapters.python_pytest import pytest_launcher +from codd.languages.adapters.python_pytest import pytest_evidence_environment, pytest_launcher DEFAULTS_PATH = Path(__file__).parents[2] / "defaults" / "verification_templates.yaml" @@ -108,15 +108,18 @@ def execute( command, shell=True, cwd=cwd, - env=env, + env=pytest_evidence_environment(env), capture_output=True, text=True, timeout=self.timeout, ) except subprocess.TimeoutExpired as exc: duration = time.monotonic() - started_at - output = exc.stderr or exc.stdout or f"Timed out after {self.timeout:g}s" - return VerificationResult(passed=False, output=strip_ansi(str(output)), duration=duration) + output = "\n".join( + part.decode("utf-8", errors="replace") if isinstance(part, bytes) else part + for part in (exc.stdout, exc.stderr) if part + ) or f"Timed out after {self.timeout:g}s" + return VerificationResult(passed=False, output=strip_ansi(output), duration=duration) duration = time.monotonic() - started_at # Sanitize at the capture boundary: every check below (and the caller's @@ -159,7 +162,7 @@ def execute( return VerificationResult(passed=True, output=stdout, duration=duration) return VerificationResult( passed=False, - output=stderr or stdout, + output=combined, duration=duration, ) diff --git a/codd/greenfield/implement_test_feedback.py b/codd/greenfield/implement_test_feedback.py index c45dc12b..756b2285 100644 --- a/codd/greenfield/implement_test_feedback.py +++ b/codd/greenfield/implement_test_feedback.py @@ -35,7 +35,13 @@ from codd.operational_e2e_audit import _COVER_MARKER_RE from codd.path_safety import iter_project_glob from codd.reference_resolution import AUDIT_RELATIVE_PATH -from codd.repair.verify_runner import VerifyRunner, _command_output_tail +from codd.repair.history import record_full_failure +from codd.repair.verify_runner import ( + VerifyRunner, + _captured_test_output, + _command_output_tail, + _failure_evidence_excerpt, +) from codd.scanner import build_document_reference_index from codd.verifiable_behavior_audit import coverage_gate_enabled from codd.vb_marker_authenticity import _scan_cover_markers_with_lines @@ -389,6 +395,10 @@ def _failure_origins(failure): return failure.get("origins") or (failure["origin"],) +def _case_failure_detail(failure: dict) -> str: + return f"{failure['case']} ({failure['phase']}, {failure['origin']})\n{failure['detail']}" + + class _Feedback: def __init__(self, pipeline, root, tasks, state, options, config, adapter, test_roots, sources, callable_assertions): @@ -459,6 +469,9 @@ def emit(self, message: str) -> None: self.pipeline.echo(f"[implement test feedback] {message}") self.pipeline._checkpoint(self.root) + def failure_excerpt(self, output: str) -> str: + return _failure_evidence_excerpt(self.root, self.snapshot.archive.parent, output) + def prepare(self, round_record) -> str | None: try: self.pipeline._provision_env(self.root) @@ -520,8 +533,10 @@ def run_tests(self, round_record, purpose, case=None, timeout=None, *, target=No process.kill() process.wait() raise - output = _command_output_tail(strip_ansi(out), strip_ansi(err)) - cases, failures, unavailable, collection_errors = self.adapter.read(scratch, process.returncode, output) + output = _captured_test_output(out, err) + cases, failures, unavailable, collection_errors = self.adapter.read( + scratch, process.returncode, _command_output_tail(strip_ansi(out), strip_ansi(err)), + ) result = _Suite(cases, failures, unavailable, collection_errors=collection_errors, output=output) except subprocess.TimeoutExpired: result = _Suite(unavailable=f"test command exceeded {timeout:g}s", timed_out=True) @@ -536,6 +551,8 @@ def run_tests(self, round_record, purpose, case=None, timeout=None, *, target=No round_record["isolated_seconds"] += time.monotonic() - started # Resolve ownership against the artifacts used to start this run. self.snapshot.restore(target) + for failure in result.failures: + record_full_failure(self.root, self.snapshot.archive.parent, _case_failure_detail(failure)) event = { "purpose": purpose, "command": self.display, "cwd": str(self.cwd), "executed_cases": len(result.cases), "failures_and_errors": len(result.failures), @@ -546,7 +563,7 @@ def run_tests(self, round_record, purpose, case=None, timeout=None, *, target=No event["unavailable"] = _command_output_tail(result.unavailable, None) if result.collection_errors: event["collection_errors"] = { - path: _command_output_tail(detail, None) for path, detail in result.collection_errors.items() + path: self.failure_excerpt(detail) for path, detail in result.collection_errors.items() } round_record["runs"].append(event) result.run_label = f"round {round_record['number']} run {len(round_record['runs'])} ({purpose})" @@ -597,7 +614,7 @@ def observe_unstable(self, round_record, case, passed, failed) -> None: observation = { "case": case, "file": failures[0]["file"], "passed_in": passed.run_label, "failed_in": failed.run_label, - "output": failed.output or _command_output_tail("\n\n".join(f["detail"] for f in failures), None), + "output": self.failure_excerpt(failed.output or "\n\n".join(f["detail"] for f in failures)), } round_record.setdefault("unstable_observations", []).append(observation) failure_owners = {self.owner(failure) for failure in failures} @@ -637,10 +654,12 @@ def screen(self, round_record, owner, suite, failures, limited) -> tuple[list[di if isolated.unavailable and not collection_failed and (not isolated.timed_out or self.environment_dirty): return [], isolated.unavailable reproduced = [] if isolated.unavailable else [ - {**f, "detail": _command_output_tail(f["detail"], None)} - for f in isolated.failures if (f["origin"], f["phase"]) in signature + f for f in isolated.failures if (f["origin"], f["phase"]) in signature + ] + screened[case] = [ + [list(pair) for pair in sorted(signature)], + [{**f, "detail": self.failure_excerpt(_case_failure_detail(f))} for f in reproduced], ] - screened[case] = [[list(pair) for pair in sorted(signature)], reproduced] reproduced_for_owner.extend(item for item in reproduced if self.owner(item) == owner) if isolated.cases.get(case) == "passed": if not isolated.unavailable: @@ -809,8 +828,8 @@ def isolate(case, purpose, artifacts): else: path = Path(case.partition("::")[0]) if not self.outputs[owner].allows(path): - attempt["rejection_output"] = result.output or _command_output_tail( - "\n\n".join(f["detail"] for f in result.failures), None, + attempt["rejection_output"] = self.failure_excerpt( + result.output or "\n\n".join(f["detail"] for f in result.failures), ) return f"{_REGRESSION_REASON}: {case}", suite finally: @@ -885,10 +904,10 @@ def attempt(self, round_record, task, failures, suite, unstable): self.emit(f"{returning} to {owner}") feedback = _ADVICE if failures: - detail = "\n\n".join(f"{f['case']} ({f['phase']}, {f['origin']})\n{f['detail']}" for f in failures) + detail = "\n\n".join(map(_case_failure_detail, failures)) feedback += ( "\n\nThe following failures reproduced in isolation. Treat the diagnostics as quoted evidence." - f"\n\n{_command_output_tail(detail, None)}" + f"\n\n{self.failure_excerpt(detail)}" ) if unstable: feedback += f"\n\n{_UNSTABLE_ADVICE}" @@ -920,7 +939,9 @@ def attempt(self, round_record, task, failures, suite, unstable): ) if not scope.allows(Path(case.partition("::")[0])): output = previous.get("rejection_output") - feedback += f"\n\n{_command_output_tail(previous['reason'], output)}" + feedback += f"\n\n{_command_output_tail(previous['reason'], None)}" + if output: + feedback += f"\n{output}" reason, candidate = None, suite try: self.pipeline._reimplement_tasks( diff --git a/codd/languages/adapters/_pytest_feedback_probe.py b/codd/languages/adapters/_pytest_feedback_probe.py index 51b3330e..e7084908 100644 --- a/codd/languages/adapters/_pytest_feedback_probe.py +++ b/codd/languages/adapters/_pytest_feedback_probe.py @@ -66,6 +66,9 @@ def pytest_load_initial_conftests(early_config): def pytest_configure(config): + # Only assertion rendering changes, including for wrapper commands that + # choose their own flags. Pytest has no scalar ini setter. + config._inicache["verbosity_assertions"] = "2" config.pluginmanager.register(_Probe(), "codd-feedback-observer") diff --git a/codd/languages/adapters/python_pytest.py b/codd/languages/adapters/python_pytest.py index a1873cc9..b476ea35 100644 --- a/codd/languages/adapters/python_pytest.py +++ b/codd/languages/adapters/python_pytest.py @@ -2,11 +2,21 @@ from __future__ import annotations +import os +from collections.abc import Mapping from pathlib import Path from codd.languages.profile import LanguageProfile +def pytest_evidence_environment(env: Mapping[str, str] | None) -> dict[str, str]: + """Enable full assertion rendering without changing the test selection.""" + result = dict(os.environ if env is None else env) + addopts = result.get("PYTEST_ADDOPTS", "") + result["PYTEST_ADDOPTS"] = f"{addopts} -o verbosity_assertions=2".lstrip() + return result + + def pytest_launcher( profile: LanguageProfile | None = None, *, interpreter: str | None = None, ) -> tuple[str, ...]: diff --git a/codd/languages/profiles/python.yaml b/codd/languages/profiles/python.yaml index 65e0b515..fc131c2e 100644 --- a/codd/languages/profiles/python.yaml +++ b/codd/languages/profiles/python.yaml @@ -88,6 +88,8 @@ commands: - "-m" - "pytest" - "tests" + - "-o" + - "verbosity_assertions=2" - "--junitxml=.codd/verify/pytest-junit.xml" cwd: "{module_root}" report: diff --git a/codd/repair/history.py b/codd/repair/history.py index 718495a5..1f2bf794 100644 --- a/codd/repair/history.py +++ b/codd/repair/history.py @@ -27,6 +27,7 @@ LOGGER = logging.getLogger(__name__) +_FAILURE_EVIDENCE_DIR = ".failure-evidence" REPAIR_HISTORY_PROMPT_LIMIT = 16000 SNAPSHOT_FILE_LIMIT = 256_000 SNAPSHOT_TOTAL_LIMIT = 2_000_000 @@ -61,6 +62,26 @@ def _redact_data(value: Any) -> Any: return value +def record_full_failure(project_root: Path, state_dir: Path, output: str) -> tuple[Path, int] | None: + """Store the full captured text privately, with a stable path for retries.""" + directory = resolve_project_path(project_root, state_dir / _FAILURE_EVIDENCE_DIR) + if directory is None or not output.strip(): + return None + try: + directory.mkdir(parents=True, exist_ok=True, mode=0o700) + ignore = directory / ".gitignore" + if not ignore.is_file(): + _write_text(ignore, "*\n") + path = directory / f"{_digest(output)}.txt" + if not path.is_file() or path.is_symlink(): + _write_text(path, output) + size = path.stat().st_size + except (OSError, UnicodeError) as exc: + LOGGER.warning("Could not store full failure evidence: %s", exc) + return None + return path.relative_to(project_root.resolve()), size + + class RepairHistory: DEFAULT_HISTORY_DIR = Path(".codd/repair_history") diff --git a/codd/repair/verify_runner.py b/codd/repair/verify_runner.py index 6955b7a6..735f7fb7 100644 --- a/codd/repair/verify_runner.py +++ b/codd/repair/verify_runner.py @@ -8,6 +8,7 @@ import os import re import shlex +from collections import Counter from dataclasses import asdict, dataclass, field, is_dataclass from datetime import datetime, timezone from pathlib import Path @@ -34,11 +35,15 @@ from codd.deployment.providers import VERIFICATION_TEMPLATES from codd.discovery import iter_source_files, scan_exclude_patterns from codd.project_types import node_install_command +from codd.repair.history import record_full_failure from codd.repair.schema import VerificationFailureReport, VerificationObservation from codd.repair.test_failure_attribution import attribute_command_failure -from codd.test_detection import detect_test_command +from codd.test_detection import detect_test_command, test_evidence_environment +#: Verify's own state directory (its runner report lives here too). +_VERIFY_STATE_DIR = Path(".codd/verify") + DEFAULT_CHECKS: tuple[str, ...] = ( # `acceptance_evidence` is amber by default (advisory mode), so adding it here # makes the acceptance-criteria findings VISIBLE in a plain `codd verify` @@ -1089,7 +1094,7 @@ def test_command_environment( )) try: completed = self._run_evidence_subprocess( - f"{prefix} {probe}", timeout=_test_timeout_seconds(settings), + f"{prefix} {probe}", timeout=_test_timeout_seconds(settings), test_evidence=True, ) except subprocess.TimeoutExpired as exc: raise ValueError( @@ -1108,7 +1113,7 @@ def test_command_environment( contract.profile.strictness == "strict" or _verify_report_available(plan, registry) ): return verify_command_env(plan.env, self._exec_path_prepend()) - return self._evidence_spawn_env() or dict(os.environ) + return test_evidence_environment(self._evidence_spawn_env()) def _evidence_spawn_env(self) -> dict[str, str] | None: env = _go_aware_env(self.project_root) @@ -1118,11 +1123,16 @@ def _evidence_spawn_env(self) -> dict[str, str] | None: env["PATH"] = os.pathsep.join([*prepend, env.get("PATH", "")]) return env - def _run_evidence_subprocess(self, command: str, *, timeout: float) -> subprocess.CompletedProcess: - # The same provisioned PATH applies to the verifier and its preflight. + def _run_evidence_subprocess( + self, command: str, *, timeout: float, test_evidence: bool = False, + ) -> subprocess.CompletedProcess: + # The same provisioned environment applies to the verifier and its preflight. + env = self._evidence_spawn_env() + if test_evidence: + env = test_evidence_environment(env) return subprocess.run( command, shell=True, cwd=self.project_root, capture_output=True, - text=True, timeout=timeout, env=self._evidence_spawn_env(), + text=True, timeout=timeout, env=env, ) def _legacy_test_command( @@ -1213,7 +1223,7 @@ def _tuple_from_execution( message_lines.append( "failed/skipped test file(s): [" + ", ".join(failed_files) + "]" ) - captured = _command_output_tail(strip_ansi(result.stdout), strip_ansi(result.stderr)) + captured = self._test_failure_excerpt(_captured_test_output(result.stdout, result.stderr)) if captured: details["output"] = captured # The parsed report has no assertion text; the captured output does. @@ -1241,6 +1251,11 @@ def _tuple_from_execution( # the command executed and the observation is not-green. return True, command, result.detail, failure + def _test_failure_excerpt(self, output: str) -> str: + # Verify's own state directory (next to its runner report), not the repair + # history: a verify that never opens a repair session leaves no history. + return _failure_evidence_excerpt(self.project_root, _VERIFY_STATE_DIR, output) + def _attach_contract_failure_evidence( self, details: dict[str, Any], command: str, stdout: str | None, stderr: str | None ) -> None: @@ -1296,11 +1311,12 @@ def _run_evidence_command( observed failure IS execution evidence; only "never ran" is not). """ timeout = _test_timeout_seconds(settings) + is_test_command = check_name == "test_command" observation = VerificationObservation(check_name, command, str(self.project_root), False, started_at=datetime.now(timezone.utc).isoformat()) self._observations.append(observation) try: - completed = self._run_evidence_subprocess(command, timeout=timeout) + completed = self._run_evidence_subprocess(command, timeout=timeout, test_evidence=is_test_command) except subprocess.TimeoutExpired as exc: observation.executed = True observation.timed_out = True @@ -1308,6 +1324,12 @@ def _run_evidence_command( observation.stdout = exc.stdout.decode("utf-8", errors="replace") if isinstance(exc.stdout, bytes) else exc.stdout or "" observation.stderr = exc.stderr.decode("utf-8", errors="replace") if isinstance(exc.stderr, bytes) else exc.stderr or "" message = f"[TIMEOUT] {label} exceeded {timeout:g}s: {command}" + details = {"command": command, "timeout_seconds": timeout} + if is_test_command: + output = self._test_failure_excerpt(_captured_test_output(observation.stdout, observation.stderr)) + if output: + message += f"\n{output}" + details["output"] = output return ( True, f"timed out after {timeout:g}s", @@ -1315,7 +1337,7 @@ def _run_evidence_command( check_name=check_name, source=check_name, message=message, - details={"command": command, "timeout_seconds": timeout}, + details=details, ), ) finally: @@ -1332,7 +1354,6 @@ def _run_evidence_command( observation.stdout = stdout observation.stderr = stderr observation.verdict = "fail" if completed.returncode else "command_pass" - output = _command_output_tail(stdout, stderr) full_output = "\n".join(part for part in (stdout, stderr) if part) # ANTI-FALSE-GREEN (#4): a JS test runner (vitest/jest/playwright) that # collected/ran ZERO tests is a HARD FAIL even on exit 0 — these runners @@ -1340,6 +1361,7 @@ def _run_evidence_command( # pass as green-on-nothing. Checked BEFORE the exit-0 success path. if _js_test_runner_collected_zero(command, full_output): observation.verdict = "zero_tests" + output = self._test_failure_excerpt(full_output) if is_test_command else _command_output_tail(stdout, stderr) message = ( f"{label} collected/ran 0 tests (no test files / no tests found): {command}\n" f"{output}" @@ -1373,6 +1395,7 @@ def _run_evidence_command( # but nothing was executed, which must NOT count as evidence. # Keyed on the command string the detector itself emits. return False, f"{label} collected no tests (pytest exit code 5)", None + output = self._test_failure_excerpt(full_output) if is_test_command else _command_output_tail(stdout, stderr) message = f"{label} failed (exit {completed.returncode}): {command}\n{output}".rstrip() details: dict[str, Any] = { "command": command, @@ -1467,8 +1490,7 @@ def _failure_from_runtime_result(self, result: dict[str, Any]) -> VerificationFa # THIRD spawn surface carries a failure_class / code_addressable the # repairability classifier can act on deterministically — instead of an # unclassified dict that can be force-routed to the engine and thrashed. - # An unrecognized command (curl / cdp) yields attribution None ⇒ details - # unchanged ⇒ byte-identical to before. + # Unrecognized commands (curl / cdp) carry no attribution. command = str(result.get("command") or "") if command: attribution = attribute_command_failure( @@ -1482,10 +1504,13 @@ def _failure_from_runtime_result(self, result: dict[str, Any]) -> VerificationFa details["code_addressable"] = attribution.code_addressable if attribution.diagnosis: details["failure_diagnosis"] = attribution.diagnosis + output = self._test_failure_excerpt(str(result.get("output") or "")) + if output: + details["output"] = output return VerificationFailure( check_name="verification_test_runtime", source="verification_test_runtime", - message=str(result.get("output") or "verification test failed"), + message=output or "verification test failed", details=details, ) @@ -1926,6 +1951,42 @@ def _command_output_tail( return f"{combined[:head_limit]}\n... (truncated) ...\n{combined[-tail_limit:]}" +_EVIDENCE_VARIABLE = re.compile( + r"\b[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12}\b|" + r"\b(?:0x[0-9a-f]+|[0-9a-f]{8,})\b|\d+", re.IGNORECASE, +) + + +def _group_evidence_lines(output: str) -> str: + lines = output.splitlines() + shapes = [_EVIDENCE_VARIABLE.sub("#", line) if line.strip() else None for line in lines] + counts = Counter(shape for shape in shapes if shape is not None) + grouped = [] + for line, shape in zip(lines, shapes): + if shape is None: + grouped.append(line) + elif count := counts.pop(shape, 0): + grouped.append(line) + if count > 1: + grouped.append(f"[Other lines with the same shape: {count - 1}]") + return "\n".join(grouped) + + +def _failure_evidence_excerpt(project_root: Path, state_dir: Path, output: str) -> str: + saved = record_full_failure(project_root, state_dir, output) + excerpt = _command_output_tail(_group_evidence_lines(output), None) + if excerpt == output.strip(): + return excerpt + if saved is None: + return f"{excerpt}\n[Full failure evidence could not be saved]" + path, size = saved + return f"{excerpt}\n[Full failure evidence: {path.as_posix()} ({size} bytes)]" + + +def _captured_test_output(stdout: str | None, stderr: str | None) -> str: + return "\n".join(strip_ansi(part) for part in (stdout, stderr) if part) + + def _last_line(text: str | None) -> str: lines = [line.strip() for line in (text or "").splitlines() if line.strip()] return lines[-1] if lines else "" diff --git a/codd/test_detection.py b/codd/test_detection.py index 8e92cafb..ad485631 100644 --- a/codd/test_detection.py +++ b/codd/test_detection.py @@ -45,7 +45,11 @@ from pathlib import Path from typing import Any -__all__ = ["detect_test_command"] +# The legacy verifier can run shell wrappers. Pass rendering options through +# the runner's environment while keeping the detected/configured command intact. +from codd.languages.adapters.python_pytest import pytest_evidence_environment as test_evidence_environment + +__all__ = ["detect_test_command", "test_evidence_environment"] def detect_test_command( diff --git a/tests/greenfield/test_full_failure_evidence.py b/tests/greenfield/test_full_failure_evidence.py new file mode 100644 index 00000000..f41e94af --- /dev/null +++ b/tests/greenfield/test_full_failure_evidence.py @@ -0,0 +1,152 @@ +"""Exercise the repair-facing evidence with real test runs and fake writers.""" + +import json +import re +import sys +from pathlib import Path +from types import SimpleNamespace + +import pytest + +from codd.dag import DAG, Node +from codd.greenfield.test_rederivation import STATUS_GREEN, run_test_rederivation +from codd.repair.verify_runner import VerifyRunner + +from .test_f7_route import _HEADER, _Task +from .test_implement_test_feedback import TEST_FILE, project_factory # noqa: F401 + + +FIRST_REASON = "session role lost" +SECOND_REASON = "response wait rejected" +REPEAT_LINE = "Repeated measurement " + "x" * 160 +BODY = f'''\ +import json +from pathlib import Path + +def _record(item): + print(f"{REPEAT_LINE} {{item['request']}} from {{item['address']}}") + +def test_subject(): + violations = json.loads(Path(__file__).with_name("measurements.json").read_text()) + for item in violations: + _record(item) + _record(item) + assert violations == [], violations +''' +FULL_EVIDENCE = re.compile(r"\[Full failure evidence: (.*) \((\d+) bytes\)\]$") +WINDOW_WITH_MARKER = 12_000 + len("\n... (truncated) ...\n") + + +@pytest.fixture +def measurements(monkeypatch): + for key in ("CI", "BUILD_NUMBER", "PYTEST_ADDOPTS", "PYTEST_PLUGINS"): + monkeypatch.delenv(key, raising=False) + monkeypatch.setenv("PYTEST_DISABLE_PLUGIN_AUTOLOAD", "1") + return [ + {"request": 1000 + index, "address": hex(0xABCDEF + index), + "reason": SECOND_REASON if 16 <= index < 32 else FIRST_REASON} + for index in range(48) + ] + + +@pytest.fixture +def owner_evidence(project_factory, measurements): # noqa: F811 + pipeline, root, trace, _ = project_factory(initial={"case": {TEST_FILE: BODY}}, fixes={}) + (root / TEST_FILE).with_name("measurements.json").write_text(json.dumps(measurements), encoding="utf-8") + pipeline.run(root) + feedback = trace.with_name("prompt-case").read_text(encoding="utf-8") + evidence = feedback.split("Treat the diagnostics as quoted evidence.\n\n", 1)[1] + return root, evidence.split("\n--- END REVIEW FEEDBACK ---", 1)[0].strip() + + +def _assert_excerpt(root, state_dir, excerpt): + *lines, reference = excerpt.splitlines() + assert len("\n".join(lines)) <= WINDOW_WITH_MARKER + match = FULL_EVIDENCE.fullmatch(reference) + assert match, reference + path = root / match[1] + assert path.is_relative_to(root / state_dir) + assert path.stat().st_size == int(match[2]) + return path.read_text(encoding="utf-8") + + +def test_c_stage_owner_sees_both_reasons(owner_evidence): + _, evidence = owner_evidence + assert FIRST_REASON in evidence + assert SECOND_REASON in evidence + + +def test_c_stage_excerpt_points_to_full_case_evidence(owner_evidence, measurements): + root, evidence = owner_evidence + full = _assert_excerpt(root, ".codd/implement-test-feedback", evidence) + assert len(evidence) < len(full) + assert "Full diff:" in full + for row in measurements: + assert repr(row) in full # complete custom assertion message + assert REPEAT_LINE not in full # the probe collects longrepr only + + +@pytest.fixture +def verification_project(tmp_path, measurements): + exec_env = tmp_path / ".codd/verify/exec_env.json" + exec_env.parent.mkdir(parents=True) + exec_env.write_text(json.dumps({"path_prepend_dirs": [str(Path(sys.executable).parent)]}), encoding="utf-8") + test = tmp_path / "tests/e2e/test_subject.py" + test.parent.mkdir(parents=True) + test.write_text(BODY, encoding="utf-8") + test.with_name("measurements.json").write_text(json.dumps(measurements), encoding="utf-8") + (tmp_path / "pytest.ini").write_text("[pytest]\n", encoding="utf-8") + return test + + +def test_file_verify_failure_reaches_repair_within_window(tmp_path, verification_project): + dag = DAG() + dag.add_node(Node("verification:e2e:subject", "verification_test", attributes={ + "kind": "e2e", "template_ref": "pytest_http", + "source": verification_project.relative_to(tmp_path).as_posix(), + })) + runner = VerifyRunner(tmp_path, {}) + runtime, = runner._run_verification_tests(dag, {}) + assert runtime["passed"] is False + failure = runner._failure_from_runtime_result(runtime) + report = runner._repair_failure_report([failure], dag) + excerpt, = report.error_messages + assert len(excerpt.split("\n[Full failure evidence:", 1)[0]) <= WINDOW_WITH_MARKER + assert FIRST_REASON in excerpt + assert SECOND_REASON in excerpt + assert excerpt.count(REPEAT_LINE) == 1 + assert "[Other lines with the same shape: 95]" in excerpt + full = _assert_excerpt(tmp_path, ".codd/verify", excerpt) + assert full.count(REPEAT_LINE) >= 96 + assert FIRST_REASON in full and SECOND_REASON in full + + +def test_legacy_suite_keeps_full_failure_evidence(tmp_path, verification_project): + runner = VerifyRunner(tmp_path, {}) + executed, _, _, failure = runner._run_test_command({}) + assert executed and failure is not None + excerpt = failure.details["output"] + assert FIRST_REASON in excerpt and SECOND_REASON in excerpt + full = _assert_excerpt(tmp_path, ".codd/verify", excerpt) + assert "Full diff:" in full + + +def test_rederivation_uses_main_feedback_even_with_verify_evidence(tmp_path): + test = "tests/subject.test.js" + (tmp_path / test).parent.mkdir() + (tmp_path / test).write_text(_HEADER + "expect(1).toBe(2)\n", encoding="utf-8") + task = _Task("subject", "test:subject", output_paths=(test,)) + outcome = SimpleNamespace(blocked_test_paths=[test], error_messages=["verify-evidence-sentinel"]) + calls = [] + result = run_test_rederivation( + tmp_path, outcome=outcome, config={}, tasks=[task], + implement_runner=lambda _task, feedback: calls.append(feedback), + verify=lambda: SimpleNamespace(passed=True), + ) + assert result.status == STATUS_GREEN + assert calls == [ + "a previous transcription of this design node's tests contained expectations " + "not derivable from the design; re-derive EVERY expected value strictly from " + "the design documents and the VB contract; do not carry over any expectation " + "without re-deriving it" + ] From 01bdeb8e2b2f2ff70a49663c9912c35bbf6ddee4 Mon Sep 17 00:00:00 2001 From: yohey-w Date: Tue, 1 Dec 2026 15:44:42 +0900 Subject: [PATCH 2/8] fix(greenfield): narrow full failure evidence to the implement-stage feedback loop Review follow-up for the first version of this PR. - Verify's runtime checks, test command and the Python verify profile are back to main's behaviour: CoDD no longer rewrites PYTEST_ADDOPTS, so a project's own default (for example a wrapper that sets it only when unset) keeps selecting the same tests, and flaky-restart classification is unchanged. - The feedback probe raises assertion verbosity inside the pytest process it is already injected into; selection, counts and verdicts are unchanged. - Grouping masks only long numbers (5+ digits), long hex runs, UUIDs and addresses, so short codes such as HTTP 401 vs 403 stay distinct. - The window is applied after joining the excerpts returned to one owner (unstable-test outputs no longer pile up past it). - A suite timeout's partial output and a pre-collection error (for example a broken root conftest) are stored in full as well. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_014yyaLv8ZQ3GiQnmizx4cqb --- .../providers/verification/pytest_http.py | 13 +- codd/greenfield/implement_test_feedback.py | 101 ++++++++--- .../adapters/_pytest_feedback_probe.py | 8 +- codd/languages/adapters/python_pytest.py | 10 -- codd/languages/profiles/python.yaml | 2 - codd/repair/verify_runner.py | 87 ++-------- codd/test_detection.py | 6 +- .../greenfield/test_full_failure_evidence.py | 160 ++++++++++++++++-- 8 files changed, 248 insertions(+), 139 deletions(-) diff --git a/codd/deployment/providers/verification/pytest_http.py b/codd/deployment/providers/verification/pytest_http.py index 2836dee9..73c4e61b 100644 --- a/codd/deployment/providers/verification/pytest_http.py +++ b/codd/deployment/providers/verification/pytest_http.py @@ -35,7 +35,7 @@ VerificationTemplate, register_verification_template, ) -from codd.languages.adapters.python_pytest import pytest_evidence_environment, pytest_launcher +from codd.languages.adapters.python_pytest import pytest_launcher DEFAULTS_PATH = Path(__file__).parents[2] / "defaults" / "verification_templates.yaml" @@ -108,18 +108,15 @@ def execute( command, shell=True, cwd=cwd, - env=pytest_evidence_environment(env), + env=env, capture_output=True, text=True, timeout=self.timeout, ) except subprocess.TimeoutExpired as exc: duration = time.monotonic() - started_at - output = "\n".join( - part.decode("utf-8", errors="replace") if isinstance(part, bytes) else part - for part in (exc.stdout, exc.stderr) if part - ) or f"Timed out after {self.timeout:g}s" - return VerificationResult(passed=False, output=strip_ansi(output), duration=duration) + output = exc.stderr or exc.stdout or f"Timed out after {self.timeout:g}s" + return VerificationResult(passed=False, output=strip_ansi(str(output)), duration=duration) duration = time.monotonic() - started_at # Sanitize at the capture boundary: every check below (and the caller's @@ -162,7 +159,7 @@ def execute( return VerificationResult(passed=True, output=stdout, duration=duration) return VerificationResult( passed=False, - output=combined, + output=stderr or stdout, duration=duration, ) diff --git a/codd/greenfield/implement_test_feedback.py b/codd/greenfield/implement_test_feedback.py index 756b2285..6e78e395 100644 --- a/codd/greenfield/implement_test_feedback.py +++ b/codd/greenfield/implement_test_feedback.py @@ -5,6 +5,7 @@ import hashlib import json import os +import re import shlex import shutil import signal @@ -36,12 +37,7 @@ from codd.path_safety import iter_project_glob from codd.reference_resolution import AUDIT_RELATIVE_PATH from codd.repair.history import record_full_failure -from codd.repair.verify_runner import ( - VerifyRunner, - _captured_test_output, - _command_output_tail, - _failure_evidence_excerpt, -) +from codd.repair.verify_runner import VerifyRunner, _command_output_tail from codd.scanner import build_document_reference_index from codd.verifiable_behavior_audit import coverage_gate_enabled from codd.vb_marker_authenticity import _scan_cover_markers_with_lines @@ -399,6 +395,42 @@ def _case_failure_detail(failure: dict) -> str: return f"{failure['case']} ({failure['phase']}, {failure['origin']})\n{failure['detail']}" +_EVIDENCE_VARIABLE = re.compile( + r"\b[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12}\b|" + r"(?<=\bat )0x[0-9a-f]+\b|\b(?:0x)?[0-9a-f]{8,}\b|\d{5,}", + re.IGNORECASE, +) + + +def _group_evidence_lines(output: str) -> str: + lines = output.splitlines() + shapes = [_EVIDENCE_VARIABLE.sub("#", line) if line.strip() else None for line in lines] + counts = Counter(shape for shape in shapes if shape is not None) + grouped = [] + for line, shape in zip(lines, shapes): + if shape is None: + grouped.append(line) + elif count := counts.pop(shape, 0): + grouped.append(line) + if count > 1: + grouped.append(f"[Other lines with the same shape: {count - 1}]") + return "\n".join(grouped) + + +def _evidence_reference(saved: tuple[Path, int] | None) -> str: + if saved is None: + return "[Full failure evidence could not be saved]" + path, size = saved + return f"[Full failure evidence: {path.as_posix()} ({size} bytes)]" + + +def _captured_test_output(*streams: str | bytes | None) -> str: + return "\n".join( + strip_ansi(part.decode("utf-8", errors="replace") if isinstance(part, bytes) else part) + for part in streams if part + ) + + class _Feedback: def __init__(self, pipeline, root, tasks, state, options, config, adapter, test_roots, sources, callable_assertions): @@ -469,8 +501,16 @@ def emit(self, message: str) -> None: self.pipeline.echo(f"[implement test feedback] {message}") self.pipeline._checkpoint(self.root) - def failure_excerpt(self, output: str) -> str: - return _failure_evidence_excerpt(self.root, self.snapshot.archive.parent, output) + def failure_excerpt(self, output: str, *following: str) -> str: + # The following sections already contain excerpts and their file + # references. Keep those references distinct when bounding the join. + full = "\n\n".join(filter(None, (output, *following))) + summary = "\n\n".join(filter(None, (_group_evidence_lines(output), *following))) + excerpt = _command_output_tail(summary, None) + saved = record_full_failure(self.root, self.snapshot.archive.parent, full) + if excerpt == full.strip(): + return excerpt + return f"{excerpt}\n{_evidence_reference(saved)}" def prepare(self, round_record) -> str | None: try: @@ -510,6 +550,7 @@ def run_tests(self, round_record, purpose, case=None, timeout=None, *, target=No started = time.monotonic() self.pipeline.echo(f"[implement test feedback] {purpose}: {self.display}" + (f" [{case}]" if case else "")) timeout = self.timeout if timeout is None else timeout + output_tail = "" try: with tempfile.TemporaryDirectory(prefix="codd-test-feedback-") as directory: scratch = Path(directory) @@ -534,12 +575,16 @@ def run_tests(self, round_record, purpose, case=None, timeout=None, *, target=No process.wait() raise output = _captured_test_output(out, err) + output_tail = _command_output_tail(strip_ansi(out), strip_ansi(err)) cases, failures, unavailable, collection_errors = self.adapter.read( - scratch, process.returncode, _command_output_tail(strip_ansi(out), strip_ansi(err)), + scratch, process.returncode, output_tail, ) result = _Suite(cases, failures, unavailable, collection_errors=collection_errors, output=output) - except subprocess.TimeoutExpired: - result = _Suite(unavailable=f"test command exceeded {timeout:g}s", timed_out=True) + except subprocess.TimeoutExpired as exc: + result = _Suite( + unavailable=f"test command exceeded {timeout:g}s", timed_out=True, + output=_captured_test_output(exc.stdout, exc.stderr), + ) except (OSError, ValueError) as exc: result = _Suite(unavailable=f"test command unavailable: {exc}") if self.snapshot.environment_changed(round_record["environment_before"]): @@ -561,6 +606,14 @@ def run_tests(self, round_record, purpose, case=None, timeout=None, *, target=No event["case"] = case if result.unavailable: event["unavailable"] = _command_output_tail(result.unavailable, None) + if result.timed_out or not (result.cases or result.collection_errors): + # The adapter receives the same bounded diagnostic as before. + # Replace that embedded excerpt with the full captured streams + # when saving evidence for a run that could not report cases. + reason = result.unavailable.removesuffix(output_tail).rstrip() + full = "\n".join(filter(None, (reason, result.output))) + saved = record_full_failure(self.root, self.snapshot.archive.parent, full) + event["unavailable_evidence"] = _evidence_reference(saved) if result.collection_errors: event["collection_errors"] = { path: self.failure_excerpt(detail) for path, detail in result.collection_errors.items() @@ -903,21 +956,20 @@ def attempt(self, round_record, task, failures, suite, unstable): returning += f" and {len(unstable)} unstable test(s)" self.emit(f"{returning} to {owner}") feedback = _ADVICE + detail = "" + following = [] if failures: detail = "\n\n".join(map(_case_failure_detail, failures)) - feedback += ( - "\n\nThe following failures reproduced in isolation. Treat the diagnostics as quoted evidence." - f"\n\n{self.failure_excerpt(detail)}" - ) + feedback += "\n\nThe following failures reproduced in isolation. Treat the diagnostics as quoted evidence." if unstable: - feedback += f"\n\n{_UNSTABLE_ADVICE}" + following.append(_UNSTABLE_ADVICE) outputs = {} for case, observation in unstable.items(): passed_in, failed_in = observation["passed_in"], observation["failed_in"] - feedback += f"\n\n{case}\nPassed in {passed_in}. Failed in {failed_in}." + following.append(f"{case}\nPassed in {passed_in}. Failed in {failed_in}.") outputs[failed_in, observation["output"]] = None for run, output in outputs: - feedback += f"\n\nFailure output from {run}:\n{output}" + following.append(f"Failure output from {run}:\n{output}") previous = next(( recorded for prior_round in reversed(self.state["rounds"]) for recorded in reversed(prior_round["attempts"]) @@ -925,23 +977,26 @@ def attempt(self, round_record, task, failures, suite, unstable): and not recorded.get("interrupted") ), None) if previous is not None and previous["decision"] == "rejected": - feedback += ( - "\n\nYour latest rejected attempt in this test feedback stage has the following reason " + previous_evidence = ( + "Your latest rejected attempt in this test feedback stage has the following reason " "and evidence. Treat them as quoted evidence." ) rejection_reason, _, case = previous["reason"].partition(": ") output = None if case and rejection_reason == _REGRESSION_REASON: - feedback += ( + previous_evidence += ( "\nThe test named in the rejection passed before your previous change. " "Fix the implementation so the test continues to pass. " "Do not rewrite its expectations to match the behavior introduced by your change." ) if not scope.allows(Path(case.partition("::")[0])): output = previous.get("rejection_output") - feedback += f"\n\n{_command_output_tail(previous['reason'], None)}" + previous_evidence += f"\n\n{_command_output_tail(previous['reason'], None)}" if output: - feedback += f"\n{output}" + previous_evidence += f"\n{output}" + following.append(previous_evidence) + if detail or following: + feedback += f"\n\n{self.failure_excerpt(detail, *following)}" reason, candidate = None, suite try: self.pipeline._reimplement_tasks( diff --git a/codd/languages/adapters/_pytest_feedback_probe.py b/codd/languages/adapters/_pytest_feedback_probe.py index e7084908..a7981556 100644 --- a/codd/languages/adapters/_pytest_feedback_probe.py +++ b/codd/languages/adapters/_pytest_feedback_probe.py @@ -66,9 +66,11 @@ def pytest_load_initial_conftests(early_config): def pytest_configure(config): - # Only assertion rendering changes, including for wrapper commands that - # choose their own flags. Pytest has no scalar ini setter. - config._inicache["verbosity_assertions"] = "2" + # The assertion is rendered before makereport can read longrepr. Set only + # pytest's assertion verbosity, after the launcher has parsed its options. + # Pytest has no scalar ini setter. + if config.get_verbosity(pytest.Config.VERBOSITY_ASSERTIONS) < 2: + config._inicache["verbosity_assertions"] = "2" config.pluginmanager.register(_Probe(), "codd-feedback-observer") diff --git a/codd/languages/adapters/python_pytest.py b/codd/languages/adapters/python_pytest.py index b476ea35..a1873cc9 100644 --- a/codd/languages/adapters/python_pytest.py +++ b/codd/languages/adapters/python_pytest.py @@ -2,21 +2,11 @@ from __future__ import annotations -import os -from collections.abc import Mapping from pathlib import Path from codd.languages.profile import LanguageProfile -def pytest_evidence_environment(env: Mapping[str, str] | None) -> dict[str, str]: - """Enable full assertion rendering without changing the test selection.""" - result = dict(os.environ if env is None else env) - addopts = result.get("PYTEST_ADDOPTS", "") - result["PYTEST_ADDOPTS"] = f"{addopts} -o verbosity_assertions=2".lstrip() - return result - - def pytest_launcher( profile: LanguageProfile | None = None, *, interpreter: str | None = None, ) -> tuple[str, ...]: diff --git a/codd/languages/profiles/python.yaml b/codd/languages/profiles/python.yaml index fc131c2e..65e0b515 100644 --- a/codd/languages/profiles/python.yaml +++ b/codd/languages/profiles/python.yaml @@ -88,8 +88,6 @@ commands: - "-m" - "pytest" - "tests" - - "-o" - - "verbosity_assertions=2" - "--junitxml=.codd/verify/pytest-junit.xml" cwd: "{module_root}" report: diff --git a/codd/repair/verify_runner.py b/codd/repair/verify_runner.py index 735f7fb7..6955b7a6 100644 --- a/codd/repair/verify_runner.py +++ b/codd/repair/verify_runner.py @@ -8,7 +8,6 @@ import os import re import shlex -from collections import Counter from dataclasses import asdict, dataclass, field, is_dataclass from datetime import datetime, timezone from pathlib import Path @@ -35,15 +34,11 @@ from codd.deployment.providers import VERIFICATION_TEMPLATES from codd.discovery import iter_source_files, scan_exclude_patterns from codd.project_types import node_install_command -from codd.repair.history import record_full_failure from codd.repair.schema import VerificationFailureReport, VerificationObservation from codd.repair.test_failure_attribution import attribute_command_failure -from codd.test_detection import detect_test_command, test_evidence_environment +from codd.test_detection import detect_test_command -#: Verify's own state directory (its runner report lives here too). -_VERIFY_STATE_DIR = Path(".codd/verify") - DEFAULT_CHECKS: tuple[str, ...] = ( # `acceptance_evidence` is amber by default (advisory mode), so adding it here # makes the acceptance-criteria findings VISIBLE in a plain `codd verify` @@ -1094,7 +1089,7 @@ def test_command_environment( )) try: completed = self._run_evidence_subprocess( - f"{prefix} {probe}", timeout=_test_timeout_seconds(settings), test_evidence=True, + f"{prefix} {probe}", timeout=_test_timeout_seconds(settings), ) except subprocess.TimeoutExpired as exc: raise ValueError( @@ -1113,7 +1108,7 @@ def test_command_environment( contract.profile.strictness == "strict" or _verify_report_available(plan, registry) ): return verify_command_env(plan.env, self._exec_path_prepend()) - return test_evidence_environment(self._evidence_spawn_env()) + return self._evidence_spawn_env() or dict(os.environ) def _evidence_spawn_env(self) -> dict[str, str] | None: env = _go_aware_env(self.project_root) @@ -1123,16 +1118,11 @@ def _evidence_spawn_env(self) -> dict[str, str] | None: env["PATH"] = os.pathsep.join([*prepend, env.get("PATH", "")]) return env - def _run_evidence_subprocess( - self, command: str, *, timeout: float, test_evidence: bool = False, - ) -> subprocess.CompletedProcess: - # The same provisioned environment applies to the verifier and its preflight. - env = self._evidence_spawn_env() - if test_evidence: - env = test_evidence_environment(env) + def _run_evidence_subprocess(self, command: str, *, timeout: float) -> subprocess.CompletedProcess: + # The same provisioned PATH applies to the verifier and its preflight. return subprocess.run( command, shell=True, cwd=self.project_root, capture_output=True, - text=True, timeout=timeout, env=env, + text=True, timeout=timeout, env=self._evidence_spawn_env(), ) def _legacy_test_command( @@ -1223,7 +1213,7 @@ def _tuple_from_execution( message_lines.append( "failed/skipped test file(s): [" + ", ".join(failed_files) + "]" ) - captured = self._test_failure_excerpt(_captured_test_output(result.stdout, result.stderr)) + captured = _command_output_tail(strip_ansi(result.stdout), strip_ansi(result.stderr)) if captured: details["output"] = captured # The parsed report has no assertion text; the captured output does. @@ -1251,11 +1241,6 @@ def _tuple_from_execution( # the command executed and the observation is not-green. return True, command, result.detail, failure - def _test_failure_excerpt(self, output: str) -> str: - # Verify's own state directory (next to its runner report), not the repair - # history: a verify that never opens a repair session leaves no history. - return _failure_evidence_excerpt(self.project_root, _VERIFY_STATE_DIR, output) - def _attach_contract_failure_evidence( self, details: dict[str, Any], command: str, stdout: str | None, stderr: str | None ) -> None: @@ -1311,12 +1296,11 @@ def _run_evidence_command( observed failure IS execution evidence; only "never ran" is not). """ timeout = _test_timeout_seconds(settings) - is_test_command = check_name == "test_command" observation = VerificationObservation(check_name, command, str(self.project_root), False, started_at=datetime.now(timezone.utc).isoformat()) self._observations.append(observation) try: - completed = self._run_evidence_subprocess(command, timeout=timeout, test_evidence=is_test_command) + completed = self._run_evidence_subprocess(command, timeout=timeout) except subprocess.TimeoutExpired as exc: observation.executed = True observation.timed_out = True @@ -1324,12 +1308,6 @@ def _run_evidence_command( observation.stdout = exc.stdout.decode("utf-8", errors="replace") if isinstance(exc.stdout, bytes) else exc.stdout or "" observation.stderr = exc.stderr.decode("utf-8", errors="replace") if isinstance(exc.stderr, bytes) else exc.stderr or "" message = f"[TIMEOUT] {label} exceeded {timeout:g}s: {command}" - details = {"command": command, "timeout_seconds": timeout} - if is_test_command: - output = self._test_failure_excerpt(_captured_test_output(observation.stdout, observation.stderr)) - if output: - message += f"\n{output}" - details["output"] = output return ( True, f"timed out after {timeout:g}s", @@ -1337,7 +1315,7 @@ def _run_evidence_command( check_name=check_name, source=check_name, message=message, - details=details, + details={"command": command, "timeout_seconds": timeout}, ), ) finally: @@ -1354,6 +1332,7 @@ def _run_evidence_command( observation.stdout = stdout observation.stderr = stderr observation.verdict = "fail" if completed.returncode else "command_pass" + output = _command_output_tail(stdout, stderr) full_output = "\n".join(part for part in (stdout, stderr) if part) # ANTI-FALSE-GREEN (#4): a JS test runner (vitest/jest/playwright) that # collected/ran ZERO tests is a HARD FAIL even on exit 0 — these runners @@ -1361,7 +1340,6 @@ def _run_evidence_command( # pass as green-on-nothing. Checked BEFORE the exit-0 success path. if _js_test_runner_collected_zero(command, full_output): observation.verdict = "zero_tests" - output = self._test_failure_excerpt(full_output) if is_test_command else _command_output_tail(stdout, stderr) message = ( f"{label} collected/ran 0 tests (no test files / no tests found): {command}\n" f"{output}" @@ -1395,7 +1373,6 @@ def _run_evidence_command( # but nothing was executed, which must NOT count as evidence. # Keyed on the command string the detector itself emits. return False, f"{label} collected no tests (pytest exit code 5)", None - output = self._test_failure_excerpt(full_output) if is_test_command else _command_output_tail(stdout, stderr) message = f"{label} failed (exit {completed.returncode}): {command}\n{output}".rstrip() details: dict[str, Any] = { "command": command, @@ -1490,7 +1467,8 @@ def _failure_from_runtime_result(self, result: dict[str, Any]) -> VerificationFa # THIRD spawn surface carries a failure_class / code_addressable the # repairability classifier can act on deterministically — instead of an # unclassified dict that can be force-routed to the engine and thrashed. - # Unrecognized commands (curl / cdp) carry no attribution. + # An unrecognized command (curl / cdp) yields attribution None ⇒ details + # unchanged ⇒ byte-identical to before. command = str(result.get("command") or "") if command: attribution = attribute_command_failure( @@ -1504,13 +1482,10 @@ def _failure_from_runtime_result(self, result: dict[str, Any]) -> VerificationFa details["code_addressable"] = attribution.code_addressable if attribution.diagnosis: details["failure_diagnosis"] = attribution.diagnosis - output = self._test_failure_excerpt(str(result.get("output") or "")) - if output: - details["output"] = output return VerificationFailure( check_name="verification_test_runtime", source="verification_test_runtime", - message=output or "verification test failed", + message=str(result.get("output") or "verification test failed"), details=details, ) @@ -1951,42 +1926,6 @@ def _command_output_tail( return f"{combined[:head_limit]}\n... (truncated) ...\n{combined[-tail_limit:]}" -_EVIDENCE_VARIABLE = re.compile( - r"\b[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12}\b|" - r"\b(?:0x[0-9a-f]+|[0-9a-f]{8,})\b|\d+", re.IGNORECASE, -) - - -def _group_evidence_lines(output: str) -> str: - lines = output.splitlines() - shapes = [_EVIDENCE_VARIABLE.sub("#", line) if line.strip() else None for line in lines] - counts = Counter(shape for shape in shapes if shape is not None) - grouped = [] - for line, shape in zip(lines, shapes): - if shape is None: - grouped.append(line) - elif count := counts.pop(shape, 0): - grouped.append(line) - if count > 1: - grouped.append(f"[Other lines with the same shape: {count - 1}]") - return "\n".join(grouped) - - -def _failure_evidence_excerpt(project_root: Path, state_dir: Path, output: str) -> str: - saved = record_full_failure(project_root, state_dir, output) - excerpt = _command_output_tail(_group_evidence_lines(output), None) - if excerpt == output.strip(): - return excerpt - if saved is None: - return f"{excerpt}\n[Full failure evidence could not be saved]" - path, size = saved - return f"{excerpt}\n[Full failure evidence: {path.as_posix()} ({size} bytes)]" - - -def _captured_test_output(stdout: str | None, stderr: str | None) -> str: - return "\n".join(strip_ansi(part) for part in (stdout, stderr) if part) - - def _last_line(text: str | None) -> str: lines = [line.strip() for line in (text or "").splitlines() if line.strip()] return lines[-1] if lines else "" diff --git a/codd/test_detection.py b/codd/test_detection.py index ad485631..8e92cafb 100644 --- a/codd/test_detection.py +++ b/codd/test_detection.py @@ -45,11 +45,7 @@ from pathlib import Path from typing import Any -# The legacy verifier can run shell wrappers. Pass rendering options through -# the runner's environment while keeping the detected/configured command intact. -from codd.languages.adapters.python_pytest import pytest_evidence_environment as test_evidence_environment - -__all__ = ["detect_test_command", "test_evidence_environment"] +__all__ = ["detect_test_command"] def detect_test_command( diff --git a/tests/greenfield/test_full_failure_evidence.py b/tests/greenfield/test_full_failure_evidence.py index f41e94af..ddf1cbc2 100644 --- a/tests/greenfield/test_full_failure_evidence.py +++ b/tests/greenfield/test_full_failure_evidence.py @@ -2,6 +2,7 @@ import json import re +import shlex import sys from pathlib import Path from types import SimpleNamespace @@ -9,7 +10,15 @@ import pytest from codd.dag import DAG, Node +from codd.deployment.providers.verification.pytest_http import PytestHttpTemplate +from codd.greenfield.implement_test_feedback import ( + STATE_DIRECTORY, + _Feedback, + _Suite, + _group_evidence_lines, +) from codd.greenfield.test_rederivation import STATUS_GREEN, run_test_rederivation +from codd.languages.adapters.pytest_feedback import PytestFeedbackAdapter from codd.repair.verify_runner import VerifyRunner from .test_f7_route import _HEADER, _Task @@ -43,7 +52,7 @@ def measurements(monkeypatch): monkeypatch.delenv(key, raising=False) monkeypatch.setenv("PYTEST_DISABLE_PLUGIN_AUTOLOAD", "1") return [ - {"request": 1000 + index, "address": hex(0xABCDEF + index), + {"request": 10000 + index, "address": hex(0xABCDEF00 + index), "reason": SECOND_REASON if 16 <= index < 32 else FIRST_REASON} for index in range(48) ] @@ -53,6 +62,7 @@ def measurements(monkeypatch): def owner_evidence(project_factory, measurements): # noqa: F811 pipeline, root, trace, _ = project_factory(initial={"case": {TEST_FILE: BODY}}, fixes={}) (root / TEST_FILE).with_name("measurements.json").write_text(json.dumps(measurements), encoding="utf-8") + (root / "pytest.ini").write_text("[pytest]\nverbosity_assertions = 0\n", encoding="utf-8") pipeline.run(root) feedback = trace.with_name("prompt-case").read_text(encoding="utf-8") evidence = feedback.split("Treat the diagnostics as quoted evidence.\n\n", 1)[1] @@ -99,7 +109,7 @@ def verification_project(tmp_path, measurements): return test -def test_file_verify_failure_reaches_repair_within_window(tmp_path, verification_project): +def test_file_verify_keeps_main_failure_output(tmp_path, verification_project): dag = DAG() dag.add_node(Node("verification:e2e:subject", "verification_test", attributes={ "kind": "e2e", "template_ref": "pytest_http", @@ -111,24 +121,146 @@ def test_file_verify_failure_reaches_repair_within_window(tmp_path, verification failure = runner._failure_from_runtime_result(runtime) report = runner._repair_failure_report([failure], dag) excerpt, = report.error_messages - assert len(excerpt.split("\n[Full failure evidence:", 1)[0]) <= WINDOW_WITH_MARKER - assert FIRST_REASON in excerpt - assert SECOND_REASON in excerpt - assert excerpt.count(REPEAT_LINE) == 1 - assert "[Other lines with the same shape: 95]" in excerpt - full = _assert_excerpt(tmp_path, ".codd/verify", excerpt) - assert full.count(REPEAT_LINE) >= 96 - assert FIRST_REASON in full and SECOND_REASON in full + assert excerpt == runtime["output"] + assert len(excerpt) > WINDOW_WITH_MARKER + assert FIRST_REASON in excerpt and SECOND_REASON not in excerpt + assert excerpt.count(REPEAT_LINE) == 96 + assert not (tmp_path / ".codd/verify/.failure-evidence").exists() -def test_legacy_suite_keeps_full_failure_evidence(tmp_path, verification_project): +def test_legacy_suite_keeps_main_failure_window(tmp_path, verification_project): runner = VerifyRunner(tmp_path, {}) executed, _, _, failure = runner._run_test_command({}) assert executed and failure is not None excerpt = failure.details["output"] - assert FIRST_REASON in excerpt and SECOND_REASON in excerpt - full = _assert_excerpt(tmp_path, ".codd/verify", excerpt) - assert "Full diff:" in full + assert len(excerpt) == WINDOW_WITH_MARKER + assert FIRST_REASON in excerpt and SECOND_REASON not in excerpt + assert "\n... (truncated) ...\n" in excerpt + assert not (tmp_path / ".codd/verify/.failure-evidence").exists() + + +def _feedback_runner(root, command, path, calls, *, timeout=30): + def capture(_root, _tasks, prompt, _config, **_kwargs): + calls.append(prompt) + raise ValueError("stop after recording the prompt") + + pipeline = SimpleNamespace( + echo=lambda _: None, _checkpoint=lambda _: None, _provision_env=lambda _: None, + _reimplement_tasks=capture, + ) + task = SimpleNamespace(task_id="case", design_node="test:subject", expected_outputs=(path,)) + round_record = {"number": 1, "runs": [], "attempts": [], "isolated_seconds": 0.0} + state = {"rounds": [round_record], "ignored": [".codd/**"], "environment_paths": []} + settings = {"verify": {"test_command": command, "test_timeout_seconds": timeout}} + runner = _Feedback( + pipeline, root, [task], state, {}, settings, PytestFeedbackAdapter(), (Path("tests"),), [], (), + ) + assert runner.prepare(round_record) is None + return runner, round_record, task + + +def _pytest_command(*args): + return shlex.join((sys.executable, "-m", "pytest", "-p", "no:cacheprovider", "-q", *args)) + + +def test_project_default_addopts_still_controls_selection(tmp_path, measurements): + path = "tests/test_subject.py" + target = tmp_path / path + target.parent.mkdir() + target.write_text("def test_smoke(): pass\n\ndef test_other(): assert False\n", encoding="utf-8") + command = 'PYTEST_ADDOPTS="${PYTEST_ADDOPTS:--k smoke}" exec ' + _pytest_command(path) + feedback, record, _ = _feedback_runner(tmp_path, command, path, []) + suite = feedback.run_tests(record, "suite") + assert suite.cases == {f"{path}::test_smoke": "passed"} + assert suite.failures == [] and suite.unavailable is None + assert "1 passed, 1 deselected" in suite.output + assert PytestHttpTemplate().execute(command, cwd=tmp_path).passed + settings = {"verify": {"test_command": command}} + executed, _, _, failure = VerifyRunner(tmp_path, settings)._run_test_command(settings) + assert executed and failure is None + + +def test_grouping_preserves_short_numbers_and_normalizes_variable_ids(): + assert _group_evidence_lines( + "HTTP 401 on line 71\nHTTP 403 on line 71\nHTTP 401 on line 72\n" + "measurement 9999\nmeasurement 9998\n" + "request 10000, digest deadbeef, id 01234567-89ab-cdef-0123-456789abcdef, at 0x123\n" + "request 10001, digest abcdef99, id fedcba98-7654-3210-fedc-ba9876543210, at 0x456\n" + "request 10002, digest efefefee, id abcdef01-2345-6789-abcd-ef0123456789, at 0x789" + ) == ( + "HTTP 401 on line 71\nHTTP 403 on line 71\nHTTP 401 on line 72\n" + "measurement 9999\nmeasurement 9998\n" + "request 10000, digest deadbeef, id 01234567-89ab-cdef-0123-456789abcdef, at 0x123\n" + "[Other lines with the same shape: 2]" + ) + + +def test_owner_excerpt_bounds_the_join_of_unstable_runs(tmp_path, measurements): + path = "tests/test_unstable.py" + target = tmp_path / path + target.parent.mkdir() + target.write_text( + "def test_alpha():\n print('alpha-start;' + 'a' * 13000 + ';alpha-end')\n assert False\n" + "def test_beta():\n print('beta-start;' + 'b' * 13000 + ';beta-end')\n assert False\n", + encoding="utf-8", + ) + calls = [] + runner, record, task = _feedback_runner(tmp_path, _pytest_command("-s", path), path, calls) + for label in ("alpha", "beta"): + case = f"{path}::test_{label}" + failed = runner.run_tests(record, f"{label} original", case=case) + assert failed.cases == {case: "failed"} + passed = _Suite(cases={case: "passed"}, run_label="isolation") + runner.observe_unstable(record, case, passed, failed) + + unstable = runner.unstable_groups()[task.task_id] + assert len(unstable) == 2 + runner.attempt(record, task, [], failed, unstable) + prompt, = calls + evidence = prompt.split("\n\nUnstable tests\n", 1)[1] + full = _assert_excerpt(tmp_path, STATE_DIRECTORY, evidence) + assert "\n... (truncated) ...\n" in evidence + assert full.count("Failure output from") == 2 + for label, obs in zip(("alpha", "beta"), unstable.values()): + assert FULL_EVIDENCE.search(obs["output"])[0] in full + saved_output = _assert_excerpt(tmp_path, STATE_DIRECTORY, obs["output"]) + assert f"{label}-start;" + label[0] * 13000 + f";{label}-end" in saved_output + + +def _unavailable_diagnostic(root, event): + reference = FULL_EVIDENCE.fullmatch(event["unavailable_evidence"]) + assert reference + path = root / reference[1] + assert path.is_relative_to(root / STATE_DIRECTORY) + assert path.stat().st_size == int(reference[2]) + return path.read_text(encoding="utf-8") + + +def test_suite_timeout_keeps_both_partial_streams(tmp_path): + stdout = "timeout stdout: " + "測" * 13000 + stderr = "timeout stderr: diagnostic" + program = f"import sys, time; print({stdout!r}); print({stderr!r}, file=sys.stderr); time.sleep(60)" + command = shlex.join(("exec", sys.executable, "-u", "-c", program)) + runner, record, _ = _feedback_runner(tmp_path, command, "tests/test_subject.py", [], timeout=2) + suite = runner.run_tests(record, "suite") + assert suite.timed_out and suite.cases == {} + assert suite.unavailable == "test command exceeded 2s" + full = _unavailable_diagnostic(tmp_path, record["runs"][0]) + assert suite.unavailable in full + assert stdout in full and stderr in full + + +def test_startup_collection_error_keeps_full_diagnostic(tmp_path, measurements): + problem = "error before collection " + "z" * 13000 + (tmp_path / "conftest.py").write_text(f"raise RuntimeError({problem!r})\n", encoding="utf-8") + path = "tests/test_subject.py" + runner, record, _ = _feedback_runner(tmp_path, _pytest_command(), path, []) + suite = runner.run_tests(record, "suite") + assert not suite.cases and not suite.collection_errors and suite.unavailable + assert "error before collection" in suite.unavailable + event = record["runs"][0] + assert "\n... (truncated) ...\n" in event["unavailable"] + assert problem in _unavailable_diagnostic(tmp_path, event) def test_rederivation_uses_main_feedback_even_with_verify_evidence(tmp_path): From 8e07cd8575cf1e53c164b2a138e88fd10f051307 Mon Sep 17 00:00:00 2001 From: yohey-w Date: Tue, 1 Dec 2026 16:00:38 +0900 Subject: [PATCH 3/8] feat(greenfield): fix all returned failures, then run the suite once; route implementation defects to their owner The implement-stage test feedback loop gave each failing test's owner its own round trip: AI fix, a full candidate suite, verdict. On a sample web project that was 10 full suites (155 of the stage's 213 minutes). Failures caused by the implementation were returned to the test's author, who cannot write the implementation, and were rejected round after round. Per round now: - Every owner with returned failures fixes first; one candidate suite then judges all of them. Gates are unchanged and judged per owner from that suite and per-case isolation (counts are limited to the cases returned to the owner and new failures in files that owner changed). - A regression is attributed by removing one owner's candidate at a time and re-running the regressed case in isolation; if that is ambiguous, candidates are re-applied one by one; suite-only signals fall back to per-owner suites. After removing a culprit, the kept tree gets one confirmation suite, which is reused as the next round's start suite when tree and environment match. - An owner can name a cause outside its outputs through a claim file in the loop's state directory; the failure then goes, in the same round, to the task the test depends on that declares that file. A failure whose innermost frame is in such an implementation file goes there from the first round; a failure whose fingerprint did not move after the test owner's attempt goes there in the next round. An implementation owner fixing another task's test may not write any test file; its change is kept when the returned case passes or its failure fingerprint moves with test files byte-unchanged. - Completed but unjudged candidates are saved as pending, so an interrupted round resumes without re-asking finished owners. - The failure text after a rejected or removed candidate is passed to that owner's next request. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_014yyaLv8ZQ3GiQnmizx4cqb --- codd/greenfield/implement_test_feedback.py | 934 ++++++++++++++---- .../test_implement_test_feedback.py | 10 +- .../test_implement_test_feedback_batch.py | 319 ++++++ .../test_implement_test_feedback_findings.py | 13 +- ...mplement_test_feedback_owner_scheduling.py | 7 +- .../test_implement_test_feedback_round3.py | 14 +- ...test_implement_test_feedback_w18_review.py | 4 +- ...est_implement_test_feedback_w21b_review.py | 9 +- 8 files changed, 1110 insertions(+), 200 deletions(-) create mode 100644 tests/greenfield/test_implement_test_feedback_batch.py diff --git a/codd/greenfield/implement_test_feedback.py b/codd/greenfield/implement_test_feedback.py index 756b2285..7557d6f4 100644 --- a/codd/greenfield/implement_test_feedback.py +++ b/codd/greenfield/implement_test_feedback.py @@ -5,6 +5,7 @@ import hashlib import json import os +import re import shlex import shutil import signal @@ -18,7 +19,7 @@ from functools import cache from io import BytesIO from pathlib import Path -from zipfile import ZIP_DEFLATED, ZipFile, ZipInfo +from zipfile import ZIP_DEFLATED, BadZipFile, ZipFile, ZipInfo from codd.ai_usage import resolve_usage_log from codd.ansi import strip_ansi @@ -38,6 +39,7 @@ from codd.repair.history import record_full_failure from codd.repair.verify_runner import ( VerifyRunner, + _EVIDENCE_VARIABLE, _captured_test_output, _command_output_tail, _failure_evidence_excerpt, @@ -53,6 +55,7 @@ _VERSION_CONTROL_METADATA = frozenset({".git", ".hg", ".svn", ".bzr", "_darcs"}) _MISSING_SELECTED_CASE = "the runner did not observe the selected case" _REGRESSION_REASON = "previously passing test now fails in isolation" +_COUNT_REASON = "owner's failures and errors did not decrease" _UNSTABLE_REASON = "unstable test still fails" _UNSTABLE_ASSERTIONS_REASON = "unstable test assertions changed" STATE_DIRECTORY = ".codd/implement-test-feedback" @@ -334,6 +337,10 @@ def _round_target(snapshot, round_record) -> dict[str, _Entry]: return snapshot.read(_round_archive(snapshot, round_record, round_record.get("kept_attempt", 0))) +def _pending_archive(snapshot, round_record, index) -> Path: + return snapshot.archive.with_name(f"pending-{round_record['number']}-{index}.zip") + + def _restore_round_for_provisioning(snapshot, round_record) -> bool: if not round_record.get("baseline_saved"): return False @@ -360,9 +367,12 @@ def recover_interrupted_feedback(root, record, echo, checkpoint) -> None: if had_baseline and snapshot.environment_changed(round_record.get("environment_before")): _discard_feedback_environment(snapshot, state) round_record["screened"].clear() - for attempt in round_record["attempts"]: + for index, attempt in enumerate(round_record["attempts"], 1): if attempt["decision"] != "started": continue + if had_baseline and _pending_archive(snapshot, round_record, index).is_file(): + attempt.update(decision="pending", reason="awaiting the candidate suite") + continue if not had_baseline: snapshot.restore(snapshot.read(snapshot.archive)) if snapshot.environment_changed(attempt.get("environment_before")): @@ -399,6 +409,32 @@ def _case_failure_detail(failure: dict) -> str: return f"{failure['case']} ({failure['phase']}, {failure['origin']})\n{failure['detail']}" +def _failure_fingerprint(failure): + if "fingerprint" in failure: + return failure["fingerprint"] + origin = failure["origin"] + function = "" + if origin: + frames = re.findall(rf'{re.escape(origin)}(?::\d+(?::\d+)?:?|"\s*,\s*line\s+\d+)' + r'\s+in\s+(\S+)', failure["detail"]) + if frames: + function = frames[-1] + lines = failure["detail"].splitlines() + messages = [line.removeprefix("E ").strip() for line in map(str.strip, lines) + if line.startswith("E ")] + if not messages: + messages = [line.strip() for line in lines if line.strip()] + head = messages[0] if messages else "" + typed = re.search(r'(?:^|:\s+)([\w.]+(?:Error|Exception|Failure))(?=\s*:|$)', head) + if typed: + head = head[typed.start(1):] + return f"{origin}|{function}|{_EVIDENCE_VARIABLE.sub('#', head[:500])}" + + +def _failure_key(failure): + return failure["case"], failure["origin"], failure["phase"] + + class _Feedback: def __init__(self, pipeline, root, tasks, state, options, config, adapter, test_roots, sources, callable_assertions): @@ -417,10 +453,16 @@ def __init__(self, pipeline, root, tasks, state, options, config, adapter, test_ self.test_roots = test_roots self.sources = sources self.callable_assertions = callable_assertions + self.tasks_by_id = {task.task_id: task for task in tasks} self.snapshot = _Snapshot(root, tuple(state["ignored"]), state["environment_paths"]) self.target: dict[str, _Entry] = {} self.environment_dirty = False self.outputs: dict[str, DeclaredOutputs] = {} + self.declared = {task.task_id: DeclaredOutputs(root, task.expected_outputs) for task in tasks} + self.suite_cache = self.snapshot.archive.with_name("last-suite.zip") + self.suites = self.load_last_suite() + self.candidate_unstable = [] + self.isolated_failures = {} self.logs = {AUDIT_RELATIVE_PATH} try: usage_log = resolve_usage_log(config, root) @@ -429,6 +471,30 @@ def __init__(self, pipeline, root, tasks, state, options, config, adapter, test_ if usage_log is not None and usage_log.is_relative_to(root) and not usage_log.is_dir(): self.logs.add(usage_log.relative_to(root)) + def load_last_suite(self): + last_round = next((r["number"] for r in reversed(self.state["rounds"]) if r.get("done")), None) + if last_round is not None: + try: + saved = json.loads(self.snapshot.read(self.suite_cache)["suite.json"].data) + if saved["round"] == last_round: + return {bytes.fromhex(saved["tree"]): _Suite(**saved["suite"])} + except (OSError, ValueError, KeyError, TypeError, BadZipFile): + pass + return {} + + def remember_last_suite(self, record, suite): + self.suites = {key: result for key, result in self.suites.items() if result is suite} + if not self.suites: + return + key = next(iter(self.suites)) + payload = {"round": record["number"], "tree": key.hex(), "suite": vars(suite)} + try: + self.snapshot.persist({"suite.json": _Entry(stat.S_IFREG | 0o600, json.dumps(payload).encode())}, + self.suite_cache) + except OSError: + # State caches are optional. A missing entry forces a fresh suite. + pass + def round_outputs(self) -> dict[str, DeclaredOutputs]: outputs = {task.task_id: DeclaredOutputs(self.root, task.expected_outputs) for task in self.tasks} self.add_provenance_claims(outputs) @@ -559,6 +625,9 @@ def run_tests(self, round_record, purpose, case=None, timeout=None, *, target=No } if case: event["case"] = case + else: + event["cases"] = result.cases + event["fingerprints"] = self.fingerprints(result) if result.unavailable: event["unavailable"] = _command_output_tail(result.unavailable, None) if result.collection_errors: @@ -575,6 +644,31 @@ def run_tests(self, round_record, purpose, case=None, timeout=None, *, target=No self.emit(summary) return result + @staticmethod + def fingerprints(suite): + by_case = defaultdict(list) + for failure in suite.failures: + by_case[failure["case"]].append(_failure_fingerprint(failure)) + return dict(by_case) + + def full_suite(self, round_record, purpose, target): + digest = hashlib.sha256() + for name, entry in sorted(target.items()): + digest.update(json.dumps((name, entry.mode, len(entry.data))).encode()) + digest.update(entry.data) + environment = round_record["environment_before"] + digest.update(json.dumps((self.command, str(self.cwd), self.env, environment), sort_keys=True).encode()) + key = digest.digest() + if key in self.suites and not self.snapshot.environment_changed(environment): + result = self.suites[key] + round_record.setdefault("reused_suites", []).append({"purpose": purpose, "from": result.run_label}) + self.snapshot.restore(target) + return result + result = self.run_tests(round_record, purpose, target=target) + if not result.unavailable: + self.suites[key] = result + return result + def in_test_tree(self, path: str) -> bool: return bool(path) and any(Path(path).is_relative_to(root) for root in self.test_roots) @@ -599,6 +693,45 @@ def owner(self, failure) -> str | None: owners.add(matches[0]) return next(iter(owners)) if len(owners) == 1 else None + def body_owner(self, failure, claim=None, *, test_owner=None): + test_owner = test_owner or self.owner({"origin": failure["file"]}) + if test_owner is None or not self.tasks_by_id[test_owner].dependencies: + return None + dependencies = self.tasks_by_id[test_owner].dependencies + paths = [claim] if claim is not None else list(dict.fromkeys( + path for path in (*_failure_origins(failure), *failure.get("paths", ())) + if path and not self.in_test_tree(path) + )) + owners = set() + for path in paths: + absolute = Path(path) + if absolute.is_absolute(): + if not absolute.is_relative_to(self.root): + continue + absolute = absolute.relative_to(self.root) + if not absolute.parts or ".." in absolute.parts or self.in_test_tree(absolute.as_posix()): + continue + matches = [task_id for task_id, outputs in self.declared.items() if outputs.allows(absolute)] + if len(matches) == 1 and matches[0] in dependencies: + owners.add(matches[0]) + return next(iter(owners)) if len(owners) == 1 else None + + def body_groups(self, suite, routes): + grouped = defaultdict(list) + for failure in suite.failures: + origins = _failure_origins(failure) + owner = None + if len(origins) == 1 and origins[0] and not self.in_test_tree(origins[0]): + owner = self.body_owner(failure, origins[0]) + for route in routes: + if (route["owner"] in self.tasks_by_id and route["case"] == failure["case"] + and route["fingerprint"] == _failure_fingerprint(failure)): + owner = route["owner"] + break + if owner is not None: + grouped[owner].append(failure) + return grouped + def owner_groups(self, suite): grouped = defaultdict(list) for failure in suite.failures: @@ -632,7 +765,7 @@ def unstable_groups(self) -> dict[str, dict[str, dict]]: grouped[owner][case] = observation return grouped - def screen(self, round_record, owner, suite, failures, limited) -> tuple[list[dict], str | None]: + def screen(self, round_record, owner, suite, failures, limited, *, body=False) -> tuple[list[dict], str | None]: screened = round_record["screened"] isolated_by_owner = round_record.setdefault("isolated_by_owner", {}) by_case = defaultdict(set) @@ -660,7 +793,7 @@ def screen(self, round_record, owner, suite, failures, limited) -> tuple[list[di [list(pair) for pair in sorted(signature)], [{**f, "detail": self.failure_excerpt(_case_failure_detail(f))} for f in reproduced], ] - reproduced_for_owner.extend(item for item in reproduced if self.owner(item) == owner) + reproduced_for_owner.extend(item for item in reproduced if body or self.owner(item) == owner) if isolated.cases.get(case) == "passed": if not isolated.unavailable: self.observe_unstable(round_record, case, isolated, suite) @@ -705,18 +838,31 @@ def integrity_problem(self, before, after, unstable_files: set[str]) -> str | No return f"skip/xfail increased in {rel}" return None - def count(self, suite, owner, cases, unstable) -> int: - return sum( - f["case"] not in unstable and ( - f["case"] in cases or self.owner(f) == owner - or self.outputs[owner].matches(Path(f["file"])) and bool(f["file"]) - ) - for f in suite.failures - ) + def count(self, suite, failures, unstable, changed, baseline, *, isolated=False) -> int: + returned = {_failure_key(f) for f in failures} + cases = {f["case"] for f in failures} + changed = set(changed) + count = 0 + for failure in suite.failures: + case = failure["case"] + if case in unstable: + continue + key = _failure_key(failure) + if key in returned: + count += 1 + continue + touched = failure["file"] in changed or changed.issuperset(_failure_origins(failure)) + if isolated: + # A returned error can move between phases in isolation. + # Charge a changed file for a new error, rather than that move. + count += touched and (case, _failure_fingerprint(failure)) not in baseline + else: + count += (case in cases or touched) and key not in baseline + return count - def change_problem(self, owner, before, after, unstable) -> str | None: + def change_problem(self, outputs, before, after, unstable) -> str | None: outside = [rel for rel, new in _writes(before, after).items() if not self.allowed_change( - Path(rel), self.outputs[owner], before.get(rel), new + Path(rel), outputs, before.get(rel), new )] if outside: return f"write outside declared outputs: {', '.join(sorted(outside))}" @@ -733,15 +879,12 @@ def change_problem(self, owner, before, after, unstable) -> str | None: unstable_files = {observation["file"] for observation in unstable.values()} return self.integrity_problem(before, after, unstable_files) - def assess(self, round_record, attempt, suite, failures, owner, before, target) -> tuple[str | None, _Suite]: + def gate_problem(self, round_record, target): from codd.greenfield.pipeline import _enforce_stage_coverage_gate - case_ids = list(dict.fromkeys(f["case"] for f in failures)) - returned_failures = {(f["case"], f["origin"], f["phase"]) for f in failures} - unstable = attempt.get("unstable_cases", {}) + self.snapshot.restore(target) + reason = None try: - # prepare() provisioned the round's environment before snapshotting - # it. Judge the candidate in that same environment. self.pipeline._enforce_implement_oracle_gate( self.root, self.tasks, self.options, verdict_only=True, reuse_test_environment=True, @@ -751,94 +894,344 @@ def assess(self, round_record, attempt, suite, failures, owner, before, target) authenticity_profile=self.pipeline._resolve_layout_profile(self.root), ) except StageError as exc: - return f"implement gate or coverage audit failed: {exc}", suite + reason = f"implement gate or coverage audit failed: {exc}" if self.snapshot.environment_changed(round_record["environment_before"]): self.environment_dirty = True - return "test environment changed during candidate checks", suite + return "test environment changed during candidate checks" + return reason - candidate = self.run_tests(round_record, "candidate suite", target=target) - attempt["after"] = self.count(candidate, owner, case_ids, unstable) - attempt["suite_after"] = len(candidate.failures) + @staticmethod + def suite_problem(suite, candidate): if candidate.unavailable: - return "candidate suite could not complete", suite + return "candidate suite could not complete" if candidate.collection_errors.keys() - suite.collection_errors.keys(): - return "candidate introduced collection errors", suite - for case in unstable: - if candidate.cases.get(case) != "passed": - return f"{_UNSTABLE_REASON}: {case}", suite + return "candidate introduced collection errors" if list(candidate.cases.values()).count("skipped") > list(suite.cases.values()).count("skipped"): - return "runtime skip/xfail increased", suite - if failures and attempt["after"] >= attempt["before"]: - return "owner's failures and errors did not decrease", suite - - regressions = [case for case, status in suite.cases.items() - if status == "passed" and candidate.cases.get(case) != "passed"] - deadline = time.monotonic() + self.timeout + return "runtime skip/xfail increased" + return None - def isolate(case, purpose, artifacts): - budget_exceeded = "candidate isolation exceeded the test time budget" - remaining = deadline - time.monotonic() - if remaining <= 0: - return None, budget_exceeded - result = self.run_tests(round_record, purpose, case, remaining, target=artifacts) - if result.timed_out: - return None, budget_exceeded - if result.unavailable or result.cases[case] == "skipped": - return None, f"candidate could not verify {case}" - return result, None + def isolate(self, round_record, case, purpose, target, deadline): + exceeded = "candidate isolation exceeded the test time budget" + remaining = deadline - time.monotonic() + if remaining <= 0: + return None, exceeded + result = self.run_tests(round_record, purpose, case, remaining, target=target) + if result.timed_out: + return None, exceeded + if result.unavailable or result.cases[case] == "skipped": + return None, f"candidate could not verify {case}" + return result, None + + def check_returned(self, record, attempt, suite, candidate, target, changes, deadline): + failures = attempt["returned_failures"] + unstable = attempt.get("unstable_cases", {}) + case_ids = list(dict.fromkeys(f["case"] for f in failures)) + baseline = {_failure_key(f) for f in suite.failures} + attempt["before"] = self.count(suite, failures, unstable, (), baseline) + attempt["after"] = self.count(candidate, failures, unstable, changes, baseline) + attempt["suite_after"] = len(candidate.failures) + attempt["isolated_after"] = None + isolated_failures = self.isolated_failures[id(attempt)] = [] + for case in unstable: + if candidate.cases.get(case) != "passed": + return f"{_UNSTABLE_REASON}: {case}" + body = attempt["recipient"] == "body" + if body and any(suite.cases.get(case) != "failed" for case in case_ids): + return "returned failure no longer reproduces in the baseline suite" + count_problem = None + if not body and failures and attempt["after"] >= attempt["before"]: + count_problem = _COUNT_REASON isolated_after = 0 + progress = [] + # Confirm a source owner's progress with the original test files, + # even when the combined suite contains other owners' test edits. + isolation_target = self.combine(self.target, [changes]) if body else target + returned = {_failure_key(f) for f in failures} + known_errors = {(f["case"], _failure_fingerprint(f)) for f in suite.failures} for case in case_ids: - result, problem = isolate(case, "candidate isolate", target) + result, problem = self.isolate(record, case, "candidate isolate", isolation_target, deadline) if problem: - return problem, suite - isolated_after += sum( - (f["case"], f["origin"], f["phase"]) in returned_failures for f in result.failures - ) - + return count_problem or problem + isolated_failures.extend(result.failures) + if body: + for observed, original in ((candidate, suite.failures), (result, failures)): + before = {_failure_fingerprint(f) for f in original + if f["case"] == case and _failure_key(f) in returned} + if observed.cases.get(case) == "passed": + progress.append("fixed") + elif (before and observed.cases.get(case) == "failed" and + (after := set(self.fingerprints(observed).get(case, ()))) and before.isdisjoint(after)): + progress.append("progressed") + else: + return f"failure fingerprint did not advance: {case}" + else: + isolated_after += self.count(result, failures, unstable, changes, known_errors, + isolated=True) + if candidate.cases.get(case) == "failed" and result.cases[case] == "passed": + self.candidate_unstable.append((case, result, candidate)) for case in unstable: for _ in range(_UNSTABLE_VERIFICATION_RUNS): - result, problem = isolate(case, "candidate unstable isolate", target) + result, problem = self.isolate(record, case, "candidate unstable isolate", target, deadline) if problem: - return problem, suite + return problem + isolated_failures.extend(result.failures) if result.cases[case] != "passed": - return f"{_UNSTABLE_REASON}: {case}", suite + return f"{_UNSTABLE_REASON}: {case}" - for case in regressions: + attempt["isolated_after"] = isolated_after + if body: + attempt["progress"] = "progressed" if "progressed" in progress else "fixed" + return count_problem + + def defer_unstable(self, record, case, passed, failed): + self.observe_unstable(record, case, passed, failed) + deferred = record.setdefault("deferred_unstable", []) + if case not in deferred: + deferred.append(case) + + def regression(self, record, attempts, suite, candidate, before, target, deadline, *, baseline_errors=None): + for case, status in suite.cases.items(): + if status != "passed" or candidate.cases.get(case) == "passed": + continue for _ in range(_CANDIDATE_REGRESSION_RUNS): - result, problem = isolate(case, "candidate isolate", target) + result, problem = self.isolate(record, case, "candidate isolate", target, deadline) if problem: - return problem, suite + return problem, None, None if result.cases[case] == "passed": + if candidate.cases.get(case) == "failed": + self.candidate_unstable.append((case, result, candidate)) break if result.cases[case] == "passed": continue - - try: - for passed in range(_BASELINE_REGRESSION_RUNS): - baseline, problem = isolate(case, "baseline isolate", before) - if problem: - return problem, suite - if baseline.cases[case] != "passed": + for passed in range(_BASELINE_REGRESSION_RUNS): + baseline, problem = self.isolate(record, case, "baseline isolate", before, deadline) + if problem: + return problem, None, None + if baseline.cases[case] != "passed": + for attempt in attempts: attempt.setdefault("baseline_failures", []).append({ "case": case, "passed": passed, "failed": 1, }) - self.observe_unstable(round_record, case, suite, baseline) - break - else: - path = Path(case.partition("::")[0]) - if not self.outputs[owner].allows(path): - attempt["rejection_output"] = self.failure_excerpt( - result.output or "\n\n".join(f["detail"] for f in result.failures), + if baseline_errors is not None: + baseline_errors.update( + (_failure_key(failure), _failure_fingerprint(failure)) for failure in baseline.failures ) - return f"{_REGRESSION_REASON}: {case}", suite - finally: - self.snapshot.restore(target) + self.observe_unstable(record, case, suite, baseline) + break + else: + return f"{_REGRESSION_REASON}: {case}", case, result + return None, None, None - attempt["isolated_after"] = isolated_after - if failures and isolated_after >= len(failures): - return "isolated failures and errors did not decrease", suite - return None, candidate + @staticmethod + def combine(before, changes): + combined = before.copy() + for delta in changes: + for path, entry in delta.items(): + if entry is None: + combined.pop(path, None) + else: + combined[path] = entry + return combined + + def culprit(self, before, active, changes, passes): + # A repair can interact with another repair. Try omissions first, + # then replay in generation order when the result is ambiguous. + def check(identifiers): + return passes(self.combine(before, (changes[index] for index in identifiers))) + + if len(active) == 1: + return active[0] + omissions = [] + for index in active: + result = check(other for other in active if other != index) + if result is None: + return None + if result: + omissions.append(index) + if len(omissions) == 1: + return omissions[0] + for end, index in enumerate(active, 1): + result = check(active[:end]) + if result is None: + return None + if not result: + return index + return None + + def reject(self, attempt, reason, candidate=None, *, culprit=False, regression=None): + attempt.update(decision="rejected", reason=reason, verdict="culprit" if culprit else "gate rejected") + if candidate is not None: + cases = {f["case"] for f in attempt["returned_failures"]} | attempt.get("unstable_cases", {}).keys() + failures = [*candidate.failures, *self.isolated_failures.get(id(attempt), ())] + detail = "\n\n".join(dict.fromkeys(_case_failure_detail(f) for f in failures if f["case"] in cases)) + if detail: + attempt["candidate_failure"] = self.failure_excerpt(detail) + saved = record_full_failure(self.root, self.snapshot.archive.parent, detail) + if saved: + attempt["candidate_failure_path"] = saved[0].as_posix() + if self.record_stall(attempt, candidate) and "did not decrease" in reason: + attempt["verdict"] = "stalled" + elif "fingerprint did not advance" in reason: + attempt["verdict"] = "stalled" + _, _, case = reason.partition(": ") + scope = self.scope(attempt["owner"], attempt["recipient"] == "body") + if regression is not None and not scope.allows(Path(case.partition("::")[0])): + attempt["rejection_output"] = self.failure_excerpt( + regression.output or "\n\n".join(f["detail"] for f in regression.failures), + ) + + def review_one_at_a_time(self, record, attempts, active, changes, before, suite): + accepted = [] + for index in active: + attempt = attempts[index] + self.isolated_failures.pop(id(attempt), None) + target = self.combine(before, [changes[index]]) + reason = self.gate_problem(record, target) + candidate = regression = None + if not reason: + candidate = self.full_suite(record, "candidate suite (one owner)", target) + reason = self.suite_problem(suite, candidate) + if not reason: + deadline = time.monotonic() + self.timeout + reason = self.check_returned(record, attempt, suite, candidate, target, changes[index], deadline) + if not reason: + reason, _, regression = self.regression(record, [attempt], suite, candidate, before, target, deadline) + reason = reason or self.isolated_problem(attempt) + if reason: + self.reject(attempt, reason, candidate, regression=regression) + else: + accepted.append(index) + before, suite = target, candidate + if self.environment_dirty: + break + return accepted, suite + + @staticmethod + def isolated_problem(attempt): + if (attempt["recipient"] == "test" and attempt["isolated_before"] + and attempt["isolated_after"] is not None + and attempt["isolated_after"] >= attempt["isolated_before"]): + return "isolated failures and errors did not decrease" + return None + + def review_batch(self, record, attempts, active, changes, suite): + before = self.target + if len({attempts[index]["owner"] for index in active}) != len(active): + return self.review_one_at_a_time(record, attempts, active, changes, before, suite) + purpose = "candidate suite" + while active: + self.isolated_failures.clear() + target = self.combine(before, (changes[index] for index in active)) + reason = self.gate_problem(record, target) + candidate = regression = None + if self.environment_dirty: + break + if reason: + def passes(artifacts): + problem = self.gate_problem(record, artifacts) + return None if self.environment_dirty else problem is None + + culprit = self.culprit(before, active, changes, passes) + else: + candidate = self.full_suite(record, purpose, target) + reason = self.suite_problem(suite, candidate) + if reason: + if len(active) == 1: + self.reject(attempts[active[0]], reason, candidate) + return [], suite + return self.review_one_at_a_time(record, attempts, active, changes, before, suite) + problems = {} + deadline = time.monotonic() + self.timeout + for index in active: + attempt = attempts[index] + owner_deadline = deadline if len(active) == 1 else time.monotonic() + self.timeout + problem = self.check_returned(record, attempt, suite, candidate, + target, changes[index], owner_deadline) + if self.environment_dirty: + return [], suite + if problem: + problems[index] = problem + if len(active) == 1 and problems: + self.reject(attempts[active[0]], problems[active[0]], candidate) + return [], suite + if len(active) > 1: + deadline = time.monotonic() + self.timeout + observed_errors = set() + reason, case, regression = self.regression( + record, [attempts[index] for index in active], suite, candidate, before, target, deadline, + baseline_errors=observed_errors, + ) + if not reason: + baseline_errors = { + _failure_key(failure) for failure in candidate.failures + if (_failure_key(failure), _failure_fingerprint(failure)) in observed_errors + } + if baseline_errors: + baseline_errors.update(map(_failure_key, suite.failures)) + for index, problem in list(problems.items()): + if problem != _COUNT_REASON: + continue + attempt = attempts[index] + if attempt["isolated_after"] is None: + continue + attempt["after"] = self.count( + candidate, attempt["returned_failures"], attempt.get("unstable_cases", {}), + changes[index], baseline_errors, + ) + if attempt["after"] < attempt["before"]: + del problems[index] + for index in active: + if problem := self.isolated_problem(attempts[index]): + problems.setdefault(index, problem) + if not problems: + return active, candidate + if len(active) > 1 and self.ambiguous_owner_problem( + problems, attempts, changes, suite, candidate, baseline_errors, + ): + return self.review_one_at_a_time(record, attempts, active, changes, before, suite) + for index, problem in problems.items(): + self.reject(attempts[index], problem, candidate) + active = [index for index in active if index not in problems] + purpose = "suite after removing candidates" + continue + + def passes(artifacts): + result, problem = self.isolate(record, case, "attribute regression", artifacts, deadline) + return None if problem else result.cases[case] == "passed" + + culprit = self.culprit(before, active, changes, passes) if case else None + + if self.environment_dirty: + break + if culprit is None and len(active) > 1: + return self.review_one_at_a_time(record, attempts, active, changes, before, suite) + index = active[0] if culprit is None else culprit + self.reject(attempts[index], reason, candidate, culprit=len(active) > 1 or purpose != "candidate suite", + regression=regression) + active.remove(index) + purpose = "suite after removing candidates" + return [], suite + + def ambiguous_owner_problem(self, problems, attempts, changes, suite, candidate, baseline_errors): + baseline = baseline_errors | {_failure_key(f) for f in suite.failures} + for index, problem in problems.items(): + if problem.startswith(("candidate could not verify", "candidate isolation exceeded")): + return True + if problem == _COUNT_REASON: + attempt = attempts[index] + failures = attempt["returned_failures"] + unstable = attempt.get("unstable_cases", {}) + returned = {_failure_key(f) for f in failures} + existing = sum(_failure_key(f) in returned and f["case"] not in unstable + for f in candidate.failures) + if existing < attempt["before"] <= self.count( + candidate, failures, unstable, changes[index], baseline, + ): + # A new error in this owner's file can originate in + # another candidate. Replay with the earlier baseline. + return True + return False def allowed_change(self, path, outputs, old, new) -> bool: if outputs.allows(path): @@ -855,9 +1248,8 @@ def allowed_change(self, path, outputs, old, new) -> bool: and (old is None or (old.mode == new.mode and new.data.startswith(old.data))) ) - def candidate_target(self, owner, after): + def candidate_target(self, outputs, after): kept = self.target.copy() - outputs = self.outputs[owner] for rel, new in sorted(_writes(self.target, after).items()): if not outputs.matches(Path(rel)): continue @@ -881,28 +1273,58 @@ def keep_outputs(self, round_record, kept): round_record["kept_attempt"] = index self.target = kept - def attempt(self, round_record, task, failures, suite, unstable): - owner = task.task_id + @staticmethod + def route(failure, owner): + return {"case": failure["case"], "fingerprint": _failure_fingerprint(failure), "owner": owner} + + def scope(self, owner, body): scope = self.outputs[owner] + if not body: + return scope + narrowed = DeclaredOutputs(self.root, ()) + narrowed.paths = scope.paths.copy() + narrowed.excluded = {**scope.excluded, **dict.fromkeys(self.test_roots, True)} + return narrowed + + def attempt(self, round_record, task, failures, suite, unstable, *, body=False): + owner = task.task_id + scope = self.scope(owner, body) before = self.target self.snapshot.restore(before) environment_before = round_record["environment_before"] - case_ids = {f["case"] for f in failures} + baseline = {_failure_key(f) for f in suite.failures} attempt = { - "owner": owner, "decision": "started", "before": self.count(suite, owner, case_ids, unstable), + "owner": owner, "recipient": "body" if body else "test", + "decision": "started", "before": self.count(suite, failures, unstable, (), baseline), "after": None, "suite_before": len(suite.failures), "suite_after": None, "isolated_before": len(failures), "isolated_after": None, "environment_before": environment_before, + "returned_failures": [ + {**{key: value for key, value in failure.items() if key != "detail"}, + "fingerprint": _failure_fingerprint(failure)} for failure in failures + ], } if unstable: attempt["unstable_cases"] = unstable round_record["attempts"].append(attempt) - previous_target = _round_archive(self.snapshot, round_record, round_record.get("kept_attempt", 0)) + index = len(round_record["attempts"]) + claim_file = self.snapshot.archive.parent / "claims" / f"{round_record['number']}-{index}.json" + if not body: + claim_file.parent.mkdir(parents=True, exist_ok=True) + claim_file.unlink(missing_ok=True) returning = f"returning {len(failures)} reproducible failure(s)/error(s)" if unstable: returning += f" and {len(unstable)} unstable test(s)" self.emit(f"{returning} to {owner}") feedback = _ADVICE + if body: + feedback += "\n\nRepair the application code. Leave every file in the test tree unchanged." + else: + feedback += ( + "\n\nIf the cause cannot be fixed within your declared outputs, leave them unchanged " + f"and write a JSON object with string fields path and reason to {claim_file.relative_to(self.root)}. " + "Use the path of the source file that needs the fix." + ) if failures: detail = "\n\n".join(map(_case_failure_detail, failures)) feedback += ( @@ -942,63 +1364,172 @@ def attempt(self, round_record, task, failures, suite, unstable): feedback += f"\n\n{_command_output_tail(previous['reason'], None)}" if output: feedback += f"\n{output}" - reason, candidate = None, suite + if candidate_failure := previous.get("candidate_failure"): + feedback += f"\n\nAfter your previous change, the returned cases failed as follows:\n{candidate_failure}" + reason = None + no_output = False try: self.pipeline._reimplement_tasks( self.root, [task], feedback, self.config, feedback_output_paths=scope, ) except Exception as exc: reason = f"could not evaluate the candidate: {exc}" + no_output = any(marker in str(exc) for marker in ( + "AI command did not produce any file changes", "empty output", "no file change proposed:", + )) self.environment_dirty = self.snapshot.environment_changed(environment_before) - if not self.environment_dirty and reason is None: - try: + try: + if self.environment_dirty: + reason = ( + "test environment changed during the task rerun or candidate checks; " + "discarding and reprovisioning it" + ) + else: proposed = self.snapshot.capture() - reason = self.change_problem(owner, before, proposed, unstable) - if reason is None: - target = self.candidate_target(owner, proposed) - self.snapshot.restore(target) - reason, candidate = self.assess(round_record, attempt, suite, failures, owner, before, target) + if not body and (reason is None or no_output) and proposed == before: + claim = self.read_claim(claim_file) + if claim: + attempt.update(decision="declined", verdict="declined", claim=claim, + reason=f"outside own outputs: {claim['path']}") + routes = round_record.setdefault("claims", []) + for failure in failures: + if (recipient := self.body_owner(failure, claim["path"], test_owner=owner)) is not None: + routes.append(self.route(failure, recipient)) + if not reason and attempt["decision"] == "started": + reason = self.change_problem(scope, before, proposed, unstable) + if not reason: + target = self.candidate_target(scope, proposed) + self.snapshot.persist(target, _pending_archive(self.snapshot, round_record, index)) + attempt.update(decision="pending", reason="awaiting the candidate suite") + except (OSError, ValueError) as exc: + reason = f"could not evaluate the candidate: {exc}" + finally: + # Leave an interrupted AI turn to recovery. A completed turn owns + # only its archived candidate until it passes the review. + if attempt["decision"] != "started" or reason is not None: + self.snapshot.restore(before) + if attempt["decision"] == "started": + self.reject(attempt, reason) + for case in unstable: + self.pending_unstable.pop(case, None) + self.emit(f"{owner}: {attempt['decision']} · {attempt['reason']}") + return self.environment_dirty + + @staticmethod + def read_claim(path): + try: + claim = json.loads(path.read_text()) + except (OSError, ValueError): + return None + if (isinstance(claim, dict) and all(isinstance(claim.get(key), str) and claim[key].strip() + for key in ("path", "reason"))): + return {key: claim[key].strip() for key in ("path", "reason")} + return None + + def settle(self, record, suite): + attempts = {index: attempt for index, attempt in enumerate(record["attempts"], 1) + if attempt["decision"] == "pending"} + if not attempts: + return suite + before = self.target + self.candidate_unstable.clear() + self.isolated_failures.clear() + changes = {} + for index, attempt in attempts.items(): + if not suite.unavailable and attempt["environment_before"] != record["environment_before"]: + if problem := self.check_reprovisioned_baseline(record, attempt): + self.reject(attempt, problem) + continue + try: + changes[index] = _writes(before, self.snapshot.read(_pending_archive(self.snapshot, record, index))) + except (OSError, ValueError, BadZipFile) as exc: + self.reject(attempt, f"could not read the pending candidate: {exc}") + # Keep records pending on disk while checks run. A resume can redo the + # tests even if interrupted during attribution or snapshot restoration. + if suite.unavailable or self.environment_dirty: + accepted, candidate = [], suite + else: + try: + accepted, candidate = self.review_batch(record, attempts, list(changes), changes, suite) except Exception as exc: - reason = f"could not evaluate the candidate: {exc}" - dirty = self.environment_dirty or self.snapshot.environment_changed(environment_before) - if not dirty and reason is None: + accepted, candidate = [], suite + for attempt in attempts.values(): + self.reject(attempt, f"could not evaluate the candidate: {exc}") + if self.environment_dirty: + accepted, candidate = [], suite + for attempt in attempts.values(): + self.reject(attempt, "test environment changed during candidate checks") + if accepted: + kept = self.combine(before, (changes[index] for index in accepted)) try: - self.keep_outputs(round_record, target) + self.keep_outputs(record, kept) except (OSError, ValueError) as exc: - reason = f"could not keep the candidate: {exc}" - if dirty: - reason = ( - "test environment changed during the task rerun or candidate checks; " - "discarding and reprovisioning it" + accepted, candidate = [], suite + for attempt in attempts.values(): + self.reject(attempt, f"could not keep the candidate: {exc}") + for index, attempt in attempts.items(): + if index in accepted: + self.record_stall(attempt, candidate) + reason = ("failures decreased" if attempt["isolated_before"] + else "unstable tests passed the suite and isolated checks") + verdict = "fixed" + if attempt["recipient"] == "body": + verdict = attempt["progress"] + reason = "returned tests passed" if verdict == "fixed" else "failure fingerprint advanced" + attempt.update(decision="accepted", reason=reason, verdict=verdict) + elif attempt["decision"] == "pending": + self.reject(attempt, "candidate suite could not complete") + self.snapshot.restore(self.target) + if accepted: + for case, passed, failed in self.candidate_unstable: + if failed is candidate: + self.defer_unstable(record, case, passed, failed) + self.pipeline._checkpoint(self.root) + for index, attempt in attempts.items(): + self.pipeline.echo( + f"[implement test feedback] {attempt['owner']}: {attempt['decision']} · {attempt['reason']} · " + f"owner {attempt['before']} → {attempt['after']} · " + f"suite {attempt['suite_before']} → {attempt['suite_after']}" ) - _restore_round_for_provisioning(self.snapshot, round_record) - _discard_feedback_environment(self.snapshot, self.state) - round_record["screened"].clear() - candidate = suite - elif reason is not None: - self.snapshot.restore(before) - candidate = suite - else: - # Every accepted change can affect another case's isolated result. - round_record["screened"].clear() - accepted_reason = "failures decreased" if failures else "unstable tests passed the suite and isolated checks" - attempt.update(decision="rejected" if reason else "accepted", reason=reason or accepted_reason) - for case in unstable: - self.pending_unstable.pop(case, None) - if dirty: - self.pipeline._checkpoint(self.root) - candidate.unavailable = self.prepare(round_record) - self.emit( - f"{owner}: {attempt['decision']} · {attempt['reason']} · " - f"owner {attempt['before']} → {attempt['after'] if attempt['after'] is not None else '—'} · " - f"suite {attempt['suite_before']} → {attempt['suite_after'] if attempt['suite_after'] is not None else '—'}" + _pending_archive(self.snapshot, record, index).unlink(missing_ok=True) + return candidate + + def check_reprovisioned_baseline(self, record, attempt): + if attempt.get("unstable_cases"): + return "unstable test observations are from a different environment" + deadline = time.monotonic() + self.timeout + returned = defaultdict(Counter) + for failure in attempt["returned_failures"]: + returned[failure["case"]][_failure_key(failure)] += 1 + for case, expected in returned.items(): + result, problem = self.isolate(record, case, "reprovisioned baseline isolate", self.target, deadline) + if problem or expected - Counter(map(_failure_key, result.failures)): + return f"returned failure no longer reproduces after reprovisioning: {case}" + return None + + def record_stall(self, attempt, candidate): + if attempt["recipient"] != "test": + return False + before = {(f["case"], _failure_fingerprint(f)) for f in attempt["returned_failures"]} + stalled = [f for f in candidate.failures if (f["case"], _failure_fingerprint(f)) in before] + if stalled: + attempt["stalled_routes"] = [ + self.route(failure, owner) for failure in stalled + if (owner := self.body_owner(failure, test_owner=attempt["owner"])) is not None + ] + return bool(stalled) + + def reprovision(self, record): + _restore_round_for_provisioning(self.snapshot, record) + _discard_feedback_environment(self.snapshot, self.state) + self.suites.clear() + record["screened"].clear() + problem = self.prepare(record) + return _Suite(unavailable=problem) if problem else self.full_suite( + record, "suite after reprovisioning", self.target, ) - if reason is None: - previous_target.unlink(missing_ok=True) - return candidate, dirty def run(self, rounds: int) -> None: - tasks = {task.task_id: task for task in self.tasks} for index in range(rounds): if index == len(self.state["rounds"]): self.state["rounds"].append({ @@ -1006,83 +1537,122 @@ def run(self, rounds: int) -> None: "isolated_seconds": 0.0, "passed_in_isolation": 0, "over_isolation_budget": 0, "screened": {}, }) - round_record = self.state["rounds"][index] - if round_record.get("done"): - if round_record["stop"]: + record = self.state["rounds"][index] + if record.get("done"): + if record["stop"]: break continue - problem = self.prepare(round_record) - suite = _Suite(unavailable=problem) if problem else self.run_tests(round_record, f"round {index + 1} suite") - handled = {attempt["owner"] for attempt in round_record["attempts"] if not attempt.get("interrupted")} - # Interrupted work stays ineligible for ordinary failure feedback. - # Pending unstable observations can still be returned on resume. - interrupted = { - attempt["owner"] for recorded in self.state["rounds"] - for attempt in recorded["attempts"] if attempt.get("interrupted") - } - limited = set(round_record.get("cases_outside_isolation_budget", ())) + prior_routes = [ + route for attempt in self.state["rounds"][index - 1]["attempts"] + for route in attempt.get("stalled_routes", ()) + ] if index else [] + problem = self.prepare(record) + suite = _Suite(unavailable=problem) if problem else self.full_suite( + record, f"round {index + 1} suite", self.target, + ) + handled = {(a["owner"], a.get("recipient", "test")) for a in record["attempts"] + if not a.get("interrupted")} + interrupted = {a["owner"] for r in self.state["rounds"] for a in r["attempts"] if a.get("interrupted")} + limited = set(record.get("cases_outside_isolation_budget", ())) unreproduced = set() + deferred = record.setdefault("deferred_unstable", []) isolation_problem = None while not suite.unavailable: + body_groups = self.body_groups(suite, [*prior_routes, *record.get("claims", ())]) + redirected = {_failure_key(f) for failures in body_groups.values() for f in failures} pending = { - owner: failures for owner, failures in self.owner_groups(suite) - if owner not in handled and owner not in interrupted and owner not in unreproduced + (owner, "test"): [f for f in failures if _failure_key(f) not in redirected] + for owner, failures in self.owner_groups(suite) if owner not in interrupted + and any(_failure_key(f) not in redirected for f in failures) } - for owner in sorted(self.unstable_groups().keys() - handled): - pending.setdefault(owner, []) - if not pending: - break - owner = next(iter(pending)) - failures, isolation_problem = self.screen(round_record, owner, suite, pending[owner], limited) - time_exhausted = round_record["isolated_seconds"] >= self.timeout - if time_exhausted: - limited.update(f["case"] for other, owned in pending.items() if other != owner for f in owned) - round_record["over_isolation_budget"] = len(limited) - if limited: - round_record["cases_outside_isolation_budget"] = sorted(limited) - if time_exhausted: - round_record["isolation_time_exhausted"] = True - self.emit("isolation time budget exhausted") - if isolation_problem: - break - owned_unstable = self.unstable_groups().get(owner, {}) - unstable = dict(list(owned_unstable.items())[:_MAX_ISOLATED_CASES]) - failures = [failure for failure in failures if failure["case"] not in owned_unstable] - if failures or unstable: - handled.add(owner) - suite, reprovisioned = self.attempt(round_record, tasks[owner], failures, suite, unstable) - if reprovisioned or round_record["attempts"][-1]["decision"] == "accepted": + observations = self.unstable_groups() + for owner, unstable in sorted(observations.items()): + if any(case not in deferred for case in unstable): + pending.setdefault((owner, "test"), []) + for owner, failures in sorted(body_groups.items()): + if owner not in interrupted: + pending[owner, "body"] = failures + pending = {key: failures for key, failures in pending.items() + if key not in handled and key not in unreproduced} + + if not pending or record.get("isolation_time_exhausted"): + before = self.target + suite = self.settle(record, suite) + if self.environment_dirty: + suite = self.reprovision(record) unreproduced.clear() - if not suite.unavailable and (reprovisioned or self.has_helper(failures)): - round_record["screened"].clear() - purpose = "suite after reprovisioning" if reprovisioned else "suite after helper decision" - suite = self.run_tests(round_record, purpose) + continue + if self.target == before or record.get("isolation_time_exhausted"): + break + # An isolated failure may become reproducible only after + # another owner has passed review. Preserve that opportunity. + eligible = unreproduced | {(owner, "test") for owner in self.unstable_groups()} + new_test_owners = {(owner, "test") for owner, _ in self.owner_groups(suite)} + new_body_owners = {(owner, "body") for owner in self.body_groups(suite, prior_routes)} + handled.update((new_test_owners | new_body_owners) - eligible) + unreproduced.clear() + continue + + (owner, recipient), owned = next(iter(pending.items())) + if recipient == "body": + failures, isolation_problem = self.screen(record, owner, suite, owned, limited, body=True) else: - unreproduced.add(owner) + failures, isolation_problem = self.screen(record, owner, suite, owned, limited) + time_exhausted = record["isolated_seconds"] >= self.timeout if time_exhausted: + limited.update(f["case"] for key, group in pending.items() if key != (owner, recipient) for f in group) + record["isolation_time_exhausted"] = True + self.emit("isolation time budget exhausted") + if isolation_problem: break - # A clean suite can still leave evidence for an owner already handled this round. + own_observations = self.unstable_groups().get(owner, {}) if recipient == "test" else {} + unstable = dict((case, obs) for case, obs in own_observations.items() if case not in deferred) + unstable = dict(list(unstable.items())[:_MAX_ISOLATED_CASES]) + failures = [failure for failure in failures if failure["case"] not in own_observations] + if not (failures or unstable): + unreproduced.add((owner, recipient)) + continue + handled.add((owner, recipient)) + args = (record, self.tasks_by_id[owner], failures, suite, unstable) + dirty = self.attempt(*args, body=True) if recipient == "body" else self.attempt(*args) + if dirty: + unreproduced.clear() + suite = self.reprovision(record) + + if not self.environment_dirty: + suite = self.settle(record, suite) + else: + for attempt in record["attempts"]: + if attempt["decision"] == "pending": + self.reject(attempt, "test environment changed during candidate checks") + routes = [route for attempt in record["attempts"] for route in attempt.get("stalled_routes", ())] stop = bool(suite.unavailable) or not ( self.unstable_groups() or any(owner not in interrupted for owner, _ in self.owner_groups(suite)) + or any(owner not in interrupted for owner in self.body_groups(suite, routes)) ) + record["over_isolation_budget"] = len(limited) if limited: + record["cases_outside_isolation_budget"] = sorted(limited) self.emit(f"{len(limited)} failing case(s) left outside the isolation budget") - if round_record.get("baseline_saved"): + if record.get("baseline_saved"): self.snapshot.restore(self.target) if self.environment_dirty: _discard_feedback_environment(self.snapshot, self.state) + self.suites.clear() self.emit("test environment changed; discarded before the next run") - round_record.update(done=True, stop=stop) + record.update(done=True, stop=stop) + self.remember_last_suite(record, suite) problem = suite.unavailable or isolation_problem if problem: - round_record["skipped"] = _command_output_tail(problem, None) - self.emit(f"round {index + 1} skipped · {round_record['skipped']}") + record["skipped"] = _command_output_tail(problem, None) + self.emit(f"round {index + 1} skipped · {record['skipped']}") self.emit( f"round {index + 1}: {len(suite.failures)} failure(s)/error(s) remain · " - f"{round_record['passed_in_isolation']} passed in isolation" + f"{record['passed_in_isolation']} passed in isolation" ) - for attempt_index in range(len(round_record["attempts"]) + 1): - _round_archive(self.snapshot, round_record, attempt_index).unlink(missing_ok=True) + for attempt_index in range(len(record["attempts"]) + 1): + _round_archive(self.snapshot, record, attempt_index).unlink(missing_ok=True) + _pending_archive(self.snapshot, record, attempt_index).unlink(missing_ok=True) if stop: break diff --git a/tests/greenfield/test_implement_test_feedback.py b/tests/greenfield/test_implement_test_feedback.py index da30b2ee..a547d51f 100644 --- a/tests/greenfield/test_implement_test_feedback.py +++ b/tests/greenfield/test_implement_test_feedback.py @@ -279,15 +279,17 @@ def test_flaky(request): calls = trace.read_text().splitlines() assert [x for x in calls if x.startswith("feedback ")] == ["feedback helper", "feedback case"] assert calls.index("both audits") < calls.index("provision") < calls.index("suite") - between = calls[calls.index("feedback helper"):calls.index("feedback case")] - assert between[:4] == ["feedback helper", "oracle verdict", "both audits verdict", "suite"] + assert calls.index("feedback helper") < calls.index("feedback case") < calls.index("oracle verdict") + assert calls.count("suite") == 3 # round baseline, combined candidate, final verification assert calls[-3:] == ["provision", "verify", "suite"] [round_record] = feedback(root)["rounds"] assert round_record["passed_in_isolation"] == 1 - assert any(run["purpose"] == "suite after helper decision" for run in round_record["runs"]) + assert [run["purpose"] for run in round_record["runs"] if "case" not in run] == [ + "round 1 suite", "candidate suite", + ] assert [item["decision"] for item in round_record["attempts"]] == ["accepted", "accepted"] - assert [(item["before"], item["after"]) for item in round_record["attempts"]] == [(1, 0), (2, 1)] + assert [(item["before"], item["after"]) for item in round_record["attempts"]] == [(1, 0), (1, 0)] case_prompt = trace.with_name("prompt-case").read_text() reproduced, unstable = case_prompt.split("\n\nUnstable tests\n", 1) assert "test_subject (call" in reproduced diff --git a/tests/greenfield/test_implement_test_feedback_batch.py b/tests/greenfield/test_implement_test_feedback_batch.py new file mode 100644 index 00000000..ee681ade --- /dev/null +++ b/tests/greenfield/test_implement_test_feedback_batch.py @@ -0,0 +1,319 @@ +"""Batch feedback acceptance, attribution, and handoff to source owners.""" + +import json +import os +import subprocess +import sys +from dataclasses import replace + +import pytest + +from codd import ai_invoke +from codd.greenfield import implement_test_feedback as engine + +from .test_implement_test_feedback import APP, TEST_FILE, feedback, project_factory +from .test_implement_test_feedback_w21b_review import ( + A, B, C, REPAIR, RUNTIME, SOURCE, TEST, THIRD, attempts, fake, ref, revised, write, +) + + +REGRESSION = TEST + "::test_passing" + + +def three_owners(tmp_path, monkeypatch, *, regression=None, skip_after_removal=False): + def outcomes(root, selected): + a, b, c = (revised(root, name) for name in (REPAIR, TEST, THIRD)) + cases = { + A: "passed" if a else "failed", + B: "passed" if b else "failed", + C: "passed" if c else "failed", + REGRESSION: "failed" if regression and regression(a, b) else "passed", + } + if skip_after_removal: + cases[B + "_runtime"] = "skipped" if b and not a and not selected else "passed" + return ({selected: cases[selected]} if selected else cases), {} + + return fake(tmp_path, monkeypatch, [ + ref("a", REPAIR), ref("b", TEST), ref("c", THIRD), + ], outcomes) + + +def test_y1_three_owners_share_one_candidate_suite(tmp_path, monkeypatch): + fixture = three_owners(tmp_path, monkeypatch) + [record] = fixture.drive(1)["rounds"] + assert [owner for owner, _ in fixture.prompts] == ["a", "b", "c"] + assert [(run["purpose"], run["failures_and_errors"]) + for run in record["runs"] if "case" not in run] == [ + ("round 1 suite", 3), ("candidate suite", 0), + ] + assert [attempt["decision"] for attempt in record["attempts"]] == ["accepted"] * 3 + + +def test_y2_attributes_cross_owner_regression_from_combined_tree(tmp_path, monkeypatch): + fixture = three_owners(tmp_path, monkeypatch, regression=lambda a, b: a) + [record] = fixture.drive(1)["rounds"] + assert [revised(fixture.root, name) for name in (REPAIR, TEST, THIRD)] == [False, True, True] + first, second, third = record["attempts"] + assert first.get("verdict") == "culprit" + assert first["reason"].endswith(REGRESSION) + assert [second["decision"], third["decision"]] == ["accepted", "accepted"] + assert first["suite_after"] == 1 + assert sum(run["purpose"] == "attribute regression" for run in record["runs"]) == 3 + assert any(run["purpose"] == "suite after removing candidates" for run in record["runs"]) + + +def test_d6_checks_for_suite_only_skip_after_removing_culprit(tmp_path, monkeypatch): + fixture = three_owners(tmp_path, monkeypatch, regression=lambda a, b: a, skip_after_removal=True) + state = fixture.drive(1) + assert [revised(fixture.root, name) for name in (REPAIR, TEST, THIRD)] == [False, False, True] + assert attempts(state) == [ + ("a", "rejected", f"previously passing test now fails in isolation: {REGRESSION}"), + ("b", "rejected", "runtime skip/xfail increased"), + ("c", "accepted", "failures decreased"), + ] + + +@pytest.mark.parametrize("interaction", [False, True]) +def test_d2_replays_prefixes_when_omission_is_ambiguous(tmp_path, monkeypatch, interaction): + def regression(a, b): + return a and b if interaction else a or b + + fixture = three_owners(tmp_path, monkeypatch, regression=regression) + [record] = fixture.drive(1)["rounds"] + assert [revised(fixture.root, name) for name in (REPAIR, TEST, THIRD)] == [interaction, False, True] + assert [a["owner"] for a in record["attempts"] if a["verdict"] == "culprit"] == ( + ["b"] if interaction else ["a", "b"] + ) + assert sum(run["purpose"] == "attribute regression" for run in record["runs"]) >= 4 + + +def test_d1_candidate_instability_is_returned_in_the_next_round(tmp_path, monkeypatch): + def outcomes(root, selected): + a, b = (revised(root, name) for name in (REPAIR, TEST)) + cases = {A: "passed" if a else "failed", B: "failed" if a and not b and not selected else "passed"} + return ({selected: cases[selected]} if selected else cases), {} + + fixture = fake(tmp_path, monkeypatch, [ref("a", REPAIR), ref("b", TEST)], outcomes) + first, second = fixture.drive(2)["rounds"] + assert [(a["owner"], a["decision"]) for a in first["attempts"]] == [("a", "accepted")] + assert first["deferred_unstable"] == [B] + [attempt] = second["attempts"] + assert (attempt["owner"], attempt["decision"]) == ("b", "accepted") + assert list(attempt["unstable_cases"]) == [B] + assert sum(run["purpose"] == "candidate unstable isolate" for run in second["runs"]) == 3 + + +def test_d7_resumes_the_pending_batch_when_validation_is_interrupted(tmp_path, monkeypatch): + fixture = three_owners(tmp_path, monkeypatch) + run_tests = engine._Feedback.run_tests + + def interrupt(self, record, purpose, case=None, timeout=None, *, target=None): + if purpose == "candidate suite": + self.snapshot.restore(target) + raise KeyboardInterrupt + return run_tests(self, record, purpose, case, timeout, target=target) + + with monkeypatch.context() as patch: + patch.setattr(engine._Feedback, "run_tests", interrupt) + with pytest.raises(KeyboardInterrupt): + fixture.drive(1) + assert [a["decision"] for a in fixture.record["test_feedback"]["rounds"][0]["attempts"]] == ["pending"] * 3 + assert [owner for owner, _ in fixture.prompts] == ["a", "b", "c"] + [record] = fixture.drive(1, resume=True)["rounds"] + assert [a["decision"] for a in record["attempts"]] == ["accepted"] * 3 + assert [owner for owner, _ in fixture.prompts] == ["a", "b", "c"] + + +def test_reprovisioning_requires_pending_failures_to_reproduce_again(tmp_path, monkeypatch): + provisions = 0 + + def provision(root): + nonlocal provisions + provisions += 1 + write(root, RUNTIME, "old environment" if provisions == 1 else "new environment") + + def outcomes(root, selected): + new_environment = (root / RUNTIME).read_text() == "new environment" + cases = { + A: "passed" if revised(root, REPAIR) or (selected == A and new_environment) else "failed", + B: "passed" if new_environment else "failed", + } + return ({selected: cases[selected]} if selected else cases), {} + + def edit(root, owner, scope): + if owner == "b": + write(root, RUNTIME, "environment changed by the candidate") + else: + write(root, REPAIR, (root / REPAIR).read_text() + "# revised\n") + + fixture = fake(tmp_path, monkeypatch, [ref("a", REPAIR), ref("b", TEST)], outcomes, + edit=edit, provision=provision) + state = fixture.drive(1) + first, second = state["rounds"][0]["attempts"] + assert first["reason"].startswith("returned failure no longer reproduces after reprovisioning") + assert "discarding and reprovisioning" in second["reason"] + assert provisions == 2 and not revised(fixture.root, REPAIR) + + +@pytest.mark.parametrize("source_is_origin", [False, True]) +def test_d3_returns_stalled_and_source_origin_failures(tmp_path, monkeypatch, source_is_origin): + def outcomes(root, selected): + failed = not revised(root, SOURCE) + origin = SOURCE if source_is_origin else TEST + frames = [TEST, SOURCE] if source_is_origin or revised(root, TEST) else [TEST] + return {B: "failed" if failed else "passed"}, { + B: {"origin": origin, "paths": frames, "detail": "ValueError: Invalid state"}, + } + + author = replace(ref("author", TEST), dependencies=("application",)) + fixture = fake(tmp_path, monkeypatch, [author, ref("application", SOURCE)], outcomes) + rounds = fixture.drive(2)["rounds"] + if source_is_origin: + assert len(rounds) == 1 + else: + first = rounds[0]["attempts"][0] + assert (first["owner"], first["verdict"]) == ("author", "stalled") + [body] = rounds[-1]["attempts"] + assert (body["owner"], body["recipient"], body["verdict"]) == ("application", "body", "fixed") + assert revised(fixture.root, SOURCE) and not revised(fixture.root, TEST) + + +def setup_claim_project(project_factory, *, write_test=False): + tests = """\ +from stub_app import subject + +def test_subject(): + actual = subject.value() + assert actual is not None, "blocked before the comparison" + assert actual == 7, "reached the comparison" +""" + source = "def value():\n return None\n" + body_fix = {APP: "def value():\n return 8\n"} + body_outputs = (APP,) + if write_test: + body_fix["checks/test_body_owned.py"] = "def test_body_owned():\n assert True\n" + body_outputs += ("checks/test_body_owned.py",) + claim = {f"{engine.STATE_DIRECTORY}/claims/1-1.json": json.dumps({ + "path": APP, "reason": "value returns no result before the comparison", + })} + pipeline, root, trace, _ = project_factory( + rounds=1 if write_test else 2, + initial={"case": {TEST_FILE: tests}, "application": {APP: source}}, + owned={"case": (TEST_FILE,), "application": body_outputs}, + fixes={"case": {"direct": claim}, "application": {"files": body_fix}}, + ) + lister = pipeline.task_lister + pipeline.task_lister = lambda project: [ + replace(task, dependencies=("application",)) if task.task_id == "case" else task + for task in lister(project) + ] + return pipeline, root, trace + + +def test_y3_claim_returns_to_dependency_and_retains_progress(project_factory, monkeypatch): + pipeline, root, _ = setup_claim_project(project_factory) + rerun = pipeline._reimplement_tasks + observed = [] + + def remember(project, tasks, prompt, config, **kwargs): + observed.append((tasks[0].task_id, prompt, (root / TEST_FILE).read_bytes())) + return rerun(project, tasks, prompt, config, **kwargs) + + monkeypatch.setattr(pipeline, "_reimplement_tasks", remember) + pipeline.run(root) + first, second = feedback(root)["rounds"] + assert [(a["owner"], a["decision"]) for a in first["attempts"]] == [ + ("case", "declined"), ("application", "accepted"), + ] + assert first["attempts"][1]["verdict"] == "progressed" + assert first["attempts"][1]["recipient"] == "body" + assert "return 8" in (root / APP).read_text() + assert all(content == (root / TEST_FILE).read_bytes() for _, _, content in observed) + assert [owner for owner, _, _ in observed] == ["case", "application", "case"] + assert f"{engine.STATE_DIRECTORY}/claims/1-1.json" in observed[0][1] + assert "AssertionError: reached the comparison" in observed[-1][1] + assert second["reused_suites"][0]["purpose"] == "round 2 suite" + + +def test_y4_body_turn_rejects_writes_even_to_its_own_test(project_factory): + pipeline, root, _ = setup_claim_project(project_factory, write_test=True) + pipeline.run(root) + [record] = feedback(root)["rounds"] + _, body = record["attempts"] + assert body["decision"] == "rejected" + assert "write outside declared outputs" in body["reason"] + assert "return None" in (root / APP).read_text() + assert not (root / "checks/test_body_owned.py").exists() + + +def test_d3_file_writer_can_leave_a_claim_without_captured_changes(project_factory, monkeypatch): + pipeline, root, trace = setup_claim_project(project_factory) + monkeypatch.setenv("GIT_CONFIG_GLOBAL", os.devnull) + monkeypatch.setenv("GIT_CONFIG_NOSYSTEM", "1") + subprocess.run(["git", "init", "-q", "--template="], cwd=root, check=True) + script = trace.with_name("ai.py") + script.write_text(script.read_text() + '\nif part == "feedback" and owner == "case": print("paths: []")\n') + rerun = pipeline._reimplement_tasks + + def with_capture(*args, **kwargs): + with monkeypatch.context() as patch: + patch.setattr(ai_invoke, "is_file_writing_agent", lambda argv: argv[0] == sys.executable) + return rerun(*args, **kwargs) + + monkeypatch.setattr(pipeline, "_reimplement_tasks", with_capture) + pipeline.run(root) + first, _ = feedback(root)["rounds"] + assert [a["decision"] for a in first["attempts"]] == ["declined", "accepted"] + + +@pytest.mark.parametrize("same_failure", [False, True]) +def test_y5_rejected_candidate_failure_is_delivered_on_retry(tmp_path, monkeypatch, same_failure): + def outcomes(root, selected): + detail = "candidate encounters a later comparison" if revised(root, TEST) and not same_failure else "initial failure" + return {B: "failed"}, {B: {"detail": detail}} + + fixture = fake(tmp_path, monkeypatch, [ref("test", TEST)], outcomes) + first, second = fixture.drive(2)["rounds"] + original, retry = first["attempts"][0], second["attempts"][0] + assert original["decision"] == retry["decision"] == "rejected" + assert not revised(fixture.root, TEST) + assert original["reason"] == "owner's failures and errors did not decrease" + assert "After your previous change" in fixture.prompts[1][1] + assert ("initial failure" if same_failure else "candidate encounters a later comparison") in original["candidate_failure"] + assert (fixture.root / original["candidate_failure_path"]).is_file() + + +def test_y5_retry_includes_failures_seen_only_in_candidate_isolation(tmp_path, monkeypatch): + def outcomes(root, selected): + candidate = revised(root, TEST) + details = {B: {"detail": "candidate isolation fails" if candidate else "initial failure"}} + return {B: "passed" if candidate and not selected else "failed"}, details + + fixture = fake(tmp_path, monkeypatch, [ref("test", TEST)], outcomes) + first, _ = fixture.drive(2)["rounds"] + [attempt] = first["attempts"] + assert attempt["suite_after"] == 0 and attempt["isolated_after"] == 1 + assert attempt["reason"] == "isolated failures and errors did not decrease" + assert "candidate isolation fails" in fixture.prompts[1][1] + assert "candidate isolation fails" in (fixture.root / attempt["candidate_failure_path"]).read_text() + + +@pytest.mark.parametrize("resume", [False, True]) +def test_y6_reuses_previous_rounds_final_suite(tmp_path, monkeypatch, resume): + second_case = TEST + "::test_remaining" + + def outcomes(root, selected): + cases = {B: "passed" if revised(root, TEST) else "failed", second_case: "failed"} + return ({selected: cases[selected]} if selected else cases), {} + + def edit(root, owner, outputs): + write(root, TEST, (root / TEST).read_text() + "# revised\n") + + fixture = fake(tmp_path, monkeypatch, [ref("test", TEST)], outcomes, edit=edit) + if resume: + fixture.drive(1) + first, second = fixture.drive(2, resume=resume)["rounds"] + assert first["attempts"][0]["decision"] == "accepted" + assert second["attempts"][0]["decision"] == "rejected" + assert all(run["purpose"] != "round 2 suite" for run in second["runs"]) + assert second["reused_suites"][0]["from"].endswith("(candidate suite)") diff --git a/tests/greenfield/test_implement_test_feedback_findings.py b/tests/greenfield/test_implement_test_feedback_findings.py index 5ecc37f7..33ddb5b6 100644 --- a/tests/greenfield/test_implement_test_feedback_findings.py +++ b/tests/greenfield/test_implement_test_feedback_findings.py @@ -451,6 +451,7 @@ def test_case_depends_on_collection(request): assert actual == 1 """) pipeline, root, trace, _ = project_factory( + rounds=2, initial={ "case": {TEST_FILE: tests}, "helper": {HELPER: "FIXED = False\ndef value():\n return [7][1]\n"}, @@ -463,15 +464,17 @@ def test_case_depends_on_collection(request): ) result = pipeline.run(root) assert result.status == "success", result.error - record = _round(root) - helper, unstable = record["attempts"] + first, second = feedback(root)["rounds"] + helper, ordinary = first["attempts"] + [unstable] = second["attempts"] assert (helper["owner"], helper["decision"]) == ("helper", "accepted") + assert ordinary["owner"] == "case" and "unstable_cases" not in ordinary events = _trace(trace) isolate = f"isolate {TEST_FILE}::test_case_depends_on_collection" - assert events.count(isolate) == 1 assert events.index("feedback helper") < events.index(isolate) < events.index("feedback case") - assert [run["purpose"] for run in record["runs"][-3:]] == ["suite after helper decision", "isolate", "candidate suite"] - assert record["passed_in_isolation"] == 1 + assert second["reused_suites"][0]["purpose"] == "round 2 suite" + assert second["passed_in_isolation"] == 1 + assert list(unstable["unstable_cases"]) == [f"{TEST_FILE}::test_case_depends_on_collection"] assert (unstable["owner"], unstable["decision"]) == ("case", "rejected") assert unstable["reason"] == f"unstable test still fails: {TEST_FILE}::test_case_depends_on_collection" diff --git a/tests/greenfield/test_implement_test_feedback_owner_scheduling.py b/tests/greenfield/test_implement_test_feedback_owner_scheduling.py index 2c8c717a..6ef476b4 100644 --- a/tests/greenfield/test_implement_test_feedback_owner_scheduling.py +++ b/tests/greenfield/test_implement_test_feedback_owner_scheduling.py @@ -81,7 +81,8 @@ def exhaust_first_round(self, record, purpose, case=None, timeout=None, **kwargs first, second = rounds assert first["isolation_time_exhausted"] and not first["stop"] assert first["attempts"] == [] - assert second["runs"][0]["purpose"] == "round 2 suite" + assert second["reused_suites"] == [{"purpose": "round 2 suite", "from": "round 1 run 1 (round 1 suite)"}] + assert second["runs"][0]["purpose"] == "isolate" assert [(attempt["owner"], attempt["decision"]) for attempt in second["attempts"]] == [ ("case", "accepted"), ] @@ -123,6 +124,10 @@ def interrupt(project_root, tasks, *args, **kwargs): with pytest.raises(KeyboardInterrupt): pipeline.run(root) + [interrupted_round] = feedback(root)["rounds"] + assert [(attempt["owner"], attempt["decision"]) for attempt in interrupted_round["attempts"]] == [ + ("a", "pending"), ("b", "started"), + ] [record] = _run(pipeline, root, resume=True) assert [(attempt["owner"], attempt["decision"]) for attempt in record["attempts"]] == [ ("a", "accepted"), ("b", "rejected"), ("c", "accepted"), diff --git a/tests/greenfield/test_implement_test_feedback_round3.py b/tests/greenfield/test_implement_test_feedback_round3.py index 5ae22e1b..91b04f1a 100644 --- a/tests/greenfield/test_implement_test_feedback_round3.py +++ b/tests/greenfield/test_implement_test_feedback_round3.py @@ -44,6 +44,7 @@ def test_dependent(request): assert test_subject.FIX_ENABLED and len(request.session.items) == 1 """) pipeline, root, trace, _ = project_factory( + rounds=2, initial={"case": {TEST_FILE: "FIX_ENABLED = False\n" + TESTS}, "dependent": {other: dependent}}, owned={"case": (TEST_FILE,), "dependent": (other,)}, fixes={ @@ -51,16 +52,21 @@ def test_dependent(request): "dependent": {"files": {other: "# Still depends on collection.\n" + dependent}}, }, ) - record = _run(pipeline, root) - attempt, unstable = record["attempts"] + result = pipeline.run(root) + assert result.status == "success", result.error + first, second = feedback(root)["rounds"] + attempt, ordinary = first["attempts"] + [unstable] = second["attempts"] assert (attempt["owner"], attempt["decision"]) == ("case", "accepted") assert attempt["suite_after"] == 1 - assert record["passed_in_isolation"] == 1 + assert ordinary["owner"] == "dependent" and "unstable_cases" not in ordinary + assert second["passed_in_isolation"] == 1 timeline = trace.read_text().splitlines() isolate = f"isolate {other}::test_dependent" - assert timeline.count(isolate) == 1 assert timeline.index("feedback case") < timeline.index(isolate) assert timeline.index(isolate) < timeline.index("feedback dependent") + assert second["reused_suites"][0]["purpose"] == "round 2 suite" + assert list(unstable["unstable_cases"]) == [f"{other}::test_dependent"] assert (unstable["owner"], unstable["decision"]) == ("dependent", "rejected") assert unstable["reason"] == f"unstable test still fails: {other}::test_dependent" diff --git a/tests/greenfield/test_implement_test_feedback_w18_review.py b/tests/greenfield/test_implement_test_feedback_w18_review.py index b6858f1a..ffe8be90 100644 --- a/tests/greenfield/test_implement_test_feedback_w18_review.py +++ b/tests/greenfield/test_implement_test_feedback_w18_review.py @@ -178,8 +178,8 @@ def cleanup(): ("case", "accepted", 1, 0), ] helper_attempt, case_attempt = record["attempts"] - assert (helper_attempt["suite_before"], helper_attempt["suite_after"]) == (2, 1) - assert (case_attempt["suite_before"], case_attempt["suite_after"]) == (1, 0) + assert (helper_attempt["suite_before"], helper_attempt["suite_after"]) == (2, 0) + assert (case_attempt["suite_before"], case_attempt["suite_after"]) == (2, 0) helper_prompt = trace.with_name("prompt-helper").read_text() case_prompt = trace.with_name("prompt-case").read_text() assert "test_shared (teardown" in helper_prompt and "test_shared (call" not in helper_prompt diff --git a/tests/greenfield/test_implement_test_feedback_w21b_review.py b/tests/greenfield/test_implement_test_feedback_w21b_review.py index c7bdec70..f8d8643b 100644 --- a/tests/greenfield/test_implement_test_feedback_w21b_review.py +++ b/tests/greenfield/test_implement_test_feedback_w21b_review.py @@ -191,8 +191,11 @@ def outcomes(root, selected): failed = False cases = {A: "passed" if fixed else "failed", B: "failed" if failed else "passed"} if reprovision: + cases[B] = "failed" if not selected and not already_reprovisioned else "passed" cases[C] = "passed" if already_reprovisioned else "failed" details = {A: {"origin": HELPER}, B: {"detail": "baseline evidence", **(origin or {})}} + if reprovision: + details[B]["origin"] = HELPER return ({selected: cases[selected]} if selected else cases), details return outcomes @@ -236,8 +239,10 @@ def edit(root, owner, scope): assert [owner for owner, _ in case.prompts] == ["repair", "third"] and n_provisions == 2 [record] = state["rounds"] assert record["unstable_observations"][0]["case"] == B - assert record["runs"][-1]["purpose"] == "suite after reprovisioning" - assert record["runs"][-1]["failures_and_errors"] == 0 + [reprovisioned] = [run for run in record["runs"] if run["purpose"] == "suite after reprovisioning"] + assert reprovisioned["failures_and_errors"] == 1 + assert record["runs"][-1]["purpose"] == "candidate isolate" + assert record["attempts"][0]["suite_after"] == 0 assert state["pending_unstable"] == {} and record["stop"] From c0f2fe16842c80f6471bb7fedf20778c27ad63eb Mon Sep 17 00:00:00 2001 From: yohey-w Date: Tue, 1 Dec 2026 16:22:42 +0900 Subject: [PATCH 4/8] fix(greenfield): keep judging runs unchanged; re-run only elided failures for evidence Second review follow-up. - Runs that decide verdicts (the round suite, candidate suites and isolation runs) use pytest's default assertion rendering again: a more verbose AssertionError text could change a test that matches on it. - When a returned failure shows pytest's elision markers (kept as data in the pytest feedback adapter), that one case is re-run once with full assertion rendering, inside the existing isolation time budget. Its text is used only as evidence, and only when it failed at the same place and phase. - Masked tokens use placeholders that do not occur in ordinary output, so a literal "#" can no longer collide with a masked number. - Fixed instructions to the owner stay outside the window; only the evidence is windowed. - The loop's state directory is never treated as a declared output (a `**/*.txt` glob no longer makes stored evidence writable or part of the existing-output context). - An aborted start after earlier commands reported cases still stores the full output. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_014yyaLv8ZQ3GiQnmizx4cqb --- codd/greenfield/implement_test_feedback.py | 119 +++++++--- .../adapters/_pytest_feedback_probe.py | 23 +- codd/languages/adapters/pytest_feedback.py | 16 +- .../greenfield/test_full_failure_evidence.py | 212 +++++++++++++++++- .../test_implement_test_feedback.py | 7 +- 5 files changed, 332 insertions(+), 45 deletions(-) diff --git a/codd/greenfield/implement_test_feedback.py b/codd/greenfield/implement_test_feedback.py index 6e78e395..56f54c8b 100644 --- a/codd/greenfield/implement_test_feedback.py +++ b/codd/greenfield/implement_test_feedback.py @@ -51,7 +51,8 @@ _REGRESSION_REASON = "previously passing test now fails in isolation" _UNSTABLE_REASON = "unstable test still fails" _UNSTABLE_ASSERTIONS_REASON = "unstable test assertions changed" -STATE_DIRECTORY = ".codd/implement-test-feedback" +_STATE_ROOT = Path(".codd") +STATE_DIRECTORY = f"{_STATE_ROOT}/implement-test-feedback" _ARCHIVE = f"{STATE_DIRECTORY}/rollback.zip" _ADVICE = ( "The design documents and their verifiable behaviors are the acceptance criteria. " @@ -87,10 +88,11 @@ def __init__(self, root: Path, outputs, *, expand_globs: bool = True): relative = bool(path.parts) and not absolute and ".." not in path.parts and ":" not in name if expand_globs and (absolute or relative) and _is_glob_decl(name): for match in iter_project_glob(root, name, follow_symlinks=False): - if match.is_file(): - self.paths[match.relative_to(root)] = False + matched_path = match.relative_to(root) + if not matched_path.is_relative_to(_STATE_ROOT) and match.is_file(): + self.paths[matched_path] = False continue - if not relative: + if not relative or path.is_relative_to(_STATE_ROOT): continue target = root / path if target.resolve() != target: @@ -116,7 +118,7 @@ def exclude_claims(self, other: DeclaredOutputs) -> None: self.excluded[path] = directory or self.excluded.get(path, False) def excludes(self, path: Path) -> bool: - return self._contains(path, self.excluded) + return path.is_relative_to(_STATE_ROOT) or self._contains(path, self.excluded) @staticmethod def _contains(path: Path, paths: dict[Path, bool]) -> bool: @@ -380,6 +382,7 @@ class _Suite: collection_errors: dict[str, str] = field(default_factory=dict) output: str = "" run_label: str = "" + unreported_launch: bool = False def _writes(before, after): @@ -396,15 +399,26 @@ def _case_failure_detail(failure: dict) -> str: _EVIDENCE_VARIABLE = re.compile( - r"\b[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12}\b|" - r"(?<=\bat )0x[0-9a-f]+\b|\b(?:0x)?[0-9a-f]{8,}\b|\d{5,}", + r"(?P\b[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12}\b)|" + r"(?P
(?<=\bat )0x[0-9a-f]+\b)|" + r"(?P\b(?:0x)?[0-9a-f]{8,}\b)|(?P\d{5,})", re.IGNORECASE, ) +def _evidence_line_shape(line: str) -> tuple[str, ...]: + # Alternate literal spans with markers so a literal marker cannot match a substitution. + spans = [] + end = 0 + for match in _EVIDENCE_VARIABLE.finditer(line): + spans.extend((line[end:match.start()], f"⟨{match.lastgroup}⟩")) + end = match.end() + return (*spans, line[end:]) + + def _group_evidence_lines(output: str) -> str: lines = output.splitlines() - shapes = [_EVIDENCE_VARIABLE.sub("#", line) if line.strip() else None for line in lines] + shapes = [_evidence_line_shape(line) if line.strip() else None for line in lines] counts = Counter(shape for shape in shapes if shape is not None) grouped = [] for line, shape in zip(lines, shapes): @@ -542,19 +556,14 @@ def prepare(self, round_record) -> str | None: self.pipeline._checkpoint(self.root) return None - def run_tests(self, round_record, purpose, case=None, timeout=None, *, target=None) -> _Suite: - # Each command starts with the round baseline and the selected outputs. - target = self.target if target is None else target - self.snapshot.restore(target) + def _execute_tests(self, case, timeout, started, *, detailed=False) -> tuple[_Suite, str]: shell = isinstance(self.command, str) - started = time.monotonic() - self.pipeline.echo(f"[implement test feedback] {purpose}: {self.display}" + (f" [{case}]" if case else "")) - timeout = self.timeout if timeout is None else timeout output_tail = "" try: with tempfile.TemporaryDirectory(prefix="codd-test-feedback-") as directory: scratch = Path(directory) - env = self.adapter.environment(self.env, scratch, self.root, self.sources, case) + options = {"detailed": True} if detailed else {} + env = self.adapter.environment(self.env, scratch, self.root, self.sources, case, **options) with subprocess.Popen( self.adapter.instrument_command(self.command, scratch), cwd=self.cwd, env=env, shell=shell, text=True, @@ -580,6 +589,8 @@ def run_tests(self, round_record, purpose, case=None, timeout=None, *, target=No scratch, process.returncode, output_tail, ) result = _Suite(cases, failures, unavailable, collection_errors=collection_errors, output=output) + if has_unreported_launch := getattr(self.adapter, "has_unreported_launch", None): + result.unreported_launch = has_unreported_launch(scratch) except subprocess.TimeoutExpired as exc: result = _Suite( unavailable=f"test command exceeded {timeout:g}s", timed_out=True, @@ -587,6 +598,16 @@ def run_tests(self, round_record, purpose, case=None, timeout=None, *, target=No ) except (OSError, ValueError) as exc: result = _Suite(unavailable=f"test command unavailable: {exc}") + return result, output_tail + + def run_tests(self, round_record, purpose, case=None, timeout=None, *, target=None) -> _Suite: + # Each command starts with the round baseline and the selected outputs. + target = self.target if target is None else target + self.snapshot.restore(target) + started = time.monotonic() + self.pipeline.echo(f"[implement test feedback] {purpose}: {self.display}" + (f" [{case}]" if case else "")) + timeout = self.timeout if timeout is None else timeout + result, output_tail = self._execute_tests(case, timeout, started) if self.snapshot.environment_changed(round_record["environment_before"]): self.environment_dirty = True result.unavailable = "test environment changed during test execution" @@ -606,14 +627,14 @@ def run_tests(self, round_record, purpose, case=None, timeout=None, *, target=No event["case"] = case if result.unavailable: event["unavailable"] = _command_output_tail(result.unavailable, None) - if result.timed_out or not (result.cases or result.collection_errors): - # The adapter receives the same bounded diagnostic as before. - # Replace that embedded excerpt with the full captured streams - # when saving evidence for a run that could not report cases. - reason = result.unavailable.removesuffix(output_tail).rstrip() - full = "\n".join(filter(None, (reason, result.output))) - saved = record_full_failure(self.root, self.snapshot.archive.parent, full) - event["unavailable_evidence"] = _evidence_reference(saved) + if result.unavailable or (result.unreported_launch and result.output): + # An earlier invocation in a compound command may already have + # reported cases when a later one fails before it can report any. + reason = (result.unavailable or "").removesuffix(output_tail).rstrip() + full = "\n".join(filter(None, (reason, result.output))) + saved = record_full_failure(self.root, self.snapshot.archive.parent, full) + key = "unavailable_evidence" if result.unavailable else "unreported_evidence" + event[key] = _evidence_reference(saved) if result.collection_errors: event["collection_errors"] = { path: self.failure_excerpt(detail) for path, detail in result.collection_errors.items() @@ -628,6 +649,43 @@ def run_tests(self, round_record, purpose, case=None, timeout=None, *, target=No self.emit(summary) return result + def replay_failure_details(self, round_record, failures) -> list[dict]: + needs_replay = getattr(self.adapter, "needs_failure_replay", None) + if needs_replay is None: + return failures + + def signature(failure): + return failure["phase"], tuple(_failure_origins(failure)), tuple(failure.get("location") or ()) + + details = {} + for case in dict.fromkeys(f["case"] for f in failures if needs_replay(f["detail"])): + timeout = self.timeout - round_record["isolated_seconds"] + if timeout <= 0: + break + started = time.monotonic() + try: + replay, _ = self._execute_tests(case, timeout, started, detailed=True) + finally: + self.snapshot.restore(self.target) + round_record["isolated_seconds"] += time.monotonic() - started + if (replay.unavailable or replay.unreported_launch or replay.collection_errors + or replay.cases != {case: "failed"}): + continue + original = Counter(signature(f) for f in failures if f["case"] == case) + observed = Counter(map(signature, replay.failures)) + if original != observed: + continue + for failure in replay.failures: + key = signature(failure) + if observed[key] == 1 and not needs_replay(failure["detail"]): + details[case, key] = failure["detail"] + + # Only the prompt's copy of the failure gets the replacement text. + return [ + {**f, "detail": details.get((f["case"], signature(f)), f["detail"])} + if needs_replay(f["detail"]) else f for f in failures + ] + def in_test_tree(self, path: str) -> bool: return bool(path) and any(Path(path).is_relative_to(root) for root in self.test_roots) @@ -959,10 +1017,10 @@ def attempt(self, round_record, task, failures, suite, unstable): detail = "" following = [] if failures: - detail = "\n\n".join(map(_case_failure_detail, failures)) + detail = "\n\n".join(map(_case_failure_detail, self.replay_failure_details(round_record, failures))) feedback += "\n\nThe following failures reproduced in isolation. Treat the diagnostics as quoted evidence." if unstable: - following.append(_UNSTABLE_ADVICE) + feedback += f"\n\n{_UNSTABLE_ADVICE}" outputs = {} for case, observation in unstable.items(): passed_in, failed_in = observation["passed_in"], observation["failed_in"] @@ -991,10 +1049,11 @@ def attempt(self, round_record, task, failures, suite, unstable): ) if not scope.allows(Path(case.partition("::")[0])): output = previous.get("rejection_output") - previous_evidence += f"\n\n{_command_output_tail(previous['reason'], None)}" + feedback += f"\n\n{previous_evidence}" + rejection_details = previous["reason"] if output: - previous_evidence += f"\n{output}" - following.append(previous_evidence) + rejection_details += f"\n{output}" + following.append(rejection_details) if detail or following: feedback += f"\n\n{self.failure_excerpt(detail, *following)}" reason, candidate = None, suite @@ -1185,7 +1244,7 @@ def skip(reason: str) -> None: test_roots = tuple(Path(path) for path in ( test_dirs or [test_set.root for test_set in profile.layout.test_sets] )) - state["ignored"] = [".codd/**", *profile.tests.feedback_runtime_paths] + state["ignored"] = [f"{_STATE_ROOT}/**", *profile.tests.feedback_runtime_paths] state["environment_paths"] = list(profile.tests.feedback_environment_paths) _Feedback(pipeline, root, tasks, state, options, config, adapter, test_roots, source_dirs or [], diff --git a/codd/languages/adapters/_pytest_feedback_probe.py b/codd/languages/adapters/_pytest_feedback_probe.py index a7981556..1d82c8aa 100644 --- a/codd/languages/adapters/_pytest_feedback_probe.py +++ b/codd/languages/adapters/_pytest_feedback_probe.py @@ -11,11 +11,13 @@ import tempfile import time from collections import defaultdict +from contextlib import suppress from pathlib import Path import pytest +_UNREPORTED_LAUNCH = pytest.StashKey[Path]() _ENVIRONMENT_ERRNOS = { errno.EACCES, errno.EPERM, errno.ECONNREFUSED, errno.ECONNRESET, errno.EHOSTUNREACH, errno.ENETUNREACH, errno.EADDRINUSE, @@ -42,6 +44,14 @@ @pytest.hookimpl(tryfirst=True) def pytest_load_initial_conftests(early_config): + # A compound command can hide this launch's exit status. Mark the launch + # before conftest imports and clear it once its case report is available. + report_dir = os.environ.get("CODD_TEST_FEEDBACK_REPORT") + if report_dir: + with suppress(OSError), tempfile.NamedTemporaryFile( + dir=report_dir, prefix="unreported-", delete=False, + ) as marker: + early_config.stash[_UNREPORTED_LAUNCH] = Path(marker.name) cache_dir = os.environ.get("CODD_TEST_FEEDBACK_CACHE_DIR") if not cache_dir or not early_config.pluginmanager.hasplugin("cacheprovider"): return @@ -66,10 +76,10 @@ def pytest_load_initial_conftests(early_config): def pytest_configure(config): - # The assertion is rendered before makereport can read longrepr. Set only - # pytest's assertion verbosity, after the launcher has parsed its options. - # Pytest has no scalar ini setter. - if config.get_verbosity(pytest.Config.VERBOSITY_ASSERTIONS) < 2: + # Assertion rewriting also uses this setting in the exception message. + # Change it only when replaying a case for evidence. Pytest has no scalar ini setter. + if (os.environ.get("CODD_TEST_FEEDBACK_DETAILED") == "1" + and config.get_verbosity(pytest.Config.VERBOSITY_ASSERTIONS) < 2): config._inicache["verbosity_assertions"] = "2" config.pluginmanager.register(_Probe(), "codd-feedback-observer") @@ -177,6 +187,7 @@ def pytest_runtest_makereport(self, item, call): if problem: self.environment.append(problem) origins, paths = self._failure_paths(chain) + crash = getattr(report.longrepr, "reprcrash", None) self.failures.append({ "case": case, "file": file, @@ -184,6 +195,7 @@ def pytest_runtest_makereport(self, item, call): "origins": origins, "paths": paths, "phase": report.when, + "location": [crash.path, crash.lineno] if crash is not None else None, "detail": str(report.longrepr), }) outcome = report.outcome if not getattr(report, "wasxfail", None) else "skipped" @@ -209,6 +221,9 @@ def pytest_sessionfinish(self, session, exitstatus): "cases": cases, "failures": self.failures, "environment": self.environment, "collection_errors": self.collection_errors, "exitstatus": exitstatus, }, stream) + if marker := session.config.stash.get(_UNREPORTED_LAUNCH, None): + with suppress(OSError): + marker.unlink(missing_ok=True) def _project_path(self, filename): if str(filename).startswith("<"): diff --git a/codd/languages/adapters/pytest_feedback.py b/codd/languages/adapters/pytest_feedback.py index b661d069..6830a473 100644 --- a/codd/languages/adapters/pytest_feedback.py +++ b/codd/languages/adapters/pytest_feedback.py @@ -5,6 +5,7 @@ import ast import json import os +import re import shutil from collections import Counter, defaultdict from collections.abc import Collection @@ -17,6 +18,12 @@ _PROBE = Path(__file__).with_name("_pytest_feedback_probe.py") +_ASSERTION_OMISSION = re.compile( + r"^(?:E[ \t]+)?(?:Use -v to get more diff|" + r"(?:Omitting \d+ identical items|Skipping \d+ identical (?:leading|trailing) characters in diff)," + r" use -vv? to show|\.\.\.Full output truncated(?: \(\d+ lines? hidden\))?, use '-vv' to show)[ \t]*$", + re.IGNORECASE | re.MULTILINE, +) _MAX_ASSERTION_COPIES = 256 _MAX_NAME_EXPANSION_DEPTH = 64 _MAX_EXPANDED_FORM_NODES = 2_000 @@ -47,7 +54,7 @@ def instrument_command(self, command, scratch: Path): def environment( self, env: dict[str, str], scratch: Path, project_root: Path, - source_dirs: list[str], case: str | None, + source_dirs: list[str], case: str | None, *, detailed: bool = False, ) -> dict[str, str]: # The project's provisioned interpreter need not have CoDD installed. shutil.copyfile(_PROBE, scratch / _PROBE.name) @@ -63,8 +70,15 @@ def environment( "CODD_TEST_FEEDBACK_SOURCES": json.dumps(source_dirs), "CODD_TEST_FEEDBACK_REPORT": str(scratch), "CODD_TEST_FEEDBACK_CASE": case or "", + "CODD_TEST_FEEDBACK_DETAILED": "1" if detailed else "", } + def needs_failure_replay(self, detail: str) -> bool: + return _ASSERTION_OMISSION.search(detail) is not None + + def has_unreported_launch(self, scratch: Path) -> bool: + return next(scratch.glob("unreported-*"), None) is not None + def read( self, scratch: Path, returncode: int, output: str, ) -> tuple[dict[str, str], list[dict], str | None, dict[str, str]]: diff --git a/tests/greenfield/test_full_failure_evidence.py b/tests/greenfield/test_full_failure_evidence.py index ddf1cbc2..ec1d15ec 100644 --- a/tests/greenfield/test_full_failure_evidence.py +++ b/tests/greenfield/test_full_failure_evidence.py @@ -3,6 +3,7 @@ import json import re import shlex +import subprocess import sys from pathlib import Path from types import SimpleNamespace @@ -13,11 +14,15 @@ from codd.deployment.providers.verification.pytest_http import PytestHttpTemplate from codd.greenfield.implement_test_feedback import ( STATE_DIRECTORY, + _ADVICE, _Feedback, + _REGRESSION_REASON, _Suite, + _UNSTABLE_ADVICE, _group_evidence_lines, ) from codd.greenfield.test_rederivation import STATUS_GREEN, run_test_rederivation +from codd.implementer import _existing_output_files_context from codd.languages.adapters.pytest_feedback import PytestFeedbackAdapter from codd.repair.verify_runner import VerifyRunner @@ -139,7 +144,7 @@ def test_legacy_suite_keeps_main_failure_window(tmp_path, verification_project): assert not (tmp_path / ".codd/verify/.failure-evidence").exists() -def _feedback_runner(root, command, path, calls, *, timeout=30): +def _feedback_runner(root, command, path, calls, *, timeout=30, extra_outputs=()): def capture(_root, _tasks, prompt, _config, **_kwargs): calls.append(prompt) raise ValueError("stop after recording the prompt") @@ -148,7 +153,7 @@ def capture(_root, _tasks, prompt, _config, **_kwargs): echo=lambda _: None, _checkpoint=lambda _: None, _provision_env=lambda _: None, _reimplement_tasks=capture, ) - task = SimpleNamespace(task_id="case", design_node="test:subject", expected_outputs=(path,)) + task = SimpleNamespace(task_id="case", design_node="test:subject", expected_outputs=(path, *extra_outputs)) round_record = {"number": 1, "runs": [], "attempts": [], "isolated_seconds": 0.0} state = {"rounds": [round_record], "ignored": [".codd/**"], "environment_paths": []} settings = {"verify": {"test_command": command, "test_timeout_seconds": timeout}} @@ -217,7 +222,7 @@ def test_owner_excerpt_bounds_the_join_of_unstable_runs(tmp_path, measurements): assert len(unstable) == 2 runner.attempt(record, task, [], failed, unstable) prompt, = calls - evidence = prompt.split("\n\nUnstable tests\n", 1)[1] + evidence = prompt.split(f"\n\n{_UNSTABLE_ADVICE}\n\n", 1)[1] full = _assert_excerpt(tmp_path, STATE_DIRECTORY, evidence) assert "\n... (truncated) ...\n" in evidence assert full.count("Failure output from") == 2 @@ -227,8 +232,8 @@ def test_owner_excerpt_bounds_the_join_of_unstable_runs(tmp_path, measurements): assert f"{label}-start;" + label[0] * 13000 + f";{label}-end" in saved_output -def _unavailable_diagnostic(root, event): - reference = FULL_EVIDENCE.fullmatch(event["unavailable_evidence"]) +def _saved_run_diagnostic(root, event, evidence_key="unavailable_evidence"): + reference = FULL_EVIDENCE.fullmatch(event[evidence_key]) assert reference path = root / reference[1] assert path.is_relative_to(root / STATE_DIRECTORY) @@ -245,7 +250,7 @@ def test_suite_timeout_keeps_both_partial_streams(tmp_path): suite = runner.run_tests(record, "suite") assert suite.timed_out and suite.cases == {} assert suite.unavailable == "test command exceeded 2s" - full = _unavailable_diagnostic(tmp_path, record["runs"][0]) + full = _saved_run_diagnostic(tmp_path, record["runs"][0]) assert suite.unavailable in full assert stdout in full and stderr in full @@ -260,7 +265,7 @@ def test_startup_collection_error_keeps_full_diagnostic(tmp_path, measurements): assert "error before collection" in suite.unavailable event = record["runs"][0] assert "\n... (truncated) ...\n" in event["unavailable"] - assert problem in _unavailable_diagnostic(tmp_path, event) + assert problem in _saved_run_diagnostic(tmp_path, event) def test_rederivation_uses_main_feedback_even_with_verify_evidence(tmp_path): @@ -282,3 +287,196 @@ def test_rederivation_uses_main_feedback_even_with_verify_evidence(tmp_path): "the design documents and the VB contract; do not carry over any expectation " "without re-deriving it" ] + + +def _project_test(root, body): + path = "tests/test_subject.py" + (root / path).parent.mkdir() + (root / path).write_text(body, encoding="utf-8") + (root / "pytest.ini").write_text("[pytest]\nverbosity_assertions = 0\n", encoding="utf-8") + return path + + +def test_e6_judgment_matches_main_suite_and_isolation(tmp_path, measurements): + path = _project_test(tmp_path, '''\ +import pytest + +def test_expected_message(): + with pytest.raises(AssertionError, match="Use -v to get more diff"): + assert list(range(40)) == [] + +def test_failure(): + items = [{"item": n} for n in range(40)] + assert items == [], items + +def test_followup(): + pass +''') + command = _pytest_command(path) + runner, record, _ = _feedback_runner(tmp_path, command, path, []) + case = f"{path}::test_failure" + for selected, expected_cases in ( + (None, {f"{path}::test_expected_message": "passed", case: "failed", f"{path}::test_followup": "passed"}), + (case, {case: "failed"}), + ): + # Plain pytest is the main branch's assertion/terminal behavior. Compare + # the full captured streams apart from the wall time printed by pytest. + main = subprocess.run(shlex.split(_pytest_command(selected or path)), cwd=tmp_path, + capture_output=True, text=True, check=False) + observed = runner.run_tests(record, "isolate" if selected else "suite", case=selected) + assert main.returncode == 1 + assert observed.unavailable is None and observed.cases == expected_cases + assert len(observed.failures) == 1 and observed.failures[0]["case"] == case + output = "\n".join(part for part in (main.stdout, main.stderr) if part) + elapsed = r" in \d+(?:\.\d+)?s(?=\s*$)" + assert re.sub(elapsed, "", observed.output) == re.sub(elapsed, "", output) + + +def test_e6_replays_only_omitted_diagnostic_and_only_once(tmp_path, measurements, monkeypatch): + path = _project_test(tmp_path, BODY + "\ndef test_short():\n assert False, 'Full output truncated'\n") + (tmp_path / path).with_name("measurements.json").write_text(json.dumps(measurements), encoding="utf-8") + calls = [] + runner, record, task = _feedback_runner(tmp_path, _pytest_command(path), path, calls) + suite = runner.run_tests(record, "suite") + record.update(screened={}, isolated=0, passed_in_isolation=0) + failures, problem = runner.screen(record, task.task_id, suite, suite.failures, set()) + assert problem is None and len(failures) == 2 + assert SECOND_REASON not in suite.output + assert "Use -v to get more diff" in failures[0]["detail"] + assert SECOND_REASON not in failures[0]["detail"] + before_replay = record["isolated_seconds"] + replays = [] + execute = runner._execute_tests + + def track(case, timeout, started, *, detailed=False): + replays.append((case, timeout, detailed)) + return execute(case, timeout, started, detailed=detailed) + + monkeypatch.setattr(runner, "_execute_tests", track) + runner.attempt(record, task, failures, suite, {}) + assert replays == [(f"{path}::test_subject", runner.timeout - before_replay, True)] + assert record["isolated_seconds"] > before_replay + assert len(record["runs"]) == 3 # suite and the two judgment runs + assert record["attempts"][0]["isolated_before"] == 2 + assert SECOND_REASON not in failures[0]["detail"] + prompt, = calls + assert FIRST_REASON in prompt and SECOND_REASON in prompt and "Full output truncated" in prompt + + +@pytest.mark.parametrize("replay_outcome", ["passes", "setup fails", "other assertion fails", "no time"]) +def test_e6_keeps_original_when_replay_cannot_reproduce(tmp_path, measurements, replay_outcome): + path = _project_test(tmp_path, f'''\ +import pytest + +@pytest.fixture +def verbose(request): + enabled = request.config.get_verbosity("assertions") >= 2 + if enabled and {replay_outcome!r} == "setup fails": + pytest.fail("discard this replay") + return enabled + +def test_subject(verbose): + if verbose and {replay_outcome!r} != "no time": + if {replay_outcome!r} == "other assertion fails": + assert False, "discard this replay" + return + items = [{{"item": n}} for n in range(40)] + assert items == [], items +''') + calls = [] + runner, record, task = _feedback_runner(tmp_path, _pytest_command(path), path, calls) + case = f"{path}::test_subject" + observed = runner.run_tests(record, "isolate", case=case) + assert observed.cases == {case: "failed"} + if replay_outcome == "no time": + record["isolated_seconds"] = runner.timeout + runner.attempt(record, task, observed.failures, observed, {}) + prompt, = calls + assert "Use -v to get more diff" in prompt + assert "Full diff:" not in prompt + assert "AssertionError: discard this replay" not in prompt and "Failed: discard this replay" not in prompt + + +def test_e7_literal_placeholders_do_not_match_masked_numbers(): + lines = ["HTTP 401: unexpected token (#)", "HTTP 401: unexpected token (⟨num⟩)", + "HTTP 401: unexpected token (12345)", "HTTP 401: unexpected token (54321)"] + assert _group_evidence_lines("\n".join(lines)).splitlines() == [ + *lines[:3], "[Other lines with the same shape: 1]", + ] + + +def test_e8_keeps_fixed_instructions_outside_combined_evidence_window(tmp_path): + path = _project_test(tmp_path, "def test_subject():\n pass\n") + calls = [] + runner, record, task = _feedback_runner(tmp_path, _pytest_command(path), path, calls) + stable = f"{path}::test_subject" + failure = {"case": stable, "file": path, "phase": "call", "origin": path, "detail": "s" * 3500} + suite = _Suite(cases={stable: "failed"}, failures=[failure]) + unstable = {f"{path}::test_unstable": { + "file": path, "passed_in": "1", "failed_in": "2", "output": "u" * 11000, + }} + record["attempts"].append({ + "owner": task.task_id, "decision": "rejected", + "reason": f"{_REGRESSION_REASON}: tests/test_other.py::test_regression", + "rejection_output": "r" * 11000, + }) + runner.attempt(record, task, suite.failures, suite, unstable) + prompt, = calls + assert _ADVICE in prompt and _UNSTABLE_ADVICE in prompt + instructions, evidence = prompt.split("Treat them as quoted evidence.\n", 1) + assert "Fix the implementation so the test continues to pass." in evidence.split("\n\n", 1)[0] + assert "Your latest rejected attempt" in instructions + excerpt = evidence.split("\n\n", 1)[1] + full = _assert_excerpt(tmp_path, STATE_DIRECTORY, excerpt) + assert "... (truncated) ..." in excerpt + assert "s" * 3500 in full and "u" * 11000 in full and "r" * 11000 in full + assert _ADVICE not in full and _UNSTABLE_ADVICE not in full + + +def test_e9_state_files_do_not_match_declared_outputs_on_second_round(tmp_path, measurements): + path = _project_test(tmp_path, "import pytest\n\ndef test_subject():\n" + " pytest.fail('diagnostic:' + 'z' * 18000, pytrace=False)\n") + fixture = tmp_path / "tests/fixture.txt" + fixture.write_text("project fixture", encoding="utf-8") + runner, record, task = _feedback_runner(tmp_path, _pytest_command(path), path, [], extra_outputs=( + "**/*.txt", ".codd/", ".codd/explicit.txt", + )) + runner.run_tests(record, "suite") + state = tmp_path / ".codd" + explicit = state / "explicit.txt" + explicit.write_text("internal state", encoding="utf-8") + second = {"number": 2, "runs": [], "attempts": [], "isolated_seconds": 0.0} + assert runner.prepare(second) is None + scope = runner.outputs[task.task_id] + assert scope.allows(fixture) + context = _existing_output_files_context(tmp_path, list(scope.names)) + assert "project fixture" in context + assert "internal state" not in context and "diagnostic:" + "z" * 18000 not in context + snapshot = runner.snapshot.capture() + artifacts = list(state.rglob("*.txt")) + assert len(artifacts) >= 2 + for file in artifacts: + relative = file.relative_to(tmp_path) + assert scope.excludes(relative) and not scope.allows(file) + assert relative.as_posix() not in snapshot + explicit.write_text("new internal state", encoding="utf-8") + runner.snapshot.restore(snapshot) + assert explicit.read_text(encoding="utf-8") == "new internal state" + + +@pytest.mark.parametrize("masked_exit", [False, True]) +def test_e10_keeps_precollection_error_after_reported_cases(tmp_path, measurements, masked_exit): + path = _project_test(tmp_path, "def test_subject():\n pass\n") + later = tmp_path / "later" + later.mkdir() + problem = "startup error: " + "x" * 15000 + ":end" + (later / "conftest.py").write_text(f"raise RuntimeError({problem!r})\n", encoding="utf-8") + command = f"{_pytest_command(path)} && (cd later && {_pytest_command()})" + if masked_exit: + command += "; true" + runner, record, _ = _feedback_runner(tmp_path, command, path, []) + suite = runner.run_tests(record, "suite") + assert suite.cases == {f"{path}::test_subject": "passed"} + assert bool(suite.unavailable) is not masked_exit and not suite.collection_errors + evidence_key = "unreported_evidence" if masked_exit else "unavailable_evidence" + assert problem in _saved_run_diagnostic(tmp_path, record["runs"][0], evidence_key) diff --git a/tests/greenfield/test_implement_test_feedback.py b/tests/greenfield/test_implement_test_feedback.py index da30b2ee..276f2c88 100644 --- a/tests/greenfield/test_implement_test_feedback.py +++ b/tests/greenfield/test_implement_test_feedback.py @@ -289,9 +289,10 @@ def test_flaky(request): assert [item["decision"] for item in round_record["attempts"]] == ["accepted", "accepted"] assert [(item["before"], item["after"]) for item in round_record["attempts"]] == [(1, 0), (2, 1)] case_prompt = trace.with_name("prompt-case").read_text() - reproduced, unstable = case_prompt.split("\n\nUnstable tests\n", 1) - assert "test_subject (call" in reproduced - assert f"{TEST_FILE}::test_flaky\nPassed in " in unstable + instructions, diagnostics = case_prompt.split("\n\nUnstable tests\n", 1) + assert "The following failures reproduced in isolation." in instructions + assert "test_subject (call" in diagnostics + assert f"{TEST_FILE}::test_flaky\nPassed in " in diagnostics helper_prompt = trace.with_name("prompt-helper").read_text() review = helper_prompt.split("--- REVIEW FEEDBACK", 1)[1].split("--- END REVIEW FEEDBACK", 1)[0] assert HELPER in review and "test_helper" in review From 088c24e9c840678c26aad1312772dd67e287d397 Mon Sep 17 00:00:00 2001 From: yohey-w Date: Tue, 1 Dec 2026 17:21:47 +0900 Subject: [PATCH 5/8] fix(greenfield): run evidence re-runs last and show both texts Third review follow-up. - Evidence re-runs (full assertion rendering for an elided failure) run only after the round's verdict isolation runs are done and only within the time that is left, so they never push a verdict run out of the budget. While other owners are still unprocessed in the round, the original text is returned. - When the re-run text is used, the original (verdict) text comes first and the re-run text follows, labelled as a re-run whose different rendering can show a different reason. - Elision markers are matched after trimming surrounding whitespace (`--tb=native` indents them). Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_014yyaLv8ZQ3GiQnmizx4cqb --- codd/greenfield/implement_test_feedback.py | 33 ++++--- codd/languages/adapters/pytest_feedback.py | 8 +- .../greenfield/test_full_failure_evidence.py | 95 +++++++++++++++++++ 3 files changed, 119 insertions(+), 17 deletions(-) diff --git a/codd/greenfield/implement_test_feedback.py b/codd/greenfield/implement_test_feedback.py index 56f54c8b..8c07edc8 100644 --- a/codd/greenfield/implement_test_feedback.py +++ b/codd/greenfield/implement_test_feedback.py @@ -652,12 +652,12 @@ def run_tests(self, round_record, purpose, case=None, timeout=None, *, target=No def replay_failure_details(self, round_record, failures) -> list[dict]: needs_replay = getattr(self.adapter, "needs_failure_replay", None) if needs_replay is None: - return failures + return [] def signature(failure): return failure["phase"], tuple(_failure_origins(failure)), tuple(failure.get("location") or ()) - details = {} + details = [] for case in dict.fromkeys(f["case"] for f in failures if needs_replay(f["detail"])): timeout = self.timeout - round_record["isolated_seconds"] if timeout <= 0: @@ -671,20 +671,16 @@ def signature(failure): if (replay.unavailable or replay.unreported_launch or replay.collection_errors or replay.cases != {case: "failed"}): continue - original = Counter(signature(f) for f in failures if f["case"] == case) + original = [f for f in failures if f["case"] == case] observed = Counter(map(signature, replay.failures)) - if original != observed: + if Counter(map(signature, original)) != observed: continue + omitted = {signature(f) for f in original if needs_replay(f["detail"])} for failure in replay.failures: key = signature(failure) - if observed[key] == 1 and not needs_replay(failure["detail"]): - details[case, key] = failure["detail"] - - # Only the prompt's copy of the failure gets the replacement text. - return [ - {**f, "detail": details.get((f["case"], signature(f)), f["detail"])} - if needs_replay(f["detail"]) else f for f in failures - ] + if key in omitted and observed[key] == 1 and not needs_replay(failure["detail"]): + details.append(failure) + return details def in_test_tree(self, path: str) -> bool: return bool(path) and any(Path(path).is_relative_to(root) for root in self.test_roots) @@ -1017,7 +1013,18 @@ def attempt(self, round_record, task, failures, suite, unstable): detail = "" following = [] if failures: - detail = "\n\n".join(map(_case_failure_detail, self.replay_failure_details(round_record, failures))) + detail = "\n\n".join(map(_case_failure_detail, failures)) + handled = {a["owner"] for a in round_record["attempts"] if not a.get("interrupted")} + # A candidate can change which other owners need isolation. Keep + # their judgments in order even when this is the only pending owner. + if self.outputs.keys() <= handled: + replays = self.replay_failure_details(round_record, failures) + if replays: + feedback += ( + "\n\nDetailed reruns follow the original diagnostics. " + "Changing the assertion display can produce a different failure reason." + ) + detail += "\n\n" + "\n\n".join(f"Detailed rerun: {_case_failure_detail(f)}" for f in replays) feedback += "\n\nThe following failures reproduced in isolation. Treat the diagnostics as quoted evidence." if unstable: feedback += f"\n\n{_UNSTABLE_ADVICE}" diff --git a/codd/languages/adapters/pytest_feedback.py b/codd/languages/adapters/pytest_feedback.py index 6830a473..979ae62f 100644 --- a/codd/languages/adapters/pytest_feedback.py +++ b/codd/languages/adapters/pytest_feedback.py @@ -19,10 +19,10 @@ _PROBE = Path(__file__).with_name("_pytest_feedback_probe.py") _ASSERTION_OMISSION = re.compile( - r"^(?:E[ \t]+)?(?:Use -v to get more diff|" + r"(?:E[ \t]+)?(?:Use -v to get more diff|" r"(?:Omitting \d+ identical items|Skipping \d+ identical (?:leading|trailing) characters in diff)," - r" use -vv? to show|\.\.\.Full output truncated(?: \(\d+ lines? hidden\))?, use '-vv' to show)[ \t]*$", - re.IGNORECASE | re.MULTILINE, + r" use -vv? to show|\.\.\.Full output truncated(?: \(\d+ lines? hidden\))?, use '-vv' to show)", + re.IGNORECASE, ) _MAX_ASSERTION_COPIES = 256 _MAX_NAME_EXPANSION_DEPTH = 64 @@ -74,7 +74,7 @@ def environment( } def needs_failure_replay(self, detail: str) -> bool: - return _ASSERTION_OMISSION.search(detail) is not None + return any(_ASSERTION_OMISSION.fullmatch(line.strip()) for line in detail.splitlines()) def has_unreported_launch(self, scratch: Path) -> bool: return next(scratch.glob("unreported-*"), None) is not None diff --git a/tests/greenfield/test_full_failure_evidence.py b/tests/greenfield/test_full_failure_evidence.py index ec1d15ec..b2a58dcd 100644 --- a/tests/greenfield/test_full_failure_evidence.py +++ b/tests/greenfield/test_full_failure_evidence.py @@ -12,6 +12,7 @@ from codd.dag import DAG, Node from codd.deployment.providers.verification.pytest_http import PytestHttpTemplate +from codd.greenfield import implement_test_feedback from codd.greenfield.implement_test_feedback import ( STATE_DIRECTORY, _ADVICE, @@ -480,3 +481,97 @@ def test_e10_keeps_precollection_error_after_reported_cases(tmp_path, measuremen assert bool(suite.unavailable) is not masked_exit and not suite.collection_errors evidence_key = "unreported_evidence" if masked_exit else "unavailable_evidence" assert problem in _saved_run_diagnostic(tmp_path, record["runs"][0], evidence_key) + + +@pytest.mark.parametrize("timeout", [6, 10], ids=["exhausted", "remaining"]) +def test_e11_replays_only_after_the_rounds_judgment_isolates(tmp_path, monkeypatch, timeout): + first = _project_test(tmp_path, "def test_subject(): pass\n") + second = "tests/test_second.py" + (tmp_path / second).write_text("def test_subject(): pass\n", encoding="utf-8") + calls = [] + runner, _, _ = _feedback_runner(tmp_path, _pytest_command("tests"), first, calls, timeout=timeout) + runner.tasks.append(SimpleNamespace(task_id="second", design_node="test:second", expected_outputs=(second,))) + runner.state["rounds"].clear() + + cases = [f"{path}::test_subject" for path in (first, second)] + files = dict(zip(cases, (first, second))) + durations = dict(zip(cases, (4, 2))) + now = 0.0 + commands = [] + + def execute(case, budget, _started, *, detailed=False): + nonlocal now + commands.append((case, budget, detailed)) + duration = durations.get(case, 0) + now += min(duration, budget) + if duration > budget: + return _Suite(timed_out=True, unavailable="test command timed out"), "" + selected = [case] if case else cases + outcomes = dict.fromkeys(selected, "failed") + failures = [ + {"case": name, "file": files[name], "origin": files[name], "phase": "call", + "detail": "full assertion diff" if detailed else "Use -v to get more diff"} + for name in selected + ] + return _Suite(cases=outcomes, failures=failures), "" + + monkeypatch.setattr(implement_test_feedback, "time", SimpleNamespace(monotonic=lambda: now)) + monkeypatch.setattr(runner, "_execute_tests", execute) + runner.run(1) + + record, = runner.state["rounds"] + assert [(event.get("case"), event["executed_cases"], event["failures_and_errors"]) for event in record["runs"]] == [ + (None, 2, 2), (cases[0], 1, 1), (cases[1], 1, 1), + ] + expected_commands = [(None, timeout, False), (cases[0], timeout, False), (cases[1], timeout - 4, False)] + if timeout > 6: + expected_commands.append((cases[1], timeout - 6, True)) + assert commands == expected_commands + assert [(attempt["owner"], attempt["isolated_before"]) for attempt in record["attempts"]] == [ + ("case", 1), ("second", 1), + ] + first_prompt, second_prompt = calls + assert "Use -v to get more diff" in first_prompt and "Detailed rerun:" not in first_prompt + assert "Use -v to get more diff" in second_prompt + assert ("full assertion diff" in second_prompt) == (timeout > 6) + + +def test_e12_keeps_judgment_reason_when_detailed_replay_fails_at_same_line(tmp_path, measurements): + (tmp_path / "reasons.txt").write_text("original-parser-bug\nfallback-server-bug\n", encoding="utf-8") + path = _project_test(tmp_path, '''\ +from pathlib import Path + +def test_subject(): + original, fallback = Path('reasons.txt').read_text().splitlines() + try: + assert list(range(40)) == [] + except AssertionError as error: + reason = original if 'Use -v to get more diff' in str(error) else fallback + rows = [{'reason': reason}] * 40 + assert rows == [], rows +''') + calls = [] + runner, _, _ = _feedback_runner(tmp_path, _pytest_command("--tb=short", path), path, calls) + runner.state["rounds"].clear() + runner.run(1) + + prompt, = calls + assert "Changing the assertion display can produce a different failure reason." in prompt + original, detailed = prompt.split("\n\nDetailed rerun:", 1) + assert "original-parser-bug" in original and "Use -v to get more diff" in original + assert "fallback-server-bug" not in original and "fallback-server-bug" in detailed + + +def test_e13_replays_indented_omission_in_native_traceback(tmp_path, measurements): + path = _project_test(tmp_path, BODY) + (tmp_path / path).with_name("measurements.json").write_text(json.dumps(measurements), encoding="utf-8") + calls = [] + runner, record, task = _feedback_runner(tmp_path, _pytest_command("--tb=native", path), path, calls) + observed = runner.run_tests(record, "isolate", f"{path}::test_subject") + failure, = observed.failures + omission = next(line for line in failure["detail"].splitlines() if "Use -v to get more diff" in line) + assert omission.startswith(" ") and SECOND_REASON not in failure["detail"] + + runner.attempt(record, task, observed.failures, observed, {}) + prompt, = calls + assert FIRST_REASON in prompt and SECOND_REASON in prompt From 9d138b6184a847600fea6f441a6bbd578a2b7329 Mon Sep 17 00:00:00 2001 From: yohey-w Date: Tue, 1 Dec 2026 17:45:14 +0900 Subject: [PATCH 6/8] fix(greenfield): use the combined suite only to screen; accept owners one by one Review follow-up (10 blocking findings on judging every owner from one combined suite: another owner's change could hide a failure, make a useless change look like progress, or swap a correct fix for the culprit). - After every returned owner has made its fix, one combined suite screens them: an owner whose returned cases neither passed nor (for an implementation owner) moved is rejected and restored without a suite of its own. The rest are accepted or rejected one at a time exactly as on main (each candidate on top of the accepted tree, gates 1-9 unchanged). - Routing to the implementation owner uses the dependencies of the task that declares the failing test file; a claim names the case ids it covers and applies only to them; CoDD's own appends (usage log) no longer turn a claim into "could not evaluate". - The failure fingerprint is the whole masked failure text; the failure after a rejected change is kept per owner and case. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_014yyaLv8ZQ3GiQnmizx4cqb --- codd/ai_invoke.py | 22 + codd/greenfield/implement_test_feedback.py | 853 +++++++++--------- .../test_implement_test_feedback.py | 6 +- ...implement_test_feedback_assertion_forms.py | 4 +- ...nt_test_feedback_assertion_forms_round2.py | 2 +- .../test_implement_test_feedback_batch.py | 221 ++++- .../test_implement_test_feedback_round2.py | 2 +- .../test_implement_test_feedback_unstable.py | 5 +- .../test_implement_test_feedback_w18_r2.py | 10 +- ...test_implement_test_feedback_w18_review.py | 4 +- ...est_implement_test_feedback_w21b_review.py | 52 +- 11 files changed, 669 insertions(+), 512 deletions(-) diff --git a/codd/ai_invoke.py b/codd/ai_invoke.py index 4091a10b..674827db 100644 --- a/codd/ai_invoke.py +++ b/codd/ai_invoke.py @@ -51,6 +51,7 @@ import sys import tempfile import time +from contextlib import contextmanager from contextvars import ContextVar from pathlib import Path from typing import Any, Callable, Mapping @@ -109,6 +110,25 @@ # Plain text-in/text-out AI invoker signature shared across the codebase. AiInvoke = Callable[[str], str] +_stdout_observer: ContextVar[Callable[[str], None] | None] = ContextVar( + "ai_stdout_observer", default=None, +) + + +@contextmanager +def observe_ai_stdout(observer: Callable[[str], None]): + """Observe a successful subprocess response before file capture replaces it.""" + token = _stdout_observer.set(observer) + try: + yield + finally: + _stdout_observer.reset(token) + + +def _observe_stdout(output: str) -> None: + if observer := _stdout_observer.get(): + observer(output) + # The implement/generate file-output contract a text-in/text-out CLI emits on # stdout: one ``=== FILE: ===`` header per generated file. Kept local # (not imported from ``codd.implementer``) to avoid a circular import — the @@ -415,6 +435,7 @@ def invoke_file_writing_agent( detail = (result.stderr.strip() or result.stdout.strip() or f"exit code {result.returncode}") raise ValueError(f"AI command failed: {detail}") + _observe_stdout(result.stdout) # Keep UTF-8 names literal in both listings and make diff paths relative to cwd. # Set the options in the subprocess environments to preserve the Git argv. @@ -600,6 +621,7 @@ def _invoke_subprocess( note_failure("empty_output") raise ValueError("AI command returned empty output") + _observe_stdout(result.stdout) return result.stdout diff --git a/codd/greenfield/implement_test_feedback.py b/codd/greenfield/implement_test_feedback.py index 6b5130c8..216711de 100644 --- a/codd/greenfield/implement_test_feedback.py +++ b/codd/greenfield/implement_test_feedback.py @@ -21,6 +21,7 @@ from pathlib import Path from zipfile import ZIP_DEFLATED, BadZipFile, ZipFile, ZipInfo +from codd.ai_invoke import observe_ai_stdout from codd.ai_usage import resolve_usage_log from codd.ansi import strip_ansi from codd.greenfield.pipeline import ( @@ -55,6 +56,7 @@ _STATE_ROOT = Path(".codd") STATE_DIRECTORY = f"{_STATE_ROOT}/implement-test-feedback" _ARCHIVE = f"{STATE_DIRECTORY}/rollback.zip" +_CLAIM_PREFIX = "CODD_TEST_FEEDBACK_CLAIM " _ADVICE = ( "The design documents and their verifiable behaviors are the acceptance criteria. " "Do not rewrite expectations to match observed behavior. If the cause is outside your " @@ -406,32 +408,11 @@ def _case_failure_detail(failure: dict) -> str: return f"{failure['case']} ({failure['phase']}, {failure['origin']})\n{failure['detail']}" -_FINGERPRINT_VARIABLE = re.compile( - r"\b[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12}\b|" - r"\b(?:0x[0-9a-f]+|[0-9a-f]{8,})\b|\d+", re.IGNORECASE, -) - - def _failure_fingerprint(failure): if "fingerprint" in failure: return failure["fingerprint"] - origin = failure["origin"] - function = "" - if origin: - frames = re.findall(rf'{re.escape(origin)}(?::\d+(?::\d+)?:?|"\s*,\s*line\s+\d+)' - r'\s+in\s+(\S+)', failure["detail"]) - if frames: - function = frames[-1] - lines = failure["detail"].splitlines() - messages = [line.removeprefix("E ").strip() for line in map(str.strip, lines) - if line.startswith("E ")] - if not messages: - messages = [line.strip() for line in lines if line.strip()] - head = messages[0] if messages else "" - typed = re.search(r'(?:^|:\s+)([\w.]+(?:Error|Exception|Failure))(?=\s*:|$)', head) - if typed: - head = head[typed.start(1):] - return f"{origin}|{function}|{_FINGERPRINT_VARIABLE.sub('#', head[:500])}" + shape = _evidence_line_shape(failure["detail"]) + return hashlib.sha256(json.dumps(shape).encode()).hexdigest() def _failure_key(failure): @@ -512,7 +493,7 @@ def __init__(self, pipeline, root, tasks, state, options, config, adapter, test_ self.suite_cache = self.snapshot.archive.with_name("last-suite.zip") self.suites = self.load_last_suite() self.candidate_unstable = [] - self.isolated_failures = {} + self.isolated_failures = [] self.logs = {AUDIT_RELATIVE_PATH} try: usage_log = resolve_usage_log(config, root) @@ -729,7 +710,7 @@ def fingerprints(suite): by_case[failure["case"]].append(_failure_fingerprint(failure)) return dict(by_case) - def full_suite(self, round_record, purpose, target): + def full_suite(self, round_record, purpose, target, *, reuse=False): digest = hashlib.sha256() for name, entry in sorted(target.items()): digest.update(json.dumps((name, entry.mode, len(entry.data))).encode()) @@ -737,7 +718,7 @@ def full_suite(self, round_record, purpose, target): environment = round_record["environment_before"] digest.update(json.dumps((self.command, str(self.cwd), self.env, environment), sort_keys=True).encode()) key = digest.digest() - if key in self.suites and not self.snapshot.environment_changed(environment): + if reuse and key in self.suites and not self.snapshot.environment_changed(environment): result = self.suites[key] round_record.setdefault("reused_suites", []).append({"purpose": purpose, "from": result.run_label}) self.snapshot.restore(target) @@ -808,8 +789,12 @@ def owner(self, failure) -> str | None: owners.add(matches[0]) return next(iter(owners)) if len(owners) == 1 else None - def body_owner(self, failure, claim=None, *, test_owner=None): - test_owner = test_owner or self.owner({"origin": failure["file"]}) + def body_owner(self, failure, claim=None): + file = failure["file"] + if not self.in_test_tree(file): + return None + test_owners = [owner for owner, scope in self.declared.items() if scope.allows(Path(file))] + test_owner = test_owners[0] if len(test_owners) == 1 else None if test_owner is None or not self.tasks_by_id[test_owner].dependencies: return None dependencies = self.tasks_by_id[test_owner].dependencies @@ -953,27 +938,14 @@ def integrity_problem(self, before, after, unstable_files: set[str]) -> str | No return f"skip/xfail increased in {rel}" return None - def count(self, suite, failures, unstable, changed, baseline, *, isolated=False) -> int: - returned = {_failure_key(f) for f in failures} - cases = {f["case"] for f in failures} - changed = set(changed) - count = 0 - for failure in suite.failures: - case = failure["case"] - if case in unstable: - continue - key = _failure_key(failure) - if key in returned: - count += 1 - continue - touched = failure["file"] in changed or changed.issuperset(_failure_origins(failure)) - if isolated: - # A returned error can move between phases in isolation. - # Charge a changed file for a new error, rather than that move. - count += touched and (case, _failure_fingerprint(failure)) not in baseline - else: - count += (case in cases or touched) and key not in baseline - return count + def count(self, suite, owner, cases, unstable): + return sum( + f["case"] not in unstable and ( + f["case"] in cases or self.owner(f) == owner + or self.outputs[owner].matches(Path(f["file"])) and bool(f["file"]) + ) + for f in suite.failures + ) def change_problem(self, outputs, before, after, unstable) -> str | None: outside = [rel for rel, new in _writes(before, after).items() if not self.allowed_change( @@ -1015,16 +987,6 @@ def gate_problem(self, round_record, target): return "test environment changed during candidate checks" return reason - @staticmethod - def suite_problem(suite, candidate): - if candidate.unavailable: - return "candidate suite could not complete" - if candidate.collection_errors.keys() - suite.collection_errors.keys(): - return "candidate introduced collection errors" - if list(candidate.cases.values()).count("skipped") > list(suite.cases.values()).count("skipped"): - return "runtime skip/xfail increased" - return None - def isolate(self, round_record, case, purpose, target, deadline): exceeded = "candidate isolation exceeded the test time budget" remaining = deadline - time.monotonic() @@ -1037,82 +999,100 @@ def isolate(self, round_record, case, purpose, target, deadline): return None, f"candidate could not verify {case}" return result, None - def check_returned(self, record, attempt, suite, candidate, target, changes, deadline): - failures = attempt["returned_failures"] + @staticmethod + def body_progress(suite, case, before): + status = suite.cases.get(case) + if status == "passed": + return "fixed" + after = {_failure_fingerprint(f) for f in suite.failures if f["case"] == case} + if status == "failed" and before and after and before.isdisjoint(after): + return "progressed" + return None + + def assess(self, record, attempt, suite, failures, target): + owner = attempt["owner"] + body = attempt["recipient"] == "body" unstable = attempt.get("unstable_cases", {}) + before = self.target + keys = {_failure_key(f) for f in failures} case_ids = list(dict.fromkeys(f["case"] for f in failures)) - baseline = {_failure_key(f) for f in suite.failures} - attempt["before"] = self.count(suite, failures, unstable, (), baseline) - attempt["after"] = self.count(candidate, failures, unstable, changes, baseline) + attempt["before"] = self.count(suite, owner, case_ids, unstable) + attempt["suite_before"] = len(suite.failures) + attempt["isolated_before"] = len(failures) + if reason := self.gate_problem(record, target): + return reason, None, None + + candidate = self.full_suite(record, "candidate suite", target) + attempt["after"] = self.count(candidate, owner, case_ids, unstable) attempt["suite_after"] = len(candidate.failures) - attempt["isolated_after"] = None - isolated_failures = self.isolated_failures[id(attempt)] = [] + if candidate.unavailable: + return "candidate suite could not complete", candidate, None + if candidate.collection_errors.keys() - suite.collection_errors.keys(): + return "candidate introduced collection errors", candidate, None for case in unstable: if candidate.cases.get(case) != "passed": - return f"{_UNSTABLE_REASON}: {case}" - body = attempt["recipient"] == "body" - if body and any(suite.cases.get(case) != "failed" for case in case_ids): - return "returned failure no longer reproduces in the baseline suite" - count_problem = None + return f"{_UNSTABLE_REASON}: {case}", candidate, None + if list(candidate.cases.values()).count("skipped") > list(suite.cases.values()).count("skipped"): + return "runtime skip/xfail increased", candidate, None if not body and failures and attempt["after"] >= attempt["before"]: - count_problem = _COUNT_REASON + return _COUNT_REASON, candidate, None + deadline = time.monotonic() + self.timeout isolated_after = 0 progress = [] - # Confirm a source owner's progress with the original test files, - # even when the combined suite contains other owners' test edits. - isolation_target = self.combine(self.target, [changes]) if body else target - returned = {_failure_key(f) for f in failures} - known_errors = {(f["case"], _failure_fingerprint(f)) for f in suite.failures} for case in case_ids: - result, problem = self.isolate(record, case, "candidate isolate", isolation_target, deadline) + if body and suite.cases.get(case) != "failed": + return "returned failure no longer reproduces in the baseline suite", candidate, None + result, problem = self.isolate(record, case, "candidate isolate", target, deadline) if problem: - return count_problem or problem - isolated_failures.extend(result.failures) + return problem, candidate, None + self.isolated_failures.extend(result.failures) if body: for observed, original in ((candidate, suite.failures), (result, failures)): - before = {_failure_fingerprint(f) for f in original - if f["case"] == case and _failure_key(f) in returned} - if observed.cases.get(case) == "passed": - progress.append("fixed") - elif (before and observed.cases.get(case) == "failed" and - (after := set(self.fingerprints(observed).get(case, ()))) and before.isdisjoint(after)): - progress.append("progressed") - else: - return f"failure fingerprint did not advance: {case}" + fingerprints = {_failure_fingerprint(f) for f in original + if f["case"] == case and _failure_key(f) in keys} + outcome = self.body_progress(observed, case, fingerprints) + if not outcome: + return f"failure fingerprint did not advance: {case}", candidate, None + progress.append(outcome) else: - isolated_after += self.count(result, failures, unstable, changes, known_errors, - isolated=True) + isolated_after += sum(_failure_key(f) in keys for f in result.failures) if candidate.cases.get(case) == "failed" and result.cases[case] == "passed": self.candidate_unstable.append((case, result, candidate)) + for case in unstable: for _ in range(_UNSTABLE_VERIFICATION_RUNS): result, problem = self.isolate(record, case, "candidate unstable isolate", target, deadline) if problem: - return problem - isolated_failures.extend(result.failures) + return problem, candidate, None + self.isolated_failures.extend(result.failures) if result.cases[case] != "passed": - return f"{_UNSTABLE_REASON}: {case}" + return f"{_UNSTABLE_REASON}: {case}", candidate, None + reason, regression = self.regression(record, attempt, suite, candidate, before, target, deadline) + if reason: + return reason, candidate, regression attempt["isolated_after"] = isolated_after + if not body and failures and isolated_after >= len(failures): + return "isolated failures and errors did not decrease", candidate, None if body: attempt["progress"] = "progressed" if "progressed" in progress else "fixed" - return count_problem + return None, candidate, None def defer_unstable(self, record, case, passed, failed): - self.observe_unstable(record, case, passed, failed) deferred = record.setdefault("deferred_unstable", []) if case not in deferred: deferred.append(case) + self.observe_unstable(record, case, passed, failed) - def regression(self, record, attempts, suite, candidate, before, target, deadline, *, baseline_errors=None): + def regression(self, record, attempt, suite, candidate, before, target, deadline): for case, status in suite.cases.items(): if status != "passed" or candidate.cases.get(case) == "passed": continue for _ in range(_CANDIDATE_REGRESSION_RUNS): result, problem = self.isolate(record, case, "candidate isolate", target, deadline) if problem: - return problem, None, None + return problem, None if result.cases[case] == "passed": if candidate.cases.get(case) == "failed": self.candidate_unstable.append((case, result, candidate)) @@ -1122,72 +1102,40 @@ def regression(self, record, attempts, suite, candidate, before, target, deadlin for passed in range(_BASELINE_REGRESSION_RUNS): baseline, problem = self.isolate(record, case, "baseline isolate", before, deadline) if problem: - return problem, None, None + return problem, None if baseline.cases[case] != "passed": - for attempt in attempts: - attempt.setdefault("baseline_failures", []).append({ - "case": case, "passed": passed, "failed": 1, - }) - if baseline_errors is not None: - baseline_errors.update( - (_failure_key(failure), _failure_fingerprint(failure)) for failure in baseline.failures - ) + attempt.setdefault("baseline_failures", []).append({ + "case": case, "passed": passed, "failed": 1, + }) self.observe_unstable(record, case, suite, baseline) break else: - return f"{_REGRESSION_REASON}: {case}", case, result - return None, None, None + return f"{_REGRESSION_REASON}: {case}", result + return None, None - @staticmethod - def combine(before, changes): - combined = before.copy() - for delta in changes: - for path, entry in delta.items(): - if entry is None: - combined.pop(path, None) - else: - combined[path] = entry - return combined - - def culprit(self, before, active, changes, passes): - # A repair can interact with another repair. Try omissions first, - # then replay in generation order when the result is ambiguous. - def check(identifiers): - return passes(self.combine(before, (changes[index] for index in identifiers))) - - if len(active) == 1: - return active[0] - omissions = [] - for index in active: - result = check(other for other in active if other != index) - if result is None: - return None - if result: - omissions.append(index) - if len(omissions) == 1: - return omissions[0] - for end, index in enumerate(active, 1): - result = check(active[:end]) - if result is None: - return None - if not result: - return index - return None - - def reject(self, attempt, reason, candidate=None, *, culprit=False, regression=None): - attempt.update(decision="rejected", reason=reason, verdict="culprit" if culprit else "gate rejected") + def reject(self, attempt, reason, candidate=None, *, suite=None, regression=None, screening=False): + attempt.update(decision="rejected", reason=reason, verdict="gate rejected") if candidate is not None: cases = {f["case"] for f in attempt["returned_failures"]} | attempt.get("unstable_cases", {}).keys() - failures = [*candidate.failures, *self.isolated_failures.get(id(attempt), ())] - detail = "\n\n".join(dict.fromkeys(_case_failure_detail(f) for f in failures if f["case"] in cases)) - if detail: + sections = defaultdict(dict) + for failure in (*candidate.failures, *self.isolated_failures): + if failure["case"] in cases: + sections[failure["case"]][_case_failure_detail(failure)] = None + if sections: + details = {case: "\n\n".join(lines) for case, lines in sections.items()} + detail = "\n\n".join(details.values()) attempt["candidate_failure"] = self.failure_excerpt(detail) + attempt["candidate_failures_by_case"] = { + case: self.failure_excerpt(output) for case, output in details.items() + } saved = record_full_failure(self.root, self.snapshot.archive.parent, detail) if saved: attempt["candidate_failure_path"] = saved[0].as_posix() - if self.record_stall(attempt, candidate) and "did not decrease" in reason: + if screening: + attempt["candidate_failure_from_screening"] = True + if self.record_stall(attempt, suite, candidate) and reason == _COUNT_REASON: attempt["verdict"] = "stalled" - elif "fingerprint did not advance" in reason: + elif reason.startswith("failure fingerprint did not advance"): attempt["verdict"] = "stalled" _, _, case = reason.partition(": ") scope = self.scope(attempt["owner"], attempt["recipient"] == "body") @@ -1196,157 +1144,32 @@ def reject(self, attempt, reason, candidate=None, *, culprit=False, regression=N regression.output or "\n\n".join(f["detail"] for f in regression.failures), ) - def review_one_at_a_time(self, record, attempts, active, changes, before, suite): - accepted = [] - for index in active: - attempt = attempts[index] - self.isolated_failures.pop(id(attempt), None) - target = self.combine(before, [changes[index]]) - reason = self.gate_problem(record, target) - candidate = regression = None - if not reason: - candidate = self.full_suite(record, "candidate suite (one owner)", target) - reason = self.suite_problem(suite, candidate) - if not reason: - deadline = time.monotonic() + self.timeout - reason = self.check_returned(record, attempt, suite, candidate, target, changes[index], deadline) - if not reason: - reason, _, regression = self.regression(record, [attempt], suite, candidate, before, target, deadline) - reason = reason or self.isolated_problem(attempt) - if reason: - self.reject(attempt, reason, candidate, regression=regression) - else: - accepted.append(index) - before, suite = target, candidate - if self.environment_dirty: - break - return accepted, suite - - @staticmethod - def isolated_problem(attempt): - if (attempt["recipient"] == "test" and attempt["isolated_before"] - and attempt["isolated_after"] is not None - and attempt["isolated_after"] >= attempt["isolated_before"]): - return "isolated failures and errors did not decrease" - return None - - def review_batch(self, record, attempts, active, changes, suite): - before = self.target - if len({attempts[index]["owner"] for index in active}) != len(active): - return self.review_one_at_a_time(record, attempts, active, changes, before, suite) - purpose = "candidate suite" - while active: - self.isolated_failures.clear() - target = self.combine(before, (changes[index] for index in active)) - reason = self.gate_problem(record, target) - candidate = regression = None - if self.environment_dirty: - break - if reason: - def passes(artifacts): - problem = self.gate_problem(record, artifacts) - return None if self.environment_dirty else problem is None - - culprit = self.culprit(before, active, changes, passes) - else: - candidate = self.full_suite(record, purpose, target) - reason = self.suite_problem(suite, candidate) - if reason: - if len(active) == 1: - self.reject(attempts[active[0]], reason, candidate) - return [], suite - return self.review_one_at_a_time(record, attempts, active, changes, before, suite) - problems = {} - deadline = time.monotonic() + self.timeout - for index in active: - attempt = attempts[index] - owner_deadline = deadline if len(active) == 1 else time.monotonic() + self.timeout - problem = self.check_returned(record, attempt, suite, candidate, - target, changes[index], owner_deadline) - if self.environment_dirty: - return [], suite - if problem: - problems[index] = problem - if len(active) == 1 and problems: - self.reject(attempts[active[0]], problems[active[0]], candidate) - return [], suite - if len(active) > 1: - deadline = time.monotonic() + self.timeout - observed_errors = set() - reason, case, regression = self.regression( - record, [attempts[index] for index in active], suite, candidate, before, target, deadline, - baseline_errors=observed_errors, - ) - if not reason: - baseline_errors = { - _failure_key(failure) for failure in candidate.failures - if (_failure_key(failure), _failure_fingerprint(failure)) in observed_errors - } - if baseline_errors: - baseline_errors.update(map(_failure_key, suite.failures)) - for index, problem in list(problems.items()): - if problem != _COUNT_REASON: - continue - attempt = attempts[index] - if attempt["isolated_after"] is None: - continue - attempt["after"] = self.count( - candidate, attempt["returned_failures"], attempt.get("unstable_cases", {}), - changes[index], baseline_errors, - ) - if attempt["after"] < attempt["before"]: - del problems[index] - for index in active: - if problem := self.isolated_problem(attempts[index]): - problems.setdefault(index, problem) - if not problems: - return active, candidate - if len(active) > 1 and self.ambiguous_owner_problem( - problems, attempts, changes, suite, candidate, baseline_errors, - ): - return self.review_one_at_a_time(record, attempts, active, changes, before, suite) - for index, problem in problems.items(): - self.reject(attempts[index], problem, candidate) - active = [index for index in active if index not in problems] - purpose = "suite after removing candidates" - continue - - def passes(artifacts): - result, problem = self.isolate(record, case, "attribute regression", artifacts, deadline) - return None if problem else result.cases[case] == "passed" - - culprit = self.culprit(before, active, changes, passes) if case else None - - if self.environment_dirty: - break - if culprit is None and len(active) > 1: - return self.review_one_at_a_time(record, attempts, active, changes, before, suite) - index = active[0] if culprit is None else culprit - self.reject(attempts[index], reason, candidate, culprit=len(active) > 1 or purpose != "candidate suite", - regression=regression) - active.remove(index) - purpose = "suite after removing candidates" - return [], suite - - def ambiguous_owner_problem(self, problems, attempts, changes, suite, candidate, baseline_errors): - baseline = baseline_errors | {_failure_key(f) for f in suite.failures} - for index, problem in problems.items(): - if problem.startswith(("candidate could not verify", "candidate isolation exceeded")): - return True - if problem == _COUNT_REASON: - attempt = attempts[index] - failures = attempt["returned_failures"] - unstable = attempt.get("unstable_cases", {}) - returned = {_failure_key(f) for f in failures} - existing = sum(_failure_key(f) in returned and f["case"] not in unstable - for f in candidate.failures) - if existing < attempt["before"] <= self.count( - candidate, failures, unstable, changes[index], baseline, - ): - # A new error in this owner's file can originate in - # another candidate. Replay with the earlier baseline. - return True - return False + def screening_rejection(self, attempt, baseline, candidate): + if attempt["recipient"] == "body": + for case in dict.fromkeys(f["case"] for f in attempt["returned_failures"]): + original = {_failure_fingerprint(f) for f in baseline.failures if f["case"] == case} + if self.body_progress(candidate, case, original): + return None + return "failure fingerprint did not advance in screening" + unstable = attempt.get("unstable_cases", {}) + if any(candidate.cases.get(case) == "passed" for case in unstable): + return None + before = Counter(_failure_key(f) for f in attempt["returned_failures"]) + after = Counter(map(_failure_key, candidate.failures)) + cases = {case for case, _, _ in before} + if any(candidate.cases.get(case) == "passed" for case in cases): + return None + known = Counter(map(_failure_key, baseline.failures)) + for key, occurrences in before.items(): + case = key[0] + remaining = Counter({k: n for k, n in after.items() if k[0] == case}) + # A shared case may still fail in an existing phase. Replacing a + # returned failure with a new one gives no screening signal. + if remaining and after[key] < occurrences and remaining <= known: + return None + if unstable and not before: + return f"{_UNSTABLE_REASON}: {next(iter(unstable))}" + return _COUNT_REASON def allowed_change(self, path, outputs, old, new) -> bool: if outputs.allows(path): @@ -1358,6 +1181,9 @@ def allowed_change(self, path, outputs, old, new) -> bool: path in log.parents for log in self.logs ) # The shared implementation entry point appends its own diagnostics. + return self.diagnostic_append(path, old, new) + + def diagnostic_append(self, path, old, new): return ( path in self.logs and new is not None and stat.S_ISREG(new.mode) and (old is None or (old.mode == new.mode and new.data.startswith(old.data))) @@ -1380,10 +1206,9 @@ def candidate_target(self, outputs, after): raise ValueError(f"declared output has a non-directory parent in the snapshot: {name}") return kept - def keep_outputs(self, round_record, kept): + def keep_outputs(self, round_record, index, kept): # Commit the new target and the acceptance decision in that order. # An interrupted checkpoint can still use the previous target. - index = len(round_record["attempts"]) self.snapshot.persist(kept, _round_archive(self.snapshot, round_record, index)) round_record["kept_attempt"] = index self.target = kept @@ -1407,13 +1232,14 @@ def attempt(self, round_record, task, failures, suite, unstable, *, body=False): before = self.target self.snapshot.restore(before) environment_before = round_record["environment_before"] - baseline = {_failure_key(f) for f in suite.failures} + case_ids = {f["case"] for f in failures} attempt = { "owner": owner, "recipient": "body" if body else "test", - "decision": "started", "before": self.count(suite, failures, unstable, (), baseline), + "decision": "started", "before": self.count(suite, owner, case_ids, unstable), "after": None, "suite_before": len(suite.failures), "suite_after": None, "isolated_before": len(failures), "isolated_after": None, - "environment_before": environment_before, + "environment_before": environment_before, "baseline_run": suite.run_label, + "pending_delta": True, "returned_failures": [ {**{key: value for key, value in failure.items() if key != "detail"}, "fingerprint": _failure_fingerprint(failure)} for failure in failures @@ -1436,9 +1262,11 @@ def attempt(self, round_record, task, failures, suite, unstable, *, body=False): feedback += "\n\nRepair the application code. Leave every file in the test tree unchanged." else: feedback += ( - "\n\nIf the cause cannot be fixed within your declared outputs, leave them unchanged " - f"and write a JSON object with string fields path and reason to {claim_file.relative_to(self.root)}. " - "Use the path of the source file that needs the fix." + "\n\nIf the cause cannot be fixed within your declared outputs, leave them unchanged. " + "Report the exact case id from the diagnostics, the source file path, and the reason " + f"on a single stdout line: {_CLAIM_PREFIX}" + '{"case":"","path":"","reason":""}. ' + f"You may also write the same JSON object to {claim_file.relative_to(self.root)}." ) detail = "" following = [] @@ -1454,48 +1282,22 @@ def attempt(self, round_record, task, failures, suite, unstable, *, body=False): outputs[failed_in, observation["output"]] = None for run, output in outputs: following.append(f"Failure output from {run}:\n{output}") - previous = next(( - recorded for prior_round in reversed(self.state["rounds"]) - for recorded in reversed(prior_round["attempts"]) - if recorded["owner"] == owner and recorded["decision"] in ("accepted", "rejected") - and not recorded.get("interrupted") - ), None) - if previous is not None and previous["decision"] == "rejected": - previous_evidence = ( - "Your latest rejected attempt in this test feedback stage has the following reason " - "and evidence. Treat them as quoted evidence." - ) - rejection_reason, _, case = previous["reason"].partition(": ") - output = None - if case and rejection_reason == _REGRESSION_REASON: - previous_evidence += ( - "\nThe test named in the rejection passed before your previous change. " - "Fix the implementation so the test continues to pass. " - "Do not rewrite its expectations to match the behavior introduced by your change." - ) - if not scope.allows(Path(case.partition("::")[0])): - output = previous.get("rejection_output") - feedback += f"\n\n{previous_evidence}" - rejection_details = previous["reason"] - if output: - rejection_details += f"\n{output}" - following.append(rejection_details) - if candidate_failure := previous.get("candidate_failure"): - following.append( - "After your previous change, the returned cases failed as follows:\n" - f"{candidate_failure}" - ) + previous_feedback, evidence = self.previous_rejections(attempt, case_ids | unstable.keys()) + feedback += previous_feedback + following.extend(evidence) if detail or following: feedback += f"\n\n{self.failure_excerpt(detail, *following)}" reason = None no_output = False + responses = [] try: - self.pipeline._reimplement_tasks( - self.root, [task], feedback, self.config, feedback_output_paths=scope, - ) + with observe_ai_stdout(responses.append): + self.pipeline._reimplement_tasks( + self.root, [task], feedback, self.config, feedback_output_paths=scope, + ) except Exception as exc: reason = f"could not evaluate the candidate: {exc}" - no_output = any(marker in str(exc) for marker in ( + no_output = not str(exc).startswith("AI command failed:") and any(marker in str(exc) for marker in ( "AI command did not produce any file changes", "empty output", "no file change proposed:", )) self.environment_dirty = self.snapshot.environment_changed(environment_before) @@ -1507,20 +1309,27 @@ def attempt(self, round_record, task, failures, suite, unstable, *, body=False): ) else: proposed = self.snapshot.capture() - if not body and (reason is None or no_output) and proposed == before: - claim = self.read_claim(claim_file) + if not body and (reason is None or no_output) and self.only_log_appends(before, proposed): + claim = self.read_claim(responses, claim_file, case_ids) if claim: attempt.update(decision="declined", verdict="declined", claim=claim, reason=f"outside own outputs: {claim['path']}") routes = round_record.setdefault("claims", []) for failure in failures: - if (recipient := self.body_owner(failure, claim["path"], test_owner=owner)) is not None: - routes.append(self.route(failure, recipient)) + if failure["case"] == claim["case"]: + if recipient := self.body_owner(failure, claim["path"]): + routes.append(self.route(failure, recipient)) if not reason and attempt["decision"] == "started": reason = self.change_problem(scope, before, proposed, unstable) if not reason: target = self.candidate_target(scope, proposed) - self.snapshot.persist(target, _pending_archive(self.snapshot, round_record, index)) + delta = {} + for path, new in _writes(before, target).items(): + if path in before: + delta[f"before/{path}"] = before[path] + if new is not None: + delta[f"after/{path}"] = new + self.snapshot.persist(delta, _pending_archive(self.snapshot, round_record, index)) attempt.update(decision="pending", reason="awaiting the candidate suite") except (OSError, ValueError) as exc: reason = f"could not evaluate the candidate: {exc}" @@ -1536,113 +1345,279 @@ def attempt(self, round_record, task, failures, suite, unstable, *, body=False): self.emit(f"{owner}: {attempt['decision']} · {attempt['reason']}") return self.environment_dirty + def only_log_appends(self, before, proposed): + writes = _writes(before, proposed) + allowed = set() + for path in self.logs: + rel = path.as_posix() + new, old = writes.get(rel), before.get(rel) + if self.diagnostic_append(path, old, new): + allowed.add(rel) + for parent in path.parents: + name = parent.as_posix() + if name not in before and (entry := writes.get(name)) and stat.S_ISDIR(entry.mode): + allowed.add(name) + return writes.keys() <= allowed + @staticmethod - def read_claim(path): + def read_claim(responses, path, cases): + lines = [line.removeprefix(_CLAIM_PREFIX) for response in responses + for line in response.splitlines() if line.startswith(_CLAIM_PREFIX)] + if len(lines) > 1: + return None try: - claim = json.loads(path.read_text()) + claim = json.loads(lines[0] if lines else path.read_text()) except (OSError, ValueError): return None - if (isinstance(claim, dict) and all(isinstance(claim.get(key), str) and claim[key].strip() - for key in ("path", "reason"))): - return {key: claim[key].strip() for key in ("path", "reason")} - return None + fields = ("case", "path", "reason") + if not isinstance(claim, dict) or not all( + isinstance(claim.get(key), str) and claim[key].strip() for key in fields + ): + return None + claim = {key: claim[key].strip() for key in fields} + return claim if claim["case"] in cases else None - def settle(self, record, suite): - attempts = {index: attempt for index, attempt in enumerate(record["attempts"], 1) - if attempt["decision"] == "pending"} - if not attempts: - return suite - before = self.target - self.candidate_unstable.clear() - self.isolated_failures.clear() - changes = {} - for index, attempt in attempts.items(): - if not suite.unavailable and attempt["environment_before"] != record["environment_before"]: - if problem := self.check_reprovisioned_baseline(record, attempt): - self.reject(attempt, problem) + @staticmethod + def returned_cases(attempt): + return {f["case"] for f in attempt.get("returned_failures", ())} | attempt.get("unstable_cases", {}).keys() + + def previous_rejections(self, attempt, cases): + feedback = "" + evidence = [] + regression = False + for prior_round in reversed(self.state["rounds"]): + for previous in reversed(prior_round["attempts"]): + if (previous["owner"] != attempt["owner"] + or previous.get("recipient", "test") != attempt["recipient"] + or previous["decision"] not in ("accepted", "rejected") + or previous.get("interrupted")): continue + shared = cases & self.returned_cases(previous) + # Older records do not carry case ids. + if not shared and "returned_failures" not in previous: + shared = cases + if not shared: + continue + cases = cases - shared + if previous["decision"] == "rejected": + if not feedback: + feedback = ( + "\n\nYour latest rejected attempt in this test feedback stage has the following reason " + "and evidence. Treat them as quoted evidence." + ) + evidence.append(previous["reason"]) + if previous["reason"].startswith(_REGRESSION_REASON): + regression = True + if output := previous.get("rejection_output"): + evidence.append(output) + if "candidate_failures_by_case" in previous: + output = "\n\n".join(text for case, text in previous["candidate_failures_by_case"].items() + if case in shared) + else: + output = previous.get("candidate_failure", "") + if output: + context = " The screening suite included other owners' changes." if ( + previous.get("candidate_failure_from_screening") + ) else "" + evidence.append( + "After your previous change, the returned cases failed as follows:" + f"{context}\n{output}" + ) + if not cases: + break + if not cases: + break + if regression: + feedback += ( + "\nThe test named in the rejection passed before your previous change. " + "Fix the implementation so the test continues to pass. " + "Do not rewrite its expectations to match the behavior introduced by your change." + ) + return feedback, evidence + + def pending_changes(self, record, index, attempt): + entries = self.snapshot.read(_pending_archive(self.snapshot, record, index)) + if not attempt.get("pending_delta"): + # A pre-v4 archive contains a whole tree. Extract only this owner's + # outputs since other owners may already have been kept on resume. + if any(previous["decision"] == "accepted" and previous["owner"] == attempt["owner"] + for previous in record["attempts"][:index - 1]): + raise ValueError("cannot reapply an older candidate over this owner's accepted changes") + scope = self.scope(attempt["owner"], attempt["recipient"] == "body") + target = self.candidate_target(scope, entries) + return {path: (self.target.get(path), new) for path, new in _writes(self.target, target).items()} + before = {name.removeprefix("before/"): entry for name, entry in entries.items() + if name.startswith("before/")} + after = {name.removeprefix("after/"): entry for name, entry in entries.items() + if name.startswith("after/")} + return {path: (before.get(path), after.get(path)) for path in before.keys() | after.keys()} + + @staticmethod + def apply_changes(target, changes): + target = target.copy() + for path, (old, new) in changes.items(): + if target.get(path) not in (old, new): + raise ValueError(f"pending candidate conflicts with an earlier change: {path}") + if new is None: + target.pop(path, None) + else: + target[path] = new + for path in target: + parent, _, _ = path.rpartition("/") + if parent and (parent not in target or not stat.S_ISDIR(target[parent].mode)): + raise ValueError(f"pending candidate has a missing or non-directory parent: {path}") + return target + + def screen_candidates(self, record, suite, pending): + if record.get("screening_done"): + return + target = self.target + self.isolated_failures.clear() + try: + for _, _, changes in pending: + target = self.apply_changes(target, changes) + candidate = self.run_tests(record, "screening suite", target=target) + except (OSError, ValueError): + # Incompatible deltas cannot be screened together. Review each separately. + candidate = None + finally: + self.snapshot.restore(self.target) + rejected = [] + if self.environment_dirty and len(pending) == 1: + index, attempt, _ = pending[0] + self.reject(attempt, "test environment changed during candidate checks") + rejected.append((index, attempt)) + if (not self.environment_dirty and candidate and not candidate.unavailable + and not candidate.unreported_launch + and not candidate.collection_errors.keys() - suite.collection_errors.keys()): + for index, attempt, _ in pending: + if reason := self.screening_rejection(attempt, suite, candidate): + attempt["suite_after"] = len(candidate.failures) + attempt["after"] = self.count(candidate, attempt["owner"], self.returned_cases(attempt), + attempt.get("unstable_cases", {})) + self.reject(attempt, reason, candidate, suite=suite, screening=True) + rejected.append((index, attempt)) + record["screening_done"] = True + self.pipeline._checkpoint(self.root) + for index, attempt in rejected: + self.finish_attempt(record, index, attempt) + + def finish_attempt(self, record, index, attempt): + self.snapshot.restore(self.target) + self.emit( + f"[implement test feedback] {attempt['owner']}: {attempt['decision']} · {attempt['reason']} · " + f"owner {attempt['before']} → {attempt['after']} · " + f"suite {attempt['suite_before']} → {attempt['suite_after']}" + ) + _pending_archive(self.snapshot, record, index).unlink(missing_ok=True) + + def settle(self, record, suite): + pending = [] + for index, attempt in enumerate(record["attempts"], 1): + if attempt["decision"] != "pending": + continue try: - changes[index] = _writes(before, self.snapshot.read(_pending_archive(self.snapshot, record, index))) + changes = self.pending_changes(record, index, attempt) except (OSError, ValueError, BadZipFile) as exc: self.reject(attempt, f"could not read the pending candidate: {exc}") - # Keep records pending on disk while checks run. A resume can redo the - # tests even if interrupted during attribution or snapshot restoration. - if suite.unavailable or self.environment_dirty: - accepted, candidate = [], suite + self.finish_attempt(record, index, attempt) + else: + pending.append((index, attempt, changes)) + if pending and not suite.unavailable and not self.environment_dirty: + self.screen_candidates(record, suite, pending) + for index, attempt, changes in pending: + if self.environment_dirty: + break + if attempt["decision"] == "pending": + suite = self.review_candidate(record, index, attempt, changes, suite) + return suite + + def review_candidate(self, record, index, attempt, changes, suite): + self.candidate_unstable.clear() + self.isolated_failures.clear() + candidate = regression = None + reason = "candidate suite could not complete" if suite.unavailable else None + try: + if not reason: + failures, reason = self.current_failures(record, attempt, suite) + if not reason: + target = self.apply_changes(self.target, changes) + body = attempt["recipient"] == "body" + reason = self.change_problem(self.scope(attempt["owner"], body), self.target, target, + attempt.get("unstable_cases", {})) + if not reason: + reason, candidate, regression = self.assess(record, attempt, suite, failures, target) + if self.environment_dirty: + reason = "test environment changed during candidate checks" + if not reason: + self.keep_outputs(record, index, target) + except Exception as exc: + reason = f"could not evaluate the candidate: {exc}" + + if reason: + self.reject(attempt, reason, candidate, suite=suite, regression=regression) else: - try: - accepted, candidate = self.review_batch(record, attempts, list(changes), changes, suite) - except Exception as exc: - accepted, candidate = [], suite - for attempt in attempts.values(): - self.reject(attempt, f"could not evaluate the candidate: {exc}") - if self.environment_dirty: - accepted, candidate = [], suite - for attempt in attempts.values(): - self.reject(attempt, "test environment changed during candidate checks") - if accepted: - kept = self.combine(before, (changes[index] for index in accepted)) - try: - self.keep_outputs(record, kept) - except (OSError, ValueError) as exc: - accepted, candidate = [], suite - for attempt in attempts.values(): - self.reject(attempt, f"could not keep the candidate: {exc}") - for index, attempt in attempts.items(): - if index in accepted: - self.record_stall(attempt, candidate) - reason = ("failures decreased" if attempt["isolated_before"] - else "unstable tests passed the suite and isolated checks") - verdict = "fixed" - if attempt["recipient"] == "body": - verdict = attempt["progress"] - reason = "returned tests passed" if verdict == "fixed" else "failure fingerprint advanced" - attempt.update(decision="accepted", reason=reason, verdict=verdict) - elif attempt["decision"] == "pending": - self.reject(attempt, "candidate suite could not complete") - self.snapshot.restore(self.target) - if accepted: + self.record_stall(attempt, suite, candidate) + verdict = "fixed" + reason = "failures decreased" if failures else "unstable tests passed the suite and isolated checks" + if attempt["recipient"] == "body": + verdict = attempt["progress"] + reason = "returned tests passed" if verdict == "fixed" else "failure fingerprint advanced" + attempt.update(decision="accepted", reason=reason, verdict=verdict) + record["screened"].clear() + suite = candidate for case, passed, failed in self.candidate_unstable: - if failed is candidate: - self.defer_unstable(record, case, passed, failed) - self.pipeline._checkpoint(self.root) - for index, attempt in attempts.items(): - self.pipeline.echo( - f"[implement test feedback] {attempt['owner']}: {attempt['decision']} · {attempt['reason']} · " - f"owner {attempt['before']} → {attempt['after']} · " - f"suite {attempt['suite_before']} → {attempt['suite_after']}" - ) - _pending_archive(self.snapshot, record, index).unlink(missing_ok=True) - return candidate + self.defer_unstable(record, case, passed, failed) + self.finish_attempt(record, index, attempt) + return suite - def check_reprovisioned_baseline(self, record, attempt): - if attempt.get("unstable_cases"): - return "unstable test observations are from a different environment" + def current_failures(self, record, attempt, suite): + failures = attempt["returned_failures"] + same_environment = attempt["environment_before"] == record["environment_before"] + if not same_environment and attempt.get("unstable_cases"): + return [], "unstable test observations are from a different environment" + if same_environment and attempt.get("baseline_run") == suite.run_label: + return failures, None + returned = defaultdict(set) + for failure in failures: + returned[failure["case"]].add(_failure_key(failure)) + suite_keys = {_failure_key(failure) for failure in suite.failures} + reproduced = [] deadline = time.monotonic() + self.timeout - returned = defaultdict(Counter) - for failure in attempt["returned_failures"]: - returned[failure["case"]][_failure_key(failure)] += 1 - for case, expected in returned.items(): - result, problem = self.isolate(record, case, "reprovisioned baseline isolate", self.target, deadline) - if problem or expected - Counter(map(_failure_key, result.failures)): - return f"returned failure no longer reproduces after reprovisioning: {case}" - return None - - def record_stall(self, attempt, candidate): - if attempt["recipient"] != "test": + for case, keys in returned.items(): + expected = keys & suite_keys + if not expected: + continue + purpose = "baseline isolate" if same_environment else "reprovisioned baseline isolate" + result, problem = self.isolate(record, case, purpose, self.target, deadline) + observed = [] if problem else [f for f in result.failures if _failure_key(f) in expected] + if not observed: + if same_environment and not problem and result.cases[case] == "passed": + self.defer_unstable(record, case, result, suite) + context = "the current baseline" if same_environment else "reprovisioning" + return [], f"returned failure no longer reproduces after {context}: {case}" + reproduced.extend(observed) + if failures and not reproduced: + return [], "returned failures no longer reproduce in the baseline suite" + return reproduced, None + + def record_stall(self, attempt, suite, candidate): + if attempt["recipient"] != "test" or candidate.unavailable: return False - before = {(f["case"], _failure_fingerprint(f)) for f in attempt["returned_failures"]} + returned = {_failure_key(f) for f in attempt["returned_failures"]} + before = {(f["case"], _failure_fingerprint(f)) for f in suite.failures if _failure_key(f) in returned} stalled = [f for f in candidate.failures if (f["case"], _failure_fingerprint(f)) in before] if stalled: attempt["stalled_routes"] = [ self.route(failure, owner) for failure in stalled - if (owner := self.body_owner(failure, test_owner=attempt["owner"])) is not None + if (owner := self.body_owner(failure)) is not None ] return bool(stalled) def reprovision(self, record): _restore_round_for_provisioning(self.snapshot, record) _discard_feedback_environment(self.snapshot, self.state) + self.environment_dirty = False self.suites.clear() record["screened"].clear() problem = self.prepare(record) @@ -1669,7 +1644,7 @@ def run(self, rounds: int) -> None: ] if index else [] problem = self.prepare(record) suite = _Suite(unavailable=problem) if problem else self.full_suite( - record, f"round {index + 1} suite", self.target, + record, f"round {index + 1} suite", self.target, reuse=True, ) handled = {(a["owner"], a.get("recipient", "test")) for a in record["attempts"] if not a.get("interrupted")} @@ -1740,12 +1715,10 @@ def run(self, rounds: int) -> None: unreproduced.clear() suite = self.reprovision(record) - if not self.environment_dirty: + while any(attempt["decision"] == "pending" for attempt in record["attempts"]): + if self.environment_dirty: + suite = self.reprovision(record) suite = self.settle(record, suite) - else: - for attempt in record["attempts"]: - if attempt["decision"] == "pending": - self.reject(attempt, "test environment changed during candidate checks") routes = [route for attempt in record["attempts"] for route in attempt.get("stalled_routes", ())] stop = bool(suite.unavailable) or not ( self.unstable_groups() or any(owner not in interrupted for owner, _ in self.owner_groups(suite)) diff --git a/tests/greenfield/test_implement_test_feedback.py b/tests/greenfield/test_implement_test_feedback.py index a45832d2..615a57f6 100644 --- a/tests/greenfield/test_implement_test_feedback.py +++ b/tests/greenfield/test_implement_test_feedback.py @@ -280,16 +280,16 @@ def test_flaky(request): assert [x for x in calls if x.startswith("feedback ")] == ["feedback helper", "feedback case"] assert calls.index("both audits") < calls.index("provision") < calls.index("suite") assert calls.index("feedback helper") < calls.index("feedback case") < calls.index("oracle verdict") - assert calls.count("suite") == 3 # round baseline, combined candidate, final verification + assert calls.count("suite") == 5 # baseline, screening, two individual suites, final verification assert calls[-3:] == ["provision", "verify", "suite"] [round_record] = feedback(root)["rounds"] assert round_record["passed_in_isolation"] == 1 assert [run["purpose"] for run in round_record["runs"] if "case" not in run] == [ - "round 1 suite", "candidate suite", + "round 1 suite", "screening suite", "candidate suite", "candidate suite", ] assert [item["decision"] for item in round_record["attempts"]] == ["accepted", "accepted"] - assert [(item["before"], item["after"]) for item in round_record["attempts"]] == [(1, 0), (1, 0)] + assert [(item["before"], item["after"]) for item in round_record["attempts"]] == [(1, 0), (2, 1)] case_prompt = trace.with_name("prompt-case").read_text() instructions, diagnostics = case_prompt.split("\n\nUnstable tests\n", 1) assert "The following failures reproduced in isolation." in instructions diff --git a/tests/greenfield/test_implement_test_feedback_assertion_forms.py b/tests/greenfield/test_implement_test_feedback_assertion_forms.py index 78b30614..ce8f8c2d 100644 --- a/tests/greenfield/test_implement_test_feedback_assertion_forms.py +++ b/tests/greenfield/test_implement_test_feedback_assertion_forms.py @@ -48,7 +48,7 @@ def edit(root, owner, scope): assert attempts(state) == [("author", "accepted", "unstable tests passed the suite and isolated checks")] assert "state was pending" in case.prompts[0][1] assert any("marker authenticity OK" in message for message in case.messages) - assert runs == [(False, ""), (False, B), (True, ""), (True, B), (True, B), (True, B)] + assert runs == [(False, ""), (False, B), (True, ""), (True, ""), (True, B), (True, B), (True, B)] assert (case.root / TEST).read_text() == candidate @@ -106,7 +106,7 @@ def edit(root, owner, scope): assert runs[:2] == [(False, ""), (False, case_id)] if accepted: assert attempts(state) == [("author", "accepted", "failures decreased")] - assert runs[2:] == [(True, ""), (True, case_id)] + assert runs[2:] == [(True, ""), (True, ""), (True, case_id)] assert (case.root / TEST).read_text() == candidate else: assert attempts(state) == [ diff --git a/tests/greenfield/test_implement_test_feedback_assertion_forms_round2.py b/tests/greenfield/test_implement_test_feedback_assertion_forms_round2.py index 6dac71df..6ada23b7 100644 --- a/tests/greenfield/test_implement_test_feedback_assertion_forms_round2.py +++ b/tests/greenfield/test_implement_test_feedback_assertion_forms_round2.py @@ -30,7 +30,7 @@ def edit(root, owner, scope): assert attempts(case.drive(1)) == [("author", decision, reason)] expected = [(False, ""), (False, B)] if decision == "accepted": - expected.extend([(True, ""), (True, B)]) + expected.extend([(True, ""), (True, ""), (True, B)]) if unstable: expected.extend([(True, B), (True, B)]) assert runs == expected diff --git a/tests/greenfield/test_implement_test_feedback_batch.py b/tests/greenfield/test_implement_test_feedback_batch.py index ee681ade..1b66cc36 100644 --- a/tests/greenfield/test_implement_test_feedback_batch.py +++ b/tests/greenfield/test_implement_test_feedback_batch.py @@ -1,4 +1,4 @@ -"""Batch feedback acceptance, attribution, and handoff to source owners.""" +"""Screening, individual acceptance, and handoff to source owners.""" import json import os @@ -13,21 +13,25 @@ from .test_implement_test_feedback import APP, TEST_FILE, feedback, project_factory from .test_implement_test_feedback_w21b_review import ( - A, B, C, REPAIR, RUNTIME, SOURCE, TEST, THIRD, attempts, fake, ref, revised, write, + A, B, C, HELPER, REPAIR, RUNTIME, SOURCE, TEST, THIRD, attempts, fake, ref, revised, write, ) REGRESSION = TEST + "::test_passing" -def three_owners(tmp_path, monkeypatch, *, regression=None, skip_after_removal=False): +def three_owners(tmp_path, monkeypatch, *, fixed=None, regression=None, regression_case=REGRESSION, + skip_after_removal=False): + fixed = fixed or (lambda a, b, c: (a, b, c)) + def outcomes(root, selected): a, b, c = (revised(root, name) for name in (REPAIR, TEST, THIRD)) + fixed_a, fixed_b, fixed_c = fixed(a, b, c) cases = { - A: "passed" if a else "failed", - B: "passed" if b else "failed", - C: "passed" if c else "failed", - REGRESSION: "failed" if regression and regression(a, b) else "passed", + A: "passed" if fixed_a else "failed", + B: "passed" if fixed_b else "failed", + C: "passed" if fixed_c else "failed", + regression_case: "failed" if regression and regression(a, b) else "passed", } if skip_after_removal: cases[B + "_runtime"] = "skipped" if b and not a and not selected else "passed" @@ -38,31 +42,50 @@ def outcomes(root, selected): ], outcomes) -def test_y1_three_owners_share_one_candidate_suite(tmp_path, monkeypatch): - fixture = three_owners(tmp_path, monkeypatch) +def test_y1_screening_skips_individual_suites_for_owners_without_progress(tmp_path, monkeypatch): + fixture = three_owners(tmp_path, monkeypatch, fixed=lambda a, b, c: (False, b, False)) [record] = fixture.drive(1)["rounds"] assert [owner for owner, _ in fixture.prompts] == ["a", "b", "c"] assert [(run["purpose"], run["failures_and_errors"]) for run in record["runs"] if "case" not in run] == [ - ("round 1 suite", 3), ("candidate suite", 0), + ("round 1 suite", 3), ("screening suite", 2), ("candidate suite", 2), ] - assert [attempt["decision"] for attempt in record["attempts"]] == ["accepted"] * 3 + assert [attempt["decision"] for attempt in record["attempts"]] == ["rejected", "accepted", "rejected"] + assert [revised(fixture.root, name) for name in (REPAIR, TEST, THIRD)] == [False, True, False] -def test_y2_attributes_cross_owner_regression_from_combined_tree(tmp_path, monkeypatch): - fixture = three_owners(tmp_path, monkeypatch, regression=lambda a, b: a) +def test_screening_does_not_count_a_new_failure_phase_as_a_fix(tmp_path, monkeypatch): + def outcomes(root, selected): + return {B: "failed"}, {B: {"phase": "teardown" if revised(root, TEST) else "call"}} + + fixture = fake(tmp_path, monkeypatch, [ref("test", TEST)], outcomes) [record] = fixture.drive(1)["rounds"] + assert record["attempts"][0]["decision"] == "rejected" + assert [run["purpose"] for run in record["runs"] if "case" not in run] == [ + "round 1 suite", "screening suite", + ] + + +@pytest.mark.parametrize("masked", ["unchanged failure", "regression"]) +def test_y2_individual_suite_exposes_what_another_owner_masks(tmp_path, monkeypatch, masked): + if masked == "unchanged failure": + fixture = three_owners(tmp_path, monkeypatch, fixed=lambda a, b, c: (b, b, c)) + reason = "owner's failures and errors did not decrease" + else: + fixture = three_owners(tmp_path, monkeypatch, regression=lambda a, b: a and not b) + reason = f"previously passing test now fails in isolation: {REGRESSION}" + [record] = fixture.drive(1)["rounds"] + [screening] = [run for run in record["runs"] if run["purpose"] == "screening suite"] + assert set(screening["cases"].values()) == {"passed"} assert [revised(fixture.root, name) for name in (REPAIR, TEST, THIRD)] == [False, True, True] first, second, third = record["attempts"] - assert first.get("verdict") == "culprit" - assert first["reason"].endswith(REGRESSION) + assert first["decision"] == "rejected" and first["reason"] == reason + assert not first.get("candidate_failure_from_screening") assert [second["decision"], third["decision"]] == ["accepted", "accepted"] - assert first["suite_after"] == 1 - assert sum(run["purpose"] == "attribute regression" for run in record["runs"]) == 3 - assert any(run["purpose"] == "suite after removing candidates" for run in record["runs"]) + assert first["suite_after"] == 3 -def test_d6_checks_for_suite_only_skip_after_removing_culprit(tmp_path, monkeypatch): +def test_individual_suite_detects_skip_hidden_while_another_candidate_is_present(tmp_path, monkeypatch): fixture = three_owners(tmp_path, monkeypatch, regression=lambda a, b: a, skip_after_removal=True) state = fixture.drive(1) assert [revised(fixture.root, name) for name in (REPAIR, TEST, THIRD)] == [False, False, True] @@ -74,17 +97,19 @@ def test_d6_checks_for_suite_only_skip_after_removing_culprit(tmp_path, monkeypa @pytest.mark.parametrize("interaction", [False, True]) -def test_d2_replays_prefixes_when_omission_is_ambiguous(tmp_path, monkeypatch, interaction): +def test_individual_suites_compare_against_only_the_earlier_accepted_changes(tmp_path, monkeypatch, interaction): + regression_case = "checks/test_existing.py::test_passing" + def regression(a, b): return a and b if interaction else a or b - fixture = three_owners(tmp_path, monkeypatch, regression=regression) + fixture = three_owners(tmp_path, monkeypatch, regression=regression, regression_case=regression_case) [record] = fixture.drive(1)["rounds"] assert [revised(fixture.root, name) for name in (REPAIR, TEST, THIRD)] == [interaction, False, True] - assert [a["owner"] for a in record["attempts"] if a["verdict"] == "culprit"] == ( + assert [a["owner"] for a in record["attempts"] if a["reason"].endswith(regression_case)] == ( ["b"] if interaction else ["a", "b"] ) - assert sum(run["purpose"] == "attribute regression" for run in record["runs"]) >= 4 + assert sum(run["purpose"] == "candidate suite" for run in record["runs"]) == 3 def test_d1_candidate_instability_is_returned_in_the_next_round(tmp_path, monkeypatch): @@ -108,7 +133,7 @@ def test_d7_resumes_the_pending_batch_when_validation_is_interrupted(tmp_path, m run_tests = engine._Feedback.run_tests def interrupt(self, record, purpose, case=None, timeout=None, *, target=None): - if purpose == "candidate suite": + if purpose == "screening suite": self.snapshot.restore(target) raise KeyboardInterrupt return run_tests(self, record, purpose, case, timeout, target=target) @@ -124,6 +149,27 @@ def interrupt(self, record, purpose, case=None, timeout=None, *, target=None): assert [owner for owner, _ in fixture.prompts] == ["a", "b", "c"] +def test_d7_resumes_individual_validation_without_undoing_the_first_acceptance(tmp_path, monkeypatch): + fixture = three_owners(tmp_path, monkeypatch) + run_tests = engine._Feedback.run_tests + + def interrupt(self, record, purpose, case=None, timeout=None, *, target=None): + if purpose == "candidate suite" and record["attempts"][0]["decision"] == "accepted": + self.snapshot.restore(target) + raise KeyboardInterrupt + return run_tests(self, record, purpose, case, timeout, target=target) + + with monkeypatch.context() as patch: + patch.setattr(engine._Feedback, "run_tests", interrupt) + with pytest.raises(KeyboardInterrupt): + fixture.drive(1) + [record] = fixture.drive(1, resume=True)["rounds"] + assert [a["decision"] for a in record["attempts"]] == ["accepted"] * 3 + assert [revised(fixture.root, name) for name in (REPAIR, TEST, THIRD)] == [True] * 3 + assert [owner for owner, _ in fixture.prompts] == ["a", "b", "c"] + assert sum(run["purpose"] == "screening suite" for run in record["runs"]) == 1 + + def test_reprovisioning_requires_pending_failures_to_reproduce_again(tmp_path, monkeypatch): provisions = 0 @@ -178,7 +224,7 @@ def outcomes(root, selected): assert revised(fixture.root, SOURCE) and not revised(fixture.root, TEST) -def setup_claim_project(project_factory, *, write_test=False): +def setup_claim_project(project_factory, *, write_test=False, stdout=False): tests = """\ from stub_app import subject @@ -193,15 +239,22 @@ def test_subject(): if write_test: body_fix["checks/test_body_owned.py"] = "def test_body_owned():\n assert True\n" body_outputs += ("checks/test_body_owned.py",) - claim = {f"{engine.STATE_DIRECTORY}/claims/1-1.json": json.dumps({ - "path": APP, "reason": "value returns no result before the comparison", - })} + claim = json.dumps({"case": f"{TEST_FILE}::test_subject", + "path": APP, "reason": "value returns no result before the comparison"}) + direct = {} if stdout else {f"{engine.STATE_DIRECTORY}/claims/1-1.json": claim} pipeline, root, trace, _ = project_factory( rounds=1 if write_test else 2, initial={"case": {TEST_FILE: tests}, "application": {APP: source}}, owned={"case": (TEST_FILE,), "application": body_outputs}, - fixes={"case": {"direct": claim}, "application": {"files": body_fix}}, + fixes={"case": {"direct": direct}, "application": {"files": body_fix}}, ) + if stdout: + script = trace.with_name("ai.py") + script.write_text(script.read_text() + ( + '\nif part == "feedback" and owner == "case" and "AssertionError: blocked before the comparison" in prompt:\n' + ' print("paths: []")\n' + f' print({("CODD_TEST_FEEDBACK_CLAIM " + claim)!r})\n' + )) lister = pipeline.task_lister pipeline.task_lister = lambda project: [ replace(task, dependencies=("application",)) if task.task_id == "case" else task @@ -211,7 +264,7 @@ def test_subject(): def test_y3_claim_returns_to_dependency_and_retains_progress(project_factory, monkeypatch): - pipeline, root, _ = setup_claim_project(project_factory) + pipeline, root, _ = setup_claim_project(project_factory, stdout=True) rerun = pipeline._reimplement_tasks observed = [] @@ -230,7 +283,7 @@ def remember(project, tasks, prompt, config, **kwargs): assert "return 8" in (root / APP).read_text() assert all(content == (root / TEST_FILE).read_bytes() for _, _, content in observed) assert [owner for owner, _, _ in observed] == ["case", "application", "case"] - assert f"{engine.STATE_DIRECTORY}/claims/1-1.json" in observed[0][1] + assert 'CODD_TEST_FEEDBACK_CLAIM {"case":' in observed[0][1] assert "AssertionError: reached the comparison" in observed[-1][1] assert second["reused_suites"][0]["purpose"] == "round 2 suite" @@ -246,13 +299,12 @@ def test_y4_body_turn_rejects_writes_even_to_its_own_test(project_factory): assert not (root / "checks/test_body_owned.py").exists() -def test_d3_file_writer_can_leave_a_claim_without_captured_changes(project_factory, monkeypatch): - pipeline, root, trace = setup_claim_project(project_factory) +def test_d3_file_writer_can_mix_claim_and_path_list_with_usage_logging(project_factory, monkeypatch): + pipeline, root, _ = setup_claim_project(project_factory, stdout=True) + monkeypatch.setenv("CODD_AI_USAGE_LOG", "usage/ai.jsonl") monkeypatch.setenv("GIT_CONFIG_GLOBAL", os.devnull) monkeypatch.setenv("GIT_CONFIG_NOSYSTEM", "1") subprocess.run(["git", "init", "-q", "--template="], cwd=root, check=True) - script = trace.with_name("ai.py") - script.write_text(script.read_text() + '\nif part == "feedback" and owner == "case": print("paths: []")\n') rerun = pipeline._reimplement_tasks def with_capture(*args, **kwargs): @@ -264,6 +316,105 @@ def with_capture(*args, **kwargs): pipeline.run(root) first, _ = feedback(root)["rounds"] assert [a["decision"] for a in first["attempts"]] == ["declined", "accepted"] + assert (root / "usage/ai.jsonl").is_file() + + +@pytest.mark.parametrize("depends_on_body", [False, True]) +def test_h2_claim_is_scoped_to_one_case_and_uses_the_test_files_dependencies( + tmp_path, monkeypatch, depends_on_body, +): + other = f"{TEST}::test_other" + + def outcomes(root, selected): + cases = {B: "passed" if revised(root, SOURCE) else "failed", other: "failed"} + return ({selected: cases[selected]} if selected else cases), { + B: {"origin": HELPER, "paths": [TEST, HELPER]}, + other: {"origin": HELPER, "paths": [TEST, HELPER]}, + } + + def edit(root, owner, scope): + if owner == "helper": + write(root, f"{engine.STATE_DIRECTORY}/claims/1-1.json", json.dumps({ + "case": B, "path": SOURCE, "reason": "source implementation causes the helper error", + })) + else: + write(root, SOURCE, "# revised\n") + + # An opposite dependency on the helper exposes both mistaken directions. + test = replace(ref("test", TEST), dependencies=("body",) if depends_on_body else ()) + helper = replace(ref("helper", HELPER), dependencies=() if depends_on_body else ("body",)) + fixture = fake(tmp_path, monkeypatch, [test, helper, ref("body", SOURCE)], outcomes, edit=edit) + [record] = fixture.drive(1)["rounds"] + assert record["attempts"][0]["decision"] == "declined" + if depends_on_body: + _, body = record["attempts"] + assert body["decision"] == "accepted" + assert [failure["case"] for failure in body["returned_failures"]] == [B] + else: + assert [owner for owner, _ in fixture.prompts] == ["helper"] + + +def test_h3_claim_can_follow_codd_usage_appends_to_a_new_directory(tmp_path, monkeypatch): + from codd.ai_usage import usage_session, usage_trial + + monkeypatch.setenv("CODD_AI_USAGE_LOG", "usage/log.jsonl") + + def outcomes(root, selected): + return {B: "passed" if revised(root, SOURCE) else "failed"}, {} + + def edit(root, owner, scope): + if owner == "body": + write(root, SOURCE, "# revised\n") + return + with usage_session(project_root=root), usage_trial("prompt", "stub", ["stub"]): + write(root, f"{engine.STATE_DIRECTORY}/claims/1-1.json", json.dumps({ + "case": B, "path": SOURCE, "reason": "source defect", + })) + assert (root / "usage/log.jsonl").is_file() + raise RuntimeError("AI command did not produce any file changes") + + test = replace(ref("test", TEST), dependencies=("body",)) + fixture = fake(tmp_path, monkeypatch, [test, ref("body", SOURCE)], outcomes, edit=edit) + [record] = fixture.drive(1)["rounds"] + assert [attempt["decision"] for attempt in record["attempts"]] == ["declined", "accepted"] + + +def test_h4_fingerprint_matches_full_evidence_masking(): + def signature(first, function="parse", code=401): + return engine._failure_fingerprint({ + "detail": f"{first}\n in {function}\nFinal exception: status {code}", + }) + + first = "Invalid key 123456 0xeeeeaaaa address at 0xf0" + assert signature(first) == signature("Invalid key 999999 0xffffaaaa address at 0x12") + assert signature(first) != signature("Missing key 123456 0xeeeeaaaa address at 0xf0") + assert signature(first) != signature(first, function="validate") + assert signature(first) != signature(first, code=403) + + +def test_h5_body_turn_does_not_overwrite_rejected_test_diagnostics(tmp_path, monkeypatch): + def outcomes(root, selected): + cases = {A: "failed", B: "passed" if revised(root, SOURCE) else "failed"} + details = { + A: {"detail": "rejected candidate evidence" if revised(root, REPAIR) else "initial failure"}, + B: {"origin": SOURCE, "paths": [TEST, SOURCE]}, + } + return ({selected: cases[selected]} if selected else cases), details + + def edit(root, owner, scope): + assert owner == "mixed" + path = REPAIR if scope.allows(root / REPAIR) else SOURCE + write(root, path, (root / path).read_text() + "\n# revised\n") + + foreign = replace(ref("foreign", TEST), dependencies=("mixed",)) + fixture = fake(tmp_path, monkeypatch, [foreign, ref("mixed", REPAIR, SOURCE)], outcomes, edit=edit) + first, second = fixture.drive(2)["rounds"] + assert [(a["recipient"], a["decision"]) for a in first["attempts"]] == [ + ("test", "rejected"), ("body", "accepted"), + ] + assert second["attempts"][0]["recipient"] == "test" + assert "After your previous change" in fixture.prompts[-1][1] + assert "rejected candidate evidence" in fixture.prompts[-1][1] @pytest.mark.parametrize("same_failure", [False, True]) diff --git a/tests/greenfield/test_implement_test_feedback_round2.py b/tests/greenfield/test_implement_test_feedback_round2.py index f1642829..fb2e56f7 100644 --- a/tests/greenfield/test_implement_test_feedback_round2.py +++ b/tests/greenfield/test_implement_test_feedback_round2.py @@ -124,7 +124,7 @@ def prepare(project_root): case = f"isolate {second}::test_second" assert lines.count(case) == 1 assert lines.index("feedback case") < lines.index(case) < lines.index("feedback second") - assert [run["purpose"] for run in record["runs"][-3:]] == ["suite after reprovisioning", "isolate", "candidate suite"] + assert [run["purpose"] for run in record["runs"][-3:]] == ["suite after reprovisioning", "isolate", "screening suite"] assert (unstable["owner"], unstable["decision"]) == ("second", "rejected") assert unstable["reason"] == f"unstable test still fails: {second}::test_second" assert record["passed_in_isolation"] == 1 diff --git a/tests/greenfield/test_implement_test_feedback_unstable.py b/tests/greenfield/test_implement_test_feedback_unstable.py index ed4113ac..a1eacf18 100644 --- a/tests/greenfield/test_implement_test_feedback_unstable.py +++ b/tests/greenfield/test_implement_test_feedback_unstable.py @@ -141,7 +141,8 @@ def outcomes(version, selected, count): statuses = { SUBJECT: "passed" if repaired else "failed", OTHER: other, - OBSERVER: "failed" if repaired and not observer_fixed and count == 0 else "passed", + # Both the screening suite and the individual suite see this failure. + OBSERVER: "failed" if repaired and not observer_fixed and count < 2 else "passed", } return ({selected: statuses[selected]} if selected else statuses), "suite output" @@ -160,6 +161,8 @@ def outcomes(version, selected, count): observer = rounds[-1]["attempts"][-1] assert (observer["owner"], observer["decision"], observer["isolated_before"]) == ("observer", "accepted", 0) if already_handled: + assert rounds[1]["reused_suites"][0]["purpose"] == "round 2 suite" + assert rounds[1]["runs"][0]["purpose"] == "isolate" assert rounds[1]["runs"][0]["failures_and_errors"] == 0 diff --git a/tests/greenfield/test_implement_test_feedback_w18_r2.py b/tests/greenfield/test_implement_test_feedback_w18_r2.py index e8d949ca..e5f72657 100644 --- a/tests/greenfield/test_implement_test_feedback_w18_r2.py +++ b/tests/greenfield/test_implement_test_feedback_w18_r2.py @@ -66,8 +66,8 @@ def rotate_helper(request): helper.unlink() helper.symlink_to(replacement.name) - def test_a(rotate_helper): - assert helpers.value() == 7 + def test_a(request, rotate_helper): + assert helpers.value(isolated=len(request.session.items) == 1) == 7 def test_b(request): if len(request.session.items) > 1: @@ -78,8 +78,8 @@ def test_b(request): helper = textwrap.dedent("""\ EXTRA_FIXED = False - def value(): - return [7][1] + def value(isolated): + return 7 if EXTRA_FIXED and not isolated else [7][1] def extra(): return 8 if EXTRA_FIXED else [8][1] @@ -104,7 +104,7 @@ def record_original(project_root, *args, **kwargs): [record] = feedback(root)["rounds"] [attempt] = record["attempts"] [isolation] = [run for run in record["runs"] if run["purpose"] == "candidate isolate"] - assert (attempt["suite_before"], attempt["suite_after"], attempt["isolated_before"]) == (2, 1, 1) + assert (attempt["suite_before"], attempt["suite_after"], attempt["isolated_before"]) == (2, 0, 1) assert isolation["case"] == f"{TEST_FILE}::test_a" assert isolation["failures_and_errors"] == 1 assert attempt["isolated_after"] == 1 diff --git a/tests/greenfield/test_implement_test_feedback_w18_review.py b/tests/greenfield/test_implement_test_feedback_w18_review.py index ffe8be90..b6858f1a 100644 --- a/tests/greenfield/test_implement_test_feedback_w18_review.py +++ b/tests/greenfield/test_implement_test_feedback_w18_review.py @@ -178,8 +178,8 @@ def cleanup(): ("case", "accepted", 1, 0), ] helper_attempt, case_attempt = record["attempts"] - assert (helper_attempt["suite_before"], helper_attempt["suite_after"]) == (2, 0) - assert (case_attempt["suite_before"], case_attempt["suite_after"]) == (2, 0) + assert (helper_attempt["suite_before"], helper_attempt["suite_after"]) == (2, 1) + assert (case_attempt["suite_before"], case_attempt["suite_after"]) == (1, 0) helper_prompt = trace.with_name("prompt-helper").read_text() case_prompt = trace.with_name("prompt-case").read_text() assert "test_shared (teardown" in helper_prompt and "test_shared (call" not in helper_prompt diff --git a/tests/greenfield/test_implement_test_feedback_w21b_review.py b/tests/greenfield/test_implement_test_feedback_w21b_review.py index f8d8643b..f592b737 100644 --- a/tests/greenfield/test_implement_test_feedback_w21b_review.py +++ b/tests/greenfield/test_implement_test_feedback_w21b_review.py @@ -175,27 +175,21 @@ def edit(root, owner, scope): assert "without broadening the values they accept" in case.prompts[0][1] -def baseline_script(*, origin=None, reprovision=False): +def baseline_script(*, origin=None): full_after_repair = 0 def outcomes(root, selected): nonlocal full_after_repair fixed = revised(root, HELPER) - already_reprovisioned = reprovision and (root / RUNTIME).read_text() == "new" if selected == B: - failed = not (already_reprovisioned or revised(root, TEST)) + failed = not revised(root, TEST) elif not selected and fixed: full_after_repair += 1 - failed = full_after_repair == 1 + failed = full_after_repair <= 2 # Screening and the first individual review. else: failed = False cases = {A: "passed" if fixed else "failed", B: "failed" if failed else "passed"} - if reprovision: - cases[B] = "failed" if not selected and not already_reprovisioned else "passed" - cases[C] = "passed" if already_reprovisioned else "failed" details = {A: {"origin": HELPER}, B: {"detail": "baseline evidence", **(origin or {})}} - if reprovision: - details[B]["origin"] = HELPER return ({selected: cases[selected]} if selected else cases), details return outcomes @@ -224,25 +218,39 @@ def provision(root): n_provisions += 1 write(root, RUNTIME, "new" if n_provisions > 1 else "old") - def edit(root, owner, scope): - if owner == "third": - write(root, RUNTIME, "changed by candidate") - else: - [name] = scope.names - write(root, name, (root / name).read_text() + "\n# revised\n") - - case = fake(tmp_path, monkeypatch, [ref("repair", HELPER), ref("observer", TEST), ref("third", THIRD)], - baseline_script(reprovision=True), edit=edit, provision=provision) + def outcomes(root, selected): + new_environment = (root / RUNTIME).read_text() == "new" + repaired = revised(root, REPAIR) + cases = { + A: "passed" if repaired else "failed", + B: "failed" if repaired and not selected and not new_environment else "passed", + C: "passed" if revised(root, THIRD) or new_environment else "failed", + } + return ({selected: cases[selected]} if selected else cases), {} + + case = fake(tmp_path, monkeypatch, [ref("repair", REPAIR), ref("observer", TEST), ref("third", THIRD)], + outcomes, provision=provision) + verdict = engine._Feedback.gate_problem + + def change_environment(self, record, target): + self.snapshot.restore(target) + if revised(case.root, THIRD): + write(case.root, RUNTIME, "changed during candidate checks") + return verdict(self, record, target) + + monkeypatch.setattr(engine._Feedback, "gate_problem", change_environment) state = case.drive(4) assert [(a, b) for a, b, _ in attempts(state)] == [("repair", "accepted"), ("third", "rejected")] - assert "discarding and reprovisioning" in attempts(state)[1][2] + assert "test environment changed during candidate checks" in attempts(state)[1][2] assert [owner for owner, _ in case.prompts] == ["repair", "third"] and n_provisions == 2 [record] = state["rounds"] assert record["unstable_observations"][0]["case"] == B + assert record["unstable_observations"][0]["failed_in"].endswith("(candidate suite)") + [initial] = [run for run in record["runs"] if run["purpose"] == "round 1 suite"] + assert initial["cases"][B] == "passed" [reprovisioned] = [run for run in record["runs"] if run["purpose"] == "suite after reprovisioning"] - assert reprovisioned["failures_and_errors"] == 1 - assert record["runs"][-1]["purpose"] == "candidate isolate" - assert record["attempts"][0]["suite_after"] == 0 + assert reprovisioned["failures_and_errors"] == 0 + assert record["attempts"][0]["suite_after"] == 2 assert state["pending_unstable"] == {} and record["stop"] From 785da5f21880c478246750c8202858950e794d7d Mon Sep 17 00:00:00 2001 From: yohey-w Date: Tue, 1 Dec 2026 18:56:41 +0900 Subject: [PATCH 7/8] fix(greenfield): keep main's one-by-one acceptance; drop the screening suite Second review follow-up. Running a combined screening suite changed shared state outside the tree (fixtures), the test environment and unstable-test observations before the individual verdicts, so later verdicts could differ from main's. The loop's acceptance flow is back to main's: each owner fixes, its own candidate suite runs, gates 1-9 decide. Kept: routing a failure to the implementation owner (innermost frame in an implementation file, a case-id claim file, or a fingerprint that did not move; only when exactly one target exists), that owner's test-tree fence and its fixed-or-moved acceptance, the failure after a rejected change per owner and case, and reuse of the round-start suite on the same tree and environment. Claims are read only from the state-directory JSON; the stdout observer is removed. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_014yyaLv8ZQ3GiQnmizx4cqb --- codd/ai_invoke.py | 23 - codd/greenfield/implement_test_feedback.py | 614 +++++++----------- .../test_implement_test_feedback.py | 6 +- ...implement_test_feedback_assertion_forms.py | 4 +- ...nt_test_feedback_assertion_forms_round2.py | 2 +- .../test_implement_test_feedback_batch.py | 135 ++-- .../test_implement_test_feedback_findings.py | 13 +- ...mplement_test_feedback_owner_scheduling.py | 2 +- .../test_implement_test_feedback_round2.py | 2 +- .../test_implement_test_feedback_round3.py | 14 +- .../test_implement_test_feedback_unstable.py | 3 +- .../test_implement_test_feedback_w18_r2.py | 10 +- ...est_implement_test_feedback_w21b_review.py | 13 +- 13 files changed, 337 insertions(+), 504 deletions(-) diff --git a/codd/ai_invoke.py b/codd/ai_invoke.py index c69b4d27..50f7532a 100644 --- a/codd/ai_invoke.py +++ b/codd/ai_invoke.py @@ -51,7 +51,6 @@ import sys import tempfile import time -from contextlib import contextmanager from contextvars import ContextVar from pathlib import Path from typing import Any, Callable, Mapping @@ -112,26 +111,6 @@ FileCaptureFallback = Callable[[str], str | None] - -_stdout_observer: ContextVar[Callable[[str], None] | None] = ContextVar( - "ai_stdout_observer", default=None, -) - - -@contextmanager -def observe_ai_stdout(observer: Callable[[str], None]): - """Observe a successful subprocess response before file capture replaces it.""" - token = _stdout_observer.set(observer) - try: - yield - finally: - _stdout_observer.reset(token) - - -def _observe_stdout(output: str) -> None: - if observer := _stdout_observer.get(): - observer(output) - # The implement/generate file-output contract a text-in/text-out CLI emits on # stdout: one ``=== FILE: ===`` header per generated file. Kept local # (not imported from ``codd.implementer``) to avoid a circular import — the @@ -443,7 +422,6 @@ def invoke_file_writing_agent( detail = (result.stderr.strip() or result.stdout.strip() or f"exit code {result.returncode}") raise ValueError(f"AI command failed: {detail}") - _observe_stdout(result.stdout) # Keep UTF-8 names literal in both listings and make diff paths relative to cwd. # Set the options in the subprocess environments to preserve the Git argv. @@ -630,7 +608,6 @@ def _invoke_subprocess( note_failure("empty_output") raise ValueError("AI command returned empty output") - _observe_stdout(result.stdout) return result.stdout diff --git a/codd/greenfield/implement_test_feedback.py b/codd/greenfield/implement_test_feedback.py index 3b0b857e..2a43d235 100644 --- a/codd/greenfield/implement_test_feedback.py +++ b/codd/greenfield/implement_test_feedback.py @@ -21,7 +21,6 @@ from pathlib import Path from zipfile import ZIP_DEFLATED, BadZipFile, ZipFile, ZipInfo -from codd.ai_invoke import observe_ai_stdout from codd.ai_usage import resolve_usage_log from codd.ansi import strip_ansi from codd.greenfield.pipeline import ( @@ -56,7 +55,6 @@ _STATE_ROOT = Path(".codd") STATE_DIRECTORY = f"{_STATE_ROOT}/implement-test-feedback" _ARCHIVE = f"{STATE_DIRECTORY}/rollback.zip" -_CLAIM_PREFIX = "CODD_TEST_FEEDBACK_CLAIM " _ADVICE = ( "The design documents and their verifiable behaviors are the acceptance criteria. " "Do not rewrite expectations to match observed behavior. If the cause is outside your " @@ -335,10 +333,6 @@ def _round_target(snapshot, round_record) -> dict[str, _Entry]: return snapshot.read(_round_archive(snapshot, round_record, round_record.get("kept_attempt", 0))) -def _pending_archive(snapshot, round_record, index) -> Path: - return snapshot.archive.with_name(f"pending-{round_record['number']}-{index}.zip") - - def _restore_round_for_provisioning(snapshot, round_record) -> bool: if not round_record.get("baseline_saved"): return False @@ -366,10 +360,14 @@ def recover_interrupted_feedback(root, record, echo, checkpoint) -> None: _discard_feedback_environment(snapshot, state) round_record["screened"].clear() for index, attempt in enumerate(round_record["attempts"], 1): - if attempt["decision"] != "started": + if attempt["decision"] not in ("started", "pending"): continue - if had_baseline and _pending_archive(snapshot, round_record, index).is_file(): - attempt.update(decision="pending", reason="awaiting the candidate suite") + if attempt["decision"] == "pending": + # An older checkpoint can contain unreviewed candidates. + attempt.update(decision="rejected", verdict="gate rejected", + reason="unreviewed candidate discarded on resume") + (snapshot.archive.parent / f"pending-{round_record['number']}-{index}.zip").unlink(missing_ok=True) + checkpoint(root) continue if not had_baseline: snapshot.restore(snapshot.read(snapshot.archive)) @@ -484,16 +482,12 @@ def __init__(self, pipeline, root, tasks, state, options, config, adapter, test_ self.test_roots = test_roots self.sources = sources self.callable_assertions = callable_assertions - self.tasks_by_id = {task.task_id: task for task in tasks} self.snapshot = _Snapshot(root, tuple(state["ignored"]), state["environment_paths"]) self.target: dict[str, _Entry] = {} self.environment_dirty = False self.outputs: dict[str, DeclaredOutputs] = {} - self.declared = {task.task_id: DeclaredOutputs(root, task.expected_outputs) for task in tasks} self.suite_cache = self.snapshot.archive.with_name("last-suite.zip") - self.suites = self.load_last_suite() - self.candidate_unstable = [] - self.isolated_failures = [] + self.last_suite = self.load_last_suite() self.logs = {AUDIT_RELATIVE_PATH} try: usage_log = resolve_usage_log(config, root) @@ -508,16 +502,15 @@ def load_last_suite(self): try: saved = json.loads(self.snapshot.read(self.suite_cache)["suite.json"].data) if saved["round"] == last_round: - return {bytes.fromhex(saved["tree"]): _Suite(**saved["suite"])} + return bytes.fromhex(saved["tree"]), _Suite(**saved["suite"]) except (OSError, ValueError, KeyError, TypeError, BadZipFile): pass - return {} + return None - def remember_last_suite(self, record, suite): - self.suites = {key: result for key, result in self.suites.items() if result is suite} - if not self.suites: + def remember_last_suite(self, record): + if self.last_suite is None: return - key = next(iter(self.suites)) + key, suite = self.last_suite payload = {"round": record["number"], "tree": key.hex(), "suite": vars(suite)} try: self.snapshot.persist({"suite.json": _Entry(stat.S_IFREG | 0o600, json.dumps(payload).encode())}, @@ -589,6 +582,8 @@ def prepare(self, round_record) -> str | None: self.display = self.command if isinstance(self.command, str) else shlex.join(self.command) try: self.target = self.snapshot.capture() + self.tasks_by_id = {task.task_id: task for task in self.tasks} + self.declared = {task.task_id: DeclaredOutputs(self.root, task.expected_outputs) for task in self.tasks} self.outputs = self.round_outputs() environment = self.snapshot.environment_fingerprint() if self.pending_unstable: @@ -718,14 +713,14 @@ def full_suite(self, round_record, purpose, target, *, reuse=False): environment = round_record["environment_before"] digest.update(json.dumps((self.command, str(self.cwd), self.env, environment), sort_keys=True).encode()) key = digest.digest() - if reuse and key in self.suites and not self.snapshot.environment_changed(environment): - result = self.suites[key] + if (reuse and self.last_suite is not None and key == self.last_suite[0] + and not self.snapshot.environment_changed(environment)): + result = self.last_suite[1] round_record.setdefault("reused_suites", []).append({"purpose": purpose, "from": result.run_label}) self.snapshot.restore(target) return result result = self.run_tests(round_record, purpose, target=target) - if not result.unavailable: - self.suites[key] = result + self.last_suite = None if result.unavailable or result.unreported_launch else (key, result) return result def replay_failure_details(self, round_record, failures) -> list[dict]: @@ -785,19 +780,14 @@ def owner(self, failure) -> str | None: owners.add(matches[0]) return next(iter(owners)) if len(owners) == 1 else None - def body_owner(self, failure, claim=None): + def body_owners(self, failure, paths): file = failure["file"] if not self.in_test_tree(file): - return None + return set() test_owners = [owner for owner, scope in self.declared.items() if scope.allows(Path(file))] - test_owner = test_owners[0] if len(test_owners) == 1 else None - if test_owner is None or not self.tasks_by_id[test_owner].dependencies: - return None - dependencies = self.tasks_by_id[test_owner].dependencies - paths = [claim] if claim is not None else list(dict.fromkeys( - path for path in (*_failure_origins(failure), *failure.get("paths", ())) - if path and not self.in_test_tree(path) - )) + if len(test_owners) != 1: + return set() + dependencies = getattr(self.tasks_by_id[test_owners[0]], "dependencies", ()) owners = set() for path in paths: absolute = Path(path) @@ -810,22 +800,27 @@ def body_owner(self, failure, claim=None): matches = [task_id for task_id, outputs in self.declared.items() if outputs.allows(absolute)] if len(matches) == 1 and matches[0] in dependencies: owners.add(matches[0]) - return next(iter(owners)) if len(owners) == 1 else None + return owners def body_groups(self, suite, routes): - grouped = defaultdict(list) + reported = defaultdict(set) + for route in routes: + if route["owner"] in self.tasks_by_id: + reported[route["case"], route["fingerprint"]].add(route["owner"]) + by_case = defaultdict(list) for failure in suite.failures: origins = _failure_origins(failure) - owner = None - if len(origins) == 1 and origins[0] and not self.in_test_tree(origins[0]): - owner = self.body_owner(failure, origins[0]) - for route in routes: - if (route["owner"] in self.tasks_by_id and route["case"] == failure["case"] - and route["fingerprint"] == _failure_fingerprint(failure)): - owner = route["owner"] - break - if owner is not None: - grouped[owner].append(failure) + case = failure["case"] + owners = self.body_owners(failure, origins) + if len(origins) > 1 and len(owners) == 1: + owners.clear() + owners.update(reported.get((case, _failure_fingerprint(failure)), ())) + by_case[case].append((failure, owners)) + grouped = defaultdict(list) + for reports in by_case.values(): + owners = set().union(*(owners for _, owners in reports)) + if len(owners) == 1: + grouped[next(iter(owners))].extend(failure for failure, owners in reports if owners) return grouped def owner_groups(self, suite): @@ -889,7 +884,14 @@ def screen(self, round_record, owner, suite, failures, limited, *, body=False) - [list(pair) for pair in sorted(signature)], [{**f, "detail": self.failure_excerpt(_case_failure_detail(f))} for f in reproduced], ] - reproduced_for_owner.extend(item for item in reproduced if body or self.owner(item) == owner) + if body and reproduced: + other_owners = set().union(*( + self.body_owners(failure, _failure_origins(failure)) for failure in isolated.failures + )) - {owner} + if not other_owners: + reproduced_for_owner.extend(isolated.failures) + elif not body: + reproduced_for_owner.extend(item for item in reproduced if self.owner(item) == owner) if isolated.cases.get(case) == "passed": if not isolated.unavailable: self.observe_unstable(round_record, case, isolated, suite) @@ -1005,7 +1007,7 @@ def body_progress(suite, case, before): return "progressed" return None - def assess(self, record, attempt, suite, failures, target): + def assess(self, record, attempt, suite, failures, target, isolated_failures): owner = attempt["owner"] body = attempt["recipient"] == "body" unstable = attempt.get("unstable_cases", {}) @@ -1042,26 +1044,23 @@ def assess(self, record, attempt, suite, failures, target): result, problem = self.isolate(record, case, "candidate isolate", target, deadline) if problem: return problem, candidate, None - self.isolated_failures.extend(result.failures) + isolated_failures.extend(result.failures) if body: for observed, original in ((candidate, suite.failures), (result, failures)): - fingerprints = {_failure_fingerprint(f) for f in original - if f["case"] == case and _failure_key(f) in keys} + fingerprints = {_failure_fingerprint(f) for f in original if f["case"] == case} outcome = self.body_progress(observed, case, fingerprints) if not outcome: return f"failure fingerprint did not advance: {case}", candidate, None progress.append(outcome) else: isolated_after += sum(_failure_key(f) in keys for f in result.failures) - if candidate.cases.get(case) == "failed" and result.cases[case] == "passed": - self.candidate_unstable.append((case, result, candidate)) for case in unstable: for _ in range(_UNSTABLE_VERIFICATION_RUNS): result, problem = self.isolate(record, case, "candidate unstable isolate", target, deadline) if problem: return problem, candidate, None - self.isolated_failures.extend(result.failures) + isolated_failures.extend(result.failures) if result.cases[case] != "passed": return f"{_UNSTABLE_REASON}: {case}", candidate, None @@ -1075,12 +1074,6 @@ def assess(self, record, attempt, suite, failures, target): attempt["progress"] = "progressed" if "progressed" in progress else "fixed" return None, candidate, None - def defer_unstable(self, record, case, passed, failed): - deferred = record.setdefault("deferred_unstable", []) - if case not in deferred: - deferred.append(case) - self.observe_unstable(record, case, passed, failed) - def regression(self, record, attempt, suite, candidate, before, target, deadline): for case, status in suite.cases.items(): if status != "passed" or candidate.cases.get(case) == "passed": @@ -1090,8 +1083,6 @@ def regression(self, record, attempt, suite, candidate, before, target, deadline if problem: return problem, None if result.cases[case] == "passed": - if candidate.cases.get(case) == "failed": - self.candidate_unstable.append((case, result, candidate)) break if result.cases[case] == "passed": continue @@ -1109,12 +1100,12 @@ def regression(self, record, attempt, suite, candidate, before, target, deadline return f"{_REGRESSION_REASON}: {case}", result return None, None - def reject(self, attempt, reason, candidate=None, *, suite=None, regression=None, screening=False): + def reject(self, attempt, reason, candidate, *, suite, regression, isolated_failures): attempt.update(decision="rejected", reason=reason, verdict="gate rejected") if candidate is not None: cases = {f["case"] for f in attempt["returned_failures"]} | attempt.get("unstable_cases", {}).keys() sections = defaultdict(dict) - for failure in (*candidate.failures, *self.isolated_failures): + for failure in (*candidate.failures, *isolated_failures): if failure["case"] in cases: sections[failure["case"]][_case_failure_detail(failure)] = None if sections: @@ -1127,9 +1118,7 @@ def reject(self, attempt, reason, candidate=None, *, suite=None, regression=None saved = record_full_failure(self.root, self.snapshot.archive.parent, detail) if saved: attempt["candidate_failure_path"] = saved[0].as_posix() - if screening: - attempt["candidate_failure_from_screening"] = True - if self.record_stall(attempt, suite, candidate) and reason == _COUNT_REASON: + if self.record_stall(attempt, suite, candidate, isolated_failures) and reason == _COUNT_REASON: attempt["verdict"] = "stalled" elif reason.startswith("failure fingerprint did not advance"): attempt["verdict"] = "stalled" @@ -1140,33 +1129,6 @@ def reject(self, attempt, reason, candidate=None, *, suite=None, regression=None regression.output or "\n\n".join(f["detail"] for f in regression.failures), ) - def screening_rejection(self, attempt, baseline, candidate): - if attempt["recipient"] == "body": - for case in dict.fromkeys(f["case"] for f in attempt["returned_failures"]): - original = {_failure_fingerprint(f) for f in baseline.failures if f["case"] == case} - if self.body_progress(candidate, case, original): - return None - return "failure fingerprint did not advance in screening" - unstable = attempt.get("unstable_cases", {}) - if any(candidate.cases.get(case) == "passed" for case in unstable): - return None - before = Counter(_failure_key(f) for f in attempt["returned_failures"]) - after = Counter(map(_failure_key, candidate.failures)) - cases = {case for case, _, _ in before} - if any(candidate.cases.get(case) == "passed" for case in cases): - return None - known = Counter(map(_failure_key, baseline.failures)) - for key, occurrences in before.items(): - case = key[0] - remaining = Counter({k: n for k, n in after.items() if k[0] == case}) - # A shared case may still fail in an existing phase. Replacing a - # returned failure with a new one gives no screening signal. - if remaining and after[key] < occurrences and remaining <= known: - return None - if unstable and not before: - return f"{_UNSTABLE_REASON}: {next(iter(unstable))}" - return _COUNT_REASON - def allowed_change(self, path, outputs, old, new) -> bool: if outputs.allows(path): return True @@ -1202,9 +1164,10 @@ def candidate_target(self, outputs, after): raise ValueError(f"declared output has a non-directory parent in the snapshot: {name}") return kept - def keep_outputs(self, round_record, index, kept): + def keep_outputs(self, round_record, kept): # Commit the new target and the acceptance decision in that order. # An interrupted checkpoint can still use the previous target. + index = len(round_record["attempts"]) self.snapshot.persist(kept, _round_archive(self.snapshot, round_record, index)) round_record["kept_attempt"] = index self.target = kept @@ -1234,8 +1197,7 @@ def attempt(self, round_record, task, failures, suite, unstable, *, body=False): "decision": "started", "before": self.count(suite, owner, case_ids, unstable), "after": None, "suite_before": len(suite.failures), "suite_after": None, "isolated_before": len(failures), "isolated_after": None, - "environment_before": environment_before, "baseline_run": suite.run_label, - "pending_delta": True, + "environment_before": environment_before, "returned_failures": [ {**{key: value for key, value in failure.items() if key != "detail"}, "fingerprint": _failure_fingerprint(failure)} for failure in failures @@ -1245,6 +1207,7 @@ def attempt(self, round_record, task, failures, suite, unstable, *, body=False): attempt["unstable_cases"] = unstable round_record["attempts"].append(attempt) index = len(round_record["attempts"]) + previous_target = _round_archive(self.snapshot, round_record, round_record.get("kept_attempt", 0)) claim_file = self.snapshot.archive.parent / "claims" / f"{round_record['number']}-{index}.json" if not body: claim_file.parent.mkdir(parents=True, exist_ok=True) @@ -1253,16 +1216,87 @@ def attempt(self, round_record, task, failures, suite, unstable, *, body=False): if unstable: returning += f" and {len(unstable)} unstable test(s)" self.emit(f"{returning} to {owner}") + feedback = self.attempt_feedback(round_record, attempt, failures, unstable, claim_file) + reason = None + no_output = False + claim = None + candidate = regression = None + isolated_failures = [] + try: + self.pipeline._reimplement_tasks( + self.root, [task], feedback, self.config, feedback_output_paths=scope, + ) + except Exception as exc: + reason = f"could not evaluate the candidate: {exc}" + no_output = not str(exc).startswith("AI command failed:") and any(marker in str(exc) for marker in ( + "AI command did not produce any file changes", "empty output", "no file change proposed:", + )) + self.environment_dirty = self.snapshot.environment_changed(environment_before) + if not self.environment_dirty and (reason is None or not body and no_output): + try: + proposed = self.snapshot.capture() + if not body and self.only_log_appends(before, proposed): + claim = self.read_claim(claim_file, case_ids) + if reason is None and claim is None: + reason = self.change_problem(scope, before, proposed, unstable) + if reason is None: + target = self.candidate_target(scope, proposed) + reason, candidate, regression = self.assess( + round_record, attempt, suite, failures, target, isolated_failures, + ) + except Exception as exc: + reason = f"could not evaluate the candidate: {exc}" + dirty = self.environment_dirty or self.snapshot.environment_changed(environment_before) + if dirty: + self.environment_dirty = True + reason = ( + "test environment changed during the task rerun or candidate checks; " + "discarding and reprovisioning it" + ) + if reason is None and claim is None: + try: + self.keep_outputs(round_record, target) + except (OSError, ValueError) as exc: + reason = f"could not keep the candidate: {exc}" + if claim is not None and not dirty: + self.record_claim(round_record, attempt, suite, claim) + elif reason is not None: + self.reject(attempt, reason, candidate if not dirty else None, suite=suite, + regression=regression, isolated_failures=isolated_failures) + else: + self.record_stall(attempt, suite, candidate, isolated_failures) + verdict = "fixed" + accepted = "failures decreased" if failures else "unstable tests passed the suite and isolated checks" + if body: + verdict = attempt["progress"] + accepted = "returned tests passed" if verdict == "fixed" else "failure fingerprint advanced" + attempt.update(decision="accepted", reason=accepted, verdict=verdict) + round_record["screened"].clear() + suite = candidate + self.snapshot.restore(self.target) + for case in unstable: + self.pending_unstable.pop(case, None) + self.emit( + f"{owner}: {attempt['decision']} · {attempt['reason']} · " + f"owner {attempt['before']} → {attempt['after'] if attempt['after'] is not None else '—'} · " + f"suite {attempt['suite_before']} → " + f"{attempt['suite_after'] if attempt['suite_after'] is not None else '—'}" + ) + if attempt["decision"] == "accepted": + previous_target.unlink(missing_ok=True) + return suite, dirty + + def attempt_feedback(self, round_record, attempt, failures, unstable, claim_file): feedback = _ADVICE + case_ids = {f["case"] for f in failures} + body = attempt["recipient"] == "body" if body: feedback += "\n\nRepair the application code. Leave every file in the test tree unchanged." else: feedback += ( "\n\nIf the cause cannot be fixed within your declared outputs, leave them unchanged. " - "Report the exact case id from the diagnostics, the source file path, and the reason " - f"on a single stdout line: {_CLAIM_PREFIX}" - '{"case":"","path":"","reason":""}. ' - f"You may also write the same JSON object to {claim_file.relative_to(self.root)}." + f"Write a single JSON object to {claim_file.relative_to(self.root)} using this format: " + '{"case":"","path":"","reason":""}.' ) detail = "" following = [] @@ -1294,63 +1328,17 @@ def attempt(self, round_record, task, failures, suite, unstable, *, body=False): following.extend(evidence) if detail or following: feedback += f"\n\n{self.failure_excerpt(detail, *following)}" - reason = None - no_output = False - responses = [] - try: - with observe_ai_stdout(responses.append): - self.pipeline._reimplement_tasks( - self.root, [task], feedback, self.config, feedback_output_paths=scope, - ) - except Exception as exc: - reason = f"could not evaluate the candidate: {exc}" - no_output = not str(exc).startswith("AI command failed:") and any(marker in str(exc) for marker in ( - "AI command did not produce any file changes", "empty output", "no file change proposed:", - )) - self.environment_dirty = self.snapshot.environment_changed(environment_before) - try: - if self.environment_dirty: - reason = ( - "test environment changed during the task rerun or candidate checks; " - "discarding and reprovisioning it" - ) - else: - proposed = self.snapshot.capture() - if not body and (reason is None or no_output) and self.only_log_appends(before, proposed): - claim = self.read_claim(responses, claim_file, case_ids) - if claim: - attempt.update(decision="declined", verdict="declined", claim=claim, - reason=f"outside own outputs: {claim['path']}") - routes = round_record.setdefault("claims", []) - for failure in failures: - if failure["case"] == claim["case"]: - if recipient := self.body_owner(failure, claim["path"]): - routes.append(self.route(failure, recipient)) - if not reason and attempt["decision"] == "started": - reason = self.change_problem(scope, before, proposed, unstable) - if not reason: - target = self.candidate_target(scope, proposed) - delta = {} - for path, new in _writes(before, target).items(): - if path in before: - delta[f"before/{path}"] = before[path] - if new is not None: - delta[f"after/{path}"] = new - self.snapshot.persist(delta, _pending_archive(self.snapshot, round_record, index)) - attempt.update(decision="pending", reason="awaiting the candidate suite") - except (OSError, ValueError) as exc: - reason = f"could not evaluate the candidate: {exc}" - finally: - # Leave an interrupted AI turn to recovery. A completed turn owns - # only its archived candidate until it passes the review. - if attempt["decision"] != "started" or reason is not None: - self.snapshot.restore(before) - if attempt["decision"] == "started": - self.reject(attempt, reason) - for case in unstable: - self.pending_unstable.pop(case, None) - self.emit(f"{owner}: {attempt['decision']} · {attempt['reason']}") - return self.environment_dirty + return feedback + + def record_claim(self, record, attempt, suite, claim): + attempt.update(decision="declined", verdict="declined", claim=claim, + reason=f"outside own outputs: {claim['path']}") + routes = record.setdefault("claims", []) + returned = {_failure_key(f) for f in attempt["returned_failures"] if f["case"] == claim["case"]} + for failure in suite.failures: + if _failure_key(failure) in returned: + for owner in sorted(self.body_owners(failure, (claim["path"],))): + routes.append(self.route(failure, owner)) def only_log_appends(self, before, proposed): writes = _writes(before, proposed) @@ -1367,13 +1355,9 @@ def only_log_appends(self, before, proposed): return writes.keys() <= allowed @staticmethod - def read_claim(responses, path, cases): - lines = [line.removeprefix(_CLAIM_PREFIX) for response in responses - for line in response.splitlines() if line.startswith(_CLAIM_PREFIX)] - if len(lines) > 1: - return None + def read_claim(path, cases): try: - claim = json.loads(lines[0] if lines else path.read_text()) + claim = json.loads(path.read_text(encoding="utf-8")) except (OSError, ValueError): return None fields = ("case", "path", "reason") @@ -1442,182 +1426,30 @@ def previous_rejections(self, attempt, cases): ) return feedback, evidence - def pending_changes(self, record, index, attempt): - entries = self.snapshot.read(_pending_archive(self.snapshot, record, index)) - if not attempt.get("pending_delta"): - # A pre-v4 archive contains a whole tree. Extract only this owner's - # outputs since other owners may already have been kept on resume. - if any(previous["decision"] == "accepted" and previous["owner"] == attempt["owner"] - for previous in record["attempts"][:index - 1]): - raise ValueError("cannot reapply an older candidate over this owner's accepted changes") - scope = self.scope(attempt["owner"], attempt["recipient"] == "body") - target = self.candidate_target(scope, entries) - return {path: (self.target.get(path), new) for path, new in _writes(self.target, target).items()} - before = {name.removeprefix("before/"): entry for name, entry in entries.items() - if name.startswith("before/")} - after = {name.removeprefix("after/"): entry for name, entry in entries.items() - if name.startswith("after/")} - return {path: (before.get(path), after.get(path)) for path in before.keys() | after.keys()} - - @staticmethod - def apply_changes(target, changes): - target = target.copy() - for path, (old, new) in changes.items(): - if target.get(path) not in (old, new): - raise ValueError(f"pending candidate conflicts with an earlier change: {path}") - if new is None: - target.pop(path, None) - else: - target[path] = new - for path in target: - parent, _, _ = path.rpartition("/") - if parent and (parent not in target or not stat.S_ISDIR(target[parent].mode)): - raise ValueError(f"pending candidate has a missing or non-directory parent: {path}") - return target - - def screen_candidates(self, record, suite, pending): - if record.get("screening_done"): - return - target = self.target - self.isolated_failures.clear() - try: - for _, _, changes in pending: - target = self.apply_changes(target, changes) - candidate = self.run_tests(record, "screening suite", target=target) - except (OSError, ValueError): - # Incompatible deltas cannot be screened together. Review each separately. - candidate = None - finally: - self.snapshot.restore(self.target) - rejected = [] - if self.environment_dirty and len(pending) == 1: - index, attempt, _ = pending[0] - self.reject(attempt, "test environment changed during candidate checks") - rejected.append((index, attempt)) - if (not self.environment_dirty and candidate and not candidate.unavailable - and not candidate.unreported_launch - and not candidate.collection_errors.keys() - suite.collection_errors.keys()): - for index, attempt, _ in pending: - if reason := self.screening_rejection(attempt, suite, candidate): - attempt["suite_after"] = len(candidate.failures) - attempt["after"] = self.count(candidate, attempt["owner"], self.returned_cases(attempt), - attempt.get("unstable_cases", {})) - self.reject(attempt, reason, candidate, suite=suite, screening=True) - rejected.append((index, attempt)) - record["screening_done"] = True - self.pipeline._checkpoint(self.root) - for index, attempt in rejected: - self.finish_attempt(record, index, attempt) - - def finish_attempt(self, record, index, attempt): - self.snapshot.restore(self.target) - self.emit( - f"[implement test feedback] {attempt['owner']}: {attempt['decision']} · {attempt['reason']} · " - f"owner {attempt['before']} → {attempt['after']} · " - f"suite {attempt['suite_before']} → {attempt['suite_after']}" - ) - _pending_archive(self.snapshot, record, index).unlink(missing_ok=True) - - def settle(self, record, suite): - pending = [] - for index, attempt in enumerate(record["attempts"], 1): - if attempt["decision"] != "pending": - continue - try: - changes = self.pending_changes(record, index, attempt) - except (OSError, ValueError, BadZipFile) as exc: - self.reject(attempt, f"could not read the pending candidate: {exc}") - self.finish_attempt(record, index, attempt) - else: - pending.append((index, attempt, changes)) - if pending and not suite.unavailable and not self.environment_dirty: - self.screen_candidates(record, suite, pending) - for index, attempt, changes in pending: - if self.environment_dirty: - break - if attempt["decision"] == "pending": - suite = self.review_candidate(record, index, attempt, changes, suite) - return suite - - def review_candidate(self, record, index, attempt, changes, suite): - self.candidate_unstable.clear() - self.isolated_failures.clear() - candidate = regression = None - reason = "candidate suite could not complete" if suite.unavailable else None - try: - if not reason: - failures, reason = self.current_failures(record, attempt, suite) - if not reason: - target = self.apply_changes(self.target, changes) - body = attempt["recipient"] == "body" - reason = self.change_problem(self.scope(attempt["owner"], body), self.target, target, - attempt.get("unstable_cases", {})) - if not reason: - reason, candidate, regression = self.assess(record, attempt, suite, failures, target) - if self.environment_dirty: - reason = "test environment changed during candidate checks" - if not reason: - self.keep_outputs(record, index, target) - except Exception as exc: - reason = f"could not evaluate the candidate: {exc}" - - if reason: - self.reject(attempt, reason, candidate, suite=suite, regression=regression) - else: - self.record_stall(attempt, suite, candidate) - verdict = "fixed" - reason = "failures decreased" if failures else "unstable tests passed the suite and isolated checks" - if attempt["recipient"] == "body": - verdict = attempt["progress"] - reason = "returned tests passed" if verdict == "fixed" else "failure fingerprint advanced" - attempt.update(decision="accepted", reason=reason, verdict=verdict) - record["screened"].clear() - suite = candidate - for case, passed, failed in self.candidate_unstable: - self.defer_unstable(record, case, passed, failed) - self.finish_attempt(record, index, attempt) - return suite - - def current_failures(self, record, attempt, suite): - failures = attempt["returned_failures"] - same_environment = attempt["environment_before"] == record["environment_before"] - if not same_environment and attempt.get("unstable_cases"): - return [], "unstable test observations are from a different environment" - if same_environment and attempt.get("baseline_run") == suite.run_label: - return failures, None - returned = defaultdict(set) - for failure in failures: - returned[failure["case"]].add(_failure_key(failure)) - suite_keys = {_failure_key(failure) for failure in suite.failures} - reproduced = [] - deadline = time.monotonic() + self.timeout - for case, keys in returned.items(): - expected = keys & suite_keys - if not expected: - continue - purpose = "baseline isolate" if same_environment else "reprovisioned baseline isolate" - result, problem = self.isolate(record, case, purpose, self.target, deadline) - observed = [] if problem else [f for f in result.failures if _failure_key(f) in expected] - if not observed: - if same_environment and not problem and result.cases[case] == "passed": - self.defer_unstable(record, case, result, suite) - context = "the current baseline" if same_environment else "reprovisioning" - return [], f"returned failure no longer reproduces after {context}: {case}" - reproduced.extend(observed) - if failures and not reproduced: - return [], "returned failures no longer reproduce in the baseline suite" - return reproduced, None - - def record_stall(self, attempt, suite, candidate): + def record_stall(self, attempt, suite, candidate, isolated_failures): if attempt["recipient"] != "test" or candidate.unavailable: return False - returned = {_failure_key(f) for f in attempt["returned_failures"]} - before = {(f["case"], _failure_fingerprint(f)) for f in suite.failures if _failure_key(f) in returned} - stalled = [f for f in candidate.failures if (f["case"], _failure_fingerprint(f)) in before] - if stalled: + def signature(failure): + return _failure_key(failure), _failure_fingerprint(failure) + + returned = {signature(f) for f in attempt["returned_failures"]} + keys = {key for key, _ in returned} + baseline = [f for f in suite.failures if _failure_key(f) in keys] + baseline_signatures = {signature(f) for f in baseline} + stalled = [f for f in candidate.failures if signature(f) in baseline_signatures] + stalled.extend(f for f in isolated_failures if signature(f) in returned) + owners_by_case = defaultdict(set) + for failure in stalled: + paths = (*_failure_origins(failure), *failure.get("paths", ())) + owners_by_case[failure["case"]].update(self.body_owners(failure, paths)) + stalled_keys = {_failure_key(failure) for failure in stalled} + routes = {(failure["case"], _failure_fingerprint(failure), owner) + for failure in baseline if _failure_key(failure) in stalled_keys + for owner in owners_by_case[failure["case"]]} + if routes: attempt["stalled_routes"] = [ - self.route(failure, owner) for failure in stalled - if (owner := self.body_owner(failure)) is not None + {"case": case, "fingerprint": fingerprint, "owner": owner} + for case, fingerprint, owner in sorted(routes) ] return bool(stalled) @@ -1625,7 +1457,7 @@ def reprovision(self, record): _restore_round_for_provisioning(self.snapshot, record) _discard_feedback_environment(self.snapshot, self.state) self.environment_dirty = False - self.suites.clear() + self.last_suite = None record["screened"].clear() problem = self.prepare(record) return _Suite(unavailable=problem) if problem else self.full_suite( @@ -1647,60 +1479,59 @@ def run(self, rounds: int) -> None: continue prior_routes = [ route for attempt in self.state["rounds"][index - 1]["attempts"] + if not attempt.get("candidate_failure_from_screening") for route in attempt.get("stalled_routes", ()) ] if index else [] problem = self.prepare(record) suite = _Suite(unavailable=problem) if problem else self.full_suite( - record, f"round {index + 1} suite", self.target, reuse=True, + record, f"round {index + 1} suite", self.target, + reuse=not record["runs"] and not record["attempts"], ) handled = {(a["owner"], a.get("recipient", "test")) for a in record["attempts"] if not a.get("interrupted")} interrupted = {a["owner"] for r in self.state["rounds"] for a in r["attempts"] if a.get("interrupted")} + body_attempted = defaultdict(set) + for attempt in record["attempts"]: + if attempt.get("recipient") == "body": + body_attempted[attempt["owner"]].update(self.returned_cases(attempt)) limited = set(record.get("cases_outside_isolation_budget", ())) unreproduced = set() - deferred = record.setdefault("deferred_unstable", []) isolation_problem = None while not suite.unavailable: - body_groups = self.body_groups(suite, [*prior_routes, *record.get("claims", ())]) + claims = record.get("claims", ()) + body_groups = self.body_groups(suite, [*prior_routes, *claims]) redirected = {_failure_key(f) for failures in body_groups.values() for f in failures} - pending = { + claimed_cases = {(claim["owner"], claim["case"], claim["fingerprint"]) for claim in claims} + claimed_body, other_body = {}, {} + for owner, failures in sorted(body_groups.items()): + if owner in interrupted: + continue + claimed = [f for f in failures if ( + (owner, f["case"], _failure_fingerprint(f)) in claimed_cases + and f["case"] not in body_attempted[owner] + )] + if claimed: + claimed_body[owner, "body"] = claimed + elif (owner, "body") not in handled: + other_body[owner, "body"] = failures + pending = dict(claimed_body) + pending.update({ (owner, "test"): [f for f in failures if _failure_key(f) not in redirected] for owner, failures in self.owner_groups(suite) if owner not in interrupted and any(_failure_key(f) not in redirected for f in failures) - } - observations = self.unstable_groups() - for owner, unstable in sorted(observations.items()): - if any(case not in deferred for case in unstable): + }) + for owner in sorted(self.unstable_groups()): + if (owner, "test") not in handled: pending.setdefault((owner, "test"), []) - for owner, failures in sorted(body_groups.items()): - if owner not in interrupted: - pending[owner, "body"] = failures + pending.update(other_body) pending = {key: failures for key, failures in pending.items() - if key not in handled and key not in unreproduced} - - if not pending or record.get("isolation_time_exhausted"): - before = self.target - suite = self.settle(record, suite) - if self.environment_dirty: - suite = self.reprovision(record) - unreproduced.clear() - continue - if self.target == before or record.get("isolation_time_exhausted"): - break - # An isolated failure may become reproducible only after - # another owner has passed review. Preserve that opportunity. - eligible = unreproduced | {(owner, "test") for owner in self.unstable_groups()} - new_test_owners = {(owner, "test") for owner, _ in self.owner_groups(suite)} - new_body_owners = {(owner, "body") for owner in self.body_groups(suite, prior_routes)} - handled.update((new_test_owners | new_body_owners) - eligible) - unreproduced.clear() - continue + if (key not in handled or key in claimed_body) and key not in unreproduced} + if not pending: + break (owner, recipient), owned = next(iter(pending.items())) - if recipient == "body": - failures, isolation_problem = self.screen(record, owner, suite, owned, limited, body=True) - else: - failures, isolation_problem = self.screen(record, owner, suite, owned, limited) + body = recipient == "body" + failures, isolation_problem = self.screen(record, owner, suite, owned, limited, body=body) time_exhausted = record["isolated_seconds"] >= self.timeout if time_exhausted: limited.update(f["case"] for key, group in pending.items() if key != (owner, recipient) for f in group) @@ -1708,24 +1539,26 @@ def run(self, rounds: int) -> None: self.emit("isolation time budget exhausted") if isolation_problem: break - own_observations = self.unstable_groups().get(owner, {}) if recipient == "test" else {} - unstable = dict((case, obs) for case, obs in own_observations.items() if case not in deferred) - unstable = dict(list(unstable.items())[:_MAX_ISOLATED_CASES]) + own_observations = {} if body else self.unstable_groups().get(owner, {}) + unstable = dict(list(own_observations.items())[:_MAX_ISOLATED_CASES]) failures = [failure for failure in failures if failure["case"] not in own_observations] - if not (failures or unstable): + if failures or unstable: + handled.add((owner, recipient)) + if body: + body_attempted[owner].update(failure["case"] for failure in failures) + args = (record, self.tasks_by_id[owner], failures, suite, unstable) + suite, dirty = self.attempt(*args, body=True) if body else self.attempt(*args) + if dirty or record["attempts"][-1]["decision"] == "accepted": + unreproduced.clear() + if dirty: + suite = self.reprovision(record) + elif not body and self.has_helper(failures): + record["screened"].clear() + suite = self.full_suite(record, "suite after helper decision", self.target) + else: unreproduced.add((owner, recipient)) - continue - handled.add((owner, recipient)) - args = (record, self.tasks_by_id[owner], failures, suite, unstable) - dirty = self.attempt(*args, body=True) if recipient == "body" else self.attempt(*args) - if dirty: - unreproduced.clear() - suite = self.reprovision(record) - - while any(attempt["decision"] == "pending" for attempt in record["attempts"]): - if self.environment_dirty: - suite = self.reprovision(record) - suite = self.settle(record, suite) + if time_exhausted: + break routes = [route for attempt in record["attempts"] for route in attempt.get("stalled_routes", ())] stop = bool(suite.unavailable) or not ( self.unstable_groups() or any(owner not in interrupted for owner, _ in self.owner_groups(suite)) @@ -1739,10 +1572,10 @@ def run(self, rounds: int) -> None: self.snapshot.restore(self.target) if self.environment_dirty: _discard_feedback_environment(self.snapshot, self.state) - self.suites.clear() + self.last_suite = None self.emit("test environment changed; discarded before the next run") record.update(done=True, stop=stop) - self.remember_last_suite(record, suite) + self.remember_last_suite(record) problem = suite.unavailable or isolation_problem if problem: record["skipped"] = _command_output_tail(problem, None) @@ -1753,7 +1586,6 @@ def run(self, rounds: int) -> None: ) for attempt_index in range(len(record["attempts"]) + 1): _round_archive(self.snapshot, record, attempt_index).unlink(missing_ok=True) - _pending_archive(self.snapshot, record, attempt_index).unlink(missing_ok=True) if stop: break diff --git a/tests/greenfield/test_implement_test_feedback.py b/tests/greenfield/test_implement_test_feedback.py index 615a57f6..84cac689 100644 --- a/tests/greenfield/test_implement_test_feedback.py +++ b/tests/greenfield/test_implement_test_feedback.py @@ -279,14 +279,14 @@ def test_flaky(request): calls = trace.read_text().splitlines() assert [x for x in calls if x.startswith("feedback ")] == ["feedback helper", "feedback case"] assert calls.index("both audits") < calls.index("provision") < calls.index("suite") - assert calls.index("feedback helper") < calls.index("feedback case") < calls.index("oracle verdict") - assert calls.count("suite") == 5 # baseline, screening, two individual suites, final verification + between = calls[calls.index("feedback helper"):calls.index("feedback case")] + assert between[:4] == ["feedback helper", "oracle verdict", "both audits verdict", "suite"] assert calls[-3:] == ["provision", "verify", "suite"] [round_record] = feedback(root)["rounds"] assert round_record["passed_in_isolation"] == 1 assert [run["purpose"] for run in round_record["runs"] if "case" not in run] == [ - "round 1 suite", "screening suite", "candidate suite", "candidate suite", + "round 1 suite", "candidate suite", "suite after helper decision", "candidate suite", ] assert [item["decision"] for item in round_record["attempts"]] == ["accepted", "accepted"] assert [(item["before"], item["after"]) for item in round_record["attempts"]] == [(1, 0), (2, 1)] diff --git a/tests/greenfield/test_implement_test_feedback_assertion_forms.py b/tests/greenfield/test_implement_test_feedback_assertion_forms.py index ce8f8c2d..78b30614 100644 --- a/tests/greenfield/test_implement_test_feedback_assertion_forms.py +++ b/tests/greenfield/test_implement_test_feedback_assertion_forms.py @@ -48,7 +48,7 @@ def edit(root, owner, scope): assert attempts(state) == [("author", "accepted", "unstable tests passed the suite and isolated checks")] assert "state was pending" in case.prompts[0][1] assert any("marker authenticity OK" in message for message in case.messages) - assert runs == [(False, ""), (False, B), (True, ""), (True, ""), (True, B), (True, B), (True, B)] + assert runs == [(False, ""), (False, B), (True, ""), (True, B), (True, B), (True, B)] assert (case.root / TEST).read_text() == candidate @@ -106,7 +106,7 @@ def edit(root, owner, scope): assert runs[:2] == [(False, ""), (False, case_id)] if accepted: assert attempts(state) == [("author", "accepted", "failures decreased")] - assert runs[2:] == [(True, ""), (True, ""), (True, case_id)] + assert runs[2:] == [(True, ""), (True, case_id)] assert (case.root / TEST).read_text() == candidate else: assert attempts(state) == [ diff --git a/tests/greenfield/test_implement_test_feedback_assertion_forms_round2.py b/tests/greenfield/test_implement_test_feedback_assertion_forms_round2.py index 6ada23b7..6dac71df 100644 --- a/tests/greenfield/test_implement_test_feedback_assertion_forms_round2.py +++ b/tests/greenfield/test_implement_test_feedback_assertion_forms_round2.py @@ -30,7 +30,7 @@ def edit(root, owner, scope): assert attempts(case.drive(1)) == [("author", decision, reason)] expected = [(False, ""), (False, B)] if decision == "accepted": - expected.extend([(True, ""), (True, ""), (True, B)]) + expected.extend([(True, ""), (True, B)]) if unstable: expected.extend([(True, B), (True, B)]) assert runs == expected diff --git a/tests/greenfield/test_implement_test_feedback_batch.py b/tests/greenfield/test_implement_test_feedback_batch.py index 1b66cc36..912c0a60 100644 --- a/tests/greenfield/test_implement_test_feedback_batch.py +++ b/tests/greenfield/test_implement_test_feedback_batch.py @@ -1,4 +1,4 @@ -"""Screening, individual acceptance, and handoff to source owners.""" +"""Sequential candidate judgments and handoff to source owners.""" import json import os @@ -18,6 +18,7 @@ REGRESSION = TEST + "::test_passing" +CLAIM = ".codd/implement-test-feedback/claims/1-1.json" def three_owners(tmp_path, monkeypatch, *, fixed=None, regression=None, regression_case=REGRESSION, @@ -42,19 +43,24 @@ def outcomes(root, selected): ], outcomes) -def test_y1_screening_skips_individual_suites_for_owners_without_progress(tmp_path, monkeypatch): +def test_each_owner_is_judged_before_the_next_owner_edits(tmp_path, monkeypatch): fixture = three_owners(tmp_path, monkeypatch, fixed=lambda a, b, c: (False, b, False)) [record] = fixture.drive(1)["rounds"] assert [owner for owner, _ in fixture.prompts] == ["a", "b", "c"] assert [(run["purpose"], run["failures_and_errors"]) for run in record["runs"] if "case" not in run] == [ - ("round 1 suite", 3), ("screening suite", 2), ("candidate suite", 2), + ("round 1 suite", 3), ("candidate suite", 3), ("candidate suite", 2), ("candidate suite", 2), + ] + timeline = [message.removeprefix("[implement test feedback] ") for message in fixture.messages] + assert [message.split(":", 1)[0].split(" to ")[-1] for message in timeline + if message.startswith("returning ") or message.startswith("candidate suite: fake-runner")] == [ + "a", "candidate suite", "b", "candidate suite", "c", "candidate suite", ] assert [attempt["decision"] for attempt in record["attempts"]] == ["rejected", "accepted", "rejected"] assert [revised(fixture.root, name) for name in (REPAIR, TEST, THIRD)] == [False, True, False] -def test_screening_does_not_count_a_new_failure_phase_as_a_fix(tmp_path, monkeypatch): +def test_candidate_suite_does_not_count_a_new_failure_phase_as_a_fix(tmp_path, monkeypatch): def outcomes(root, selected): return {B: "failed"}, {B: {"phase": "teardown" if revised(root, TEST) else "call"}} @@ -62,7 +68,7 @@ def outcomes(root, selected): [record] = fixture.drive(1)["rounds"] assert record["attempts"][0]["decision"] == "rejected" assert [run["purpose"] for run in record["runs"] if "case" not in run] == [ - "round 1 suite", "screening suite", + "round 1 suite", "candidate suite", ] @@ -75,12 +81,9 @@ def test_y2_individual_suite_exposes_what_another_owner_masks(tmp_path, monkeypa fixture = three_owners(tmp_path, monkeypatch, regression=lambda a, b: a and not b) reason = f"previously passing test now fails in isolation: {REGRESSION}" [record] = fixture.drive(1)["rounds"] - [screening] = [run for run in record["runs"] if run["purpose"] == "screening suite"] - assert set(screening["cases"].values()) == {"passed"} assert [revised(fixture.root, name) for name in (REPAIR, TEST, THIRD)] == [False, True, True] first, second, third = record["attempts"] assert first["decision"] == "rejected" and first["reason"] == reason - assert not first.get("candidate_failure_from_screening") assert [second["decision"], third["decision"]] == ["accepted", "accepted"] assert first["suite_after"] == 3 @@ -112,49 +115,28 @@ def regression(a, b): assert sum(run["purpose"] == "candidate suite" for run in record["runs"]) == 3 -def test_d1_candidate_instability_is_returned_in_the_next_round(tmp_path, monkeypatch): +def test_earlier_candidate_can_expose_instability_for_the_same_round(tmp_path, monkeypatch): def outcomes(root, selected): a, b = (revised(root, name) for name in (REPAIR, TEST)) cases = {A: "passed" if a else "failed", B: "failed" if a and not b and not selected else "passed"} return ({selected: cases[selected]} if selected else cases), {} fixture = fake(tmp_path, monkeypatch, [ref("a", REPAIR), ref("b", TEST)], outcomes) - first, second = fixture.drive(2)["rounds"] - assert [(a["owner"], a["decision"]) for a in first["attempts"]] == [("a", "accepted")] - assert first["deferred_unstable"] == [B] - [attempt] = second["attempts"] + [record] = fixture.drive(1)["rounds"] + first, attempt = record["attempts"] + assert (first["owner"], first["decision"]) == ("a", "accepted") assert (attempt["owner"], attempt["decision"]) == ("b", "accepted") assert list(attempt["unstable_cases"]) == [B] - assert sum(run["purpose"] == "candidate unstable isolate" for run in second["runs"]) == 3 + assert sum(run["purpose"] == "candidate unstable isolate" for run in record["runs"]) == 3 -def test_d7_resumes_the_pending_batch_when_validation_is_interrupted(tmp_path, monkeypatch): +@pytest.mark.parametrize("interrupted", ["a", "b"]) +def test_resume_discards_the_interrupted_candidate_and_keeps_earlier_acceptances(tmp_path, monkeypatch, interrupted): fixture = three_owners(tmp_path, monkeypatch) run_tests = engine._Feedback.run_tests def interrupt(self, record, purpose, case=None, timeout=None, *, target=None): - if purpose == "screening suite": - self.snapshot.restore(target) - raise KeyboardInterrupt - return run_tests(self, record, purpose, case, timeout, target=target) - - with monkeypatch.context() as patch: - patch.setattr(engine._Feedback, "run_tests", interrupt) - with pytest.raises(KeyboardInterrupt): - fixture.drive(1) - assert [a["decision"] for a in fixture.record["test_feedback"]["rounds"][0]["attempts"]] == ["pending"] * 3 - assert [owner for owner, _ in fixture.prompts] == ["a", "b", "c"] - [record] = fixture.drive(1, resume=True)["rounds"] - assert [a["decision"] for a in record["attempts"]] == ["accepted"] * 3 - assert [owner for owner, _ in fixture.prompts] == ["a", "b", "c"] - - -def test_d7_resumes_individual_validation_without_undoing_the_first_acceptance(tmp_path, monkeypatch): - fixture = three_owners(tmp_path, monkeypatch) - run_tests = engine._Feedback.run_tests - - def interrupt(self, record, purpose, case=None, timeout=None, *, target=None): - if purpose == "candidate suite" and record["attempts"][0]["decision"] == "accepted": + if purpose == "candidate suite" and record["attempts"][-1]["owner"] == interrupted: self.snapshot.restore(target) raise KeyboardInterrupt return run_tests(self, record, purpose, case, timeout, target=target) @@ -163,14 +145,22 @@ def interrupt(self, record, purpose, case=None, timeout=None, *, target=None): patch.setattr(engine._Feedback, "run_tests", interrupt) with pytest.raises(KeyboardInterrupt): fixture.drive(1) + [unfinished] = fixture.record["test_feedback"]["rounds"] + assert [(a["owner"], a["decision"]) for a in unfinished["attempts"]] == ( + [("a", "started")] if interrupted == "a" else [("a", "accepted"), ("b", "started")] + ) [record] = fixture.drive(1, resume=True)["rounds"] - assert [a["decision"] for a in record["attempts"]] == ["accepted"] * 3 - assert [revised(fixture.root, name) for name in (REPAIR, TEST, THIRD)] == [True] * 3 + assert [a["decision"] for a in record["attempts"]] == [ + "rejected" if owner == interrupted else "accepted" for owner in ("a", "b", "c") + ] + assert [revised(fixture.root, name) for name in (REPAIR, TEST, THIRD)] == [ + interrupted != "a", interrupted != "b", True, + ] assert [owner for owner, _ in fixture.prompts] == ["a", "b", "c"] - assert sum(run["purpose"] == "screening suite" for run in record["runs"]) == 1 + assert not list((fixture.root / engine.STATE_DIRECTORY).glob("pending-*.zip")) -def test_reprovisioning_requires_pending_failures_to_reproduce_again(tmp_path, monkeypatch): +def test_reprovisioning_preserves_earlier_accepted_output(tmp_path, monkeypatch): provisions = 0 def provision(root): @@ -196,9 +186,9 @@ def edit(root, owner, scope): edit=edit, provision=provision) state = fixture.drive(1) first, second = state["rounds"][0]["attempts"] - assert first["reason"].startswith("returned failure no longer reproduces after reprovisioning") + assert first["decision"] == "accepted" assert "discarding and reprovisioning" in second["reason"] - assert provisions == 2 and not revised(fixture.root, REPAIR) + assert provisions == 2 and revised(fixture.root, REPAIR) @pytest.mark.parametrize("source_is_origin", [False, True]) @@ -224,7 +214,37 @@ def outcomes(root, selected): assert revised(fixture.root, SOURCE) and not revised(fixture.root, TEST) -def setup_claim_project(project_factory, *, write_test=False, stdout=False): +def test_j4_case_with_two_source_owners_is_not_handed_off(tmp_path, monkeypatch): + second_source = "src/cleanup.py" + author = replace(ref("author", TEST), dependencies=("application", "cleanup")) + fixture = fake(tmp_path, monkeypatch, [ + author, ref("application", SOURCE), ref("cleanup", second_source), + ], None, files={ + TEST: ( + "import pytest\n" + "from src import cleanup, subject\n\n" + "@pytest.fixture\n" + "def resource():\n" + " yield\n" + " cleanup.release()\n\n" + "def test_subject(resource):\n" + " subject.run()\n" + ), + SOURCE: "def run():\n raise ValueError('call failed')\n", + second_source: "def release():\n raise RuntimeError('cleanup failed')\n", + }) + monkeypatch.setattr(engine, "subprocess", subprocess) + monkeypatch.setattr(engine.VerifyRunner, "feedback_test_command", lambda *_: ( + [sys.executable, "-m", "pytest", "-q", "checks"], + fixture.root, {**os.environ, "PYTHONPATH": str(fixture.root), "PYTEST_DISABLE_PLUGIN_AUTOLOAD": "1"}, 30, + )) + [record] = fixture.drive(1)["rounds"] + [suite] = record["runs"] + assert suite["cases"][B] == "failed" and len(suite["fingerprints"][B]) == 2 + assert record["attempts"] == [] and fixture.prompts == [] + + +def setup_claim_project(project_factory, *, write_test=False, stale_stdout=False): tests = """\ from stub_app import subject @@ -241,19 +261,20 @@ def test_subject(): body_outputs += ("checks/test_body_owned.py",) claim = json.dumps({"case": f"{TEST_FILE}::test_subject", "path": APP, "reason": "value returns no result before the comparison"}) - direct = {} if stdout else {f"{engine.STATE_DIRECTORY}/claims/1-1.json": claim} pipeline, root, trace, _ = project_factory( rounds=1 if write_test else 2, initial={"case": {TEST_FILE: tests}, "application": {APP: source}}, owned={"case": (TEST_FILE,), "application": body_outputs}, - fixes={"case": {"direct": direct}, "application": {"files": body_fix}}, + fixes={"case": {"direct": {CLAIM: claim}}, "application": {"files": body_fix}}, ) - if stdout: + if stale_stdout: + stale = json.dumps({"case": f"{TEST_FILE}::test_subject", + "path": "src/obsolete.py", "reason": "stale report"}) script = trace.with_name("ai.py") script.write_text(script.read_text() + ( '\nif part == "feedback" and owner == "case" and "AssertionError: blocked before the comparison" in prompt:\n' ' print("paths: []")\n' - f' print({("CODD_TEST_FEEDBACK_CLAIM " + claim)!r})\n' + f' print({("CODD_TEST_FEEDBACK_CLAIM " + stale)!r})\n' )) lister = pipeline.task_lister pipeline.task_lister = lambda project: [ @@ -264,7 +285,7 @@ def test_subject(): def test_y3_claim_returns_to_dependency_and_retains_progress(project_factory, monkeypatch): - pipeline, root, _ = setup_claim_project(project_factory, stdout=True) + pipeline, root, _ = setup_claim_project(project_factory) rerun = pipeline._reimplement_tasks observed = [] @@ -283,7 +304,8 @@ def remember(project, tasks, prompt, config, **kwargs): assert "return 8" in (root / APP).read_text() assert all(content == (root / TEST_FILE).read_bytes() for _, _, content in observed) assert [owner for owner, _, _ in observed] == ["case", "application", "case"] - assert 'CODD_TEST_FEEDBACK_CLAIM {"case":' in observed[0][1] + assert CLAIM in observed[0][1] and '{"case":' in observed[0][1] + assert "CODD_TEST_FEEDBACK_CLAIM" not in observed[0][1] assert "AssertionError: reached the comparison" in observed[-1][1] assert second["reused_suites"][0]["purpose"] == "round 2 suite" @@ -299,8 +321,8 @@ def test_y4_body_turn_rejects_writes_even_to_its_own_test(project_factory): assert not (root / "checks/test_body_owned.py").exists() -def test_d3_file_writer_can_mix_claim_and_path_list_with_usage_logging(project_factory, monkeypatch): - pipeline, root, _ = setup_claim_project(project_factory, stdout=True) +def test_j3_file_writer_uses_json_despite_stale_stdout_and_usage_logging(project_factory, monkeypatch): + pipeline, root, _ = setup_claim_project(project_factory, stale_stdout=True) monkeypatch.setenv("CODD_AI_USAGE_LOG", "usage/ai.jsonl") monkeypatch.setenv("GIT_CONFIG_GLOBAL", os.devnull) monkeypatch.setenv("GIT_CONFIG_NOSYSTEM", "1") @@ -316,6 +338,7 @@ def with_capture(*args, **kwargs): pipeline.run(root) first, _ = feedback(root)["rounds"] assert [a["decision"] for a in first["attempts"]] == ["declined", "accepted"] + assert first["attempts"][0]["claim"]["path"] == APP assert (root / "usage/ai.jsonl").is_file() @@ -468,3 +491,11 @@ def edit(root, owner, outputs): assert second["attempts"][0]["decision"] == "rejected" assert all(run["purpose"] != "round 2 suite" for run in second["runs"]) assert second["reused_suites"][0]["from"].endswith("(candidate suite)") + + +def test_y6_reruns_when_the_final_suite_used_a_rejected_tree(tmp_path, monkeypatch): + fixture = fake(tmp_path, monkeypatch, [ref("test", TEST)], lambda *_: ({B: "failed"}, {})) + first, second = fixture.drive(2)["rounds"] + assert first["attempts"][0]["decision"] == "rejected" + assert second["runs"][0]["purpose"] == "round 2 suite" + assert "reused_suites" not in second diff --git a/tests/greenfield/test_implement_test_feedback_findings.py b/tests/greenfield/test_implement_test_feedback_findings.py index 33ddb5b6..5ecc37f7 100644 --- a/tests/greenfield/test_implement_test_feedback_findings.py +++ b/tests/greenfield/test_implement_test_feedback_findings.py @@ -451,7 +451,6 @@ def test_case_depends_on_collection(request): assert actual == 1 """) pipeline, root, trace, _ = project_factory( - rounds=2, initial={ "case": {TEST_FILE: tests}, "helper": {HELPER: "FIXED = False\ndef value():\n return [7][1]\n"}, @@ -464,17 +463,15 @@ def test_case_depends_on_collection(request): ) result = pipeline.run(root) assert result.status == "success", result.error - first, second = feedback(root)["rounds"] - helper, ordinary = first["attempts"] - [unstable] = second["attempts"] + record = _round(root) + helper, unstable = record["attempts"] assert (helper["owner"], helper["decision"]) == ("helper", "accepted") - assert ordinary["owner"] == "case" and "unstable_cases" not in ordinary events = _trace(trace) isolate = f"isolate {TEST_FILE}::test_case_depends_on_collection" + assert events.count(isolate) == 1 assert events.index("feedback helper") < events.index(isolate) < events.index("feedback case") - assert second["reused_suites"][0]["purpose"] == "round 2 suite" - assert second["passed_in_isolation"] == 1 - assert list(unstable["unstable_cases"]) == [f"{TEST_FILE}::test_case_depends_on_collection"] + assert [run["purpose"] for run in record["runs"][-3:]] == ["suite after helper decision", "isolate", "candidate suite"] + assert record["passed_in_isolation"] == 1 assert (unstable["owner"], unstable["decision"]) == ("case", "rejected") assert unstable["reason"] == f"unstable test still fails: {TEST_FILE}::test_case_depends_on_collection" diff --git a/tests/greenfield/test_implement_test_feedback_owner_scheduling.py b/tests/greenfield/test_implement_test_feedback_owner_scheduling.py index 6ef476b4..a85e0a5d 100644 --- a/tests/greenfield/test_implement_test_feedback_owner_scheduling.py +++ b/tests/greenfield/test_implement_test_feedback_owner_scheduling.py @@ -126,7 +126,7 @@ def interrupt(project_root, tasks, *args, **kwargs): [interrupted_round] = feedback(root)["rounds"] assert [(attempt["owner"], attempt["decision"]) for attempt in interrupted_round["attempts"]] == [ - ("a", "pending"), ("b", "started"), + ("a", "accepted"), ("b", "started"), ] [record] = _run(pipeline, root, resume=True) assert [(attempt["owner"], attempt["decision"]) for attempt in record["attempts"]] == [ diff --git a/tests/greenfield/test_implement_test_feedback_round2.py b/tests/greenfield/test_implement_test_feedback_round2.py index fb2e56f7..f1642829 100644 --- a/tests/greenfield/test_implement_test_feedback_round2.py +++ b/tests/greenfield/test_implement_test_feedback_round2.py @@ -124,7 +124,7 @@ def prepare(project_root): case = f"isolate {second}::test_second" assert lines.count(case) == 1 assert lines.index("feedback case") < lines.index(case) < lines.index("feedback second") - assert [run["purpose"] for run in record["runs"][-3:]] == ["suite after reprovisioning", "isolate", "screening suite"] + assert [run["purpose"] for run in record["runs"][-3:]] == ["suite after reprovisioning", "isolate", "candidate suite"] assert (unstable["owner"], unstable["decision"]) == ("second", "rejected") assert unstable["reason"] == f"unstable test still fails: {second}::test_second" assert record["passed_in_isolation"] == 1 diff --git a/tests/greenfield/test_implement_test_feedback_round3.py b/tests/greenfield/test_implement_test_feedback_round3.py index 91b04f1a..5ae22e1b 100644 --- a/tests/greenfield/test_implement_test_feedback_round3.py +++ b/tests/greenfield/test_implement_test_feedback_round3.py @@ -44,7 +44,6 @@ def test_dependent(request): assert test_subject.FIX_ENABLED and len(request.session.items) == 1 """) pipeline, root, trace, _ = project_factory( - rounds=2, initial={"case": {TEST_FILE: "FIX_ENABLED = False\n" + TESTS}, "dependent": {other: dependent}}, owned={"case": (TEST_FILE,), "dependent": (other,)}, fixes={ @@ -52,21 +51,16 @@ def test_dependent(request): "dependent": {"files": {other: "# Still depends on collection.\n" + dependent}}, }, ) - result = pipeline.run(root) - assert result.status == "success", result.error - first, second = feedback(root)["rounds"] - attempt, ordinary = first["attempts"] - [unstable] = second["attempts"] + record = _run(pipeline, root) + attempt, unstable = record["attempts"] assert (attempt["owner"], attempt["decision"]) == ("case", "accepted") assert attempt["suite_after"] == 1 - assert ordinary["owner"] == "dependent" and "unstable_cases" not in ordinary - assert second["passed_in_isolation"] == 1 + assert record["passed_in_isolation"] == 1 timeline = trace.read_text().splitlines() isolate = f"isolate {other}::test_dependent" + assert timeline.count(isolate) == 1 assert timeline.index("feedback case") < timeline.index(isolate) assert timeline.index(isolate) < timeline.index("feedback dependent") - assert second["reused_suites"][0]["purpose"] == "round 2 suite" - assert list(unstable["unstable_cases"]) == [f"{other}::test_dependent"] assert (unstable["owner"], unstable["decision"]) == ("dependent", "rejected") assert unstable["reason"] == f"unstable test still fails: {other}::test_dependent" diff --git a/tests/greenfield/test_implement_test_feedback_unstable.py b/tests/greenfield/test_implement_test_feedback_unstable.py index a1eacf18..e23f1ebc 100644 --- a/tests/greenfield/test_implement_test_feedback_unstable.py +++ b/tests/greenfield/test_implement_test_feedback_unstable.py @@ -141,8 +141,7 @@ def outcomes(version, selected, count): statuses = { SUBJECT: "passed" if repaired else "failed", OTHER: other, - # Both the screening suite and the individual suite see this failure. - OBSERVER: "failed" if repaired and not observer_fixed and count < 2 else "passed", + OBSERVER: "failed" if repaired and not observer_fixed and count == 0 else "passed", } return ({selected: statuses[selected]} if selected else statuses), "suite output" diff --git a/tests/greenfield/test_implement_test_feedback_w18_r2.py b/tests/greenfield/test_implement_test_feedback_w18_r2.py index e5f72657..e8d949ca 100644 --- a/tests/greenfield/test_implement_test_feedback_w18_r2.py +++ b/tests/greenfield/test_implement_test_feedback_w18_r2.py @@ -66,8 +66,8 @@ def rotate_helper(request): helper.unlink() helper.symlink_to(replacement.name) - def test_a(request, rotate_helper): - assert helpers.value(isolated=len(request.session.items) == 1) == 7 + def test_a(rotate_helper): + assert helpers.value() == 7 def test_b(request): if len(request.session.items) > 1: @@ -78,8 +78,8 @@ def test_b(request): helper = textwrap.dedent("""\ EXTRA_FIXED = False - def value(isolated): - return 7 if EXTRA_FIXED and not isolated else [7][1] + def value(): + return [7][1] def extra(): return 8 if EXTRA_FIXED else [8][1] @@ -104,7 +104,7 @@ def record_original(project_root, *args, **kwargs): [record] = feedback(root)["rounds"] [attempt] = record["attempts"] [isolation] = [run for run in record["runs"] if run["purpose"] == "candidate isolate"] - assert (attempt["suite_before"], attempt["suite_after"], attempt["isolated_before"]) == (2, 0, 1) + assert (attempt["suite_before"], attempt["suite_after"], attempt["isolated_before"]) == (2, 1, 1) assert isolation["case"] == f"{TEST_FILE}::test_a" assert isolation["failures_and_errors"] == 1 assert attempt["isolated_after"] == 1 diff --git a/tests/greenfield/test_implement_test_feedback_w21b_review.py b/tests/greenfield/test_implement_test_feedback_w21b_review.py index f592b737..ff3671a1 100644 --- a/tests/greenfield/test_implement_test_feedback_w21b_review.py +++ b/tests/greenfield/test_implement_test_feedback_w21b_review.py @@ -175,20 +175,23 @@ def edit(root, owner, scope): assert "without broadening the values they accept" in case.prompts[0][1] -def baseline_script(*, origin=None): +def baseline_script(*, origin=None, reprovision=False): full_after_repair = 0 def outcomes(root, selected): nonlocal full_after_repair fixed = revised(root, HELPER) + already_reprovisioned = reprovision and (root / RUNTIME).read_text() == "new" if selected == B: - failed = not revised(root, TEST) + failed = not (already_reprovisioned or revised(root, TEST)) elif not selected and fixed: full_after_repair += 1 - failed = full_after_repair <= 2 # Screening and the first individual review. + failed = full_after_repair == 1 else: failed = False cases = {A: "passed" if fixed else "failed", B: "failed" if failed else "passed"} + if reprovision: + cases[C] = "passed" if already_reprovisioned else "failed" details = {A: {"origin": HELPER}, B: {"detail": "baseline evidence", **(origin or {})}} return ({selected: cases[selected]} if selected else cases), details @@ -226,7 +229,7 @@ def outcomes(root, selected): B: "failed" if repaired and not selected and not new_environment else "passed", C: "passed" if revised(root, THIRD) or new_environment else "failed", } - return ({selected: cases[selected]} if selected else cases), {} + return ({selected: cases[selected]} if selected else cases), {B: {"origin": THIRD}} case = fake(tmp_path, monkeypatch, [ref("repair", REPAIR), ref("observer", TEST), ref("third", THIRD)], outcomes, provision=provision) @@ -241,7 +244,7 @@ def change_environment(self, record, target): monkeypatch.setattr(engine._Feedback, "gate_problem", change_environment) state = case.drive(4) assert [(a, b) for a, b, _ in attempts(state)] == [("repair", "accepted"), ("third", "rejected")] - assert "test environment changed during candidate checks" in attempts(state)[1][2] + assert "discarding and reprovisioning" in attempts(state)[1][2] assert [owner for owner, _ in case.prompts] == ["repair", "third"] and n_provisions == 2 [record] = state["rounds"] assert record["unstable_observations"][0]["case"] == B From 52230b03783659e50e3e9daa837bfb72e210cbcb Mon Sep 17 00:00:00 2001 From: yohey-w Date: Tue, 1 Dec 2026 19:39:27 +0900 Subject: [PATCH 8/8] fix(greenfield): close the last review findings; keep every main test expectation Final review follow-up. - The round-start suite runs every round again (reusing it missed a changed symlink target inside the test environment). - An implementation owner fixing another task's test may not change files that test-tree symlinks point to. - A stored claim's destination is re-validated against the current task list and dependencies every time it is used. - An implementation owner's change counts as progress when the set of failure fingerprints of the returned case changed (one of a call and a teardown failure going away is progress). - No expectation of an existing test on main changed; the added scenarios live in tests/greenfield/test_implement_test_feedback_batch.py. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_014yyaLv8ZQ3GiQnmizx4cqb --- codd/greenfield/implement_test_feedback.py | 209 +++++++------- .../test_implement_test_feedback.py | 4 +- .../test_implement_test_feedback_batch.py | 256 +++++++++++++++++- ...mplement_test_feedback_owner_scheduling.py | 7 +- .../test_implement_test_feedback_unstable.py | 2 - ...est_implement_test_feedback_w21b_review.py | 38 +-- 6 files changed, 364 insertions(+), 152 deletions(-) diff --git a/codd/greenfield/implement_test_feedback.py b/codd/greenfield/implement_test_feedback.py index 2a43d235..536faecc 100644 --- a/codd/greenfield/implement_test_feedback.py +++ b/codd/greenfield/implement_test_feedback.py @@ -19,7 +19,7 @@ from functools import cache from io import BytesIO from pathlib import Path -from zipfile import ZIP_DEFLATED, BadZipFile, ZipFile, ZipInfo +from zipfile import ZIP_DEFLATED, ZipFile, ZipInfo from codd.ai_usage import resolve_usage_log from codd.ansi import strip_ansi @@ -34,7 +34,7 @@ from codd.languages.contract import resolve_language_profile from codd.languages.registry import UnknownLanguageError, default_adapter_registry from codd.operational_e2e_audit import _COVER_MARKER_RE -from codd.path_safety import iter_project_glob +from codd.path_safety import iter_project_glob, project_relative_path from codd.reference_resolution import AUDIT_RELATIVE_PATH from codd.repair.history import record_full_failure from codd.repair.verify_runner import VerifyRunner, _command_output_tail @@ -359,15 +359,8 @@ def recover_interrupted_feedback(root, record, echo, checkpoint) -> None: if had_baseline and snapshot.environment_changed(round_record.get("environment_before")): _discard_feedback_environment(snapshot, state) round_record["screened"].clear() - for index, attempt in enumerate(round_record["attempts"], 1): - if attempt["decision"] not in ("started", "pending"): - continue - if attempt["decision"] == "pending": - # An older checkpoint can contain unreviewed candidates. - attempt.update(decision="rejected", verdict="gate rejected", - reason="unreviewed candidate discarded on resume") - (snapshot.archive.parent / f"pending-{round_record['number']}-{index}.zip").unlink(missing_ok=True) - checkpoint(root) + for attempt in round_record["attempts"]: + if attempt["decision"] != "started": continue if not had_baseline: snapshot.restore(snapshot.read(snapshot.archive)) @@ -486,8 +479,6 @@ def __init__(self, pipeline, root, tasks, state, options, config, adapter, test_ self.target: dict[str, _Entry] = {} self.environment_dirty = False self.outputs: dict[str, DeclaredOutputs] = {} - self.suite_cache = self.snapshot.archive.with_name("last-suite.zip") - self.last_suite = self.load_last_suite() self.logs = {AUDIT_RELATIVE_PATH} try: usage_log = resolve_usage_log(config, root) @@ -496,29 +487,6 @@ def __init__(self, pipeline, root, tasks, state, options, config, adapter, test_ if usage_log is not None and usage_log.is_relative_to(root) and not usage_log.is_dir(): self.logs.add(usage_log.relative_to(root)) - def load_last_suite(self): - last_round = next((r["number"] for r in reversed(self.state["rounds"]) if r.get("done")), None) - if last_round is not None: - try: - saved = json.loads(self.snapshot.read(self.suite_cache)["suite.json"].data) - if saved["round"] == last_round: - return bytes.fromhex(saved["tree"]), _Suite(**saved["suite"]) - except (OSError, ValueError, KeyError, TypeError, BadZipFile): - pass - return None - - def remember_last_suite(self, record): - if self.last_suite is None: - return - key, suite = self.last_suite - payload = {"round": record["number"], "tree": key.hex(), "suite": vars(suite)} - try: - self.snapshot.persist({"suite.json": _Entry(stat.S_IFREG | 0o600, json.dumps(payload).encode())}, - self.suite_cache) - except OSError: - # State caches are optional. A missing entry forces a fresh suite. - pass - def round_outputs(self) -> dict[str, DeclaredOutputs]: outputs = {task.task_id: DeclaredOutputs(self.root, task.expected_outputs) for task in self.tasks} self.add_provenance_claims(outputs) @@ -705,24 +673,6 @@ def fingerprints(suite): by_case[failure["case"]].append(_failure_fingerprint(failure)) return dict(by_case) - def full_suite(self, round_record, purpose, target, *, reuse=False): - digest = hashlib.sha256() - for name, entry in sorted(target.items()): - digest.update(json.dumps((name, entry.mode, len(entry.data))).encode()) - digest.update(entry.data) - environment = round_record["environment_before"] - digest.update(json.dumps((self.command, str(self.cwd), self.env, environment), sort_keys=True).encode()) - key = digest.digest() - if (reuse and self.last_suite is not None and key == self.last_suite[0] - and not self.snapshot.environment_changed(environment)): - result = self.last_suite[1] - round_record.setdefault("reused_suites", []).append({"purpose": purpose, "from": result.run_label}) - self.snapshot.restore(target) - return result - result = self.run_tests(round_record, purpose, target=target) - self.last_suite = None if result.unavailable or result.unreported_launch else (key, result) - return result - def replay_failure_details(self, round_record, failures) -> list[dict]: needs_replay = getattr(self.adapter, "needs_failure_replay", None) if needs_replay is None: @@ -805,8 +755,7 @@ def body_owners(self, failure, paths): def body_groups(self, suite, routes): reported = defaultdict(set) for route in routes: - if route["owner"] in self.tasks_by_id: - reported[route["case"], route["fingerprint"]].add(route["owner"]) + reported[route["case"], route["fingerprint"]].add(route["owner"]) by_case = defaultdict(list) for failure in suite.failures: origins = _failure_origins(failure) @@ -823,6 +772,23 @@ def body_groups(self, suite, routes): grouped[next(iter(owners))].extend(failure for failure, owners in reports if owners) return grouped + def valid_routes(self, suite, routes): + if not routes: + return [] + failures = {(f["case"], _failure_fingerprint(f)): f for f in suite.failures} + valid = [] + for route in routes: + failure = failures.get((route["case"], route["fingerprint"])) + if failure is None: + continue + paths = route.get("paths", (*_failure_origins(failure), *failure.get("paths", ()))) + owners = self.body_owners(failure, paths) + if route["owner"] in owners: + # Preserve conflicting owners so the case still has to pass + # the uniqueness check across all of its failure reports. + valid.extend({**route, "owner": owner} for owner in sorted(owners)) + return valid + def owner_groups(self, suite): grouped = defaultdict(list) for failure in suite.failures: @@ -1003,7 +969,7 @@ def body_progress(suite, case, before): if status == "passed": return "fixed" after = {_failure_fingerprint(f) for f in suite.failures if f["case"] == case} - if status == "failed" and before and after and before.isdisjoint(after): + if status == "failed" and before and after and before != after: return "progressed" return None @@ -1020,7 +986,7 @@ def assess(self, record, attempt, suite, failures, target, isolated_failures): if reason := self.gate_problem(record, target): return reason, None, None - candidate = self.full_suite(record, "candidate suite", target) + candidate = self.run_tests(record, "candidate suite", target=target) attempt["after"] = self.count(candidate, owner, case_ids, unstable) attempt["suite_after"] = len(candidate.failures) if candidate.unavailable: @@ -1086,21 +1052,24 @@ def regression(self, record, attempt, suite, candidate, before, target, deadline break if result.cases[case] == "passed": continue - for passed in range(_BASELINE_REGRESSION_RUNS): - baseline, problem = self.isolate(record, case, "baseline isolate", before, deadline) - if problem: - return problem, None - if baseline.cases[case] != "passed": - attempt.setdefault("baseline_failures", []).append({ - "case": case, "passed": passed, "failed": 1, - }) - self.observe_unstable(record, case, suite, baseline) - break - else: - return f"{_REGRESSION_REASON}: {case}", result + try: + for passed in range(_BASELINE_REGRESSION_RUNS): + baseline, problem = self.isolate(record, case, "baseline isolate", before, deadline) + if problem: + return problem, None + if baseline.cases[case] != "passed": + attempt.setdefault("baseline_failures", []).append({ + "case": case, "passed": passed, "failed": 1, + }) + self.observe_unstable(record, case, suite, baseline) + break + else: + return f"{_REGRESSION_REASON}: {case}", result + finally: + self.snapshot.restore(target) return None, None - def reject(self, attempt, reason, candidate, *, suite, regression, isolated_failures): + def reject(self, attempt, reason, candidate, *, suite, scope, regression, isolated_failures): attempt.update(decision="rejected", reason=reason, verdict="gate rejected") if candidate is not None: cases = {f["case"] for f in attempt["returned_failures"]} | attempt.get("unstable_cases", {}).keys() @@ -1123,7 +1092,6 @@ def reject(self, attempt, reason, candidate, *, suite, regression, isolated_fail elif reason.startswith("failure fingerprint did not advance"): attempt["verdict"] = "stalled" _, _, case = reason.partition(": ") - scope = self.scope(attempt["owner"], attempt["recipient"] == "body") if regression is not None and not scope.allows(Path(case.partition("::")[0])): attempt["rejection_output"] = self.failure_excerpt( regression.output or "\n\n".join(f["detail"] for f in regression.failures), @@ -1173,23 +1141,51 @@ def keep_outputs(self, round_record, kept): self.target = kept @staticmethod - def route(failure, owner): - return {"case": failure["case"], "fingerprint": _failure_fingerprint(failure), "owner": owner} + def route(failure, owner, paths): + return {"case": failure["case"], "fingerprint": _failure_fingerprint(failure), + "owner": owner, "paths": sorted(set(paths))} - def scope(self, owner, body): + def test_tree_paths(self, entries): + protected = dict.fromkeys(self.test_roots, True) + for root in self.test_roots: + try: + resolved = project_relative_path(self.root, root) + except RuntimeError: # A symlink loop on older Python versions. + continue + if resolved is not None: + protected[Path(resolved)] = True + # A linked directory can contain more links. Walk only links already + # inventoried in the project snapshot, once each. + links = {Path(rel) for rel, entry in entries.items() if stat.S_ISLNK(entry.mode)} + while reachable := {link for link in links if DeclaredOutputs._contains(link, protected)}: + links -= reachable + for link in reachable: + try: + resolved = project_relative_path(self.root, link) + except RuntimeError: # A symlink loop on older Python versions. + continue + if resolved is not None: + path = Path(resolved) + protected[path] = protected.get(path, False) or (self.root / path).is_dir() + return protected + + def scope(self, owner, protected): scope = self.outputs[owner] - if not body: + if not protected: return scope narrowed = DeclaredOutputs(self.root, ()) narrowed.paths = scope.paths.copy() - narrowed.excluded = {**scope.excluded, **dict.fromkeys(self.test_roots, True)} + narrowed.excluded = scope.excluded.copy() + for path, directory in protected.items(): + narrowed.excluded[path] = directory or narrowed.excluded.get(path, False) return narrowed def attempt(self, round_record, task, failures, suite, unstable, *, body=False): owner = task.task_id - scope = self.scope(owner, body) before = self.target self.snapshot.restore(before) + protected = self.test_tree_paths(before) if body else {} + scope = self.scope(owner, protected) environment_before = round_record["environment_before"] case_ids = {f["case"] for f in failures} attempt = { @@ -1239,6 +1235,8 @@ def attempt(self, round_record, task, failures, suite, unstable, *, body=False): claim = self.read_claim(claim_file, case_ids) if reason is None and claim is None: reason = self.change_problem(scope, before, proposed, unstable) + if reason is None and body and self.test_tree_paths(proposed) != protected: + reason = "test-tree symbolic link targets changed" if reason is None: target = self.candidate_target(scope, proposed) reason, candidate, regression = self.assess( @@ -1261,7 +1259,7 @@ def attempt(self, round_record, task, failures, suite, unstable, *, body=False): if claim is not None and not dirty: self.record_claim(round_record, attempt, suite, claim) elif reason is not None: - self.reject(attempt, reason, candidate if not dirty else None, suite=suite, + self.reject(attempt, reason, candidate if not dirty else None, suite=suite, scope=scope, regression=regression, isolated_failures=isolated_failures) else: self.record_stall(attempt, suite, candidate, isolated_failures) @@ -1338,7 +1336,17 @@ def record_claim(self, record, attempt, suite, claim): for failure in suite.failures: if _failure_key(failure) in returned: for owner in sorted(self.body_owners(failure, (claim["path"],))): - routes.append(self.route(failure, owner)) + routes.append(self.route(failure, owner, (claim["path"],))) + + @staticmethod + def claim_routes(record): + # Older checkpoints kept the claim path on the declined attempt only. + paths = defaultdict(set) + for attempt in record["attempts"]: + if attempt["decision"] == "declined" and (claim := attempt.get("claim")): + paths[claim["case"]].add(claim["path"]) + return [route if "paths" in route else {**route, "paths": paths[route["case"]]} + for route in record.get("claims", ())] def only_log_appends(self, before, proposed): writes = _writes(before, proposed) @@ -1438,31 +1446,29 @@ def signature(failure): baseline_signatures = {signature(f) for f in baseline} stalled = [f for f in candidate.failures if signature(f) in baseline_signatures] stalled.extend(f for f in isolated_failures if signature(f) in returned) - owners_by_case = defaultdict(set) + paths_by_case = defaultdict(set) for failure in stalled: - paths = (*_failure_origins(failure), *failure.get("paths", ())) - owners_by_case[failure["case"]].update(self.body_owners(failure, paths)) + paths_by_case[failure["case"]].update((*_failure_origins(failure), *failure.get("paths", ()))) stalled_keys = {_failure_key(failure) for failure in stalled} - routes = {(failure["case"], _failure_fingerprint(failure), owner) - for failure in baseline if _failure_key(failure) in stalled_keys - for owner in owners_by_case[failure["case"]]} + routes = [] + for failure in baseline: + if _failure_key(failure) in stalled_keys: + paths = paths_by_case[failure["case"]] + for owner in sorted(self.body_owners(failure, paths)): + route = self.route(failure, owner, paths) + if route not in routes: + routes.append(route) if routes: - attempt["stalled_routes"] = [ - {"case": case, "fingerprint": fingerprint, "owner": owner} - for case, fingerprint, owner in sorted(routes) - ] + attempt["stalled_routes"] = routes return bool(stalled) def reprovision(self, record): _restore_round_for_provisioning(self.snapshot, record) _discard_feedback_environment(self.snapshot, self.state) self.environment_dirty = False - self.last_suite = None record["screened"].clear() problem = self.prepare(record) - return _Suite(unavailable=problem) if problem else self.full_suite( - record, "suite after reprovisioning", self.target, - ) + return _Suite(unavailable=problem) if problem else self.run_tests(record, "suite after reprovisioning") def run(self, rounds: int) -> None: for index in range(rounds): @@ -1483,9 +1489,8 @@ def run(self, rounds: int) -> None: for route in attempt.get("stalled_routes", ()) ] if index else [] problem = self.prepare(record) - suite = _Suite(unavailable=problem) if problem else self.full_suite( - record, f"round {index + 1} suite", self.target, - reuse=not record["runs"] and not record["attempts"], + suite = _Suite(unavailable=problem) if problem else self.run_tests( + record, f"round {index + 1} suite", ) handled = {(a["owner"], a.get("recipient", "test")) for a in record["attempts"] if not a.get("interrupted")} @@ -1498,8 +1503,8 @@ def run(self, rounds: int) -> None: unreproduced = set() isolation_problem = None while not suite.unavailable: - claims = record.get("claims", ()) - body_groups = self.body_groups(suite, [*prior_routes, *claims]) + claims = self.valid_routes(suite, self.claim_routes(record)) + body_groups = self.body_groups(suite, [*self.valid_routes(suite, prior_routes), *claims]) redirected = {_failure_key(f) for failures in body_groups.values() for f in failures} claimed_cases = {(claim["owner"], claim["case"], claim["fingerprint"]) for claim in claims} claimed_body, other_body = {}, {} @@ -1554,7 +1559,7 @@ def run(self, rounds: int) -> None: suite = self.reprovision(record) elif not body and self.has_helper(failures): record["screened"].clear() - suite = self.full_suite(record, "suite after helper decision", self.target) + suite = self.run_tests(record, "suite after helper decision") else: unreproduced.add((owner, recipient)) if time_exhausted: @@ -1562,7 +1567,7 @@ def run(self, rounds: int) -> None: routes = [route for attempt in record["attempts"] for route in attempt.get("stalled_routes", ())] stop = bool(suite.unavailable) or not ( self.unstable_groups() or any(owner not in interrupted for owner, _ in self.owner_groups(suite)) - or any(owner not in interrupted for owner in self.body_groups(suite, routes)) + or any(owner not in interrupted for owner in self.body_groups(suite, self.valid_routes(suite, routes))) ) record["over_isolation_budget"] = len(limited) if limited: @@ -1572,10 +1577,8 @@ def run(self, rounds: int) -> None: self.snapshot.restore(self.target) if self.environment_dirty: _discard_feedback_environment(self.snapshot, self.state) - self.last_suite = None self.emit("test environment changed; discarded before the next run") record.update(done=True, stop=stop) - self.remember_last_suite(record) problem = suite.unavailable or isolation_problem if problem: record["skipped"] = _command_output_tail(problem, None) diff --git a/tests/greenfield/test_implement_test_feedback.py b/tests/greenfield/test_implement_test_feedback.py index 84cac689..276f2c88 100644 --- a/tests/greenfield/test_implement_test_feedback.py +++ b/tests/greenfield/test_implement_test_feedback.py @@ -285,9 +285,7 @@ def test_flaky(request): [round_record] = feedback(root)["rounds"] assert round_record["passed_in_isolation"] == 1 - assert [run["purpose"] for run in round_record["runs"] if "case" not in run] == [ - "round 1 suite", "candidate suite", "suite after helper decision", "candidate suite", - ] + assert any(run["purpose"] == "suite after helper decision" for run in round_record["runs"]) assert [item["decision"] for item in round_record["attempts"]] == ["accepted", "accepted"] assert [(item["before"], item["after"]) for item in round_record["attempts"]] == [(1, 0), (2, 1)] case_prompt = trace.with_name("prompt-case").read_text() diff --git a/tests/greenfield/test_implement_test_feedback_batch.py b/tests/greenfield/test_implement_test_feedback_batch.py index 912c0a60..b973751f 100644 --- a/tests/greenfield/test_implement_test_feedback_batch.py +++ b/tests/greenfield/test_implement_test_feedback_batch.py @@ -5,6 +5,7 @@ import subprocess import sys from dataclasses import replace +from pathlib import Path import pytest @@ -13,7 +14,8 @@ from .test_implement_test_feedback import APP, TEST_FILE, feedback, project_factory from .test_implement_test_feedback_w21b_review import ( - A, B, C, HELPER, REPAIR, RUNTIME, SOURCE, TEST, THIRD, attempts, fake, ref, revised, write, + A, B, C, HELPER, REPAIR, RUNTIME, SOURCE, TEST, THIRD, attempts, baseline_script, fake, ref, revised, + write, ) @@ -60,6 +62,15 @@ def test_each_owner_is_judged_before_the_next_owner_edits(tmp_path, monkeypatch) assert [revised(fixture.root, name) for name in (REPAIR, TEST, THIRD)] == [False, True, False] +def test_suite_order_includes_the_helper_recheck(tmp_path, monkeypatch): + fixture = fake(tmp_path, monkeypatch, [ref("repair", HELPER), ref("observer", TEST)], baseline_script()) + [record] = fixture.drive(1)["rounds"] + assert [run["purpose"] for run in record["runs"] if "case" not in run] == [ + "round 1 suite", "candidate suite", "suite after helper decision", "candidate suite", + ] + assert [item["decision"] for item in record["attempts"]] == ["accepted", "accepted"] + + def test_candidate_suite_does_not_count_a_new_failure_phase_as_a_fix(tmp_path, monkeypatch): def outcomes(root, selected): return {B: "failed"}, {B: {"phase": "teardown" if revised(root, TEST) else "call"}} @@ -191,6 +202,50 @@ def edit(root, owner, scope): assert provisions == 2 and revised(fixture.root, REPAIR) +def test_reprovisioning_discards_instability_first_seen_in_candidate_suite(tmp_path, monkeypatch): + n_provisions = 0 + + def provision(root): + nonlocal n_provisions + n_provisions += 1 + write(root, RUNTIME, "new" if n_provisions > 1 else "old") + + def outcomes(root, selected): + new_environment = (root / RUNTIME).read_text() == "new" + repaired = revised(root, REPAIR) + cases = { + A: "passed" if repaired else "failed", + B: "failed" if repaired and not selected and not new_environment else "passed", + C: "passed" if revised(root, THIRD) or new_environment else "failed", + } + return ({selected: cases[selected]} if selected else cases), {B: {"origin": THIRD}} + + fixture = fake(tmp_path, monkeypatch, [ref("repair", REPAIR), ref("observer", TEST), ref("third", THIRD)], + outcomes, provision=provision) + verdict = engine._Feedback.gate_problem + + def change_environment(self, record, target): + self.snapshot.restore(target) + if revised(fixture.root, THIRD): + write(fixture.root, RUNTIME, "changed during candidate checks") + return verdict(self, record, target) + + monkeypatch.setattr(engine._Feedback, "gate_problem", change_environment) + state = fixture.drive(4) + assert [(a, b) for a, b, _ in attempts(state)] == [("repair", "accepted"), ("third", "rejected")] + assert "discarding and reprovisioning" in attempts(state)[1][2] + assert [owner for owner, _ in fixture.prompts] == ["repair", "third"] and n_provisions == 2 + [record] = state["rounds"] + assert record["unstable_observations"][0]["case"] == B + assert record["unstable_observations"][0]["failed_in"].endswith("(candidate suite)") + [initial] = [run for run in record["runs"] if run["purpose"] == "round 1 suite"] + assert initial["cases"][B] == "passed" + [reprovisioned] = [run for run in record["runs"] if run["purpose"] == "suite after reprovisioning"] + assert reprovisioned["failures_and_errors"] == 0 + assert record["attempts"][0]["suite_after"] == 2 + assert state["pending_unstable"] == {} and record["stop"] + + @pytest.mark.parametrize("source_is_origin", [False, True]) def test_d3_returns_stalled_and_source_origin_failures(tmp_path, monkeypatch, source_is_origin): def outcomes(root, selected): @@ -214,6 +269,14 @@ def outcomes(root, selected): assert revised(fixture.root, SOURCE) and not revised(fixture.root, TEST) +def use_real_tests(fixture, monkeypatch): + monkeypatch.setattr(engine, "subprocess", subprocess) + monkeypatch.setattr(engine.VerifyRunner, "feedback_test_command", lambda *_: ( + [sys.executable, "-m", "pytest", "-q", "-p", "no:cacheprovider", "checks"], + fixture.root, {**os.environ, "PYTHONPATH": str(fixture.root), "PYTEST_DISABLE_PLUGIN_AUTOLOAD": "1"}, 30, + )) + + def test_j4_case_with_two_source_owners_is_not_handed_off(tmp_path, monkeypatch): second_source = "src/cleanup.py" author = replace(ref("author", TEST), dependencies=("application", "cleanup")) @@ -233,11 +296,7 @@ def test_j4_case_with_two_source_owners_is_not_handed_off(tmp_path, monkeypatch) SOURCE: "def run():\n raise ValueError('call failed')\n", second_source: "def release():\n raise RuntimeError('cleanup failed')\n", }) - monkeypatch.setattr(engine, "subprocess", subprocess) - monkeypatch.setattr(engine.VerifyRunner, "feedback_test_command", lambda *_: ( - [sys.executable, "-m", "pytest", "-q", "checks"], - fixture.root, {**os.environ, "PYTHONPATH": str(fixture.root), "PYTEST_DISABLE_PLUGIN_AUTOLOAD": "1"}, 30, - )) + use_real_tests(fixture, monkeypatch) [record] = fixture.drive(1)["rounds"] [suite] = record["runs"] assert suite["cases"][B] == "failed" and len(suite["fingerprints"][B]) == 2 @@ -307,7 +366,7 @@ def remember(project, tasks, prompt, config, **kwargs): assert CLAIM in observed[0][1] and '{"case":' in observed[0][1] assert "CODD_TEST_FEEDBACK_CLAIM" not in observed[0][1] assert "AssertionError: reached the comparison" in observed[-1][1] - assert second["reused_suites"][0]["purpose"] == "round 2 suite" + assert second["runs"][0]["purpose"] == "round 2 suite" def test_y4_body_turn_rejects_writes_even_to_its_own_test(project_factory): @@ -321,6 +380,143 @@ def test_y4_body_turn_rejects_writes_even_to_its_own_test(project_factory): assert not (root / "checks/test_body_owned.py").exists() +@pytest.mark.parametrize("directory_link", [False, True], ids=["file-link", "directory-link"]) +def test_k2_body_turn_rejects_writes_to_linked_expectations(tmp_path, monkeypatch, directory_link): + data = "src/settings/rate.txt" + linked = "checks/expected/rate.txt" if directory_link else "checks/expected_rate.txt" + test_source = f"""\ +from pathlib import Path +from src.subject import rate + +def test_subject(): + actual = rate() + assert actual == int(Path({linked!r}).read_text()) +""" + application = """\ +from pathlib import Path + +def rate(): + current = int(Path(__file__).parent.joinpath('settings', 'rate.txt').read_text()) + if current < 8: + raise ValueError('outdated default rate') + return current +""" + + def edit(root, owner, scope): + assert owner == "body" + scopes.append((scope.allows(Path(SOURCE)), scope.allows(Path(data)))) + write(root, data, "8\n") + + scopes = [] + author = replace(ref("test", TEST), dependencies=("body",)) + fixture = fake(tmp_path, monkeypatch, [author, ref("body", SOURCE, data)], None, + files={TEST: test_source, SOURCE: application, data: "7\n"}, edit=edit) + if directory_link: + (fixture.root / linked).parent.symlink_to("../src/settings", target_is_directory=True) + else: + (fixture.root / linked).symlink_to("../" + data) + use_real_tests(fixture, monkeypatch) + [record] = fixture.drive(1)["rounds"] + [attempt] = record["attempts"] + assert (attempt["recipient"], attempt["decision"]) == ("body", "rejected") + assert attempt["reason"] == f"write outside declared outputs: {data}" + assert (fixture.root / data).read_text() == (fixture.root / linked).read_text() == "7\n" + assert scopes == [(True, False)] + assert [run["purpose"] for run in record["runs"]] == ["round 1 suite", "isolate"] + + +@pytest.mark.parametrize("change", ["none", "dependency", "output", "overlap", "legacy-claim"]) +def test_k3_resumed_claim_is_checked_against_current_tasks(tmp_path, monkeypatch, change): + tasks = [replace(ref("test", TEST), dependencies=("body",)), ref("body", SOURCE)] + + def outcomes(root, selected): + return {B: "passed" if revised(root, SOURCE) else "failed"}, {} + + def edit(root, owner, scope): + if owner == "test": + write(root, CLAIM, json.dumps({"case": B, "path": SOURCE, "reason": "source defect"})) + else: + write(root, SOURCE, "# revised\n") + + fixture = fake(tmp_path, monkeypatch, tasks, outcomes, edit=edit) + screen = engine._Feedback.screen + + def interrupt_before_body(self, *args, body=False, **kwargs): + if body: + raise KeyboardInterrupt + return screen(self, *args, body=body, **kwargs) + + with monkeypatch.context() as patch: + patch.setattr(engine._Feedback, "screen", interrupt_before_body) + with pytest.raises(KeyboardInterrupt): + fixture.drive(1) + + checkpoint = fixture.root / ".codd/review-session.json" + saved = json.loads(checkpoint.read_text()) + [record] = saved["test_feedback"]["rounds"] + assert [a["decision"] for a in record["attempts"]] == ["declined"] + assert [route["owner"] for route in record["claims"]] == ["body"] + if change == "dependency": + tasks[0] = replace(tasks[0], dependencies=()) + elif change == "output": + tasks[1] = ref("body", "src/other.py") + elif change == "overlap": + tasks.append(ref("other", SOURCE)) + elif change == "legacy-claim": + record["claims"][0].pop("paths", None) + checkpoint.write_text(json.dumps(saved)) + + [resumed] = fixture.drive(1, resume=True)["rounds"] + if change in ("none", "legacy-claim"): + assert [(a["owner"], a["decision"]) for a in resumed["attempts"]] == [ + ("test", "declined"), ("body", "accepted"), + ] + assert revised(fixture.root, SOURCE) + else: + assert [a["owner"] for a in resumed["attempts"]] == ["test"] + assert not revised(fixture.root, SOURCE) + + +def test_k4_body_progress_can_remove_one_of_two_failure_fingerprints(tmp_path, monkeypatch): + test_source = """\ +import pytest +from src import subject + +@pytest.fixture +def cleanup(): + yield + subject.clean() + +def test_subject(cleanup): + subject.run() +""" + application = """\ +def run(): + raise ValueError('call failure') + +def clean(): + raise RuntimeError('cleanup failure') +""" + + def edit(root, owner, scope): + assert owner == "body" + write(root, SOURCE, application.replace("raise ValueError('call failure')", "return")) + + author = replace(ref("test", TEST), dependencies=("body",)) + fixture = fake(tmp_path, monkeypatch, [author, ref("body", SOURCE)], None, + files={TEST: test_source, SOURCE: application}, edit=edit) + use_real_tests(fixture, monkeypatch) + [record] = fixture.drive(1)["rounds"] + [attempt] = record["attempts"] + baseline, candidate = [run for run in record["runs"] if "case" not in run] + assert len(baseline["fingerprints"][B]) == 2 + assert len(candidate["fingerprints"][B]) == 1 + assert set(candidate["fingerprints"][B]) < set(baseline["fingerprints"][B]) + assert (attempt["decision"], attempt["verdict"]) == ("accepted", "progressed") + assert (fixture.root / TEST).read_text() == test_source + assert "raise RuntimeError('cleanup failure')" in (fixture.root / SOURCE).read_text() + + def test_j3_file_writer_uses_json_despite_stale_stdout_and_usage_logging(project_factory, monkeypatch): pipeline, root, _ = setup_claim_project(project_factory, stale_stdout=True) monkeypatch.setenv("CODD_AI_USAGE_LOG", "usage/ai.jsonl") @@ -473,7 +669,7 @@ def outcomes(root, selected): @pytest.mark.parametrize("resume", [False, True]) -def test_y6_reuses_previous_rounds_final_suite(tmp_path, monkeypatch, resume): +def test_k1_reruns_suite_for_unchanged_tree_at_next_round_start(tmp_path, monkeypatch, resume): second_case = TEST + "::test_remaining" def outcomes(root, selected): @@ -489,13 +685,51 @@ def edit(root, owner, outputs): first, second = fixture.drive(2, resume=resume)["rounds"] assert first["attempts"][0]["decision"] == "accepted" assert second["attempts"][0]["decision"] == "rejected" - assert all(run["purpose"] != "round 2 suite" for run in second["runs"]) - assert second["reused_suites"][0]["from"].endswith("(candidate suite)") + assert [[run["purpose"] for run in record["runs"] if "case" not in run] for record in (first, second)] == [ + ["round 1 suite", "candidate suite"], ["round 2 suite", "candidate suite"], + ] + assert "reused_suites" not in second -def test_y6_reruns_when_the_final_suite_used_a_rejected_tree(tmp_path, monkeypatch): +def test_k1_reruns_suite_after_a_rejected_candidate(tmp_path, monkeypatch): fixture = fake(tmp_path, monkeypatch, [ref("test", TEST)], lambda *_: ({B: "failed"}, {})) first, second = fixture.drive(2)["rounds"] assert first["attempts"][0]["decision"] == "rejected" assert second["runs"][0]["purpose"] == "round 2 suite" assert "reused_suites" not in second + + +def test_k1_round_start_detects_changes_behind_environment_link(tmp_path, monkeypatch): + backing = tmp_path / "dependency-data" + + def provision(root): + link = root / RUNTIME + if not link.is_symlink(): + link.parent.mkdir() + link.symlink_to(backing) + backing.write_text("old") + else: + backing.write_text("new") + + def outcomes(root, selected): + cases = { + A: "passed" if revised(root, REPAIR) else "failed", + B: "failed", + C: "failed" if (root / RUNTIME).read_text() == "new" and not revised(root, THIRD) else "passed", + } + return ({selected: cases[selected]} if selected else cases), {} + + def edit(root, owner, scope): + if owner == "b": + raise RuntimeError("AI command did not produce any file changes") + [path] = scope.names + write(root, path, (root / path).read_text() + "\n# revised\n") + + fixture = fake(tmp_path, monkeypatch, [ref("a", REPAIR), ref("b", TEST), ref("c", THIRD)], + outcomes, provision=provision, edit=edit) + first, second = fixture.drive(2)["rounds"] + assert first["environment_before"] == second["environment_before"] + assert first["runs"][0]["cases"][C] == "passed" + assert second["runs"][0]["purpose"] == "round 2 suite" + assert second["runs"][0]["cases"][C] == "failed" + assert [(a["owner"], a["decision"]) for a in second["attempts"]] == [("b", "rejected"), ("c", "accepted")] diff --git a/tests/greenfield/test_implement_test_feedback_owner_scheduling.py b/tests/greenfield/test_implement_test_feedback_owner_scheduling.py index a85e0a5d..2c8c717a 100644 --- a/tests/greenfield/test_implement_test_feedback_owner_scheduling.py +++ b/tests/greenfield/test_implement_test_feedback_owner_scheduling.py @@ -81,8 +81,7 @@ def exhaust_first_round(self, record, purpose, case=None, timeout=None, **kwargs first, second = rounds assert first["isolation_time_exhausted"] and not first["stop"] assert first["attempts"] == [] - assert second["reused_suites"] == [{"purpose": "round 2 suite", "from": "round 1 run 1 (round 1 suite)"}] - assert second["runs"][0]["purpose"] == "isolate" + assert second["runs"][0]["purpose"] == "round 2 suite" assert [(attempt["owner"], attempt["decision"]) for attempt in second["attempts"]] == [ ("case", "accepted"), ] @@ -124,10 +123,6 @@ def interrupt(project_root, tasks, *args, **kwargs): with pytest.raises(KeyboardInterrupt): pipeline.run(root) - [interrupted_round] = feedback(root)["rounds"] - assert [(attempt["owner"], attempt["decision"]) for attempt in interrupted_round["attempts"]] == [ - ("a", "accepted"), ("b", "started"), - ] [record] = _run(pipeline, root, resume=True) assert [(attempt["owner"], attempt["decision"]) for attempt in record["attempts"]] == [ ("a", "accepted"), ("b", "rejected"), ("c", "accepted"), diff --git a/tests/greenfield/test_implement_test_feedback_unstable.py b/tests/greenfield/test_implement_test_feedback_unstable.py index e23f1ebc..ed4113ac 100644 --- a/tests/greenfield/test_implement_test_feedback_unstable.py +++ b/tests/greenfield/test_implement_test_feedback_unstable.py @@ -160,8 +160,6 @@ def outcomes(version, selected, count): observer = rounds[-1]["attempts"][-1] assert (observer["owner"], observer["decision"], observer["isolated_before"]) == ("observer", "accepted", 0) if already_handled: - assert rounds[1]["reused_suites"][0]["purpose"] == "round 2 suite" - assert rounds[1]["runs"][0]["purpose"] == "isolate" assert rounds[1]["runs"][0]["failures_and_errors"] == 0 diff --git a/tests/greenfield/test_implement_test_feedback_w21b_review.py b/tests/greenfield/test_implement_test_feedback_w21b_review.py index ff3671a1..c7bdec70 100644 --- a/tests/greenfield/test_implement_test_feedback_w21b_review.py +++ b/tests/greenfield/test_implement_test_feedback_w21b_review.py @@ -221,39 +221,23 @@ def provision(root): n_provisions += 1 write(root, RUNTIME, "new" if n_provisions > 1 else "old") - def outcomes(root, selected): - new_environment = (root / RUNTIME).read_text() == "new" - repaired = revised(root, REPAIR) - cases = { - A: "passed" if repaired else "failed", - B: "failed" if repaired and not selected and not new_environment else "passed", - C: "passed" if revised(root, THIRD) or new_environment else "failed", - } - return ({selected: cases[selected]} if selected else cases), {B: {"origin": THIRD}} - - case = fake(tmp_path, monkeypatch, [ref("repair", REPAIR), ref("observer", TEST), ref("third", THIRD)], - outcomes, provision=provision) - verdict = engine._Feedback.gate_problem - - def change_environment(self, record, target): - self.snapshot.restore(target) - if revised(case.root, THIRD): - write(case.root, RUNTIME, "changed during candidate checks") - return verdict(self, record, target) - - monkeypatch.setattr(engine._Feedback, "gate_problem", change_environment) + def edit(root, owner, scope): + if owner == "third": + write(root, RUNTIME, "changed by candidate") + else: + [name] = scope.names + write(root, name, (root / name).read_text() + "\n# revised\n") + + case = fake(tmp_path, monkeypatch, [ref("repair", HELPER), ref("observer", TEST), ref("third", THIRD)], + baseline_script(reprovision=True), edit=edit, provision=provision) state = case.drive(4) assert [(a, b) for a, b, _ in attempts(state)] == [("repair", "accepted"), ("third", "rejected")] assert "discarding and reprovisioning" in attempts(state)[1][2] assert [owner for owner, _ in case.prompts] == ["repair", "third"] and n_provisions == 2 [record] = state["rounds"] assert record["unstable_observations"][0]["case"] == B - assert record["unstable_observations"][0]["failed_in"].endswith("(candidate suite)") - [initial] = [run for run in record["runs"] if run["purpose"] == "round 1 suite"] - assert initial["cases"][B] == "passed" - [reprovisioned] = [run for run in record["runs"] if run["purpose"] == "suite after reprovisioning"] - assert reprovisioned["failures_and_errors"] == 0 - assert record["attempts"][0]["suite_after"] == 2 + assert record["runs"][-1]["purpose"] == "suite after reprovisioning" + assert record["runs"][-1]["failures_and_errors"] == 0 assert state["pending_unstable"] == {} and record["stop"]