Skip to main content

znippy_plugin_git/
lib.rs

1//! znippy handler for **git object stores** — the `git` package format.
2//!
3//! One archive holds one git repository (D12: one `.znippy` per repo). The
4//! consumer is `gunnar`, a pure-Rust git server whose `repack()` writes the cold
5//! tier.
6//!
7//! ## The two tiers a repository can be stored as
8//!
9//! | tier | data entries | what it preserves |
10//! |---|---|---|
11//! | **objects** | one per object, named by its **oid hex**, holding its canonical bytes `"<type> <size>\0<content>"` | the oid is checkable by re-hashing the entry |
12//! | **packs** | `pack-<id>.pack` + `pack-<id>.idx` | the client's own **deflate** and every **delta chain** |
13//!
14//! The object tier is the one this format was designed around and is what the
15//! `__gunnar_*` sub-indexes describe. **The pack tier is what gunnar actually
16//! seals**, and the reason is measured: a git object in a pack is already
17//! deflated and often a delta, so storing it inflated per oid costs an OpenZL
18//! decode plus a fresh zlib deflate on every fetch, for ever, and forecloses
19//! pack-copy permanently. gunnar measured an archive of 60000 small git objects
20//! at 3.4× *larger* than its input. See [`sections::GitIndexBuilder::pack_tier`].
21//!
22//! ## What this format adds on top of a plain archive
23//!
24//! | column / module | carries |
25//! |---|---|
26//! | `object_type` | `blob` / `tree` / `commit` / `tag` for the object tier; `packfile` / `pack-index` for the pack tier — typed listing with no reads |
27//! | `object_size` | content length, so quota gates and size analytics are index-only |
28//! | `__gunnar_oid__` | an `stree` over the first 8 bytes of every oid → its lookup row |
29//! | `__gunnar_graph__` | the commit graph as Arrow: `oid, parents[], tree, committer_time, generation` |
30//! | `__gunnar_reach__` | per-commit reachability bitmaps (roaring) over object ordinals |
31//! | `__gunnar_refs__` / `__gunnar_secrets__` | the server's push logs, on **either** tier |
32//!
33//! The last three object modules are emitted for the object tier only — a pack
34//! carries its own `.idx`, which is a better oid index than `__gunnar_oid__`
35//! because it addresses pack offsets.
36//!
37//! All of these modules are **reserved** (`znippy_common::is_reserved_module`),
38//! so `znippy list`, `decompress`, the iceberg sink and the manifest readers skip
39//! them exactly as they skip the lookup and the trie.
40//!
41//! ## Laws it honours
42//!
43//! **P-1** one archive = one ecosystem (`--format git`); **P-2** it writes only
44//! the columns it declared; **P-3** it is discovered through [`meta`]; **P-4** a
45//! malformed or hostile entry never panics — `object_type` degrades to
46//! `unknown` and the archive still writes.
47//!
48//! ## Who writes the reserved sections
49//!
50//! [`GitIndexBuilder`] does, handed to `ArrowIpcSink::with_reserved_builder` by
51//! the writer that knows the object set — gunnar's `repack()`. It is deliberately
52//! **not** wired into `znippy compress --format git`: the CLI's small-file batch
53//! pass never sees objects that take the big-file path, so a CLI-built index
54//! would be silently incomplete, and a silently incomplete oid index is worse
55//! than none. `znippy compress --format git` therefore writes the two columns and
56//! no reserved sections; `znippy run git lookup|graph` reads archives that carry
57//! them.
58//!
59//! Native builtin, registered in `znippy-cli/src/handlers.rs::builtin_handlers`.
60//! Deliberately **not** a WASM plugin: the oid index's hot path is `stree`, which
61//! needs AVX2, an mmap and prefetch, none of which wasm offers.
62
63use std::collections::HashMap;
64
65use znippy_common::arrow::datatypes::{DataType, Field};
66use znippy_common::plugin::{
67    ArchiveTypePlugin, ExtensionRow, ExtensionValue, HandlerCommand, HandlerMeta,
68};
69
70/// The measured workloads behind the `znippy.git_*` benches (feature
71/// `bench-kernels`). Not linked into a shipped archiver.
72#[cfg(feature = "bench-kernels")]
73pub mod bench_kernels;
74/// The push path's archive writer: one trait, three durability contracts
75/// ([`FastWriter`](archive_write::FastWriter),
76/// [`SafeWriter`](archive_write::SafeWriter),
77/// [`UringWriter`](uring_write::UringWriter)).
78pub mod archive_write;
79pub(crate) mod archive_map;
80/// **Which implementation of each trait a store is built on.** One selector,
81/// read once at construction, never per operation — [`arms::StoreConfig`].
82pub mod arms;
83pub mod graph;
84pub mod index_layout;
85/// The shared, off-the-ack-path index builder — one indexer per account,
86/// gatling fan-out, index tables built last.
87pub mod indexer;
88pub mod memguard;
89pub mod progress;
90pub mod object;
91pub mod oid_index;
92/// Computing a git delta, for the one entry shape this engine cannot copy: a
93/// stored delta whose base falls outside the request and whose receiver holds
94/// nothing. The only place in this crate that computes one.
95pub mod delta;
96/// One pass over a pushed packfile's entries — the split the closure check
97/// falls out of. Ours, gated against gix's grammar entry for entry.
98pub mod pack_walk;
99pub mod pushlog;
100/// The read path as one stack: Ragnar `stree` in front, the Arrow index tables
101/// it points into, and the redb un-sealed tail it falls through to.
102pub mod read_stack;
103/// Pack entries to oids: the indexer's half of the split, off the ack path.
104pub mod resolve;
105/// §14's exploded objects table: resolved content, derived from the verbatim
106/// truth, built eagerly by the same indexer, droppable at any time.
107pub mod exploded;
108pub mod exploded_arrow;
109pub mod exploded_cache;
110pub use exploded_cache::{suppress_write_back, write_back_suppressed, SuppressWriteBack};
111pub mod forest;
112pub mod reach;
113pub mod refs;
114/// Store-side replication to another gunnar. **Deliberately empty** — signature
115/// and contract only, no transport.
116pub mod replicate;
117/// One repository's stored bytes in ONE FILE: [`replicate`]'s decisions with a
118/// body, and a file instead of a transport. `archive_out` / `archive_in`.
119pub mod archive_file;
120pub mod secrets;
121pub mod store;
122/// Garbage collection: one trait, two implementations
123/// ([`gc::CompactInPlace`] in place, [`gc::NewGeneration`] into a new
124/// generation — the default).
125pub mod gc;
126/// `GitOps` — the typed API gunnar calls, and the store that implements it.
127/// Base znippy never sees this trait.
128pub mod git_ops;
129/// `GitServe` — the **reading** contract: decoded reads, the `HEAD` accessor
130/// pair, negotiation and pack emission. Layered above [`git_ops`], answered out
131/// of Arrow IPC, and **containing no gix** — see the module header for why that
132/// is a rule rather than a coincidence.
133pub mod serve;
134/// **Stock `git` as the arbiter, inside a repository.** Test support only —
135/// nothing on a serving, storing or indexing path may call it, because it forks
136/// `git`. It is `pub` because `tests/concurrent_push.rs` compiles against the
137/// library, and it exists because `git index-pack --strict` *segfaults* outside
138/// a repository, which is how an oracle came to be incapable of failing.
139pub mod git_oracle;
140/// io_uring arm of [`archive_write`]. Linux only — the module is empty
141/// elsewhere rather than substituting a `pwrite` path under an io_uring name.
142pub mod uring_write;
143pub mod sections;
144#[cfg(test)]
145mod thin_storm;
146/// **The corpus the tests run on, generated rather than found.** Test support
147/// only, and compiled only under `cfg(test)`: it exists because the fixture
148/// used to be whichever repository `read_dir` handed back first on one
149/// developer's box. See the module header for the eight guards that measured.
150#[cfg(test)]
151pub(crate) mod pack_fixture;
152
153pub use archive_write::{ArchiveWrite, Faults, FastWriter, SafeWriter};
154pub use arms::{
155    ALL_ENV, DEFAULT_REDB_CACHE_BYTES, ENV_BOUNDARY_DELTA, ENV_EMIT_WORKERS, ENV_EXPLODE, ENV_GC,
156    ENV_BASE_BUDGET_BYTES, ENV_INDEX, ENV_INDEX_BATCH_ROWS, ENV_MEM_BUDGET_BYTES, ENV_MEM_BUDGET_PCT,
157    ENV_MEMINFO, ENV_REACH_COMMITS, ENV_REDB_CACHE, ENV_WRITER, GcArm, IndexArm, StoreConfig,
158    WriterArm, env_reads, env_reads_here, redb_cache_bytes, set_graph_cache_default, ENV_GRAPH_CACHE,
159};
160pub use indexer::{AccountIndexer, IndexJob, IndexRow, IndexerPool, Lookup, PushPath};
161#[cfg(target_os = "linux")]
162pub use uring_write::UringWriter;
163
164pub use graph::{CommitNode, decode_graph, graph_schema, read_graph};
165pub use object::{
166    GitHashKind, GitObject, GitObjectKind, PACKFILE_TYPE, PACK_INDEX_TYPE, PackFileKind, canonical,
167    is_oid_path, pack_path_kind, parse_canonical, parse_commit, tree_entries,
168};
169pub use oid_index::{GitOidIndex, OidEntry, OidHit, OidLayout, key_for_oid};
170pub use pushlog::{
171    CompactionPolicy, CompactionReport, Finish, PushLog, PushLogScan, scan_frames,
172};
173pub use reach::{ReachEntry, ReachPolicy, decode_reach, read_reach, reach_schema};
174pub use refs::{RefLog, RefState, RefUpdate, read_refs, refs_schema};
175pub use secrets::{SecretState, SecretUpdate, SecretsLog, read_secrets, secrets_schema};
176pub use sections::GitIndexBuilder;
177pub use git_ops::{
178    GitOps, GitStore, LookupPath, Oid, RefRow, SelectedStore, Stored, TxId, lookup_path,
179    open_from_env, open_selected,
180};
181pub use serve::{Caps, GitServe, PackStats, ReachSet, HEAD};
182/// The typed ref rejection, re-exported so a consumer of this crate reaches it
183/// without also naming the contract crate. `RefRejection::of(&err)` is the only
184/// sanctioned way to ask whether a ref write lost a race — never a message.
185pub use git_storage_trait::{Observed, RefCas, RefRejection, RefTarget};
186
187/// DenseUnion / `pkg_type` discriminant. Clear of the built-ins (1–25), media
188/// (25), skidbladnir (40) and rust-toolchain (41).
189pub const GIT_TYPE_ID: i8 = 42;
190
191/// `object_type` written when the entry is not parseable as a canonical git
192/// object. A distinct, queryable state — never a silent `blob`.
193pub const UNKNOWN_OBJECT_TYPE: &str = "unknown";
194
195/// Native git-object handler.
196pub struct NativeGitPlugin;
197
198impl NativeGitPlugin {
199    pub fn new() -> Self {
200        NativeGitPlugin
201    }
202}
203
204impl Default for NativeGitPlugin {
205    fn default() -> Self {
206        Self::new()
207    }
208}
209
210impl ArchiveTypePlugin for NativeGitPlugin {
211    fn name(&self) -> &str {
212        "git"
213    }
214
215    fn type_id(&self) -> i8 {
216        GIT_TYPE_ID
217    }
218
219    fn meta(&self) -> HandlerMeta {
220        HandlerMeta {
221            name: "git".into(),
222            aliases: vec!["gunnar".into(), "git-objects".into()],
223            type_id: GIT_TYPE_ID,
224            ecosystem: "Git object store (gunnar cold tier — one archive per repository)".into(),
225            // Left empty on purpose, and it is not an oversight. A loose git
226            // object carries no extension at all — its name IS its oid — and
227            // the pack entries this handler also claims are matched on their
228            // whole `pack-<oid>.<ext>` shape, not on a suffix. An extension
229            // list here would claim every `.pack` and `.idx` in any archive,
230            // which is wider than the truth. `matches_path` is the authority.
231            extensions: Vec::new(),
232            description: "Stores a git repository: either canonical objects keyed by oid hex, \
233                          with the reserved __gunnar_oid__ (stree) / __gunnar_graph__ (commit \
234                          graph) / __gunnar_reach__ (reachability bitmaps) sub-indexes, or the \
235                          pack tier (pack-<id>.pack / .idx) that preserves the client's deflate \
236                          and its delta chains"
237                .into(),
238            commands: vec![
239                HandlerCommand::new(
240                    "inspect",
241                    "Print type/size/sha1/sha256 for a file of canonical git object bytes",
242                ),
243                HandlerCommand::new(
244                    "lookup",
245                    "Resolve an oid against an archive's __gunnar_oid__ index: `git lookup <archive> <oid>`",
246                ),
247                HandlerCommand::new(
248                    "graph",
249                    "Print an archive's commit graph (oid, generation, time, parents)",
250                ),
251                HandlerCommand::new(
252                    "refs",
253                    "Print a live store's ref namespace: `git refs <store-root>`",
254                ),
255            ],
256        }
257    }
258
259    /// **CLI-only string dispatch** (§13.3). A server never comes through here:
260    /// it holds a [`GitStore`] and calls [`GitOps`] directly, typed.
261    ///
262    /// `refs` is what that delegation looks like — open the store, call the trait
263    /// method, print what it returned, and carry no logic of its own. The three
264    /// commands beside it are older and are **archive inspection**, not store
265    /// operations: they read a *sealed* archive's sections, which is a different
266    /// thing from a live store and is deliberately not modelled as a `GitOps`
267    /// call. They are left as they are rather than bent through a trait that does
268    /// not describe them.
269    fn run_command(&self, cmd: &str, args: &[String]) -> anyhow::Result<()> {
270        match cmd {
271            "refs" => {
272                let root = args
273                    .first()
274                    .ok_or_else(|| anyhow::anyhow!("usage: git refs <store-root>"))?;
275                // Everything below this line is printing. The answer comes from
276                // the trait.
277                let store = GitStore::open(std::path::Path::new(root), "cli")?;
278                for r in store.refs()? {
279                    println!(
280                        "{}\t{}{}",
281                        r.name,
282                        r.oid.as_deref().map(hex::encode).unwrap_or_else(|| "-".into()),
283                        match (&r.peeled, &r.symref_target) {
284                            (Some(p), _) => format!("\t^{}", hex::encode(p)),
285                            (None, Some(t)) => format!("\t-> {t}"),
286                            (None, None) => String::new(),
287                        }
288                    );
289                }
290                Ok(())
291            }
292            "inspect" => {
293                let path = args
294                    .first()
295                    .ok_or_else(|| anyhow::anyhow!("usage: git inspect <object-file>"))?;
296                let data = std::fs::read(path)?;
297                match parse_canonical(&data) {
298                    Some(obj) => {
299                        println!("type:   {}", obj.kind.as_str());
300                        println!("size:   {}", obj.payload.len());
301                        println!("sha1:   {}", GitHashKind::Sha1.oid_hex_of(&data));
302                        println!("sha256: {}", GitHashKind::Sha256.oid_hex_of(&data));
303                        Ok(())
304                    }
305                    None => anyhow::bail!(
306                        "'{path}' is not canonical git object bytes (`<type> <size>\\0<content>`)"
307                    ),
308                }
309            }
310            "lookup" => {
311                let (archive, oid) = match (args.first(), args.get(1)) {
312                    (Some(a), Some(o)) => (a, o),
313                    _ => anyhow::bail!("usage: git lookup <archive> <oid-hex>"),
314                };
315                let index = GitOidIndex::open(std::path::Path::new(archive))?.ok_or_else(|| {
316                    anyhow::anyhow!("'{archive}' carries no __gunnar_oid__ index")
317                })?;
318                match index.lookup_hex(oid) {
319                    Some(hit) => {
320                        println!("oid:        {oid}");
321                        println!("lookup_row: {}", hit.lookup_row);
322                        println!("ordinal:    {}", hit.ordinal);
323                        Ok(())
324                    }
325                    None => anyhow::bail!("oid '{oid}' is not in '{archive}'"),
326                }
327            }
328            "graph" => {
329                let archive = args
330                    .first()
331                    .ok_or_else(|| anyhow::anyhow!("usage: git graph <archive>"))?;
332                let nodes = read_graph(std::path::Path::new(archive))?.ok_or_else(|| {
333                    anyhow::anyhow!("'{archive}' carries no __gunnar_graph__ section")
334                })?;
335                println!("commits: {}", nodes.len());
336                for n in &nodes {
337                    println!(
338                        "  {} gen={} time={} parents=[{}]",
339                        n.oid,
340                        n.generation,
341                        n.committer_time.map(|t| t.to_string()).unwrap_or_else(|| "-".into()),
342                        n.parents.join(" ")
343                    );
344                }
345                Ok(())
346            }
347            other => anyhow::bail!("git: unknown subcommand '{other}'"),
348        }
349    }
350
351    /// A git archive's entries are either **oids** — the whole `relative_path`
352    /// is 40 or 64 lowercase hex characters — or the **packs** of a repository's
353    /// cold tier, `pack-<id>.pack` / `pack-<id>.idx`.
354    ///
355    /// Both are the same ecosystem and so belong to one handler (P-1). Which of
356    /// the two an archive holds is not a variant of the format: it is what the
357    /// writer had. gunnar's `repack()` produces a consolidated pack and seals
358    /// that, because a pack preserves the pushing client's own deflate and its
359    /// delta chains, and an inflated per-oid tier destroys both permanently.
360    fn matches_path(&self, path: &str) -> bool {
361        is_oid_path(path) || pack_path_kind(path).is_some()
362    }
363
364    fn schema_fields(&self) -> Vec<Field> {
365        vec![
366            Field::new("object_type", DataType::Utf8, true),
367            // UInt32: the index's extension-column writer materialises UInt32 and
368            // Utf8 only. A git object larger than 4 GiB saturates here; its exact
369            // byte length is always available from the base `uncompressed_size`
370            // column, which is u64 and is the authority.
371            Field::new("object_size", DataType::UInt32, true),
372        ]
373    }
374
375    fn extract_metadata(&self, path: &str, data: &[u8]) -> Option<ExtensionRow> {
376        if !self.matches_path(path) {
377            return None;
378        }
379        let mut f: HashMap<String, ExtensionValue> = HashMap::new();
380
381        // A pack is typed by its magic, never by its name. A name is a claim
382        // the writer made; the magic is what the bytes are. `pack-<hex>.pack`
383        // over something that is not a packfile degrades to `unknown` exactly
384        // as malformed object bytes do (P-4) — a wrong type in the index is
385        // worse than an honest absence, because it is queried and believed.
386        if let Some(kind) = pack_path_kind(path) {
387            let typed = if data.starts_with(kind.magic()) {
388                kind.as_str()
389            } else {
390                UNKNOWN_OBJECT_TYPE
391            };
392            f.insert("object_type".into(), ExtensionValue::Str(typed.into()));
393            f.insert(
394                "object_size".into(),
395                ExtensionValue::U32(data.len().min(u32::MAX as usize) as u32),
396            );
397            return Some(ExtensionRow { fields: f });
398        }
399
400        match parse_canonical(data) {
401            Some(obj) => {
402                f.insert("object_type".into(), ExtensionValue::Str(obj.kind.as_str().into()));
403                f.insert(
404                    "object_size".into(),
405                    ExtensionValue::U32(obj.payload.len().min(u32::MAX as usize) as u32),
406                );
407            }
408            None => {
409                // P-4: a decompress bomb, a truncated object or plain garbage
410                // still writes a row — typed `unknown`, sized by what is there.
411                f.insert(
412                    "object_type".into(),
413                    ExtensionValue::Str(UNKNOWN_OBJECT_TYPE.into()),
414                );
415                f.insert(
416                    "object_size".into(),
417                    ExtensionValue::U32(data.len().min(u32::MAX as usize) as u32),
418                );
419            }
420        }
421        Some(ExtensionRow { fields: f })
422    }
423}
424
425#[cfg(test)]
426mod tests {
427    use super::*;
428    use crate::object::canonical;
429
430    fn get<'a>(row: &'a ExtensionRow, k: &str) -> Option<&'a ExtensionValue> {
431        row.fields.get(k)
432    }
433
434    #[test]
435    fn claims_oid_paths_and_nothing_else() {
436        let p = NativeGitPlugin::new();
437        assert!(p.matches_path(&"a1b2c3d4".repeat(5)));       // 40 hex
438        assert!(p.matches_path(&"0f".repeat(32)));            // 64 hex
439        assert!(!p.matches_path("refs/heads/main"));
440        assert!(!p.matches_path("objects/pack/pack-abc.pack"));
441        assert!(!p.matches_path(&"A1B2C3D4".repeat(5)));
442    }
443
444    /// The pack tier's two file names are claimed, and only in the shape git
445    /// itself writes. A bare `.pack` suffix is not enough: an archive of
446    /// arbitrary files must not have its entries retyped as git packs.
447    #[test]
448    fn claims_the_pack_tier_by_its_whole_name_not_by_a_suffix() {
449        let p = NativeGitPlugin::new();
450        let id40 = "a1b2c3d4".repeat(5);
451        let id64 = "0f".repeat(32);
452        assert_eq!(pack_path_kind(&format!("pack-{id40}.pack")), Some(PackFileKind::Data));
453        assert_eq!(pack_path_kind(&format!("pack-{id64}.idx")), Some(PackFileKind::Index));
454        assert!(p.matches_path(&format!("pack-{id64}.pack")));
455        assert!(p.matches_path(&format!("objects/pack/pack-{id40}.idx")));
456
457        for not_ours in [
458            "pack-nothex.pack",
459            "somefile.pack",
460            "pack-.pack",
461            &format!("pack-{id40}.bitmap"),
462            &format!("pack-{}.pack", "A1B2C3D4".repeat(5)),
463            &format!("{id40}.pack"),
464        ] {
465            assert_eq!(pack_path_kind(not_ours), None, "wrongly claimed {not_ours}");
466        }
467        assert!(!p.matches_path("somefile.pack"));
468    }
469
470    /// A pack is typed by its **magic**, never by the name the writer chose.
471    /// A file called `pack-….pack` that does not start with `PACK` is
472    /// `unknown` — the same honest state malformed object bytes get (P-4).
473    #[test]
474    fn a_pack_is_typed_by_its_magic_and_a_liar_is_unknown() {
475        let p = NativeGitPlugin::new();
476        let id = "0f".repeat(32);
477
478        let mut pack = b"PACK".to_vec();
479        pack.extend_from_slice(&2u32.to_be_bytes());
480        pack.extend_from_slice(&7u32.to_be_bytes());
481        let row = p.extract_metadata(&format!("pack-{id}.pack"), &pack).unwrap();
482        assert_eq!(get(&row, "object_type"), Some(&ExtensionValue::Str(PACKFILE_TYPE.into())));
483        assert_eq!(get(&row, "object_size"), Some(&ExtensionValue::U32(pack.len() as u32)));
484
485        let idx = b"\xfftOc\x00\x00\x00\x02".to_vec();
486        let row = p.extract_metadata(&format!("pack-{id}.idx"), &idx).unwrap();
487        assert_eq!(get(&row, "object_type"), Some(&ExtensionValue::Str(PACK_INDEX_TYPE.into())));
488
489        // Now the liars. Each is named as a pack and is not one.
490        for (name, bytes) in [
491            (format!("pack-{id}.pack"), &b"NOTAPACK"[..]),
492            (format!("pack-{id}.idx"), &b"PACK\0\0\0\x02"[..]),
493            (format!("pack-{id}.pack"), &b""[..]),
494        ] {
495            let row = p.extract_metadata(&name, bytes).expect("a claimed path always yields a row");
496            assert_eq!(
497                get(&row, "object_type"),
498                Some(&ExtensionValue::Str(UNKNOWN_OBJECT_TYPE.into())),
499                "{name} carries {bytes:?}, which is not that kind of file — it must not be typed \
500                 from its name"
501            );
502        }
503    }
504
505    #[test]
506    fn types_and_sizes_come_from_the_stored_bytes() {
507        let p = NativeGitPlugin::new();
508        let body = b"hello world";
509        let bytes = canonical(GitObjectKind::Blob, body);
510        let oid = GitHashKind::Sha256.oid_hex_of(&bytes);
511        let row = p.extract_metadata(&oid, &bytes).unwrap();
512        assert_eq!(get(&row, "object_type"), Some(&ExtensionValue::Str("blob".into())));
513        assert_eq!(get(&row, "object_size"), Some(&ExtensionValue::U32(body.len() as u32)));
514
515        let commit = canonical(GitObjectKind::Commit, b"tree x\n\nmsg\n");
516        let coid = GitHashKind::Sha1.oid_hex_of(&commit);
517        let crow = p.extract_metadata(&coid, &commit).unwrap();
518        assert_eq!(get(&crow, "object_type"), Some(&ExtensionValue::Str("commit".into())));
519    }
520
521    #[test]
522    fn garbage_degrades_to_unknown_and_never_panics() {
523        let p = NativeGitPlugin::new();
524        let oid = "d".repeat(64);
525        for bad in [&b""[..], &b"\0\0\0"[..], &[0xffu8; 4096][..], &b"blob 99\0short"[..]] {
526            let row = p.extract_metadata(&oid, bad).expect("a claimed path always yields a row");
527            assert_eq!(
528                get(&row, "object_type"),
529                Some(&ExtensionValue::Str(UNKNOWN_OBJECT_TYPE.into())),
530                "unparseable bytes must be typed `unknown`, never guessed"
531            );
532            assert_eq!(get(&row, "object_size"), Some(&ExtensionValue::U32(bad.len() as u32)));
533        }
534    }
535
536    #[test]
537    fn a_path_that_is_not_an_oid_yields_no_row() {
538        let p = NativeGitPlugin::new();
539        assert!(p.extract_metadata("HEAD", b"ref: refs/heads/main\n").is_none());
540    }
541
542    #[test]
543    fn meta_is_the_discovery_record() {
544        let m = NativeGitPlugin::new().meta();
545        assert_eq!(m.name, "git");
546        assert_eq!(m.type_id, GIT_TYPE_ID);
547        assert!(m.aliases.contains(&"gunnar".to_string()));
548        assert_eq!(m.commands.len(), 4);
549        assert!(
550            m.commands.iter().any(|c| c.name == "refs"),
551            "the GitOps-delegating command is not advertised"
552        );
553    }
554}