diff --git a/README.md b/README.md index a664959..654cf3e 100644 --- a/README.md +++ b/README.md @@ -185,6 +185,10 @@ minigit pull 127.0.0.1:9418 main --token demo-token # fetch, then integra ## Docs +- [Storage demo](docs/demo.md) - a runnable loose, mixed, and packed snapshot + rehearsal; the full project demo remains in progress. +- [Module 1 writeup](docs/writeups/module-1.md) - object formats, validation, + packfiles, measured tradeoffs, and remaining limitations. - [Onboarding guide](https://docs.google.com/document/d/1D77Ncmtunxj7GVADytHo1An6BKzaV-Ep7AxAYfL405k/edit?tab=t.0) - start here if you are new: setup, branching, workflow, pull requests, code review, and coding standards. diff --git a/docs/demo.md b/docs/demo.md new file mode 100644 index 0000000..7fb1283 --- /dev/null +++ b/docs/demo.md @@ -0,0 +1,93 @@ +# Storage demo + +This is the Module 1 segment for the shared demo. The complete local/network +runbook and teammate rehearsal remain tracked in #63/#70; the project-source +trial is #73. This segment uses a disposable repository and the existing Python +object API. There is no `pack` CLI command. + +## Run the storage segment + +From the repository root after installing the project environment: + +```bash +.venv/bin/python scripts/demo_storage.py +``` + +On Windows, use `.\.venv\Scripts\python.exe scripts\demo_storage.py`. + +Expected output: + +```text +identical bytes -> same object ID: true +changed bytes -> different object ID: true +nested tree -> links to subtree and blob: true +merge commit -> preserves both parents: true +loose snapshot -> all seven objects verified: true +mixed snapshot -> all seven objects verified: true +packed-only snapshot -> all seven objects verified: true +temporary repository cleaned up: true +``` + +[`scripts/demo_storage.py`](../scripts/demo_storage.py) creates a blob, two +linked trees, a root commit, two children of that root, and a two-parent commit. +It verifies exact object types/bytes, nested tree links, and parent order using +a fresh store in each storage state. This illustrates storage and graph links; +the interactive merge/conflict workflow belongs in M3's shared demo segment. + +| State | Fixture action | Check | +| --- | --- | --- | +| Loose | Keep all seven loose objects | Fresh store verifies every object | +| Mixed | Pack three objects and remove their loose fixture copies | Fresh store verifies all seven through loose and packed reads | +| Packed-only | Pack all seven and remove remaining loose fixture copies | Fresh store verifies every object and both parent links | + +Loose-file removal happens only inside `TemporaryDirectory`; cleanup also runs +if an assertion fails. Do not remove loose objects from a working repository +to rehearse this demo. Rerunning the script creates a new isolated fixture. + +## Performance segment + +The separate storage benchmark is reproducible with: + +```bash +.venv/bin/python scripts/benchmark_packfiles.py --profile +.venv/bin/python scripts/benchmark_packfiles.py --no-cache --profile +``` + +Use the same Windows interpreter substitution as above. Commands, exact +production revision, environment, byte totals, and fresh/repeated-run +definitions are in [the performance report](performance.md#reproduction-of-71). +The default fixture contains 512 blobs, each with a 22-byte prefix plus 2,048 +generated bytes. It does not replace #47/#58's shared project/network benchmark. + +`--no-cache` is a controlled comparison on the current code. It preserves full +pack/index validation and disables metadata reuse; it is not an exact checkout +of an older implementation. The output reports retained loose bytes separately +from pack and index bytes. + +## Failure guarantees to explain + +- Missing hashes raise `ObjectNotFoundError`; malformed stored objects raise + `ObjectCorruptError`. +- A corrupt loose copy is never hidden by fallback to a valid packed copy. +- Duplicate writes validate the existing object before returning its hash. +- Pack publication validates both temporary files, renames the pack first, and + publishes the index last. Earlier objects remain readable after a failed + publication; readers ignore an orphan pack without a published index. +- The 64-entry metadata cache assumes immutable published files and invalidates + on size, nanosecond modification-time, or inode changes. Selected records are + decoded and hash-checked on every read. See [cache assumptions](packfiles.md#lookup-and-validation). + +## Validation record and remaining rehearsal + +The original storage flow was reported as rehearsed on `006740a` with Python +3.11.9/Windows and 79 object tests. The executable flow above was validated on +2026-11-18 with the #72 integration changes based on `edee155`, Python +3.13.5/macOS 26.6.2. Its exact stdout matches the block above, and the combined +quality check passes all 445 tests, including 82 object tests. The final #72 +commit identifies the complete script and documentation revision. + +Another teammate must still follow this segment at the final shared-checkpoint +revision and record their name, revision, environment, and any blockers in +#60/#67. This local validation does not claim that teammate rehearsal or the +full project demo is complete. Pruning, garbage collection, delta compression, +and a pack CLI remain outside this segment. diff --git a/docs/packfiles.md b/docs/packfiles.md index 878e43f..2b6c528 100644 --- a/docs/packfiles.md +++ b/docs/packfiles.md @@ -5,6 +5,10 @@ through `read_object`, and returns `(pack_path, index_path)`. Loose originals remain in place; new objects are written loose. Pruning and delta compression are not implemented. +Packfiles are currently a Python API, not a CLI command. The supported entry +point is `ObjectStore.pack_objects`; `hash-object` and `cat-file` continue to +operate on individual objects. + ```python from minigit.objects import ObjectStore @@ -71,3 +75,10 @@ an orphaned pack without an index is ignored. Loose originals remain readable. History, checkout, diff, merge, and networking use the same object API for loose, packed, and mixed storage. Packfiles are a local storage format: push continues to transfer validated individual objects through the existing protocol. + +## Readiness limitations + +The current format retains loose originals after packing, has no pruning or +garbage collection, and does not use delta compression. The index and pack +formats remain version 1. The [storage demo](demo.md) uses a disposable +repository to demonstrate loose, mixed, and packed-only snapshots. diff --git a/docs/writeups/module-1.md b/docs/writeups/module-1.md new file mode 100644 index 0000000..b371849 --- /dev/null +++ b/docs/writeups/module-1.md @@ -0,0 +1,124 @@ +# Module 1: object storage + +## What was built + +Module 1 owns every read and write under `.minigit/objects/`. `ObjectStore` +provides the stable boundary used by trees, commits, the working tree, and +networking: + +- `hash_object(data, type)` computes an object ID without writing. +- `write_object(data, type)` validates duplicate objects and atomically writes + compressed loose storage. +- `read_object(hash)` returns `(type, bytes)` with loose-first lookup. +- `write_tree` and `read_tree` serialize and validate nested tree entries. +- `pack_objects(hashes)` creates and publishes a local pack/index pair. + +The public object API and SHA-1 IDs are unchanged by the packfile work. + +## Object framing and hashing + +An object ID is the SHA-1 digest of: + +```text + \0 +``` + +The length is measured in bytes, not characters, so binary and UTF-8 payloads +are addressed consistently. A loose object stores the same header and payload +inside one zlib stream at: + +```text +.minigit/objects// +``` + +Writes use a temporary file in the destination directory, flush the compressed +bytes, and publish with `os.replace`. A failed write removes its temporary +file. Rewriting an existing object is not accepted blindly: duplicate writes +read and validate the existing object first. + +## Trees and commits + +Trees are object payloads containing one newline-terminated entry per line: + +```text + \t\n +``` + +Entries are sorted by name and validated for supported modes, object types, +lowercase SHA-1 hashes, unique names, and safe filenames. A nested tree points +to another tree object, while a blob entry points to file bytes. + +A commit stores the root tree hash, zero or more parent hashes, author +metadata, and the message. Consequently, a commit points to the root tree, +the root tree points through subtrees to blobs, and the complete snapshot is +reachable through object IDs. Two-parent commits preserve both parent links. + +## Pack layout and lookup + +`pack_objects` reads selected objects through `read_object`, deduplicates the +requested hashes, and writes version-1 `.pack` and `.idx` files under +`.minigit/objects/pack/`. Each pack record preserves the object type and exact +uncompressed bytes, while zlib compresses the payload. The index maps each raw +20-byte SHA-1 to a record offset and length. + +Publication is deliberately ordered: the temporary pack and index are flushed, +fsynced, and validated; the pack is renamed first; the index is renamed last. +Readers discover only published indexes. An interrupted publication can leave +an orphan pack, but cannot make an unpublished index visible. Loose originals +remain readable and are not pruned. + +Reads check loose storage first. If no loose file exists, each published index +is validated before a matching packed record is decoded. The per-store index +metadata cache avoids repeating complete pack validation after the first +validated read. Current pack/index metadata is still discovered on every lookup, +and a change to size, nanosecond modification time, or inode invalidates the +cache. It retains at most 64 parsed indexes with least-recently-used eviction; +memory per index depends on the pack size. The cache assumes published pairs +are immutable; external edits preserving all signature fields require a fresh +store for complete validation. Selected records remain decompressed, +length-checked, and hash-checked on every read. + +## Error behavior and tradeoffs + +- An invalid hash or missing object raises `ObjectNotFoundError`. +- Malformed compressed bytes, headers, lengths, types, hashes, indexes, or packs + raise `ObjectCorruptError`. +- A corrupt loose object never falls back to a valid packed copy. +- A corrupt published index or pack is not silently skipped. + +The design favors correctness and simple recovery over aggressive storage +reclamation. It keeps loose originals, has no pruning or garbage collection, +does not use delta compression, and retains a simple version-1 format. The +metadata cache reduces repeated parsing and decompression work but does not +cache object payloads, so loose-file latency and filesystem discovery remain +costs. + +## Measured results + +Use the [canonical storage measurements](../performance.md#reproduction-of-71) +for exact commands, production revision, environment, and fresh/repeated-run +definitions. The reproduced #71 fixture contains 512 blobs, each with a +22-byte unique prefix plus 2,048 generated bytes. On Python 3.13.5/macOS +26.6.2, one sequential cached/uncached comparison measured 32.947 ms versus +2,151.480 ms for a fresh-store packed read, and 0.146 s versus 8.975 s for +three profiled passes. These are fixture-specific observations, not guarantees. + +Both runs stored 27,534 loose bytes and a 33,179-byte pack plus 18,444-byte +index. Packed-only storage is larger for this highly compressible fixture; +packing also retains the loose originals unless the disposable benchmark +removes them. `--no-cache` disables reuse on the same code, not an exact +historical checkout. Earlier Windows measurements remain separately labeled +in the performance documents. + +This storage-only fixture does not complete the shared project/network +benchmark in #47/#58. The one-pack measurement also does not isolate the +effect of the 64-entry bound or inode checks added in #71. + +## What I would change next + +First, measure cache memory, hit rates, and lookup behavior with more than +64 published packs before changing the current bound or eviction policy. Next, +add explicit lifecycle tooling for pruning loose originals and obsolete packs +only after reachability and crash-recovery rules are specified. Delta compression +and a format redesign +would be separate compatibility decisions, not incremental demo work. diff --git a/scripts/demo_storage.py b/scripts/demo_storage.py new file mode 100644 index 0000000..123344f --- /dev/null +++ b/scripts/demo_storage.py @@ -0,0 +1,72 @@ +"""Rehearse storage invariants in a disposable repository.""" + +import sys +from pathlib import Path +from tempfile import TemporaryDirectory + +sys.path.insert(0, str(Path(__file__).resolve().parents[1])) + +from minigit.commits import CommitManager +from minigit.objects import ObjectStore, TreeEntry + + +def verify_snapshot(root, expected, root_tree, nested_tree, blob, merge, parents): + """Use a fresh store to check every object plus the tree and parent links.""" + reader = ObjectStore(root) + for object_id, value in expected.items(): + assert reader.read_object(object_id) == value + assert reader.read_tree(root_tree) == [TreeEntry("40000", "tree", nested_tree, "nested")] + assert reader.read_tree(nested_tree) == [TreeEntry("100644", "blob", blob, "hello.txt")] + assert CommitManager(root, store=reader).read_commit(merge).parents == parents + + +def main() -> int: + with TemporaryDirectory(prefix="minigit-storage-demo-") as directory: + root = Path(directory) + store = ObjectStore(root) + commits = CommitManager(root, store=store) + original = b"hello\n" + original_id = store.hash_object(original, "blob") + assert original_id == store.hash_object(original, "blob") + assert original_id != store.hash_object(b"hello, storage\n", "blob") + print("identical bytes -> same object ID: true") + print("changed bytes -> different object ID: true") + + blob = store.write_object(original, "blob") + nested_tree = store.write_tree([TreeEntry("100644", "blob", blob, "hello.txt")]) + root_tree = store.write_tree([TreeEntry("40000", "tree", nested_tree, "nested")]) + author = "demo " + base = commits.create_commit(root_tree, [], author, "base") + left = commits.create_commit(root_tree, [base], author, "left") + right = commits.create_commit(root_tree, [base], author, "right") + parents = [left, right] + merge = commits.create_commit(root_tree, parents, author, "merge") + objects = [blob, nested_tree, root_tree, base, left, right, merge] + expected = {object_id: store.read_object(object_id) for object_id in objects} + assert expected[blob] == ("blob", original) + + verify_snapshot(root, expected, root_tree, nested_tree, blob, merge, parents) + print("nested tree -> links to subtree and blob: true") + print("merge commit -> preserves both parents: true") + print("loose snapshot -> all seven objects verified: true") + + # All loose-file removal stays inside this TemporaryDirectory fixture. + mixed_objects = [blob, nested_tree, base] + store.pack_objects(mixed_objects) + for object_id in mixed_objects: + store._object_path(object_id).unlink() + verify_snapshot(root, expected, root_tree, nested_tree, blob, merge, parents) + print("mixed snapshot -> all seven objects verified: true") + + store.pack_objects(objects) + for object_id in objects: + store._object_path(object_id).unlink(missing_ok=True) + verify_snapshot(root, expected, root_tree, nested_tree, blob, merge, parents) + print("packed-only snapshot -> all seven objects verified: true") + + print("temporary repository cleaned up: true") + return 0 + + +if __name__ == "__main__": + raise SystemExit(main())