Coverage for src/romfarmer/driver/session.py: 96%

93 statements  

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

1"""PlanSession — INVENTORY once, replan many times (intent brief v3 §4 / v4 §4). 

2 

3CATALOG is NAS-I/O bound (9m50 wall / 20 s CPU for 20 platforms); PLAN is 

4~30 ms. The agent loop therefore catalogs each platform once per session 

5and iterates ``run_plan`` alone. Catalogs are cached by 

6``(platform, source dirs, dat file)`` and each carries an 

7``inventory_digest`` — sha256 over every disc's path + strongest identity 

8(derived from the Catalog itself, zero extra I/O) — which the Spec records as 

9``intent.inventory_digest``. Within a session the cache is frozen by design 

10(INVENTORY once); a new session re-catalogs through the FileDigestCache's 

11stat check. 

12""" 

13 

14from __future__ import annotations 

15 

16import hashlib 

17import logging 

18from dataclasses import dataclass, field 

19from pathlib import Path 

20from typing import Any 

21 

22from romfarmer.ir.catalog import Catalog 

23from romfarmer.ir.spec import Spec 

24 

25from .capability import Capabilities, capabilities 

26from .resolve import ResolvedBuild 

27from .spec_resolve import resolve_build 

28from .summary import PlanSummary, PlatformSummary, summarize, summarize_platform 

29 

30logger = logging.getLogger(__name__) 

31 

32 

33def inventory_digest(catalog: Catalog) -> str: 

34 """``sha256:<hex>`` over every disc's path and its strongest known identity. 

35 

36 Identity precedence is sha256 > md5 > zip ``crc32:size:member`` (from the 

37 zip central directory, which CATALOG always reads), falling back to size 

38 only when the catalog has no hash at all. A repaired ROM at the same 

39 path and size therefore changes the digest — the G4 #3 class of staleness 

40 is not invisible here. 

41 """ 

42 h = hashlib.sha256() 

43 for u in sorted(catalog.units, key=lambda u: u.unit_id): 

44 for d in u.discs: 

45 ident = d.identity 

46 try: 

47 kind, value = ident.best_key() 

48 except ValueError: 

49 kind, value = "size", str(ident.size or 0) 

50 h.update(f"{d.source.path}\0{kind}:{value}\n".encode()) 

51 return "sha256:" + h.hexdigest() 

52 

53 

54@dataclass 

55class PlanSession: 

56 """Holds cached Catalogs + shared KB/CostModel for one agent session.""" 

57 

58 workspace_root: Path 

59 config_root: Path 

60 _catalogs: dict[tuple[str, tuple[str, ...], str], Catalog] = field(default_factory=dict) 

61 _kb: Any = None 

62 _cost_model: Any = None 

63 

64 # ------------------------------------------------------------------ 

65 

66 def kb(self) -> Any: 

67 if self._kb is None: 

68 from romfarmer.analysis.knowledge import KnowledgeBase 

69 from romfarmer.driver.workspace import Workspace 

70 

71 db = Workspace.at(self.workspace_root).metadata_db 

72 self._kb = KnowledgeBase(db if db.exists() else None) 

73 return self._kb 

74 

75 def cost_model(self) -> Any: 

76 if self._cost_model is None: 

77 from romfarmer.planner import CostModel 

78 

79 sd = self.config_root / "size_data.json" 

80 self._cost_model = CostModel( 

81 size_data_path=sd if sd.exists() else None, knowledge_base=self.kb() 

82 ) 

83 return self._cost_model 

84 

85 def _key(self, rb: ResolvedBuild) -> tuple[str, tuple[str, ...], str]: 

86 return (rb.platform, tuple(str(d) for d, _ in rb.source_dirs), str(rb.dat_file or "")) 

87 

88 def catalog(self, rb: ResolvedBuild) -> Catalog: 

89 """CATALOG for *rb*, computed once per (platform, sources, DAT) per session.""" 

90 key = self._key(rb) 

91 cat = self._catalogs.get(key) 

92 if cat is None: 

93 from romfarmer.new_orchestrator import run_catalog 

94 

95 logger.info("INVENTORY %s: cataloging %s", rb.platform, ", ".join(key[1])) 

96 from romfarmer.driver.workspace import Workspace 

97 

98 cat = run_catalog( 

99 rb.resolved, 

100 source_dir=rb.source_dir, 

101 dat_file=rb.dat_file, 

102 kb=self.kb(), 

103 digest_db=Workspace.at(self.workspace_root).metadata_db, 

104 ) 

105 self._catalogs[key] = cat 

106 return cat 

107 

108 def inventory(self, spec: Spec) -> dict[str, dict[str, Any]]: 

109 """INVENTORY step: catalog every platform of *spec*; returns per-platform facts.""" 

110 out: dict[str, dict[str, Any]] = {} 

111 for rb in resolve_build(spec, self.config_root, workspace_root=self.workspace_root): 

112 cat = self.catalog(rb) 

113 files = sum(len(u.discs) for u in cat.units) 

114 out[rb.platform] = { 

115 "units": len(cat.units), 

116 "files": files, 

117 "bytes": sum(u.source_size for u in cat.units), 

118 "dat_matched": sum(1 for u in cat.units if any(d.dat_name for d in u.discs)), 

119 "rated": sum(1 for u in cat.units if u.rating is not None), 

120 "inventory_digest": inventory_digest(cat), 

121 } 

122 combined = hashlib.sha256() 

123 for plat in sorted(out): 

124 combined.update(f"{plat}={out[plat]['inventory_digest']}\n".encode()) 

125 result: dict[str, Any] = dict(out) 

126 result["_inventory_digest"] = "sha256:" + combined.hexdigest() 

127 return result 

128 

129 def capabilities(self, spec: Spec) -> Capabilities: 

130 return capabilities(spec.target.frontend, spec.target.device, self.config_root) 

131 

132 def dry_run(self, spec: Spec) -> PlanSummary: 

133 """VALIDATE + PLAN over cached catalogs → PlanSummary. Zero bytes moved.""" 

134 from romfarmer.driver.workspace import Workspace 

135 from romfarmer.engine.telemetry import UnitTelemetryStore 

136 from romfarmer.new_orchestrator import run_plan 

137 

138 caps = self.capabilities(spec) 

139 db = Workspace.at(self.workspace_root).metadata_db 

140 tele = UnitTelemetryStore(db) if db.exists() else None 

141 rows: list[PlatformSummary] = [] 

142 try: 

143 for rb in resolve_build(spec, self.config_root, workspace_root=self.workspace_root): 

144 cat = self.catalog(rb) 

145 planned = run_plan( 

146 cat, rb.manifest, cost_model=self.cost_model(), kb=self.kb(), chain=rb.chain 

147 ) 

148 tool = rb.chain[0] if rb.chain else "" 

149 tq = tele.quantiles(rb.platform, tool) if tele is not None else {} 

150 try: 

151 cap = caps.require(rb.platform) 

152 tier, quality = cap.tier, cap.quality 

153 except KeyError: 

154 tier, quality = None, None 

155 rows.append( 

156 summarize_platform( 

157 platform=rb.platform, 

158 chain=rb.chain, 

159 catalog_in=cat, 

160 catalog_out=planned.catalog, 

161 traces=tuple(planned.traces), 

162 stages=tuple(planned.stages), 

163 cost_model=self.cost_model(), 

164 telemetry_quantiles=tq or None, 

165 tier=tier, 

166 quality=quality, 

167 unrated_rank=rb.manifest.unrated_rank(), 

168 max_bytes=rb.manifest.budget_bytes, 

169 preferred_chain=(caps.formats.get(rb.platform) or (None,))[0], 

170 resolve_notes=rb.notes, 

171 ) 

172 ) 

173 finally: 

174 if tele is not None: 

175 tele.close() 

176 return summarize( 

177 spec.spec_hash(), 

178 rows, 

179 storage_bytes=spec.target.storage_bytes, 

180 reserve_bytes=spec.target.reserve_bytes 

181 if spec.target.reserve_bytes is not None 

182 else caps.reserve_bytes, 

183 allocation_note=spec.intent.allocation_note, 

184 )