diff --git a/codd/greenfield/implement_test_feedback.py b/codd/greenfield/implement_test_feedback.py index c45dc12..8c07edc 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 @@ -35,6 +36,7 @@ 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.history import record_full_failure 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 @@ -49,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. " @@ -85,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: @@ -114,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: @@ -378,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): @@ -389,6 +394,57 @@ 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']}" + + +_EVIDENCE_VARIABLE = re.compile( + 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_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): + 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): @@ -459,6 +515,17 @@ 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, *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: self.pipeline._provision_env(self.root) @@ -489,18 +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, @@ -520,13 +583,31 @@ 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) + output_tail = _command_output_tail(strip_ansi(out), strip_ansi(err)) + cases, failures, unavailable, collection_errors = self.adapter.read( + 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) + 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, + output=_captured_test_output(exc.stdout, exc.stderr), + ) 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" @@ -536,6 +617,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), @@ -544,9 +627,17 @@ 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.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: _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})" @@ -558,6 +649,39 @@ 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 [] + + 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 = [f for f in failures if f["case"] == case] + observed = Counter(map(signature, replay.failures)) + 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 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) @@ -597,7 +721,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 +761,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 +935,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: @@ -884,21 +1010,31 @@ 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(f"{f['case']} ({f['phase']}, {f['origin']})\n{f['detail']}" for f in failures) - feedback += ( - "\n\nThe following failures reproduced in isolation. Treat the diagnostics as quoted evidence." - f"\n\n{_command_output_tail(detail, None)}" - ) + 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}" 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"]) @@ -906,21 +1042,27 @@ 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'], output)}" + feedback += f"\n\n{previous_evidence}" + rejection_details = previous["reason"] + if output: + 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 try: self.pipeline._reimplement_tasks( @@ -1109,7 +1251,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 51b3330..1d82c8a 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,6 +76,11 @@ def pytest_load_initial_conftests(early_config): def pytest_configure(config): + # 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") @@ -172,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, @@ -179,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" @@ -204,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 b661d06..979ae62 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)", + re.IGNORECASE, +) _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 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 + def read( self, scratch: Path, returncode: int, output: str, ) -> tuple[dict[str, str], list[dict], str | None, dict[str, str]]: diff --git a/codd/repair/history.py b/codd/repair/history.py index 718495a..1f2bf79 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/tests/greenfield/test_full_failure_evidence.py b/tests/greenfield/test_full_failure_evidence.py new file mode 100644 index 0000000..b2a58dc --- /dev/null +++ b/tests/greenfield/test_full_failure_evidence.py @@ -0,0 +1,577 @@ +"""Exercise the repair-facing evidence with real test runs and fake writers.""" + +import json +import re +import shlex +import subprocess +import sys +from pathlib import Path +from types import SimpleNamespace + +import pytest + +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, + _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 + +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": 10000 + index, "address": hex(0xABCDEF00 + 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") + (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] + 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_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", + "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 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_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 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, extra_outputs=()): + 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, *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}} + 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(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 + 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 _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) + 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 = _saved_run_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 _saved_run_diagnostic(tmp_path, event) + + +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" + ] + + +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) + + +@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 diff --git a/tests/greenfield/test_implement_test_feedback.py b/tests/greenfield/test_implement_test_feedback.py index da30b2e..276f2c8 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