Coverage for src/romfarmer/engine/executor.py: 90%
176 statements
« prev ^ index » next coverage.py v7.15.4, created at 2026-09-05 02:19 -0700
« prev ^ index » next coverage.py v7.15.4, created at 2026-09-05 02:19 -0700
1"""Executor — drives the BuildPlan DAG through the ActionCache and CAS.
3The Executor is the only component that:
4 * requires ``Identity.is_complete`` (sha256 non-null) for CAS operations
5 * writes ``artifact_aliases`` (via :class:`ActionCache.record_aliases`)
6 * emits telemetry records (``ROMTransformation`` rows, if a recorder is set)
8The execution model is:
9 1. For each :class:`UnitPlan`, process :class:`Action`\\s in order.
10 2. For each :class:`Action`:
11 a. Attempt to resolve the :class:`ActionKey` via :func:`resolve_key`.
12 b. If resolved → check :class:`ActionCache`. Hit → use cached outputs.
13 c. Miss (or key not yet resolvable) → materialise inputs from CAS →
14 run the :class:`Transform` → ingest outputs into CAS → record
15 aliases → store in :class:`ActionCache`.
16 3. Accumulate ``known_outputs`` across actions so later actions can
17 resolve their :class:`PendingRef` inputs.
19This is intentionally **not** threaded — a future parallel executor can
20be built on top of the same interfaces.
21"""
23from __future__ import annotations
25import hashlib
26import logging
27import os
28import secrets
29import shutil
30import time
31from collections.abc import Callable, Mapping
32from pathlib import Path
33from typing import Any
35from romfarmer.ir.actions import (
36 Action,
37 ActionId,
38 ArtifactDecl,
39 BuildPlan,
40 ContentRef,
41 PendingRef,
42 Retention,
43 UnitPlan,
44 resolve_key,
45)
46from romfarmer.ir.catalog import UnitId
47from romfarmer.ir.identity import Identity
48from romfarmer.ir.layout import OutputSet
50from .actioncache import ActionCache
51from .scratch import ScratchDir
52from .transforms.base import Transform
54logger = logging.getLogger(__name__)
57# ---------------------------------------------------------------------------
58# CAS helpers (thin wrappers so the Executor doesn't depend on ContentStore)
59# ---------------------------------------------------------------------------
62def _sha256_file(path: Path) -> str:
63 h = hashlib.sha256()
64 with open(path, "rb") as f:
65 for chunk in iter(lambda: f.read(1_048_576), b""):
66 h.update(chunk)
67 return h.hexdigest()
70def _cas_path(cas_dir: Path, sha256: str, ext: str = "") -> Path:
71 """Return the CAS blob path for *sha256* (2-char prefix sharding)."""
72 prefix = sha256[:2]
73 rest = sha256[2:]
74 return cas_dir / prefix / (rest + ext)
77def _ingest_to_cas(file: Path, cas_dir: Path) -> str:
78 """Move (or copy) *file* into CAS; return its sha256. Idempotent.
80 Prefers ``os.rename`` so the source bytes are not read twice (zero extra
81 I/O for same-filesystem scratch→CAS paths). Falls back to
82 ``shutil.copy2`` when the rename crosses a filesystem boundary.
84 The tmp name includes PID + random token so concurrent ingests of the same
85 content cannot collide on the intermediate file.
86 """
87 sha256 = _sha256_file(file)
88 dest = _cas_path(cas_dir, sha256, file.suffix)
89 if not dest.exists():
90 dest.parent.mkdir(parents=True, exist_ok=True)
91 tmp = dest.with_suffix(f"{dest.suffix}.tmp.{os.getpid()}.{secrets.token_hex(4)}")
92 try:
93 os.rename(file, tmp)
94 except OSError:
95 # Cross-device move; fall back to copy
96 shutil.copy2(file, tmp)
97 # os.replace is atomic and handles the race: if another process already
98 # wrote the same content-addressed blob, we overwrite it with identical
99 # bytes — safe because CAS is content-addressed.
100 os.replace(tmp, dest)
101 return sha256
104def _blob_exists(sha256: str, cas_dir: Path) -> bool:
105 """Return True if a CAS blob for *sha256* exists on disk."""
106 parent = cas_dir / sha256[:2]
107 if not parent.is_dir():
108 return False
109 return any(parent.glob(f"{sha256[2:]}*"))
112def _materialise_from_cas(sha256: str, cas_dir: Path, dest: Path) -> None:
113 """Hardlink (or copy) a CAS blob to *dest*."""
114 blobs = list(cas_dir.glob(f"{sha256[:2]}/{sha256[2:]}*"))
115 if not blobs:
116 raise FileNotFoundError(f"CAS blob not found for sha256={sha256[:16]}… in {cas_dir}")
117 src = blobs[0]
118 dest.parent.mkdir(parents=True, exist_ok=True)
119 import os
121 try:
122 os.link(src, dest)
123 except OSError:
124 shutil.copy2(src, dest)
127# ---------------------------------------------------------------------------
128# Executor
129# ---------------------------------------------------------------------------
132class Executor:
133 """Runs a :class:`BuildPlan` through the :class:`ActionCache` and CAS.
135 Args:
136 action_cache: The unified action + alias cache.
137 transforms: Registry mapping ``tool`` name → :class:`Transform`.
138 cas_dir: Root of the content-addressable store.
139 scratch_base: Parent for per-unit scratch dirs.
140 telemetry_cb: Optional callback ``(action, outputs) → None`` called
141 after each successful execution (for stats / DB writes).
142 budget_bytes: Optional stop-early threshold. When cumulative actual
143 terminal bytes reaches this limit, remaining units are
144 skipped and returned as ``budget_stop`` names. ``None``
145 means unlimited.
146 unit_telemetry_cb: Optional callback
147 ``(unit_plan, terminal_identities, duration_seconds)``
148 called once per unit that produced terminal artifacts —
149 the CostModel feedback loop (``UnitTelemetryStore``).
150 ``duration_seconds`` is ``_run_unit``'s wall time for
151 that unit (extraction + transcode + CAS ingest); an
152 action-cache hit still reports its own (near-zero)
153 time, uncategorised.
154 """
156 def __init__(
157 self,
158 action_cache: ActionCache,
159 transforms: Mapping[str, Transform],
160 cas_dir: Path,
161 scratch_base: Path | None = None,
162 telemetry_cb: Callable[[Action, tuple[Identity, ...]], None] | None = None,
163 budget_bytes: int | None = None,
164 unit_telemetry_cb: Callable[[UnitPlan, tuple[Identity, ...], float], None] | None = None,
165 ) -> None:
166 self._cache = action_cache
167 self._transforms = transforms
168 self._cas = cas_dir
169 self._scratch_base = scratch_base or (cas_dir.parent / "scratch")
170 self._telemetry = telemetry_cb
171 self._unit_telemetry = unit_telemetry_cb
172 self._budget_bytes = budget_bytes
173 self._tree_store: object | None = None # lazy TreeStore, for kind="tree" outputs
175 # ------------------------------------------------------------------
176 # Public entry point
177 # ------------------------------------------------------------------
179 def _sweep_stale_scratch(self) -> None:
180 """Remove any leftover scratch dirs from previously killed runs."""
181 if not self._scratch_base.exists():
182 return
183 for entry in self._scratch_base.iterdir():
184 if entry.name.startswith("scratch_") and entry.is_dir():
185 try:
186 shutil.rmtree(entry)
187 logger.debug("swept stale scratch dir: %s", entry.name)
188 except OSError as exc:
189 logger.warning("could not sweep stale scratch %s: %s", entry, exc)
191 def run(self, plan: BuildPlan) -> OutputSet:
192 """Execute *plan* and return the set of terminal output identities.
194 When ``budget_bytes`` is set, units are expected to be in
195 rating-descending order (as produced by the budget pass). Once
196 cumulative actual terminal bytes reach the budget, remaining units
197 are skipped and their ``unit_id`` is recorded in
198 ``OutputSet.budget_stopped``.
199 """
200 self._sweep_stale_scratch()
201 all_outputs: dict[UnitId, tuple[Identity, ...]] = {}
202 budget_stopped: list[str] = []
203 cumulative_bytes = 0
205 for unit_plan in plan.units:
206 if self._budget_bytes is not None and cumulative_bytes >= self._budget_bytes:
207 budget_stopped.append(str(unit_plan.unit.unit_id))
208 logger.info(
209 "budget stop-early: skipping %s (cumulative %d bytes ≥ budget %d)",
210 unit_plan.unit.canonical_name,
211 cumulative_bytes,
212 self._budget_bytes,
213 )
214 continue
216 start = time.monotonic()
217 terminal = self._run_unit(unit_plan)
218 duration_seconds = time.monotonic() - start
219 if terminal:
220 all_outputs[unit_plan.unit.unit_id] = tuple(terminal)
221 cumulative_bytes += sum(ident.size or 0 for ident in terminal)
222 if self._unit_telemetry is not None:
223 self._unit_telemetry(unit_plan, tuple(terminal), duration_seconds)
225 import types
227 return OutputSet(
228 unit_outputs=types.MappingProxyType(all_outputs),
229 budget_stopped=tuple(budget_stopped),
230 )
232 # ------------------------------------------------------------------
233 # Per-unit execution
234 # ------------------------------------------------------------------
236 def _run_unit(self, unit_plan: UnitPlan) -> list[Identity]:
237 """Execute all actions for one game unit; return terminal identities."""
238 known_outputs: dict[ActionId, tuple[Identity, ...]] = {}
239 terminal_identities: list[Identity] = []
240 # Declared output names, so inputs can be materialised under the
241 # filenames tools expect (7z member names, chdman extension sniffing).
242 declared = {a.action_id: a.outputs for a in unit_plan.actions}
244 with ScratchDir(self._scratch_base, str(unit_plan.unit.unit_id)) as scratch:
245 for action in unit_plan.actions:
246 outputs = self._run_action(action, known_outputs, scratch, declared)
247 known_outputs[action.action_id] = outputs
249 # Collect terminal outputs
250 for decl, ident in zip(action.outputs, outputs, strict=False):
251 if decl.retention == Retention.TERMINAL:
252 terminal_identities.append(ident)
254 return terminal_identities
256 # ------------------------------------------------------------------
257 # Per-action execution
258 # ------------------------------------------------------------------
260 def _run_action(
261 self,
262 action: Action,
263 known_outputs: dict[ActionId, tuple[Identity, ...]],
264 scratch: Path,
265 declared: Mapping[ActionId, tuple[ArtifactDecl, ...]] | None = None,
266 ) -> tuple[Identity, ...]:
267 """Execute one action (cache-first); return resolved output identities."""
269 # Attempt early cache lookup
270 key = resolve_key(action, known_outputs)
271 if key is not None:
272 cached = self._cache.get(key)
273 if cached is not None:
274 # Verify every blob still exists — a deleted or GC'd blob would
275 # otherwise produce a materialise failure on the next step.
276 # On any missing blob, treat the row as a miss and re-execute.
277 missing = [
278 ident.sha256
279 for ident in cached
280 if ident.sha256 is not None and not _blob_exists(ident.sha256, self._cas)
281 ]
282 if not missing:
283 logger.debug("cache hit: %s (%s)", action.tool, key[:16])
284 return cached
285 logger.warning(
286 "cache hit for %s (%s) but %d blob(s) missing — re-executing",
287 action.tool,
288 key[:16],
289 len(missing),
290 )
292 # Materialise inputs into the scratch dir
293 input_paths = self._materialise_inputs(
294 action, known_outputs, scratch / action.action_id, declared or {}
295 )
297 # Run the transform
298 transform = self._transforms.get(action.tool)
299 if transform is None:
300 raise ValueError(f"No transform registered for tool '{action.tool}'")
302 logger.debug("executing: %s %s", action.tool, action.action_id)
303 output_paths = transform.run(input_paths, action.params, scratch)
305 # Ingest outputs into CAS and build Identity tuples.
306 # Capture size BEFORE ingest: _ingest_to_cas may rename the file out of
307 # scratch, making the path unavailable for stat() afterwards.
308 identities: list[Identity] = []
309 for out_path, decl in zip(output_paths, action.outputs, strict=False):
310 if decl.kind == "tree":
311 # Folder-shaped artifact (PS3 JB folder, etc.) — ingested via
312 # the CAS tree store (per-file dedup + a manifest blob),
313 # not the single-file blob path below.
314 manifest = self._get_tree_store().ingest(
315 out_path,
316 format=decl.kind,
317 source_name=decl.logical_name,
318 tool=action.tool,
319 tool_version=action.tool_version,
320 hardlink=True,
321 )
322 ident = Identity(sha256=manifest.tree_hash, size=manifest.total_size)
323 else:
324 file_size = out_path.stat().st_size
325 sha256 = _ingest_to_cas(out_path, self._cas)
326 ident = Identity(sha256=sha256, size=file_size)
327 self._cache.record_aliases(ident)
328 identities.append(ident)
330 result = tuple(identities)
332 # Store in action cache (resolves key now that outputs are known)
333 resolved_known = dict(known_outputs)
334 for aid, outs in zip([action.action_id], [result], strict=False):
335 resolved_known[aid] = outs
336 final_key = resolve_key(action, resolved_known)
337 if final_key is not None:
338 self._cache.store(final_key, result, action.tool, action.tool_version)
340 # Emit telemetry
341 if self._telemetry is not None:
342 self._telemetry(action, result)
344 return result
346 # ------------------------------------------------------------------
347 # Tree store (folder-shaped artifacts, e.g. PS3 JB folders)
348 # ------------------------------------------------------------------
350 def _get_tree_store(self) -> Any: # TreeStore (lazy import keeps engine→cas optional)
351 """Lazily construct the CAS tree store, sharing this executor's blob dir."""
352 if self._tree_store is None:
353 from romfarmer.cas.store import ContentStore
354 from romfarmer.cas.tree import TreeStore
356 self._tree_store = TreeStore(ContentStore(self._cas))
357 return self._tree_store
359 # ------------------------------------------------------------------
360 # Input materialisation
361 # ------------------------------------------------------------------
363 def _materialise_inputs(
364 self,
365 action: Action,
366 known_outputs: dict[ActionId, tuple[Identity, ...]],
367 dest_dir: Path,
368 declared: Mapping[ActionId, tuple[ArtifactDecl, ...]],
369 ) -> list[Path]:
370 """Copy / hardlink all action inputs into *dest_dir*.
372 Inputs produced by an earlier action are named after that action's
373 declared ``logical_name``; anything else falls back to ``input_NNN``.
374 """
375 dest_dir.mkdir(parents=True, exist_ok=True)
376 paths: list[Path] = []
377 used: set[str] = set()
379 for idx, inp in enumerate(action.inputs):
380 sha256: str
381 name = f"input_{idx:03d}"
382 if isinstance(inp, ContentRef):
383 sha256 = inp.sha256
384 else: # PendingRef — must be resolved by now
385 assert isinstance(inp, PendingRef)
386 outputs = known_outputs.get(inp.producer)
387 if outputs is None or inp.output_index >= len(outputs):
388 raise RuntimeError(
389 f"Cannot materialise PendingRef {inp} — producer outputs not yet known"
390 )
391 raw_sha = outputs[inp.output_index].sha256
392 if raw_sha is None:
393 raise RuntimeError(
394 f"PendingRef {inp} output identity is incomplete (no sha256)"
395 )
396 sha256 = raw_sha
397 decls = declared.get(inp.producer, ())
398 if inp.output_index < len(decls):
399 name = Path(decls[inp.output_index].logical_name).name
400 if name in used:
401 name = f"{idx:03d}_{name}"
402 used.add(name)
403 dest = dest_dir / name
404 _materialise_from_cas(sha256, self._cas, dest)
405 paths.append(dest)
407 return paths