(* 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. *) (** Direct commit-graph oracles from the committed Git traces. The generation recurrence and ordered parents follow gitformat-commit-graph(5). *) module G = Git.Commit_graph let trace path = Filename.concat "../interop/commit-graph/traces" path let read path = In_channel.with_open_bin (trace path) In_channel.input_all let words s = String.split_on_char ' ' s |> List.filter (( <> ) "") type commit = { hash : Git.Hash.t; tree : Git.Hash.t; parents : Git.Hash.t list; date : int64; } let commits () = let codec = Csv.( Row.( obj (fun _name hash tree parents date -> { 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 _ -> "") |> 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)) in match Csv.of_file codec (trace "commits.csv") with | Ok rows -> rows | Error e -> Alcotest.failf "%a" Csv.Error.pp e let parse ?base data = match G.of_read ?base ~length:(String.length data) (String.sub data) with | Ok graph -> graph | Error (`Msg m) -> Alcotest.fail m let graph shape = if List.mem shape [ "single"; "v1" ] then (parse (read ("graphs/" ^ shape ^ "/commit-graph")), 1) else let directory = "graphs/" ^ shape ^ "/commit-graphs/" in let names = read (directory ^ "commit-graph-chain") |> String.split_on_char '\n' |> List.filter (( <> ) "") in let result = List.fold_left (fun base name -> Some (parse ?base (read (directory ^ "graph-" ^ name ^ ".graph")))) None names in match result with | Some graph -> Alcotest.(check string) "top layer checksum" (List.hd (List.rev names)) (Git.Hash.to_hex (G.checksum graph)); (graph, List.length names) | None -> Alcotest.fail "empty committed graph chain" let check_shape shape () = let graph, layers = graph shape in let rows = commits () in let corrected = List.mem shape [ "single"; "chain" ] in let rec generation corrected hash = let row = List.find (fun r -> Git.Hash.equal r.hash hash) rows in let parent = List.fold_left (fun best p -> Int64.max best (generation corrected p)) (if corrected then -1L else 0L) row.parents in if corrected then Int64.max row.date (Int64.succ parent) else Int64.succ parent in Alcotest.(check int) "all recorded commits" (List.length rows) (G.count graph); Alcotest.(check int) "layer count" layers (G.layers graph); Alcotest.(check bool) "generation kind" corrected (G.corrected_dates graph); List.iter (fun row -> let position = match G.find graph row.hash with | Some p -> p | None -> Alcotest.fail "recorded commit absent" in Alcotest.(check string) "hash at position" (Git.Hash.to_hex row.hash) (Git.Hash.to_hex (G.hash graph position)); Alcotest.(check string) "root tree" (Git.Hash.to_hex row.tree) (Git.Hash.to_hex (G.tree graph position)); Alcotest.(check (list string)) "ordered parents" (List.map Git.Hash.to_hex row.parents) (List.map (fun p -> Git.Hash.to_hex (G.hash graph p)) (G.parents graph position)); Alcotest.(check int64) "commit date" row.date (G.commit_time graph position); Alcotest.(check int64) "generation recurrence" (generation corrected row.hash) (G.generation graph position)) rows; Alcotest.(check (option int)) "unknown commit" None (G.find graph Git.Hash.null) (* {1 Writing a layer on disk} [Repository.write_commit_graph] over the interop fixture's packs, every commit a tip, from each graph git left there: none, the whole file missing the last stage, the chain without its top layer, and the whole graph. Git writes from the same start ([git commit-graph write --split --stdin-commits]): the files must be git's, git's own [commit-graph verify] must accept them, and the write must read the objects of the commits the graph lacked and no others. *) 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) let with_fixture ?(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" then write_file (Filename.concat pack_dir e) (read (Filename.concat "repo" e))) (Sys.readdir (trace "repo")); Option.iter (fun s -> copy_tree (trace (Filename.concat "graphs" s)) (Filename.concat objects "info")) shape; setup git_dir; f ~reopen:(fun () -> Git_eio.Repository.open_repo ~sw ~fs dir) dir git_dir (Git_eio.Repository.open_repo ~sw ~fs dir) (* gitformat-commit-graph(5), TRAILER: the hash covers all preceding bytes. These offsets are the CDAT chunk starts of the committed Git vectors; its first 20 bytes are a root-tree OID, so changing one preserves every table, size, base identity and parent position. *) let check_checksum ~single () = let shape = if single then "single" else "chain" in with_fixture (Some shape) @@ fun ~reopen _ git_dir repo -> let original = Option.get (Git_eio.Repository.commit_graph repo) in Alcotest.(check int) "the unmodified Git graph loads" 28 (G.count original); let info = Filename.concat git_dir "objects/info" in let path, offset = if single then (Filename.concat info "commit-graph", 1676) else let directory = Filename.concat info "commit-graphs" in let names = read_file (Filename.concat directory "commit-graph-chain") |> String.split_on_char '\n' |> List.filter (( <> ) "") in ( Filename.concat directory ("graph-" ^ List.hd (List.rev names) ^ ".graph"), 1348 ) in let bytes = Bytes.of_string (read_file path) in Bytes.set bytes offset (Char.chr (Char.code (Bytes.get bytes offset) lxor 1)); write_file path (Bytes.to_string bytes); let loaded = Git_eio.Repository.commit_graph (reopen ()) in if single then Alcotest.(check bool) "the altered whole graph is refused" true (Option.is_none loaded) else match loaded with | Some graph -> Alcotest.(check int) "only the two valid base layers remain" 17 (G.count graph) | None -> Alcotest.fail "the valid base prefix was discarded" let graph_files git_dir = let info = Filename.concat git_dir "objects/info" in let dir = Filename.concat info "commit-graphs" in let single = Filename.concat info "commit-graph" in let digest f = Digest.to_hex (Digest.string (read_file f)) in (if Sys.file_exists single then [ "commit-graph " ^ digest single ] else []) @ if Sys.file_exists dir then Sys.readdir dir |> Array.to_list |> List.sort String.compare |> List.map (fun f -> "commit-graphs/" ^ f ^ " " ^ digest (Filename.concat dir f)) else [] let without_top git_dir = let dir = Filename.concat git_dir "objects/info/commit-graphs" in let chain = Filename.concat dir "commit-graph-chain" in let names = read_file chain |> String.split_on_char '\n' |> List.filter (( <> ) "") in let top = List.length names - 1 in write_file chain (String.concat "" (List.filteri (fun i _ -> i < top) names |> List.map (fun n -> n ^ "\n"))); Sys.remove (Filename.concat dir ("graph-" ^ List.nth names top ^ ".graph")) let starts = [ ("no graph", None, ignore); ("whole file missing the last stage", Some "stale", ignore); ("chain without its top layer", Some "chain", without_top); ("whole graph", Some "single", ignore); ] let check_write (_, shape, setup) () = let rows = commits () in let tips = List.map (fun r -> r.hash) rows in let tip_file = Filename.temp_file "tips" "" in write_file tip_file (String.concat "" (List.map (fun h -> Git.Hash.to_hex h ^ "\n") tips)); let expected = with_fixture ~setup shape @@ fun ~reopen:_ dir git_dir _ -> Test_helpers.git ~dir ("commit-graph write --split --stdin-commits < " ^ Filename.quote tip_file); graph_files git_dir in with_fixture ~setup shape @@ fun ~reopen dir git_dir repo -> let lacked = match Git_eio.Repository.commit_graph repo with | None -> List.length rows | Some g -> List.length (List.filter (fun r -> G.find g r.hash = None) rows) in let stats = Git_eio.Repository.stats repo in let before = stats.loose_reads + stats.pack_reads in Test_helpers.or_fail "write_commit_graph" (Git_eio.Repository.write_commit_graph repo tips); Alcotest.(check int) "objects read" lacked (stats.loose_reads + stats.pack_reads - before); Alcotest.(check (list string)) "files, as git wrote them" expected (graph_files git_dir); Test_helpers.git ~dir "commit-graph verify"; match Git_eio.Repository.commit_graph (reopen ()) with | Some g -> Alcotest.(check int) "commits in the graph" (List.length rows) (G.count g) | None -> Alcotest.fail "no graph after the write" (* Another writer's lock is refused, and nothing is written. *) let check_write_locked () = with_fixture (Some "stale") @@ fun ~reopen:_ _ git_dir repo -> let dir = Filename.concat git_dir "objects/info/commit-graphs" in Sys.mkdir dir 0o755; write_file (Filename.concat dir "commit-graph-chain.lock") ""; let before = graph_files git_dir in (match Git_eio.Repository.write_commit_graph repo (List.map (fun r -> r.hash) (commits ())) with | Ok () -> Alcotest.fail "wrote under another writer's lock" | Error _ -> ()); Alcotest.(check (list string)) "files" before (graph_files git_dir) (* A layer costs the commits it adds, not the history below them: over a graph of [n] commits, adding [k] reads [k] objects, at two sizes of history an order of magnitude apart. *) let extend ~n ~k = Test_helpers.with_temp_repo @@ fun sw fs dir -> let repo = Git_eio.Repository.init ~sw ~fs dir in let tree = Git_eio.Repository.write_tree repo (Git.Tree.v []) in let line from count = List.fold_left (fun parent i -> Some (Test_helpers.commit ~repo ~tree ~parents:(Option.to_list parent) ~message:(Fmt.str "c%d" i))) from (List.init count (fun i -> i)) in let write tip = Test_helpers.or_fail "write_commit_graph" (Git_eio.Repository.write_commit_graph repo [ tip ]) in let base = Option.get (line None n) in write base; let tip = Option.get (line (Some base) k) in let stats = Git_eio.Repository.stats repo in let before = stats.loose_reads + stats.pack_reads in write tip; let reads = stats.loose_reads + stats.pack_reads - before in let graph = Option.get (Git_eio.Repository.commit_graph repo) in (reads, G.count graph, G.layers graph) let check_bounded () = List.iter (fun n -> Alcotest.(check (triple int int int)) (Fmt.str "objects read, commits, layers over %d commits" n) (3, n + 3, 2) (extend ~n ~k:3)) [ 40; 400 ] let suite = ( "commit_graph", List.map (fun shape -> Alcotest.test_case ("Git trace " ^ shape) `Quick (check_shape shape)) [ "single"; "v1"; "chain"; "mixed"; "v1-top" ] @ List.map (fun ((what, _, _) as start) -> Alcotest.test_case ("write from " ^ what) `Quick (check_write start)) starts @ [ Alcotest.test_case "write under another writer's lock" `Quick check_write_locked; Alcotest.test_case "a layer reads its commits" `Quick check_bounded; Alcotest.test_case "a whole graph verifies its body checksum" `Quick (check_checksum ~single:true); Alcotest.test_case "a split graph verifies its new layer checksum" `Quick (check_checksum ~single:false); ] )