Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
214 changes: 178 additions & 36 deletions codd/greenfield/implement_test_feedback.py

Large diffs are not rendered by default.

20 changes: 20 additions & 0 deletions codd/languages/adapters/_pytest_feedback_probe.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand All @@ -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
Expand All @@ -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")


Expand Down Expand Up @@ -172,13 +187,15 @@ 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,
"origin": origins[0] if origins else "",
"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"
Expand All @@ -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("<"):
Expand Down
16 changes: 15 additions & 1 deletion codd/languages/adapters/pytest_feedback.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
import ast
import json
import os
import re
import shutil
from collections import Counter, defaultdict
from collections.abc import Collection
Expand All @@ -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
Expand Down Expand Up @@ -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)
Expand All @@ -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]]:
Expand Down
21 changes: 21 additions & 0 deletions codd/repair/history.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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")

Expand Down
Loading
Loading