(* 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. *) (* The lines of a note as git-notes(1), "NOTES MERGE STRATEGIES", describes cat_sort_uniq: "cat | sort | uniq" over both versions. Where the manual is silent (empty lines, a missing final newline, a NUL), the expected values are what git 2.54 writes; the interop test under interop/notes holds the same cases as git wrote them. *) let lines = Alcotest.(list string) let test_lines () = Alcotest.check lines "one per newline" [ "a"; "b" ] (Git.Notes.lines "a\nb\n"); Alcotest.check lines "no final newline" [ "a"; "b" ] (Git.Notes.lines "a\nb"); Alcotest.check lines "empty lines dropped" [ "a"; "b" ] (Git.Notes.lines "\n\na\n\n\nb\n\n"); Alcotest.check lines "carriage return kept" [ "a\r"; "b" ] (Git.Notes.lines "a\r\nb\n"); Alcotest.check lines "nothing after a NUL" [ "mid" ] (Git.Notes.lines "mid\000dle\nx\n"); Alcotest.check lines "the empty note" [] (Git.Notes.lines "") let test_add_line () = Alcotest.(check string) "to nothing" "x\n" (Git.Notes.add_line "" "x"); Alcotest.(check string) "after a line" "a\nx\n" (Git.Notes.add_line "a\n" "x"); Alcotest.(check string) "after a line with no newline" "a\nx\n" (Git.Notes.add_line "a" "x"); Alcotest.(check string) "spaces kept" "a\n x y \n" (Git.Notes.add_line "a\n" " x y "); let refused name line = match Git.Notes.add_line "a\n" line with | s -> Alcotest.failf "%s: accepted as %S" name s | exception Invalid_argument _ -> () in refused "the empty line" ""; refused "two lines" "x\ny"; refused "a final newline" "x\n"; refused "a NUL" "x\000y" let test_cat_sort_uniq () = Alcotest.(check string) "union, sorted, each once" "a\nb\nc\n" (Git.Notes.cat_sort_uniq "b\na\n" "c\na\n"); Alcotest.(check string) "a duplicate on one side" "a\nb\n" (Git.Notes.cat_sort_uniq "b\nb\na\n" ""); Alcotest.(check string) "bytewise order" "B\nZ\na\nb\n\195\169\n" (Git.Notes.cat_sort_uniq "b\n\195\169\nZ\n" "a\nB\n"); Alcotest.(check string) "empty lines and missing newlines" "a\nb\nc\n" (Git.Notes.cat_sort_uniq "\n\nb\n\nc" "a"); Alcotest.(check string) "a NUL ends a note" "mid\ny\n" (Git.Notes.cat_sort_uniq "mid\000dle\nx\n" "y\n"); Alcotest.(check string) "no lines at all" "" (Git.Notes.cat_sort_uniq "\n\n" "") let test_pp_merge_result () = let h = Git.Hash.of_hex "0123456789abcdef0123456789abcdef01234567" in let has name sub v = let s = Fmt.str "%a" Git.Notes.pp_merge_result v in if not (Astring.String.is_infix ~affix:sub s) then Alcotest.failf "%s: %S has no %S" name s sub in has "up to date" "up to date" Git.Notes.Up_to_date; has "fast-forward" "fast-forward" (Git.Notes.Fast_forward h); has "fast-forward commit" (Git.Hash.to_hex h) (Git.Notes.Fast_forward h); has "merged" "merged" (Git.Notes.Merged h); has "merged commit" (Git.Hash.to_hex h) (Git.Notes.Merged h) (* {1 What a peer's notes make a reader spend} A store in memory that counts the trees and blobs read from it. *) module Mem = struct type t = { objects : (string, Git.Value.t) Hashtbl.t; refs : (string, Git.Hash.t) Hashtbl.t; mutable trees : int; mutable blobs : int; mutable swaps : int; mutable race : (string * Git.Hash.t) option; } let v () = { objects = Hashtbl.create 16; refs = Hashtbl.create 4; trees = 0; blobs = 0; swaps = 0; race = None; } let read t h = match Hashtbl.find_opt t.objects (Git.Hash.to_hex h) with | None -> Error (`Msg (Git.Hash.to_hex h ^ " is absent")) | Some v -> (match Git.Value.kind v with | `Tree -> t.trees <- t.trees + 1 | `Blob -> t.blobs <- t.blobs + 1 | `Commit | `Tag -> ()); Ok v let write t v = let h = Git.Value.digest v in Hashtbl.replace t.objects (Git.Hash.to_hex h) v; h let commit_graph _ = None let read_ref t name = Ok (Hashtbl.find_opt t.refs name) let compare_and_swap_ref t name ~expected ~reflog:_ h = t.swaps <- t.swaps + 1; match t.race with | Some (ref, competing) when String.equal ref name -> t.race <- None; Hashtbl.replace t.refs name competing; Error `Raced | Some _ | None -> if Option.equal Git.Hash.equal (Hashtbl.find_opt t.refs name) expected then ( Hashtbl.replace t.refs name h; Ok ()) else Error `Raced end module N = Git.Notes.Make (Mem) let who = Git.User.v ~name:"Q Ueue" ~email:"q@example.test" ~date:1700000000L () let commit store ?(parents = []) tree = Mem.write store (Git.Value.commit (Git.Commit.v ~tree ~author:who ~committer:who ~parents (Some "notes"))) (* A notes commit whose tree has [levels] fan-out levels, each naming one tree [fanout] times, under which one tree holds [fanout] notes: [levels] + 2 objects for [fanout] ^ ([levels] + 1) notes. *) let shared_fanout store ~levels ~fanout = let blob = Mem.write store (Git.Value.blob (Git.Blob.of_string "x\n")) in let hex2 i = Fmt.str "%02x" i in let leaves = List.init fanout (fun i -> Git.Tree.entry ~perm:`Normal ~name:(hex2 i ^ String.make ((2 * (20 - levels)) - 2) '0') blob) in let rec up tree n = if n = 0 then tree else let dirs = List.init fanout (fun i -> Git.Tree.entry ~perm:`Dir ~name:(hex2 i) tree) in up (Mem.write store (Git.Value.tree (Git.Tree.v dirs))) (n - 1) in let bottom = Mem.write store (Git.Value.tree (Git.Tree.v leaves)) in commit store (up bottom levels) (* A notes tree whose fan-out directories name one tree at several prefixes expands to fanout ^ (levels + 1) notes from levels + 2 objects: at three levels, 16 notes from fan-outs of 2 and 160000 from fan-outs of 20, for ten times the input. Git writes no such tree: two directories with one tree id annotate objects whose ids share every digit below the prefix. The listing refuses it as it reads the second, having read each distinct tree once at both sizes. *) let test_shared_fanout () = let reads fanout = let store = Mem.v () in let c = shared_fanout store ~levels:3 ~fanout in store.trees <- 0; let listed = N.list_commit store c in (Result.is_error listed, store.trees) in Alcotest.(check (pair bool int)) "fan-outs of 2" (true, 4) (reads 2); Alcotest.(check (pair bool int)) "fan-outs of 20" (true, 4) (reads 20) (* A union of a notes commit the ref already holds in its history, as a pull of a peer whose notes did not move asks, holds nothing new: it reads no note, at 100 notes as at 1000. *) let test_union_held () = let reads n = let store = Mem.v () in let obj i = Git.Value.digest (Git.Value.blob (Git.Blob.of_string (string_of_int i))) in let entries = List.init n (fun i -> (obj i, Fmt.str "passed %d" i)) in let remote = match N.append_all store ~author:who ~committer:who ~ref:"refs/notes/r" entries with | Ok (Some c) -> c | Ok None | Error _ -> Alcotest.fail "the remote notes" in Hashtbl.replace store.refs "refs/notes/l" remote; (match N.append store ~author:who ~committer:who ~ref:"refs/notes/l" (obj n) "local" with | Ok _ -> () | Error (`Msg m) -> Alcotest.failf "the local note: %s" m); store.blobs <- 0; match N.union_commit store ~author:who ~committer:who ~ref:"refs/notes/l" remote with | Ok Git.Notes.Up_to_date -> store.blobs | Ok r -> Alcotest.failf "%a" Git.Notes.pp_merge_result r | Error (`Msg m) -> Alcotest.failf "the union: %s" m in Alcotest.(check int) "100 notes" 0 (reads 100); Alcotest.(check int) "1000 notes" 0 (reads 1000) (* An immutable notes commit is the snapshot, even if the live ref has moved before the reader is constructed or looked up. *) let test_reader_commit () = let store = Mem.v () in let obj = Git.Value.digest (Git.Value.blob (Git.Blob.of_string "object")) in let append line = match N.append store ~author:who ~committer:who ~ref:"refs/notes/n" obj line with | Ok c -> c | Error (`Msg m) -> Alcotest.fail m in let first = append "first" in let second = append "second" in let reader c = match N.reader_commit store c with | Ok f -> f | Error (`Msg m) -> Alcotest.fail m in let old = reader first and fresh = reader second in let content f = match Result.get_ok (f obj) with | Some blob -> ( match Mem.read store blob with | Ok (Git.Value.Blob b) -> Git.Blob.to_string b | _ -> Alcotest.fail "not a note blob") | None -> Alcotest.fail "missing note" in Alcotest.(check string) "captured commit, not current ref" "first\n" (content old); Alcotest.(check string) "later snapshot" "first\nsecond\n" (content fresh); let missing = Git.Value.digest (Git.Value.blob (Git.Blob.of_string "missing")) in let blob = Mem.write store (Git.Value.blob (Git.Blob.of_string "not notes")) in List.iter (fun h -> Alcotest.(check bool) "invalid snapshot is refused" true (Result.is_error (N.reader_commit store h))) [ missing; blob ]; let absent = Git.Value.digest (Git.Value.blob (Git.Blob.of_string "absent")) in Alcotest.(check bool) "unannotated object" true (Option.is_none (Result.get_ok (old absent))) let notes_ref = "refs/notes/guard" let object_id text = Git.Value.digest (Git.Value.blob (Git.Blob.of_string text)) (* A lookup under a fan-out directory whose tree does not read is told so, as an error of the lookup, and a lookup that reads no such directory answers: catches a reader that raises, or one that reads the unreadable directory as no note. *) let test_reader_unreadable_directory () = let store = Mem.v () in let obj = object_id "annotated" in let gone = Git.Value.digest (Git.Value.blob (Git.Blob.of_string "gone")) in let prefix = String.sub (Git.Hash.to_hex obj) 0 2 in let tree = Mem.write store (Git.Value.tree (Git.Tree.v [ Git.Tree.entry ~perm:`Dir ~name:prefix gone ])) in let read = match N.reader_commit store (commit store tree) with | Ok read -> read | Error (`Msg m) -> Alcotest.fail m in Alcotest.(check bool) "an unreadable directory is an error, not no note" true (Result.is_error (read obj)); let elsewhere = List.find (fun o -> String.sub (Git.Hash.to_hex o) 0 2 <> prefix) (List.map object_id [ "a"; "b"; "c" ]) in match read elsewhere with | Ok None -> () | Ok (Some _) -> Alcotest.fail "a note under no directory" | Error (`Msg m) -> Alcotest.failf "an object under no directory: %s" m let appended store obj line = Result.get_ok (N.append store ~author:who ~committer:who ~ref:notes_ref obj line) let observed_note store obj = Result.get_ok ((Result.get_ok (N.reader store ~ref:notes_ref)) obj) let race_on store ~before competing = Hashtbl.replace store.Mem.refs notes_ref before; store.swaps <- 0; store.race <- Some (notes_ref, competing) let changed_note store ~obj ~expected competing = (match N.append_all store ~expected:[ (obj, expected) ] ~author:who ~committer:who ~ref:notes_ref [ (obj, "ours") ] with | Error (`Msg why) -> Alcotest.(check bool) "refusal names changed note" true (Astring.String.is_infix ~affix:"changed" why) | Ok _ -> Alcotest.fail "append retried against an unvalidated changed note"); Alcotest.(check bool) "competing ref remains" true (Option.equal Git.Hash.equal (Some competing) (Hashtbl.find_opt store.Mem.refs notes_ref)); Alcotest.(check int) "retry refuses before another CAS" 1 store.swaps let test_expected_changed_note () = let store = Mem.v () in let obj = object_id "annotated" in let before = appended store obj "before" in let expected = observed_note store obj in let blob = Mem.write store (Git.Value.blob (Git.Blob.of_string "origin\000suffix")) in let tree = Mem.write store (Git.Value.tree (Git.Tree.v [ Git.Tree.entry ~perm:`Normal ~name:(Git.Hash.to_hex obj) blob ])) in let competing = commit store ~parents:[ before ] tree in race_on store ~before competing; changed_note store ~obj ~expected competing; Alcotest.(check (option string)) "opaque competitor preserved exactly" (Some "origin\000suffix") (Result.get_ok (N.find store ~ref:notes_ref obj)) let test_expected_absent_note () = let store = Mem.v () in let obj = object_id "new annotated" in let before = appended store (object_id "other") "before" in let competing = appended store obj "created concurrently" in race_on store ~before competing; changed_note store ~obj ~expected:None competing let test_expected_unrelated_note () = let store = Mem.v () in let obj = object_id "annotated" in let other = object_id "other" in let before = appended store obj "before" in let expected = observed_note store obj in let competing = appended store other "concurrent" in race_on store ~before competing; ignore (Result.get_ok (N.append_all store ~expected:[ (obj, expected) ] ~author:who ~committer:who ~ref:notes_ref [ (obj, "ours") ])); Alcotest.(check (option string)) "observed object gets its append" (Some "before\nours\n") (Result.get_ok (N.find store ~ref:notes_ref obj)); Alcotest.(check (option string)) "unrelated concurrent fact preserved" (Some "concurrent\n") (Result.get_ok (N.find store ~ref:notes_ref other)); Alcotest.(check int) "unrelated movement safely retries" 2 store.swaps let test_append_objects () = let store = Mem.v () in let obj = object_id "held publication" in let before = appended store obj "old" in store.swaps <- 0; let update = Option.get (Result.get_ok (N.append_objects store ~author:who ~committer:who ~ref:notes_ref [ (obj, "new") ])) in Alcotest.(check int) "preparation never publishes" 0 store.swaps; Alcotest.check Test_helpers.hash "actual ref remains observed" before (Hashtbl.find store.refs notes_ref); Alcotest.(check string) "exact ref name" notes_ref update.name; Alcotest.(check bool) "observed ref is guarded" true (match update.expected with | Git.Ref_transaction.Value observed -> Git.Hash.equal before observed | _ -> false); let after = match update.target with | Git.Ref_transaction.Set h -> h | _ -> Alcotest.fail "append did not propose a set" in let read = Result.get_ok (N.reader_commit store after) in let blob = Option.get (Result.get_ok (read obj)) in (match Result.get_ok (Mem.read store blob) with | Git.Value.Blob b -> Alcotest.(check string) "prepared note" "old\nnew\n" (Git.Blob.to_string b) | _ -> Alcotest.fail "prepared note is not a blob"); Alcotest.(check bool) "stale observed note refuses before publication" true (Result.is_error (N.append_objects store ~expected:[ (obj, None) ] ~author:who ~committer:who ~ref:notes_ref [ (obj, "bad") ])); Alcotest.(check int) "refused preparation never publishes" 0 store.swaps let test_append_objects_empty () = let store = Mem.v () in let update = Result.get_ok (N.append_objects store ~author:who ~committer:who ~ref:notes_ref []) in Alcotest.(check bool) "no simulated publication" true (Option.is_none update); Alcotest.(check int) "no objects for no entries" 0 (Hashtbl.length store.objects); Alcotest.(check int) "no CAS for no entries" 0 store.swaps (* Notes.reader_commit: an immutable tip names one reader and its loaded directories. Identity catches rebuilding an equally answering reader. *) let test_cached_reader () = let store = Mem.v () in let cache = Git.Notes.reader_cache () in let obj = Git.Value.digest (Git.Value.blob (Git.Blob.of_string "object")) in let append line = Result.get_ok (N.append store ~author:who ~committer:who ~ref:"refs/notes/n" obj line) in let reader c = Result.get_ok (N.reader_commit ~cache store c) in let first = append "first" in let old = reader first in let old_blob = Result.get_ok (old obj) in let again = reader first in Alcotest.(check bool) "one immutable tip keeps its reader, rather than rebuilding it" true (old == again); let second = append "second" in let fresh = reader second in Alcotest.(check bool) "a moved tip has another reader" false (old == fresh); Alcotest.(check (option string)) "the captured reader retains its first note" (Some (Git.Hash.to_hex (Git.Hash.digest_string ~kind:`Blob "first\n"))) (Option.map Git.Hash.to_hex old_blob); Alcotest.(check (option string)) "the later reader holds both lines" (Some (Git.Hash.to_hex (Git.Hash.digest_string ~kind:`Blob "first\nsecond\n"))) (Option.map Git.Hash.to_hex (Result.get_ok (fresh obj))); let invalid = Mem.write store (Git.Value.blob (Git.Blob.of_string "not notes")) in Alcotest.(check bool) "a non-commit is refused" true (Result.is_error (N.reader_commit ~cache store invalid)); Alcotest.(check bool) "a refused snapshot leaves the last successful reader kept" true (fresh == reader second); Alcotest.(check (option string)) "the old snapshot remains usable" (Option.map Git.Hash.to_hex old_blob) (Option.map Git.Hash.to_hex (Result.get_ok (old obj))) (* Git.Notes.Make.append_all adds lines in input order as append adds one. A single annotated object exercises copying the growing blob, which a fixture with one line per object would miss. *) let test_append_all_allocation () = let store = Mem.v () in let obj = object_id "receives all results" in let old_note = "previous result without a final newline" in let blob = Mem.write store (Git.Value.blob (Git.Blob.of_string old_note)) in let tree = Git.Tree.v [ Git.Tree.entry ~perm:`Normal ~name:(Git.Hash.to_hex obj) blob ] in let tip = commit store (Mem.write store (Git.Value.tree tree)) in Hashtbl.add store.refs notes_ref tip; let padding = String.make 124 'x' in let lines = List.init 1024 (fun i -> Fmt.str "%04d%s" i padding) in let entries = List.map (fun line -> (obj, line)) lines in let expected = String.concat "\n" ((old_note :: lines) @ [ "" ]) in let before = Gc.allocated_bytes () in let appended = N.append_all store ~author:who ~committer:who ~ref:notes_ref entries in let allocated = Gc.allocated_bytes () -. before in ignore (Result.get_ok appended); let actual = Result.get_ok (N.find store ~ref:notes_ref obj) in Alcotest.(check (option string)) "old bytes and every new line in order" (Some (Git.Hash.to_hex (Git.Hash.digest_string ~kind:`Blob expected))) (Option.map (fun text -> Git.Hash.to_hex (Git.Hash.digest_string ~kind:`Blob text)) actual); let budget = 8. *. float_of_int (String.length expected) in if allocated > budget then Alcotest.failf "allocated %.0f bytes for a %d-byte note (budget %.0f)" allocated (String.length expected) budget (* Git-notes(1), NOTES MERGE STRATEGIES: independent appends to one object merge with cat_sort_uniq. The base, local and remote each read their root and that object's directory, whatever the number of unchanged directories. *) let test_merge_changed_directory () = let reads directories = let store = Mem.v () in let local = "refs/notes/local" and remote = "refs/notes/remote" in let object_at slot offset = Fmt.kstr Git.Hash.of_hex "%02x%038x" slot ((2 * slot) + offset) in let entries = List.init (2 * directories) (fun i -> let slot = i / 2 * 256 / directories in (object_at slot (i mod 2), "shared")) in let base = Option.get (Result.get_ok (N.append_all store ~author:who ~committer:who ~ref:local entries)) in Hashtbl.add store.refs remote base; let obj = object_at 0 0 in let append ref line = ignore (Result.get_ok (N.append store ~author:who ~committer:who ~ref obj line)) in append local "local"; append remote "remote"; store.trees <- 0; (match Result.get_ok (N.merge store ~author:who ~committer:who ~ref:local remote) with | Git.Notes.Merged _ -> () | _ -> Alcotest.fail "the refs diverged from the shared commit"); let reads = store.trees in Alcotest.(check (option string)) "the edited note has both appends in Git order" (Some "local\nremote\nshared\n") (Result.get_ok (N.find store ~ref:local obj)); Alcotest.(check (option string)) "the note in an unchanged directory keeps its exact text" (Some "shared\n") (Result.get_ok (N.find store ~ref:local (object_at 128 1))); reads in Alcotest.(check (pair int int)) "one root and one changed directory from each tree at both fan-outs" (6, 6) (reads 32, reads 256) let suite = ( "notes", [ Alcotest.test_case "object-only append proposal" `Quick test_append_objects; Alcotest.test_case "empty object-only append" `Quick test_append_objects_empty; Alcotest.test_case "immutable commit reader" `Quick test_reader_commit; Alcotest.test_case "a reader's unreadable directory" `Quick test_reader_unreadable_directory; Alcotest.test_case "changed observed note refuses after CAS race" `Quick test_expected_changed_note; Alcotest.test_case "created observed-absent note refuses" `Quick test_expected_absent_note; Alcotest.test_case "unrelated note movement still retries" `Quick test_expected_unrelated_note; Alcotest.test_case "lines" `Quick test_lines; Alcotest.test_case "add_line" `Quick test_add_line; Alcotest.test_case "cat_sort_uniq" `Quick test_cat_sort_uniq; Alcotest.test_case "pp_merge_result" `Quick test_pp_merge_result; Alcotest.test_case "a tree shared by fan-out directories" `Quick test_shared_fanout; Alcotest.test_case "a union of notes the ref holds" `Quick test_union_held; Alcotest.test_case "an immutable notes reader is kept" `Quick test_cached_reader; Alcotest.test_case "a note batch allocates in proportion to its text" `Quick test_append_all_allocation; Alcotest.test_case "a divergent merge reads only the changed directory" `Quick test_merge_changed_directory; ] )