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