(* Copyright (c) 2026 Thomas Gazagnaire 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. *) (** Interop: the commit-graph (gitformat-commit-graph(5)) and the multi-pack-index (gitformat-pack(5), "multi-pack-index (MIDX) files") that real git writes. Traces generated by: the git named in [traces/git-version]. Regenerate: [REGEN=1 dune build @traces]. [scripts/generate.sh] builds one history in three packed stages: merges, a four-parent octopus (the Extra Edge List), a criss-cross with two merge bases, a committer date older than its parent's, a corrected commit date offset past 31 bits (the Generation Data Overflow chunk), a commit time past 32 bits and two roots. Git writes a commit-graph over it in six shapes: one file, one file of generation data v1 only, one file missing the last stage, a chain of three layers, a chain whose base layer has no generation data v2, and a chain whose top layer has none: generation numbers are corrected commit dates only when every layer carries them. The answers come from git with [core.commitGraph=false]; each shape, and no graph at all, must give exactly those answers. {b Known upstream bugs (git 2.54.0, Apple Git-157):} - [git commit-graph write] stores a wrong Generation Data offset for a commit whose corrected commit date is past 2^32 while its own date is not: the offset is cut to 32 bits and no overflow entry is written. [git commit-graph verify] refuses the file and [git merge-base --is-ancestor] answers wrongly with it. The fixture makes no such commit; its date past 2^32 is on a branch nothing merges. No upstream issue filed as of 2026-09-29. *) let trace path = Filename.concat "traces" path let rows codec file = match Csv.of_file codec (trace file) with | Ok rows -> rows | Error e -> Alcotest.failf "%s: %a" file Csv.Error.pp e let words s = String.split_on_char ' ' s |> List.filter (( <> ) "") type commit = { name : string; hash : Git.Hash.t; tree : Git.Hash.t; parents : Git.Hash.t list; date : int64; } let commits = rows Csv.( Row.( obj (fun name hash tree parents date -> { name; hash = Git.Hash.of_hex hash; tree = Git.Hash.of_hex tree; parents = List.map Git.Hash.of_hex (words parents); date = Int64.of_string date; }) |> col "name" Field.string ~enc:(fun r -> r.name) |> col "hash" Field.string ~enc:(fun r -> Git.Hash.to_hex r.hash) |> col "tree" Field.string ~enc:(fun r -> Git.Hash.to_hex r.tree) |> col "parents" Field.string ~enc:(fun _ -> "") |> col "date" Field.string ~enc:(fun r -> Int64.to_string r.date) |> finish)) "commits.csv" let commit name = match List.find_opt (fun c -> c.name = name) commits with | Some c -> c | None -> Alcotest.failf "no commit %s in commits.csv" name let name_of hash = match List.find_opt (fun c -> Git.Hash.equal c.hash hash) commits with | Some c -> c.name | None -> Git.Hash.to_hex hash let triple a b c = (a, b, c) let triples file (x, y, z) = rows Csv.( Row.( obj triple |> col x Field.string ~enc:(fun (a, _, _) -> a) |> col y Field.string ~enc:(fun (_, b, _) -> b) |> col z Field.string ~enc:(fun (_, _, c) -> c) |> finish)) file let ancestry = triples "ancestry.csv" ("ancestor", "descendant", "expected") let merge_bases = triples "merge_bases.csv" ("left", "right", "best") let ranges = triples "ranges.csv" ("base", "head", "commits") (* The commits reachable from the branch tips of a stage. *) let stage name = rows Csv.( Row.( obj (fun stage name -> (stage, name)) |> col "stage" Field.string ~enc:fst |> col "name" Field.string ~enc:snd |> finish)) "stages.csv" |> List.filter_map (fun (s, n) -> if s = name then Some n else None) (* The commits git has in the graph that misses the last stage. *) let stage2 = stage "s2" (* {1 A repository per graph shape} *) let read_file path = In_channel.with_open_bin path In_channel.input_all let write_file path data = Out_channel.with_open_bin path (fun oc -> Out_channel.output_string oc data) let rec copy_tree src dst = if Sys.is_directory src then begin if not (Sys.file_exists dst) then Sys.mkdir dst 0o755; Array.iter (fun e -> copy_tree (Filename.concat src e) (Filename.concat dst e)) (Sys.readdir src) end else write_file dst (read_file src) (* The graph shapes git wrote, and [None] for a repository without one. *) let shapes = [ None; Some "single"; Some "v1"; Some "stale"; Some "chain"; Some "mixed"; Some "v1-top"; ] (* The shapes that hold every commit of the history. *) let complete = function | Some ("single" | "v1" | "chain" | "mixed" | "v1-top") -> true | _ -> false let shape_name = function None -> "none" | Some s -> s (* [with_repo shape f] runs [f] on a repository holding the fixture's packs and, for [Some s], the commit-graph files of shape [s] in [objects/info]; [setup] then edits its git directory before it is opened. *) let with_repo ?(midx = false) ?(setup = ignore) shape f = Test_helpers.with_temp_repo @@ fun sw fs dir -> let git_dir = Fpath.(to_string (dir / ".git")) in ignore (Git_eio.Repository.init ~sw ~fs dir); let objects = Filename.concat git_dir "objects" in let pack_dir = Filename.concat objects "pack" in List.iter (fun d -> if not (Sys.file_exists d) then Sys.mkdir d 0o755) [ pack_dir; Filename.concat objects "info" ]; Array.iter (fun e -> if Filename.check_suffix e ".pack" || Filename.check_suffix e ".idx" || (midx && e = "multi-pack-index") then write_file (Filename.concat pack_dir e) (read_file (Filename.concat (trace "repo") e))) (Sys.readdir (trace "repo")); Option.iter (fun s -> copy_tree (Filename.concat (trace "graphs") s) (Filename.concat objects "info")) shape; setup git_dir; f (Git_eio.Repository.open_repo ~sw ~fs dir) (* {1 Answers} *) (* Each case compares its whole table at once: a mismatch shows as the rows that differ. *) let check_table what expected got = Alcotest.(check (list string)) what expected got let check_ancestry shape () = with_repo shape @@ fun repo -> let row via (a, d, _) = let ancestor = (commit a).hash and descendant = (commit d).hash in Fmt.str "%s %s %b" a d (via repo ~ancestor ~descendant) in let expected = List.map (fun (a, d, e) -> Fmt.str "%s %s %s" a d e) ancestry in check_table "Rev_list.is_ancestor" expected (List.map (row Git_eio.Rev_list.is_ancestor) ancestry); check_table "Repository.is_ancestor" expected (List.map (row Git_eio.Repository.is_ancestor) ancestry) let merge_bases_all = triples "merge_bases.csv" ("left", "right", "all") let check_merge_base shape () = with_repo shape @@ fun repo -> let row via to_string (l, r, _) = Fmt.str "%s %s %s" l r (to_string (via repo (commit l).hash (commit r).hash)) in check_table "merge-base" (List.map (fun (l, r, best) -> Fmt.str "%s %s %s" l r best) merge_bases) (List.map (row Git_eio.Rev_list.merge_base (Option.fold ~none:"" ~some:name_of)) merge_bases); check_table "merge-base --all" (List.map (fun (l, r, all) -> Fmt.str "%s %s %s" l r all) merge_bases_all) (List.map (row Git_eio.Rev_list.merge_bases (fun hs -> List.map name_of hs |> List.sort String.compare |> String.concat " ")) merge_bases_all) let check_range shape () = with_repo shape @@ fun repo -> check_table "rev-list" (List.map (fun (b, h, e) -> Fmt.str "%s..%s %s" b h e) ranges) (List.map (fun (b, h, _) -> match Git_eio.Rev_list.range repo ~base:(commit b).hash ~head:(commit h).hash with | Ok got -> Fmt.str "%s..%s %s" b h (String.concat " " (List.map name_of got)) | Error (`Msg m) -> Fmt.str "%s..%s error: %s" b h m) ranges) (* Every commit's parents, in order, as a walk of the whole history sees them: an octopus's third and fourth parents come from the Extra Edge List. *) let check_parents shape () = with_repo shape @@ fun repo -> let line name parents = Fmt.str "%s: %s" name (String.concat " " (List.map name_of parents)) in List.iter (fun c -> match Git_eio.Rev_list.topo_sort_reverse repo c.hash ~stop:(fun _ -> false) with | Error (`Msg m) -> Alcotest.failf "walk from %s: %s" c.name m | Ok infos -> let names = List.map (fun (i : Git_eio.Rev_list.commit_info) -> name_of i.hash) infos in check_table (Fmt.str "parents below %s" c.name) (List.map (fun n -> line n (commit n).parents) names) (List.map (fun (i : Git_eio.Rev_list.commit_info) -> line (name_of i.hash) i.parents) infos)) commits (* {1 What a walk reads} The commit-graph holds a commit's parents and generation, so a walk inside the graph reads no commit object; with the graph that misses the last stage, a walk reads at most the commits of that stage. Without the graph the same walks read the history. *) module Counting = struct include Git_eio.Repository let reads = ref 0 let read repo hash = incr reads; Git_eio.Repository.read repo hash end module Counted = Git.Rev_list.Make (Counting) let outside = List.length commits - List.length stage2 let bound shape = if complete shape then 0 else outside let check_reads shape () = with_repo shape @@ fun repo -> let bound = bound shape in List.iter (fun (a, d, _) -> Counting.reads := 0; ignore (Counted.is_ancestor repo ~ancestor:(commit a).hash ~descendant:(commit d).hash); if !Counting.reads > bound then Alcotest.failf "is_ancestor %s %s read %d commits, more than %d" a d !Counting.reads bound) ancestry; List.iter (fun (l, r, _) -> Counting.reads := 0; ignore (Counted.merge_base repo (commit l).hash (commit r).hash); if !Counting.reads > bound then Alcotest.failf "merge_base %s %s read %d commits, more than %d" l r !Counting.reads bound) merge_bases let suite shape = let case name f = Alcotest.test_case name `Quick (f shape) in ( shape_name shape, [ case "is_ancestor" check_ancestry; case "merge_base" check_merge_base; case "range" check_range; case "parents" check_parents; ] @ if shape = None then [] else [ case "reads" check_reads ] ) (* {1 The multi-pack-index} Git wrote it over the first two packs, which [midx-packs] names; every object of those packs is found in it at the offset [git show-index] gives, and no object of the third pack is. *) let objects = triples "objects.csv" ("hash", "pack", "offset") let midx_packs = read_file (trace "midx-packs") |> String.split_on_char '\n' |> List.filter (( <> ) "") let check_midx_lookup () = match Git.Multi_pack_index.of_string (read_file (Filename.concat (trace "repo") "multi-pack-index")) with | Error (`Msg m) -> Alcotest.failf "multi-pack-index: %s" m | Ok midx -> let packs = Git.Multi_pack_index.packs midx in Alcotest.(check (list string)) "packs" midx_packs (List.sort String.compare packs); let expected (h, pack, offset) = if List.mem pack midx_packs then Fmt.str "%s %s %s" h pack offset else Fmt.str "%s absent" h in let got (h, _, _) = match Git.Multi_pack_index.find midx (Git.Hash.of_hex h) with | None -> Fmt.str "%s absent" h | Some (id, offset) -> Fmt.str "%s %s %s" h (List.nth packs id) (Optint.Int63.to_string offset) in check_table "objects" (List.map expected objects) (List.map got objects); Alcotest.(check int) "count" (List.length (List.filter (fun (_, p, _) -> List.mem p midx_packs) objects)) (Git.Multi_pack_index.count midx) (* Every object reads to the same bytes with and without the multi-pack-index, and with it an object of a pack it covers costs one index search, one of the third pack two. *) let check_midx_reads () = let read ~midx = with_repo ~midx None @@ fun repo -> let stats = Git_eio.Repository.stats repo in List.map (fun (h, pack, _) -> let before = stats.index_probes in let body = match Git_eio.Repository.read_object_raw repo (Git.Hash.of_hex h) with | Ok (_, body) -> Digest.to_hex (Digest.string body) | Error (`Msg m) -> "error: " ^ m in let probes = stats.index_probes - before in let covered = List.mem pack midx_packs in (Fmt.str "%s %s" h body, (Fmt.str "%s %b" h covered, probes))) objects in let plain = read ~midx:false and indexed = read ~midx:true in check_table "bodies" (List.map fst plain) (List.map fst indexed); check_table "index probes" (List.map (fun (_, (k, _)) -> Fmt.str "%s %d" k (if String.ends_with ~suffix:"true" k then 1 else 2)) indexed) (List.map (fun (_, (k, n)) -> Fmt.str "%s %d" k n) indexed) (* With no multi-pack-index, the packs are searched most recently used first, as Git searches packed_git_mru (packfile.c, find_pack_entry): a pack an object is found in moves to the front. After one object of each pack, read in the order of their names, the order is the third, the second, the first, whatever order the directory lists them in, and each read below costs the rank its pack has then. A search in listing order costs one pack's rank on every read and a search of the last pack found first then listing order costs three on the fourth read, so both miss these counts. *) let check_mru_reads () = with_repo None @@ fun repo -> let stats = Git_eio.Repository.stats repo in let packs = List.sort_uniq String.compare (List.map (fun (_, p, _) -> p) objects) in let of_pack p = List.filter (fun (_, q, _) -> String.equal p q) objects in let queue = Hashtbl.create 3 in List.iter (fun p -> Hashtbl.replace queue p (of_pack p)) packs; let probes p = match Hashtbl.find queue p with | [] -> Alcotest.failf "no object of %s left" p | (h, _, _) :: rest -> Hashtbl.replace queue p rest; let before = stats.index_probes in (match Git_eio.Repository.read_object_raw repo (Git.Hash.of_hex h) with | Ok _ -> () | Error (`Msg m) -> Alcotest.failf "%s: %s" h m); stats.index_probes - before in let pack i = List.nth packs i in List.iter (fun p -> ignore (probes p)) packs; let reads = [ (0, 3); (0, 1); (1, 3); (0, 2); (2, 3) ] in check_table "index probes" (List.map (fun (i, n) -> Fmt.str "%s %d" (pack i) n) reads) (List.map (fun (i, _) -> Fmt.str "%s %d" (pack i) (probes (pack i))) reads) (* Through a fresh handle, an object of a pack the multi-pack-index covers opens the multi-pack-index and that pack, and no pack index; one of the third pack opens the multi-pack-index, the third pack's index and the third pack. The handle itself opens none. A handle that opens every pack's index and pack before its first lookup holds seven. *) let check_midx_opens () = let opens (h, pack, _) = with_repo ~midx:true None @@ fun repo -> let handle = Git_eio.Pack_windows.open_files () in (match Git_eio.Repository.read_object_raw repo (Git.Hash.of_hex h) with | Ok _ -> () | Error (`Msg m) -> Alcotest.failf "%s: %s" h m); let lookup = Git_eio.Pack_windows.open_files () - handle in Fmt.str "%s %b handle %d lookup %d" h (List.mem pack midx_packs) handle lookup in let expected (h, pack, _) = let covered = List.mem pack midx_packs in Fmt.str "%s %b handle 0 lookup %d" h covered (if covered then 2 else 3) in check_table "files opened" (List.map expected objects) (List.map opens objects) (* {1 Where git reads no graph} Git uses no commit-graph where core.commitGraph is false, where grafts rewrite parents, or while the repository is shallow (gitformat-commit-graph(5), "Design Details"): the parents a graph records are not the ones git answers with there. Each case adds one of those to a repository whose complete graph is otherwise used. *) let append path data = Out_channel.with_open_gen [ Open_append; Open_creat; Open_binary ] 0o644 path (fun oc -> Out_channel.output_string oc data) let graph_used ?setup () = with_repo ?setup (Some "single") @@ fun repo -> Option.is_some (Git_eio.Repository.commit_graph repo) let check_graph_used () = Alcotest.(check bool) "complete graph" true (graph_used ()) let check_graph_ignored what setup () = Alcotest.(check bool) what false (graph_used ~setup ()) let a1 = Git.Hash.to_hex (commit "a1").hash let ignored = [ ( "core.commitGraph=false", fun git_dir -> append (Filename.concat git_dir "config") "[core]\n\tcommitGraph = false\n" ); ( "grafts", fun git_dir -> write_file (Filename.concat git_dir "objects/info/grafts") (a1 ^ "\n") ); ( "shallow", fun git_dir -> write_file (Filename.concat git_dir "shallow") (a1 ^ "\n") ); ] (* {1 A multi-pack-index naming a pack that is gone} After a repack, a multi-pack-index can name a pack the directory no longer holds while its objects sit in a pack it does not name. Here the first pack it covers is renamed: every object still reads to the same bytes. *) let check_midx_gone_pack () = let bodies ?setup ~midx () = with_repo ~midx ?setup None @@ fun repo -> List.map (fun (h, _, _) -> match Git_eio.Repository.read_object_raw repo (Git.Hash.of_hex h) with | Ok (_, body) -> Fmt.str "%s %s" h (Digest.to_hex (Digest.string body)) | Error (`Msg m) -> Fmt.str "%s error: %s" h m) objects in let gone = Filename.chop_suffix (List.hd midx_packs) ".idx" in let setup git_dir = let pack_dir = Filename.concat git_dir "objects/pack" in List.iter (fun ext -> Sys.rename (Filename.concat pack_dir (gone ^ ext)) (Filename.concat pack_dir ("pack-" ^ String.make 40 '0' ^ ext))) [ ".idx"; ".pack" ] in check_table "bodies" (bodies ~midx:false ()) (bodies ~midx:true ~setup ()) (* {1 Writing} Each file git wrote is written again from the commits it holds, their objects' fields from [commits.csv] and the layer below read from git's own file: the bytes must be git's. [single] holds every commit and [stale] the first two stages; [chain] is the first stage, then the second over it, then the rest over both; [mixed]'s top layer, over a base with no generation data v2, carries none either. *) let graph_commit name = let c = commit name in { Git.Commit_graph.hash = c.hash; tree = c.tree; parents = c.parents; time = c.date; } let all_names = List.map (fun c -> c.name) commits let minus a b = List.filter (fun n -> not (List.mem n b)) a let chain_files shape = let dir = Filename.concat (trace "graphs") (Filename.concat shape "commit-graphs") in read_file (Filename.concat dir "commit-graph-chain") |> String.split_on_char '\n' |> List.filter (( <> ) "") |> List.map (fun h -> read_file (Filename.concat dir ("graph-" ^ h ^ ".graph"))) let graph_of ?base s = match Git.Commit_graph.of_string ?base s with | Ok g -> g | Error (`Msg m) -> Alcotest.failf "git's layer does not read: %s" m (* The first byte where [got] differs from git's [expected], so a mismatch names the chunk to look at. *) let check_bytes what expected got = if expected <> got then let n = min (String.length expected) (String.length got) in let rec first i = if i < n && expected.[i] = got.[i] then first (i + 1) else i in Alcotest.failf "%s: %d bytes, git wrote %d; first difference at byte %d" what (String.length got) (String.length expected) (first 0) let check_encode what ?base names expected () = check_bytes what expected (Git.Commit_graph.encode ?base (List.map graph_commit names)) let encode_cases = let s1 = stage "s1" and s2 = stage "s2" in let chain = chain_files "chain" and mixed = chain_files "mixed" in let l1 = graph_of (List.nth chain 0) in let l2 = graph_of ~base:l1 (List.nth chain 1) in let case what f = Alcotest.test_case what `Quick f in [ case "single" (check_encode "single" all_names (read_file (trace "graphs/single/commit-graph"))); case "stale" (check_encode "stale" s2 (read_file (trace "graphs/stale/commit-graph"))); case "chain, first layer" (check_encode "chain 1" s1 (List.nth chain 0)); case "chain, second layer" (check_encode "chain 2" ~base:l1 (minus s2 s1) (List.nth chain 1)); case "chain, third layer" (check_encode "chain 3" ~base:l2 (minus all_names s2) (List.nth chain 2)); case "mixed, over a base without generation data" (check_encode "mixed 2" ~base:(graph_of (List.nth mixed 0)) (minus all_names s1) (List.nth mixed 1)); ] (* A commit whose parent the layer cannot name is refused, not written. *) let check_encode_refuses () = let m5 = graph_commit "m5" in match Git.Commit_graph.encode [ m5 ] with | _ -> Alcotest.fail "a layer without m5's parents was written" | exception Invalid_argument _ -> () let () = Alcotest.run "commit-graph" (List.map suite shapes @ [ ( "multi-pack-index", [ Alcotest.test_case "lookup" `Quick check_midx_lookup; Alcotest.test_case "reads" `Quick check_midx_reads; Alcotest.test_case "most recently used first" `Quick check_mru_reads; Alcotest.test_case "opens" `Quick check_midx_opens; Alcotest.test_case "gone pack" `Quick check_midx_gone_pack; ] ); ( "encode", encode_cases @ [ Alcotest.test_case "missing parent" `Quick check_encode_refuses ] ); ( "graph ignored", Alcotest.test_case "complete graph used" `Quick check_graph_used :: List.map (fun (what, setup) -> Alcotest.test_case what `Quick (check_graph_ignored what setup)) ignored ); ])