Skip to main content

znippy_plugin_git/
git_oracle.rs

1//! **Stock `git` as the arbiter for a pack this crate emitted β€” inside a
2//! repository, and never as a segfault mistaken for a verdict.**
3//!
4//! # πŸ”΄ Why this module exists at all
5//!
6//! `git index-pack --strict` **crashes with SIGSEGV** when it is run outside a
7//! git repository and its strictness has anything to say. Measured on oden with
8//! git 2.53.0, 2026-08-11:
9//!
10//! ```text
11//! pack holding one tree whose blob is absent
12//!   in a bare repo   β†’ exit 128  fatal: did not receive expected object ce013625…
13//!   outside a repo   β†’ exit 139  (SIGSEGV, and NOT ONE BYTE of output)
14//! ```
15//!
16//! It is not specific to `--check-self-contained-and-connected`; plain
17//! `--strict` does it too, because both reach the same `fsck_walk` and it needs
18//! a repository under it. The pack has to be *rejectable* for the crash to
19//! happen β€” a good pack indexes fine outside a repo β€” so the failure appears
20//! **only when the oracle was about to be useful.**
21//!
22//! That is not a hypothetical. It is why the bug `8c2679d` fixed shipped: the
23//! subset test in [`crate::store`] ran the oracle in a plain temporary directory,
24//! hit the crash, and was *narrowed to three objects until it stopped crashing*
25//! β€” the comment on that line read `// see the ignore note: larger subsets
26//! segfault git`. With three objects there was no tree naming an absent child,
27//! the oracle had nothing to say, and a narrowed clone shipped broken for four
28//! sessions. **A test whose oracle segfaults is a test that cannot fail**, and
29//! the reflex that shrinks the input until the crash goes away removes the
30//! coverage rather than the crash.
31//!
32//! So every call goes through here, and here does two things nothing did before:
33//! it runs git **inside a freshly initialised bare repository**, and it treats a
34//! **death by signal as an oracle failure in its own right** rather than as a
35//! non-zero exit code with an empty message.
36//!
37//! # Not a production path
38//!
39//! Nothing in this crate's serving, storing or indexing paths calls any of this,
40//! and nothing may: it forks `git`. It is `pub` only because
41//! `tests/concurrent_push.rs` is an integration test and compiles against the
42//! library rather than into it, and one shared oracle beats four copies of the
43//! same twenty lines (LAW 5). The caller supplies the scratch directory, so this
44//! needs no `tempfile` and stays out of the dependency graph.
45
46use std::path::{Path, PathBuf};
47use std::process::{Command, Output};
48
49use anyhow::{anyhow, bail, Context, Result};
50
51/// How hard git should look at the pack.
52#[derive(Debug, Clone, Copy, PartialEq, Eq)]
53pub enum Strictness {
54    /// Plain `index-pack`: **every delta in the pack resolves inside it**, and
55    /// nothing else. The honest question to ask of a set that is not
56    /// reachability-closed β€” an arbitrary subset's tree will name a blob the
57    /// subset does not carry, and a connectivity walk would then be judging the
58    /// *caller's selection* rather than this crate's emitter.
59    SelfContained,
60    /// `--strict --check-self-contained-and-connected`: what `git clone` itself
61    /// runs. Every received object's links are walked and each one demanded, so
62    /// this is the arbiter for a request that **is** closed β€” a clone, a fetch,
63    /// or a whole repository.
64    Connected,
65}
66
67impl Strictness {
68    fn args(self) -> &'static [&'static str] {
69        match self {
70            Strictness::SelfContained => &["index-pack"],
71            Strictness::Connected => &[
72                "index-pack",
73                "--strict",
74                "--check-self-contained-and-connected",
75            ],
76        }
77    }
78}
79
80/// A freshly initialised **bare repository** under `scratch`, named `name`.
81///
82/// Fresh and empty on purpose: a connectivity verdict is only about the pack if
83/// the repository brings no objects of its own to satisfy a link with.
84pub fn empty_bare_repo(scratch: &Path, name: &str) -> Result<PathBuf> {
85    let repo = scratch.join(name);
86    let out = Command::new("git")
87        .args(["init", "-q", "--bare"])
88        .arg(&repo)
89        .output()
90        .context("running `git init --bare` for the oracle's repository")?;
91    verdict(&out, "git init --bare")?;
92    Ok(repo)
93}
94
95/// **Hand `pack` to stock git, inside a repository, and return its verdict.**
96///
97/// `Ok(())` means git accepted it. `Err` names why, and β€” the part this module
98/// exists for β€” an oracle that *crashed* is an `Err` that says so, instead of an
99/// exit code nobody looks at behind an empty stderr.
100pub fn git_accepts(scratch: &Path, name: &str, pack: &[u8], how: Strictness) -> Result<()> {
101    let repo = empty_bare_repo(scratch, name)?;
102    let path = repo.join("oracle.pack");
103    std::fs::write(&path, pack)
104        .with_context(|| format!("writing the pack under test to {}", path.display()))?;
105    let out = Command::new("git")
106        .args(how.args())
107        .arg(&path)
108        .current_dir(&repo)
109        .output()
110        .context("running `git index-pack` as the oracle")?;
111    verdict(&out, "git index-pack")
112        .with_context(|| format!("{how:?}, in the repository at {}", repo.display()))
113}
114
115/// **The `.idx` stock git writes for this pack.**
116///
117/// `index-pack` computes an oid for every entry β€” deltas resolved β€” and files
118/// it with the offset it found it at. That file is the only independent
119/// statement of "what git thinks is in this pack" available without a
120/// repository that already has one, so it is the arbiter
121/// [`crate::resolve`]'s oid guard needs for a pack the test itself built.
122///
123/// Until 2026-08-25 that guard could only find such a pair by scanning
124/// `/home/rickard/git` for a repository that happened to have both, which made
125/// its corpus the developer's disk and made it fail outright on a fresh clone.
126/// A generated pack has no `.idx` of its own; this is where one comes from.
127pub fn git_idx_for(scratch: &Path, name: &str, pack: &[u8]) -> Result<Vec<u8>> {
128    let repo = empty_bare_repo(scratch, name)?;
129    let path = repo.join("oracle.pack");
130    std::fs::write(&path, pack)
131        .with_context(|| format!("writing the pack to be indexed to {}", path.display()))?;
132    let out = Command::new("git")
133        .args(["index-pack", "--strict"])
134        .arg(&path)
135        .current_dir(&repo)
136        .output()
137        .context("running `git index-pack` to obtain an .idx")?;
138    verdict(&out, "git index-pack")?;
139    let idx = path.with_extension("idx");
140    std::fs::read(&idx).with_context(|| format!("reading the .idx git wrote at {}", idx.display()))
141}
142
143/// The same, as an assertion, because that is what a test wants.
144///
145/// `#[track_caller]` so the panic points at the test rather than at this line.
146#[track_caller]
147pub fn assert_git_accepts(scratch: &Path, name: &str, pack: &[u8], how: Strictness) {
148    if let Err(e) = git_accepts(scratch, name, pack, how) {
149        panic!("stock git refused a pack this crate emitted: {e:#}");
150    }
151}
152
153/// **What stock git reads back out of a pack this crate emitted**: every object
154/// in it, by oid, as `(kind, bytes)`.
155///
156/// `git_accepts` proves a pack is *well formed and connected*. It cannot prove
157/// the bytes are the **right** bytes, and that is precisely the failure mode a
158/// computed delta introduces: a wrong copy offset produces a pack `index-pack`
159/// indexes happily, because the oid it files the entry under is the one it
160/// computed from the entry's own content. Only reading the content back and
161/// comparing it against what the store holds can see it β€” `P-001`, applied
162/// output rather than a state round-trip.
163///
164/// The pack goes in through `index-pack --stdin`, which lands it in the
165/// repository's `objects/pack` where `cat-file` can reach it;
166/// [`git_accepts`] deliberately does not, because a verdict must not depend on
167/// the repository having adopted the objects.
168pub fn git_reads_back(scratch: &Path, name: &str, pack: &[u8]) -> Result<Vec<(String, Vec<u8>)>> {
169    use std::io::Write as _;
170
171    let repo = empty_bare_repo(scratch, name)?;
172    let mut child = Command::new("git")
173        .args(["index-pack", "--stdin"])
174        .current_dir(&repo)
175        .stdin(std::process::Stdio::piped())
176        .stdout(std::process::Stdio::piped())
177        .stderr(std::process::Stdio::piped())
178        .spawn()
179        .context("spawning `git index-pack --stdin` to adopt the pack")?;
180    child
181        .stdin
182        .take()
183        .ok_or_else(|| anyhow!("git index-pack --stdin has no stdin"))?
184        .write_all(pack)
185        .context("streaming the pack to `git index-pack --stdin`")?;
186    let out = child
187        .wait_with_output()
188        .context("waiting for `git index-pack --stdin`")?;
189    verdict(&out, "git index-pack --stdin")?;
190
191    let listed = Command::new("git")
192        .args(["cat-file", "--batch-all-objects", "--batch"])
193        .current_dir(&repo)
194        .output()
195        .context("running `git cat-file --batch-all-objects --batch`")?;
196    verdict(&listed, "git cat-file --batch")?;
197
198    // `<oid> <type> <size>\n<size bytes>\n`, repeated.
199    let buf = listed.stdout;
200    let mut at = 0usize;
201    let mut objects = Vec::new();
202    while at < buf.len() {
203        let nl = buf[at..]
204            .iter()
205            .position(|b| *b == b'\n')
206            .ok_or_else(|| anyhow!("a cat-file record has no header terminator"))?
207            + at;
208        let header = std::str::from_utf8(&buf[at..nl]).context("a cat-file header is not utf-8")?;
209        let mut f = header.split_whitespace();
210        let oid = f
211            .next()
212            .ok_or_else(|| anyhow!("a cat-file header has no oid: {header:?}"))?
213            .to_owned();
214        let size: usize = f
215            .nth(1)
216            .ok_or_else(|| anyhow!("a cat-file header has no size: {header:?}"))?
217            .parse()
218            .with_context(|| format!("a cat-file size is not a number: {header:?}"))?;
219        let from = nl + 1;
220        let to = from
221            .checked_add(size)
222            .filter(|to| *to <= buf.len())
223            .ok_or_else(|| anyhow!("a cat-file body of {size} bytes runs off the output"))?;
224        objects.push((oid, buf[from..to].to_vec()));
225        at = to + 1;
226    }
227    Ok(objects)
228}
229
230/// Turn a finished child into a verdict, **refusing to read a crash as a
231/// judgement**.
232///
233/// A process killed by a signal has `ExitStatus::code() == None` on unix, and
234/// that is the case that has to be named rather than folded into "non-zero":
235/// `assert!(status.success())` is technically false for a SIGSEGV, but it prints
236/// an empty stderr and a `None` code, which reads exactly like a tool that
237/// declined to explain itself β€” and the documented response to it in this
238/// repository was to shrink the input until it stopped.
239fn verdict(out: &Output, what: &str) -> Result<()> {
240    #[cfg(unix)]
241    {
242        use std::os::unix::process::ExitStatusExt as _;
243        if let Some(signal) = out.status.signal() {
244            bail!(
245                "`{what}` DIED ON SIGNAL {signal} instead of judging the pack. That is the \
246                 oracle crashing, not the pack failing, and the two must never be confused: \
247                 outside a repository git 2.53.0 segfaults on any pack `--strict` would have \
248                 rejected, so a green here would have meant nothing. Do NOT make this go away \
249                 by shrinking the input.\nstderr: {}",
250                String::from_utf8_lossy(&out.stderr).trim()
251            );
252        }
253    }
254    if !out.status.success() {
255        return Err(anyhow!(
256            "`{what}` exited {:?}\nstderr: {}\nstdout: {}",
257            out.status.code(),
258            String::from_utf8_lossy(&out.stderr).trim(),
259            String::from_utf8_lossy(&out.stdout).trim()
260        ));
261    }
262    Ok(())
263}
264
265#[cfg(test)]
266mod tests {
267    use super::*;
268    use crate::object::{canonical, GitHashKind, GitObjectKind};
269    use crate::pack_walk::{emit_pack, EmitEntry};
270    use crate::store::tests::tmpdir;
271
272    /// One pack holding exactly `bodies`, every entry whole, with a real
273    /// trailer β€” `emit_pack` computes it, which is why this does not hand-roll
274    /// one.
275    fn whole_pack(bodies: &[(GitObjectKind, Vec<u8>)]) -> Vec<u8> {
276        use std::io::Write as _;
277        let hash = GitHashKind::Sha1;
278        let entries: Vec<EmitEntry> = bodies
279            .iter()
280            .enumerate()
281            .map(|(i, (kind, body))| {
282                let t = crate::serve::resolved_type(*kind);
283                let mut stored = Vec::new();
284                crate::pack_walk::encode_type_and_size(&mut stored, t, body.len() as u64);
285                let mut z =
286                    flate2::write::ZlibEncoder::new(Vec::new(), flate2::Compression::fast());
287                z.write_all(body).unwrap();
288                stored.extend_from_slice(&z.finish().unwrap());
289                EmitEntry {
290                    oid: hash.oid_of(&canonical(*kind, body)),
291                    // Hand-built bytes that no archive holds β€” the
292                    // `EntryBytes::Owned` exception, in its test shape.
293                    stored: crate::pack_walk::EntryBytes::Owned(stored),
294                    obj_type: t,
295                    uncompressed_size: body.len() as u64,
296                    delta_base: 0,
297                    offset: i as u64 + 1,
298                    recompressed: false,
299                    deltified: false,
300                }
301            })
302            .collect();
303        let mut out = Vec::new();
304        emit_pack(&entries, hash, &mut out, &|i| {
305            crate::pack_walk::resolve_against(&entries[i], &[])
306        })
307        .expect("emitting the fixture pack");
308        out
309    }
310
311    /// πŸ”΄ **The oracle can FAIL, and it fails with a sentence rather than a
312    /// signal.**
313    ///
314    /// The pack is one tree naming a blob that is not in it β€” the exact shape
315    /// that broke a narrowed clone in production, and the exact shape that
316    /// segfaults `git index-pack --strict` outside a repository.
317    ///
318    /// Three assertions, and the third is the one this module was written for:
319    /// [`Strictness::Connected`] must **reject** it; the rejection must name the
320    /// missing object; and it must **not** be a signal death, because a signal
321    /// death is the oracle crashing rather than the pack failing, and the
322    /// documented reflex to it was to shrink the input until it stopped.
323    #[test]
324    fn the_oracle_rejects_a_pack_whose_tree_owes_a_child_and_does_not_crash_doing_it() {
325        let hash = GitHashKind::Sha1;
326        let orphan = b"a blob that is deliberately left out of the pack\n".to_vec();
327        let orphan_oid = hash.oid_of(&canonical(GitObjectKind::Blob, &orphan));
328        let mut tree = b"100644 f.txt\0".to_vec();
329        tree.extend_from_slice(&orphan_oid);
330
331        let scratch = tmpdir("oracle-red");
332        let pack = whole_pack(&[(GitObjectKind::Tree, tree.clone())]);
333
334        let err = git_accepts(&scratch, "red.git", &pack, Strictness::Connected)
335            .expect_err("a tree whose child is absent must be refused");
336        let msg = format!("{err:#}");
337        assert!(
338            msg.contains(&hex::encode(&orphan_oid)),
339            "the refusal must name the object the pack owes; got: {msg}"
340        );
341        assert!(
342            !msg.contains("DIED ON SIGNAL"),
343            "the oracle crashed instead of judging β€” it is not running inside a repository: \
344             {msg}"
345        );
346
347        // …and the same pack is fine when nothing is asking about connectivity:
348        // every delta in it resolves inside it, because there are no deltas.
349        // Without this the test could not tell a working oracle from one that
350        // rejects everything.
351        git_accepts(&scratch, "green.git", &pack, Strictness::SelfContained)
352            .expect("a self-containment check has nothing to complain about here");
353
354        // The premise, stated last because it is the one that would make the
355        // whole module pointless if it stopped being true: **outside** a
356        // repository this same command dies on a signal with no output at all.
357        let bare_dir = scratch.join("not-a-repo");
358        std::fs::create_dir_all(&bare_dir).unwrap();
359        let path = bare_dir.join("oracle.pack");
360        std::fs::write(&path, &pack).unwrap();
361        let out = Command::new("git")
362            .args(Strictness::Connected.args())
363            .arg(&path)
364            .current_dir(&bare_dir)
365            .output()
366            .expect("running git index-pack outside a repository");
367        let outside = verdict(&out, "git index-pack")
368            .expect_err("outside a repository this cannot possibly succeed");
369        assert!(
370            format!("{outside:#}").contains("DIED ON SIGNAL"),
371            "git stopped segfaulting outside a repository β€” this module's premise has changed \
372             and its docs must be re-measured, not deleted. It said: {outside:#}"
373        );
374    }
375}