Coverage for src/romfarmer/engine/actioncache.py: 95%
82 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"""ActionCache — the new SQLite-backed action cache for the ROM Farmer engine.
3Uses raw sqlite3 (no SQLAlchemy) over two new tables in the shared
4``metadata/database/romfarmer.db``:
6 action_cache(key, outputs_json, tool, tool_version, created_at)
7 artifact_aliases(sha256, md5, zip_crc32, zip_size, zip_member)
9This module is the **SOLE WRITER** of ``artifact_aliases``. Every
10known alias for an artifact is written atomically in one transaction
11(method ``record_aliases``). This is the structural fix for the
12MD5-vs-CRC32 cache divergence described in system briefing §3.9:
13previously, CAS ingest and DAT matching each wrote their own alias
14independently, so a lookup by the *other* alias missed even though
15the file was cached.
16"""
18from __future__ import annotations
20import json
21import sqlite3
22from collections.abc import Sequence
23from pathlib import Path
25from romfarmer.ir.actions import ActionKey
26from romfarmer.ir.identity import Identity, ZipIdentity
28# ---------------------------------------------------------------------------
29# DDL
30# ---------------------------------------------------------------------------
32_DDL = """
33CREATE TABLE IF NOT EXISTS action_cache (
34 key TEXT PRIMARY KEY,
35 outputs_json TEXT NOT NULL,
36 tool TEXT NOT NULL,
37 tool_version TEXT NOT NULL,
38 created_at TEXT NOT NULL
39 DEFAULT (strftime('%Y-%m-%dT%H:%M:%SZ', 'now'))
40);
42CREATE TABLE IF NOT EXISTS artifact_aliases (
43 sha256 TEXT NOT NULL,
44 md5 TEXT,
45 zip_crc32 INTEGER,
46 zip_size INTEGER,
47 zip_member TEXT
48);
50CREATE UNIQUE INDEX IF NOT EXISTS ix_aliases_sha256
51 ON artifact_aliases (sha256);
53CREATE INDEX IF NOT EXISTS ix_aliases_md5
54 ON artifact_aliases (md5)
55 WHERE md5 IS NOT NULL;
57CREATE INDEX IF NOT EXISTS ix_aliases_zip
58 ON artifact_aliases (zip_crc32, zip_size)
59 WHERE zip_crc32 IS NOT NULL;
60"""
63# ---------------------------------------------------------------------------
64# Serialization helpers
65# ---------------------------------------------------------------------------
68def _identity_to_dict(ident: Identity) -> dict[str, object]:
69 d: dict[str, object] = {
70 "sha256": ident.sha256,
71 "md5": ident.md5,
72 "size": ident.size,
73 }
74 if ident.zip_identity is not None:
75 d["zip_crc32"] = ident.zip_identity.member_crc32
76 d["zip_size"] = ident.zip_identity.member_size
77 d["zip_member"] = ident.zip_identity.member_name
78 return d
81def _dict_to_identity(d: dict[str, object]) -> Identity:
82 zi: ZipIdentity | None = None
83 crc_val = d.get("zip_crc32")
84 sz_val = d.get("zip_size")
85 mem_val = d.get("zip_member")
86 if crc_val is not None and sz_val is not None and mem_val is not None:
87 zi = ZipIdentity(
88 member_crc32=int(str(crc_val)),
89 member_size=int(str(sz_val)),
90 member_name=str(mem_val),
91 )
92 size_val = d.get("size")
93 sha_val = d.get("sha256")
94 md5_val = d.get("md5")
95 return Identity(
96 sha256=str(sha_val) if sha_val else None,
97 md5=str(md5_val) if md5_val else None,
98 size=int(str(size_val)) if size_val is not None else None,
99 zip_identity=zi,
100 )
103# ---------------------------------------------------------------------------
104# ActionCache
105# ---------------------------------------------------------------------------
108class ActionCache:
109 """SQLite facade over ``action_cache`` + ``artifact_aliases`` tables.
111 Thread-safe for concurrent readers; writes are serialised by SQLite's
112 WAL mode. The database file is the shared ``romfarmer.db`` so the
113 tables coexist with the existing ``rom_cache`` / ``rom_transformation``
114 etc. tables.
115 """
117 def __init__(self, db_path: Path) -> None:
118 self._db_path = db_path
119 db_path.parent.mkdir(parents=True, exist_ok=True)
120 self._conn = sqlite3.connect(str(db_path), check_same_thread=False, isolation_level=None)
121 self._conn.execute("PRAGMA journal_mode=WAL")
122 self._conn.execute("PRAGMA busy_timeout=30000")
123 self._conn.execute("PRAGMA foreign_keys=ON")
124 self._conn.executescript(_DDL)
126 def close(self) -> None:
127 self._conn.close()
129 def __enter__(self) -> ActionCache:
130 return self
132 def __exit__(self, *_: object) -> None:
133 self.close()
135 # ------------------------------------------------------------------
136 # Action cache operations
137 # ------------------------------------------------------------------
139 def get(self, key: ActionKey) -> tuple[Identity, ...] | None:
140 """Return cached output identities for *key*, or ``None`` on miss."""
141 row = self._conn.execute(
142 "SELECT outputs_json FROM action_cache WHERE key = ?", (key,)
143 ).fetchone()
144 if row is None:
145 return None
146 raw: list[dict[str, object]] = json.loads(row[0])
147 return tuple(_dict_to_identity(d) for d in raw)
149 def store(
150 self,
151 key: ActionKey,
152 outputs: Sequence[Identity],
153 tool: str,
154 tool_version: str,
155 ) -> None:
156 """Store action outputs and atomically write all known aliases.
158 On conflict (same key already present) the existing row is kept —
159 identical ActionKey means identical result by construction.
160 """
161 outputs_json = json.dumps([_identity_to_dict(o) for o in outputs])
162 with self._conn:
163 self._conn.execute(
164 """
165 INSERT OR IGNORE INTO action_cache
166 (key, outputs_json, tool, tool_version)
167 VALUES (?, ?, ?, ?)
168 """,
169 (key, outputs_json, tool, tool_version),
170 )
171 for ident in outputs:
172 if ident.sha256 is not None:
173 self._record_aliases_in_tx(ident)
175 # ------------------------------------------------------------------
176 # Alias operations (SOLE WRITER of artifact_aliases)
177 # ------------------------------------------------------------------
179 def record_aliases(self, identity: Identity) -> None:
180 """Atomically write all known aliases for *identity*.
182 ``identity.sha256`` MUST be set — the executor only calls this
183 after computing or verifying the sha256 of an output file.
185 Raises:
186 ValueError: if ``identity.sha256`` is None.
187 """
188 if identity.sha256 is None:
189 raise ValueError("ActionCache.record_aliases requires a non-null sha256")
190 with self._conn:
191 self._record_aliases_in_tx(identity)
193 def _record_aliases_in_tx(self, identity: Identity) -> None:
194 """Write alias row inside the caller's transaction (no commit)."""
195 assert identity.sha256 is not None
196 zi = identity.zip_identity
197 self._conn.execute(
198 """
199 INSERT INTO artifact_aliases (sha256, md5, zip_crc32, zip_size, zip_member)
200 VALUES (?, ?, ?, ?, ?)
201 ON CONFLICT(sha256) DO UPDATE SET
202 md5 = COALESCE(excluded.md5, md5),
203 zip_crc32 = COALESCE(excluded.zip_crc32, zip_crc32),
204 zip_size = COALESCE(excluded.zip_size, zip_size),
205 zip_member = COALESCE(excluded.zip_member, zip_member)
206 """,
207 (
208 identity.sha256,
209 identity.md5,
210 zi.member_crc32 if zi else None,
211 zi.member_size if zi else None,
212 zi.member_name if zi else None,
213 ),
214 )
216 def lookup_by_md5(self, md5: str) -> Identity | None:
217 """Look up the full identity for a file known by its MD5 alias."""
218 row = self._conn.execute(
219 "SELECT sha256, md5, zip_crc32, zip_size, zip_member "
220 "FROM artifact_aliases WHERE md5 = ?",
221 (md5,),
222 ).fetchone()
223 if row is None:
224 return None
225 return self._row_to_identity(row)
227 def lookup_by_zip(self, crc32: int, size: int, member: str | None = None) -> Identity | None:
228 """Look up the full identity for a file known by its ZIP identity."""
229 if member is not None:
230 row = self._conn.execute(
231 "SELECT sha256, md5, zip_crc32, zip_size, zip_member "
232 "FROM artifact_aliases "
233 "WHERE zip_crc32 = ? AND zip_size = ? AND zip_member = ?",
234 (crc32, size, member),
235 ).fetchone()
236 else:
237 row = self._conn.execute(
238 "SELECT sha256, md5, zip_crc32, zip_size, zip_member "
239 "FROM artifact_aliases WHERE zip_crc32 = ? AND zip_size = ?",
240 (crc32, size),
241 ).fetchone()
242 if row is None:
243 return None
244 return self._row_to_identity(row)
246 # ------------------------------------------------------------------
247 # Internal helpers
248 # ------------------------------------------------------------------
250 @staticmethod
251 def _row_to_identity(
252 row: tuple[str | None, str | None, int | None, int | None, str | None],
253 ) -> Identity:
254 sha256, md5, zip_crc32, zip_size, zip_member = row
255 zi: ZipIdentity | None = None
256 if zip_crc32 is not None and zip_size is not None and zip_member is not None:
257 zi = ZipIdentity(
258 member_crc32=zip_crc32,
259 member_size=zip_size,
260 member_name=zip_member,
261 )
262 return Identity(sha256=sha256, md5=md5, zip_identity=zi)