Coverage for src/romfarmer/ir/actions.py: 93%

76 statements  

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

1"""Actions — the action graph layer of the ROM Farmer IR. 

2 

3``Action`` is the unit of caching: one tool invocation with typed 

4inputs/outputs. ``BuildPlan`` is the full DAG. ``resolve_key`` computes the 

5``ActionKey`` (the global cache key) once all input identities are known. 

6 

7The canonical form used by ``resolve_key`` is FROZEN FOREVER — changing it 

8invalidates the action cache for every user. See the golden test. 

9""" 

10 

11from __future__ import annotations 

12 

13import enum 

14import hashlib 

15import json 

16import types 

17import unicodedata 

18from collections.abc import Mapping 

19from dataclasses import dataclass 

20from typing import NewType 

21 

22from .catalog import GameUnit 

23from .identity import Identity 

24 

25ActionId = NewType("ActionId", str) 

26# GLOBAL cache key: sha256(canonical JSON of tool, tool_version, params, resolved inputs) 

27ActionKey = NewType("ActionKey", str) 

28 

29 

30@dataclass(frozen=True, slots=True) 

31class ContentRef: 

32 """An input whose content identity (sha256) is known at plan time.""" 

33 

34 sha256: str 

35 

36 

37@dataclass(frozen=True, slots=True) 

38class PendingRef: 

39 """An input whose sha256 is only known once its producer has run (or hit cache).""" 

40 

41 producer: ActionId 

42 output_index: int 

43 

44 

45InputRef = ContentRef | PendingRef 

46 

47 

48class Retention(enum.Enum): 

49 INTERMEDIATE = "intermediate" # GC-eligible once all consumers are done 

50 TERMINAL = "terminal" # pinned while any LayoutEntry references it 

51 

52 

53@dataclass(frozen=True, slots=True) 

54class ArtifactDecl: 

55 """Declaration of one output artifact from an ``Action``.""" 

56 

57 logical_name: str # e.g. "Halo (USA).iso" 

58 kind: str # "xiso" | "chd" | "m3u" | "squashfs" | "tree" | ... 

59 retention: Retention 

60 

61 

62@dataclass(frozen=True, slots=True) 

63class Action: 

64 """One tool invocation in the build plan. 

65 

66 ``params`` is stored as an immutable ``MappingProxyType`` regardless of 

67 what the caller passes. The ``__post_init__`` wraps any plain ``dict`` or 

68 other ``Mapping`` automatically. Caller code may pass a plain ``dict`` for 

69 convenience; it will be frozen on construction. 

70 """ 

71 

72 action_id: ActionId 

73 tool: str # "unzip" | "extract-xiso" | "mksquashfs" | "chdman" | ... 

74 tool_version: str # version bump → cache miss, by design 

75 params: Mapping[str, str] 

76 inputs: tuple[InputRef, ...] 

77 outputs: tuple[ArtifactDecl, ...] 

78 

79 def __post_init__(self) -> None: 

80 # Validate param types, NFC-normalize values, then freeze into 

81 # MappingProxyType. All three steps happen unconditionally so that 

82 # a MappingProxyType passed directly is also validated and normalized. 

83 # 

84 # Type rule: both keys and values MUST be str. Anything else (int, 

85 # float, None …) would serialize differently from its str equivalent 

86 # and could produce silent key mismatches or false cache hits. 

87 # 

88 # NFC rule: normalize values to Unicode NFC before freezing. Mac 

89 # HFS+ supplies NFD filenames (decomposed accents); without this a 

90 # "Pokémon" param value would produce two different ActionKeys 

91 # depending on where the source files were copied from. 

92 raw: dict[str, str] = {} 

93 for k, v in self.params.items(): 

94 if not isinstance(k, str): 

95 raise TypeError(f"Action param keys must be str; got {type(k).__name__}: {k!r}") 

96 if not isinstance(v, str): 

97 raise TypeError(f"Action param values must be str; got {type(v).__name__}: {v!r}") 

98 raw[k] = unicodedata.normalize("NFC", v) 

99 object.__setattr__(self, "params", types.MappingProxyType(raw)) 

100 

101 

102@dataclass(frozen=True, slots=True) 

103class SizePrediction: 

104 """Cost-model output for one ``GameUnit``.""" 

105 

106 ratio: float 

107 source: str # "telemetry:psx/chd,n=212" | "prior:size_data.json" 

108 confidence: float # 0..1; scales the per-unit safety margin 

109 

110 

111@dataclass(frozen=True, slots=True) 

112class UnitPlan: 

113 """The scheduled work for one ``GameUnit``.""" 

114 

115 unit: GameUnit 

116 actions: tuple[Action, ...] 

117 predicted_output_bytes: int 

118 prediction: SizePrediction 

119 

120 

121@dataclass(frozen=True, slots=True) 

122class BuildPlan: 

123 """The complete action DAG for one build.""" 

124 

125 units: tuple[UnitPlan, ...] 

126 

127 

128# --------------------------------------------------------------------------- 

129# ActionKey resolution 

130# --------------------------------------------------------------------------- 

131 

132 

133def resolve_key( 

134 action: Action, 

135 known_outputs: Mapping[ActionId, tuple[Identity, ...]], 

136) -> ActionKey | None: 

137 """Compute the global cache key for ``action`` given resolved output identities. 

138 

139 Returns ``None`` while any ``PendingRef`` input's producer either: 

140 - is not yet present in ``known_outputs``, or 

141 - has a ``None`` sha256 for the referenced output index. 

142 

143 ``known_outputs`` is populated from BOTH cache rows and just-executed 

144 actions — the executor drives this. 

145 

146 ────────────────────────────────────────────────────────────────────── 

147 CANONICAL FORM — FROZEN FOREVER 

148 ────────────────────────────────────────────────────────────────────── 

149 ActionKey = sha256_hex(UTF-8(canonical_json)) where canonical_json is: 

150 

151 {"inputs":[<sha256>,...], "params":{<sorted>}, "tool":..., "tool_version":...} 

152 

153 - Top-level keys are sorted alphabetically (sort_keys=True). 

154 - Inputs are the resolved sha256 strings in declared order. 

155 - params keys are sorted before serialization. 

156 - No whitespace (separators=(",", ":")). 

157 

158 This is Nix-style content addressing: ActionKey hashes the *content 

159 identity* of inputs, not upstream ActionKeys. Early cutoff: if an 

160 upstream action re-runs but produces byte-identical output, every 

161 downstream key is unchanged and still hits the cache. 

162 

163 Changing any aspect of this form is a cache-invalidation event for 

164 every user — never a casual update. 

165 ────────────────────────────────────────────────────────────────────── 

166 """ 

167 resolved_inputs: list[str] = [] 

168 for inp in action.inputs: 

169 if isinstance(inp, ContentRef): 

170 resolved_inputs.append(inp.sha256) 

171 else: # PendingRef 

172 outputs = known_outputs.get(inp.producer) 

173 if outputs is None: 

174 return None 

175 if inp.output_index >= len(outputs): 

176 return None 

177 sha256 = outputs[inp.output_index].sha256 

178 if sha256 is None: 

179 return None 

180 resolved_inputs.append(sha256) 

181 

182 canonical = json.dumps( 

183 { 

184 "inputs": resolved_inputs, 

185 "params": dict(sorted(action.params.items())), 

186 "tool": action.tool, 

187 "tool_version": action.tool_version, 

188 }, 

189 separators=(",", ":"), 

190 sort_keys=True, 

191 ) 

192 return ActionKey(hashlib.sha256(canonical.encode("utf-8")).hexdigest())