Coverage for src/romfarmer/analysis/file_digest_cache.py: 81%

54 statements  

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

1"""File digest cache — fast-path memoisation for CATALOG phase. 

2 

3Avoids re-hashing unchanged source files on every build by storing 

4``(size, mtime_ns, inode) → md5`` in a lightweight SQLite table. 

5 

6Design follows Git's index and Bazel's digest cache: 

7- Hit requires ALL THREE of (size, mtime_ns, inode) to match. 

8- Racy guard: if a file's mtime_ns falls within the same second as the 

9 scan's start time, the entry is treated as a miss (re-hash anyway). 

10 This matches the "racy-stat" guard in Git. 

11- Writer: CatalogBuilder only — sole-writer doctrine. 

12 

13Known failure modes and their status: 

14- Coarse mtime (FAT, 2 s granularity): covered by racy guard. 

15- mtime-preserving replace (rsync -a): the only true hole; accepted risk 

16 with a ``force_rehash=True`` escape hatch on CatalogBuilder.build(). 

17- NFS unstable inodes: not this deployment. 

18- Reflink copies: get new inodes → correct cache miss. 

19""" 

20 

21from __future__ import annotations 

22 

23import logging 

24import os 

25import sqlite3 

26from dataclasses import dataclass 

27from pathlib import Path 

28 

29logger = logging.getLogger(__name__) 

30 

31_DDL = """ 

32CREATE TABLE IF NOT EXISTS file_digest_cache ( 

33 path TEXT PRIMARY KEY, 

34 size INTEGER NOT NULL, 

35 mtime_ns INTEGER NOT NULL, 

36 inode INTEGER NOT NULL, 

37 md5 TEXT, 

38 updated_at TEXT NOT NULL 

39 DEFAULT (strftime('%Y-%m-%dT%H:%M:%SZ', 'now')) 

40); 

41""" 

42 

43# Added after the initial schema: dominant zip member (name, crc32, size) so 

44# a warm CATALOG needs no zip I/O at all. NULL for non-zip files. 

45_MIGRATIONS = ( 

46 "ALTER TABLE file_digest_cache ADD COLUMN member_name TEXT", 

47 "ALTER TABLE file_digest_cache ADD COLUMN member_crc32 INTEGER", 

48 "ALTER TABLE file_digest_cache ADD COLUMN member_size INTEGER", 

49) 

50 

51 

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

53class DigestEntry: 

54 md5: str | None 

55 member_name: str | None = None 

56 member_crc32: int | None = None 

57 member_size: int | None = None 

58 

59 

60class FileDigestCache: 

61 """Fast-path md5 cache keyed on ``(size, mtime_ns, inode)`` triples. 

62 

63 Thread-safe for concurrent readers under WAL mode. 

64 ``CatalogBuilder`` is the sole writer of this table. 

65 """ 

66 

67 def __init__(self, db_path: Path) -> None: 

68 self._db_path = db_path 

69 db_path.parent.mkdir(parents=True, exist_ok=True) 

70 self._conn = sqlite3.connect(str(db_path), check_same_thread=False, isolation_level=None) 

71 self._conn.execute("PRAGMA journal_mode=WAL") 

72 self._conn.execute("PRAGMA busy_timeout=30000") 

73 self._conn.executescript(_DDL) 

74 existing = {r[1] for r in self._conn.execute("PRAGMA table_info(file_digest_cache)")} 

75 for stmt in _MIGRATIONS: 

76 if stmt.split(" ADD COLUMN ")[1].split()[0] not in existing: 

77 self._conn.execute(stmt) 

78 

79 def close(self) -> None: 

80 self._conn.close() 

81 

82 def __enter__(self) -> FileDigestCache: 

83 return self 

84 

85 def __exit__(self, *_: object) -> None: 

86 self.close() 

87 

88 def lookup( 

89 self, 

90 path: Path, 

91 stat: os.stat_result, 

92 scan_start_ns: int, 

93 ) -> str | None: 

94 """Return cached md5 if the stat triple matches; ``None`` on miss.""" 

95 entry = self.lookup_entry(path, stat, scan_start_ns) 

96 return entry.md5 if entry is not None else None 

97 

98 def lookup_entry( 

99 self, 

100 path: Path, 

101 stat: os.stat_result, 

102 scan_start_ns: int, 

103 ) -> DigestEntry | None: 

104 """Return the full cached entry if the stat triple matches; ``None`` on miss. 

105 

106 Racy guard: if ``stat.st_mtime_ns // 1_000_000_000`` equals 

107 ``scan_start_ns // 1_000_000_000``, the entry is treated as a miss 

108 regardless of the cached value. 

109 """ 

110 # Racy guard: mtime within the current second → force re-hash 

111 if stat.st_mtime_ns // 1_000_000_000 >= scan_start_ns // 1_000_000_000: 

112 return None 

113 

114 row = self._conn.execute( 

115 "SELECT md5, member_name, member_crc32, member_size FROM file_digest_cache " 

116 "WHERE path = ? AND size = ? AND mtime_ns = ? AND inode = ?", 

117 (str(path), stat.st_size, stat.st_mtime_ns, stat.st_ino), 

118 ).fetchone() 

119 if row is None: 

120 return None 

121 return DigestEntry( 

122 md5=str(row[0]) if row[0] is not None else None, 

123 member_name=row[1], 

124 member_crc32=row[2], 

125 member_size=row[3], 

126 ) 

127 

128 def store( 

129 self, 

130 path: Path, 

131 stat: os.stat_result, 

132 md5: str | None, 

133 member: tuple[str, int, int] | None = None, 

134 ) -> None: 

135 """Upsert the digest entry for *path* (``member`` = name, crc32, size).""" 

136 name, crc, size = member if member is not None else (None, None, None) 

137 with self._conn: 

138 self._conn.execute( 

139 """ 

140 INSERT INTO file_digest_cache 

141 (path, size, mtime_ns, inode, md5, member_name, member_crc32, member_size) 

142 VALUES (?, ?, ?, ?, ?, ?, ?, ?) 

143 ON CONFLICT(path) DO UPDATE SET 

144 size = excluded.size, 

145 mtime_ns = excluded.mtime_ns, 

146 inode = excluded.inode, 

147 md5 = excluded.md5, 

148 member_name = excluded.member_name, 

149 member_crc32 = excluded.member_crc32, 

150 member_size = excluded.member_size, 

151 updated_at = strftime('%Y-%m-%dT%H:%M:%SZ', 'now') 

152 """, 

153 (str(path), stat.st_size, stat.st_mtime_ns, stat.st_ino, md5, name, crc, size), 

154 ) 

155 

156 def prune_missing(self, known_paths: set[str]) -> int: 

157 """Delete rows for paths no longer in *known_paths*. Returns count.""" 

158 rows = self._conn.execute("SELECT path FROM file_digest_cache").fetchall() 

159 to_delete = [r[0] for r in rows if r[0] not in known_paths] 

160 if to_delete: 

161 with self._conn: 

162 self._conn.executemany( 

163 "DELETE FROM file_digest_cache WHERE path = ?", 

164 [(p,) for p in to_delete], 

165 ) 

166 return len(to_delete)