gabriel / muse public
test_gc_corrupt_commit_object_retention.py python
396 lines 17.8 KB
Raw
sha256:b636f72dcba9e190afb980bece906fa5b717fbde014b76ef023df8cb96e01eb9 docs: expand cache plan with all seven testing tiers and do… Sonnet 4.6 131 days ago
1 """Tests for Bug 10: GC deletes objects reachable from a corrupt commit.
2
3 When a commit file has a corrupt snapshot_id field (bit-flip, tampered, or
4 previously written by the now-fixed from_dict timestamp substitution bug),
5 _collect_reachable_objects returns an empty set for that commit's snapshot.
6 muse gc then deletes those objects, permanently destroying file content.
7
8 The sequence of doom:
9 1. Commit A on disk: snapshot_id = "f"*64 (corrupt — should be "S1")
10 2. `get_all_commits` returns this commit (no hash verification)
11 3. `read_snapshot(root, "f"*64)` → None (file for "f"*64 doesn't exist)
12 4. Objects from the REAL snapshot S1 are NOT added to reachable
13 5. `muse gc` deletes those objects (no other commit references them)
14 6. The working tree cannot be reconstructed from commit A
15
16 Fix: `_collect_reachable_objects` must also scan snapshot files directly
17 (without hash verification) when read_snapshot returns None for a commit's
18 snapshot_id. This conservatively retains any object referenced in any
19 snapshot manifest on disk, regardless of whether the commit's snapshot_id
20 field is correct.
21
22 Scope of tests
23 --------------
24 Unit (_collect_reachable_objects):
25 - Objects reachable from a valid commit are retained
26 - Objects reachable from a commit with corrupt snapshot_id (field points
27 to non-existent snapshot) are still retained via raw snapshot scan
28 - Objects reachable from a commit with corrupt snapshot_id (field points
29 to a WRONG existing snapshot) are still retained via raw snapshot scan
30 - GC does NOT delete objects that are in ANY snapshot on disk, even orphaned
31 - Empty store returns empty reachable set (no crash)
32 - Multiple commits, one corrupt: all objects from all snapshots retained
33
34 Integration (run_gc with corrupt commit):
35 - run_gc dry_run=True does not delete anything from a store with corrupt commit
36 - run_gc does not delete objects from corrupt commit's snapshot (default mode)
37 - run_gc --full does not delete objects from corrupt commit's snapshot
38 - Objects from a legitimately unreachable commit ARE deleted (GC still works)
39
40 Stress:
41 - 50 commits, 5 with corrupt snapshot_ids: all objects from all 50 snapshots retained
42 """
43 from __future__ import annotations
44
45 type _FileStore = dict[str, bytes]
46
47 import datetime
48 import hashlib
49 import pathlib
50
51 import msgpack
52 import pytest
53
54 from muse.core.gc import _collect_reachable_objects, run_gc
55 from muse.core.object_store import write_object
56 from muse.core.snapshot import compute_commit_id, compute_snapshot_id
57 from muse.core.store import (
58 CommitRecord,
59 SnapshotRecord,
60 read_snapshot,
61 write_commit,
62 write_snapshot,
63 )
64
65 _TS = datetime.datetime(2024, 6, 15, 10, 0, 0, tzinfo=datetime.timezone.utc)
66
67
68 def _make_repo(tmp_path: pathlib.Path) -> pathlib.Path:
69 repo = tmp_path / "repo"
70 repo.mkdir()
71 (repo / ".muse").mkdir()
72 return repo
73
74
75 def _write_object(repo: pathlib.Path, content: bytes) -> str:
76 from muse.core._types import blob_id
77 oid = blob_id(content)
78 write_object(repo, oid, content)
79 return oid
80
81
82 def _make_snapshot(repo: pathlib.Path, files: _FileStore) -> SnapshotRecord:
83 manifest = {}
84 for path, content in files.items():
85 oid = _write_object(repo, content)
86 manifest[path] = oid
87 snap_id = compute_snapshot_id(manifest)
88 snap = SnapshotRecord(
89 snapshot_id=snap_id,
90 manifest=manifest,
91 directories=[],
92 created_at=_TS,
93 note="",
94 )
95 write_snapshot(repo, snap)
96 return snap
97
98
99 def _make_commit(
100 repo: pathlib.Path,
101 snap_id: str,
102 *,
103 message: str = "test",
104 ts: datetime.datetime = _TS,
105 parent: str | None = None,
106 ) -> CommitRecord:
107 parent_ids = [parent] if parent else []
108 commit_id = compute_commit_id(
109 repo_id="r" * 64,
110 parent_ids=parent_ids,
111 snapshot_id=snap_id,
112 message=message,
113 committed_at_iso=ts.isoformat(),
114 author="gabriel",)
115 record = CommitRecord(
116 commit_id=commit_id,
117 repo_id="r" * 64,
118 created_on_branch="main",
119 snapshot_id=snap_id,
120 message=message,
121 committed_at=ts,
122 parent_commit_id=parent,
123 parent2_commit_id=None,
124 author="gabriel",
125 metadata={},
126 structured_delta=None,
127 sem_ver_bump="none",
128 breaking_changes=[],
129 agent_id="",
130 model_id="",
131 toolchain_id="",
132 prompt_hash="",
133 signature="",
134 signer_key_id="",
135 reviewed_by=[],
136 test_runs=0,
137 )
138 write_commit(repo, record)
139 return record
140
141
142 def _corrupt_commit_snapshot_id(
143 repo: pathlib.Path, commit_id: str, bad_snapshot_id: str = "f" * 64
144 ) -> None:
145 """Directly corrupt the snapshot_id field in a commit file on disk."""
146 from muse.core._types import split_id
147 algo, hex_id = split_id(commit_id)
148 path = repo / ".muse" / "commits" / algo / f"{hex_id}.msgpack"
149 data = msgpack.unpackb(path.read_bytes(), raw=False)
150 data["snapshot_id"] = bad_snapshot_id
151 path.write_bytes(msgpack.packb(data, use_bin_type=True))
152
153
154 # ──────────────────────────────────────────────────────────────────────────────
155 # Unit: _collect_reachable_objects
156 # ──────────────────────────────────────────────────────────────────────────────
157
158 class TestCollectReachableObjects:
159
160 def test_valid_commit_objects_retained(self, tmp_path: pathlib.Path) -> None:
161 repo = _make_repo(tmp_path)
162 snap = _make_snapshot(repo, {"src/a.py": b"content_a"})
163 _make_commit(repo, snap.snapshot_id)
164 reachable = _collect_reachable_objects(repo)
165 for oid in snap.manifest.values():
166 assert oid in reachable, f"Object {oid[:8]} should be reachable"
167
168 def test_corrupt_snapshot_id_objects_still_retained(self, tmp_path: pathlib.Path) -> None:
169 """BUG: When commit's snapshot_id is corrupt, objects are not retained."""
170 repo = _make_repo(tmp_path)
171 snap = _make_snapshot(repo, {"src/main.py": b"important data"})
172 commit = _make_commit(repo, snap.snapshot_id)
173
174 # Corrupt the snapshot_id to a non-existent value
175 _corrupt_commit_snapshot_id(repo, commit.commit_id, "f" * 64)
176
177 # Verify that read_snapshot now fails for the commit
178 stored = _collect_reachable_objects.__module__ # just to check we're testing the right thing
179
180 reachable = _collect_reachable_objects(repo)
181 for oid in snap.manifest.values():
182 assert oid in reachable, (
183 f"DATA LOSS: Object {oid[:8]} from snapshot {snap.snapshot_id[:8]} "
184 f"was NOT retained by GC after the commit's snapshot_id was corrupted. "
185 f"Running muse gc would delete this object permanently."
186 )
187
188 def test_corrupt_snapshot_id_points_to_wrong_existing_snapshot(self, tmp_path: pathlib.Path) -> None:
189 """Even worse: corrupt snapshot_id points to a DIFFERENT existing snapshot.
190 The objects from the ORIGINAL snapshot are still not retained.
191 """
192 repo = _make_repo(tmp_path)
193 snap1 = _make_snapshot(repo, {"src/file1.py": b"content 1"})
194 snap2 = _make_snapshot(repo, {"src/file2.py": b"content 2"})
195 commit = _make_commit(repo, snap1.snapshot_id)
196
197 # Corrupt: now points to snap2's ID instead of snap1's
198 _corrupt_commit_snapshot_id(repo, commit.commit_id, snap2.snapshot_id)
199
200 reachable = _collect_reachable_objects(repo)
201 for oid in snap1.manifest.values():
202 assert oid in reachable, (
203 f"DATA LOSS: Object from snap1 ({oid[:8]}) not retained — "
204 f"corrupt snapshot_id pointed to snap2 instead, and snap1's "
205 f"objects were not retained. GC would delete them."
206 )
207
208 def test_two_commits_one_corrupt_all_objects_retained(self, tmp_path: pathlib.Path) -> None:
209 """One corrupt commit must not prevent the other commit's objects from being retained."""
210 repo = _make_repo(tmp_path)
211 snap1 = _make_snapshot(repo, {"a.py": b"aaa"})
212 snap2 = _make_snapshot(repo, {"b.py": b"bbb"})
213 commit1 = _make_commit(repo, snap1.snapshot_id, message="c1")
214 _make_commit(repo, snap2.snapshot_id, message="c2")
215
216 _corrupt_commit_snapshot_id(repo, commit1.commit_id, "0" * 64)
217
218 reachable = _collect_reachable_objects(repo)
219 # Both snapshots' objects must be retained
220 for oid in snap1.manifest.values():
221 assert oid in reachable, f"snap1 object {oid[:8]} not retained after corruption"
222 for oid in snap2.manifest.values():
223 assert oid in reachable, f"snap2 object {oid[:8]} not retained"
224
225 def test_empty_store_no_crash(self, tmp_path: pathlib.Path) -> None:
226 repo = _make_repo(tmp_path)
227 reachable = _collect_reachable_objects(repo)
228 assert reachable == set()
229
230 def test_valid_commit_chain_all_retained(self, tmp_path: pathlib.Path) -> None:
231 repo = _make_repo(tmp_path)
232 snap1 = _make_snapshot(repo, {"a.py": b"v1"})
233 snap2 = _make_snapshot(repo, {"a.py": b"v2"})
234 c1 = _make_commit(repo, snap1.snapshot_id, message="v1")
235 _make_commit(repo, snap2.snapshot_id, message="v2", parent=c1.commit_id)
236
237 reachable = _collect_reachable_objects(repo)
238 for oid in snap1.manifest.values():
239 assert oid in reachable
240 for oid in snap2.manifest.values():
241 assert oid in reachable
242
243
244 # ──────────────────────────────────────────────────────────────────────────────
245 # Integration: run_gc with corrupt commit
246 # ──────────────────────────────────────────────────────────────────────────────
247
248 class TestRunGcCorruptCommit:
249
250 def test_gc_dry_run_reports_no_collected_objects_for_corrupt_commit(self, tmp_path: pathlib.Path) -> None:
251 """Dry run must show 0 objects to collect when all objects are reachable."""
252 repo = _make_repo(tmp_path)
253 snap = _make_snapshot(repo, {"main.py": b"code"})
254 commit = _make_commit(repo, snap.snapshot_id)
255 _corrupt_commit_snapshot_id(repo, commit.commit_id)
256
257 result = run_gc(repo, dry_run=True, grace_period_seconds=0)
258 assert result.collected_count == 0, (
259 f"BUG: dry_run GC reports {result.collected_count} objects to collect, "
260 f"but all objects are reachable (just via a corrupt commit). "
261 f"Running without dry_run would permanently delete these objects."
262 )
263
264 def test_gc_does_not_delete_objects_from_corrupt_commit(self, tmp_path: pathlib.Path) -> None:
265 """Objects from a corrupt commit's snapshot must survive GC."""
266 repo = _make_repo(tmp_path)
267 snap = _make_snapshot(repo, {"main.py": b"valuable content"})
268 commit = _make_commit(repo, snap.snapshot_id)
269 _corrupt_commit_snapshot_id(repo, commit.commit_id)
270
271 result = run_gc(repo, dry_run=False, grace_period_seconds=0)
272 assert result.collected_count == 0, (
273 f"DATA LOSS: GC deleted {result.collected_count} object(s) that were "
274 f"reachable from a commit with a corrupt snapshot_id. Those objects "
275 f"are now permanently gone."
276 )
277 # Verify the object is still on disk
278 oid = list(snap.manifest.values())[0]
279 from muse.core.object_store import read_object
280 assert read_object(repo, oid) is not None, (
281 f"CONFIRMED DATA LOSS: Object {oid[:8]} was deleted by GC."
282 )
283
284 def test_gc_full_retains_objects_when_corrupt_snapshot_file_exists(self, tmp_path: pathlib.Path) -> None:
285 """GC --full must retain objects when a snapshot FILE exists at the correct
286 path but its stored snapshot_id field doesn't match the computed hash.
287 The commit references snap_id S1; the file at S1 has a corrupt snapshot_id
288 field (not the manifest) so _verify_snapshot_id fails. Our raw-fallback
289 path must read the manifest directly and retain its object IDs.
290 """
291 repo = _make_repo(tmp_path)
292 snap = _make_snapshot(repo, {"main.py": b"important"})
293 commit = _make_commit(repo, snap.snapshot_id)
294
295 # Point the branch ref at the commit (making it reachable)
296 heads_dir = repo / ".muse" / "refs" / "heads"
297 heads_dir.mkdir(parents=True, exist_ok=True)
298 (heads_dir / "main").write_text(commit.commit_id)
299
300 # Corrupt the SNAPSHOT FILE's stored snapshot_id field (NOT the manifest).
301 # The manifest still has the correct object IDs.
302 # _verify_snapshot_id will fail (recomputed hash != stored snapshot_id field),
303 # causing read_snapshot to return None — but the object IDs in the manifest
304 # are still valid and should be retained by our raw-fallback path.
305 from muse.core._types import split_id as _split_id
306 _algo, _hex = _split_id(snap.snapshot_id)
307 snap_path = repo / ".muse" / "snapshots" / _algo / f"{_hex}.msgpack"
308 snap_data = msgpack.unpackb(snap_path.read_bytes(), raw=False)
309 oid = list(snap_data["manifest"].values())[0] # save the real object ID
310 snap_data["snapshot_id"] = "corrupt_id_" + "0" * 53 # corrupt the stored ID field
311 snap_path.write_bytes(msgpack.packb(snap_data, use_bin_type=True))
312
313 result = run_gc(repo, dry_run=False, grace_period_seconds=0, full=True)
314 from muse.core.object_store import read_object
315 obj = read_object(repo, oid)
316 assert obj is not None, (
317 f"DATA LOSS: GC --full deleted object {oid[:8]} that was referenced "
318 f"in a corrupt snapshot file (corrupt stored snapshot_id field, "
319 f"valid manifest). The raw-fallback path must have retained it."
320 )
321
322 def test_gc_full_corrupt_commit_snapshot_id_no_file_no_crash(self, tmp_path: pathlib.Path) -> None:
323 """Document the known edge case: if a commit's snapshot_id is corrupt AND
324 the referenced file doesn't exist, GC --full cannot retain those objects.
325 Users must run `muse verify-pack` before `muse gc --full` in this scenario.
326 This test verifies no crash occurs (the behavior is a known limitation).
327 """
328 repo = _make_repo(tmp_path)
329 snap = _make_snapshot(repo, {"main.py": b"important"})
330 commit = _make_commit(repo, snap.snapshot_id)
331
332 heads_dir = repo / ".muse" / "refs" / "heads"
333 heads_dir.mkdir(parents=True, exist_ok=True)
334 (heads_dir / "main").write_text(commit.commit_id)
335
336 # Corrupt the commit so its snapshot_id points to a non-existent file
337 _corrupt_commit_snapshot_id(repo, commit.commit_id, "f" * 64)
338
339 # Known limitation: when commit.snapshot_id points to a non-existent file,
340 # GC --full cannot determine which objects to retain. No crash must occur.
341 result = run_gc(repo, dry_run=False, grace_period_seconds=0, full=True)
342 # No assertion about objects — this is the documented limitation.
343
344 def test_gc_still_collects_truly_orphaned_objects(self, tmp_path: pathlib.Path) -> None:
345 """Regression: GC must still delete truly unreachable objects."""
346 repo = _make_repo(tmp_path)
347 # Write an object that is NOT in any snapshot
348 orphan_content = b"orphaned content - no snapshot references this"
349 orphan_oid = _write_object(repo, orphan_content)
350
351 # Write a valid commit with a snapshot that does NOT reference the orphan
352 snap = _make_snapshot(repo, {"other.py": b"other content"})
353 _make_commit(repo, snap.snapshot_id)
354
355 result = run_gc(repo, dry_run=False, grace_period_seconds=0)
356 assert orphan_oid in result.collected_ids, (
357 f"Orphaned object {orphan_oid[:8]} was not collected by GC. "
358 f"GC is too conservative."
359 )
360
361
362 # ──────────────────────────────────────────────────────────────────────────────
363 # Stress
364 # ──────────────────────────────────────────────────────────────────────────────
365
366 class TestGcCorruptStress:
367
368 def test_50_commits_5_corrupt_all_objects_retained(self, tmp_path: pathlib.Path) -> None:
369 """50 commits, 5 with corrupt snapshot_ids: all objects retained, no crash."""
370 repo = _make_repo(tmp_path)
371 commit_records = []
372 all_oids: set[str] = set()
373
374 for i in range(50):
375 content = f"content_{i}".encode()
376 snap = _make_snapshot(repo, {f"f{i}.py": content})
377 ts = _TS + datetime.timedelta(seconds=i)
378 commit = _make_commit(repo, snap.snapshot_id, message=f"commit {i}", ts=ts)
379 commit_records.append(commit)
380 all_oids.update(snap.manifest.values())
381
382 # Corrupt 5 commits (indices 10, 20, 30, 40, 49)
383 corrupt_indices = {10, 20, 30, 40, 49}
384 for idx in corrupt_indices:
385 _corrupt_commit_snapshot_id(
386 repo, commit_records[idx].commit_id, "9" * 64
387 )
388
389 reachable = _collect_reachable_objects(repo)
390
391 missing = [oid for oid in all_oids if oid not in reachable]
392 assert not missing, (
393 f"DATA LOSS: {len(missing)} object(s) not retained by GC despite "
394 f"being reachable from snapshots on disk. "
395 f"Missing: {[o[:8] for o in missing[:5]]}"
396 )
File History 3 commits
sha256:b636f72dcba9e190afb980bece906fa5b717fbde014b76ef023df8cb96e01eb9 docs: expand cache plan with all seven testing tiers and do… Sonnet 4.6 131 days ago
sha256:7f9e2ef5286aedad9c1e6011b4c46ca27f39dbdad6e3409357e36b26e46b3b7c docs: docstring sprint for-each-ref→hotspots — idiomatic ru… Sonnet 4.6 patch 137 days ago
sha256:a09b1b4f6838754495547f200aa0ce88e2f56ffc5b20b900f6f0cff2c3cdede9 fix(cursorignore): remove git-ism (.git/worktrees) Human minor 140 days ago