Coverage for src/romfarmer/engine/transforms/base.py: 100%

16 statements  

« prev     ^ index     » next       coverage.py v7.15.4, created at 2026-09-05 02:19 -0700

1"""Transform protocol — the cache-unaware tool-invocation interface. 

2 

3A :class:`Transform` knows nothing about :class:`StageContext`, caches, 

4databases, or the IR. It takes a list of input files, a parameter mapping, 

5and a scratch directory; it returns a list of output files (inside *scratch* 

6or elsewhere). The :class:`~romfarmer.engine.executor.Executor` handles 

7caching, CAS ingestion, and identity tracking. 

8""" 

9 

10from __future__ import annotations 

11 

12import os 

13from collections.abc import Mapping 

14from pathlib import Path 

15from typing import Protocol, runtime_checkable 

16 

17# Environment handed to every external tool. Locale/timezone/SOURCE_DATE_EPOCH 

18# are pinned so tool output cannot vary with the operator's shell; only the 

19# variables needed to locate binaries and scratch space pass through. 

20_PASSTHROUGH_ENV = ("PATH", "HOME", "TMPDIR", "TMP", "TEMP") 

21 

22 

23def pinned_env() -> dict[str, str]: 

24 """Return the deterministic subprocess environment for transforms.""" 

25 env = {k: v for k in _PASSTHROUGH_ENV if (v := os.environ.get(k)) is not None} 

26 env.update(LC_ALL="C", LANG="C", TZ="UTC", SOURCE_DATE_EPOCH="0") 

27 return env 

28 

29 

30class TransformError(Exception): 

31 """Raised when a Transform fails to produce its expected outputs.""" 

32 

33 

34@runtime_checkable 

35class Transform(Protocol): 

36 """Protocol for all tool-invocation cores. 

37 

38 Implementations: 

39 - Must be **cache-unaware** and **context-unaware**. 

40 - Must write outputs inside *scratch* (or return absolute paths). 

41 - Must raise :class:`TransformError` on non-zero tool exit codes. 

42 - May raise standard :mod:`subprocess` / :mod:`os` exceptions for 

43 lower-level failures. 

44 """ 

45 

46 name: str 

47 """Stable identifier used as the ``tool`` field in :class:`ActionKey`.""" 

48 

49 def run( 

50 self, 

51 inputs: list[Path], 

52 params: Mapping[str, str], 

53 scratch: Path, 

54 ) -> list[Path]: 

55 """Execute the transformation. 

56 

57 Args: 

58 inputs: Materialised input file paths (from CAS). 

59 params: Immutable parameter mapping (from :class:`Action.params`). 

60 scratch: Writable directory for intermediate and output files. 

61 

62 Returns: 

63 List of output file paths (in *scratch* or absolute CAS paths). 

64 

65 Raises: 

66 TransformError: tool returned non-zero or produced no output. 

67 """ 

68 ...