girt 0.11.0

An incremental, idiomatic Rust implementation of Git
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
#![warn(
    clippy::unwrap_used,
    clippy::expect_used,
    clippy::panic,
    clippy::unreachable,
    clippy::indexing_slicing,
    reason = "parses untrusted repository or network input (#103)"
)]
use std::collections::{BTreeMap, BTreeSet};
use std::fs::{self, File};
use std::io::{Read, Write};
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicBool, Ordering};

use super::{Error, Limits, Table};
use crate::ObjectFormat;
use crate::refs::ReferenceError;
use crate::refs::store::{Lock, check_path, io_error, malformed};

/// Bounds shared by every table in one stack operation.
///
/// Use this bound for aggregate eager stack reads; more tables increase both opening work and
/// simultaneous file pins. A large byte budget does not waive a table-count refusal.
///
/// ```
/// use std::sync::atomic::AtomicBool;
///
/// use girt::refs::Backend;
/// use girt::refs::reftable::{Snapshot, StackLimits};
/// use girt::{InitKind, ObjectFormat, Repository};
/// let directory = tempfile::tempdir()?;
/// let repo = Repository::init_with_backend(
///     ObjectFormat::Sha1,
///     directory.path().join("r.git"),
///     InitKind::Bare,
///     Backend::Reftable,
/// )?;
/// let stack = repo.git_dir().join("reftable");
/// assert!(
///     Snapshot::read(
///         &stack,
///         ObjectFormat::Sha1,
///         StackLimits::default().with_tables(0),
///         &AtomicBool::new(false)
///     )
///     .is_err()
/// );
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
#[derive(Clone, Copy, Debug)]
#[non_exhaustive]
pub struct StackLimits {
    /// Maximum table count and simultaneously pinned file handles.
    pub tables: usize,
    /// Maximum bytes in `tables.list`.
    pub list_bytes: usize,
    /// Aggregate encoded, decoded and record limits, plus per-block/string limits.
    pub records: Limits,
}

impl StackLimits {
    /// Sets [`Self::tables`].
    #[must_use]
    pub fn with_tables(mut self, tables: usize) -> Self {
        self.tables = tables;
        self
    }

    /// Sets [`Self::list_bytes`].
    #[must_use]
    pub fn with_list_bytes(mut self, list_bytes: usize) -> Self {
        self.list_bytes = list_bytes;
        self
    }

    /// Sets [`Self::records`].
    #[must_use]
    pub fn with_records(mut self, records: Limits) -> Self {
        self.records = records;
        self
    }
}

impl Default for StackLimits {
    fn default() -> Self {
        Self {
            tables: 1024,
            list_bytes: 1024 * 1024,
            records: Limits::default(),
        }
    }
}

impl StackLimits {
    /// Returns generous finite stack bounds for caller-approved repository metadata.
    ///
    /// Table-count and list-byte limits retain arithmetic headroom, and decoding uses
    /// [`Limits::trusted`]. Reading pins all listed tables before decoding, so file-handle or
    /// allocation failures can occur well before these bounds. Prefer selected default-bound
    /// overrides when the application needs a predictable resource policy.
    pub const fn trusted() -> Self {
        Self {
            tables: usize::MAX / 4,
            list_bytes: usize::MAX / 4,
            records: Limits::trusted(),
        }
    }
}

/// An owned merged generation of a reftable stack.
///
/// Opening pins all listed files before reading their immutable contents. Once decoded, no file
/// handles remain. Existing snapshots remain usable after publication or compaction. A missing
/// listed file fails the single opening attempt; the caller may explicitly retry. In-place table
/// mutation, adversarial path replacement and network filesystems are outside this contract.
///
/// Prefer a snapshot for repeated reads from one generation. Ordinary reference operations open
/// fresh state; an old snapshot intentionally does not see later publications. Reading is eager
/// and bounded across the whole stack, rather than a lazy on-disk key lookup. See [`Self::read`]
/// for an executable repository example and [`compact`] for reducing the number of tables.
///
/// ```
/// use std::sync::atomic::AtomicBool;
///
/// use girt::refs::reftable::{Snapshot, StackLimits};
/// use girt::refs::{Backend, Expected, RefName, Target};
/// use girt::{InitKind, ObjectFormat, Repository};
/// let directory = tempfile::tempdir()?;
/// let repo = Repository::init_with_backend(
///     ObjectFormat::Sha1,
///     directory.path().join("r.git"),
///     InitKind::Bare,
///     Backend::Reftable,
/// )?;
/// let stack = repo.git_dir().join("reftable");
/// let before = Snapshot::read(
///     &stack,
///     ObjectFormat::Sha1,
///     StackLimits::default(),
///     &AtomicBool::new(false),
/// )?;
/// let tag = RefName::new("refs/tags/new")?;
/// let id = repo.loose_objects().write_blob(b"manifest")?;
/// repo.references()?
///     .update_without_reflog(&tag, Target::Direct(id), Expected::Absent)?;
/// assert!(
///     !before
///         .table
///         .references
///         .iter()
///         .any(|r| r.name.as_bytes() == tag.as_bytes())
/// );
/// assert!(repo.references()?.read(&tag)?.is_some());
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
#[derive(Clone, Debug)]
#[non_exhaustive]
pub struct Snapshot {
    /// Merged records, including tombstones. Newer tables override older records with the same
    /// key.
    pub table: Table,
    pub(super) names: Vec<String>,
    pub(super) used_bytes: usize,
    pub(super) used_records: usize,
    pub(super) used_decoded: usize,
}

impl Snapshot {
    /// Reads a stack directory using one bounded attempt.
    ///
    /// An absent `tables.list` denotes an empty stack. Names must be single ASCII file components
    /// ending in `.ref` or `.log`. Cancellation is checked between file opens, table decodes and
    /// merges; one bounded table decode may finish before cancellation is observed.
    ///
    /// # Errors
    ///
    /// Reports I/O, malformed names/order/data, format mismatch, cancellation and exhausted
    /// aggregate budgets. No filesystem mutation or automatic retry occurs.
    ///
    /// ```
    /// use std::sync::atomic::AtomicBool;
    ///
    /// use girt::refs::reftable::{Snapshot, StackLimits};
    /// use girt::refs::{Backend, Expected, RefName, Target};
    /// use girt::{InitKind, ObjectFormat, Repository};
    /// let directory = tempfile::tempdir()?;
    /// let repo = Repository::init_with_backend(
    ///     ObjectFormat::Sha256,
    ///     directory.path().join("r"),
    ///     InitKind::Bare,
    ///     Backend::Reftable,
    /// )?;
    /// let id = repo.loose_objects().write_blob(b"tagged")?;
    /// repo.references()?.update_without_reflog(
    ///     &RefName::new("refs/tags/one")?,
    ///     Target::Direct(id),
    ///     Expected::Absent,
    /// )?;
    /// let snapshot = Snapshot::read(
    ///     &repo.common_dir().join("reftable"),
    ///     ObjectFormat::Sha256,
    ///     StackLimits::default(),
    ///     &AtomicBool::new(false),
    /// )?;
    /// assert!(
    ///     snapshot
    ///         .table
    ///         .references
    ///         .iter()
    ///         .any(|record| record.target == Some(Target::Direct(id)))
    /// );
    /// # Ok::<(), Box<dyn std::error::Error>>(())
    /// ```
    pub fn read(
        directory: &Path,
        format: ObjectFormat,
        limits: StackLimits,
        cancel: &AtomicBool,
    ) -> Result<Self, ReferenceError> {
        #[cfg(feature = "tracing")]
        let span = tracing::debug_span!(target: "girt", "reftable.snapshot", outcome = "incomplete", failure_class = tracing::field::Empty);
        let operation = || Self::read_inner(directory, format, limits, cancel);
        #[cfg(feature = "tracing")]
        let result = span.in_scope(operation);
        #[cfg(not(feature = "tracing"))]
        let result = operation();
        #[cfg(feature = "tracing")]
        crate::trace::finish(&span, &result, crate::trace::reference);
        result
    }

    fn read_inner(
        directory: &Path,
        format: ObjectFormat,
        limits: StackLimits,
        cancel: &AtomicBool,
    ) -> Result<Self, ReferenceError> {
        cancelled(cancel)?;
        let directory = fs::canonicalize(directory).map_err(|error| io_error(directory, error))?;
        let directory = directory.as_path();
        let list_path = directory.join("tables.list");
        let bytes = match read_file(&list_path, limits.list_bytes) {
            Ok(bytes) => bytes,
            Err(ReferenceError::Io { source, .. })
                if source.kind() == std::io::ErrorKind::NotFound =>
            {
                Vec::new()
            }
            Err(error) => return Err(error),
        };
        let names = list(&bytes, limits, &list_path)?;
        let mut files = Vec::new();
        for name in &names {
            cancelled(cancel)?;
            let path = directory.join(name);
            check_path(&path)?;
            let file = File::open(&path).map_err(|error| io_error(&path, error))?;
            files.push((path, file));
        }
        let mut references = BTreeMap::new();
        let mut logs = BTreeMap::new();
        let mut remaining = limits.records;
        let mut min = 0;
        let mut max = 0;
        for (index, (path, mut file)) in files.into_iter().enumerate() {
            cancelled(cancel)?;
            let bytes = read_handle(&mut file, &path, remaining.bytes)?;
            let (table, record_count, decoded_bytes) = Table::decode_usage(&bytes, remaining)?;
            if table.format != format {
                return Err(Error::Malformed("stack hash format").into());
            }
            if index != 0 && table.min_update_index <= max {
                return Err(Error::Malformed("stack update order").into());
            }
            if index == 0 {
                min = table.min_update_index;
            }
            max = table.max_update_index;
            remaining.bytes -= bytes.len();
            remaining.records -= record_count;
            remaining.decoded_bytes -= decoded_bytes;
            for record in table.references {
                references.insert(record.name.clone(), record);
            }
            for record in table.logs {
                logs.insert(
                    (record.name.clone(), std::cmp::Reverse(record.update_index)),
                    record,
                );
            }
        }
        cancelled(cancel)?;
        Ok(Self {
            table: Table {
                format,
                min_update_index: min,
                max_update_index: max,
                references: references.into_values().collect(),
                logs: logs.into_values().collect(),
            },
            names,
            used_bytes: limits.records.bytes - remaining.bytes,
            used_records: limits.records.records - remaining.records,
            used_decoded: limits.records.decoded_bytes - remaining.decoded_bytes,
        })
    }
}

/// Completed compaction and obsolete files that could not be removed.
///
/// The replacement stack is already visible on success. Failed obsolete-file cleanup never
/// reverses publication. Retrying compaction is safe but is not an obsolete-file cleanup service.
/// See the [`reftable module example`](crate::refs::reftable#example) for a complete workflow.
#[derive(Debug)]
#[non_exhaustive]
pub struct Compaction {
    /// Number of input tables replaced.
    pub input_tables: usize,
    /// Obsolete file paths and unlink failures; callers may inspect them before later cleanup.
    pub retained: Vec<(PathBuf, std::io::Error)>,
}

/// Effects of a conditional, durable reflog-expiry stack rewrite.
#[cfg(unix)]
pub(crate) struct ExpiredStack {
    pub(crate) published: Vec<(PathBuf, Vec<u8>)>,
    pub(crate) removed: Vec<PathBuf>,
    pub(crate) retained: Vec<(PathBuf, std::io::Error)>,
}

/// A rejected or interrupted expiry rewrite.
#[cfg(unix)]
pub(crate) enum ExpireStackError {
    Changed,
    Failed {
        source: ReferenceError,
        /// The replacement list may be visible. Old tables remain listed or unlisted but intact.
        publication_uncertain: bool,
        /// The replacement list was visible and both it and the directory were synchronized.
        durable: bool,
    },
}

/// Replaces one stack with its live records minus selected reflog transaction keys.
///
/// The caller excludes noncooperating writers and old readers. This function acquires the stack
/// and table locks, compares the merged generation with `expected`, and leaves old tables intact
/// until the replacement table and `tables.list` have been synchronized. On a failed publication,
/// the caller must rescan before retrying.
#[cfg(unix)]
pub(crate) fn expire_logs(
    directory: &Path,
    format: ObjectFormat,
    limits: StackLimits,
    expected: &Snapshot,
    keys: &BTreeSet<(super::RecordName, u64)>,
    cancel: &AtomicBool,
) -> Result<ExpiredStack, ExpireStackError> {
    expire_logs_with_sync(
        directory,
        format,
        limits,
        expected,
        keys,
        cancel,
        sync_directory,
    )
}

#[cfg(unix)]
pub(super) fn expire_logs_with_sync(
    directory: &Path,
    format: ObjectFormat,
    limits: StackLimits,
    expected: &Snapshot,
    keys: &BTreeSet<(super::RecordName, u64)>,
    cancel: &AtomicBool,
    mut sync: impl FnMut(&Path) -> Result<(), ReferenceError>,
) -> Result<ExpiredStack, ExpireStackError> {
    let _lock_operation = crate::locks::operation();
    let fail = |source| ExpireStackError::Failed {
        source,
        publication_uncertain: false,
        durable: false,
    };
    cancelled(cancel).map_err(fail)?;
    let directory =
        fs::canonicalize(directory).map_err(|error| fail(io_error(directory, error)))?;
    let lock = Lock::acquire(directory.join("tables.list")).map_err(fail)?;
    let mut snapshot = Snapshot::read(&directory, format, limits, cancel).map_err(fail)?;
    if snapshot.names != expected.names || snapshot.table != expected.table {
        return Err(ExpireStackError::Changed);
    }
    let mut table_locks = Vec::new();
    for name in &snapshot.names {
        table_locks.push(Lock::acquire(directory.join(name)).map_err(fail)?);
    }
    cancelled(cancel).map_err(fail)?;
    let original_count = snapshot
        .table
        .logs
        .iter()
        .filter(|record| record.value.is_some())
        .count();
    snapshot
        .table
        .references
        .retain(|record| record.target.is_some());
    snapshot.table.logs.retain(|record| {
        record.value.is_some() && !keys.contains(&(record.name.clone(), record.update_index))
    });
    if original_count - snapshot.table.logs.len() != keys.len() {
        return Err(ExpireStackError::Changed);
    }
    let bytes = snapshot
        .table
        .encode(limits.records)
        .map_err(|error| fail(error.into()))?;
    cancelled(cancel).map_err(fail)?;
    let prefix = format!(
        "0x{:012x}-0x{:012x}-",
        snapshot.table.min_update_index, snapshot.table.max_update_index
    );
    let mut temporary = tempfile::Builder::new()
        .prefix(&prefix)
        .suffix(".ref")
        .tempfile_in(&directory)
        .map_err(|error| fail(io_error(&directory, error)))?;
    let permissions = fs::metadata(directory.join("tables.list"))
        .map_err(|error| fail(io_error(&directory, error)))?
        .permissions();
    temporary
        .as_file()
        .set_permissions(permissions)
        .map_err(|error| fail(io_error(temporary.path(), error)))?;
    temporary
        .write_all(&bytes)
        .and_then(|()| temporary.as_file().sync_all())
        .map_err(|error| fail(io_error(temporary.path(), error)))?;
    #[expect(
        clippy::unwrap_used,
        reason = "a named temporary file has a basename, and it is ASCII: the numeric prefix, \
                  tempfile's random portion and the suffix are all ASCII, whatever the ancestors"
    )]
    let name = temporary
        .path()
        .file_name()
        .unwrap()
        .to_str()
        .unwrap()
        .to_owned();
    let (_file, _path) = temporary
        .keep()
        .map_err(|error| fail(io_error(&directory, error.error)))?;
    sync(&directory).map_err(fail)?;
    cancelled(cancel).map_err(fail)?;
    let list = format!("{name}\n");
    if list.len() > limits.list_bytes {
        return Err(fail(Error::Limit("stack list bytes").into()));
    }
    lock.publish_retaining_lock(list.as_bytes())
        .map_err(|source| ExpireStackError::Failed {
            source,
            publication_uncertain: true,
            durable: false,
        })?;
    File::open(directory.join("tables.list"))
        .and_then(|file| file.sync_all())
        .map_err(|error| ExpireStackError::Failed {
            source: io_error(&directory, error),
            publication_uncertain: true,
            durable: false,
        })?;
    sync(&directory).map_err(|source| ExpireStackError::Failed {
        source,
        publication_uncertain: true,
        durable: false,
    })?;
    let mut retained = Vec::new();
    for name in &expected.names {
        let path = directory.join(name);
        if let Err(error) = fs::remove_file(&path) {
            retained.push((path, error));
        }
    }
    sync(&directory).map_err(|source| ExpireStackError::Failed {
        source,
        publication_uncertain: true,
        durable: true,
    })?;
    let removed = expected
        .names
        .iter()
        .map(|name| directory.join(name))
        .filter(|path| !retained.iter().any(|(kept, _)| kept == path))
        .collect();
    Ok(ExpiredStack {
        retained,
        removed,
        published: vec![
            (directory.join(&name), bytes),
            (directory.join("tables.list"), list.into_bytes()),
        ],
    })
}

#[cfg(unix)]
fn sync_directory(directory: &Path) -> Result<(), ReferenceError> {
    File::open(directory)
        .and_then(|file| file.sync_all())
        .map_err(|error| io_error(directory, error))
}

/// Compacts a complete stack while excluding cooperating writers and compactors.
///
/// Preserves all live reflog records and reference update indexes. Full-stack tombstones can be
/// discarded. Holds `tables.list.lock` and each input table's `.lock` until publication and cleanup
/// finish. No expiration, fsync, automatic retries or stale-lock stealing occurs. Cancellation
/// before list replacement leaves the old stack; after replacement cleanup runs to completion.
/// See the [`reftable module example`](crate::refs::reftable#example) for a runnable workflow.
///
/// # Errors
///
/// Errors preserve the old stack. An unlisted immutable table may remain if list publication fails;
/// readers ignore it. Lock cleanup is best effort and process termination can leave stale locks.
/// Successful publication with failed obsolete-file cleanup is returned as
/// [`Compaction::retained`].
///
/// # Compact a deletion without resurrecting an older value
///
/// A merged snapshot retains tombstones. Full-stack compaction covers every older table and can
/// drop them, while preserving live records and their update indexes.
///
/// ```
/// use std::sync::atomic::AtomicBool;
///
/// use girt::refs::reftable::{Snapshot, StackLimits, compact};
/// use girt::refs::{Backend, Expected, RefName, Target};
/// use girt::{InitKind, ObjectFormat, Repository};
///
/// let directory = tempfile::tempdir()?;
/// let path = directory.path().join("r");
/// let repo =
///     Repository::init_with_backend(ObjectFormat::Sha1, path, InitKind::Bare, Backend::Reftable)?;
/// let stack = repo.common_dir().join("reftable");
/// let cancel = AtomicBool::new(false);
///
/// let gone = RefName::new("refs/tags/gone")?;
/// let live = RefName::new("refs/tags/live")?;
/// let id = repo.loose_objects().write_blob(b"retained data")?;
/// let refs = repo.references()?;
/// for name in [&gone, &live] {
///     refs.update_without_reflog(name, Target::Direct(id), Expected::Absent)?;
/// }
/// refs.delete_without_reflog(&gone, Expected::Value(Target::Direct(id)))?;
/// let before = Snapshot::read(&stack, ObjectFormat::Sha1, StackLimits::default(), &cancel)?;
/// let tombstone = |record: &girt::refs::reftable::RefRecord| {
///     record.name.as_bytes() == gone.as_bytes() && record.target.is_none()
/// };
/// assert!(before.table.references.iter().any(tombstone));
/// let retained = before
///     .table
///     .references
///     .iter()
///     .find(|record| record.name.as_bytes() == live.as_bytes())
///     .unwrap()
///     .clone();
/// let report = compact(&stack, ObjectFormat::Sha1, StackLimits::default(), &cancel)?;
/// assert!(report.input_tables >= 2); // Each successful transaction publishes a table.
/// assert!(report.retained.is_empty());
/// let after = Snapshot::read(&stack, ObjectFormat::Sha1, StackLimits::default(), &cancel)?;
/// assert!(
///     !after
///         .table
///         .references
///         .iter()
///         .any(|record| record.name.as_bytes() == gone.as_bytes())
/// );
/// assert!(after.table.references.contains(&retained)); // Includes the original update index.
/// assert_eq!(refs.read(&gone)?, None);
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
pub fn compact(
    directory: &Path,
    format: ObjectFormat,
    limits: StackLimits,
    cancel: &AtomicBool,
) -> Result<Compaction, ReferenceError> {
    let _lock_operation = crate::locks::operation();
    #[cfg(feature = "tracing")]
    let span = tracing::debug_span!(target: "girt", "reftable.compact", outcome = "incomplete", failure_class = tracing::field::Empty);
    let operation = || compact_inner(directory, format, limits, cancel);
    #[cfg(feature = "tracing")]
    let result = span.in_scope(operation);
    #[cfg(not(feature = "tracing"))]
    let result = operation();
    #[cfg(feature = "tracing")]
    crate::trace::finish(&span, &result, crate::trace::reference);
    result
}

fn compact_inner(
    directory: &Path,
    format: ObjectFormat,
    limits: StackLimits,
    cancel: &AtomicBool,
) -> Result<Compaction, ReferenceError> {
    cancelled(cancel)?;
    let directory = fs::canonicalize(directory).map_err(|error| io_error(directory, error))?;
    let directory = directory.as_path();
    let lock = Lock::acquire(directory.join("tables.list"))?;
    let mut snapshot = Snapshot::read(directory, format, limits, cancel)?;
    let mut table_locks = Vec::new();
    for name in &snapshot.names {
        table_locks.push(Lock::acquire(directory.join(name))?);
    }
    let input_tables = snapshot.names.len();
    if input_tables == 0 {
        return Ok(Compaction {
            input_tables,
            retained: Vec::new(),
        });
    }
    snapshot
        .table
        .references
        .retain(|record| record.target.is_some());
    snapshot.table.logs.retain(|record| record.value.is_some());
    let bytes = snapshot.table.encode(limits.records)?;
    cancelled(cancel)?;
    publish(&lock, &[], &snapshot.table, &bytes, limits)?;
    let mut retained = Vec::new();
    for name in &snapshot.names {
        let path = directory.join(name);
        if let Err(error) = fs::remove_file(&path) {
            retained.push((path, error));
        }
    }
    Ok(Compaction {
        input_tables,
        retained,
    })
}

pub(super) fn publish(
    lock: &Lock,
    names: &[String],
    table: &Table,
    bytes: &[u8],
    limits: StackLimits,
) -> Result<(), ReferenceError> {
    publish_with(lock, names, table, bytes, limits, || Ok(()))
}

pub(super) fn publish_with(
    lock: &Lock,
    names: &[String],
    table: &Table,
    bytes: &[u8],
    limits: StackLimits,
    before_list: impl FnOnce() -> std::io::Result<()>,
) -> Result<(), ReferenceError> {
    let _lock_operation = crate::locks::operation();
    if names.len() >= limits.tables {
        return Err(Error::Limit("stack table count").into());
    }
    #[expect(
        clippy::unwrap_used,
        reason = "tables.list lies inside the reftable directory"
    )]
    let directory = lock.destination.parent().unwrap();
    let prefix = format!(
        "0x{:012x}-0x{:012x}-",
        table.min_update_index, table.max_update_index
    );
    let mut temporary = tempfile::Builder::new()
        .prefix(&prefix)
        .suffix(".ref")
        .tempfile_in(directory)
        .map_err(|error| io_error(directory, error))?;
    temporary
        .write_all(bytes)
        .map_err(|error| io_error(temporary.path(), error))?;
    #[expect(
        clippy::unwrap_used,
        reason = "a named temporary file has a basename, and it is ASCII: the numeric prefix, \
                  tempfile's random portion and the suffix are all ASCII, whatever the ancestors"
    )]
    let name = temporary
        .path()
        .file_name()
        .unwrap()
        .to_str()
        .unwrap()
        .to_owned();
    let mut list = names.join("\n").into_bytes();
    if !list.is_empty() {
        list.push(b'\n');
    }
    list.extend_from_slice(name.as_bytes());
    list.push(b'\n');
    if list.len() > limits.list_bytes {
        return Err(Error::Limit("stack list bytes").into());
    }
    // Retain the uniquely named immutable file before making it reachable from the list.
    let (_file, _path) = temporary
        .keep()
        .map_err(|error| io_error(directory, error.error))?;
    before_list().map_err(|error| io_error(&lock.destination, error))?;
    lock.publish_retaining_lock(&list)
}

fn list(bytes: &[u8], limits: StackLimits, path: &Path) -> Result<Vec<String>, ReferenceError> {
    if bytes.is_empty() {
        return Ok(Vec::new());
    }
    let body = bytes
        .strip_suffix(b"\n")
        .ok_or_else(|| malformed(path, "unterminated stack list"))?;
    let mut names = Vec::new();
    let mut seen = BTreeSet::new();
    for line in body.split(|b| *b == b'\n') {
        if names.len() == limits.tables {
            return Err(Error::Limit("stack table count").into());
        }
        if line.is_empty()
            || !line
                .iter()
                .all(|b| b.is_ascii_alphanumeric() || matches!(b, b'-' | b'_' | b'.'))
            || line.starts_with(b".")
            || !(line.ends_with(b".ref") || line.ends_with(b".log"))
        {
            return Err(malformed(path, "invalid stack table filename"));
        }
        let name = std::str::from_utf8(line)
            .map_err(|_| malformed(path, "invalid stack table filename"))?
            .to_owned();
        if !seen.insert(name.clone()) {
            return Err(malformed(path, "duplicate stack table"));
        }
        names.push(name);
    }
    Ok(names)
}

fn read_file(path: &Path, limit: usize) -> Result<Vec<u8>, ReferenceError> {
    check_path(path)?;
    let mut file = File::open(path).map_err(|error| io_error(path, error))?;
    read_handle(&mut file, path, limit)
}

fn read_handle(file: &mut File, path: &Path, limit: usize) -> Result<Vec<u8>, ReferenceError> {
    let length = file
        .metadata()
        .map_err(|error| io_error(path, error))?
        .len();
    if length > limit as u64 {
        return Err(Error::Limit("stack bytes").into());
    }
    let mut bytes = Vec::new();
    file.take((limit as u64).saturating_add(1))
        .read_to_end(&mut bytes)
        .map_err(|error| io_error(path, error))?;
    if bytes.len() > limit {
        return Err(Error::Limit("stack bytes").into());
    }
    Ok(bytes)
}

pub(super) fn cancelled(cancel: &AtomicBool) -> Result<(), ReferenceError> {
    if cancel.load(Ordering::Relaxed) {
        Err(ReferenceError::Cancelled)
    } else {
        Ok(())
    }
}