Coverage for src/governed_harness/review/cache.py: 84%

71 statements  

« prev     ^ index     » next       coverage.py v7.17.2, created at 2026-11-12 16:06 +0000

1"""The review cache (#57): one global entry per review and one entry per reviewer answer. 

2 

3* The **global key** binds a whole report: mode, diff hash, reviewer definitions hash, runner 

4 version, skip flags, forced model, provider, fallback provider and options. The same review of 

5 the same diff in the same mode is not repeated. 

6* The **per-reviewer key** leaves the mode out, so a manual review and the pre-push hook reuse 

7 each other's answers: cache version, base, provider, fallback, forced model, reviewer, model, 

8 slice hash, prompt hash, message hash (which includes the reportable locations and the slice 

9 diff), definition hash, runner version, MCP configuration hash and options. 

10 

11Entries live as JSON files under ``.harness/review/cache`` with a time to live and an entry 

12limit (the oldest go first). A corrupt entry is a miss.""" 

13 

14from __future__ import annotations 

15 

16import json 

17import os 

18import tempfile 

19import time 

20from collections.abc import Callable 

21from pathlib import Path 

22from typing import Any 

23 

24from governed_harness.evidence.hashing import sha256_json 

25 

26CACHE_VERSION = "1" 

27CACHE_DIRECTORY = ".harness/review/cache" 

28 

29 

30def global_key( 

31 *, 

32 mode: str, 

33 diff_hash: str, 

34 definitions_hash: str, 

35 runner_version: str, 

36 skip: tuple[str, ...], 

37 forced_model: str | None, 

38 provider: str, 

39 fallback: str | None, 

40 options: dict[str, Any], 

41) -> str: 

42 return sha256_json( 

43 { 

44 "kind": "global", 

45 "version": CACHE_VERSION, 

46 "mode": mode, 

47 "diff": diff_hash, 

48 "definitions": definitions_hash, 

49 "runner": runner_version, 

50 "skip": sorted(skip), 

51 "forcedModel": forced_model, 

52 "provider": provider, 

53 "fallback": fallback, 

54 "options": options, 

55 } 

56 ) 

57 

58 

59def reviewer_key( 

60 *, 

61 base: str | None, 

62 provider: str, 

63 fallback: str | None, 

64 forced_model: str | None, 

65 reviewer: str, 

66 model: str | None, 

67 slice_hash: str, 

68 prompt_hash: str, 

69 message_hash: str, 

70 definition_hash: str, 

71 runner_version: str, 

72 mcp_hash: str, 

73 options: dict[str, Any], 

74) -> str: 

75 return sha256_json( 

76 { 

77 "kind": "reviewer", 

78 "version": CACHE_VERSION, 

79 "base": base, 

80 "provider": provider, 

81 "fallback": fallback, 

82 "forcedModel": forced_model, 

83 "reviewer": reviewer, 

84 "model": model, 

85 "slice": slice_hash, 

86 "prompt": prompt_hash, 

87 "message": message_hash, 

88 "definition": definition_hash, 

89 "runner": runner_version, 

90 "mcp": mcp_hash, 

91 "options": options, 

92 } 

93 ) 

94 

95 

96class ReviewCache: 

97 def __init__( 

98 self, 

99 directory: Path, 

100 *, 

101 ttl_seconds: int, 

102 max_entries: int, 

103 clock: Callable[[], float] = time.time, 

104 ) -> None: 

105 self.directory = directory 

106 self.ttl_seconds = ttl_seconds 

107 self.max_entries = max_entries 

108 self.clock = clock 

109 

110 def _path(self, key: str) -> Path: 

111 return self.directory / f"{key.split(':', 1)[-1]}.json" 

112 

113 def get(self, key: str) -> dict[str, Any] | None: 

114 path = self._path(key) 

115 try: 

116 entry = json.loads(path.read_text(encoding="utf-8")) 

117 except (OSError, ValueError): 

118 return None 

119 if not isinstance(entry, dict) or entry.get("key") != key: 119 ↛ 120line 119 didn't jump to line 120 because the condition on line 119 was never true

120 return None 

121 stored = entry.get("storedAt") 

122 if not isinstance(stored, int | float) or self.clock() - stored > self.ttl_seconds: 

123 path.unlink(missing_ok=True) 

124 return None 

125 value = entry.get("value") 

126 return value if isinstance(value, dict) else None 

127 

128 def put(self, key: str, value: dict[str, Any]) -> None: 

129 self.directory.mkdir(parents=True, exist_ok=True, mode=0o700) 

130 data = json.dumps( 

131 {"key": key, "storedAt": self.clock(), "value": value}, sort_keys=True 

132 ).encode("utf-8") 

133 descriptor, name = tempfile.mkstemp(prefix=".entry.", dir=self.directory) 

134 try: 

135 with os.fdopen(descriptor, "wb") as handle: 

136 handle.write(data) 

137 os.replace(name, self._path(key)) 

138 except OSError: 

139 Path(name).unlink(missing_ok=True) 

140 return 

141 self.prune() 

142 

143 def prune(self) -> int: 

144 """Remove expired entries and the oldest ones beyond the limit; return how many.""" 

145 if not self.directory.is_dir(): 145 ↛ 146line 145 didn't jump to line 146 because the condition on line 145 was never true

146 return 0 

147 now = self.clock() 

148 entries: list[tuple[float, Path]] = [] 

149 removed = 0 

150 for path in self.directory.glob("*.json"): 

151 try: 

152 stored = json.loads(path.read_text(encoding="utf-8")).get("storedAt") 

153 except (OSError, ValueError, AttributeError): 

154 stored = None 

155 if not isinstance(stored, int | float) or now - stored > self.ttl_seconds: 155 ↛ 156line 155 didn't jump to line 156 because the condition on line 155 was never true

156 path.unlink(missing_ok=True) 

157 removed += 1 

158 continue 

159 entries.append((float(stored), path)) 

160 entries.sort(key=lambda item: (item[0], item[1].name)) 

161 for _stored, path in entries[: max(0, len(entries) - self.max_entries)]: 

162 path.unlink(missing_ok=True) 

163 removed += 1 

164 return removed 

165 

166 

167__all__ = ["CACHE_DIRECTORY", "CACHE_VERSION", "ReviewCache", "global_key", "reviewer_key"]