mirror of
https://github.com/norandom/OpenUltraSAST.git
synced 2026-12-03 10:18:18 +00:00
feat(detection-core): migrate benchmark readiness and admission consumers
This commit is contained in:
@@ -2,16 +2,113 @@
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import errno
|
||||
import hashlib
|
||||
import json
|
||||
import math
|
||||
from collections.abc import Mapping
|
||||
import os
|
||||
import tempfile
|
||||
from collections.abc import Iterator, Mapping
|
||||
from contextlib import contextmanager
|
||||
from dataclasses import asdict, dataclass, field
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
from .table import canonical_json
|
||||
|
||||
# Persisted attempt sequences use the portable signed 64-bit integer domain.
|
||||
MAX_ATTEMPT_ORDINAL = (1 << 63) - 1
|
||||
_UNSUPPORTED_DIRECTORY_SYNC = frozenset(
|
||||
error for name in ("EINVAL", "ENOTSUP", "EOPNOTSUPP") if (error := getattr(errno, name, None)) is not None
|
||||
)
|
||||
|
||||
|
||||
@contextmanager
|
||||
def _artifact_lock(directory: Path) -> Iterator[None]:
|
||||
directory.mkdir(parents=True, exist_ok=True)
|
||||
descriptor = os.open(directory / ".run-artifact.lock", os.O_CREAT | os.O_RDWR, 0o600)
|
||||
try:
|
||||
import fcntl
|
||||
|
||||
fcntl.flock(descriptor, fcntl.LOCK_EX)
|
||||
yield
|
||||
finally:
|
||||
fcntl.flock(descriptor, fcntl.LOCK_UN)
|
||||
os.close(descriptor)
|
||||
|
||||
|
||||
def _sync_directory(directory: Path) -> None:
|
||||
"""Durably publish a directory entry where the platform supports it."""
|
||||
if os.name == "nt":
|
||||
return
|
||||
flags = os.O_RDONLY | getattr(os, "O_DIRECTORY", 0)
|
||||
try:
|
||||
descriptor = os.open(directory, flags)
|
||||
except OSError as error:
|
||||
if error.errno in _UNSUPPORTED_DIRECTORY_SYNC:
|
||||
return
|
||||
raise
|
||||
try:
|
||||
os.fsync(descriptor)
|
||||
except OSError as error:
|
||||
if error.errno not in _UNSUPPORTED_DIRECTORY_SYNC:
|
||||
raise
|
||||
finally:
|
||||
os.close(descriptor)
|
||||
|
||||
|
||||
def _persist_sequence(directory: Path, ordinal: int) -> None:
|
||||
descriptor, temporary = tempfile.mkstemp(dir=directory, prefix=".attempt-sequence.", text=True)
|
||||
try:
|
||||
with os.fdopen(descriptor, "w", encoding="utf-8") as stream:
|
||||
stream.write(f"{ordinal}\n")
|
||||
stream.flush()
|
||||
os.fsync(stream.fileno())
|
||||
os.replace(temporary, directory / ".attempt-sequence")
|
||||
_sync_directory(directory)
|
||||
finally:
|
||||
Path(temporary).unlink(missing_ok=True)
|
||||
|
||||
|
||||
def _reserve_attempt_ordinal(directory: Path) -> int:
|
||||
sequence = directory / ".attempt-sequence"
|
||||
try:
|
||||
content = sequence.read_text()
|
||||
except FileNotFoundError:
|
||||
if _valid_attempt_artifact_exists(directory):
|
||||
raise ValueError("run attempt sequence is missing for existing artifacts; explicit recovery is required") from None
|
||||
previous = 0
|
||||
except OSError as error:
|
||||
raise ValueError("run attempt sequence is unreadable") from error
|
||||
else:
|
||||
try:
|
||||
previous = int(content.strip())
|
||||
except ValueError as error:
|
||||
raise ValueError("run attempt sequence is unreadable") from error
|
||||
if previous < 0:
|
||||
raise ValueError("run attempt sequence is invalid")
|
||||
if previous >= MAX_ATTEMPT_ORDINAL:
|
||||
raise ValueError("run attempt sequence is exhausted")
|
||||
ordinal = previous + 1
|
||||
_persist_sequence(directory, ordinal)
|
||||
return ordinal
|
||||
|
||||
|
||||
def _create_only(path: Path, content: bytes) -> None:
|
||||
if path.exists():
|
||||
if path.read_bytes() == content:
|
||||
return
|
||||
raise ValueError(f"run artifact conflict: {path}")
|
||||
try:
|
||||
with path.open("xb") as stream:
|
||||
stream.write(content)
|
||||
stream.flush()
|
||||
os.fsync(stream.fileno())
|
||||
_sync_directory(path.parent)
|
||||
except FileExistsError:
|
||||
if path.read_bytes() != content:
|
||||
raise ValueError(f"run artifact conflict: {path}") from None
|
||||
|
||||
|
||||
def _exhausted(usage: Mapping[str, float], budget: Mapping[str, float]) -> bool:
|
||||
for name in ("usd", "calls"):
|
||||
@@ -34,23 +131,36 @@ class RunArtifact:
|
||||
usage: dict[str, float]
|
||||
versions: dict[str, str]
|
||||
created: str
|
||||
attempt_ordinal: int = 0
|
||||
|
||||
@property
|
||||
def artifact_id(self) -> str:
|
||||
return hashlib.sha256(canonical_json(asdict(self)).encode("utf-8")).hexdigest()
|
||||
payload = asdict(self)
|
||||
if not self.attempt_ordinal:
|
||||
payload.pop("attempt_ordinal")
|
||||
return hashlib.sha256(canonical_json(payload).encode("utf-8")).hexdigest()
|
||||
|
||||
def finish(self, budget: Mapping[str, float]) -> RunArtifact | None:
|
||||
"""Return no completed artifact when either registered budget is exhausted."""
|
||||
return None if _exhausted(self.usage, budget) else self
|
||||
|
||||
def write(self, directory: Path | str, *, budget: Mapping[str, float] | None = None) -> Path | None:
|
||||
def write(
|
||||
self,
|
||||
directory: Path | str,
|
||||
*,
|
||||
budget: Mapping[str, float] | None = None,
|
||||
reserve_attempt: bool = False,
|
||||
) -> Path | None:
|
||||
"""Write metadata under its content id, after an optional final budget check."""
|
||||
if budget is not None and self.finish(budget) is None:
|
||||
return None
|
||||
directory = Path(directory)
|
||||
directory.mkdir(parents=True, exist_ok=True)
|
||||
path = directory / f"{self.artifact_id}.json"
|
||||
path.write_text(canonical_json({**asdict(self), "artifact_id": self.artifact_id}) + "\n", encoding="utf-8")
|
||||
with _artifact_lock(directory):
|
||||
if reserve_attempt and not self.attempt_ordinal:
|
||||
self.attempt_ordinal = _reserve_attempt_ordinal(directory)
|
||||
path = directory / f"{self.artifact_id}.json"
|
||||
content = (canonical_json({**asdict(self), "artifact_id": self.artifact_id}) + "\n").encode()
|
||||
_create_only(path, content)
|
||||
return path
|
||||
|
||||
@classmethod
|
||||
@@ -58,12 +168,24 @@ class RunArtifact:
|
||||
payload = json.loads(Path(path).read_text(encoding="utf-8"))
|
||||
identifier = payload.pop("artifact_id", None)
|
||||
payload["mask"] = tuple(payload["mask"])
|
||||
payload.setdefault("attempt_ordinal", 0)
|
||||
artifact = cls(**payload)
|
||||
if identifier != artifact.artifact_id:
|
||||
raise ValueError("run artifact id does not match its contents")
|
||||
return artifact
|
||||
|
||||
|
||||
def _valid_attempt_artifact_exists(directory: Path) -> bool:
|
||||
for path in directory.glob("*.json"):
|
||||
try:
|
||||
artifact = RunArtifact.read(path)
|
||||
except (OSError, TypeError, ValueError):
|
||||
continue
|
||||
if path.stem == artifact.artifact_id:
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
@dataclass
|
||||
class UsageLedger:
|
||||
"""Count paid calls, replay hits, spend and elapsed call time separately."""
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import fcntl
|
||||
import hashlib
|
||||
import json
|
||||
import math
|
||||
import os
|
||||
@@ -40,11 +41,21 @@ def _reserve(root: Path, program_id: str) -> Path:
|
||||
return directory
|
||||
|
||||
|
||||
def _records(directory: Path, changes: Sequence[Mapping]) -> list[dict]:
|
||||
def _records(
|
||||
directory: Path,
|
||||
destination: Path,
|
||||
changes: Sequence[Mapping],
|
||||
*,
|
||||
context: Any,
|
||||
) -> list[dict]:
|
||||
"""Load benchmark records and retain every expected change, even after a budget stop."""
|
||||
from benchmarks.unseen import score
|
||||
from benchmarks.valid.hunt_handoff import persist_hunt_runner_records
|
||||
|
||||
records = score.load_records(Path(directory)) if (Path(directory) / "inputs.json").exists() else []
|
||||
records = []
|
||||
if (Path(directory) / "inputs.json").exists():
|
||||
persist_hunt_runner_records(Path(directory), Path(destination), context=context, changes=changes)
|
||||
records = score.load_records(Path(destination))
|
||||
indexed = {r["id"]: r for r in records}
|
||||
if len(indexed) != len(records) or set(indexed) - {c["id"] for c in changes}:
|
||||
raise ValueError("records do not match the pilot population")
|
||||
@@ -57,6 +68,24 @@ def _records(directory: Path, changes: Sequence[Mapping]) -> list[dict]:
|
||||
return result
|
||||
|
||||
|
||||
def _hunt_context(source: Path, manifest: Path, program_id: str, mask: Sequence[str]) -> Any:
|
||||
from benchmarks.valid.hunt_handoff import HUNT_RUNNER_PRODUCER, discover_hunt_runner_context
|
||||
|
||||
content = Path(manifest).read_bytes()
|
||||
if not content:
|
||||
raise ValueError("hunt manifest is empty")
|
||||
manifest_digest = hashlib.sha256(content).hexdigest()
|
||||
freeze = Path(manifest).with_name("freeze-" + Path(manifest).stem.removeprefix("pool-") + ".json")
|
||||
freeze_digest = manifest_digest
|
||||
if freeze.is_file():
|
||||
payload = json.loads(freeze.read_text())
|
||||
freeze_digest = str(payload.get("freeze_digest") or "")
|
||||
context = discover_hunt_runner_context(source, manifest, producer=HUNT_RUNNER_PRODUCER, freeze_digest=freeze_digest)
|
||||
if context.program_id != program_id or context.mask != tuple(sorted(set(mask))) or context.manifest_digest != manifest_digest:
|
||||
raise ValueError("hunt report context does not match the requested program")
|
||||
return context
|
||||
|
||||
|
||||
def _instrument(records: Sequence[Mapping]) -> dict:
|
||||
"""Record changed-file bytes and verified revisions; unreadable and absent changes fail."""
|
||||
from benchmarks.unseen import score
|
||||
@@ -368,6 +397,137 @@ def _notes(analysis: dict) -> str:
|
||||
return "\n".join(lines)
|
||||
|
||||
|
||||
def _pilot_inputs(
|
||||
candidate: Candidate,
|
||||
decision: accept.Decision,
|
||||
training_runs: Sequence[Path],
|
||||
pilot_metrics: Mapping[str, Path],
|
||||
pilot_manifest: Path,
|
||||
load_changes: Any,
|
||||
) -> tuple[dict[str, Any], list[dict[str, Any]]]:
|
||||
from benchmarks.unseen.replay import load_slice
|
||||
|
||||
if not decision.accepted or decision.comparison.get("candidate_id") != candidate.program_id:
|
||||
raise ValueError("pilot gain requires the accepted decision for this candidate")
|
||||
normalized_runs = [Path(path) for path in training_runs]
|
||||
if contamination.clean_runs(normalized_runs) != normalized_runs:
|
||||
raise ValueError("contaminated training runs cannot report pilot gain")
|
||||
changes = list((load_changes or load_slice)(Path(pilot_manifest), "1"))
|
||||
if not changes or len({change["id"] for change in changes}) != len(changes):
|
||||
raise ValueError("pilot changes must be nonempty and have unique IDs")
|
||||
return _before(pilot_metrics), changes
|
||||
|
||||
|
||||
def _run_pilot_candidate(
|
||||
candidate: Candidate,
|
||||
pilot_manifest: Path,
|
||||
repos: Mapping[str, str],
|
||||
directory: Path,
|
||||
lm: Any,
|
||||
budget: Mapping[str, float],
|
||||
tools_for: Any,
|
||||
changes: list[dict[str, Any]],
|
||||
) -> runner.RunArtifact | None:
|
||||
import dspy
|
||||
|
||||
from .program import repository_tools
|
||||
|
||||
program = _candidate_program(candidate, tools_for)
|
||||
with dspy.context(lm=lm, adapter=dspy.ChatAdapter()):
|
||||
return runner.run(
|
||||
Path(pilot_manifest),
|
||||
repos,
|
||||
directory / "records",
|
||||
program=program,
|
||||
program_id=candidate.program_id,
|
||||
mask=candidate.mask,
|
||||
pilot_report=True,
|
||||
only="all",
|
||||
budget=budget,
|
||||
tools_for=tools_for or repository_tools,
|
||||
load_changes=lambda _path, _slice: changes,
|
||||
versions={"dspy": dspy.__version__},
|
||||
)
|
||||
|
||||
|
||||
def _pilot_baselines(
|
||||
candidate: Candidate,
|
||||
pilot_manifest: Path,
|
||||
baseline_runs: Sequence[Path],
|
||||
directory: Path,
|
||||
changes: list[dict[str, Any]],
|
||||
) -> list[list[dict[str, Any]]]:
|
||||
return [
|
||||
_clean(
|
||||
_records(
|
||||
Path(path),
|
||||
directory / "benchmark-baselines" / str(index),
|
||||
changes,
|
||||
context=_hunt_context(Path(path), Path(pilot_manifest), candidate.base_program_id, ()),
|
||||
)
|
||||
)
|
||||
for index, path in enumerate(baseline_runs)
|
||||
]
|
||||
|
||||
|
||||
def _successful_pilot_analysis(
|
||||
analysis: dict[str, Any],
|
||||
records: list[dict[str, Any]],
|
||||
before: dict[str, Any],
|
||||
baseline_records: list[list[dict[str, Any]]],
|
||||
) -> tuple[list[dict[str, Any]], list[str]]:
|
||||
from benchmarks.unseen import score
|
||||
|
||||
records = _clean(records)
|
||||
score.score(records)
|
||||
families = _families([dict(change=record, after=_outcome(record, record, 10)) for record in records], ("after",))
|
||||
for baseline in baseline_records:
|
||||
before_units = [dict(change=record, before=_outcome(record, record, 10)) for record in baseline]
|
||||
families = sorted(set(families) | set(_families(before_units, ("before",))))
|
||||
curve, distance = _curve(records)
|
||||
counts = [search_outcome(record, _findings(record["push"]["admission"]["defects"])).suspicions for record in records]
|
||||
analysis.update(
|
||||
before=before,
|
||||
after=_summaries(records, families),
|
||||
curve=curve,
|
||||
gate_distance=distance,
|
||||
workload={
|
||||
"suspicions_per_100_pushes": _rate(counts, [record["repo"] for record in records], scale=100),
|
||||
"flagged_pushes_per_100_pushes": _rate(
|
||||
[int(count > 0) for count in counts], [record["repo"] for record in records], binary=True, scale=100
|
||||
),
|
||||
},
|
||||
)
|
||||
return records, families
|
||||
|
||||
|
||||
def _add_pilot_baselines(
|
||||
analysis: dict[str, Any],
|
||||
baseline_runs: Sequence[Path],
|
||||
baseline_records: list[list[dict[str, Any]]],
|
||||
records: list[dict[str, Any]],
|
||||
families: list[str],
|
||||
) -> None:
|
||||
if not baseline_records:
|
||||
return
|
||||
analysis["baseline"] = []
|
||||
for path, baseline in zip(baseline_runs, baseline_records, strict=True):
|
||||
instrument = _instrument(baseline)
|
||||
entry = {"directory": str(path), "valid": instrument["valid"], "instrument": instrument}
|
||||
if entry["valid"]:
|
||||
entry["summary"] = _summaries(baseline, families)
|
||||
analysis["baseline"].append(entry)
|
||||
if all(row["valid"] for row in analysis["baseline"]):
|
||||
analysis["paired"] = _baseline_comparison(baseline_records, records, families)
|
||||
|
||||
|
||||
def _persist_pilot_analysis(directory: Path, analysis: dict[str, Any]) -> dict[str, Any]:
|
||||
normalized: dict[str, Any] = json.loads(json.dumps(analysis))
|
||||
_write(directory / "analysis.json", normalized)
|
||||
(directory / "NOTES.md").write_text(_notes(normalized), encoding="utf-8")
|
||||
return normalized
|
||||
|
||||
|
||||
def pilot_gain(
|
||||
candidate: Candidate,
|
||||
decision: accept.Decision,
|
||||
@@ -390,40 +550,11 @@ def pilot_gain(
|
||||
line scorers or real model clients are constructed here. Budget exhaustion or more than five
|
||||
percent instrument failures leaves an invalid measurement without performance numbers.
|
||||
"""
|
||||
import dspy
|
||||
|
||||
from benchmarks.unseen import score
|
||||
from benchmarks.unseen.replay import load_slice
|
||||
|
||||
from .program import repository_tools
|
||||
|
||||
if not decision.accepted or decision.comparison.get("candidate_id") != candidate.program_id:
|
||||
raise ValueError("pilot gain requires the accepted decision for this candidate")
|
||||
training_runs = [Path(p) for p in training_runs]
|
||||
if contamination.clean_runs(training_runs) != training_runs:
|
||||
raise ValueError("contaminated training runs cannot report pilot gain")
|
||||
before = _before(pilot_metrics)
|
||||
program = _candidate_program(candidate, tools_for)
|
||||
changes = list((load_changes or load_slice)(Path(pilot_manifest), "1"))
|
||||
if not changes or len({c["id"] for c in changes}) != len(changes):
|
||||
raise ValueError("pilot changes must be nonempty and have unique IDs")
|
||||
before, changes = _pilot_inputs(candidate, decision, training_runs, pilot_metrics, pilot_manifest, load_changes)
|
||||
directory = _reserve(Path(out_root), candidate.program_id)
|
||||
with dspy.context(lm=lm, adapter=dspy.ChatAdapter()):
|
||||
artifact = runner.run(
|
||||
Path(pilot_manifest),
|
||||
repos,
|
||||
directory / "records",
|
||||
program=program,
|
||||
program_id=candidate.program_id,
|
||||
mask=candidate.mask,
|
||||
pilot_report=True,
|
||||
only="all",
|
||||
budget=budget,
|
||||
tools_for=tools_for or repository_tools,
|
||||
load_changes=lambda _path, _slice: changes,
|
||||
versions={"dspy": dspy.__version__},
|
||||
)
|
||||
records = _records(directory / "records", changes)
|
||||
artifact = _run_pilot_candidate(candidate, pilot_manifest, repos, directory, lm, budget, tools_for, changes)
|
||||
context = _hunt_context(directory / "records", Path(pilot_manifest), candidate.program_id, candidate.mask)
|
||||
records = _records(directory / "records", directory / "benchmark-records", changes, context=context)
|
||||
proof = _instrument(records)
|
||||
_write(directory / "instrument.json", proof)
|
||||
analysis: dict[str, Any] = dict(
|
||||
@@ -436,37 +567,7 @@ def pilot_gain(
|
||||
if not analysis["valid"]:
|
||||
analysis["reason"] = "more than 5% instrument failures" if not proof["valid"] else "runner budget exhausted"
|
||||
else:
|
||||
records = _clean(records)
|
||||
# Run the same overall instrument gate and scorer as the pilot before quoting any scores.
|
||||
score.score(records)
|
||||
families = _families([dict(change=r, after=_outcome(r, r, 10)) for r in records], ("after",))
|
||||
baseline_records = [_clean(_records(Path(path), changes)) for path in baseline_runs]
|
||||
for baseline in baseline_records:
|
||||
families = sorted(set(families) | set(_families([dict(change=r, before=_outcome(r, r, 10)) for r in baseline], ("before",))))
|
||||
curve, distance = _curve(records)
|
||||
counts = [search_outcome(r, _findings(r["push"]["admission"]["defects"])).suspicions for r in records]
|
||||
analysis.update(
|
||||
before=before,
|
||||
after=_summaries(records, families),
|
||||
curve=curve,
|
||||
gate_distance=distance,
|
||||
workload=dict(
|
||||
suspicions_per_100_pushes=_rate(counts, [r["repo"] for r in records], scale=100),
|
||||
flagged_pushes_per_100_pushes=_rate([int(n > 0) for n in counts], [r["repo"] for r in records], binary=True, scale=100),
|
||||
),
|
||||
)
|
||||
if baseline_records:
|
||||
analysis["baseline"] = []
|
||||
for path, baseline in zip(baseline_runs, baseline_records, strict=True):
|
||||
instrument = _instrument(baseline)
|
||||
entry = dict(directory=str(path), valid=instrument["valid"], instrument=instrument)
|
||||
if entry["valid"]:
|
||||
entry["summary"] = _summaries(baseline, families)
|
||||
analysis["baseline"].append(entry)
|
||||
if all(row["valid"] for row in analysis["baseline"]):
|
||||
analysis["paired"] = _baseline_comparison(baseline_records, records, families)
|
||||
# Return the same JSON types that a reader of analysis.json receives.
|
||||
analysis = json.loads(json.dumps(analysis))
|
||||
_write(directory / "analysis.json", analysis)
|
||||
(directory / "NOTES.md").write_text(_notes(analysis), encoding="utf-8")
|
||||
return analysis
|
||||
baseline_records = _pilot_baselines(candidate, pilot_manifest, baseline_runs, directory, changes)
|
||||
records, families = _successful_pilot_analysis(analysis, records, before, baseline_records)
|
||||
_add_pilot_baselines(analysis, baseline_runs, baseline_records, records, families)
|
||||
return _persist_pilot_analysis(directory, analysis)
|
||||
|
||||
@@ -14,7 +14,7 @@ import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
import time
|
||||
from collections.abc import Iterable, Mapping
|
||||
from collections.abc import Iterable, Mapping, Sequence
|
||||
from datetime import UTC, datetime
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
@@ -219,6 +219,119 @@ def _function_at(root: Path, finding: Mapping[str, Any]) -> str | None:
|
||||
return None
|
||||
|
||||
|
||||
def _run_entries(out: Path) -> tuple[Path, list[dict[str, Any]], dict[str, dict[str, Any]]]:
|
||||
inputs_path = out / "inputs.json"
|
||||
entries = json.loads(inputs_path.read_text()) if inputs_path.is_file() else []
|
||||
return inputs_path, entries, {entry["item_id"]: entry for entry in entries}
|
||||
|
||||
|
||||
def _change_entry(
|
||||
change: Mapping[str, Any],
|
||||
program_id: str,
|
||||
mask: tuple[str, ...],
|
||||
entries: list[dict[str, Any]],
|
||||
indexed: dict[str, dict[str, Any]],
|
||||
) -> str:
|
||||
digest = input_digest(change, program_id, mask)
|
||||
entry = indexed.get(change["id"])
|
||||
if entry is None:
|
||||
entry = {"item_id": change["id"], "change": change, "input_digest": digest}
|
||||
entries.append(entry)
|
||||
indexed[change["id"]] = entry
|
||||
elif entry["input_digest"] != digest:
|
||||
entry.update(change=change, input_digest=digest)
|
||||
return digest
|
||||
|
||||
|
||||
def _record_is_complete(out: Path, change_id: str, digest: str) -> bool:
|
||||
path = record_path(out, change_id)
|
||||
if not path.is_file():
|
||||
return False
|
||||
previous = json.loads(path.read_text())
|
||||
return bool(previous.get("done") and previous.get("input_digest") == digest)
|
||||
|
||||
|
||||
def _run_change(
|
||||
change: Mapping[str, Any],
|
||||
repos: Mapping[str, str],
|
||||
out: Path,
|
||||
program: Any,
|
||||
program_id: str,
|
||||
mask: tuple[str, ...],
|
||||
render: Any,
|
||||
tools_for: Any,
|
||||
ledger: UsageLedger,
|
||||
) -> None:
|
||||
history = _lm_history()
|
||||
first_call = len(history) if history is not None else 0
|
||||
record = hunt_change(
|
||||
change,
|
||||
Path(repos[change["repo"]]).expanduser(),
|
||||
program=program,
|
||||
program_id=program_id,
|
||||
mask=mask,
|
||||
render=render,
|
||||
tools_for=tools_for,
|
||||
)
|
||||
record["input_digest"] = input_digest(change, program_id, mask)
|
||||
record["usd"] = round(spent_since(history, first_call), 6)
|
||||
ledger.add({"calls": 1, "usd": record["usd"]})
|
||||
_write_json(record_path(out, change["id"]), record)
|
||||
|
||||
|
||||
def _process_changes(
|
||||
changes: Sequence[Mapping[str, Any]],
|
||||
repos: Mapping[str, str],
|
||||
out: Path,
|
||||
program: Any,
|
||||
program_id: str,
|
||||
mask: tuple[str, ...],
|
||||
render: Any,
|
||||
tools_for: Any,
|
||||
budget: Mapping[str, float] | None,
|
||||
entries: list[dict[str, Any]],
|
||||
indexed: dict[str, dict[str, Any]],
|
||||
inputs_path: Path,
|
||||
) -> UsageLedger:
|
||||
ledger = UsageLedger()
|
||||
for change in changes:
|
||||
digest = _change_entry(change, program_id, mask, entries, indexed)
|
||||
if _record_is_complete(out, change["id"], digest):
|
||||
continue
|
||||
if budget and ledger.exhausted(budget):
|
||||
print("budget exhausted; stopping before the next change", flush=True)
|
||||
break
|
||||
_run_change(change, repos, out, program, program_id, mask, render, tools_for, ledger)
|
||||
_write_json(inputs_path, entries)
|
||||
_write_json(inputs_path, entries)
|
||||
return ledger
|
||||
|
||||
|
||||
def _run_artifact(
|
||||
manifest: Path,
|
||||
program_id: str,
|
||||
mask: tuple[str, ...],
|
||||
only: str,
|
||||
slice_id: str,
|
||||
changes: Sequence[Mapping[str, Any]],
|
||||
ledger: UsageLedger,
|
||||
versions: Mapping[str, str] | None,
|
||||
started: float,
|
||||
) -> RunArtifact:
|
||||
usage = dict(ledger.usage)
|
||||
usage["wall_seconds"] = round(time.monotonic() - started, 1)
|
||||
return RunArtifact(
|
||||
program_id=program_id,
|
||||
schema_version=1,
|
||||
mask=list(mask),
|
||||
data_digests={"manifest": hashlib.sha256(manifest.read_bytes()).hexdigest()},
|
||||
configurations=[{"only": only, "slice": slice_id, "changes": len(changes)}],
|
||||
usage=usage,
|
||||
versions=dict(versions or {}),
|
||||
created=datetime.now(UTC).isoformat(timespec="seconds"),
|
||||
)
|
||||
|
||||
|
||||
def run(
|
||||
manifest: Path,
|
||||
repos: Mapping[str, str],
|
||||
@@ -245,56 +358,10 @@ def run(
|
||||
changes = load_changes(manifest, slice_id)
|
||||
changes = [change for change in changes if only == "all" or change["kind"] == only]
|
||||
out.mkdir(parents=True, exist_ok=True)
|
||||
inputs_path = out / "inputs.json"
|
||||
entries = json.loads(inputs_path.read_text()) if inputs_path.is_file() else []
|
||||
indexed = {entry["item_id"]: entry for entry in entries}
|
||||
ledger = UsageLedger()
|
||||
inputs_path, entries, indexed = _run_entries(out)
|
||||
started = time.monotonic()
|
||||
for change in changes:
|
||||
digest = input_digest(change, program_id, mask)
|
||||
entry = indexed.get(change["id"])
|
||||
if entry is None:
|
||||
entry = {"item_id": change["id"], "change": change, "input_digest": digest}
|
||||
entries.append(entry)
|
||||
indexed[change["id"]] = entry
|
||||
elif entry["input_digest"] != digest:
|
||||
entry.update(change=change, input_digest=digest)
|
||||
path = record_path(out, change["id"])
|
||||
if path.is_file():
|
||||
previous = json.loads(path.read_text())
|
||||
if previous.get("done") and previous.get("input_digest") == digest:
|
||||
continue
|
||||
if budget and ledger.exhausted(budget):
|
||||
print("budget exhausted; stopping before the next change", flush=True)
|
||||
break
|
||||
history = _lm_history()
|
||||
first_call = len(history) if history is not None else 0
|
||||
record = hunt_change(
|
||||
change,
|
||||
Path(repos[change["repo"]]).expanduser(),
|
||||
program=program,
|
||||
program_id=program_id,
|
||||
mask=mask,
|
||||
render=render,
|
||||
tools_for=tools_for,
|
||||
)
|
||||
record["input_digest"] = digest
|
||||
record["usd"] = round(spent_since(history, first_call), 6)
|
||||
ledger.add({"calls": 1, "usd": record["usd"]})
|
||||
_write_json(path, record)
|
||||
_write_json(inputs_path, entries)
|
||||
_write_json(inputs_path, entries)
|
||||
usage = dict(ledger.usage)
|
||||
usage["wall_seconds"] = round(time.monotonic() - started, 1)
|
||||
artifact = RunArtifact(
|
||||
program_id=program_id,
|
||||
schema_version=1,
|
||||
mask=list(mask),
|
||||
data_digests={"manifest": hashlib.sha256(manifest.read_bytes()).hexdigest()},
|
||||
configurations=[{"only": only, "slice": slice_id, "changes": len(changes)}],
|
||||
usage=usage,
|
||||
versions=dict(versions or {}),
|
||||
created=datetime.now(UTC).isoformat(timespec="seconds"),
|
||||
)
|
||||
written = artifact.write(out, budget=budget) if budget else artifact.write(out)
|
||||
return artifact if written is not None else None
|
||||
ledger = _process_changes(changes, repos, out, program, program_id, mask, render, tools_for, budget, entries, indexed, inputs_path)
|
||||
artifact = _run_artifact(manifest, program_id, mask, only, slice_id, changes, ledger, versions, started)
|
||||
completed: RunArtifact | None = artifact.finish(budget) if budget else artifact
|
||||
artifact.write(out, reserve_attempt=True)
|
||||
return completed
|
||||
|
||||
Reference in New Issue
Block a user