Quarry / harness /tasks.py
jbellis-brokk's picture
Publish Quarry v1
780ecbf verified
Raw
History Blame Contribute Delete
76.9 kB
"""Single source of truth for reading + filtering the SFT task corpus.
POLICY — "Thou Shalt Not Read Tasks Manually": every access to the
``sft-tools-commits/`` and ``sfttasks/`` trees goes through this module. Do NOT
open those paths, glob them, or re-implement their filters anywhere else — if you
find yourself writing ``sft-tools-commits`` or ``sfttasks`` in another ``.py``,
call a function here instead (or add one). Centralizing keeps the binding,
large-repos, and prompt-existence filters consistent across every consumer
(p2t, localizer, generate, sft_gen, scan, the oneoffs); they have silently
drifted before. The enforcement test ``tests/test_no_manual_task_reads.py``
fails the build if a non-allowlisted module reads these paths directly.
Public surface (grouped):
- scan/commit records: ``read_scan_records``, ``read_scan_hashes``, ``ScanRecord``
- selection (the predicate engine): ``Predicates``, ``task_repos``, ``task_shas``,
``sft_task_repos``/``sft_task_shas``, ``SFT_PREDICATES``, ``select_sft_task_threshold``
- repo metadata: ``read_repo_excluded_files``, ``repo_lang``/``repo_langs``,
``large_repo_set``, ``build_times``
- build scripts + testsome templates: ``build_script_path``, ``template_path``
- build eras (per-range b+t setups, see sft_tooluse/BUILD_ERAS.md): ``era_for``
(a testsome record's era, ``None`` = HEAD), ``build_eras`` (status-registry reader),
``build_era_status`` (the era's authoring-lifecycle status subtree; ``None`` = HEAD
fields at top level — what the ``--era`` availability gate consults)
- testsome binding: ``read_testsome_outcomes``, ``testsome_outcome``, ``is_binding``,
``testsome_command``
- task variants/prompts: ``prompt_path_for``, ``index_prompt_variant_one``,
``task_variant_paths``, ``read_task_properties``, ``related_file_names``,
``read_task_metadata``
- repo status.json sidecar (read+write, owned here; find_repos keeps the scan-pipeline
orchestration on top): ``read_repo_status``/``read_repo_status_payload``,
``write_repo_status``/``write_repo_status_payload``, ``record_clone_failure_status``,
``clear_clone_failure_status``, ``has_clone_failure_status``, ``record_lfs_skip_status``,
``has_lfs_skip_status``, ``delete_repo_status``, ``status_str``/``status_int``,
``status_path_for``, ``STATUS_VERSION``, ``CLONE_STATE_FAILED``/``CLONE_STATE_SKIPPED_LFS``
- results parsing: ``parse_result_path``, ``extract_run_metrics`` (legacy helpers)
"""
from __future__ import annotations
import csv
import functools
import json
import math
import re
from contextlib import contextmanager
from collections.abc import Iterable, Mapping
from dataclasses import dataclass, replace
from datetime import datetime, timezone
import os
from pathlib import Path
import threading
import time
from types import MappingProxyType
from typing import TextIO
import sys
from collections.abc import Callable
# Default corpus roots (this module lives at the repo root beside both trees).
DEFAULT_COMMITS_DIR = Path(__file__).resolve().parent / "sft-tools-commits"
DEFAULT_SFTTASKS_DIR = Path(__file__).resolve().parent / "sfttasks"
# Canonical language metadata shared by repo discovery / collection tooling.
LANGUAGE_RANKING_NAMES: dict[str, str] = {
"c": "C",
"cpp": "C++",
"csharp": "CSharp",
"go": "Go",
"java": "Java",
"js": "JavaScript",
"php": "PHP",
"py": "Python",
"rust": "Rust",
"scala": "Scala",
"ts": "TypeScript",
}
LANGUAGE_RANKING_FILE_NAMES: dict[str, str] = {
"cpp": "CPP",
"csharp": "CSharp",
}
LANGUAGE_ALIASES: dict[str, str] = {
"c++": "cpp",
"c#": "csharp",
"cs": "csharp",
"javascript": "js",
"python": "py",
"typescript": "ts",
}
DEFAULT_LANGUAGES: tuple[str, ...] = tuple(LANGUAGE_RANKING_NAMES)
RUN_ID_SUFFIXES = "0123456789"
# Filename suffix the external sft-tools "testsome" binding-validation pass uses
# for its per-repo sidecar in the commits dir (e.g. ``Genymobile__scrcpy.testsome.jsonl``),
# living beside the canonical ``<slug>.jsonl`` results. Consumers that enumerate
# ``*.jsonl`` must skip these to avoid minting phantom ``<slug>.testsome`` repos.
TESTSOME_SIDECAR_SUFFIX = ".testsome.jsonl"
STOP_REASON_STARTED = "STARTED"
STOP_REASON_SUCCESS = "SUCCESS"
STOP_REASON_NO_EDITS = "NO_EDITS"
STOP_REASON_HARNESS_TESTS_FAILED = "HARNESS_TESTS_FAILED"
STOP_REASON_PREBUILD_FAILED = "PREBUILD_FAILED"
RUN_OUTCOME_SUCCESS = "success"
RUN_OUTCOME_TESTS_FAILED = "tests_failed"
RUN_OUTCOME_AGENT_FAILED = "agent_failed"
_SCAN_HASH_RE = re.compile(r"^[0-9a-fA-F]{6,40}$")
_LEGACY_SCAN_LINE_RE = re.compile(
r"^(?P<sha>[0-9a-fA-F]{6,40}) "
r"\((?P<first>\d+), (?P<second>\d+), (?P<third>\d+)\) "
r"(?P<summary>.*)$"
)
_TASK_METADATA_LOCKS_LOCK = threading.Lock()
_TASK_METADATA_LOCKS: dict[Path, threading.RLock] = {}
def normalize_language(value: str) -> str:
key = value.strip().lower()
if not key:
raise ValueError("language cannot be empty")
return LANGUAGE_ALIASES.get(key, key)
def ranking_language_name(language: str) -> str:
normalized = normalize_language(language)
return LANGUAGE_RANKING_NAMES.get(normalized, language.strip())
def ranking_file_name(language: str) -> str:
normalized = normalize_language(language)
return LANGUAGE_RANKING_FILE_NAMES.get(normalized, ranking_language_name(normalized))
def _language_preference_key(language: str) -> tuple[int, str]:
"""Canonical order for multi-language repo listings."""
normalized = normalize_language(language)
try:
return (DEFAULT_LANGUAGES.index(normalized), normalized)
except ValueError:
return (len(DEFAULT_LANGUAGES), normalized)
def _normalized_metadata_path(path: Path) -> Path:
return path.expanduser().resolve(strict=False)
@contextmanager
def task_metadata_file_lock(path: Path):
normalized = _normalized_metadata_path(path)
with _TASK_METADATA_LOCKS_LOCK:
lock = _TASK_METADATA_LOCKS.get(normalized)
if lock is None:
lock = threading.RLock()
_TASK_METADATA_LOCKS[normalized] = lock
with lock:
yield
@dataclass(frozen=True)
class PathMetadata:
model: str
run_id: str
project: str
hash: str
path: Path
@dataclass(frozen=True)
class ResultFileMetadata:
project: str
run_id: str
run_number: int
model: str
revision: str
path: Path
@dataclass(frozen=True)
class ScanRecord:
hash: str
oneline: str
test_files: int
non_test_files: int
code_files: int
total_files: int
token_count: int
hunks: int
insertion_hunks: int
non_test_hunks: int
non_test_insertion_hunks: int
insertion_lines: int
non_test_insertion_lines: int
non_code_files: int = 0
total_changed_lines: int = 0
non_code_changed_lines: int = 0
@dataclass(frozen=True)
class ExactSftTaskPath:
sha: str
variant_index: int
prompt_path: Path
@dataclass(frozen=True)
class ExactSftTaskTarget:
sha: str
variant_index: int
prompt_path: Path
output_dir: Path
repo_slug: str
excluded_files: tuple[str, ...]
def parse_project_and_run(
run_dir: str | Path,
) -> tuple[str, int | None]:
run_dir_name = Path(run_dir).name
project_name = run_dir_name.rstrip(RUN_ID_SUFFIXES)
run_suffix = run_dir_name[len(project_name) :]
if not run_suffix:
return project_name, None
if run_suffix.isdigit():
return project_name, int(run_suffix)
return project_name, None
def discover_projects(base_directory: Path) -> list[str]:
"""
Infer project prefixes from run directory names of the form ``<project><run_number>``.
"""
projects: set[str] = set()
for run_dir in base_directory.iterdir():
if not run_dir.is_dir():
continue
project_name, run_suffix = parse_project_and_run(run_dir)
if not project_name or run_suffix is None:
continue
projects.add(project_name)
return sorted(projects)
def parse_result_filename(filename: str) -> tuple[str | None, str | None]:
"""
Parse model-sha.json -> (model, sha).
Handles models whose names may contain dashes by splitting on the LAST dash
before the revision hash.
"""
stem = Path(filename).stem
match = re.match(r"^(.+)-([0-9a-f]+)$", stem)
if match:
model, sha = match.groups()
return (model, sha)
model, sep, revision = stem.rpartition("-")
if sep and revision and re.fullmatch(r"[0-9a-f]+", revision):
return (model, revision)
return (None, None)
def model_from_result_filename(path: str | Path) -> str:
"""
Extract model name from a result filename path.
Handles models whose names themselves contain dashes by splitting on the LAST
dash before the revision.
"""
model, _sha = parse_result_filename(Path(path).name)
if model is None:
stem = Path(path).stem
model, _sep, _revision = stem.rpartition("-")
return model if _sep else stem
return model
def _model_and_revision_from_result_path(path: Path) -> tuple[str | None, str | None]:
_model, revision = parse_result_filename(path.name)
if revision is not None:
model = _model or path.stem.rpartition("-")[0]
return model, revision
return None, None
def build_result_path(
results_root: Path,
project_name: str,
run_number: int,
model: str,
revision: str,
) -> Path:
"""
Build a result path under ``{results_root}/{project}{run_number}/{model}-{revision}.json``.
"""
results_dir = results_root / f"{project_name}{run_number}"
return results_dir / f"{model}-{revision}.json"
def parse_result_path(path: str | Path) -> ResultFileMetadata | None:
"""
Parse result file metadata from path.
"""
path = Path(path)
if path.suffix != ".json":
return None
model, revision = _model_and_revision_from_result_path(path)
if revision is None:
return None
run_id = path.parent.name
project, run_number = parse_project_and_run(run_id)
if run_number is None:
return None
return ResultFileMetadata(
project=project,
run_id=run_id,
run_number=run_number,
model=model or "",
revision=revision,
path=path,
)
def parse_path(path_str: str | Path) -> PathMetadata:
"""
Parse path metadata from a .json result path.
Backwards-compatible API used by tests. Removes tasktune suffixes from the stem
before extracting model and revision hash.
"""
path = Path(path_str)
stem = path.stem
stem = re.sub(r"-tasktune\d+$", "", stem)
model, sep, hash_val = stem.rpartition("-")
if not sep:
model = hash_val
hash_val = ""
run_id = path.parent.name
project = run_id.rstrip(RUN_ID_SUFFIXES)
return PathMetadata(
model=model,
run_id=run_id,
project=project,
hash=hash_val,
path=path,
)
def repo_slug_from_repo_path(repo_path: str | Path) -> str:
path = Path(repo_path)
name = path.name
if name == ".git":
return path.parent.name
if name.endswith(".git"):
return name[:-4]
return name
def parse_exact_sft_task_path(path_str: str | Path) -> ExactSftTaskPath:
path = Path(path_str)
match = re.fullmatch(r"([0-9a-fA-F]{6,40})-(\d+)\.txt", path.name)
if match is None:
raise ValueError(f"expected sft prompt path like <sha>-<variant>.txt, got {path}")
sha, index_text = match.groups()
return ExactSftTaskPath(
sha=sha.lower(),
variant_index=int(index_text),
prompt_path=path,
)
def _read_excluded_files_from_status_path(
path: Path,
*,
warn_if_missing: bool,
warn_callback: Callable[[str], None] | None = None,
) -> tuple[str, ...]:
if not path.exists():
if warn_if_missing:
message = f"repo status metadata missing: {path}"
if warn_callback is not None:
warn_callback(message)
else:
print(message, file=sys.stderr)
return ()
try:
payload = json.loads(path.read_text(encoding="utf-8"))
except json.JSONDecodeError as exc:
raise ValueError(f"malformed repo status metadata: {path}") from exc
if not isinstance(payload, dict):
raise ValueError(f"repo status metadata must be a JSON object: {path}")
if "excluded_files" not in payload:
if warn_if_missing:
message = f"repo status metadata missing excluded_files: {path}"
if warn_callback is not None:
warn_callback(message)
else:
print(message, file=sys.stderr)
return ()
raw = payload["excluded_files"]
if not isinstance(raw, list):
raise ValueError(f"excluded_files must be a list in {path}")
excluded: list[str] = []
seen: set[str] = set()
for item in raw:
if not isinstance(item, str) or not item.strip():
raise ValueError(f"excluded_files must contain only non-empty strings in {path}")
normalized = item.strip()
if normalized in seen:
continue
seen.add(normalized)
excluded.append(normalized)
return tuple(excluded)
def read_repo_excluded_files_for_lang(
commits_root: Path,
lang: str,
repo_slug: str,
*,
warn_if_missing: bool = True,
warn_callback: Callable[[str], None] | None = None,
) -> tuple[str, ...]:
path = commits_root / lang / f"{repo_slug}.status.json"
return _read_excluded_files_from_status_path(
path,
warn_if_missing=warn_if_missing,
warn_callback=warn_callback,
)
def read_repo_excluded_files(
commits_root: Path,
repo_slug: str,
*,
warn_if_missing: bool = False,
warn_callback: Callable[[str], None] | None = None,
) -> tuple[str, ...]:
matches = sorted(commits_root.glob(f"*/{repo_slug}.jsonl"))
if not matches:
return ()
if len(matches) == 1:
return read_repo_excluded_files_for_lang(
commits_root,
matches[0].parent.name,
repo_slug,
warn_if_missing=warn_if_missing,
warn_callback=warn_callback,
)
# Multi-language repo (e.g. Pillow = c + py): UNION the excluded files across every
# language the repo appears under instead of raising. Excluded files are non-source
# (generated/vendored) paths, so the union is the conservative, lang-agnostic choice and
# lets callers (task generation, exact-task regeneration) process the repo rather than
# skip it. Callers that know the exact language should use read_repo_excluded_files_for_lang.
excluded: set[str] = set()
for path in matches:
excluded.update(
read_repo_excluded_files_for_lang(
commits_root,
path.parent.name,
repo_slug,
warn_if_missing=False,
)
)
return tuple(sorted(excluded))
# ---------------------------------------------------------------------------
# Repo status.json sidecar (``<repo>.status.json``)
#
# The status sidecar is a SHARED, versioned, multi-writer file: the scan
# pipeline (find_repos) records scan/clone state, while generate_build_scripts
# and the binding validator add ``build_script_*`` / ``testsome_*`` fields to
# the SAME file. Reads and writes therefore go through ONE owner so the read-
# modify-write discipline (never clobber another pipeline's fields) and the
# format version live in a single place. This used to live in find_repos.py;
# it now lives here because tasks.py is the corpus SSOT and find_repos imports
# tasks (so the primitives must sit in the lower module). find_repos keeps the
# pipeline-specific ORCHESTRATION (reconcile/scan-summary) built on top of these.
# ---------------------------------------------------------------------------
STATUS_VERSION = 1
CLONE_STATE_FAILED = "failed"
# Repo uses Git LFS, which we deliberately do not support (installing git-lfs and
# pulling LFS objects would explode disk for marginal benefit). Such repos are
# skipped entirely and their clones removed; this persistent marker keeps the
# pipeline from re-cloning them on every run. Unlike CLONE_STATE_FAILED it is not
# cleared by --retry-failures, since LFS is a permanent property, not transient.
CLONE_STATE_SKIPPED_LFS = "skipped_lfs"
def checked_at_timestamp() -> str:
"""Return an ISO-8601 UTC timestamp for repo status updates."""
return datetime.now(timezone.utc).isoformat().replace("+00:00", "Z")
def status_path_for(results_dir: Path, slug: str) -> Path:
"""Return the status sidecar path for the repo *slug* under *results_dir*."""
return results_dir / f"{slug}.status.json"
def read_repo_status(status_path: Path) -> dict[str, object] | None:
"""Return parsed repo status metadata when present and version-supported."""
if not status_path.exists():
return None
try:
payload = json.loads(status_path.read_text(encoding="utf-8"))
except (OSError, ValueError, json.JSONDecodeError):
return None
if not isinstance(payload, dict):
return None
if payload.get("version") != STATUS_VERSION:
return None
return payload
def read_repo_status_payload(status_path: Path) -> dict[str, object]:
"""Return any dict-shaped status payload, even if it is not versioned scan metadata."""
if not status_path.exists():
return {}
try:
payload = json.loads(status_path.read_text(encoding="utf-8"))
except (OSError, ValueError, json.JSONDecodeError):
return {}
return payload if isinstance(payload, dict) else {}
def write_repo_status_payload(status_path: Path, payload: dict[str, object]) -> None:
"""Write a status payload while preserving non-scan metadata fields."""
status_path.parent.mkdir(parents=True, exist_ok=True)
status_path.write_text(
json.dumps(payload, indent=2, sort_keys=True) + "\n",
encoding="utf-8",
)
P2T_ORACLE_FAILED_KEY = "p2t_oracle_failed"
def p2t_oracle_failed_stamp(
status_payload: Mapping[str, object],
) -> Mapping[str, object] | None:
"""The P2T runtime-burn stamp (``{"at","run","shas","sample_error_head"}``)
that ``p2t/infra/stamp_runtime_evidence.py`` writes when EVERY landed task in a
firehose run oracle-failed for this repo — a full-repo runtime burn that leaves
no other status marker (the oracle failure happens at P2T runtime, not during
testsome authoring, so ``testsome_*``/``build_script_*`` all look healthy).
``None`` when unstamped or recovered. The firehose derivation screens stamped
repos out; a later oracle-passing outcome clears the stamp."""
stamp = status_payload.get(P2T_ORACLE_FAILED_KEY)
return stamp if isinstance(stamp, dict) else None
def is_p2t_oracle_failed(commits_dir: Path, lang: str, repo_slug: str) -> bool:
"""True iff ``repo_slug`` carries an un-cleared P2T oracle-failure stamp."""
status = read_repo_status_payload(status_path_for(commits_dir / lang, repo_slug))
return p2t_oracle_failed_stamp(status) is not None
def build_eras(status_payload: Mapping[str, object]) -> tuple[dict[str, object], ...]:
"""The repo's build-era registry from its status payload, newest-first.
Each entry is ``{"era","anchor","authored_at","samples_validated","wall_upper"}``
(see ``sft_tooluse/BUILD_ERAS.md``). A missing or malformed ``build_eras`` key
yields ``()`` — no pipeline writes this registry in Phase 1, so every current
repo resolves to zero eras (HEAD-only), preserving full backward compat. This
is a READ-ONLY accessor: the authoring/validation pipeline owns the writes and
must go through ``write_repo_status_payload`` so it preserves sibling fields
the status file shares with other pipelines."""
eras = status_payload.get("build_eras")
if not isinstance(eras, list):
return ()
return tuple(entry for entry in eras if isinstance(entry, dict))
def build_era_status(
status_payload: Mapping[str, object], era: str | None = None
) -> Mapping[str, object]:
"""The status subtree carrying a build era's authoring lifecycle fields
(``build_script_last_returncode``, ``testsome_*``, failure markers).
``era=None`` returns the payload itself — the HEAD-era fields live at the top
level, so every pre-era reader is byte-identical. An era id returns
``status["build_era_state"][era]`` (or ``{}`` when that era was never authored),
the era-scoped mirror the authoring pipeline writes so an era run NEVER touches
HEAD's top-level ``build_script_*``/``testsome_*`` fields (BUILD_ERAS.md §4). The
``--era`` availability gate consults THIS instead of the HEAD fields."""
if era is None:
return status_payload
state = status_payload.get("build_era_state")
if not isinstance(state, dict):
return {}
entry = state.get(era)
return entry if isinstance(entry, dict) else {}
TESTSOME_BUILD_FAIL_BUDGET = 4
def testsome_repo_unavailable_reason(
commits_dir: Path,
language: str,
repo_slug: str,
era: str | None = None,
) -> str | None:
"""Why the testsome validator would refuse this repo before provisioning a VM.
``era`` (an ``era-<anchor12>`` id) gates on that era's suffixed b+t artifacts
and its era-scoped status subtree instead of the HEAD-era files/fields — closing
the Phase-1 follow-up where an era ``--era`` run would read HEAD's
``build_script_last_returncode`` (which an era run never writes, so a
green era looked unavailable). ``era=None`` ⇒ the HEAD fields, byte-identical."""
lang_dir = commits_dir / language
if build_script_path(language, repo_slug, commits_dir, era=era) is None:
return "missing build script"
if template_path(language, repo_slug, commits_dir, era=era) is None:
return "missing testsome template"
status = read_repo_status_payload(status_path_for(lang_dir, repo_slug))
era_status = build_era_status(status, era)
skipped = era_status.get("testsome_skipped")
if skipped:
return f"testsome_skipped={skipped}"
last_returncode = era_status.get("build_script_last_returncode")
if last_returncode not in (0, "0"):
return f"build_script_last_returncode={last_returncode!r}"
try:
fail_count = int(era_status.get("testsome_build_fail_count", 0))
except (TypeError, ValueError):
fail_count = 0
if fail_count >= TESTSOME_BUILD_FAIL_BUDGET:
return f"testsome_build_fail_count={fail_count}"
return None
def write_repo_status(
status_path: Path,
*,
state: str,
head_sha: str | None,
commit_count: int,
result_count: int,
resume_sha: str | None,
classified_count: int | None = None,
accepted_in_window: int | None = None,
max_insertion_lines: int | None = None,
) -> None:
"""Write the repo processing status sidecar.
Read-modify-write: the same sidecar carries metadata owned by other
pipelines (build_script_* from generate_build_scripts, testsome_* from
the binding validator); overwriting from scratch silently destroyed
those fields on every re-scan.
"""
payload = read_repo_status_payload(status_path)
payload.update(
{
"version": STATUS_VERSION,
"state": state,
"head_sha": head_sha,
"commit_count": commit_count,
"checked_at": checked_at_timestamp(),
"result_count": result_count,
"resume_sha": resume_sha,
}
)
if classified_count is not None:
payload["classified_count"] = classified_count
if accepted_in_window is not None:
payload["accepted_in_window"] = accepted_in_window
if max_insertion_lines is not None:
payload["max_insertion_lines"] = max_insertion_lines
write_repo_status_payload(status_path, payload)
def record_clone_failure_status(
status_path: Path,
*,
failure_kind: str,
failure_detail: str,
history_mode: str,
history_target: int,
) -> None:
"""Persist the latest clone failure without disturbing unrelated sidecar fields."""
payload = read_repo_status_payload(status_path)
if "version" not in payload:
payload["version"] = STATUS_VERSION
attempt_at = checked_at_timestamp()
payload["clone"] = {
"state": CLONE_STATE_FAILED,
"last_attempt_at": attempt_at,
"last_failure_at": attempt_at,
"failure_kind": failure_kind,
"failure_detail": failure_detail,
"history_mode": history_mode,
"history_target": history_target,
}
write_repo_status_payload(status_path, payload)
def clear_clone_failure_status(status_path: Path) -> None:
"""Remove persisted clone failure metadata while keeping all other status fields intact."""
payload = read_repo_status_payload(status_path)
if "clone" not in payload:
return
payload.pop("clone", None)
write_repo_status_payload(status_path, payload)
def has_clone_failure_status(status_path: Path) -> bool:
"""Return True when the sidecar records a blocking clone failure."""
clone_status = read_repo_status_payload(status_path).get("clone")
if not isinstance(clone_status, dict):
return False
return clone_status.get("state") == CLONE_STATE_FAILED
def record_lfs_skip_status(status_path: Path) -> None:
"""Persist a permanent Git-LFS skip marker, replacing any prior clone state.
The repo's scan artifacts are purged alongside this call, so the sidecar is
reset to a minimal record carrying only the skip marker; admission reads it
to avoid ever re-cloning the repo.
"""
write_repo_status_payload(
status_path,
{
"version": STATUS_VERSION,
"clone": {
"state": CLONE_STATE_SKIPPED_LFS,
"last_attempt_at": checked_at_timestamp(),
},
},
)
def has_lfs_skip_status(status_path: Path) -> bool:
"""Return True when the sidecar records a permanent Git-LFS skip."""
clone_status = read_repo_status_payload(status_path).get("clone")
if not isinstance(clone_status, dict):
return False
return clone_status.get("state") == CLONE_STATE_SKIPPED_LFS
def delete_repo_status(status_path: Path) -> None:
"""Remove a repo status sidecar when present."""
if status_path.exists():
status_path.unlink()
def status_str(status: dict[str, object], key: str) -> str | None:
"""Return a string field from repo status metadata when present."""
value = status.get(key)
return value if isinstance(value, str) else None
def status_int(status: dict[str, object], key: str) -> int | None:
"""Return an integer field from repo status metadata when present."""
value = status.get(key)
return value if isinstance(value, int) else None
def resolve_exact_sft_task_target(
prompt_path: str | Path,
repo_path: str | Path,
commits_root: Path,
) -> ExactSftTaskTarget:
parsed = parse_exact_sft_task_path(prompt_path)
output_dir = parsed.prompt_path.parent
repo_slug = repo_slug_from_repo_path(repo_path)
excluded_files = read_repo_excluded_files(
commits_root,
repo_slug,
warn_if_missing=False,
)
return ExactSftTaskTarget(
sha=parsed.sha,
variant_index=parsed.variant_index,
prompt_path=parsed.prompt_path,
output_dir=output_dir,
repo_slug=repo_slug,
excluded_files=excluded_files,
)
def read_json_object(path: Path) -> object | None:
if not path.exists():
return None
try:
raw_data = json.loads(path.read_text(encoding="utf-8"))
except (OSError, json.JSONDecodeError):
return None
return raw_data
def extract_result_payload(file_data: object) -> dict:
"""
Extract the metric payload from a result JSON object.
Some historical result files nest the final run payload under ``history[-1]``.
"""
if (
isinstance(file_data, dict)
and "stopReason" not in file_data
and isinstance(file_data.get("history"), list)
and file_data["history"]
and isinstance(file_data["history"][-1], dict)
):
return file_data["history"][-1]
return file_data if isinstance(file_data, dict) else {}
def read_result_payload(path: Path) -> dict:
file_data = read_json_object(path)
if file_data is None:
return {}
return extract_result_payload(file_data)
def read_result_stop_reason(path: Path) -> str | None:
payload = read_result_payload(path)
stop_reason = payload.get("stopReason")
if isinstance(stop_reason, str):
changed_files = payload.get("changedFiles")
if stop_reason == STOP_REASON_SUCCESS and isinstance(changed_files, list) and len(changed_files) == 0:
return STOP_REASON_NO_EDITS
return stop_reason
return None
def is_incomplete_stop_reason(stop_reason: str | None) -> bool:
"""
Return whether a stop reason represents an incomplete placeholder result.
"""
return stop_reason == STOP_REASON_STARTED
def outcome_token(stop_reason: str | None) -> str:
"""
Normalize a stop reason into one of success/tests_failed/agent_failed.
"""
if stop_reason == STOP_REASON_SUCCESS:
return RUN_OUTCOME_SUCCESS
if stop_reason in (STOP_REASON_HARNESS_TESTS_FAILED, STOP_REASON_PREBUILD_FAILED):
return RUN_OUTCOME_TESTS_FAILED
return RUN_OUTCOME_AGENT_FAILED
def should_run_in_rerun_mode(
rerun_mode: str,
run_number: int,
previous_outcome: str | None,
) -> bool:
"""
Decide if a run should execute for a given rerun mode.
"""
if run_number == 1:
return True
if rerun_mode == "all":
return True
return previous_outcome != RUN_OUTCOME_SUCCESS
def safe_nonnegative_int(value: object) -> int:
"""
Convert value to a non-negative int, defaulting to 0 on invalid input.
"""
if isinstance(value, (int, float)):
return max(0, int(value))
return 0
def safe_nonnegative_float(value: object) -> float:
"""
Convert value to a non-negative finite float, defaulting to 0.0 on invalid input.
"""
if isinstance(value, (int, float)):
parsed = float(value)
if math.isfinite(parsed):
return max(0.0, parsed)
return 0.0
def _normalize_scan_hash(value: object) -> str | None:
if not isinstance(value, str):
return None
candidate = value.strip().lower()
if _SCAN_HASH_RE.fullmatch(candidate):
return candidate
return None
def _scan_record_from_payload(payload: dict) -> ScanRecord | None:
hash_value = _normalize_scan_hash(payload.get("hash"))
if hash_value is None:
return None
test_files = safe_nonnegative_int(payload.get("test_files", 0))
non_test_files = safe_nonnegative_int(payload.get("non_test_files", 0))
code_files = safe_nonnegative_int(payload.get("code_files", test_files + non_test_files))
total_files = safe_nonnegative_int(payload.get("total_files", code_files))
token_count = safe_nonnegative_int(payload.get("token_count", 0))
hunks = safe_nonnegative_int(payload.get("hunks", 0))
insertion_hunks = safe_nonnegative_int(payload.get("insertion_hunks", 0))
non_test_hunks = safe_nonnegative_int(payload.get("non_test_hunks", 0))
non_test_insertion_hunks = safe_nonnegative_int(payload.get("non_test_insertion_hunks", 0))
insertion_lines = safe_nonnegative_int(payload.get("insertion_lines", 0))
non_test_insertion_lines = safe_nonnegative_int(payload.get("non_test_insertion_lines", 0))
non_code_files = safe_nonnegative_int(payload.get("non_code_files", max(0, total_files - code_files)))
total_changed_lines = safe_nonnegative_int(payload.get("total_changed_lines", 0))
non_code_changed_lines = safe_nonnegative_int(payload.get("non_code_changed_lines", 0))
oneline = payload.get("oneline", "")
return ScanRecord(
hash=hash_value,
oneline=oneline if isinstance(oneline, str) else "",
test_files=test_files,
non_test_files=non_test_files,
code_files=code_files,
total_files=total_files,
token_count=token_count,
hunks=hunks,
insertion_hunks=insertion_hunks,
non_test_hunks=non_test_hunks,
non_test_insertion_hunks=non_test_insertion_hunks,
insertion_lines=insertion_lines,
non_test_insertion_lines=non_test_insertion_lines,
non_code_files=non_code_files,
total_changed_lines=total_changed_lines,
non_code_changed_lines=non_code_changed_lines,
)
def parse_scan_record_line(line: str) -> ScanRecord | None:
stripped = line.strip()
if not stripped:
return None
if stripped.startswith("{"):
try:
payload = json.loads(stripped)
except json.JSONDecodeError:
return None
if isinstance(payload, dict):
return _scan_record_from_payload(payload)
return None
match = _LEGACY_SCAN_LINE_RE.match(stripped)
if match is None:
return None
hash_value = match.group("sha").lower()
first = int(match.group("first"))
second = int(match.group("second"))
third = int(match.group("third"))
summary = match.group("summary")
if first > second or first == second or third < 20 or third > 200:
code_files = first
total_files = second
token_count = third
return ScanRecord(
hash=hash_value,
oneline=summary,
test_files=0,
non_test_files=code_files,
code_files=code_files,
total_files=total_files,
token_count=token_count,
hunks=0,
insertion_hunks=0,
non_test_hunks=0,
non_test_insertion_hunks=0,
insertion_lines=0,
non_test_insertion_lines=0,
)
test_files = first
total_files = second
insertion_lines = third
non_test_files = max(0, total_files - test_files)
return ScanRecord(
hash=hash_value,
oneline=summary,
test_files=test_files,
non_test_files=non_test_files,
code_files=total_files,
total_files=total_files,
token_count=0,
hunks=0,
insertion_hunks=0,
non_test_hunks=0,
non_test_insertion_hunks=0,
insertion_lines=insertion_lines,
non_test_insertion_lines=0,
)
def iter_scan_records(lines: Iterable[str]) -> Iterable[ScanRecord]:
for line in lines:
record = parse_scan_record_line(line)
if record is not None:
yield record
def read_scan_records(path: Path) -> list[ScanRecord]:
if not path.exists():
return []
with path.open(encoding="utf-8") as handle:
return list(iter_scan_records(handle))
def iter_scan_hashes(lines: Iterable[str]) -> Iterable[str]:
seen: set[str] = set()
for line in lines:
record = parse_scan_record_line(line)
if record is not None:
if record.hash not in seen:
seen.add(record.hash)
yield record.hash
continue
candidate = line.strip().split(maxsplit=1)[0].lower() if line.strip() else ""
if _SCAN_HASH_RE.fullmatch(candidate) and candidate not in seen:
seen.add(candidate)
yield candidate
def read_scan_hashes(path: Path) -> list[str]:
if not path.exists():
return []
with path.open(encoding="utf-8") as handle:
return list(iter_scan_hashes(handle))
def write_scan_records(path: Path, records: Iterable[ScanRecord]) -> None:
path.parent.mkdir(parents=True, exist_ok=True)
rows = [
json.dumps(record.__dict__, ensure_ascii=False, sort_keys=True)
for record in records
]
path.write_text(
"\n".join(rows) + ("\n" if rows else ""),
encoding="utf-8",
)
def difficulty_adjusted_task_score(final_success: bool, build_failures: object) -> float:
"""
Return the per-task score used by results aggregation.
"""
if not final_success:
return 0.0
return 1.0 / math.log2(safe_nonnegative_int(build_failures) + 2)
def extract_run_metrics(
model: str,
revision: str,
raw_payload: dict,
run_number: int,
) -> dict:
data = extract_result_payload(raw_payload)
stop_reason = str(data.get("stopReason", ""))
reasoning_output = data.get(
"reasoningOutputTokens",
data.get(
"reasoning_output_tokens",
data.get("reasoningTokens", data.get("reasoning_tokens", 0)),
),
)
return {
"run_number": run_number,
"success": stop_reason == STOP_REASON_SUCCESS,
"stop_reason": stop_reason,
"worktree": str(data.get("worktree", "")),
"input_tokens": safe_nonnegative_int(data.get("inputTokens", 0)),
"output_tokens": safe_nonnegative_int(data.get("outputTokens", 0)),
"cached_input_tokens": safe_nonnegative_int(data.get("cachedInputTokens", 0)),
"reasoning_input_tokens": safe_nonnegative_int(
data.get("reasoningInputTokens", data.get("reasoning_input_tokens", 0))
),
"reasoning_output_tokens": safe_nonnegative_int(reasoning_output),
"build": safe_nonnegative_int(data.get("buildFailures", 0)),
"parse": safe_nonnegative_int(data.get("parseRetries", 0)),
"apply": safe_nonnegative_int(data.get("applyRetries", 0)),
"api": safe_nonnegative_int(data.get("apiRetries", 0)),
"turns": safe_nonnegative_int(data.get("editBlocksTotal", 0)),
"elapsed": safe_nonnegative_int(data.get("elapsedMillis", data.get("totalMillis", 0))),
"llm": safe_nonnegative_int(data.get("llmMillis", 0)),
"cost": None,
"model": model,
"revision": revision,
}
def _iter_hashes(paths: Iterable[str]) -> Iterable[str]:
for raw_path in paths:
path_str = raw_path.strip()
if not path_str:
continue
yield parse_path(path_str).hash
# --------------------------------------------------------------------------- #
# testsome binding outcomes (moved from p2t/core/instance.py).
# --------------------------------------------------------------------------- #
def read_testsome_outcomes(commits_dir: Path, lang: str, repo_slug: str) -> dict[str, dict]:
"""Per-sha testsome binding-validation records, keyed by sha. The
``.testsome.jsonl`` sidecar is the source of truth for whether a commit's
tests bind; ``outcome == "binding"`` is the runnable gate (see ``is_binding``)."""
path = commits_dir / lang / f"{repo_slug}{TESTSOME_SIDECAR_SUFFIX}"
if not path.exists():
return {}
records: dict[str, dict] = {}
for line in path.read_text(encoding="utf-8").splitlines():
if line.strip():
record = json.loads(line)
records[record["sha"]] = record
return records
def is_binding(record: dict | None) -> bool:
"""True iff a testsome record (from ``read_testsome_outcomes``) is the runnable
binding outcome. ``None`` (no testsome data for the sha) is NOT binding."""
return bool(record) and record.get("outcome") == "binding"
def is_settled_testsome_outcome(record: dict | None) -> bool:
"""True when a testsome sidecar row is a real validation result.
``toolchain_drift`` was a pre-validation heuristic written by older production
runs. It did not execute the task against the template, so the bind pipeline must
treat it as retryable and let the measured validator outcome overwrite it.
"""
return bool(record) and record.get("outcome") != "toolchain_drift"
def is_bind_eligible(record: ScanRecord) -> bool:
"""A commit can F2P-bind only if it changes BOTH test and non-test files — a fix
(code) plus the test that exercises it. Pure-code commits render a not_applicable
(empty) test command; pure-test commits have no code change to discriminate.
This is the SINGLE definition of bind-eligibility. Both the bind FEED
(find_all_repos, which signals a repo has bind work) and the bind VALIDATOR
(validate_bindings, which decides a repo needs a VM) must agree on it — if they
drift, the feed signals shas the validator refuses and every dispatch fast-exits
NO_CANDIDATE without doing work."""
return record.test_files > 0 and record.non_test_files > 0
def testsome_command(record: dict | None) -> str | None:
"""The validated per-sha test command from a testsome record, or None."""
if not record:
return None
command = record.get("command")
return command if isinstance(command, str) and command else None
# --------------------------------------------------------------------------- #
# P2T VM portability lint (shared by the firehose derivation screen and the
# build-script authoring-acceptance gate).
#
# A recorded/rendered testsome command runs on the P2T ORACLE VM, which checks the
# repo out at a different prefix than the sft-tools AUTHORING VM. run_p2t's
# make_task_bundle rewrites exactly ONE prefix,
# ``/home/ubuntu/sft-build/<slug>/repo`` -> the P2T repo dir; any OTHER absolute
# path baked into the command (e.g. a ``run_tests.sh`` living beside ``<slug>/repo``
# but NOT under it — the burn that cost domaindrivendev__Swashbuckle.AspNetCore two
# batches) is never rewritten and does not exist on the P2T VM, so the command
# fails "No such file" -> oracle_failed. This lint flags those before they burn.
#
# It lives here (not run_p2t) so the corpus screen and the sft_tooluse authoring
# gate share ONE definition with no p2t<->sft_tooluse import edge.
# --------------------------------------------------------------------------- #
# Mirrors run_p2t.SFT_TOOLS_VM_BUILD_ROOT (the sft-tools authoring VM checkout
# root). Duplicated as a literal to avoid a tasks.py -> p2t.infra.run_p2t import
# cycle (run_p2t imports tasks, not the reverse).
SFT_TOOLS_VM_BUILD_ROOT = "/home/ubuntu/sft-build"
# The build user's HOME on the VMs; build scripts writing under $HOME / ~ land
# here, so a command path under it is "provisioned" when the (HOME-normalized)
# build script mentions it.
VM_BUILD_HOME = "/home/ubuntu"
# Absolute paths under these roots are policed; anything else is host-agnostic.
_ABS_PATH_RE = re.compile(r"(?:/opt|/srv|/home/ubuntu)(?:/[^\s'\"`;:|)&>]*)?")
@dataclass(frozen=True)
class PortabilityFinding:
command: str
path: str
reason: str
def _home_normalize(text: str) -> str:
"""Rewrite every ``$HOME`` / ``${HOME}`` / ``"$HOME"`` / leading-``~/`` spelling
to the concrete VM home so a script's ``mkdir $HOME/.cache`` matches a command's
literal ``/home/ubuntu/.cache``."""
text = text.replace('"$HOME"', VM_BUILD_HOME).replace("${HOME}", VM_BUILD_HOME)
text = text.replace("$HOME", VM_BUILD_HOME)
return re.sub(r"(?<![\w/])~(?=/)", VM_BUILD_HOME, text)
def _is_provisioned(path: str, provisioned: list[str]) -> bool:
"""True iff ``path`` is created/populated by build.sh: it equals, or shares a
parent/child prefix with, some absolute path the (normalized) script names."""
for candidate in provisioned:
candidate = candidate.rstrip("/") or candidate
if path == candidate or path.startswith(candidate + "/") or candidate.startswith(path + "/"):
return True
return False
def lint_command_portability(
commands: Iterable[str],
build_script_text: str,
repo_slug: str,
) -> list[PortabilityFinding]:
"""Absolute paths in ``commands`` that will not exist on the P2T oracle VM.
A path under ``/opt``/``/srv``/``/home/ubuntu`` is portable iff EITHER
(a) it is inside ``/home/ubuntu/sft-build/<slug>/repo`` — make_task_bundle
rewrites that prefix to the P2T repo dir; OR
(b) it is provisioned by the build script — the HOME-normalized script text
names the path (or a parent/child), so running build.sh on the P2T VM
creates it.
Every other such path yields a ``PortabilityFinding``. ``commands`` are the
recorded (firehose screen) or rendered (authoring gate) testsome commands; an
empty list means portable."""
rewrite_prefix = f"{SFT_TOOLS_VM_BUILD_ROOT}/{repo_slug}/repo"
provisioned = _ABS_PATH_RE.findall(_home_normalize(build_script_text or ""))
findings: list[PortabilityFinding] = []
seen: set[tuple[str, str]] = set()
for command in commands:
if not command:
continue
for raw in _ABS_PATH_RE.findall(_home_normalize(command)):
path = raw.rstrip("/") or raw
if path == rewrite_prefix or path.startswith(rewrite_prefix + "/"):
continue # (a) bundle rewrites this prefix
if _is_provisioned(path, provisioned):
continue # (b) build.sh creates it
key = (command, path)
if key in seen:
continue
seen.add(key)
findings.append(
PortabilityFinding(
command=command,
path=path,
reason=(
f"absolute path {path!r} is neither under the rewritten "
f"{rewrite_prefix!r} nor provisioned by build.sh; it will not "
f"exist on the P2T oracle VM"
),
)
)
return findings
def era_for(record: dict | None) -> str | None:
"""The build era a testsome sidecar record belongs to, or ``None`` for the HEAD
era. A row's optional ``"era"`` field (``"era-<anchor12>"``) rides along on the
binding record; an absent or empty field ⇒ HEAD era. The entire current corpus
carries no era field, so every existing record resolves to ``None`` — the
backward-compat anchor for the whole era feature (see BUILD_ERAS.md §1)."""
if not record:
return None
era = record.get("era")
return era if isinstance(era, str) and era else None
def _era_stem(repo_slug: str, era: str | None) -> str:
"""Filename stem for a repo's b+t artifacts in a given era. ``None`` (HEAD era)
⇒ the bare slug (``<slug>``); an older era ⇒ ``<slug>.<era>`` so the suffixed
files sort beside the HEAD-era ones. Absent-suffix = HEAD era everywhere."""
return repo_slug if era is None else f"{repo_slug}.{era}"
def build_script_path(
lang: str,
repo_slug: str,
commits_dir: Path = DEFAULT_COMMITS_DIR,
era: str | None = None,
) -> Path | None:
"""Per-repo build script path when the sft_tooluse build pass produced one.
``era`` selects an older era's suffixed script (``<slug>.<era>.sh``); the
default ``era=None`` resolves the HEAD-era ``<slug>.sh`` — byte-identical to
the prior signature and behavior."""
path = commits_dir / lang / f"{_era_stem(repo_slug, era)}.sh"
return path if path.exists() else None
def template_path(
lang: str,
repo_slug: str,
commits_dir: Path = DEFAULT_COMMITS_DIR,
era: str | None = None,
) -> Path | None:
"""Per-repo testsome template path (``<slug>.testsome``), era-suffixed to
``<slug>.<era>.testsome`` when ``era`` is given. ``era=None`` ⇒ HEAD era.
Mirrors ``build_script_path``; returns ``None`` when the template is absent."""
path = commits_dir / lang / f"{_era_stem(repo_slug, era)}.testsome"
return path if path.exists() else None
# --------------------------------------------------------------------------- #
# repo language lookup (moved from p2t/core/instance.py: find_repo_lang).
# --------------------------------------------------------------------------- #
# Per-file binding-count cache, validated by (mtime_ns, size) on every lookup so a
# status/sidecar rewrite by the binding feed mid-process is observed immediately.
_BINDING_COUNT_CACHE: dict[Path, tuple[tuple[int, int], int]] = {}
def _cached_binding_count(path: Path, count_fn) -> int:
"""(mtime_ns, size)-validated cache of one file's binding count. Absent or
unreadable/corrupt files count 0 — a broken corpus file must not crash repo
enumeration; that bucket simply competes with zero binds."""
try:
stat = path.stat()
except OSError:
return 0
stamp = (stat.st_mtime_ns, stat.st_size)
cached = _BINDING_COUNT_CACHE.get(path)
if cached is not None and cached[0] == stamp:
return cached[1]
try:
count = count_fn(path)
except (OSError, ValueError):
count = 0
_BINDING_COUNT_CACHE[path] = (stamp, count)
return count
def _status_binding_count(path: Path) -> int:
outcomes = json.loads(path.read_text(encoding="utf-8")).get("testsome_task_outcomes") or {}
return int(outcomes.get("binding", 0) or 0)
def _sidecar_binding_count(path: Path) -> int:
count = 0
for line in path.read_text(encoding="utf-8").splitlines():
if line.strip() and json.loads(line).get("outcome") == "binding":
count += 1
return count
def _repo_binding_count(commits_dir: Path, lang: str, repo_slug: str) -> int:
"""Validated binding-outcome count for one ``(lang, repo)`` bucket: the max of
the live ``.testsome.jsonl`` sidecar count and the ``status.json``
``testsome_task_outcomes`` aggregate. The two sources drift (sidecars get
cleared, aggregates lag behind fresh validation), so either alone under-counts.
"""
lang_dir = commits_dir / lang
return max(
_cached_binding_count(
lang_dir / f"{repo_slug}{TESTSOME_SIDECAR_SUFFIX}", _sidecar_binding_count
),
_cached_binding_count(lang_dir / f"{repo_slug}.status.json", _status_binding_count),
)
def _canonical_language_key(commits_dir: Path, repo_slug: str, lang: str) -> tuple:
"""Composite canonicalization key: most validated binds first, then the fixed
``DEFAULT_LANGUAGES`` preference order as the tie-break."""
return (
-_repo_binding_count(commits_dir, lang, repo_slug),
*_language_preference_key(lang),
)
def repo_langs(commits_dir: Path, repo_slug: str) -> tuple[str, ...]:
"""Every language dir holding ``<repo_slug>.jsonl``, ordered by validated
binding-outcome count (descending), then canonical preference order."""
matches = sorted(
(
path.parent.name
for path in commits_dir.glob(f"*/{repo_slug}.jsonl")
if not path.name.endswith(TESTSOME_SIDECAR_SUFFIX)
),
key=lambda lang: _canonical_language_key(commits_dir, repo_slug, lang),
)
if not matches:
raise FileNotFoundError(f"No {repo_slug}.jsonl under {commits_dir}")
return tuple(matches)
def repo_lang(commits_dir: Path, repo_slug: str) -> str:
"""Canonical language for ``repo_slug``.
When a repo is listed under multiple language directories, the canonical bucket
is the one with the MOST validated binding outcomes (sidecar or status.json
aggregate, whichever is higher); ties fall back to ``DEFAULT_LANGUAGES`` order,
then unknown languages alphabetically. Rationale: a 2026-07 audit of all 818
dual-classified repos found the scan pipeline had registered duplicate,
often mislabeled buckets per repo, and the fixed-priority rule frequently
stranded the only bucket with real binding data (argo-cd selected 0 tasks while
its js bucket held 266 validated binds). Canonical now follows validated data;
with no binding data anywhere the old priority behavior is unchanged.
``iter_repos`` and task selection use the same rule so each repo contributes
tasks through exactly one language.
"""
return repo_langs(commits_dir, repo_slug)[0]
# --------------------------------------------------------------------------- #
# task prompts / properties / variants / metadata (sfttasks/). Unifies readers
# previously duplicated across p2t/core/instance.py and sft_gen.py.
# --------------------------------------------------------------------------- #
def prompt_path_for(sfttasks_dir: Path, sha: str, variant: int | None = None) -> Path | None:
"""Resolve a task prompt path. ``variant`` pins ``<sha>-<variant>.txt``;
otherwise the default convention ``<sha>-1.txt`` then ``<sha>.txt``."""
if variant is not None:
candidate = sfttasks_dir / f"{sha}-{variant}.txt"
return candidate if candidate.exists() else None
for candidate in (sfttasks_dir / f"{sha}-1.txt", sfttasks_dir / f"{sha}.txt"):
if candidate.exists():
return candidate
return None
def task_variant_paths(sfttasks_dir: Path, sha: str) -> tuple[Path, ...]:
"""All ``<sha>-<n>.txt`` prompt variants for a commit, ordered by index."""
indexed: list[tuple[int, Path]] = []
for path in sfttasks_dir.glob(f"{sha}-*.txt"):
match = re.fullmatch(rf"{re.escape(sha)}-(\d+)\.txt", path.name)
if match:
indexed.append((int(match.group(1)), path))
return tuple(path for _, path in sorted(indexed))
def index_prompt_variant_one(sfttasks_dir: Path) -> dict[str, Path]:
"""Map ``{40-hex sha: <sha>-1.txt path}`` for every primary-variant prompt in
*sfttasks_dir*. One glob for callers that need O(1) sha->prompt lookup or the
set of prompt-backed shas (use ``.keys()``)."""
index: dict[str, Path] = {}
for path in sfttasks_dir.glob("*-1.txt"):
match = re.fullmatch(r"([0-9a-f]{40})-1\.txt", path.name)
if match:
index[match.group(1)] = path
return index
def read_task_properties(prompt_path: Path) -> dict[str, str]:
"""Key=value ``.properties`` sidecar beside a prompt (e.g. ``files=…``)."""
properties: dict[str, str] = {}
properties_path = prompt_path.with_suffix(".properties")
if not properties_path.exists():
return properties
for line in properties_path.read_text(encoding="utf-8").splitlines():
stripped = line.strip()
if not stripped or "=" not in stripped:
continue
key, value = stripped.split("=", 1)
properties[key.strip()] = value.strip()
return properties
def parse_property_list(value: str) -> tuple[str, ...]:
"""Comma-separated dedup'd list (e.g. a ``.properties`` ``files=`` value)."""
items: list[str] = []
seen: set[str] = set()
for raw in value.split(","):
item = raw.strip()
if not item or item in seen:
continue
seen.add(item)
items.append(item)
return tuple(items)
def related_file_names(prompt_path: Path) -> tuple[str, ...]:
"""RAW ``files=`` list from a task's ``.properties`` (no consumer filtering —
callers apply their own, e.g. p2t's non-test/bifrost-parseable gate)."""
return parse_property_list(read_task_properties(prompt_path).get("files", ""))
def read_task_metadata(sfttasks_dir: Path, sha: str) -> dict:
"""The ``<sha>.json`` generation-metadata sidecar (empty dict if absent)."""
data = read_json_object(sfttasks_dir / f"{sha}.json")
return data if isinstance(data, dict) else {}
def write_task_metadata(sfttasks_dir: Path, sha: str, metadata: dict) -> None:
"""Atomically (temp + replace) write the ``<sha>.json`` metadata sidecar."""
path = sfttasks_dir / f"{sha}.json"
with task_metadata_file_lock(path):
path.parent.mkdir(parents=True, exist_ok=True)
temp_path = path.with_name(
f".{path.name}.{os.getpid()}.{threading.get_ident()}.{time.time_ns()}.tmp"
)
temp_path.write_text(
json.dumps(metadata, ensure_ascii=False, indent=2, sort_keys=True),
encoding="utf-8",
)
temp_path.replace(path)
def update_task_metadata(sfttasks_dir: Path, sha: str, update: Callable[[dict], None]) -> dict:
"""Serialize a read/modify/write update to one ``<sha>.json`` sidecar."""
path = sfttasks_dir / f"{sha}.json"
with task_metadata_file_lock(path):
metadata = read_task_metadata(sfttasks_dir, sha)
update(metadata)
write_task_metadata(sfttasks_dir, sha, metadata)
return metadata
# Top-level ``<sha>.json`` key marking a task's tests as NON-fragile (blind-solvable).
# The scan-time accept filter (scan_commits_sft) now rejects blind-unsolvable commits,
# so every task generated AFTER that filter landed is tagged True at generate time
# (`generate.py` success path) to distinguish it from older, never-fragility-scanned
# tasks. A deeper recheck pass (oneoffs/reclassify_test_fragility.py) backfills the
# rest, tagging the ones it judges fragile as False instead of deleting them.
NON_FRAGILE_TESTS_KEY = "non_fragile_tests"
def read_non_fragile_tests(sfttasks_dir: Path, sha: str) -> bool | None:
"""The task's non-fragile-tests verdict, or None when never classified.
A present key (True or False) means the task has been judged, so a resuming
classification pass skips it; None means it has not been tagged yet."""
value = read_task_metadata(sfttasks_dir, sha).get(NON_FRAGILE_TESTS_KEY)
return value if isinstance(value, bool) else None
def set_non_fragile_tests(sfttasks_dir: Path, sha: str, value: bool) -> None:
"""Tag the task's ``<sha>.json`` with the (top-level) non-fragile-tests verdict."""
def update(metadata: dict) -> None:
metadata[NON_FRAGILE_TESTS_KEY] = value
update_task_metadata(sfttasks_dir, sha, update)
# Top-level ``<sha>.json`` key holding the SFT quality-gate rubric scores: the four 1-5
# dimensions (supervision_value / difficulty / leakage_risk / localization_obviousness) plus
# a ``reasoning`` string. ``generate.py``'s quality gate writes this for every commit it
# judges (kept OR rejected), so a present block means the commit was scored and a resuming
# run can skip re-scoring it.
TASK_SCORES_KEY = "scores"
# Top-level ``<sha>.json`` key naming the model that produced the current ``scores`` block.
# Lets a resuming gate skip only the commits already judged by the authoritative grader
# (gpt-5.4) and re-grade everything else (unscored OR scored by a retired cheap model).
EVALUATED_BY_KEY = "evaluated_by"
def read_task_scores(sfttasks_dir: Path, sha: str) -> dict | None:
"""The task's quality-gate rubric scores, or None when never scored.
A present dict means the gate already judged this commit (so a resuming generation run
skips it); None means it has not been scored yet."""
value = read_task_metadata(sfttasks_dir, sha).get(TASK_SCORES_KEY)
return value if isinstance(value, dict) else None
def read_task_evaluated_by(sfttasks_dir: Path, sha: str) -> str | None:
"""The model that produced the task's current ``scores`` (None if unscored/untagged)."""
value = read_task_metadata(sfttasks_dir, sha).get(EVALUATED_BY_KEY)
return value if isinstance(value, str) else None
def set_task_scores(sfttasks_dir: Path, sha: str, scores: dict, evaluated_by: str | None = None) -> None:
"""Write the quality-gate rubric ``scores`` block into the task's ``<sha>.json`` (and the
``evaluated_by`` grader tag in the same atomic metadata update when provided)."""
def update(metadata: dict) -> None:
metadata[TASK_SCORES_KEY] = scores
if evaluated_by is not None:
metadata[EVALUATED_BY_KEY] = evaluated_by
update_task_metadata(sfttasks_dir, sha, update)
# --------------------------------------------------------------------------- #
# sft-tools repo selection / ranking (moved from generate_core.py — single home).
# --------------------------------------------------------------------------- #
def large_repo_set(commits_dir: Path = DEFAULT_COMMITS_DIR) -> set[str]:
"""Repo slugs excluded for size (the ``large-repos.csv`` membership). A missing
file means none are recorded yet (same corpus lifecycle as ``repos.csv`` in
``build_times``), so it yields the empty set rather than raising."""
path = commits_dir / "large-repos.csv"
if not path.exists():
return set()
return _read_repo_column_csv(path)
def _read_repo_column_csv(path: Path) -> set[str]:
with path.open(newline="", encoding="utf-8") as handle:
reader = csv.DictReader(handle)
if reader.fieldnames is None or "repo" not in reader.fieldnames:
raise ValueError(f"{path} must have a repo column")
return {row["repo"] for row in reader if row.get("repo")}
def build_times(commits_dir: Path = DEFAULT_COMMITS_DIR) -> dict[str, float]:
"""Per-repo build time (seconds) from ``repos.csv`` — the ranking proxy. Returns a
fresh, MUTABLE dict; use ``build_times_cached`` for hot read-only lookups."""
return _read_sft_tools_build_times(commits_dir)
@functools.lru_cache(maxsize=16)
def _build_times_by_mtime(commits_dir_str: str, _mtime_ns: int) -> Mapping[str, float]:
# _mtime_ns is part of the cache key ONLY — it changes when repos.csv is appended,
# evicting the stale entry. The value is read-only (MappingProxyType) so a caller can
# never poison the shared cache by mutating it.
return MappingProxyType(_read_sft_tools_build_times(Path(commits_dir_str)))
def build_times_cached(commits_dir: Path = DEFAULT_COMMITS_DIR) -> Mapping[str, float]:
"""``build_times`` parsed ONCE and cached by ``repos.csv`` mtime, reused until the
build pipeline appends a new build time (bumping mtime invalidates the entry). Use
this for hot, repeated read-only lookups — e.g. per-repo membership — instead of
re-scanning the CSV on every call (an O(n) scan per call is an O(n^2) footgun across a
per-repo sweep). The result is READ-ONLY; copy it if you need to mutate."""
path = commits_dir / "repos.csv"
try:
mtime_ns = path.stat().st_mtime_ns
except OSError:
return {}
return _build_times_by_mtime(str(commits_dir), mtime_ns)
def _read_sft_tools_build_times(commits_dir: Path) -> dict[str, float]:
path = commits_dir / "repos.csv"
build_times: dict[str, float] = {}
if not path.exists():
return build_times # no build-time proxy yet — callers fall back to slug order
with path.open(newline="", encoding="utf-8") as handle:
reader = csv.DictReader(handle)
if reader.fieldnames is None or "repo" not in reader.fieldnames:
raise ValueError(f"{path} must have a repo column")
if "build_time" not in reader.fieldnames:
raise ValueError(f"{path} must have a build_time column")
for row in reader:
repo = row.get("repo", "")
raw_build_time = (row.get("build_time", "") or "").strip()
if not repo or not raw_build_time:
continue
try:
build_time = float(raw_build_time)
except ValueError:
continue
if build_time < 0:
continue
build_times[repo] = build_time
return build_times
def _sft_tools_skipped_repos(commits_dir: Path) -> set[str]:
skipped: set[str] = set()
for path in commits_dir.glob("*/*.status.json"):
if read_repo_status_payload(path).get("testsome_skipped"):
skipped.add(path.name.removesuffix(".status.json"))
return skipped
def select_sft_task_threshold(
task_counts: Iterable[int],
*,
thresholds: Iterable[int],
target_task_count: int,
) -> int | None:
threshold_values = sorted({int(value) for value in thresholds}, reverse=True)
if target_task_count < 1:
raise ValueError("target_task_count must be >= 1")
if not threshold_values or any(value < 1 for value in threshold_values):
raise ValueError("thresholds must contain positive integers")
counts = list(task_counts)
for threshold in threshold_values:
total = sum(count for count in counts if count >= threshold)
if total >= target_task_count:
return threshold
return None
def _repos_by_lang(
commits_dir: Path, langs: Iterable[str] | None = None
) -> dict[str, list[str]]:
by_lang: dict[str, list[str]] = {}
for lang, repo in iter_repos(commits_dir, langs):
by_lang.setdefault(lang, []).append(repo)
return by_lang
def iter_repos(
commits_dir: Path = DEFAULT_COMMITS_DIR, langs: Iterable[str] | None = None
) -> Iterable[tuple[str, str]]:
"""Every ``(lang, repo_slug)`` with a candidate ``.jsonl`` (NO filtering —
the unfiltered enumeration; callers add their own filters or use the
predicate selection helpers). Skips the ``.testsome.jsonl`` sidecars. If a
repo appears under multiple language dirs, yields it once using ``repo_lang``'s
canonical rule (most validated binds, then preference order).
``langs`` RESTRICTS BEFORE canonicalization: the repo is yielded under its
best bucket AMONG the requested languages. (The old
globally-canonicalize-then-filter behavior silently dropped a repo from
``langs=[X]`` queries whenever some other language dir won canonical — which
both blinded ``validate_bindings --language`` to shadowed buckets and broke
per-language task planning for dual-classified repos.)"""
wanted = set(langs) if langs is not None else None
preferred_by_repo: dict[str, str] = {}
for jsonl in sorted(commits_dir.glob("*/*.jsonl")):
if jsonl.name.endswith(TESTSOME_SIDECAR_SUFFIX):
continue
lang = jsonl.parent.name
if wanted is not None and lang not in wanted:
continue
repo = jsonl.stem
previous = preferred_by_repo.get(repo)
if previous is None or (
_canonical_language_key(commits_dir, repo, lang)
< _canonical_language_key(commits_dir, repo, previous)
):
preferred_by_repo[repo] = lang
for repo, lang in sorted(preferred_by_repo.items(), key=lambda item: (_language_preference_key(item[1]), item[0])):
yield lang, repo
def repo_scan_records(commits_dir: Path, lang: str, repo_slug: str) -> list[ScanRecord]:
"""Candidate commit records for one repo (``<lang>/<repo>.jsonl``)."""
return read_scan_records(commits_dir / lang / f"{repo_slug}.jsonl")
# --------------------------------------------------------------------------- #
# Composable selection — the predicate engine. ONE vocabulary, two projections
# (task_repos / task_shas). Replaces the ad-hoc selectors that were scattered
# across find_all_repos / generate / localizer / p2t. The repo gates and the
# per-sha task gates compose; `min_tasks_per_repo` bridges them by counting the
# task-predicate matches per repo BEFORE applying its own threshold.
# --------------------------------------------------------------------------- #
# Auto-progression floors for the per-repo task threshold (highest first). `10`
# is the floor used by `find_all_repos --mode sft`.
SFT_TASK_THRESHOLDS = (100, 50, 25, 10)
@dataclass(frozen=True)
class Predicates:
# --- repo-scoped ---
not_overlarge: bool = False # repo not in large-repos.csv
builds: bool = False # repo has a recorded build (repos.csv build_time)
has_testsome: bool = False # repo has a testsome sidecar (testsome ran) -> builds
not_skipped: bool = False # repo not manually testsome_skipped
min_tasks_per_repo: int | None = None # keep repos with >= N task-predicate matches
# --- task/sha-scoped ---
binding: bool = False # live .testsome.jsonl outcome == "binding" -> has_testsome
generated: bool = False # a prompt variant exists (task IS its prompt)
non_fragile_tests: bool = False # <sha>.json non_fragile_tests is STRICTLY True
include_variants: bool = False # include non-primary -n variants; else primary -1 only
def resolved(self) -> Predicates:
"""Apply prerequisites: binding => has_testsome => builds."""
has_testsome = self.has_testsome or self.binding
builds = self.builds or has_testsome
return replace(self, builds=builds, has_testsome=has_testsome)
@dataclass(frozen=True)
class TaskRef:
lang: str
repo_slug: str
sha: str
variant: int
oneline: str
prompt_path: Path | None
test_command: str | None # validated per-sha binding command, or None
@dataclass(frozen=True)
class RepoRef:
lang: str
repo_slug: str
task_count: int # task-predicate matches in the repo (pre-threshold)
def scan_records_path(commits_dir: Path, lang: str, repo_slug: str) -> Path:
"""Canonical scan-record JSONL path for a language/repository pair."""
return commits_dir / lang / f"{repo_slug}.jsonl"
def _variant_index(prompt_path: Path) -> int:
match = re.search(r"-(\d+)\.txt$", prompt_path.name)
return int(match.group(1)) if match else 1
def _structural_repos(
commits_dir: Path, p: Predicates, langs: Iterable[str] | None
) -> list[tuple[str, str]]:
"""(lang, repo) passing the repo gates EXCEPT ``min_tasks_per_repo``.
``langs`` restricts BEFORE canonicalization (see ``iter_repos``): a
dual-classified repo queried with ``langs=[X]`` competes with its best
X-bucket rather than vanishing because another language won canonical."""
by_lang = _repos_by_lang(commits_dir, langs)
wanted = set(langs) if langs is not None else None
large = large_repo_set(commits_dir) if p.not_overlarge else set()
skipped = _sft_tools_skipped_repos(commits_dir) if p.not_skipped else set()
times = build_times(commits_dir) if p.builds else {}
out: list[tuple[str, str]] = []
for lang in sorted(by_lang):
if wanted is not None and lang not in wanted:
continue
for repo in by_lang[lang]:
if p.not_overlarge and repo in large:
continue
if p.not_skipped and repo in skipped:
continue
if p.builds and repo not in times:
continue
if p.has_testsome and not read_testsome_outcomes(commits_dir, lang, repo):
continue
out.append((lang, repo))
return out
def _repo_task_refs(
commits_dir: Path, sfttasks_dir: Path, lang: str, repo: str, p: Predicates
) -> list[TaskRef]:
"""TaskRefs in one repo matching the per-sha/task gates (no threshold)."""
outcomes = read_testsome_outcomes(commits_dir, lang, repo) if p.binding else {}
refs: list[TaskRef] = []
for record in read_scan_records(scan_records_path(commits_dir, lang, repo)):
sha = record.hash
outcome = outcomes.get(sha)
if p.binding and not is_binding(outcome):
continue
if p.non_fragile_tests and read_non_fragile_tests(sfttasks_dir, sha) is not True:
continue
command = testsome_command(outcome)
if p.generated:
# The task IS its prompt: enumerate existing prompt variants.
if p.include_variants:
variant_paths = task_variant_paths(sfttasks_dir, sha)
else:
primary = prompt_path_for(sfttasks_dir, sha, variant=1)
variant_paths = (primary,) if primary is not None else ()
for path in variant_paths:
refs.append(TaskRef(lang, repo, sha, _variant_index(path),
record.oneline, path, command))
else:
# One ref per candidate sha; resolve a prompt opportunistically.
refs.append(TaskRef(lang, repo, sha, 1, record.oneline,
prompt_path_for(sfttasks_dir, sha), command))
return refs
def _select(
commits_dir: Path, sfttasks_dir: Path, p: Predicates, langs: Iterable[str] | None
) -> list[tuple[RepoRef, list[TaskRef]]]:
"""Shared engine: repos passing all gates (incl. threshold), each with its
matching TaskRefs, ranked by coarse task-count band then build time."""
p = p.resolved()
times = build_times(commits_dir)
selected: list[tuple[RepoRef, list[TaskRef]]] = []
for lang, repo in _structural_repos(commits_dir, p, langs):
refs = _repo_task_refs(commits_dir, sfttasks_dir, lang, repo, p)
if not refs:
continue # a repo with no matching tasks is not selected
if p.min_tasks_per_repo is not None and len(refs) < p.min_tasks_per_repo:
continue
selected.append((RepoRef(lang, repo, len(refs)), refs))
def rank(item: tuple[RepoRef, list[TaskRef]]) -> tuple[int, float, str]:
repo_ref = item[0]
band = -int(math.log2(repo_ref.task_count)) if repo_ref.task_count >= 1 else 1
return (band, times.get(repo_ref.repo_slug, math.inf), repo_ref.repo_slug)
selected.sort(key=rank)
return selected
def task_repos(
p: Predicates,
*,
commits_dir: Path = DEFAULT_COMMITS_DIR,
sfttasks_dir: Path = DEFAULT_SFTTASKS_DIR,
langs: Iterable[str] | None = None,
) -> list[RepoRef]:
"""Repos passing the predicates, ranked. ``min_tasks_per_repo`` counts the
repo's matches of the SAME query's task predicates (pre-threshold)."""
return [repo_ref for repo_ref, _refs in _select(commits_dir, sfttasks_dir, p, langs)]
def task_shas(
p: Predicates,
*,
commits_dir: Path = DEFAULT_COMMITS_DIR,
sfttasks_dir: Path = DEFAULT_SFTTASKS_DIR,
langs: Iterable[str] | None = None,
) -> list[TaskRef]:
"""Tasks satisfying the task predicates, in repos satisfying the repo
predicates (incl. ``min_tasks_per_repo``)."""
refs: list[TaskRef] = []
for _repo_ref, repo_refs in _select(commits_dir, sfttasks_dir, p, langs):
refs.extend(repo_refs)
return refs
# The SFT-runnable gates (no per-repo threshold): large-excluded, built, testsome,
# not skipped; binding ∧ generated ∧ vetted-non-fragile; primary variants only.
# Per-repo executors (p2t) use this base directly; corpus selection adds a threshold.
SFT_PREDICATES = Predicates(
not_overlarge=True, has_testsome=True, not_skipped=True,
binding=True, generated=True, non_fragile_tests=True,
)
def sft_predicates(task_count_threshold: int) -> Predicates:
"""``SFT_PREDICATES`` plus a ``min_tasks_per_repo`` floor (corpus selection)."""
return replace(SFT_PREDICATES, min_tasks_per_repo=task_count_threshold)
def sft_task_shas(task_count_threshold: int, **kwargs) -> list[TaskRef]:
return task_shas(sft_predicates(task_count_threshold), **kwargs)
def sft_count_for_repo(
commits_dir: Path,
sfttasks_dir: Path,
lang: str,
repo: str,
*,
large_repos: set[str] | None = None,
build_time_map: dict[str, float] | None = None,
) -> int:
"""``SFT_PREDICATES`` task count for ONE repo — the per-repo subcount whose sum
over a language equals ``len(task_shas(SFT_PREDICATES, langs=[lang]))``. Applies
the same repo gates (not-overlarge, built, has-testsome, not-skipped) then the
per-sha gates (binding ∧ generated ∧ non-fragile). Reading from disk only, so a
caller can recompute just the repos that changed instead of crawling the corpus.
Pass ``large_repos``/``build_time_map`` (read once per refresh) to skip re-reading
the small CSVs per call. ``binding`` is checked before any per-sha sfttasks read,
so this touches one ``.jsonl`` + one ``.testsome.jsonl`` + only the *binding*
shas' sfttasks."""
p = SFT_PREDICATES.resolved()
large = large_repos if large_repos is not None else large_repo_set(commits_dir)
if repo in large: # not_overlarge
return 0
times = build_time_map if build_time_map is not None else build_times(commits_dir)
if repo not in times: # builds (implied by has_testsome)
return 0
if not read_testsome_outcomes(commits_dir, lang, repo): # has_testsome
return 0
status = read_repo_status_payload(commits_dir / lang / f"{repo}.status.json")
if status.get("testsome_skipped"): # not_skipped
return 0
return len(_repo_task_refs(commits_dir, sfttasks_dir, lang, repo, p))
def sft_task_repos(task_count_threshold: int, **kwargs) -> list[RepoRef]:
return task_repos(sft_predicates(task_count_threshold), **kwargs)
def main(stdin: TextIO | None = None, stdout: TextIO | None = None) -> int:
input_stream = stdin if stdin is not None else sys.stdin
output_stream = stdout if stdout is not None else sys.stdout
for raw_path in input_stream:
path_str = raw_path.strip()
if not path_str:
continue
metadata = parse_path(path_str)
print(
json.dumps({"project": metadata.project, "hash": metadata.hash}),
file=output_stream,
)
return 0
if __name__ == "__main__":
raise SystemExit(main())