diff --git a/docs/packfiles.md b/docs/packfiles.md index 09e6554..878e43f 100644 --- a/docs/packfiles.md +++ b/docs/packfiles.md @@ -45,6 +45,21 @@ its type, zlib end-of-stream, uncompressed length, and hash. Duplicate writes an `has_object` use the same validation and work for packed-only objects. An invalid published index raises `ObjectCorruptError`; it is not silently ignored. +Published index metadata is cached per `ObjectStore` instance after the complete +index and pack pass validation. The cache retains at most 64 parsed indexes and +evicts the least recently used entry; memory per entry still depends on the +number of objects in that pack. Each lookup enumerates published indexes and +checks each index and pack's nanosecond modification time, size, and inode. +New packs are discovered, and a change to any of those metadata fields forces +full validation again. Selected records are decoded and hash-checked on every +read, even on a cache hit. + +Published pairs are immutable. The metadata cache is not a filesystem integrity +monitor: external in-place edits that preserve all signature fields can leave +cached index metadata stale. Use a fresh `ObjectStore` to revalidate the complete +pack after external changes. Selected-record byte and hash validation still +applies to every read. + ## Publication and compatibility Both temporary files are closed and validated before publication. The pack is diff --git a/docs/performance.md b/docs/performance.md index 0fe1c11..11f960a 100644 --- a/docs/performance.md +++ b/docs/performance.md @@ -69,3 +69,91 @@ most of its time is the Myers diff, which was not changed. ## Re-run Run these numbers again with the shared benchmark (#47) once it is merged. + +# Object-storage performance + +## How it was measured + +The shared packfile fixture is generated by +[`scripts/benchmark_packfiles.py`](../scripts/benchmark_packfiles.py). Each run +uses a fresh temporary repository with 512 deterministic blob objects. Each +blob contains a unique 22-byte prefix followed by 2,048 generated bytes +(`--payload-size 2048`), for 2,070 bytes total. This is an M1 storage fixture, +not the approximately 1,000-file / 100-commit end-to-end fixture still tracked +in #47 and #58. It does not measure networking or history traversal. + +On Windows from the repository root: + +```powershell +.\.venv\Scripts\python.exe scripts\benchmark_packfiles.py --profile +.\.venv\Scripts\python.exe scripts\benchmark_packfiles.py --no-cache --profile +``` + +## Earlier reported results + +Recorded on Python 3.11.9, Windows 10 build 26200, at `bc3ed1e`. This revision +predates the 64-entry cache bound and inode checks in #71; these measurements +compare metadata caching with `--no-cache`, not those later additions: + +| Measurement | Cached (`bc3ed1e`) | Uncached comparison | +| --- | ---: | ---: | +| Loose object write time | 583.413 ms | 591.064 ms | +| Loose stored bytes | 27,534 | 27,534 | +| Loose fresh-store read time | 9,084.883 ms | 1,772.944 ms | +| Pack time | 145.947 ms | 136.304 ms | +| Retained loose bytes after packing | 27,534 | 27,534 | +| Pack bytes | 33,179 | 33,179 | +| Index bytes | 18,444 | 18,444 | +| Packed-only fresh-store read time | 204.085 ms | 4,440.836 ms | +| Three repeated packed reads | 0.725 s profiled | 20.570 s profiled | + +The uncached comparison disables only the per-store index metadata cache; it +retains the same object and pack validation. The packed-only repeated-read +comparison is the bounded optimization target: cached metadata avoids repeated +full-pack parsing and decompression while selected records remain validated on +each read. Loose reads and storage sizes are otherwise unchanged. The cache is +bounded and does not cache object bytes, so filesystem discovery and loose-file +latency remain limitations. + + +## Reproduction of #71 + +Run on 2026-11-18 with production code and benchmark script at +`d00685dc1d853c22eb3bb744db23929b3d6fcecf`, Python 3.13.5, +macOS 26.6.2 on arm64. Only documentation and regression tests differed from +that revision. The following commands ran sequentially with no test suite +running concurrently: + +```bash +.venv/bin/python scripts/benchmark_packfiles.py --profile +.venv/bin/python scripts/benchmark_packfiles.py --no-cache --profile +``` + +Both runs use the default 512-object / 2,048-byte payload parameter. A fresh +store means a new `ObjectStore` instance, not a cold filesystem cache. Each +command creates its own temporary repository. The fresh read traverses all +objects once; the profiled repeated read uses another new store for three +passes. Timings below are one observational run per configuration, not a +statistical claim or a CI threshold. + +| Measurement | Cached | `--no-cache` | +| --- | ---: | ---: | +| Loose object write time | 83.924 ms | 82.399 ms | +| Loose stored bytes | 27,534 | 27,534 | +| Loose fresh-store read time | 13.691 ms | 13.947 ms | +| Pack time | 23.250 ms | 23.273 ms | +| Retained loose bytes after packing | 27,534 | 27,534 | +| Pack bytes | 33,179 | 33,179 | +| Index bytes | 18,444 | 18,444 | +| Packed-only fresh-store read time | 32.947 ms | 2,151.480 ms | +| Three repeated packed reads, profiled | 0.146 s | 8.975 s | + +`--no-cache` bypasses metadata reuse on the same code and retains complete +pack/index validation. It is a controlled comparison, not an exact checkout +of an earlier implementation. The cache bound and inode checks protect +resource use and replacement detection; this one-pack fixture does not +isolate their performance effect. Packed-only storage is 51,623 bytes here, +larger than the 27,534-byte loose-only representation. Packing retains loose +originals until the benchmark deliberately removes them in its disposable +fixture. Neither these measurements nor the older Windows runs complete the +shared project benchmark in #47/#58. diff --git a/docs/week8-performance.md b/docs/week8-performance.md index 6fdc485..b787dd8 100644 --- a/docs/week8-performance.md +++ b/docs/week8-performance.md @@ -2,11 +2,11 @@ ## Reproduction -The shared moderately large fixture is generated by +The M1 storage fixture, separate from the shared project benchmark in #47, uses [`scripts/benchmark_packfiles.py`](../scripts/benchmark_packfiles.py): 512 -deterministic blob objects, each with a 2,048-byte repeated payload and a -unique prefix. The benchmark uses a fresh temporary repository, reads through -a newly constructed `ObjectStore`, and removes loose objects before the +deterministic blob objects, each with a 2,048-byte repeated payload plus a +unique 22-byte prefix (2,070 bytes total). The benchmark uses a fresh temporary +repository, reads through a newly constructed `ObjectStore`, and removes loose objects before the packed-only read. It reports retained loose bytes separately from pack and index bytes. @@ -17,11 +17,17 @@ On Windows from the repository root: .\.venv\Scripts\python.exe scripts\benchmark_packfiles.py --no-cache --profile ``` -`--no-cache` is the pre-Week-8 comparison: it reparses and validates the -published index and complete pack for every lookup. The benchmark does not +`--no-cache` is a controlled comparison on the current code: it reparses and +validates the published index and complete pack for every lookup. It is not +an exact historical revision. The benchmark does not change the object format, enable pruning, or use delta compression. -## M4 measurement +## Earlier reported storage measurements + +These Windows measurements were reported with #65. The exact measured source +revision was not recorded, so they are historical observations rather than a +reproducible revision-to-revision baseline. Current revision-pinned measurements +and commands are in [the shared performance report](performance.md#reproduction-of-71). Environment for the recorded run: @@ -52,16 +58,19 @@ compression. The packed-only footprint in this run is 51,623 bytes ## Measured fix and profile -The pre-fix comparison (`--no-cache`) reported 5,017.308 ms for the +The controlled comparison (`--no-cache`) reported 5,017.308 ms for the packed-only fresh-store read. Its repeated-read profile (three passes) spent 28.802 seconds total, including 25.959 seconds in complete pack validation and 21.207 seconds in repeated record decoding. The fix caches metadata only after a published index and its matching pack have passed the existing validation. Each lookup still discovers the current -`pack-*.idx` directory entries, and the cache signature includes index and -pack size plus modification time. A newly published pack is therefore found, -and a changed published file invalidates its cached validation. Selected +`pack-*.idx` directory entries, and the current cache signature includes index and +pack size, nanosecond modification time, and inode. The cache retains at most +64 parsed indexes and evicts the least recently used entry. These bounds and +inode checks were added in #71, after the original caching implementation. +A newly published pack is therefore found, and changed signature fields +invalidate cached validation. Selected records continue to be decoded and hash-checked on every read. The cached repeated-read profile took 0.688 seconds for the same three passes. @@ -83,5 +92,7 @@ not wall-clock thresholds. - Packed storage is larger when loose originals are retained. Pruning and delta compression remain outside this issue. - Pack/index format redesign remains outside this issue. -- Run `scripts/quality-check.sh` before linking the PR and requesting teammate - review. This worktree intentionally has no commit, push, or pull. +- Full-project/network measurements remain tracked in #47 and #58; this + blob-only fixture does not complete those checkpoints. +- See [packfile validation](packfiles.md#lookup-and-validation) for the metadata + cache assumptions and selected-record integrity checks. diff --git a/minigit/objects.py b/minigit/objects.py index 57de788..5c78b15 100644 --- a/minigit/objects.py +++ b/minigit/objects.py @@ -15,6 +15,7 @@ import tempfile import uuid import zlib +from collections import OrderedDict from collections.abc import Iterable from pathlib import Path from typing import NamedTuple @@ -30,6 +31,7 @@ class TreeEntry(NamedTuple): class ObjectStore: + _MAX_INDEX_CACHE_ENTRIES = 64 _OBJECT_TYPES = {"blob", "tree", "commit"} _PACK_MAGIC = b"MGPK" _INDEX_MAGIC = b"MGIX" @@ -49,14 +51,14 @@ def __init__(self, repo_path=".") -> None: self.root = Path(repo_path) self.objects_dir = self.root / ".minigit" / "objects" self.pack_dir = self.objects_dir / "pack" - self._index_cache: dict[ + self._index_cache: OrderedDict[ Path, tuple[ - tuple[int, int, int, int], + tuple[int, int, int, int, int, int], dict[str, tuple[int, int]], Path, ], - ] = {} + ] = OrderedDict() def hash_object(self, data: bytes, obj_type: str) -> str: """ @@ -243,6 +245,9 @@ def _read_packed_object(self, obj_hash: str) -> tuple[str, bytes] | None: def _read_cached_index(self, index_path: Path) -> tuple[dict[str, tuple[int, int]], Path]: """ Reads a cached index from the file system. + If the index is already cached and has not changed, + return the cached entries and pack path. + Otherwise, read the index from disk, validate it, and cache it for future use. """ pack_path = index_path.with_suffix(".pack") try: @@ -254,15 +259,21 @@ def _read_cached_index(self, index_path: Path) -> tuple[dict[str, tuple[int, int signature = ( index_stat.st_mtime_ns, index_stat.st_size, + index_stat.st_ino, pack_stat.st_mtime_ns, pack_stat.st_size, + pack_stat.st_ino, ) cached = self._index_cache.get(index_path) if cached is not None and cached[0] == signature: + self._index_cache.move_to_end(index_path) return cached[1], cached[2] entries, pack_path = self._read_index(index_path, pack_path) self._index_cache[index_path] = (signature, entries, pack_path) + self._index_cache.move_to_end(index_path) + while len(self._index_cache) > self._MAX_INDEX_CACHE_ENTRIES: + self._index_cache.popitem(last=False) return entries, pack_path def _read_index( diff --git a/tests/test_cli.py b/tests/test_cli.py index c9bbf36..cd6f49f 100644 --- a/tests/test_cli.py +++ b/tests/test_cli.py @@ -1,16 +1,24 @@ +import os import subprocess import sys +from pathlib import Path from minigit.commits import CommitManager def run_cli(repo, *args): + environment = os.environ.copy() + repository_root = str(Path(__file__).resolve().parents[1]) + environment["PYTHONPATH"] = os.pathsep.join( + path for path in (repository_root, environment.get("PYTHONPATH", "")) if path + ) return subprocess.run( [sys.executable, "-m", "minigit.cli", *args], cwd=repo, text=True, capture_output=True, check=False, + env=environment, ) diff --git a/tests/test_commits.py b/tests/test_commits.py index e758db3..42a753b 100644 --- a/tests/test_commits.py +++ b/tests/test_commits.py @@ -1368,7 +1368,12 @@ def test_ref_paths_reject_symlinks_and_file_directory_collisions(tmp_path): outside = tmp_path / "outside" outside.mkdir() (outside / "topic").write_text("untouched") - (tmp_path / ".minigit/refs/heads/escape").symlink_to(outside, target_is_directory=True) + try: + (tmp_path / ".minigit/refs/heads/escape").symlink_to(outside, target_is_directory=True) + except OSError as error: + if getattr(error, "winerror", None) == 1314: + pytest.skip("directory symlinks require Windows developer mode or privilege") + raise for name in ["escape/topic", "main/topic"]: with pytest.raises(MiniGitError): manager.write_ref(name, tip) diff --git a/tests/test_index.py b/tests/test_index.py index 446391c..f6fff87 100644 --- a/tests/test_index.py +++ b/tests/test_index.py @@ -636,6 +636,9 @@ def test_unicode_text_is_diffed_as_text(repo): assert result.line_diffs["u.txt"] == [LineEdit(1, 1, ["naïve!\n"])] +@pytest.mark.skipif( + sys.platform == "win32", reason="Windows does not preserve POSIX executable bits" +) def test_mode_only_change_is_modified_with_no_line_edits(repo): write(repo, "run.sh", "echo hi\n", mode=0o644) tree = snapshot_tree(repo, ["run.sh"]) @@ -807,6 +810,9 @@ def test_cli_binary_file_reports_binary_changed(cli_repo, capsys): assert "@@" not in out +@pytest.mark.skipif( + sys.platform == "win32", reason="Windows does not preserve POSIX executable bits" +) def test_cli_mode_only_change(cli_repo, capsys): repo, commit = cli_repo write(repo, "run.sh", "echo hi\n", mode=0o644) @@ -1035,6 +1041,9 @@ def local(tmp_path): # --------------------------------------------------------------------------- +@pytest.mark.skipif( + sys.platform == "win32", reason="Windows does not preserve POSIX executable bits" +) def test_fast_forward_into_fresh_repo_restores_everything(source, local, monkeypatch, capsys): download(source, local) @@ -1054,6 +1063,9 @@ def test_fast_forward_into_fresh_repo_restores_everything(source, local, monkeyp assert diff_text(local, monkeypatch, capsys) == "" +@pytest.mark.skipif( + sys.platform == "win32", reason="Windows does not preserve POSIX executable bits" +) def test_second_fast_forward_applies_edit_delete_new_dir_and_mode( source, local, monkeypatch, capsys ): @@ -1433,6 +1445,9 @@ def test_cli_binary_files_added_and_deleted_get_a_summary(cli_repo, capsys): assert not any(line.startswith("@@") for line in out) +@pytest.mark.skipif( + sys.platform == "win32", reason="Windows rejects newline characters in filenames" +) def test_cli_diff_shows_space_unicode_and_odd_paths_clearly(cli_repo, capsys): repo, commit = cli_repo write(repo, "my dir/café notes.txt", "one\n") @@ -1496,6 +1511,9 @@ def test_status_and_diff_leave_a_conflicted_repo_unchanged(merging, monkeypatch, assert local.object_files() == objects +@pytest.mark.skipif( + sys.platform == "win32", reason="Windows rejects newline characters in filenames" +) def test_expected_failures_name_the_path_and_the_next_step(repo): with pytest.raises(MiniGitError, match=r"No such file: nope\.txt; check the path"): repo.stage_file("nope.txt") diff --git a/tests/test_objects.py b/tests/test_objects.py index 80da98a..417733d 100644 --- a/tests/test_objects.py +++ b/tests/test_objects.py @@ -560,6 +560,47 @@ def test_packed_index_cache_rechecks_changed_pack(tmp_path: Path) -> None: store.read_object(obj_hash) +@pytest.mark.parametrize("suffix", [".pack", ".idx"]) +def test_packed_index_cache_rechecks_replaced_file_with_preserved_metadata( + tmp_path: Path, suffix: str +) -> None: + """Atomic replacement must invalidate cached validation even with old size/mtime.""" + store = ObjectStore(tmp_path) + obj_hash = store.write_object(b"content", "blob") + pack_path, index_path = store.pack_objects([obj_hash]) + store._object_path(obj_hash).unlink() + assert store.read_object(obj_hash) == ("blob", b"content") + + target = pack_path if suffix == ".pack" else index_path + original_stat = target.stat() + corrupted = bytearray(target.read_bytes()) + corrupted[0] ^= 0xFF # Header corruption leaves the selected record intact. + replacement = tmp_path / "replacement" + replacement.write_bytes(corrupted) + os.utime(replacement, ns=(original_stat.st_atime_ns, original_stat.st_mtime_ns)) + os.replace(replacement, target) + assert target.stat().st_size == original_stat.st_size + assert target.stat().st_mtime_ns == original_stat.st_mtime_ns + + with pytest.raises(ObjectCorruptError): + store.read_object(obj_hash) + + +def test_packed_index_cache_is_bounded(tmp_path: Path) -> None: + """Evict old pack metadata while keeping every published pack readable.""" + store = ObjectStore(tmp_path) + hashes = [] + for index in range(store._MAX_INDEX_CACHE_ENTRIES + 1): + obj_hash = store.write_object(f"object-{index}".encode(), "blob") + store.pack_objects([obj_hash]) + store._object_path(obj_hash).unlink() + hashes.append(obj_hash) + assert store.read_object(obj_hash) == ("blob", f"object-{index}".encode()) + + assert len(store._index_cache) == store._MAX_INDEX_CACHE_ENTRIES + assert store.read_object(hashes[0]) == ("blob", b"object-0") + + def test_duplicate_write_validates_packed_only_object(tmp_path: Path) -> None: store = ObjectStore(tmp_path) obj_hash = store.write_object(b"packed", "blob") diff --git a/tests/test_remote.py b/tests/test_remote.py index 8eb0265..925fdaa 100644 --- a/tests/test_remote.py +++ b/tests/test_remote.py @@ -1576,7 +1576,12 @@ def test_bad_ref_session_does_not_stop_server(push_pair, ref_request): tip = _commit(pair.remote_store, pair.remote_commits, {}, []) pair.remote_commits.create_branch("feature/topic", tip) refs = Path(pair.server.repo_path) / ".minigit/refs/heads" - (refs / "escape").symlink_to(refs / "feature", target_is_directory=True) + try: + (refs / "escape").symlink_to(refs / "feature", target_is_directory=True) + except OSError as error: + if getattr(error, "winerror", None) == 1314: + pytest.skip("directory symlinks require Windows developer mode or privilege") + raise with socket.create_connection(("127.0.0.1", pair.server.port), timeout=2) as sock: buf = bytearray() send_line(sock, "AUTH tok")