Debian Codegraph @

misc/diff-cache.py

raw
1 #!/usr/bin/env python3
2 """Produce a diff between mypy caches.
3
4 With some infrastructure, this can allow for distributing small cache diffs to users in
5 many cases instead of full cache artifacts.
6 """
7
8 from __future__ import annotations
9
10 import argparse
11 import os
12 import sys
13 from collections import defaultdict
14 from typing import Any
15
16 sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
17
18 from librt import base64
19 from librt.internal import ReadBuffer, WriteBuffer
20
21 from mypy.cache import CacheMeta, CacheMetaEx
22 from mypy.defaults import SQLITE_NUM_SHARDS
23 from mypy.metastore import FilesystemMetadataStore, MetadataStore, SqliteMetadataStore
24 from mypy.util import json_dumps, json_loads
25
26
27 def make_cache(input_dir: str, sqlite: bool, num_shards: int = SQLITE_NUM_SHARDS) -> MetadataStore:
28 if sqlite:
29 return SqliteMetadataStore(input_dir, num_shards=num_shards)
30 else:
31 return FilesystemMetadataStore(input_dir)
32
33
34 def merge_deps(all: dict[str, set[str]], new: dict[str, set[str]]) -> None:
35 for k, v in new.items():
36 all.setdefault(k, set()).update(v)
37
38
39 def sort_deps(
40 dependencies: list[str], suppressed: list[str], dep_prios: list[int], dep_lines: list[int]
41 ) -> tuple[list[str], list[str], list[int], list[int]]:
42 """Sort dependencies and suppressed independently, keeping prios/lines aligned."""
43 all_deps = list(zip(dependencies + suppressed, dep_prios, dep_lines))
44 num_deps = len(dependencies)
45 sorted_deps = sorted(all_deps[:num_deps])
46 sorted_supp = sorted(all_deps[num_deps:])
47 if sorted_deps:
48 deps_t, prios1_t, lines1_t = zip(*sorted_deps)
49 deps_out = list(deps_t)
50 prios1 = list(prios1_t)
51 lines1 = list(lines1_t)
52 else:
53 deps_out = []
54 prios1 = []
55 lines1 = []
56 if sorted_supp:
57 supp_t, prios2_t, lines2_t = zip(*sorted_supp)
58 supp_out = list(supp_t)
59 prios2 = list(prios2_t)
60 lines2 = list(lines2_t)
61 else:
62 supp_out = []
63 prios2 = []
64 lines2 = []
65 return deps_out, supp_out, prios1 + prios2, lines1 + lines2
66
67
68 def normalize_meta(meta: CacheMeta) -> None:
69 """Normalize a CacheMeta instance to avoid spurious diffs.
70
71 Zero out mtimes and sort dependencies deterministically.
72 """
73 # TODO: handle dep_hashes here and in relevant parts below.
74 meta.mtime = 0
75 meta.data_mtime = 0
76 meta.dependencies, meta.suppressed, meta.dep_prios, meta.dep_lines = sort_deps(
77 meta.dependencies, meta.suppressed, meta.dep_prios, meta.dep_lines
78 )
79
80
81 def serialize_meta_ff(meta: CacheMeta, version_prefix: bytes) -> bytes:
82 """Serialize a CacheMeta instance back to fixed format binary."""
83 buf = WriteBuffer()
84 meta.write(buf)
85 return version_prefix + buf.getvalue()
86
87
88 def normalize_json_meta(obj: dict[str, Any]) -> None:
89 """Normalize a JSON meta dict to avoid spurious diffs.
90
91 Zero out mtimes and sort dependencies deterministically.
92 """
93 obj["mtime"] = 0
94 obj["data_mtime"] = 0
95 if "dependencies" in obj:
96 obj["dependencies"], obj["suppressed"], obj["dep_prios"], obj["dep_lines"] = sort_deps(
97 obj["dependencies"], obj["suppressed"], obj["dep_prios"], obj["dep_lines"]
98 )
99
100
101 def load(cache: MetadataStore, s: str) -> Any:
102 """Load and normalize a cache entry.
103
104 Returns:
105 - For .meta.ff: normalized binary bytes (with version prefix)
106 - For .data.ff: raw binary bytes
107 - For .meta.json/.data.json/.deps.json: parsed and normalized dict/list
108 """
109 data = cache.read(s)
110 if s.endswith(".meta.ff"):
111 version_prefix = data[:2]
112 buf = ReadBuffer(data[2:])
113 meta = CacheMeta.read(buf, data_file="")
114 if meta is None:
115 # Can't deserialize (e.g. different mypy version). Fall back to
116 # raw bytes -- we lose mtime normalization but the diff stays correct.
117 return data
118 normalize_meta(meta)
119 return serialize_meta_ff(meta, version_prefix)
120 if s.endswith(".meta_ex.ff"):
121 buf = ReadBuffer(data)
122 meta = CacheMetaEx.read(buf)
123 if meta is None:
124 # Can't deserialize. Fall back to raw bytes as above
125 return data
126 meta.dependencies.sort()
127 meta.suppressed.sort()
128 outbuf = WriteBuffer()
129 meta.write(outbuf)
130 return outbuf.getvalue()
131 if s.endswith(".data.ff"):
132 return data
133 obj = json_loads(data)
134 if s.endswith(".meta.json"):
135 normalize_json_meta(obj)
136 if s.endswith(".deps.json"):
137 # For deps files, sort the deps to avoid spurious mismatches
138 for v in obj.values():
139 v.sort()
140 return obj
141
142
143 def encode_for_diff(s: str, obj: object) -> str:
144 """Encode a cache entry value for inclusion in the JSON diff.
145
146 Fixed format binary entries are base64-encoded, JSON entries are
147 re-serialized as JSON strings.
148 """
149 if isinstance(obj, bytes):
150 return base64.b64encode(obj).decode()
151 return json_dumps(obj).decode()
152
153
154 def main() -> None:
155 parser = argparse.ArgumentParser()
156 parser.add_argument("--verbose", action="store_true", default=False, help="Increase verbosity")
157 parser.add_argument("--sqlite", action="store_true", default=False, help="Use a sqlite cache")
158 parser.add_argument(
159 "--num-shards", type=int, default=SQLITE_NUM_SHARDS, help=argparse.SUPPRESS
160 )
161 parser.add_argument("input_dir1", help="Input directory for the original cache")
162 parser.add_argument("input_dir2", help="Input directory for the target cache")
163 parser.add_argument("output", help="Output file with the diff from original cache")
164 args = parser.parse_args()
165
166 cache1 = make_cache(args.input_dir1, args.sqlite, num_shards=args.num_shards)
167 cache2 = make_cache(args.input_dir2, args.sqlite, num_shards=args.num_shards)
168
169 type_misses: dict[str, int] = defaultdict(int)
170 type_hits: dict[str, int] = defaultdict(int)
171
172 updates: dict[str, str | None] = {}
173
174 deps1: dict[str, set[str]] = {}
175 deps2: dict[str, set[str]] = {}
176
177 misses = hits = 0
178 cache1_all = list(cache1.list_all())
179 for s in cache1_all:
180 obj1 = load(cache1, s)
181 try:
182 obj2 = load(cache2, s)
183 except FileNotFoundError:
184 obj2 = None
185
186 typ = s.split(".")[-2]
187 if obj1 != obj2:
188 misses += 1
189 type_misses[typ] += 1
190
191 # Collect the dependencies instead of including them directly in the diff
192 # so we can produce a much smaller direct diff of them.
193 if ".deps." not in s:
194 if obj2 is not None:
195 updates[s] = encode_for_diff(s, obj2)
196 else:
197 updates[s] = None
198 elif obj2:
199 # This is a deps file, with json data
200 assert ".deps." in s
201 merge_deps(deps1, obj1)
202 merge_deps(deps2, obj2)
203 else:
204 hits += 1
205 type_hits[typ] += 1
206
207 cache1_all_set = set(cache1_all)
208 for s in cache2.list_all():
209 if s not in cache1_all_set:
210 raw = cache2.read(s)
211 if s.endswith(".ff"):
212 updates[s] = base64.b64encode(raw).decode()
213 else:
214 updates[s] = raw.decode()
215
216 # Compute what deps have been added and merge them all into the
217 # @root deps file.
218 new_deps = {k: deps2.get(k, set()) - deps1.get(k, set()) for k in deps2}
219 new_deps = {k: v for k, v in new_deps.items() if v}
220 try:
221 root_deps = load(cache1, "@root.deps.json")
222 except FileNotFoundError:
223 root_deps = {}
224 merge_deps(new_deps, root_deps)
225
226 new_deps_json = {k: list(v) for k, v in new_deps.items() if v}
227 updates["@root.deps.json"] = json_dumps(new_deps_json).decode()
228
229 # Drop updates to deps.meta.json for size reasons. The diff
230 # applier will manually fix it up.
231 updates.pop("./@deps.meta.json", None)
232 updates.pop("@deps.meta.json", None)
233
234 ###
235
236 print("Generated incremental cache:", hits, "hits,", misses, "misses")
237 if args.verbose:
238 print("hits", type_hits)
239 print("misses", type_misses)
240
241 with open(args.output, "wb") as f:
242 f.write(json_dumps(updates))
243
244
245 if __name__ == "__main__":
246 main()