znippy_plugin_git/archive_write.rs
1//! The push path's **archive writer**: one trait, three durability contracts.
2//!
3//! A git client pushes a packfile. Its bytes are already zlib-deflated and often
4//! delta-encoded, so they go into the znippy Apache Arrow IPC archive
5//! **verbatim** — never re-compressed, never re-encoded (the reason is measured
6//! in this crate's own module docs: re-inflating per oid cost 3.4× the input on
7//! 60 000 objects). What *does* vary is how much durability the server buys
8//! before it sends the client its ack, and that is the only axis this module
9//! exposes.
10//!
11//! The index tables are **not** built here. [`append`](ArchiveWrite::append)
12//! returns a byte extent; the extent goes over a channel to the per-account
13//! indexer in [`crate::indexer`], which builds the Arrow index tables *after*
14//! the bytes are down. See that module for why a read arriving before the index
15//! is ready still cannot be wrong.
16//!
17//! # The three arms, and what each one actually promises
18//!
19//! | impl | on return, the bytes are… | a crash right after return |
20//! |---|---|---|
21//! | [`FastWriter`] | in the **page cache** | **loses them** |
22//! | [`SafeWriter`] | on the platter, and a journal row points at them | keeps them |
23//! | [`UringWriter`] | on the platter, and a journal row points at them | keeps them |
24//!
25//! [`FastWriter`] **bounds** the other two: it is the ceiling that the cost of
26//! durability is measured against. It is also a **selectable arm** — see
27//! [`crate::arms::WriterArm`] — because there are workloads whose contract is
28//! not git's (a rebuildable mirror, a bulk import that is re-run on failure, a
29//! benchmark), and the operator who picks it is choosing the row above. Nothing
30//! here refuses it; the table is what it promises.
31//!
32//! # The ordering the two durable arms both obey
33//!
34//! Taken from `znippy-common/src/hot.rs` (:92, :310-327) and not re-invented:
35//!
36//! ```text
37//! blob bytes -> fsync(blobs) -> journal row -> fsync(journal)
38//! ```
39//!
40//! The blob bytes are durable **before** any row references them. A crash
41//! between the two leaves **orphan bytes nobody points at** — dead payload the
42//! seal drops. The reverse order would leave an index row pointing into a hole,
43//! which is a corrupt archive rather than a lost append.
44//!
45//! # The BufWriter trap
46//!
47//! The journal is written through a `std::io::BufWriter`. `flush()` moves
48//! userspace → kernel; `sync_all()` moves kernel → platter. **`sync_all()`
49//! without a prior `flush()` syncs nothing you just wrote and looks perfectly
50//! durable** — the call succeeds, the fsync is real, and the bytes are still
51//! sitting in a userspace `Vec`. [`SafeWriter`] deliberately keeps the userspace
52//! buffer so that this ordering is load-bearing and a test can see it fail; the
53//! guard `journal_flush_before_sync_is_load_bearing` in `tests/archive_write.rs`
54//! is the one that watched it.
55//!
56//! # The journal is a LOG, and a reopen appends to it
57//!
58//! One Arrow IPC schema message at the head of the file, then one batch message
59//! per acked pack, for the life of the archive. A writer opened over an archive
60//! that already has a journal **appends** — it writes no second schema and it
61//! truncates nothing.
62//!
63//! There is exactly one other kind of row and it is appended the same way: a
64//! **tombstone** ([`retire_packs`]), written by a `gc` that found every object of
65//! a pack dead. It retires that pack's extent without removing its row, because
66//! removing a row is the one thing this file's contract forbids. See
67//! [`JOURNAL_TOMBSTONE`] for the encoding and [`JournalRow`] for why a pack's
68//! ordinal counts pack rows rather than raw rows.
69//!
70//! That is not a style choice, it is the crash-recovery contract. The extents in
71//! this file are one half of §13.12's `indexed` bit: a pack is unabsorbed *iff*
72//! its extent is here and its rows are not in the index, and
73//! [`GitStore::open_with`](crate::git_ops::GitStore::open_with) diffs the two on
74//! every open. A journal truncated by the reopen would erase the evidence that a
75//! durable pack was ever acked, so the pack's bytes would stay on disk with
76//! nothing pointing at them and nothing able to re-queue them — the exact failure
77//! the ordering above exists to prevent, arriving one restart later. Emitting a
78//! second schema message mid-file would be no better: arrow's `StreamReader`
79//! stops at it, so [`read_journal()`] would silently return only the rows written
80//! before this process started.
81
82use std::fs::{File, OpenOptions};
83use std::io::{BufWriter, Write};
84use std::os::unix::fs::FileExt;
85use std::path::{Path, PathBuf};
86use std::sync::atomic::{AtomicU64, Ordering};
87use std::sync::{Arc, Mutex};
88
89use anyhow::{Result, anyhow, bail};
90use znippy_common::arrow;
91use znippy_common::arrow::array::{ArrayRef, UInt64Array};
92use znippy_common::arrow::datatypes::{DataType, Field, Schema, SchemaRef};
93use znippy_common::arrow::ipc::MetadataVersion;
94use znippy_common::arrow::ipc::writer::{
95 DictionaryTracker, IpcDataGenerator, IpcWriteOptions, write_message,
96};
97use znippy_common::arrow::record_batch::RecordBatch;
98
99/// A byte range inside the archive: `(offset, len)`. Same shape as
100/// [`crate::store::Extent`].
101pub type Extent = (u64, u64);
102
103/// Append pushed packfile bytes to an archive, verbatim.
104///
105/// One trait, three durability contracts. The implementation decides **when**
106/// `append` is allowed to return; it never decides what the bytes are.
107pub trait ArchiveWrite: Send + Sync {
108 /// Append these bytes and return when this implementation's durability
109 /// contract is met. Returns the byte extent written.
110 ///
111 /// The bytes are stored exactly as handed over: no compression, no framing,
112 /// no re-encoding. The returned `(offset, len)` addresses them inside the
113 /// archive's blob region and is the *only* thing that goes to the indexer.
114 fn append(&self, bytes: &[u8]) -> Result<Extent>;
115
116 /// Name it on a bench row.
117 fn name(&self) -> &'static str;
118
119 /// One-line statement of what a crash immediately after `append` returns
120 /// does to the bytes. On the bench table next to the throughput, because a
121 /// throughput without this is not a comparison.
122 fn durability(&self) -> &'static str;
123
124 /// **This arm's open file description on the blob file**, for the readers
125 /// in the same process.
126 ///
127 /// Every arm opens the file once, read/write, through
128 /// [`open_blobs`]; a reader `pread`s at an explicit offset and shares no
129 /// cursor with `append`, so handing the same description out is a
130 /// descriptor saved and nothing else changed. It is on the trait rather
131 /// than on the three concrete types because the one caller that matters —
132 /// [`crate::indexer::PushPath::with_absorber`] — holds a
133 /// `Box<dyn ArchiveWrite>` and would otherwise have to open its own.
134 ///
135 /// `None` is reserved for an arm that has no such file. There is none
136 /// today, and an arm that returns it gets its own handle rather than an
137 /// error.
138 fn blobs_shared(&self) -> Option<Arc<File>>;
139}
140
141// ── the journal, shared by every durable arm ────────────────────────────────
142
143/// Alignment of an IPC message in the journal. 8 is what
144/// `znippy_common::hot`'s journal segments use.
145pub const JOURNAL_ALIGNMENT: u8 = 8;
146
147/// The journal's schema: the reference from a row to the blob bytes.
148///
149/// Deliberately two `u64`s and nothing else. The journal's job is to say *these
150/// bytes exist at this extent*; everything derived from the bytes (object count,
151/// pack version, checksum) is the indexer's job and is built later, off this
152/// path.
153pub fn journal_schema() -> SchemaRef {
154 Arc::new(Schema::new(vec![
155 Field::new("blob_offset", DataType::UInt64, false),
156 Field::new("blob_size", DataType::UInt64, false),
157 ]))
158}
159
160/// The IPC write options every arm's journal uses, so the three arms' journals
161/// are byte-comparable.
162pub fn journal_options() -> Result<IpcWriteOptions> {
163 IpcWriteOptions::try_new(JOURNAL_ALIGNMENT as usize, false, MetadataVersion::V5)
164 .map_err(|e| anyhow!("journal write options: {e}"))
165}
166
167/// One journal row for one extent.
168pub fn journal_batch(offset: u64, len: u64) -> Result<RecordBatch> {
169 let off: ArrayRef = Arc::new(UInt64Array::from(vec![offset]));
170 let size: ArrayRef = Arc::new(UInt64Array::from(vec![len]));
171 RecordBatch::try_new(journal_schema(), vec![off, size])
172 .map_err(|e| anyhow!("journal batch: {e}"))
173}
174
175/// Serialize the journal's *schema* message — the header an Arrow IPC stream
176/// opens with, emitted once per segment.
177///
178/// Both durable arms call it, and each writes it **once per journal file**:
179/// [`SafeWriter`] when it finds the file empty,
180/// [`UringWriter`](crate::uring_write::UringWriter) at offset 0 of the one it
181/// creates. One encoder, one format, two transports (LAW 5) — and a
182/// second schema message inside one file is what would make [`read_journal()`]
183/// stop early, which is why neither arm can emit it per writer.
184pub fn encode_journal_schema() -> Result<Vec<u8>> {
185 let opts = journal_options()?;
186 let dg = IpcDataGenerator {};
187 let mut tracker = DictionaryTracker::new(false);
188 let encoded =
189 dg.schema_to_bytes_with_dictionary_tracker(journal_schema().as_ref(), &mut tracker, &opts);
190 let mut out = Vec::with_capacity(512);
191 write_message(&mut out, encoded, &opts).map_err(|e| anyhow!("journal schema encode: {e}"))?;
192 Ok(out)
193}
194
195/// Serialize one journal *batch* message for `(offset, len)`.
196pub fn encode_journal_row(offset: u64, len: u64) -> Result<Vec<u8>> {
197 let opts = journal_options()?;
198 let dg = IpcDataGenerator {};
199 let mut tracker = DictionaryTracker::new(false);
200 let batch = journal_batch(offset, len)?;
201 let (dicts, msg) = dg
202 .encode(&batch, &mut tracker, &opts, &mut Default::default())
203 .map_err(|e| anyhow!("journal batch encode: {e}"))?;
204 let mut out = Vec::with_capacity(512);
205 for d in dicts {
206 write_message(&mut out, d, &opts).map_err(|e| anyhow!("journal dict encode: {e}"))?;
207 }
208 write_message(&mut out, msg, &opts).map_err(|e| anyhow!("journal row encode: {e}"))?;
209 Ok(out)
210}
211
212/// Read every complete journal row back, tolerating a torn tail.
213///
214/// A journal is a **log**, not a document: a process killed mid-write leaves a
215/// partial final message, and every complete message before it is real. Same
216/// rule `znippy_common::hot`'s segment reader follows. Used by the guards to
217/// assert what a crash actually left behind rather than what the writer claimed.
218pub fn read_journal(path: &Path) -> Result<Vec<Extent>> {
219 let f = File::open(path).map_err(|e| anyhow!("journal open {}: {e}", path.display()))?;
220 if f.metadata()?.len() == 0 {
221 return Ok(Vec::new());
222 }
223 let reader = match arrow::ipc::reader::StreamReader::try_new(std::io::BufReader::new(f), None) {
224 Ok(r) => r,
225 // A journal with a torn *schema* message carries no rows at all.
226 Err(_) => return Ok(Vec::new()),
227 };
228 let mut out = Vec::new();
229 for batch in reader {
230 let Ok(batch) = batch else { break }; // torn tail: stop, keep what is whole
231 let offs = batch
232 .column(0)
233 .as_any()
234 .downcast_ref::<UInt64Array>()
235 .ok_or_else(|| anyhow!("journal column 0 is not u64"))?;
236 let sizes = batch
237 .column(1)
238 .as_any()
239 .downcast_ref::<UInt64Array>()
240 .ok_or_else(|| anyhow!("journal column 1 is not u64"))?;
241 for i in 0..batch.num_rows() {
242 out.push((offs.value(i), sizes.value(i)));
243 }
244 }
245 Ok(out)
246}
247
248// ── retirement: the one row a `gc` appends ──────────────────────────────────
249
250/// The `blob_size` of a journal row that is **not** a pack: a **tombstone**,
251/// whose `blob_offset` names a pack this archive has retired.
252///
253/// `u64::MAX` rather than `0`, and that is the whole of the encoding decision.
254/// The journal's schema is two `u64`s and a third column cannot be added without
255/// making every existing journal file unreadable by the writer that appends to
256/// it, so the marker has to live inside a value that no real pack can take. A
257/// zero-length append is at least *conceivable* — a caller handing `append` an
258/// empty slice gets `(cursor, 0)` — while an extent of 2^64-1 bytes cannot
259/// exist on any filesystem this will ever run on. The unreachable value is the
260/// safe one.
261pub const JOURNAL_TOMBSTONE: u64 = u64::MAX;
262
263/// One journal row, read back and interpreted.
264///
265/// **The ordinal of a pack is its position among the [`Pack`](JournalRow::Pack)
266/// rows, not its row index.** Tombstones are appended to the same log — that is
267/// what keeps the journal append-only — so counting raw rows would renumber
268/// every pack acked before a `gc` and make the ordinals a live process holds
269/// disagree with the ones the next open derives. Counting pack rows cannot: a
270/// pack row is never removed and never reordered, so a pack's ordinal is fixed
271/// for the life of the archive.
272#[derive(Debug, Clone, Copy, PartialEq, Eq)]
273pub enum JournalRow {
274 /// A pack was acked at this extent.
275 Pack(Extent),
276 /// The pack that starts at this offset was retired: a `gc` found **every**
277 /// one of its objects dead and dropped every row it had. Its bytes are still
278 /// in the blob file (the blob file is append-only and nothing truncates it),
279 /// but no open may ever re-queue it for indexing again.
280 Retired(u64),
281}
282
283/// Interpret what [`read_journal`] returned.
284pub fn journal_rows(rows: &[Extent]) -> Vec<JournalRow> {
285 rows.iter()
286 .map(|&(offset, len)| {
287 if len == JOURNAL_TOMBSTONE {
288 JournalRow::Retired(offset)
289 } else {
290 JournalRow::Pack((offset, len))
291 }
292 })
293 .collect()
294}
295
296/// The acked pack extents, in **ordinal order** — index `i` is pack `i`.
297pub fn acked_packs(rows: &[Extent]) -> Vec<Extent> {
298 journal_rows(rows)
299 .into_iter()
300 .filter_map(|r| match r {
301 JournalRow::Pack(e) => Some(e),
302 JournalRow::Retired(_) => None,
303 })
304 .collect()
305}
306
307/// The offsets of the packs a `gc` has retired.
308pub fn retired_offsets(rows: &[Extent]) -> std::collections::HashSet<u64> {
309 journal_rows(rows)
310 .into_iter()
311 .filter_map(|r| match r {
312 JournalRow::Retired(o) => Some(o),
313 JournalRow::Pack(_) => None,
314 })
315 .collect()
316}
317
318/// **Retire these packs: one tombstone row each, durable before this returns.**
319///
320/// Called by `GitOps::gc` *before* it drops a single index row, and that order
321/// is the crash contract. The two possible interruptions are not symmetric:
322///
323/// * killed **before** the tombstones are durable — the rows are still in the
324/// index, so the next open sees packs that have rows, calls them absorbed, and
325/// nothing is lost or resurrected. The GC simply did not happen.
326/// * killed **after** — the rows may or may not have gone, and either way the
327/// next open reads a tombstone and refuses to re-queue the pack. The dead
328/// objects cannot come back.
329///
330/// The reverse order has a window in which the rows are gone and the journal
331/// still claims an unabsorbed pack, which is exactly the resurrection this
332/// function exists to close.
333///
334/// A torn write leaves a partial final message, which [`read_journal`] discards
335/// with the rest of a torn tail — the same tolerance a torn *pack* row gets, and
336/// safe for the same reason: a tombstone that did not land is a `gc` that did not
337/// happen.
338///
339/// All the rows go out in **one** `write(2)` on an `O_APPEND` fd, so a push
340/// appending through [`SafeWriter`]'s own fd at the same instant cannot land
341/// inside one of them.
342pub fn retire_packs(journal: &Path, offsets: &[u64]) -> Result<()> {
343 if offsets.is_empty() {
344 return Ok(());
345 }
346 let mut buf = Vec::with_capacity(offsets.len() * 256);
347 for &offset in offsets {
348 buf.extend_from_slice(&encode_journal_row(offset, JOURNAL_TOMBSTONE)?);
349 }
350 let f = OpenOptions::new()
351 .append(true)
352 .open(journal)
353 .map_err(|e| anyhow!("open journal {} to retire a pack: {e}", journal.display()))?;
354 if f.metadata()?.len() == 0 {
355 // No schema message, therefore no pack row, therefore nothing that could
356 // have been retired. Writing a tombstone into an empty stream would
357 // produce a journal whose first message is a batch, which reads back as
358 // no rows at all.
359 bail!(
360 "{} is empty — nothing was ever acked here, so there is no pack to retire",
361 journal.display()
362 );
363 }
364 (&f).write_all(&buf)
365 .map_err(|e| anyhow!("journal tombstone write: {e}"))?;
366 f.sync_all()
367 .map_err(|e| anyhow!("journal tombstone fsync: {e}"))?;
368 Ok(())
369}
370
371/// **The writer lock** — `P-014`. One writer per blob file, enforced by the
372/// kernel, held for as long as the writer's handle lives.
373///
374/// # What it is protecting against, measured
375///
376/// Every arm reserves its extent from an `AtomicU64` seeded here from the file's
377/// length **at open time**. Two processes that both open before either appends
378/// therefore hold two cursors with the same value and hand out *the same
379/// offsets*. Driven on t14s 2026-08-11, two processes × 16 one-blob packs on
380/// `SafeWriter`, released together: 32 packs acked, `objects.pack` never grew
381/// past one writer's worth, and **16 of 32 acked, fsynced, journalled objects
382/// were destroyed with two zero exit codes**. Neither writer errored, which is
383/// the whole problem.
384///
385/// # Why `flock` and not an `O_EXCL` lock file
386///
387/// `S-019`: *"the `O_EXCL` store lock does not self-clear; a killed appliance
388/// will not restart."* A lock that survives a crash is worse than the race it
389/// prevents. `flock(2)` is released by the kernel when the last descriptor for
390/// the open file description closes — including on `SIGKILL`, including on a
391/// panic — so a killed server comes back up. Verified rather than recited: a
392/// store held by one process, `kill -9`, and the next open succeeds.
393///
394/// [`std::fs::File::try_lock`] *is* `flock(LOCK_EX | LOCK_NB)` on unix, so this
395/// costs no dependency, and it is **the same mechanism redb already uses** on
396/// `objects.tail` (`redb-2.6.3/src/tree_store/page_store/file_backend/unix.rs:37`).
397/// One locking discipline in this store, not two.
398///
399/// # Why at open, and NOT around `append`
400///
401/// The ack path is the latency path: `append` returns to the client and the
402/// indexer runs after it. A lock taken per append would put a syscall on that
403/// path and would still not help, because the *cursor* is what is stale, not the
404/// write. Taken once here, the ack path takes **no lock at all** and nothing
405/// about `append`'s cost changes.
406///
407/// It is here, in `open_blobs`, because that is the one function
408/// [`FastWriter`], [`SafeWriter`] and
409/// [`UringWriter`](crate::uring_write::UringWriter) all call — one lock for
410/// three arms, rather than one arm fixed and two left. It also runs *before*
411/// `UringWriter::create`'s `File::create(journal)`, so a second process can no
412/// longer truncate the journal on its way to being refused.
413///
414/// # What it deliberately does NOT cover
415///
416/// **Two threads sharing one open handle.** An advisory lock is per open file
417/// *description*; a second `try_lock` on the same handle returns `Ok`. That case
418/// is `tests/concurrent_push.rs`'s second test, and it needs no lock: the
419/// `fetch_add` cursor every arm shares makes two concurrent appends touch
420/// provably disjoint ranges. A mutex there would serialise the ack path to fix a
421/// race that cannot happen.
422///
423/// # Refuse, do not wait
424///
425/// `LOCK_NB`, matching redb. A server that blocked here would hang on startup
426/// behind a process it cannot see, with no error and no timeout; a refusal names
427/// the file and the caller already handles one, because redb's has been throwing
428/// it all along.
429fn lock_for_writing(f: &File, path: &Path) -> Result<()> {
430 match f.try_lock() {
431 Ok(()) => Ok(()),
432 Err(std::fs::TryLockError::WouldBlock) => bail!(
433 "another writer already holds {} — one process at a time appends to a store's \
434 blob file. Two would share a stale append cursor and overwrite each other's \
435 acked packs without either one erroring. The lock is an advisory flock and the \
436 kernel drops it when that process dies, so nothing has to be cleaned up by hand.",
437 path.display()
438 ),
439 Err(std::fs::TryLockError::Error(e)) => Err(anyhow!(
440 "locking {} for writing: {e} — the store is not opened without the writer lock, \
441 because an unlocked open is the P-014 race",
442 path.display()
443 )),
444 }
445}
446
447/// Open (creating) the blob file an archive's payload region lives in, and
448/// report the cursor to append at.
449///
450/// **Takes the writer lock** before reading the cursor — see
451/// [`lock_for_writing`] for why the lock is here and not around `append`. The
452/// order matters: the length this returns is only meaningful to a writer that
453/// owns the file, and it is read after the lock so it cannot be stale by the
454/// time it is used.
455/// What a journal file's head says an opening writer must do about it.
456pub(crate) struct JournalHead {
457 /// The schema message this build writes.
458 pub schema: Vec<u8>,
459 /// Write it (again). False for a file that already opens with it.
460 pub rewrite: bool,
461}
462
463/// ── AN EMPTY STORE IS NOT MADE DURABLE, IT IS MADE AGAIN ────────────────────
464///
465/// Both durable arms used to `fsync` the schema message they wrote into a fresh
466/// journal. On gunnar's create path that barrier was 8.9 ms of a 68.5 ms
467/// push-create (lane V's per-step medians, 2 vCPU rig), spent making durable a
468/// file that references nothing: a store with no journal row has acked no pack,
469/// and gunnar's create is transactional, so a create that does not finish leaves
470/// no catalog row pointing at the store at all. The first row a writer claims
471/// fsyncs the same file and takes the schema with it, so from the first ack
472/// onward nothing about durability differs.
473///
474/// The one thing the barrier bought was that a schema torn by a crash could not
475/// be inherited by the next open as if it were whole. That is bought here
476/// instead, by **checking** — a short read of a file the open is about to read
477/// anyway:
478///
479/// * an empty file gets the schema;
480/// * a file that begins with exactly this build's schema message, and is at
481/// least as long as one, is a live journal and is left alone;
482/// * anything else **no longer than the schema** was interrupted before a row
483/// could exist behind it (rows are appended after it), so it is written again
484/// and nothing is lost;
485/// * anything else **longer** than the schema did carry rows, so it is corrupt
486/// rather than interrupted, and it is said out loud instead of truncated.
487///
488/// One function for both arms on purpose: LAW 5 already claims they are
489/// indistinguishable on disk, and two copies of this reasoning is how that stops
490/// being true.
491pub(crate) fn journal_head(f: &File, path: &Path) -> Result<JournalHead> {
492 let schema = encode_journal_schema()?;
493 let already = f
494 .metadata()
495 .map_err(|e| anyhow!("stat journal {}: {e}", path.display()))?
496 .len();
497 if already == 0 {
498 return Ok(JournalHead { schema, rewrite: true });
499 }
500 let mut got = vec![0u8; schema.len().min(already as usize)];
501 f.read_exact_at(&mut got, 0)
502 .map_err(|e| anyhow!("reading the journal header of {}: {e}", path.display()))?;
503 let head_matches = got == schema[..got.len()];
504 if head_matches && already >= schema.len() as u64 {
505 return Ok(JournalHead { schema, rewrite: false });
506 }
507 if already <= schema.len() as u64 {
508 return Ok(JournalHead { schema, rewrite: true });
509 }
510 bail!(
511 "the journal {} does not begin with this build's schema message and is longer than one, \
512 so it carried acked packs: it is corrupt, and truncating it would unreference their bytes",
513 path.display()
514 )
515}
516
517/// **The one open file description on a store's blob file** — read/write,
518/// `flock`ed, and shared.
519///
520/// `Arc<File>` rather than `File` because this handle serves three callers in
521/// one process and used to be opened three times: the writer appends through
522/// it, [`crate::git_ops::Absorber`] `pread`s extents back through it, and the
523/// index workers `read_exact_at` through it. All three address the file
524/// positionally, the file is append-only and `gc` truncates nothing (§14), so
525/// there is no shared cursor and nothing to observe between them — three
526/// descriptors bought three kernel objects and three page-cache aliases per
527/// open repository and no isolation at all. See `tests/fd_per_store.rs`.
528///
529/// The `flock` therefore lives as long as the last of the three, which is the
530/// store: a reader outliving the writer can no longer drop the writer lock out
531/// from under a store that is still open.
532pub(crate) fn open_blobs(path: &Path) -> Result<(Arc<File>, u64)> {
533 let f = OpenOptions::new()
534 .read(true)
535 .write(true)
536 .create(true)
537 .truncate(false)
538 .open(path)
539 .map_err(|e| anyhow!("open blobs {}: {e}", path.display()))?;
540 lock_for_writing(&f, path)?;
541 let end = reclaim_orphan_tail(&f, path)?;
542 Ok((Arc::new(f), end))
543}
544
545/// **Give back the bytes past the last journaled extent** — the append-side gc,
546/// run once at open while this process holds the writer `flock` and before any
547/// append can race it.
548///
549/// # The leak it closes, which is older than the caller that made it obvious
550///
551/// An append is two durable acts in order — the bytes, then the journal row
552/// naming them. A crash between them leaves bytes in the blob file that no
553/// extent addresses, and the cursor is taken from the file's LENGTH, so the next
554/// append starts past them and they are never reached again.
555/// [`SafeWriter::create_inner`]'s own comment already names the shape ("a reopen
556/// that dropped them would leave their bytes unreferenced for ever") — it is
557/// talking about the journal rows, and this is the other half.
558///
559/// Nothing referenced them, so nothing is lost by taking them back: a push whose
560/// journal row never landed was never acked, and the client will send it again.
561///
562/// # It refuses every ambiguous case rather than guessing
563///
564/// Truncation is the one operation here that cannot be undone, so it happens
565/// only when the journal positively says where the data ends:
566///
567/// * **no journal file at all** — [`FastWriter`] keeps none, so an absent
568/// journal is a normal arm and not evidence of anything. Left alone.
569/// * **a journal that reads as empty** — [`read_journal`] answers `Ok(vec![])`
570/// for a torn *schema* message as well as for a genuinely empty log, and those
571/// two are not distinguishable from here. Truncating on that reading would
572/// turn one bad message into the loss of every pack in the archive. Left
573/// alone, loudly.
574/// * **tombstones** ([`JOURNAL_TOMBSTONE`]) carry `u64::MAX` as their length and
575/// are skipped: their `blob_offset` names a retired pack, and adding that
576/// length would compute a high-water mark past the end of the universe.
577fn reclaim_orphan_tail(f: &File, archive: &Path) -> Result<u64> {
578 let len = f.metadata()?.len();
579 if len == 0 {
580 return Ok(0);
581 }
582 let journal = journal_path(archive);
583 if !journal.exists() {
584 return Ok(len);
585 }
586 let rows = read_journal(&journal)?;
587 let high_water = rows
588 .iter()
589 .filter(|(_, l)| *l != JOURNAL_TOMBSTONE)
590 .map(|(o, l)| o.saturating_add(*l))
591 .max();
592 let Some(high_water) = high_water else {
593 if len > 0 {
594 tracing::warn!(
595 target: "znippy.git",
596 archive = %archive.display(),
597 blob_bytes = len,
598 "the journal names no extent but the blob file is not empty — leaving it \
599 alone: an unreadable journal and an empty one look the same from here, and \
600 truncating on that reading would drop every pack in the archive"
601 );
602 }
603 return Ok(len);
604 };
605 if len <= high_water {
606 return Ok(len);
607 }
608 let orphan = len - high_water;
609 f.set_len(high_water)
610 .map_err(|e| anyhow!("reclaiming {orphan} orphan byte(s) of {}: {e}", archive.display()))?;
611 tracing::warn!(
612 target: "znippy.git",
613 archive = %archive.display(),
614 reclaimed = orphan,
615 blob_bytes = high_water,
616 "gave back blob bytes past the last journaled extent — a crash between an append \
617 and its journal row. Nothing referenced them; the push they belonged to was never \
618 acked"
619 );
620 Ok(high_water)
621}
622
623// ── impl 1 — FastWriter ─────────────────────────────────────────────────────
624
625/// **The cheating arm.** Returns before the bytes are on disk.
626///
627/// # What it does NOT guarantee
628///
629/// `append` returns as soon as one `pwrite(2)` has handed the bytes to the
630/// kernel's page cache. There is **no `fsync`**, **no journal row**, and **no
631/// barrier of any kind**. Concretely:
632///
633/// * **A crash (power loss, kernel panic, `SIGKILL` of the box) after `append`
634/// returns loses the data.** Not "may lose" — the bytes exist only in volatile
635/// page cache and nothing has told the device about them.
636/// * Nothing on disk references the extent, so even bytes that *did* reach the
637/// platter are unreachable after a restart until something scans for them.
638/// * A process crash alone (not a machine crash) does keep them: page cache
639/// survives `exit`. That is the only crash it survives.
640///
641/// It is here to **bound** [`SafeWriter`] and [`UringWriter`]: it is the ceiling
642/// the price of durability is measured against — at 8 KiB it acks in 3.9 µs
643/// against `SafeWriter`'s 132 µs (`examples/push_path_bench.rs`, oden
644/// 2026-08-07).
645///
646/// # Selecting it
647///
648/// It is a first-class arm of [`crate::arms::WriterArm`] and
649/// [`GitStore`](crate::git_ops::GitStore) will be built on it if it is asked
650/// for. Nothing refuses it, because "durable before ack" is git's contract and
651/// not every store on this code is serving git pushes: a mirror that can be
652/// re-cloned, an import that is re-run on failure and a benchmark all have a
653/// weaker requirement, and for them the four bullets above are a price they are
654/// not obliged to pay. A store that *is* serving pushes and picks this one loses
655/// acked data on a machine crash, and that is the whole of what the choice
656/// means.
657///
658/// There is one consequence beyond durability, because it follows from the same
659/// absence: with no journal there is no durable record that a pack was ever
660/// acked, so a reopened store re-queues nothing and pack ordinals restart at 0
661/// (`indexer::packs_already_acked`).
662///
663/// # Zero-copy
664///
665/// The caller's `bytes` are handed to `pwrite` at their own address. There is no
666/// `to_vec`, no staging buffer and no `BufWriter` — one userspace→kernel copy,
667/// which is the syscall itself and cannot be removed without io_uring registered
668/// buffers (see [`UringWriter`]).
669pub struct FastWriter {
670 blobs: Arc<File>,
671 cursor: AtomicU64,
672}
673
674impl FastWriter {
675 /// Open `archive` for verbatim appends.
676 pub fn create(archive: &Path) -> Result<Self> {
677 let (blobs, end) = open_blobs(archive)?;
678 Ok(Self {
679 blobs,
680 cursor: AtomicU64::new(end),
681 })
682 }
683
684 /// The blob file, for a reader that wants to `pread` an extent back.
685 pub fn blobs(&self) -> &File {
686 &self.blobs
687 }
688}
689
690impl ArchiveWrite for FastWriter {
691 fn append(&self, bytes: &[u8]) -> Result<Extent> {
692 let len = bytes.len() as u64;
693 // Reserve the extent atomically, then write it positionally. Two
694 // concurrent appends touch disjoint ranges and never share a file
695 // offset, so no lock is needed and none is taken.
696 let offset = self.cursor.fetch_add(len, Ordering::SeqCst);
697 self.blobs.write_all_at(bytes, offset)?;
698 // …and return. The bytes are in the page cache. That is the whole point.
699 Ok((offset, len))
700 }
701
702 fn name(&self) -> &'static str {
703 "FastWriter"
704 }
705
706 fn durability(&self) -> &'static str {
707 "none — page cache only; a machine crash after return loses the bytes"
708 }
709
710 fn blobs_shared(&self) -> Option<Arc<File>> {
711 Some(Arc::clone(&self.blobs))
712 }
713}
714
715// ── impl 2 — SafeWriter ─────────────────────────────────────────────────────
716
717struct SafeJournal {
718 /// The userspace buffer the trap above is about. Raw Arrow IPC messages go
719 /// into it — [`encode_journal_schema`] once, [`encode_journal_row`] per
720 /// append — the same two calls
721 /// [`UringWriter`](crate::uring_write::UringWriter) builds its journal from
722 /// (LAW 5: one journal format, one encoder, two transports). An arrow
723 /// `StreamWriter` cannot be used here because it emits
724 /// its schema on construction, and a second schema message is what an
725 /// appending reopen must not write.
726 writer: BufWriter<File>,
727 path: PathBuf,
728}
729
730/// The ordering znippy's own hot path already uses, followed rather than
731/// re-invented.
732///
733/// Per `append`, in this order and no other:
734///
735/// 1. `pwrite` the blob bytes at the reserved extent;
736/// 2. `fsync` the **blobs** — the bytes are on the platter;
737/// 3. write one Arrow IPC `RecordBatch` naming the extent into the journal;
738/// 4. `flush()` the journal's `BufWriter` — userspace → kernel;
739/// 5. `sync_all()` the journal file — kernel → platter.
740///
741/// Steps 4 and 5 are not interchangeable and 5 alone is not enough: see the
742/// module docs' "BufWriter trap". Steps 2 and 3 are not interchangeable either
743/// — that is the crash-ordering contract, and
744/// `crash_between_fsyncs_leaves_orphan_bytes_not_a_dangling_reference` asserts
745/// it on real files.
746///
747/// # Durability on return
748///
749/// The bytes are on the device and a journal row on the device points at them.
750/// A crash after return keeps both.
751pub struct SafeWriter {
752 blobs: Arc<File>,
753 cursor: AtomicU64,
754 journal: Mutex<SafeJournal>,
755 faults: Faults,
756}
757
758/// Injected faults, so the crash-ordering guard exercises the **real** `append`
759/// rather than a hand-rolled twin of it (LAW 5: one writer, not two copies that
760/// a guard then watches agree).
761///
762/// Never set outside a test. [`SafeWriter::create`] leaves both clear.
763#[derive(Debug, Clone, Copy, Default)]
764pub struct Faults {
765 /// Skip step (2), the blob `fsync`.
766 pub skip_blob_fsync: bool,
767 /// Stop after step (2) and before step (3) — the exact on-disk state a
768 /// machine that dies between the two fsyncs leaves behind. `append` returns
769 /// `Err` because a Rust function has to return something; a real crash
770 /// simply would not return, and the bytes on the platter are identical
771 /// either way, which is what the guard asserts on.
772 pub die_between_fsyncs: bool,
773}
774
775impl SafeWriter {
776 /// Open `archive` and start a journal segment beside it at
777 /// `<archive>.journal`.
778 pub fn create(archive: &Path) -> Result<Self> {
779 Self::create_inner(archive, Faults::default())
780 }
781
782 /// Same, with an injected fault. **Tests only.**
783 pub fn create_with_faults(archive: &Path, faults: Faults) -> Result<Self> {
784 Self::create_inner(archive, faults)
785 }
786
787 fn create_inner(archive: &Path, faults: Faults) -> Result<Self> {
788 let (blobs, end) = open_blobs(archive)?;
789 let path = journal_path(archive);
790 // **Append, never truncate** (module docs): the rows already here are the
791 // durable record that those packs were acked, and a reopen that dropped
792 // them would leave their bytes unreferenced for ever.
793 let f = OpenOptions::new()
794 .read(true)
795 .append(true)
796 .create(true)
797 .open(&path)
798 .map_err(|e| anyhow!("open journal {}: {e}", path.display()))?;
799 let head = journal_head(&f, &path)?;
800 if head.rewrite && f.metadata()?.len() != 0 {
801 f.set_len(0)
802 .map_err(|e| anyhow!("resetting the interrupted journal {}: {e}", path.display()))?;
803 }
804 // DELIBERATELY buffered. See the module docs: the flush→sync ordering is
805 // only load-bearing when there is a userspace buffer to lose.
806 let mut j = SafeJournal {
807 writer: BufWriter::new(f),
808 path,
809 };
810 // The schema message opens the stream and is written **once per file**,
811 // not once per writer.
812 if head.rewrite {
813 j.writer
814 .write_all(&head.schema)
815 .map_err(|e| anyhow!("journal schema: {e}"))?;
816 // Out of the userspace buffer, so the next `sync_all` — the one the
817 // first acked pack pays — has something to make durable.
818 j.writer.flush().map_err(|e| anyhow!("journal flush: {e}"))?;
819 }
820 Ok(Self {
821 blobs,
822 cursor: AtomicU64::new(end),
823 journal: Mutex::new(j),
824 faults,
825 })
826 }
827
828 /// Path of the journal segment beside `archive`.
829 pub fn journal_path(archive: &Path) -> PathBuf {
830 journal_path(archive)
831 }
832
833 /// The blob file, for a reader that wants to `pread` an extent back.
834 pub fn blobs(&self) -> &File {
835 &self.blobs
836 }
837
838 /// The journal segment this writer is appending rows to.
839 pub fn journal_file(&self) -> PathBuf {
840 self.journal.lock().expect("journal mutex").path.clone()
841 }
842}
843
844pub(crate) fn journal_path(archive: &Path) -> PathBuf {
845 let mut s = archive.as_os_str().to_os_string();
846 s.push(".journal");
847 PathBuf::from(s)
848}
849
850impl ArchiveWrite for SafeWriter {
851 fn append(&self, bytes: &[u8]) -> Result<Extent> {
852 let len = bytes.len() as u64;
853 let offset = self.cursor.fetch_add(len, Ordering::SeqCst);
854
855 // (1) blob bytes, positional, no userspace copy of `bytes`.
856 self.blobs.write_all_at(bytes, offset)?;
857
858 // (2) blob bytes DURABLE — before anything references them. A crash from
859 // here to the end of this function leaves orphan payload nobody
860 // points at, which the seal drops. The reverse order would leave a
861 // row pointing into a hole.
862 if !self.faults.skip_blob_fsync {
863 self.blobs.sync_all()?;
864 }
865
866 if self.faults.die_between_fsyncs {
867 // The machine is gone. On-disk state: the blob bytes, fsynced, and a
868 // journal that has never heard of them. Orphan payload, not a
869 // dangling reference.
870 bail!("injected crash between the two fsyncs");
871 }
872
873 let mut j = self
874 .journal
875 .lock()
876 .map_err(|_| anyhow!("journal mutex poisoned"))?;
877 // (3) the row that claims the extent — one IPC batch message appended
878 // after every row this archive has ever acked.
879 let row = encode_journal_row(offset, len)?;
880 j.writer
881 .write_all(&row)
882 .map_err(|e| anyhow!("journal write: {e}"))?;
883 // (4) userspace -> kernel. WITHOUT THIS, (5) SYNCS NOTHING.
884 j.writer.flush().map_err(|e| anyhow!("journal flush: {e}"))?;
885 // (5) kernel -> platter.
886 j.writer
887 .get_ref()
888 .sync_all()
889 .map_err(|e| anyhow!("journal fsync: {e}"))?;
890
891 Ok((offset, len))
892 }
893
894 fn name(&self) -> &'static str {
895 "SafeWriter"
896 }
897
898 fn durability(&self) -> &'static str {
899 "full — blob fsynced, then a journal row fsynced; crash after return keeps both"
900 }
901
902 fn blobs_shared(&self) -> Option<Arc<File>> {
903 Some(Arc::clone(&self.blobs))
904 }
905}
906
907// ── generation 0: the seal that makes an archive exist at all ────────────────
908
909/// What one [`seal_generation_zero`] put on disk. Every count is taken off the
910/// journal and the sealed file, never echoed back from an argument.
911#[derive(Debug, Clone, PartialEq, Eq)]
912pub struct SealReport {
913 /// The archive that now exists.
914 pub archive: PathBuf,
915 /// Verbatim packs that got an index row — one row each, `chunk_seq = 0`.
916 pub packs_sealed: u64,
917 /// Acked packs the journal has since tombstoned. They keep their bytes in
918 /// the blob region and get **no** row, which is what makes them dead payload
919 /// for the compaction that follows.
920 pub packs_retired: u64,
921 /// Acked packs whose extent runs past the bytes that were copied — a pack
922 /// acked *after* the copy began. They get no row either, because a row for
923 /// one would address bytes this archive does not carry. Normally `0`; it is
924 /// reported rather than swallowed so a seal that raced a push says so.
925 pub packs_after_copy: u64,
926 /// Bytes of blob region carried into the archive — the whole blob file,
927 /// verbatim, so every journal extent still addresses the bytes it named.
928 pub blob_bytes: u64,
929 /// Size of the sealed archive, blob region and metadata tail together.
930 pub sealed_total_bytes: u64,
931}
932
933/// **Write generation 0.**
934///
935/// Both [`Gc`](crate::gc::Gc) implementations compact an archive that already
936/// exists — [`NewGeneration`](crate::gc::NewGeneration) writes `repository.g1.znippy`
937/// beside `repository.znippy`. Nothing created `repository.znippy`, so a `gc()`
938/// on a store that had never been sealed died on `stat: No such file or
939/// directory`. This is the function that had been missing.
940///
941/// # An archive is a blob region plus a metadata tail
942///
943/// The blob region here is the store's `objects.pack` — the verbatim pushed
944/// packs, at the offsets the journal named — and it is copied **whole and
945/// unchanged**. That is not laziness: a journal extent is `(offset, len)` into
946/// that file, and the same extents are what the store's `objects` table holds
947/// for every object. Rewriting the region to squeeze the dead packs out would
948/// move every offset after the first hole and invalidate every one of those
949/// rows. Reclaiming that payload is the compaction's job, and it can do it
950/// precisely because a retired pack gets no row here.
951///
952/// The tail is written past the copied blob region by
953/// [`ArrowIpcSink`](znippy_common::ArrowIpcSink) — the same writer
954/// `HotArchive::seal` uses, with the same reserved-section hook, so there is one
955/// metadata writer in this constellation and not two (LAW 5).
956///
957/// # One row per acked pack
958///
959/// | column | value |
960/// |---|---|
961/// | `relative_path` | `objects.pack.<ordinal>` — gunnar's `synthetic_path` convention, and the ordinal is the pack's position among the journal's [`JournalRow::Pack`] rows |
962/// | `blob_offset` / `blob_size` | the journal extent, unchanged |
963/// | `uncompressed_size` | the same length: a verbatim pack is stored raw |
964/// | `compressed` | `false` — the bytes on disk are the pack's own |
965/// | `chunk_seq` / `fdata_offset` | `0` — one chunk per pack |
966/// | `checksum` | blake3 **over the stored bytes**, which for `compressed: false` are also the original bytes — the domain `write_blobs` uses and the domain `extract_file_verified` checks against |
967///
968/// A tombstoned pack is skipped, and so is one whose extent runs past the bytes
969/// that were copied — that second case is a pack acked *after* the copy began,
970/// and a row for it would point into a hole. Both are **counted** on the
971/// [`SealReport`] rather than swallowed.
972///
973/// # Ordering
974///
975/// The blob region is copied first and the journal is read second, because the
976/// blob file is append-only: anything the journal names within the copied length
977/// is certainly present, while the reverse order could name an extent the copy
978/// had not reached. The tail is written into a staging sibling and the archive's
979/// own name appears only at the final `rename(2)`, so an interruption at any
980/// byte leaves no half-sealed archive under the name a reader opens.
981pub fn seal_generation_zero(
982 blobs: &Path,
983 journal: Option<&Path>,
984 archive: &Path,
985 reserved: Vec<znippy_common::ReservedSection>,
986) -> Result<SealReport> {
987 use znippy_common::index::{ChunkLoc, data_subindex_schema};
988 use znippy_common::{ArchiveMetaSink, ArrowIpcSink, GroupKey, base_batch_from_rows};
989
990 let staged = staging_sibling(archive);
991 let sealed = (|| -> Result<SealReport> {
992 // (1) the blob region, verbatim. Every journal extent still addresses
993 // the bytes it named because not one of them moved.
994 let blob_bytes = std::fs::copy(blobs, &staged).map_err(|e| {
995 anyhow!(
996 "copying the blob region {} into {}: {e}",
997 blobs.display(),
998 staged.display()
999 )
1000 })?;
1001
1002 // (2) the journal, second — see the ordering note above.
1003 let rows = match journal {
1004 Some(p) if p.exists() => read_journal(p)?,
1005 _ => Vec::new(),
1006 };
1007 let packs = acked_packs(&rows);
1008 let retired = retired_offsets(&rows);
1009
1010 let file = OpenOptions::new()
1011 .read(true)
1012 .write(true)
1013 .open(&staged)
1014 .map_err(|e| anyhow!("reopening {} to seal into: {e}", staged.display()))?;
1015
1016 let mut paths: Vec<String> = Vec::with_capacity(packs.len());
1017 let mut locs: Vec<ChunkLoc> = Vec::with_capacity(packs.len());
1018 let mut packs_retired = 0u64;
1019 let mut packs_after_copy = 0u64;
1020 for (ordinal, &(offset, len)) in packs.iter().enumerate() {
1021 if retired.contains(&offset) {
1022 packs_retired += 1;
1023 continue;
1024 }
1025 if offset.saturating_add(len) > blob_bytes {
1026 // Acked after the copy began. A row for it would address bytes
1027 // this archive does not carry.
1028 packs_after_copy += 1;
1029 continue;
1030 }
1031 paths.push(format!("objects.pack.{ordinal}"));
1032 locs.push(ChunkLoc {
1033 chunk_seq: 0,
1034 fdata_offset: 0,
1035 blob_offset: offset,
1036 blob_size: len,
1037 uncompressed_size: len,
1038 compressed: false,
1039 checksum: blake3_extent(&file, offset, len)?,
1040 });
1041 }
1042 let packs_sealed = paths.len() as u64;
1043
1044 // (3) the metadata tail, past the blob region.
1045 let file = Arc::new(file);
1046 let mut sink = ArrowIpcSink::new(Arc::clone(&file), blob_bytes);
1047 if !reserved.is_empty() {
1048 sink = sink.with_reserved_builder(Box::new(move |_| Ok(reserved)));
1049 }
1050 if !paths.is_empty() {
1051 let batch = base_batch_from_rows(&paths, &locs)?;
1052 sink.push_subindex(
1053 data_subindex_schema().as_ref(),
1054 &[batch],
1055 GroupKey {
1056 pkg_type: 0,
1057 repo: String::new(),
1058 module_name: String::new(),
1059 },
1060 )?;
1061 }
1062 // `finish` fsyncs before it returns the total.
1063 let sealed_total_bytes = Box::new(sink).finish()?;
1064
1065 Ok(SealReport {
1066 archive: archive.to_path_buf(),
1067 packs_sealed,
1068 packs_retired,
1069 packs_after_copy,
1070 blob_bytes,
1071 sealed_total_bytes,
1072 })
1073 })();
1074
1075 let sealed = match sealed {
1076 Ok(s) => s,
1077 Err(e) => {
1078 let _ = std::fs::remove_file(&staged);
1079 return Err(e);
1080 }
1081 };
1082
1083 // (4) the archive's own name, atomically, and only now.
1084 std::fs::rename(&staged, archive).map_err(|e| {
1085 let _ = std::fs::remove_file(&staged);
1086 anyhow!(
1087 "renaming {} into place as {}: {e}",
1088 staged.display(),
1089 archive.display()
1090 )
1091 })?;
1092 sync_parent_dir(archive);
1093 Ok(sealed)
1094}
1095
1096/// blake3 over `(offset, len)` of `file`, streamed rather than buffered whole:
1097/// a consolidated pack is tens of megabytes and there is no reason for the seal
1098/// to hold one in memory to hash it.
1099fn blake3_extent(file: &File, offset: u64, len: u64) -> Result<[u8; 32]> {
1100 const WINDOW: usize = 1 << 20;
1101 let mut hasher = znippy_common::blake3::Hasher::new();
1102 let mut buf = vec![0u8; WINDOW.min(len.max(1) as usize)];
1103 let mut done = 0u64;
1104 while done < len {
1105 let want = ((len - done) as usize).min(buf.len());
1106 file.read_exact_at(&mut buf[..want], offset + done)
1107 .map_err(|e| anyhow!("reading the pack at ({offset}, {len}) to checksum it: {e}"))?;
1108 hasher.update(&buf[..want]);
1109 done += want as u64;
1110 }
1111 Ok(*hasher.finalize().as_bytes())
1112}
1113
1114/// A sibling name nothing else can be holding: pid and nanos, the same shape
1115/// `gc.rs` stages its compaction under.
1116fn staging_sibling(archive: &Path) -> PathBuf {
1117 let unique = std::time::SystemTime::now()
1118 .duration_since(std::time::UNIX_EPOCH)
1119 .map(|d| d.as_nanos())
1120 .unwrap_or(0);
1121 let mut p = archive.as_os_str().to_owned();
1122 p.push(format!(".seal-{}-{unique}", std::process::id()));
1123 PathBuf::from(p)
1124}
1125
1126/// fsync the directory so the rename is durable and not merely visible.
1127/// Best-effort, like `gc::sync_dir`: a filesystem that will not open a directory
1128/// is not a reason to fail a seal that otherwise succeeded.
1129fn sync_parent_dir(path: &Path) {
1130 if let Some(parent) = path.parent()
1131 && let Ok(f) = File::open(parent)
1132 {
1133 let _ = f.sync_all();
1134 }
1135}