diff --git a/codd/greenfield/implement_test_feedback.py b/codd/greenfield/implement_test_feedback.py index 8c07edc..536faec 100644 --- a/codd/greenfield/implement_test_feedback.py +++ b/codd/greenfield/implement_test_feedback.py @@ -34,7 +34,7 @@ from codd.languages.contract import resolve_language_profile from codd.languages.registry import UnknownLanguageError, default_adapter_registry from codd.operational_e2e_audit import _COVER_MARKER_RE -from codd.path_safety import iter_project_glob +from codd.path_safety import iter_project_glob, project_relative_path from codd.reference_resolution import AUDIT_RELATIVE_PATH from codd.repair.history import record_full_failure from codd.repair.verify_runner import VerifyRunner, _command_output_tail @@ -49,6 +49,7 @@ _VERSION_CONTROL_METADATA = frozenset({".git", ".hg", ".svn", ".bzr", "_darcs"}) _MISSING_SELECTED_CASE = "the runner did not observe the selected case" _REGRESSION_REASON = "previously passing test now fails in isolation" +_COUNT_REASON = "owner's failures and errors did not decrease" _UNSTABLE_REASON = "unstable test still fails" _UNSTABLE_ASSERTIONS_REASON = "unstable test assertions changed" _STATE_ROOT = Path(".codd") @@ -398,6 +399,17 @@ def _case_failure_detail(failure: dict) -> str: return f"{failure['case']} ({failure['phase']}, {failure['origin']})\n{failure['detail']}" +def _failure_fingerprint(failure): + if "fingerprint" in failure: + return failure["fingerprint"] + shape = _evidence_line_shape(failure["detail"]) + return hashlib.sha256(json.dumps(shape).encode()).hexdigest() + + +def _failure_key(failure): + return failure["case"], failure["origin"], failure["phase"] + + _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)|" @@ -538,6 +550,8 @@ def prepare(self, round_record) -> str | None: self.display = self.command if isinstance(self.command, str) else shlex.join(self.command) try: self.target = self.snapshot.capture() + self.tasks_by_id = {task.task_id: task for task in self.tasks} + self.declared = {task.task_id: DeclaredOutputs(self.root, task.expected_outputs) for task in self.tasks} self.outputs = self.round_outputs() environment = self.snapshot.environment_fingerprint() if self.pending_unstable: @@ -625,6 +639,9 @@ def run_tests(self, round_record, purpose, case=None, timeout=None, *, target=No } if case: event["case"] = case + else: + event["cases"] = result.cases + event["fingerprints"] = self.fingerprints(result) if result.unavailable: event["unavailable"] = _command_output_tail(result.unavailable, None) if result.unavailable or (result.unreported_launch and result.output): @@ -649,6 +666,13 @@ def run_tests(self, round_record, purpose, case=None, timeout=None, *, target=No self.emit(summary) return result + @staticmethod + def fingerprints(suite): + by_case = defaultdict(list) + for failure in suite.failures: + by_case[failure["case"]].append(_failure_fingerprint(failure)) + return dict(by_case) + def replay_failure_details(self, round_record, failures) -> list[dict]: needs_replay = getattr(self.adapter, "needs_failure_replay", None) if needs_replay is None: @@ -706,6 +730,65 @@ def owner(self, failure) -> str | None: owners.add(matches[0]) return next(iter(owners)) if len(owners) == 1 else None + def body_owners(self, failure, paths): + file = failure["file"] + if not self.in_test_tree(file): + return set() + test_owners = [owner for owner, scope in self.declared.items() if scope.allows(Path(file))] + if len(test_owners) != 1: + return set() + dependencies = getattr(self.tasks_by_id[test_owners[0]], "dependencies", ()) + owners = set() + for path in paths: + absolute = Path(path) + if absolute.is_absolute(): + if not absolute.is_relative_to(self.root): + continue + absolute = absolute.relative_to(self.root) + if not absolute.parts or ".." in absolute.parts or self.in_test_tree(absolute.as_posix()): + continue + matches = [task_id for task_id, outputs in self.declared.items() if outputs.allows(absolute)] + if len(matches) == 1 and matches[0] in dependencies: + owners.add(matches[0]) + return owners + + def body_groups(self, suite, routes): + reported = defaultdict(set) + for route in routes: + reported[route["case"], route["fingerprint"]].add(route["owner"]) + by_case = defaultdict(list) + for failure in suite.failures: + origins = _failure_origins(failure) + case = failure["case"] + owners = self.body_owners(failure, origins) + if len(origins) > 1 and len(owners) == 1: + owners.clear() + owners.update(reported.get((case, _failure_fingerprint(failure)), ())) + by_case[case].append((failure, owners)) + grouped = defaultdict(list) + for reports in by_case.values(): + owners = set().union(*(owners for _, owners in reports)) + if len(owners) == 1: + grouped[next(iter(owners))].extend(failure for failure, owners in reports if owners) + return grouped + + def valid_routes(self, suite, routes): + if not routes: + return [] + failures = {(f["case"], _failure_fingerprint(f)): f for f in suite.failures} + valid = [] + for route in routes: + failure = failures.get((route["case"], route["fingerprint"])) + if failure is None: + continue + paths = route.get("paths", (*_failure_origins(failure), *failure.get("paths", ()))) + owners = self.body_owners(failure, paths) + if route["owner"] in owners: + # Preserve conflicting owners so the case still has to pass + # the uniqueness check across all of its failure reports. + valid.extend({**route, "owner": owner} for owner in sorted(owners)) + return valid + def owner_groups(self, suite): grouped = defaultdict(list) for failure in suite.failures: @@ -739,7 +822,7 @@ def unstable_groups(self) -> dict[str, dict[str, dict]]: grouped[owner][case] = observation return grouped - def screen(self, round_record, owner, suite, failures, limited) -> tuple[list[dict], str | None]: + def screen(self, round_record, owner, suite, failures, limited, *, body=False) -> tuple[list[dict], str | None]: screened = round_record["screened"] isolated_by_owner = round_record.setdefault("isolated_by_owner", {}) by_case = defaultdict(set) @@ -767,7 +850,14 @@ def screen(self, round_record, owner, suite, failures, limited) -> tuple[list[di [list(pair) for pair in sorted(signature)], [{**f, "detail": self.failure_excerpt(_case_failure_detail(f))} for f in reproduced], ] - reproduced_for_owner.extend(item for item in reproduced if self.owner(item) == owner) + if body and reproduced: + other_owners = set().union(*( + self.body_owners(failure, _failure_origins(failure)) for failure in isolated.failures + )) - {owner} + if not other_owners: + reproduced_for_owner.extend(isolated.failures) + elif not body: + reproduced_for_owner.extend(item for item in reproduced if self.owner(item) == owner) if isolated.cases.get(case) == "passed": if not isolated.unavailable: self.observe_unstable(round_record, case, isolated, suite) @@ -812,7 +902,7 @@ def integrity_problem(self, before, after, unstable_files: set[str]) -> str | No return f"skip/xfail increased in {rel}" return None - def count(self, suite, owner, cases, unstable) -> int: + def count(self, suite, owner, cases, unstable): return sum( f["case"] not in unstable and ( f["case"] in cases or self.owner(f) == owner @@ -821,9 +911,9 @@ def count(self, suite, owner, cases, unstable) -> int: for f in suite.failures ) - def change_problem(self, owner, before, after, unstable) -> str | None: + def change_problem(self, outputs, before, after, unstable) -> str | None: outside = [rel for rel, new in _writes(before, after).items() if not self.allowed_change( - Path(rel), self.outputs[owner], before.get(rel), new + Path(rel), outputs, before.get(rel), new )] if outside: return f"write outside declared outputs: {', '.join(sorted(outside))}" @@ -840,15 +930,12 @@ def change_problem(self, owner, before, after, unstable) -> str | None: unstable_files = {observation["file"] for observation in unstable.values()} return self.integrity_problem(before, after, unstable_files) - def assess(self, round_record, attempt, suite, failures, owner, before, target) -> tuple[str | None, _Suite]: + def gate_problem(self, round_record, target): from codd.greenfield.pipeline import _enforce_stage_coverage_gate - case_ids = list(dict.fromkeys(f["case"] for f in failures)) - returned_failures = {(f["case"], f["origin"], f["phase"]) for f in failures} - unstable = attempt.get("unstable_cases", {}) + self.snapshot.restore(target) + reason = None try: - # prepare() provisioned the round's environment before snapshotting - # it. Judge the candidate in that same environment. self.pipeline._enforce_implement_oracle_gate( self.root, self.tasks, self.options, verdict_only=True, reuse_test_environment=True, @@ -858,94 +945,157 @@ def assess(self, round_record, attempt, suite, failures, owner, before, target) authenticity_profile=self.pipeline._resolve_layout_profile(self.root), ) except StageError as exc: - return f"implement gate or coverage audit failed: {exc}", suite + reason = f"implement gate or coverage audit failed: {exc}" if self.snapshot.environment_changed(round_record["environment_before"]): self.environment_dirty = True - return "test environment changed during candidate checks", suite + return "test environment changed during candidate checks" + return reason + + def isolate(self, round_record, case, purpose, target, deadline): + exceeded = "candidate isolation exceeded the test time budget" + remaining = deadline - time.monotonic() + if remaining <= 0: + return None, exceeded + result = self.run_tests(round_record, purpose, case, remaining, target=target) + if result.timed_out: + return None, exceeded + if result.unavailable or result.cases[case] == "skipped": + return None, f"candidate could not verify {case}" + return result, None + + @staticmethod + def body_progress(suite, case, before): + status = suite.cases.get(case) + if status == "passed": + return "fixed" + after = {_failure_fingerprint(f) for f in suite.failures if f["case"] == case} + if status == "failed" and before and after and before != after: + return "progressed" + return None + + def assess(self, record, attempt, suite, failures, target, isolated_failures): + owner = attempt["owner"] + body = attempt["recipient"] == "body" + unstable = attempt.get("unstable_cases", {}) + before = self.target + keys = {_failure_key(f) for f in failures} + case_ids = list(dict.fromkeys(f["case"] for f in failures)) + attempt["before"] = self.count(suite, owner, case_ids, unstable) + attempt["suite_before"] = len(suite.failures) + attempt["isolated_before"] = len(failures) + if reason := self.gate_problem(record, target): + return reason, None, None - candidate = self.run_tests(round_record, "candidate suite", target=target) + candidate = self.run_tests(record, "candidate suite", target=target) attempt["after"] = self.count(candidate, owner, case_ids, unstable) attempt["suite_after"] = len(candidate.failures) if candidate.unavailable: - return "candidate suite could not complete", suite + return "candidate suite could not complete", candidate, None if candidate.collection_errors.keys() - suite.collection_errors.keys(): - return "candidate introduced collection errors", suite + return "candidate introduced collection errors", candidate, None for case in unstable: if candidate.cases.get(case) != "passed": - return f"{_UNSTABLE_REASON}: {case}", suite + return f"{_UNSTABLE_REASON}: {case}", candidate, None if list(candidate.cases.values()).count("skipped") > list(suite.cases.values()).count("skipped"): - return "runtime skip/xfail increased", suite - if failures and attempt["after"] >= attempt["before"]: - return "owner's failures and errors did not decrease", suite + return "runtime skip/xfail increased", candidate, None + if not body and failures and attempt["after"] >= attempt["before"]: + return _COUNT_REASON, candidate, None - regressions = [case for case, status in suite.cases.items() - if status == "passed" and candidate.cases.get(case) != "passed"] deadline = time.monotonic() + self.timeout - - def isolate(case, purpose, artifacts): - budget_exceeded = "candidate isolation exceeded the test time budget" - remaining = deadline - time.monotonic() - if remaining <= 0: - return None, budget_exceeded - result = self.run_tests(round_record, purpose, case, remaining, target=artifacts) - if result.timed_out: - return None, budget_exceeded - if result.unavailable or result.cases[case] == "skipped": - return None, f"candidate could not verify {case}" - return result, None - isolated_after = 0 + progress = [] for case in case_ids: - result, problem = isolate(case, "candidate isolate", target) + if body and suite.cases.get(case) != "failed": + return "returned failure no longer reproduces in the baseline suite", candidate, None + result, problem = self.isolate(record, case, "candidate isolate", target, deadline) if problem: - return problem, suite - isolated_after += sum( - (f["case"], f["origin"], f["phase"]) in returned_failures for f in result.failures - ) + return problem, candidate, None + isolated_failures.extend(result.failures) + if body: + for observed, original in ((candidate, suite.failures), (result, failures)): + fingerprints = {_failure_fingerprint(f) for f in original if f["case"] == case} + outcome = self.body_progress(observed, case, fingerprints) + if not outcome: + return f"failure fingerprint did not advance: {case}", candidate, None + progress.append(outcome) + else: + isolated_after += sum(_failure_key(f) in keys for f in result.failures) for case in unstable: for _ in range(_UNSTABLE_VERIFICATION_RUNS): - result, problem = isolate(case, "candidate unstable isolate", target) + result, problem = self.isolate(record, case, "candidate unstable isolate", target, deadline) if problem: - return problem, suite + return problem, candidate, None + isolated_failures.extend(result.failures) if result.cases[case] != "passed": - return f"{_UNSTABLE_REASON}: {case}", suite + return f"{_UNSTABLE_REASON}: {case}", candidate, None - for case in regressions: + reason, regression = self.regression(record, attempt, suite, candidate, before, target, deadline) + if reason: + return reason, candidate, regression + attempt["isolated_after"] = isolated_after + if not body and failures and isolated_after >= len(failures): + return "isolated failures and errors did not decrease", candidate, None + if body: + attempt["progress"] = "progressed" if "progressed" in progress else "fixed" + return None, candidate, None + + def regression(self, record, attempt, suite, candidate, before, target, deadline): + for case, status in suite.cases.items(): + if status != "passed" or candidate.cases.get(case) == "passed": + continue for _ in range(_CANDIDATE_REGRESSION_RUNS): - result, problem = isolate(case, "candidate isolate", target) + result, problem = self.isolate(record, case, "candidate isolate", target, deadline) if problem: - return problem, suite + return problem, None if result.cases[case] == "passed": break if result.cases[case] == "passed": continue - try: for passed in range(_BASELINE_REGRESSION_RUNS): - baseline, problem = isolate(case, "baseline isolate", before) + baseline, problem = self.isolate(record, case, "baseline isolate", before, deadline) if problem: - return problem, suite + return problem, None if baseline.cases[case] != "passed": attempt.setdefault("baseline_failures", []).append({ "case": case, "passed": passed, "failed": 1, }) - self.observe_unstable(round_record, case, suite, baseline) + self.observe_unstable(record, case, suite, baseline) break else: - path = Path(case.partition("::")[0]) - if not self.outputs[owner].allows(path): - attempt["rejection_output"] = self.failure_excerpt( - result.output or "\n\n".join(f["detail"] for f in result.failures), - ) - return f"{_REGRESSION_REASON}: {case}", suite + return f"{_REGRESSION_REASON}: {case}", result finally: self.snapshot.restore(target) - - attempt["isolated_after"] = isolated_after - if failures and isolated_after >= len(failures): - return "isolated failures and errors did not decrease", suite - return None, candidate + return None, None + + def reject(self, attempt, reason, candidate, *, suite, scope, regression, isolated_failures): + attempt.update(decision="rejected", reason=reason, verdict="gate rejected") + if candidate is not None: + cases = {f["case"] for f in attempt["returned_failures"]} | attempt.get("unstable_cases", {}).keys() + sections = defaultdict(dict) + for failure in (*candidate.failures, *isolated_failures): + if failure["case"] in cases: + sections[failure["case"]][_case_failure_detail(failure)] = None + if sections: + details = {case: "\n\n".join(lines) for case, lines in sections.items()} + detail = "\n\n".join(details.values()) + attempt["candidate_failure"] = self.failure_excerpt(detail) + attempt["candidate_failures_by_case"] = { + case: self.failure_excerpt(output) for case, output in details.items() + } + saved = record_full_failure(self.root, self.snapshot.archive.parent, detail) + if saved: + attempt["candidate_failure_path"] = saved[0].as_posix() + if self.record_stall(attempt, suite, candidate, isolated_failures) and reason == _COUNT_REASON: + attempt["verdict"] = "stalled" + elif reason.startswith("failure fingerprint did not advance"): + attempt["verdict"] = "stalled" + _, _, case = reason.partition(": ") + if regression is not None and not scope.allows(Path(case.partition("::")[0])): + attempt["rejection_output"] = self.failure_excerpt( + regression.output or "\n\n".join(f["detail"] for f in regression.failures), + ) def allowed_change(self, path, outputs, old, new) -> bool: if outputs.allows(path): @@ -957,14 +1107,16 @@ def allowed_change(self, path, outputs, old, new) -> bool: path in log.parents for log in self.logs ) # The shared implementation entry point appends its own diagnostics. + return self.diagnostic_append(path, old, new) + + def diagnostic_append(self, path, old, new): return ( path in self.logs and new is not None and stat.S_ISREG(new.mode) and (old is None or (old.mode == new.mode and new.data.startswith(old.data))) ) - def candidate_target(self, owner, after): + def candidate_target(self, outputs, after): kept = self.target.copy() - outputs = self.outputs[owner] for rel, new in sorted(_writes(self.target, after).items()): if not outputs.matches(Path(rel)): continue @@ -988,28 +1140,162 @@ def keep_outputs(self, round_record, kept): round_record["kept_attempt"] = index self.target = kept - def attempt(self, round_record, task, failures, suite, unstable): - owner = task.task_id + @staticmethod + def route(failure, owner, paths): + return {"case": failure["case"], "fingerprint": _failure_fingerprint(failure), + "owner": owner, "paths": sorted(set(paths))} + + def test_tree_paths(self, entries): + protected = dict.fromkeys(self.test_roots, True) + for root in self.test_roots: + try: + resolved = project_relative_path(self.root, root) + except RuntimeError: # A symlink loop on older Python versions. + continue + if resolved is not None: + protected[Path(resolved)] = True + # A linked directory can contain more links. Walk only links already + # inventoried in the project snapshot, once each. + links = {Path(rel) for rel, entry in entries.items() if stat.S_ISLNK(entry.mode)} + while reachable := {link for link in links if DeclaredOutputs._contains(link, protected)}: + links -= reachable + for link in reachable: + try: + resolved = project_relative_path(self.root, link) + except RuntimeError: # A symlink loop on older Python versions. + continue + if resolved is not None: + path = Path(resolved) + protected[path] = protected.get(path, False) or (self.root / path).is_dir() + return protected + + def scope(self, owner, protected): scope = self.outputs[owner] + if not protected: + return scope + narrowed = DeclaredOutputs(self.root, ()) + narrowed.paths = scope.paths.copy() + narrowed.excluded = scope.excluded.copy() + for path, directory in protected.items(): + narrowed.excluded[path] = directory or narrowed.excluded.get(path, False) + return narrowed + + def attempt(self, round_record, task, failures, suite, unstable, *, body=False): + owner = task.task_id before = self.target self.snapshot.restore(before) + protected = self.test_tree_paths(before) if body else {} + scope = self.scope(owner, protected) environment_before = round_record["environment_before"] case_ids = {f["case"] for f in failures} attempt = { - "owner": owner, "decision": "started", "before": self.count(suite, owner, case_ids, unstable), + "owner": owner, "recipient": "body" if body else "test", + "decision": "started", "before": self.count(suite, owner, case_ids, unstable), "after": None, "suite_before": len(suite.failures), "suite_after": None, "isolated_before": len(failures), "isolated_after": None, "environment_before": environment_before, + "returned_failures": [ + {**{key: value for key, value in failure.items() if key != "detail"}, + "fingerprint": _failure_fingerprint(failure)} for failure in failures + ], } if unstable: attempt["unstable_cases"] = unstable round_record["attempts"].append(attempt) + index = len(round_record["attempts"]) previous_target = _round_archive(self.snapshot, round_record, round_record.get("kept_attempt", 0)) + claim_file = self.snapshot.archive.parent / "claims" / f"{round_record['number']}-{index}.json" + if not body: + claim_file.parent.mkdir(parents=True, exist_ok=True) + claim_file.unlink(missing_ok=True) returning = f"returning {len(failures)} reproducible failure(s)/error(s)" if unstable: returning += f" and {len(unstable)} unstable test(s)" self.emit(f"{returning} to {owner}") + feedback = self.attempt_feedback(round_record, attempt, failures, unstable, claim_file) + reason = None + no_output = False + claim = None + candidate = regression = None + isolated_failures = [] + try: + self.pipeline._reimplement_tasks( + self.root, [task], feedback, self.config, feedback_output_paths=scope, + ) + except Exception as exc: + reason = f"could not evaluate the candidate: {exc}" + no_output = not str(exc).startswith("AI command failed:") and any(marker in str(exc) for marker in ( + "AI command did not produce any file changes", "empty output", "no file change proposed:", + )) + self.environment_dirty = self.snapshot.environment_changed(environment_before) + if not self.environment_dirty and (reason is None or not body and no_output): + try: + proposed = self.snapshot.capture() + if not body and self.only_log_appends(before, proposed): + claim = self.read_claim(claim_file, case_ids) + if reason is None and claim is None: + reason = self.change_problem(scope, before, proposed, unstable) + if reason is None and body and self.test_tree_paths(proposed) != protected: + reason = "test-tree symbolic link targets changed" + if reason is None: + target = self.candidate_target(scope, proposed) + reason, candidate, regression = self.assess( + round_record, attempt, suite, failures, target, isolated_failures, + ) + except Exception as exc: + reason = f"could not evaluate the candidate: {exc}" + dirty = self.environment_dirty or self.snapshot.environment_changed(environment_before) + if dirty: + self.environment_dirty = True + reason = ( + "test environment changed during the task rerun or candidate checks; " + "discarding and reprovisioning it" + ) + if reason is None and claim is None: + try: + self.keep_outputs(round_record, target) + except (OSError, ValueError) as exc: + reason = f"could not keep the candidate: {exc}" + if claim is not None and not dirty: + self.record_claim(round_record, attempt, suite, claim) + elif reason is not None: + self.reject(attempt, reason, candidate if not dirty else None, suite=suite, scope=scope, + regression=regression, isolated_failures=isolated_failures) + else: + self.record_stall(attempt, suite, candidate, isolated_failures) + verdict = "fixed" + accepted = "failures decreased" if failures else "unstable tests passed the suite and isolated checks" + if body: + verdict = attempt["progress"] + accepted = "returned tests passed" if verdict == "fixed" else "failure fingerprint advanced" + attempt.update(decision="accepted", reason=accepted, verdict=verdict) + round_record["screened"].clear() + suite = candidate + self.snapshot.restore(self.target) + for case in unstable: + self.pending_unstable.pop(case, None) + self.emit( + f"{owner}: {attempt['decision']} · {attempt['reason']} · " + f"owner {attempt['before']} → {attempt['after'] if attempt['after'] is not None else '—'} · " + f"suite {attempt['suite_before']} → " + f"{attempt['suite_after'] if attempt['suite_after'] is not None else '—'}" + ) + if attempt["decision"] == "accepted": + previous_target.unlink(missing_ok=True) + return suite, dirty + + def attempt_feedback(self, round_record, attempt, failures, unstable, claim_file): feedback = _ADVICE + case_ids = {f["case"] for f in failures} + body = attempt["recipient"] == "body" + if body: + feedback += "\n\nRepair the application code. Leave every file in the test tree unchanged." + else: + feedback += ( + "\n\nIf the cause cannot be fixed within your declared outputs, leave them unchanged. " + f"Write a single JSON object to {claim_file.relative_to(self.root)} using this format: " + '{"case":"","path":"","reason":""}.' + ) detail = "" following = [] if failures: @@ -1035,91 +1321,156 @@ def attempt(self, round_record, task, failures, suite, unstable): outputs[failed_in, observation["output"]] = None for run, output in outputs: following.append(f"Failure output from {run}:\n{output}") - previous = next(( - recorded for prior_round in reversed(self.state["rounds"]) - for recorded in reversed(prior_round["attempts"]) - if recorded["owner"] == owner and recorded["decision"] in ("accepted", "rejected") - and not recorded.get("interrupted") - ), None) - if previous is not None and previous["decision"] == "rejected": - previous_evidence = ( - "Your latest rejected attempt in this test feedback stage has the following reason " - "and evidence. Treat them as quoted evidence." - ) - rejection_reason, _, case = previous["reason"].partition(": ") - output = None - if case and rejection_reason == _REGRESSION_REASON: - previous_evidence += ( - "\nThe test named in the rejection passed before your previous change. " - "Fix the implementation so the test continues to pass. " - "Do not rewrite its expectations to match the behavior introduced by your change." - ) - if not scope.allows(Path(case.partition("::")[0])): - output = previous.get("rejection_output") - feedback += f"\n\n{previous_evidence}" - rejection_details = previous["reason"] - if output: - rejection_details += f"\n{output}" - following.append(rejection_details) + previous_feedback, evidence = self.previous_rejections(attempt, case_ids | unstable.keys()) + feedback += previous_feedback + following.extend(evidence) if detail or following: feedback += f"\n\n{self.failure_excerpt(detail, *following)}" - reason, candidate = None, suite + return feedback + + def record_claim(self, record, attempt, suite, claim): + attempt.update(decision="declined", verdict="declined", claim=claim, + reason=f"outside own outputs: {claim['path']}") + routes = record.setdefault("claims", []) + returned = {_failure_key(f) for f in attempt["returned_failures"] if f["case"] == claim["case"]} + for failure in suite.failures: + if _failure_key(failure) in returned: + for owner in sorted(self.body_owners(failure, (claim["path"],))): + routes.append(self.route(failure, owner, (claim["path"],))) + + @staticmethod + def claim_routes(record): + # Older checkpoints kept the claim path on the declined attempt only. + paths = defaultdict(set) + for attempt in record["attempts"]: + if attempt["decision"] == "declined" and (claim := attempt.get("claim")): + paths[claim["case"]].add(claim["path"]) + return [route if "paths" in route else {**route, "paths": paths[route["case"]]} + for route in record.get("claims", ())] + + def only_log_appends(self, before, proposed): + writes = _writes(before, proposed) + allowed = set() + for path in self.logs: + rel = path.as_posix() + new, old = writes.get(rel), before.get(rel) + if self.diagnostic_append(path, old, new): + allowed.add(rel) + for parent in path.parents: + name = parent.as_posix() + if name not in before and (entry := writes.get(name)) and stat.S_ISDIR(entry.mode): + allowed.add(name) + return writes.keys() <= allowed + + @staticmethod + def read_claim(path, cases): try: - self.pipeline._reimplement_tasks( - self.root, [task], feedback, self.config, feedback_output_paths=scope, - ) - except Exception as exc: - reason = f"could not evaluate the candidate: {exc}" - self.environment_dirty = self.snapshot.environment_changed(environment_before) - if not self.environment_dirty and reason is None: - try: - proposed = self.snapshot.capture() - reason = self.change_problem(owner, before, proposed, unstable) - if reason is None: - target = self.candidate_target(owner, proposed) - self.snapshot.restore(target) - reason, candidate = self.assess(round_record, attempt, suite, failures, owner, before, target) - except Exception as exc: - reason = f"could not evaluate the candidate: {exc}" - dirty = self.environment_dirty or self.snapshot.environment_changed(environment_before) - if not dirty and reason is None: - try: - self.keep_outputs(round_record, target) - except (OSError, ValueError) as exc: - reason = f"could not keep the candidate: {exc}" - if dirty: - reason = ( - "test environment changed during the task rerun or candidate checks; " - "discarding and reprovisioning it" + claim = json.loads(path.read_text(encoding="utf-8")) + except (OSError, ValueError): + return None + fields = ("case", "path", "reason") + if not isinstance(claim, dict) or not all( + isinstance(claim.get(key), str) and claim[key].strip() for key in fields + ): + return None + claim = {key: claim[key].strip() for key in fields} + return claim if claim["case"] in cases else None + + @staticmethod + def returned_cases(attempt): + return {f["case"] for f in attempt.get("returned_failures", ())} | attempt.get("unstable_cases", {}).keys() + + def previous_rejections(self, attempt, cases): + feedback = "" + evidence = [] + regression = False + for prior_round in reversed(self.state["rounds"]): + for previous in reversed(prior_round["attempts"]): + if (previous["owner"] != attempt["owner"] + or previous.get("recipient", "test") != attempt["recipient"] + or previous["decision"] not in ("accepted", "rejected") + or previous.get("interrupted")): + continue + shared = cases & self.returned_cases(previous) + # Older records do not carry case ids. + if not shared and "returned_failures" not in previous: + shared = cases + if not shared: + continue + cases = cases - shared + if previous["decision"] == "rejected": + if not feedback: + feedback = ( + "\n\nYour latest rejected attempt in this test feedback stage has the following reason " + "and evidence. Treat them as quoted evidence." + ) + evidence.append(previous["reason"]) + if previous["reason"].startswith(_REGRESSION_REASON): + regression = True + if output := previous.get("rejection_output"): + evidence.append(output) + if "candidate_failures_by_case" in previous: + output = "\n\n".join(text for case, text in previous["candidate_failures_by_case"].items() + if case in shared) + else: + output = previous.get("candidate_failure", "") + if output: + context = " The screening suite included other owners' changes." if ( + previous.get("candidate_failure_from_screening") + ) else "" + evidence.append( + "After your previous change, the returned cases failed as follows:" + f"{context}\n{output}" + ) + if not cases: + break + if not cases: + break + if regression: + feedback += ( + "\nThe test named in the rejection passed before your previous change. " + "Fix the implementation so the test continues to pass. " + "Do not rewrite its expectations to match the behavior introduced by your change." ) - _restore_round_for_provisioning(self.snapshot, round_record) - _discard_feedback_environment(self.snapshot, self.state) - round_record["screened"].clear() - candidate = suite - elif reason is not None: - self.snapshot.restore(before) - candidate = suite - else: - # Every accepted change can affect another case's isolated result. - round_record["screened"].clear() - accepted_reason = "failures decreased" if failures else "unstable tests passed the suite and isolated checks" - attempt.update(decision="rejected" if reason else "accepted", reason=reason or accepted_reason) - for case in unstable: - self.pending_unstable.pop(case, None) - if dirty: - self.pipeline._checkpoint(self.root) - candidate.unavailable = self.prepare(round_record) - self.emit( - f"{owner}: {attempt['decision']} · {attempt['reason']} · " - f"owner {attempt['before']} → {attempt['after'] if attempt['after'] is not None else '—'} · " - f"suite {attempt['suite_before']} → {attempt['suite_after'] if attempt['suite_after'] is not None else '—'}" - ) - if reason is None: - previous_target.unlink(missing_ok=True) - return candidate, dirty + return feedback, evidence + + def record_stall(self, attempt, suite, candidate, isolated_failures): + if attempt["recipient"] != "test" or candidate.unavailable: + return False + def signature(failure): + return _failure_key(failure), _failure_fingerprint(failure) + + returned = {signature(f) for f in attempt["returned_failures"]} + keys = {key for key, _ in returned} + baseline = [f for f in suite.failures if _failure_key(f) in keys] + baseline_signatures = {signature(f) for f in baseline} + stalled = [f for f in candidate.failures if signature(f) in baseline_signatures] + stalled.extend(f for f in isolated_failures if signature(f) in returned) + paths_by_case = defaultdict(set) + for failure in stalled: + paths_by_case[failure["case"]].update((*_failure_origins(failure), *failure.get("paths", ()))) + stalled_keys = {_failure_key(failure) for failure in stalled} + routes = [] + for failure in baseline: + if _failure_key(failure) in stalled_keys: + paths = paths_by_case[failure["case"]] + for owner in sorted(self.body_owners(failure, paths)): + route = self.route(failure, owner, paths) + if route not in routes: + routes.append(route) + if routes: + attempt["stalled_routes"] = routes + return bool(stalled) + + def reprovision(self, record): + _restore_round_for_provisioning(self.snapshot, record) + _discard_feedback_environment(self.snapshot, self.state) + self.environment_dirty = False + record["screened"].clear() + problem = self.prepare(record) + return _Suite(unavailable=problem) if problem else self.run_tests(record, "suite after reprovisioning") def run(self, rounds: int) -> None: - tasks = {task.task_id: task for task in self.tasks} for index in range(rounds): if index == len(self.state["rounds"]): self.state["rounds"].append({ @@ -1127,83 +1478,117 @@ def run(self, rounds: int) -> None: "isolated_seconds": 0.0, "passed_in_isolation": 0, "over_isolation_budget": 0, "screened": {}, }) - round_record = self.state["rounds"][index] - if round_record.get("done"): - if round_record["stop"]: + record = self.state["rounds"][index] + if record.get("done"): + if record["stop"]: break continue - problem = self.prepare(round_record) - suite = _Suite(unavailable=problem) if problem else self.run_tests(round_record, f"round {index + 1} suite") - handled = {attempt["owner"] for attempt in round_record["attempts"] if not attempt.get("interrupted")} - # Interrupted work stays ineligible for ordinary failure feedback. - # Pending unstable observations can still be returned on resume. - interrupted = { - attempt["owner"] for recorded in self.state["rounds"] - for attempt in recorded["attempts"] if attempt.get("interrupted") - } - limited = set(round_record.get("cases_outside_isolation_budget", ())) + prior_routes = [ + route for attempt in self.state["rounds"][index - 1]["attempts"] + if not attempt.get("candidate_failure_from_screening") + for route in attempt.get("stalled_routes", ()) + ] if index else [] + problem = self.prepare(record) + suite = _Suite(unavailable=problem) if problem else self.run_tests( + record, f"round {index + 1} suite", + ) + handled = {(a["owner"], a.get("recipient", "test")) for a in record["attempts"] + if not a.get("interrupted")} + interrupted = {a["owner"] for r in self.state["rounds"] for a in r["attempts"] if a.get("interrupted")} + body_attempted = defaultdict(set) + for attempt in record["attempts"]: + if attempt.get("recipient") == "body": + body_attempted[attempt["owner"]].update(self.returned_cases(attempt)) + limited = set(record.get("cases_outside_isolation_budget", ())) unreproduced = set() isolation_problem = None while not suite.unavailable: - pending = { - owner: failures for owner, failures in self.owner_groups(suite) - if owner not in handled and owner not in interrupted and owner not in unreproduced - } - for owner in sorted(self.unstable_groups().keys() - handled): - pending.setdefault(owner, []) + claims = self.valid_routes(suite, self.claim_routes(record)) + body_groups = self.body_groups(suite, [*self.valid_routes(suite, prior_routes), *claims]) + redirected = {_failure_key(f) for failures in body_groups.values() for f in failures} + claimed_cases = {(claim["owner"], claim["case"], claim["fingerprint"]) for claim in claims} + claimed_body, other_body = {}, {} + for owner, failures in sorted(body_groups.items()): + if owner in interrupted: + continue + claimed = [f for f in failures if ( + (owner, f["case"], _failure_fingerprint(f)) in claimed_cases + and f["case"] not in body_attempted[owner] + )] + if claimed: + claimed_body[owner, "body"] = claimed + elif (owner, "body") not in handled: + other_body[owner, "body"] = failures + pending = dict(claimed_body) + pending.update({ + (owner, "test"): [f for f in failures if _failure_key(f) not in redirected] + for owner, failures in self.owner_groups(suite) if owner not in interrupted + and any(_failure_key(f) not in redirected for f in failures) + }) + for owner in sorted(self.unstable_groups()): + if (owner, "test") not in handled: + pending.setdefault((owner, "test"), []) + pending.update(other_body) + pending = {key: failures for key, failures in pending.items() + if (key not in handled or key in claimed_body) and key not in unreproduced} if not pending: break - owner = next(iter(pending)) - failures, isolation_problem = self.screen(round_record, owner, suite, pending[owner], limited) - time_exhausted = round_record["isolated_seconds"] >= self.timeout - if time_exhausted: - limited.update(f["case"] for other, owned in pending.items() if other != owner for f in owned) - round_record["over_isolation_budget"] = len(limited) - if limited: - round_record["cases_outside_isolation_budget"] = sorted(limited) + + (owner, recipient), owned = next(iter(pending.items())) + body = recipient == "body" + failures, isolation_problem = self.screen(record, owner, suite, owned, limited, body=body) + time_exhausted = record["isolated_seconds"] >= self.timeout if time_exhausted: - round_record["isolation_time_exhausted"] = True + limited.update(f["case"] for key, group in pending.items() if key != (owner, recipient) for f in group) + record["isolation_time_exhausted"] = True self.emit("isolation time budget exhausted") if isolation_problem: break - owned_unstable = self.unstable_groups().get(owner, {}) - unstable = dict(list(owned_unstable.items())[:_MAX_ISOLATED_CASES]) - failures = [failure for failure in failures if failure["case"] not in owned_unstable] + own_observations = {} if body else self.unstable_groups().get(owner, {}) + unstable = dict(list(own_observations.items())[:_MAX_ISOLATED_CASES]) + failures = [failure for failure in failures if failure["case"] not in own_observations] if failures or unstable: - handled.add(owner) - suite, reprovisioned = self.attempt(round_record, tasks[owner], failures, suite, unstable) - if reprovisioned or round_record["attempts"][-1]["decision"] == "accepted": + handled.add((owner, recipient)) + if body: + body_attempted[owner].update(failure["case"] for failure in failures) + args = (record, self.tasks_by_id[owner], failures, suite, unstable) + suite, dirty = self.attempt(*args, body=True) if body else self.attempt(*args) + if dirty or record["attempts"][-1]["decision"] == "accepted": unreproduced.clear() - if not suite.unavailable and (reprovisioned or self.has_helper(failures)): - round_record["screened"].clear() - purpose = "suite after reprovisioning" if reprovisioned else "suite after helper decision" - suite = self.run_tests(round_record, purpose) + if dirty: + suite = self.reprovision(record) + elif not body and self.has_helper(failures): + record["screened"].clear() + suite = self.run_tests(record, "suite after helper decision") else: - unreproduced.add(owner) + unreproduced.add((owner, recipient)) if time_exhausted: break - # A clean suite can still leave evidence for an owner already handled this round. + routes = [route for attempt in record["attempts"] for route in attempt.get("stalled_routes", ())] stop = bool(suite.unavailable) or not ( self.unstable_groups() or any(owner not in interrupted for owner, _ in self.owner_groups(suite)) + or any(owner not in interrupted for owner in self.body_groups(suite, self.valid_routes(suite, routes))) ) + record["over_isolation_budget"] = len(limited) if limited: + record["cases_outside_isolation_budget"] = sorted(limited) self.emit(f"{len(limited)} failing case(s) left outside the isolation budget") - if round_record.get("baseline_saved"): + if record.get("baseline_saved"): self.snapshot.restore(self.target) if self.environment_dirty: _discard_feedback_environment(self.snapshot, self.state) self.emit("test environment changed; discarded before the next run") - round_record.update(done=True, stop=stop) + record.update(done=True, stop=stop) problem = suite.unavailable or isolation_problem if problem: - round_record["skipped"] = _command_output_tail(problem, None) - self.emit(f"round {index + 1} skipped · {round_record['skipped']}") + record["skipped"] = _command_output_tail(problem, None) + self.emit(f"round {index + 1} skipped · {record['skipped']}") self.emit( f"round {index + 1}: {len(suite.failures)} failure(s)/error(s) remain · " - f"{round_record['passed_in_isolation']} passed in isolation" + f"{record['passed_in_isolation']} passed in isolation" ) - for attempt_index in range(len(round_record["attempts"]) + 1): - _round_archive(self.snapshot, round_record, attempt_index).unlink(missing_ok=True) + for attempt_index in range(len(record["attempts"]) + 1): + _round_archive(self.snapshot, record, attempt_index).unlink(missing_ok=True) if stop: break diff --git a/tests/greenfield/test_implement_test_feedback_batch.py b/tests/greenfield/test_implement_test_feedback_batch.py new file mode 100644 index 0000000..b973751 --- /dev/null +++ b/tests/greenfield/test_implement_test_feedback_batch.py @@ -0,0 +1,735 @@ +"""Sequential candidate judgments and handoff to source owners.""" + +import json +import os +import subprocess +import sys +from dataclasses import replace +from pathlib import Path + +import pytest + +from codd import ai_invoke +from codd.greenfield import implement_test_feedback as engine + +from .test_implement_test_feedback import APP, TEST_FILE, feedback, project_factory +from .test_implement_test_feedback_w21b_review import ( + A, B, C, HELPER, REPAIR, RUNTIME, SOURCE, TEST, THIRD, attempts, baseline_script, fake, ref, revised, + write, +) + + +REGRESSION = TEST + "::test_passing" +CLAIM = ".codd/implement-test-feedback/claims/1-1.json" + + +def three_owners(tmp_path, monkeypatch, *, fixed=None, regression=None, regression_case=REGRESSION, + skip_after_removal=False): + fixed = fixed or (lambda a, b, c: (a, b, c)) + + def outcomes(root, selected): + a, b, c = (revised(root, name) for name in (REPAIR, TEST, THIRD)) + fixed_a, fixed_b, fixed_c = fixed(a, b, c) + cases = { + A: "passed" if fixed_a else "failed", + B: "passed" if fixed_b else "failed", + C: "passed" if fixed_c else "failed", + regression_case: "failed" if regression and regression(a, b) else "passed", + } + if skip_after_removal: + cases[B + "_runtime"] = "skipped" if b and not a and not selected else "passed" + return ({selected: cases[selected]} if selected else cases), {} + + return fake(tmp_path, monkeypatch, [ + ref("a", REPAIR), ref("b", TEST), ref("c", THIRD), + ], outcomes) + + +def test_each_owner_is_judged_before_the_next_owner_edits(tmp_path, monkeypatch): + fixture = three_owners(tmp_path, monkeypatch, fixed=lambda a, b, c: (False, b, False)) + [record] = fixture.drive(1)["rounds"] + assert [owner for owner, _ in fixture.prompts] == ["a", "b", "c"] + assert [(run["purpose"], run["failures_and_errors"]) + for run in record["runs"] if "case" not in run] == [ + ("round 1 suite", 3), ("candidate suite", 3), ("candidate suite", 2), ("candidate suite", 2), + ] + timeline = [message.removeprefix("[implement test feedback] ") for message in fixture.messages] + assert [message.split(":", 1)[0].split(" to ")[-1] for message in timeline + if message.startswith("returning ") or message.startswith("candidate suite: fake-runner")] == [ + "a", "candidate suite", "b", "candidate suite", "c", "candidate suite", + ] + assert [attempt["decision"] for attempt in record["attempts"]] == ["rejected", "accepted", "rejected"] + assert [revised(fixture.root, name) for name in (REPAIR, TEST, THIRD)] == [False, True, False] + + +def test_suite_order_includes_the_helper_recheck(tmp_path, monkeypatch): + fixture = fake(tmp_path, monkeypatch, [ref("repair", HELPER), ref("observer", TEST)], baseline_script()) + [record] = fixture.drive(1)["rounds"] + assert [run["purpose"] for run in record["runs"] if "case" not in run] == [ + "round 1 suite", "candidate suite", "suite after helper decision", "candidate suite", + ] + assert [item["decision"] for item in record["attempts"]] == ["accepted", "accepted"] + + +def test_candidate_suite_does_not_count_a_new_failure_phase_as_a_fix(tmp_path, monkeypatch): + def outcomes(root, selected): + return {B: "failed"}, {B: {"phase": "teardown" if revised(root, TEST) else "call"}} + + fixture = fake(tmp_path, monkeypatch, [ref("test", TEST)], outcomes) + [record] = fixture.drive(1)["rounds"] + assert record["attempts"][0]["decision"] == "rejected" + assert [run["purpose"] for run in record["runs"] if "case" not in run] == [ + "round 1 suite", "candidate suite", + ] + + +@pytest.mark.parametrize("masked", ["unchanged failure", "regression"]) +def test_y2_individual_suite_exposes_what_another_owner_masks(tmp_path, monkeypatch, masked): + if masked == "unchanged failure": + fixture = three_owners(tmp_path, monkeypatch, fixed=lambda a, b, c: (b, b, c)) + reason = "owner's failures and errors did not decrease" + else: + fixture = three_owners(tmp_path, monkeypatch, regression=lambda a, b: a and not b) + reason = f"previously passing test now fails in isolation: {REGRESSION}" + [record] = fixture.drive(1)["rounds"] + assert [revised(fixture.root, name) for name in (REPAIR, TEST, THIRD)] == [False, True, True] + first, second, third = record["attempts"] + assert first["decision"] == "rejected" and first["reason"] == reason + assert [second["decision"], third["decision"]] == ["accepted", "accepted"] + assert first["suite_after"] == 3 + + +def test_individual_suite_detects_skip_hidden_while_another_candidate_is_present(tmp_path, monkeypatch): + fixture = three_owners(tmp_path, monkeypatch, regression=lambda a, b: a, skip_after_removal=True) + state = fixture.drive(1) + assert [revised(fixture.root, name) for name in (REPAIR, TEST, THIRD)] == [False, False, True] + assert attempts(state) == [ + ("a", "rejected", f"previously passing test now fails in isolation: {REGRESSION}"), + ("b", "rejected", "runtime skip/xfail increased"), + ("c", "accepted", "failures decreased"), + ] + + +@pytest.mark.parametrize("interaction", [False, True]) +def test_individual_suites_compare_against_only_the_earlier_accepted_changes(tmp_path, monkeypatch, interaction): + regression_case = "checks/test_existing.py::test_passing" + + def regression(a, b): + return a and b if interaction else a or b + + fixture = three_owners(tmp_path, monkeypatch, regression=regression, regression_case=regression_case) + [record] = fixture.drive(1)["rounds"] + assert [revised(fixture.root, name) for name in (REPAIR, TEST, THIRD)] == [interaction, False, True] + assert [a["owner"] for a in record["attempts"] if a["reason"].endswith(regression_case)] == ( + ["b"] if interaction else ["a", "b"] + ) + assert sum(run["purpose"] == "candidate suite" for run in record["runs"]) == 3 + + +def test_earlier_candidate_can_expose_instability_for_the_same_round(tmp_path, monkeypatch): + def outcomes(root, selected): + a, b = (revised(root, name) for name in (REPAIR, TEST)) + cases = {A: "passed" if a else "failed", B: "failed" if a and not b and not selected else "passed"} + return ({selected: cases[selected]} if selected else cases), {} + + fixture = fake(tmp_path, monkeypatch, [ref("a", REPAIR), ref("b", TEST)], outcomes) + [record] = fixture.drive(1)["rounds"] + first, attempt = record["attempts"] + assert (first["owner"], first["decision"]) == ("a", "accepted") + assert (attempt["owner"], attempt["decision"]) == ("b", "accepted") + assert list(attempt["unstable_cases"]) == [B] + assert sum(run["purpose"] == "candidate unstable isolate" for run in record["runs"]) == 3 + + +@pytest.mark.parametrize("interrupted", ["a", "b"]) +def test_resume_discards_the_interrupted_candidate_and_keeps_earlier_acceptances(tmp_path, monkeypatch, interrupted): + fixture = three_owners(tmp_path, monkeypatch) + run_tests = engine._Feedback.run_tests + + def interrupt(self, record, purpose, case=None, timeout=None, *, target=None): + if purpose == "candidate suite" and record["attempts"][-1]["owner"] == interrupted: + self.snapshot.restore(target) + raise KeyboardInterrupt + return run_tests(self, record, purpose, case, timeout, target=target) + + with monkeypatch.context() as patch: + patch.setattr(engine._Feedback, "run_tests", interrupt) + with pytest.raises(KeyboardInterrupt): + fixture.drive(1) + [unfinished] = fixture.record["test_feedback"]["rounds"] + assert [(a["owner"], a["decision"]) for a in unfinished["attempts"]] == ( + [("a", "started")] if interrupted == "a" else [("a", "accepted"), ("b", "started")] + ) + [record] = fixture.drive(1, resume=True)["rounds"] + assert [a["decision"] for a in record["attempts"]] == [ + "rejected" if owner == interrupted else "accepted" for owner in ("a", "b", "c") + ] + assert [revised(fixture.root, name) for name in (REPAIR, TEST, THIRD)] == [ + interrupted != "a", interrupted != "b", True, + ] + assert [owner for owner, _ in fixture.prompts] == ["a", "b", "c"] + assert not list((fixture.root / engine.STATE_DIRECTORY).glob("pending-*.zip")) + + +def test_reprovisioning_preserves_earlier_accepted_output(tmp_path, monkeypatch): + provisions = 0 + + def provision(root): + nonlocal provisions + provisions += 1 + write(root, RUNTIME, "old environment" if provisions == 1 else "new environment") + + def outcomes(root, selected): + new_environment = (root / RUNTIME).read_text() == "new environment" + cases = { + A: "passed" if revised(root, REPAIR) or (selected == A and new_environment) else "failed", + B: "passed" if new_environment else "failed", + } + return ({selected: cases[selected]} if selected else cases), {} + + def edit(root, owner, scope): + if owner == "b": + write(root, RUNTIME, "environment changed by the candidate") + else: + write(root, REPAIR, (root / REPAIR).read_text() + "# revised\n") + + fixture = fake(tmp_path, monkeypatch, [ref("a", REPAIR), ref("b", TEST)], outcomes, + edit=edit, provision=provision) + state = fixture.drive(1) + first, second = state["rounds"][0]["attempts"] + assert first["decision"] == "accepted" + assert "discarding and reprovisioning" in second["reason"] + assert provisions == 2 and revised(fixture.root, REPAIR) + + +def test_reprovisioning_discards_instability_first_seen_in_candidate_suite(tmp_path, monkeypatch): + n_provisions = 0 + + def provision(root): + nonlocal n_provisions + n_provisions += 1 + write(root, RUNTIME, "new" if n_provisions > 1 else "old") + + def outcomes(root, selected): + new_environment = (root / RUNTIME).read_text() == "new" + repaired = revised(root, REPAIR) + cases = { + A: "passed" if repaired else "failed", + B: "failed" if repaired and not selected and not new_environment else "passed", + C: "passed" if revised(root, THIRD) or new_environment else "failed", + } + return ({selected: cases[selected]} if selected else cases), {B: {"origin": THIRD}} + + fixture = fake(tmp_path, monkeypatch, [ref("repair", REPAIR), ref("observer", TEST), ref("third", THIRD)], + outcomes, provision=provision) + verdict = engine._Feedback.gate_problem + + def change_environment(self, record, target): + self.snapshot.restore(target) + if revised(fixture.root, THIRD): + write(fixture.root, RUNTIME, "changed during candidate checks") + return verdict(self, record, target) + + monkeypatch.setattr(engine._Feedback, "gate_problem", change_environment) + state = fixture.drive(4) + assert [(a, b) for a, b, _ in attempts(state)] == [("repair", "accepted"), ("third", "rejected")] + assert "discarding and reprovisioning" in attempts(state)[1][2] + assert [owner for owner, _ in fixture.prompts] == ["repair", "third"] and n_provisions == 2 + [record] = state["rounds"] + assert record["unstable_observations"][0]["case"] == B + assert record["unstable_observations"][0]["failed_in"].endswith("(candidate suite)") + [initial] = [run for run in record["runs"] if run["purpose"] == "round 1 suite"] + assert initial["cases"][B] == "passed" + [reprovisioned] = [run for run in record["runs"] if run["purpose"] == "suite after reprovisioning"] + assert reprovisioned["failures_and_errors"] == 0 + assert record["attempts"][0]["suite_after"] == 2 + assert state["pending_unstable"] == {} and record["stop"] + + +@pytest.mark.parametrize("source_is_origin", [False, True]) +def test_d3_returns_stalled_and_source_origin_failures(tmp_path, monkeypatch, source_is_origin): + def outcomes(root, selected): + failed = not revised(root, SOURCE) + origin = SOURCE if source_is_origin else TEST + frames = [TEST, SOURCE] if source_is_origin or revised(root, TEST) else [TEST] + return {B: "failed" if failed else "passed"}, { + B: {"origin": origin, "paths": frames, "detail": "ValueError: Invalid state"}, + } + + author = replace(ref("author", TEST), dependencies=("application",)) + fixture = fake(tmp_path, monkeypatch, [author, ref("application", SOURCE)], outcomes) + rounds = fixture.drive(2)["rounds"] + if source_is_origin: + assert len(rounds) == 1 + else: + first = rounds[0]["attempts"][0] + assert (first["owner"], first["verdict"]) == ("author", "stalled") + [body] = rounds[-1]["attempts"] + assert (body["owner"], body["recipient"], body["verdict"]) == ("application", "body", "fixed") + assert revised(fixture.root, SOURCE) and not revised(fixture.root, TEST) + + +def use_real_tests(fixture, monkeypatch): + monkeypatch.setattr(engine, "subprocess", subprocess) + monkeypatch.setattr(engine.VerifyRunner, "feedback_test_command", lambda *_: ( + [sys.executable, "-m", "pytest", "-q", "-p", "no:cacheprovider", "checks"], + fixture.root, {**os.environ, "PYTHONPATH": str(fixture.root), "PYTEST_DISABLE_PLUGIN_AUTOLOAD": "1"}, 30, + )) + + +def test_j4_case_with_two_source_owners_is_not_handed_off(tmp_path, monkeypatch): + second_source = "src/cleanup.py" + author = replace(ref("author", TEST), dependencies=("application", "cleanup")) + fixture = fake(tmp_path, monkeypatch, [ + author, ref("application", SOURCE), ref("cleanup", second_source), + ], None, files={ + TEST: ( + "import pytest\n" + "from src import cleanup, subject\n\n" + "@pytest.fixture\n" + "def resource():\n" + " yield\n" + " cleanup.release()\n\n" + "def test_subject(resource):\n" + " subject.run()\n" + ), + SOURCE: "def run():\n raise ValueError('call failed')\n", + second_source: "def release():\n raise RuntimeError('cleanup failed')\n", + }) + use_real_tests(fixture, monkeypatch) + [record] = fixture.drive(1)["rounds"] + [suite] = record["runs"] + assert suite["cases"][B] == "failed" and len(suite["fingerprints"][B]) == 2 + assert record["attempts"] == [] and fixture.prompts == [] + + +def setup_claim_project(project_factory, *, write_test=False, stale_stdout=False): + tests = """\ +from stub_app import subject + +def test_subject(): + actual = subject.value() + assert actual is not None, "blocked before the comparison" + assert actual == 7, "reached the comparison" +""" + source = "def value():\n return None\n" + body_fix = {APP: "def value():\n return 8\n"} + body_outputs = (APP,) + if write_test: + body_fix["checks/test_body_owned.py"] = "def test_body_owned():\n assert True\n" + body_outputs += ("checks/test_body_owned.py",) + claim = json.dumps({"case": f"{TEST_FILE}::test_subject", + "path": APP, "reason": "value returns no result before the comparison"}) + pipeline, root, trace, _ = project_factory( + rounds=1 if write_test else 2, + initial={"case": {TEST_FILE: tests}, "application": {APP: source}}, + owned={"case": (TEST_FILE,), "application": body_outputs}, + fixes={"case": {"direct": {CLAIM: claim}}, "application": {"files": body_fix}}, + ) + if stale_stdout: + stale = json.dumps({"case": f"{TEST_FILE}::test_subject", + "path": "src/obsolete.py", "reason": "stale report"}) + script = trace.with_name("ai.py") + script.write_text(script.read_text() + ( + '\nif part == "feedback" and owner == "case" and "AssertionError: blocked before the comparison" in prompt:\n' + ' print("paths: []")\n' + f' print({("CODD_TEST_FEEDBACK_CLAIM " + stale)!r})\n' + )) + lister = pipeline.task_lister + pipeline.task_lister = lambda project: [ + replace(task, dependencies=("application",)) if task.task_id == "case" else task + for task in lister(project) + ] + return pipeline, root, trace + + +def test_y3_claim_returns_to_dependency_and_retains_progress(project_factory, monkeypatch): + pipeline, root, _ = setup_claim_project(project_factory) + rerun = pipeline._reimplement_tasks + observed = [] + + def remember(project, tasks, prompt, config, **kwargs): + observed.append((tasks[0].task_id, prompt, (root / TEST_FILE).read_bytes())) + return rerun(project, tasks, prompt, config, **kwargs) + + monkeypatch.setattr(pipeline, "_reimplement_tasks", remember) + pipeline.run(root) + first, second = feedback(root)["rounds"] + assert [(a["owner"], a["decision"]) for a in first["attempts"]] == [ + ("case", "declined"), ("application", "accepted"), + ] + assert first["attempts"][1]["verdict"] == "progressed" + assert first["attempts"][1]["recipient"] == "body" + assert "return 8" in (root / APP).read_text() + assert all(content == (root / TEST_FILE).read_bytes() for _, _, content in observed) + assert [owner for owner, _, _ in observed] == ["case", "application", "case"] + assert CLAIM in observed[0][1] and '{"case":' in observed[0][1] + assert "CODD_TEST_FEEDBACK_CLAIM" not in observed[0][1] + assert "AssertionError: reached the comparison" in observed[-1][1] + assert second["runs"][0]["purpose"] == "round 2 suite" + + +def test_y4_body_turn_rejects_writes_even_to_its_own_test(project_factory): + pipeline, root, _ = setup_claim_project(project_factory, write_test=True) + pipeline.run(root) + [record] = feedback(root)["rounds"] + _, body = record["attempts"] + assert body["decision"] == "rejected" + assert "write outside declared outputs" in body["reason"] + assert "return None" in (root / APP).read_text() + assert not (root / "checks/test_body_owned.py").exists() + + +@pytest.mark.parametrize("directory_link", [False, True], ids=["file-link", "directory-link"]) +def test_k2_body_turn_rejects_writes_to_linked_expectations(tmp_path, monkeypatch, directory_link): + data = "src/settings/rate.txt" + linked = "checks/expected/rate.txt" if directory_link else "checks/expected_rate.txt" + test_source = f"""\ +from pathlib import Path +from src.subject import rate + +def test_subject(): + actual = rate() + assert actual == int(Path({linked!r}).read_text()) +""" + application = """\ +from pathlib import Path + +def rate(): + current = int(Path(__file__).parent.joinpath('settings', 'rate.txt').read_text()) + if current < 8: + raise ValueError('outdated default rate') + return current +""" + + def edit(root, owner, scope): + assert owner == "body" + scopes.append((scope.allows(Path(SOURCE)), scope.allows(Path(data)))) + write(root, data, "8\n") + + scopes = [] + author = replace(ref("test", TEST), dependencies=("body",)) + fixture = fake(tmp_path, monkeypatch, [author, ref("body", SOURCE, data)], None, + files={TEST: test_source, SOURCE: application, data: "7\n"}, edit=edit) + if directory_link: + (fixture.root / linked).parent.symlink_to("../src/settings", target_is_directory=True) + else: + (fixture.root / linked).symlink_to("../" + data) + use_real_tests(fixture, monkeypatch) + [record] = fixture.drive(1)["rounds"] + [attempt] = record["attempts"] + assert (attempt["recipient"], attempt["decision"]) == ("body", "rejected") + assert attempt["reason"] == f"write outside declared outputs: {data}" + assert (fixture.root / data).read_text() == (fixture.root / linked).read_text() == "7\n" + assert scopes == [(True, False)] + assert [run["purpose"] for run in record["runs"]] == ["round 1 suite", "isolate"] + + +@pytest.mark.parametrize("change", ["none", "dependency", "output", "overlap", "legacy-claim"]) +def test_k3_resumed_claim_is_checked_against_current_tasks(tmp_path, monkeypatch, change): + tasks = [replace(ref("test", TEST), dependencies=("body",)), ref("body", SOURCE)] + + def outcomes(root, selected): + return {B: "passed" if revised(root, SOURCE) else "failed"}, {} + + def edit(root, owner, scope): + if owner == "test": + write(root, CLAIM, json.dumps({"case": B, "path": SOURCE, "reason": "source defect"})) + else: + write(root, SOURCE, "# revised\n") + + fixture = fake(tmp_path, monkeypatch, tasks, outcomes, edit=edit) + screen = engine._Feedback.screen + + def interrupt_before_body(self, *args, body=False, **kwargs): + if body: + raise KeyboardInterrupt + return screen(self, *args, body=body, **kwargs) + + with monkeypatch.context() as patch: + patch.setattr(engine._Feedback, "screen", interrupt_before_body) + with pytest.raises(KeyboardInterrupt): + fixture.drive(1) + + checkpoint = fixture.root / ".codd/review-session.json" + saved = json.loads(checkpoint.read_text()) + [record] = saved["test_feedback"]["rounds"] + assert [a["decision"] for a in record["attempts"]] == ["declined"] + assert [route["owner"] for route in record["claims"]] == ["body"] + if change == "dependency": + tasks[0] = replace(tasks[0], dependencies=()) + elif change == "output": + tasks[1] = ref("body", "src/other.py") + elif change == "overlap": + tasks.append(ref("other", SOURCE)) + elif change == "legacy-claim": + record["claims"][0].pop("paths", None) + checkpoint.write_text(json.dumps(saved)) + + [resumed] = fixture.drive(1, resume=True)["rounds"] + if change in ("none", "legacy-claim"): + assert [(a["owner"], a["decision"]) for a in resumed["attempts"]] == [ + ("test", "declined"), ("body", "accepted"), + ] + assert revised(fixture.root, SOURCE) + else: + assert [a["owner"] for a in resumed["attempts"]] == ["test"] + assert not revised(fixture.root, SOURCE) + + +def test_k4_body_progress_can_remove_one_of_two_failure_fingerprints(tmp_path, monkeypatch): + test_source = """\ +import pytest +from src import subject + +@pytest.fixture +def cleanup(): + yield + subject.clean() + +def test_subject(cleanup): + subject.run() +""" + application = """\ +def run(): + raise ValueError('call failure') + +def clean(): + raise RuntimeError('cleanup failure') +""" + + def edit(root, owner, scope): + assert owner == "body" + write(root, SOURCE, application.replace("raise ValueError('call failure')", "return")) + + author = replace(ref("test", TEST), dependencies=("body",)) + fixture = fake(tmp_path, monkeypatch, [author, ref("body", SOURCE)], None, + files={TEST: test_source, SOURCE: application}, edit=edit) + use_real_tests(fixture, monkeypatch) + [record] = fixture.drive(1)["rounds"] + [attempt] = record["attempts"] + baseline, candidate = [run for run in record["runs"] if "case" not in run] + assert len(baseline["fingerprints"][B]) == 2 + assert len(candidate["fingerprints"][B]) == 1 + assert set(candidate["fingerprints"][B]) < set(baseline["fingerprints"][B]) + assert (attempt["decision"], attempt["verdict"]) == ("accepted", "progressed") + assert (fixture.root / TEST).read_text() == test_source + assert "raise RuntimeError('cleanup failure')" in (fixture.root / SOURCE).read_text() + + +def test_j3_file_writer_uses_json_despite_stale_stdout_and_usage_logging(project_factory, monkeypatch): + pipeline, root, _ = setup_claim_project(project_factory, stale_stdout=True) + monkeypatch.setenv("CODD_AI_USAGE_LOG", "usage/ai.jsonl") + monkeypatch.setenv("GIT_CONFIG_GLOBAL", os.devnull) + monkeypatch.setenv("GIT_CONFIG_NOSYSTEM", "1") + subprocess.run(["git", "init", "-q", "--template="], cwd=root, check=True) + rerun = pipeline._reimplement_tasks + + def with_capture(*args, **kwargs): + with monkeypatch.context() as patch: + patch.setattr(ai_invoke, "is_file_writing_agent", lambda argv: argv[0] == sys.executable) + return rerun(*args, **kwargs) + + monkeypatch.setattr(pipeline, "_reimplement_tasks", with_capture) + pipeline.run(root) + first, _ = feedback(root)["rounds"] + assert [a["decision"] for a in first["attempts"]] == ["declined", "accepted"] + assert first["attempts"][0]["claim"]["path"] == APP + assert (root / "usage/ai.jsonl").is_file() + + +@pytest.mark.parametrize("depends_on_body", [False, True]) +def test_h2_claim_is_scoped_to_one_case_and_uses_the_test_files_dependencies( + tmp_path, monkeypatch, depends_on_body, +): + other = f"{TEST}::test_other" + + def outcomes(root, selected): + cases = {B: "passed" if revised(root, SOURCE) else "failed", other: "failed"} + return ({selected: cases[selected]} if selected else cases), { + B: {"origin": HELPER, "paths": [TEST, HELPER]}, + other: {"origin": HELPER, "paths": [TEST, HELPER]}, + } + + def edit(root, owner, scope): + if owner == "helper": + write(root, f"{engine.STATE_DIRECTORY}/claims/1-1.json", json.dumps({ + "case": B, "path": SOURCE, "reason": "source implementation causes the helper error", + })) + else: + write(root, SOURCE, "# revised\n") + + # An opposite dependency on the helper exposes both mistaken directions. + test = replace(ref("test", TEST), dependencies=("body",) if depends_on_body else ()) + helper = replace(ref("helper", HELPER), dependencies=() if depends_on_body else ("body",)) + fixture = fake(tmp_path, monkeypatch, [test, helper, ref("body", SOURCE)], outcomes, edit=edit) + [record] = fixture.drive(1)["rounds"] + assert record["attempts"][0]["decision"] == "declined" + if depends_on_body: + _, body = record["attempts"] + assert body["decision"] == "accepted" + assert [failure["case"] for failure in body["returned_failures"]] == [B] + else: + assert [owner for owner, _ in fixture.prompts] == ["helper"] + + +def test_h3_claim_can_follow_codd_usage_appends_to_a_new_directory(tmp_path, monkeypatch): + from codd.ai_usage import usage_session, usage_trial + + monkeypatch.setenv("CODD_AI_USAGE_LOG", "usage/log.jsonl") + + def outcomes(root, selected): + return {B: "passed" if revised(root, SOURCE) else "failed"}, {} + + def edit(root, owner, scope): + if owner == "body": + write(root, SOURCE, "# revised\n") + return + with usage_session(project_root=root), usage_trial("prompt", "stub", ["stub"]): + write(root, f"{engine.STATE_DIRECTORY}/claims/1-1.json", json.dumps({ + "case": B, "path": SOURCE, "reason": "source defect", + })) + assert (root / "usage/log.jsonl").is_file() + raise RuntimeError("AI command did not produce any file changes") + + test = replace(ref("test", TEST), dependencies=("body",)) + fixture = fake(tmp_path, monkeypatch, [test, ref("body", SOURCE)], outcomes, edit=edit) + [record] = fixture.drive(1)["rounds"] + assert [attempt["decision"] for attempt in record["attempts"]] == ["declined", "accepted"] + + +def test_h4_fingerprint_matches_full_evidence_masking(): + def signature(first, function="parse", code=401): + return engine._failure_fingerprint({ + "detail": f"{first}\n in {function}\nFinal exception: status {code}", + }) + + first = "Invalid key 123456 0xeeeeaaaa address at 0xf0" + assert signature(first) == signature("Invalid key 999999 0xffffaaaa address at 0x12") + assert signature(first) != signature("Missing key 123456 0xeeeeaaaa address at 0xf0") + assert signature(first) != signature(first, function="validate") + assert signature(first) != signature(first, code=403) + + +def test_h5_body_turn_does_not_overwrite_rejected_test_diagnostics(tmp_path, monkeypatch): + def outcomes(root, selected): + cases = {A: "failed", B: "passed" if revised(root, SOURCE) else "failed"} + details = { + A: {"detail": "rejected candidate evidence" if revised(root, REPAIR) else "initial failure"}, + B: {"origin": SOURCE, "paths": [TEST, SOURCE]}, + } + return ({selected: cases[selected]} if selected else cases), details + + def edit(root, owner, scope): + assert owner == "mixed" + path = REPAIR if scope.allows(root / REPAIR) else SOURCE + write(root, path, (root / path).read_text() + "\n# revised\n") + + foreign = replace(ref("foreign", TEST), dependencies=("mixed",)) + fixture = fake(tmp_path, monkeypatch, [foreign, ref("mixed", REPAIR, SOURCE)], outcomes, edit=edit) + first, second = fixture.drive(2)["rounds"] + assert [(a["recipient"], a["decision"]) for a in first["attempts"]] == [ + ("test", "rejected"), ("body", "accepted"), + ] + assert second["attempts"][0]["recipient"] == "test" + assert "After your previous change" in fixture.prompts[-1][1] + assert "rejected candidate evidence" in fixture.prompts[-1][1] + + +@pytest.mark.parametrize("same_failure", [False, True]) +def test_y5_rejected_candidate_failure_is_delivered_on_retry(tmp_path, monkeypatch, same_failure): + def outcomes(root, selected): + detail = "candidate encounters a later comparison" if revised(root, TEST) and not same_failure else "initial failure" + return {B: "failed"}, {B: {"detail": detail}} + + fixture = fake(tmp_path, monkeypatch, [ref("test", TEST)], outcomes) + first, second = fixture.drive(2)["rounds"] + original, retry = first["attempts"][0], second["attempts"][0] + assert original["decision"] == retry["decision"] == "rejected" + assert not revised(fixture.root, TEST) + assert original["reason"] == "owner's failures and errors did not decrease" + assert "After your previous change" in fixture.prompts[1][1] + assert ("initial failure" if same_failure else "candidate encounters a later comparison") in original["candidate_failure"] + assert (fixture.root / original["candidate_failure_path"]).is_file() + + +def test_y5_retry_includes_failures_seen_only_in_candidate_isolation(tmp_path, monkeypatch): + def outcomes(root, selected): + candidate = revised(root, TEST) + details = {B: {"detail": "candidate isolation fails" if candidate else "initial failure"}} + return {B: "passed" if candidate and not selected else "failed"}, details + + fixture = fake(tmp_path, monkeypatch, [ref("test", TEST)], outcomes) + first, _ = fixture.drive(2)["rounds"] + [attempt] = first["attempts"] + assert attempt["suite_after"] == 0 and attempt["isolated_after"] == 1 + assert attempt["reason"] == "isolated failures and errors did not decrease" + assert "candidate isolation fails" in fixture.prompts[1][1] + assert "candidate isolation fails" in (fixture.root / attempt["candidate_failure_path"]).read_text() + + +@pytest.mark.parametrize("resume", [False, True]) +def test_k1_reruns_suite_for_unchanged_tree_at_next_round_start(tmp_path, monkeypatch, resume): + second_case = TEST + "::test_remaining" + + def outcomes(root, selected): + cases = {B: "passed" if revised(root, TEST) else "failed", second_case: "failed"} + return ({selected: cases[selected]} if selected else cases), {} + + def edit(root, owner, outputs): + write(root, TEST, (root / TEST).read_text() + "# revised\n") + + fixture = fake(tmp_path, monkeypatch, [ref("test", TEST)], outcomes, edit=edit) + if resume: + fixture.drive(1) + first, second = fixture.drive(2, resume=resume)["rounds"] + assert first["attempts"][0]["decision"] == "accepted" + assert second["attempts"][0]["decision"] == "rejected" + assert [[run["purpose"] for run in record["runs"] if "case" not in run] for record in (first, second)] == [ + ["round 1 suite", "candidate suite"], ["round 2 suite", "candidate suite"], + ] + assert "reused_suites" not in second + + +def test_k1_reruns_suite_after_a_rejected_candidate(tmp_path, monkeypatch): + fixture = fake(tmp_path, monkeypatch, [ref("test", TEST)], lambda *_: ({B: "failed"}, {})) + first, second = fixture.drive(2)["rounds"] + assert first["attempts"][0]["decision"] == "rejected" + assert second["runs"][0]["purpose"] == "round 2 suite" + assert "reused_suites" not in second + + +def test_k1_round_start_detects_changes_behind_environment_link(tmp_path, monkeypatch): + backing = tmp_path / "dependency-data" + + def provision(root): + link = root / RUNTIME + if not link.is_symlink(): + link.parent.mkdir() + link.symlink_to(backing) + backing.write_text("old") + else: + backing.write_text("new") + + def outcomes(root, selected): + cases = { + A: "passed" if revised(root, REPAIR) else "failed", + B: "failed", + C: "failed" if (root / RUNTIME).read_text() == "new" and not revised(root, THIRD) else "passed", + } + return ({selected: cases[selected]} if selected else cases), {} + + def edit(root, owner, scope): + if owner == "b": + raise RuntimeError("AI command did not produce any file changes") + [path] = scope.names + write(root, path, (root / path).read_text() + "\n# revised\n") + + fixture = fake(tmp_path, monkeypatch, [ref("a", REPAIR), ref("b", TEST), ref("c", THIRD)], + outcomes, provision=provision, edit=edit) + first, second = fixture.drive(2)["rounds"] + assert first["environment_before"] == second["environment_before"] + assert first["runs"][0]["cases"][C] == "passed" + assert second["runs"][0]["purpose"] == "round 2 suite" + assert second["runs"][0]["cases"][C] == "failed" + assert [(a["owner"], a["decision"]) for a in second["attempts"]] == [("b", "rejected"), ("c", "accepted")]