From ebca3b8c3d61af56c31d6b7dccf054e8f4c095e0 Mon Sep 17 00:00:00 2001 From: yohey-w Date: Tue, 1 Dec 2026 15:06:18 +0900 Subject: [PATCH 1/4] 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/4] 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 c0f2fe16842c80f6471bb7fedf20778c27ad63eb Mon Sep 17 00:00:00 2001 From: yohey-w Date: Tue, 1 Dec 2026 16:22:42 +0900 Subject: [PATCH 3/4] 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 4/4] 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