Something went wrong. Try again.
Git format in pure OCaml
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369(* Copyright (c) 2024-2026 Thomas Gazagnaire <thomas@gazagnaire.org>
Permission to use, copy, modify, and distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. *)
(** Bitmap tests. Stock git is the oracle for the round trip: parse the .bitmap that [git repack -adb] writes and check every commit entry against [git rev-list --objects], then re-emit the bitmap with our writer and make git verify and use it; those are gated on git in PATH. The header counts are checked against a synthetic index instead, so they always run. *)
let git_available = lazy (Sys.command "git --version > /dev/null 2>&1" = 0)
(* Run git with the caller's git environment dropped. Git exports GIT_DIR and GIT_INDEX_FILE to its hook children, and a shell that drives the .todo shadow repo exports GIT_DIR by hand, so this test can inherit variables naming a real repository. They override -C, so without this a fixture's "git init" re-initialises that repository and its commits land there. Same list as scripts/git-env-strip.sh, which does this for the cram tests. *)let run ~dir args = let cmd = Fmt.str "env -u GIT_DIR -u GIT_WORK_TREE -u GIT_INDEX_FILE -u \ GIT_OBJECT_DIRECTORY -u GIT_COMMON_DIR -u \ GIT_ALTERNATE_OBJECT_DIRECTORIES -u GIT_PREFIX -u GIT_QUARANTINE_PATH \ git -C %s %s 2>&1" (Filename.quote dir) args in let ic = Unix.open_process_in cmd in let buf = Buffer.create 256 in (try while true do Buffer.add_channel buf ic 1 done with End_of_file -> ()); let status = Unix.close_process_in ic in let code = match status with Unix.WEXITED n -> n | _ -> 255 in (code, String.trim (Buffer.contents buf))
let git ~dir args = match run ~dir args with | 0, out -> out | code, out -> Alcotest.failf "git %s: exit %d: %s" args code out
let read_file path = let ic = open_in_bin path in let n = in_channel_length ic in let data = really_input_string ic n in close_in ic; data
let write_file path data = let oc = open_out_bin path in output_string oc data; close_out oc
(* A repo with three commits, each adding one file, repacked with bitmaps. Returns (dir, index, bitmap path, bitmap contents). *)let setup () = let dir = Filename.temp_dir "git-bitmap" "" in let _ = git ~dir "init -q ." in for i = 1 to 3 do let path = Fmt.str "f%d.txt" i in Fmt.kstr (write_file (Filename.concat dir path)) "content %d\n" i; let _ = Fmt.kstr (git ~dir) "add f%d.txt" i in let _ = Fmt.kstr (git ~dir) "-c user.email=a@b -c user.name=t commit -qm c%d" i in () done; let _ = git ~dir "repack -adbq" in let pack_dir = Filename.concat dir ".git/objects/pack" in let base = Sys.readdir pack_dir |> Array.to_list |> List.find (fun f -> Filename.check_suffix f ".bitmap") |> fun f -> Filename.chop_suffix f ".bitmap" in let index = match Git.Pack_index.of_string (read_file (Filename.concat pack_dir (base ^ ".idx"))) with | Ok i -> i | Error (`Msg m) -> Alcotest.fail m in let bitmap_path = Filename.concat pack_dir (base ^ ".bitmap") in (dir, index, bitmap_path, read_file bitmap_path)
let hexes_of_bits ~order bits = Ewah.fold (fun pos acc -> Git.Hash.to_hex order.(pos) :: acc) bits [] |> List.sort String.compare
let rev_list_objects ~dir commit = Fmt.kstr (git ~dir) "rev-list --objects %s" commit |> String.split_on_char '\n' |> List.filter_map (fun line -> if line = "" then None else Some (List.hd (String.split_on_char ' ' line))) |> List.sort String.compare
let parse_matches_rev_list () = if not (Lazy.force git_available) then () else begin let dir, index, _, data = setup () in let bm = match Git.Bitmap.of_string ~index data with | Ok bm -> bm | Error (`Msg m) -> Alcotest.fail m in Alcotest.(check int) "three commit entries" 3 (List.length bm.entries); Alcotest.(check int) "three commits" 3 (Ewah.cardinal bm.commits); Alcotest.(check int) "three trees" 3 (Ewah.cardinal bm.trees); Alcotest.(check int) "three blobs" 3 (Ewah.cardinal bm.blobs); Alcotest.(check int) "no tags" 0 (Ewah.cardinal bm.tags); let order = Git.Bitmap.pack_order index in List.iter (fun (e : Git.Bitmap.entry) -> let hex = Git.Hash.to_hex e.commit in Alcotest.(check (list string)) (Fmt.str "closure of %s" hex) (rev_list_objects ~dir hex) (hexes_of_bits ~order e.bits)) bm.entries end
let emitted_bitmap_accepted_by_git () = if not (Lazy.force git_available) then () else begin let dir, index, bitmap_path, data = setup () in let bm = match Git.Bitmap.of_string ~index data with | Ok bm -> bm | Error (`Msg m) -> Alcotest.fail m in let ours = match Git.Bitmap.to_string ~index ~commits:bm.commits ~trees:bm.trees ~blobs:bm.blobs ~tags:bm.tags ~entries: (List.map (fun (e : Git.Bitmap.entry) -> (e.commit, e.bits)) bm.entries) with | Ok s -> s | Error (`Msg m) -> Alcotest.fail m in Sys.remove bitmap_path; write_file bitmap_path ours; (* git verifies our bitmap against a real traversal... *) let code, out = run ~dir "rev-list --test-bitmap HEAD" in Alcotest.(check int) (Fmt.str "git --test-bitmap accepts ours: %s" out) 0 code; (* ...and traversal through it matches the plain walk. *) let plain = git ~dir "rev-list --count HEAD" in let bitmapped = git ~dir "rev-list --use-bitmap-index --count HEAD" in Alcotest.(check string) "bitmap-indexed count" plain bitmapped; (* Our parser roundtrips our own file. *) match Git.Bitmap.of_string ~index ours with | Ok bm2 -> Alcotest.(check int) "roundtrip entries" (List.length bm.entries) (List.length bm2.entries); List.iter2 (fun (a : Git.Bitmap.entry) (b : Git.Bitmap.entry) -> Alcotest.(check bool) "roundtrip bits" true (Git.Hash.equal a.commit b.commit && Ewah.equal a.bits b.bits)) bm.entries bm2.entries | Error (`Msg m) -> Alcotest.fail m end
(* Header counts against the pack *)
(* Every count in a .bitmap is a count of objects in the pack it belongs to: a bit position is a pack-order object position, and an entry is one of the pack's commits (git's Documentation/technical/bitmap-format.adoc, "bitmap entry" and the type indexes). Neither may be believed before it is checked against the index. The decoded form is one bit per position and one array slot per entry, so a file of a hundred bytes that declares millions of either is asking for an allocation the pack cannot account for. These build a synthetic index rather than a repository, so they run without git. *)
let index_for n = let entries = List.init n (fun i -> ( Fmt.kstr Git.Hash.of_hex "%040x" (i + 1), Optint.Int63.of_int (12 + (i * 32)), Wire.UInt32.of_int32 0l )) in let pack_checksum = Git.Hash.of_hex (String.make 40 'a') in match Git.Pack_index.of_string (Git.Pack_index.write ~pack_checksum entries) with | Ok index -> index | Error (`Msg m) -> Alcotest.fail m
(* A .bitmap header: magic, version 1, the FULL_DAG flag the reader requires, the entry count, and the pack checksum it is matched against. *)let bitmap_header ~index ~entry_count = let b = Bytes.make 32 '\000' in Bytes.blit_string "BITM" 0 b 0 4; Bytes.set_int16_be b 4 1; Bytes.set_int16_be b 6 1; Bytes.set_int32_be b 8 (Int32.of_int entry_count); Bytes.blit_string (Git.Hash.to_raw_string (Git.Pack_index.pack_checksum index)) 0 b 12 20; Bytes.to_string b
(* An EWAH chunk of [bit_size] zero bits. One clean run covers them all, so the chunk is 20 bytes whatever it declares. *)let ewah_chunk bit_size = let b = Bytes.make 20 '\000' in Bytes.set_int32_be b 0 (Int32.of_int bit_size); Bytes.set_int32_be b 4 1l; Bytes.set_int64_be b 8 (Int64.shift_left (Int64.of_int ((bit_size + 63) / 64)) 1); Bytes.to_string b
(* Refusing after the allocation is no refusal, so the check is on what the parse allocates as well as on what it returns. *)let refused_without_allocating name ~index data = Gc.full_major (); let before = Gc.allocated_bytes () in let result = Git.Bitmap.of_string ~index data in let allocated = Gc.allocated_bytes () -. before in (match result with | Ok _ -> Alcotest.failf "%s: %d-byte bitmap accepted" name (String.length data) | Error (`Msg m) -> if not (Astring.String.is_infix ~affix:"9 objects" m) then Alcotest.failf "%s: %S does not name the pack's object count" name m); if allocated >= 65_536. then Alcotest.failf "%s: %d-byte bitmap allocated %.0f bytes" name (String.length data) allocated
let entry_count_past_the_pack () = let index = index_for 9 in let empty = String.concat "" (List.init 4 (fun _ -> ewah_chunk 0)) in refused_without_allocating "entry count" ~index (bitmap_header ~index ~entry_count:10_000_000 ^ empty)
let bitmap_wider_than_the_pack () = let index = index_for 9 in let empty = String.concat "" (List.init 3 (fun _ -> ewah_chunk 0)) in refused_without_allocating "type bitmap" ~index (bitmap_header ~index ~entry_count:0 ^ ewah_chunk 10_000_000 ^ empty)
(* Bit positions against the pack *)
(* A bit position IS an object position. git's Documentation/technical/bitmap-format.adoc says so twice: under "Pack and multi-pack bitmaps", "the nth bit corresponds to the nth object in pack order"; and of the type indexes, "the nth bit is set to true if the nth object in the packfile or multi-pack index is of that type". A pack of n objects has positions 0 .. n-1 and no others, and git reads them that way -- for_each_bitmapped_object in pack-bitmap.c fills its all-ones bitmap over exactly num_objects bits and leaves the rest of the last word clear.
The size a chunk DECLARES is a different quantity. Appendix A stores "the number of bits of the resulting UNCOMPRESSED bitmap", which git rounds up to whole 64-bit words, so a legitimate bitmap over a nine-object pack declares 64 bits. A bound on the declared size therefore cannot tell that padding from a position the pack does not have. The set bits can. *)
(* An EWAH chunk with one bit set at [pos], declaring the whole 64-bit word that holds it -- the rounding git's serializer applies. Appendix A's layout: the bit count, the compressed word count, one RLW naming [pos / 64] clean words and one literal word, the literal itself, and the RLW's own position. Within a word the low-order bit comes first in the stream. *)let ewah_chunk_with_bit pos = let clean = pos / 64 in let b = Bytes.make 28 '\000' in Bytes.set_int32_be b 0 (Int32.of_int ((clean + 1) * 64)); Bytes.set_int32_be b 4 2l; Bytes.set_int64_be b 8 Int64.(logor (shift_left (of_int clean) 1) (shift_left 1L 33)); Bytes.set_int64_be b 16 (Int64.shift_left 1L (pos mod 64)); Bytes.to_string b
(* An entry: the commit's position in the pack index, no XOR compression, no flags, then the commit's bitmap. *)let bitmap_entry ~commit_pos chunk = let b = Bytes.make 6 '\000' in Bytes.set_int32_be b 0 (Int32.of_int commit_pos); Bytes.to_string b ^ chunk
let bitmap_file ~index ~entry_count sections = let body = bitmap_header ~index ~entry_count ^ String.concat "" sections in body ^ Hash.SHA1.(to_raw_string (digest_string body))
let empty_chunks n = List.init n (fun _ -> ewah_chunk 0)
(* Bit 8 is the ninth and last object of a nine-object pack, and the chunk holding it declares 64 bits because that is the word it sits in. Stock git writes this shape, so it must parse, and every position it carries must index [pack_order]. *)let word_padding_accepted () = let index = index_for 9 in Alcotest.(check int) "the chunk declares a whole word" 64 (Int32.to_int (String.get_int32_be (ewah_chunk_with_bit 8) 0)); let data = bitmap_file ~index ~entry_count:0 (ewah_chunk_with_bit 8 :: empty_chunks 3) in match Git.Bitmap.of_string ~index data with | Error (`Msg m) -> Alcotest.failf "word-padded bitmap refused: %s" m | Ok bm -> Alcotest.(check (list int)) "the pack's last position" [ 8 ] (Ewah.to_indices bm.commits); let order = Git.Bitmap.pack_order index in Ewah.iter (fun pos -> if pos >= Array.length order then Alcotest.failf "position %d is past the %d hashes of pack_order" pos (Array.length order)) bm.commits
(* Bit 63 sits in that same word, so no bound on the declared size can refuse it, and it names no object of a nine-object pack. [pack_order] returns exactly nine hashes, so a consumer folding such a bitmap through it indexes past the array. *)let refuses_bit_past_the_pack name ~index data = match Git.Bitmap.of_string ~index data with | Ok _ -> Alcotest.failf "%s: a bit past the pack's last object accepted" name | Error (`Msg m) -> if not (Astring.String.is_infix ~affix:"bit 63" m) then Alcotest.failf "%s: %S does not name the offending position" name m; if not (Astring.String.is_infix ~affix:"9 objects" m) then Alcotest.failf "%s: %S does not name the pack's object count" name m
let type_bitmap_bit_past_the_pack () = let index = index_for 9 in refuses_bit_past_the_pack "type bitmap" ~index (bitmap_file ~index ~entry_count:0 (ewah_chunk_with_bit 63 :: empty_chunks 3))
let entry_bitmap_bit_past_the_pack () = let index = index_for 9 in refuses_bit_past_the_pack "entry bitmap" ~index (bitmap_file ~index ~entry_count:1 (empty_chunks 4 @ [ bitmap_entry ~commit_pos:0 (ewah_chunk_with_bit 63) ]))
let suite = ( "bitmap", [ Alcotest.test_case "parse matches rev-list" `Quick parse_matches_rev_list; Alcotest.test_case "emitted bitmap accepted by git" `Quick emitted_bitmap_accepted_by_git; Alcotest.test_case "entry count past the pack" `Quick entry_count_past_the_pack; Alcotest.test_case "bitmap wider than the pack" `Quick bitmap_wider_than_the_pack; Alcotest.test_case "word padding accepted" `Quick word_padding_accepted; Alcotest.test_case "type bitmap bit past the pack" `Quick type_bitmap_bit_past_the_pack; Alcotest.test_case "entry bitmap bit past the pack" `Quick entry_bitmap_bit_past_the_pack; ] )