girt 0.16.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
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
use std::collections::{BTreeMap, BTreeSet};
use std::fs::OpenOptions;
use std::io::{self, Write};
use std::sync::atomic::AtomicBool;

use super::lock_wait::check_cancelled;
use super::store::{Lock, check_expected, conflicts, io_error, remove_loose, validate_target};
use super::{
    Expected, FilesTransactionOptions, LockWait, RefName, ReferenceError, References, Reflog,
    ReflogEntry, Target, packed, reflog,
};
use crate::ObjectId;

/// Which stored reference a conditional edit updates.
///
/// Choose [`Self::Stored`] when replacing the named symbolic spelling itself, and [`Self::Follow`]
/// when advancing its
/// terminal destination while preserving aliases. Preconditions and logging scope follow this
/// choice; changing it is not a mere convenience.
#[derive(Clone, Copy, Debug, Eq, PartialEq, Hash)]
#[non_exhaustive]
pub enum Dereference {
    /// Edit the named reference itself.
    Stored,
    /// Follow symbolic references and edit the terminal stored reference.
    Follow,
}

/// A conditional change to one stored name or one symbolic chain's terminal name.
///
/// ```
/// # use girt::refs::{Expected, RefEdit, RefName, Reflog, Target};
/// # use girt::{Commit, CommitFields, InitKind, ObjectFormat, Repository, Signature, Tree};
/// # let directory = tempfile::tempdir()?;
/// # let repo = Repository::init(ObjectFormat::Sha1, directory.path().join("r.git"), InitKind::Bare)?;
/// # let loose = repo.loose_objects();
/// # let person = Signature { name: b"A. Writer".to_vec(), email: b"a@example.com".to_vec(),
/// #                          seconds: 1_700_000_000, offset_minutes: 0 };
/// # let tree = loose.write_tree(&Tree::new(ObjectFormat::Sha1, vec![])?)?;
/// # let id = loose.write_commit(&Commit::new(CommitFields {
/// #     tree, parents: vec![], author: person.clone(), committer: person.clone(),
/// #     extra_headers: vec![], message: b"Initial snapshot\n".to_vec(),
/// # })?)?;
/// # let refs = repo.references()?;
/// # let main = RefName::new("refs/heads/main")?;
/// let head = RefName::HEAD;
/// let edit = RefEdit::new(head.clone(), Some(Target::Direct(id)), Expected::Absent,
///     Reflog::Append { committer: person, message: b"commit (initial)".to_vec() })
///     .with_dereference(girt::refs::Dereference::Follow);
/// refs.transaction(&[edit])?;
/// assert_eq!(refs.read(&head)?, Some(Target::Symbolic(main.clone())));
/// assert_eq!(refs.resolve(&head)?.id, Some(id));
/// assert_eq!(refs.reflog(&head)?.ok_or("HEAD log missing")?.len(), 1);
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
#[derive(Clone, Debug)]
#[non_exhaustive]
pub struct RefEdit {
    /// Initial name; also the destination when `dereference` is `Stored`.
    pub name: RefName,
    /// Follow up to 32 symbolic hops, keeping the chain unchanged.
    ///
    /// Only direct updates or deletion can be dereferenced. Preconditions apply to the terminal
    /// stored value. With `Stored`, a direct replacement with append logging still locks and
    /// resolves the old symbolic chain for the log identity, but edits/logs only `name` and checks
    /// the precondition against its stored value. Symbolic replacement locks both old and new
    /// chains to record their terminal IDs. Overlapping operations are rejected.
    pub dereference: Dereference,
    /// Replacement, or `None` to delete. Object existence/type is not checked.
    pub target: Option<Target>,
    /// Compared under locks before any publication.
    pub expected: Expected,
    /// Explicit history policy.
    pub reflog: Reflog,
}

impl RefEdit {
    /// Creates an edit of the stored name with explicit precondition and history policy.
    ///
    /// A `target` of `None` deletes the reference; `Some` replaces its stored target.
    /// See [`RefEdit`] for publication through HEAD and [`References::transaction`] for an
    /// expected-value update. Construction alone neither locks nor writes storage.
    pub fn new(name: RefName, target: Option<Target>, expected: Expected, reflog: Reflog) -> Self {
        Self {
            name,
            target,
            expected,
            reflog,
            dereference: crate::refs::Dereference::Stored,
        }
    }

    /// Creates `name` pointing at `id`, requiring that it doesn't exist yet.
    ///
    /// Equivalent to `RefEdit::new(name, Some(Target::Direct(id)), Expected::Absent, reflog)`,
    /// like `git update-ref <name> <id> ""`. Pass [`Repository::reflog_for`] as `reflog` to log
    /// as Git would by default. Use [`Self::new`] for a symbolic target.
    ///
    /// [`Repository::reflog_for`]: crate::Repository::reflog_for
    ///
    /// ```
    /// use girt::refs::{RefEdit, RefName, Reflog, Target};
    /// use girt::{InitKind, ObjectFormat, Repository};
    ///
    /// let directory = tempfile::tempdir()?;
    /// let repo = Repository::init(
    ///     ObjectFormat::Sha1,
    ///     directory.path().join("r.git"),
    ///     InitKind::Bare,
    /// )?;
    ///
    /// let id = repo.loose_objects().write_blob(b"release notes")?;
    /// let refs = repo.references()?;
    /// let tag = RefName::tag("notes")?;
    /// refs.transaction(&[RefEdit::create(tag.clone(), id, Reflog::Preserve)])?;
    /// assert_eq!(refs.read(&tag)?, Some(Target::Direct(id)));
    ///
    /// // A second create fails its precondition instead of replacing the tag.
    /// assert!(
    ///     refs.transaction(&[RefEdit::create(tag, id, Reflog::Preserve)])
    ///         .is_err()
    /// );
    /// # Ok::<(), Box<dyn std::error::Error>>(())
    /// ```
    pub fn create(name: RefName, id: ObjectId, reflog: Reflog) -> Self {
        Self::new(name, Some(Target::Direct(id)), Expected::Absent, reflog)
    }

    /// Moves `name` from `old` to `new`, requiring that it still points directly at `old`.
    ///
    /// Equivalent to
    /// `RefEdit::new(name, Some(Target::Direct(new)), Expected::Value(Target::Direct(old)),
    /// reflog)`, like `git update-ref <name> <new> <old>`. Note the argument order: `old` comes
    /// first here. This is a compare-and-swap, not a fast-forward check. A symbolic `name`
    /// fails the precondition; add [`Dereference::Follow`] with [`Self::with_dereference`] to
    /// move the branch it names.
    ///
    /// ```
    /// use girt::refs::{RefEdit, RefName, Reflog, Target};
    /// use girt::{InitKind, ObjectFormat, Repository};
    ///
    /// let directory = tempfile::tempdir()?;
    /// let repo = Repository::init(
    ///     ObjectFormat::Sha1,
    ///     directory.path().join("r.git"),
    ///     InitKind::Bare,
    /// )?;
    ///
    /// let loose = repo.loose_objects();
    /// let (first, second) = (loose.write_blob(b"one")?, loose.write_blob(b"two")?);
    ///
    /// let refs = repo.references()?;
    /// let branch = RefName::branch("topic")?;
    /// refs.transaction(&[RefEdit::create(branch.clone(), first, Reflog::Preserve)])?;
    /// refs.transaction(&[RefEdit::update(
    ///     branch.clone(),
    ///     first,
    ///     second,
    ///     Reflog::Preserve,
    /// )])?;
    /// assert_eq!(refs.read(&branch)?, Some(Target::Direct(second)));
    ///
    /// // `first` is stale now, so repeating the move fails without changing the branch.
    /// assert!(
    ///     refs.transaction(&[RefEdit::update(branch, first, second, Reflog::Preserve)])
    ///         .is_err()
    /// );
    /// # Ok::<(), Box<dyn std::error::Error>>(())
    /// ```
    pub fn update(name: RefName, old: ObjectId, new: ObjectId, reflog: Reflog) -> Self {
        Self::new(
            name,
            Some(Target::Direct(new)),
            Expected::Value(Target::Direct(old)),
            reflog,
        )
    }

    /// Deletes `name`, requiring that it still points directly at `old`.
    ///
    /// Equivalent to `RefEdit::new(name, None, Expected::Value(Target::Direct(old)), reflog)`, like
    /// `git update-ref -d <name> <old>`. Git deletes a branch's reflog with the branch; pass
    /// [`Reflog::Delete`] for that, or [`Reflog::Preserve`] to keep any log.
    ///
    /// ```
    /// use girt::refs::{RefEdit, RefName, Reflog};
    /// use girt::{InitKind, ObjectFormat, Repository};
    ///
    /// let directory = tempfile::tempdir()?;
    /// let repo = Repository::init(
    ///     ObjectFormat::Sha1,
    ///     directory.path().join("r.git"),
    ///     InitKind::Bare,
    /// )?;
    ///
    /// let id = repo.loose_objects().write_blob(b"draft")?;
    /// let refs = repo.references()?;
    /// let branch = RefName::branch("draft")?;
    /// refs.transaction(&[RefEdit::create(branch.clone(), id, Reflog::Preserve)])?;
    /// refs.transaction(&[RefEdit::delete(branch.clone(), id, Reflog::Delete)])?;
    /// assert_eq!(refs.read(&branch)?, None);
    /// # Ok::<(), Box<dyn std::error::Error>>(())
    /// ```
    pub fn delete(name: RefName, old: ObjectId, reflog: Reflog) -> Self {
        Self::new(name, None, Expected::Value(Target::Direct(old)), reflog)
    }

    /// Sets [`Self::name`].
    #[must_use]
    pub fn with_name(mut self, name: RefName) -> Self {
        self.name = name;
        self
    }

    /// Sets [`Self::dereference`].
    #[must_use]
    pub fn with_dereference(mut self, dereference: Dereference) -> Self {
        self.dereference = dereference;
        self
    }

    /// Sets [`Self::target`].
    #[must_use]
    pub fn with_target(mut self, target: Option<Target>) -> Self {
        self.target = target;
        self
    }

    /// Sets [`Self::expected`].
    #[must_use]
    pub fn with_expected(mut self, expected: Expected) -> Self {
        self.expected = expected;
        self
    }

    /// Sets [`Self::reflog`].
    #[must_use]
    pub fn with_reflog(mut self, reflog: Reflog) -> Self {
        self.reflog = reflog;
        self
    }
}

/// Reference publication state at the time a transaction returns.
///
/// Use this state with the matching log outcomes to diagnose publication. [`Self::Published`]
/// describes visibility, not power-loss durability; [`Self::PackedRemoved`] can already mean an
/// absent packed-only reference.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
#[non_exhaustive]
pub enum RefOutcome {
    /// No reference publication was attempted successfully for this operation.
    Unchanged,
    /// Its packed record was removed; loose publication/deletion has not succeeded.
    ///
    /// A packed-only reference is already absent. A loose shadow, if present, remains.
    PackedRemoved,
    /// Replacement or deletion completed, including deleting an already absent ref.
    Published,
}

/// Reflog mutation state at the time a transaction returns.
///
/// Inspect this state independently of reference publication. An advanced ref can have a failed or
/// partial log record; replaying the transaction can duplicate history rather than repair it.
#[derive(Clone, Debug, Eq, PartialEq)]
#[non_exhaustive]
pub enum LogOutcome {
    /// No log mutation was attempted.
    NotAttempted,
    /// The complete record was appended.
    Appended,
    /// The requested log is absent, including when already absent before deletion.
    Deleted,
    /// Mutation failed; this many record bytes were written before the failure.
    /// Deletion failures always report zero and preserve the log under the writer contract.
    ///
    /// Zero can still mean an empty log was created. A nonzero count can leave a malformed tail.
    Failed {
        /// Bytes from this record written before the error.
        bytes_written: usize,
    },
}

/// Effects for one input operation, retained in input order.
///
/// Retain these receipts after publication failure. Input order identifies the intended edits,
/// while each reference and log state describes actual effects; obtain fresh observations before
/// retrying.
#[derive(Clone, Debug, Eq, PartialEq)]
#[non_exhaustive]
pub struct RefEditOutcome {
    /// Terminal destination (or original name for a stored edit).
    pub name: RefName,
    /// Reference publication result.
    pub reference: RefOutcome,
    /// Requested logs in symbolic traversal order; empty for `Preserve` or a skipped
    /// conditional append policy.
    pub logs: Vec<(RefName, LogOutcome)>,
}

/// Failure before publication or a report of effects already made.
///
/// [`Self::Prepare`] leaves ref and log contents unchanged. [`Self::Publish`] retains exact
/// outcomes without rollback; a reference may have advanced while its reflog append failed.
/// Retain the outcomes in diagnostics and read fresh state before designing a retry. Replaying
/// the same batch blindly can overwrite intervening work or duplicate log entries.
///
/// ```
/// use girt::refs::{
///     Expected, RefEdit, RefName, RefOutcome, ReferenceError, Reflog, Target, TransactionError,
/// };
/// use girt::{InitKind, ObjectFormat, Repository};
///
/// let directory = tempfile::tempdir()?;
/// let repo = Repository::init(
///     ObjectFormat::Sha1,
///     directory.path().join("r.git"),
///     InitKind::Bare,
/// )?;
///
/// let refs = repo.references()?;
/// let name = RefName::new("refs/tags/result")?;
/// let id = repo.loose_objects().write_blob(b"build result")?;
///
/// let edit = RefEdit::new(
///     name.clone(),
///     Some(Target::Direct(id)),
///     Expected::Absent,
///     Reflog::Preserve,
/// );
///
/// let outcomes = refs.transaction(&[edit.clone()])?;
/// assert_eq!(outcomes[0].reference, RefOutcome::Published);
/// assert!(outcomes[0].logs.is_empty());
///
/// // A stale creation is refused before publication; don't replace it with Expected::Any.
/// assert!(matches!(
///     refs.transaction(&[edit]),
///     Err(TransactionError::Prepare {
///         operation: Some(0),
///         source: ReferenceError::Mismatch { .. },
///     })
/// ));
/// assert_eq!(refs.read(&name)?, Some(Target::Direct(id)));
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
#[derive(Debug, thiserror::Error)]
#[non_exhaustive]
pub enum TransactionError {
    /// No reference or log contents were changed. Empty directories can remain.
    #[error("reference transaction preparation failed")]
    Prepare {
        /// Input index when the failure belongs to one operation; otherwise a batch/lock failure.
        operation: Option<usize>,
        /// Validation, precondition, lock, or read failure.
        #[source]
        source: ReferenceError,
    },
    /// Publication stopped at the first error, without rollback.
    #[error("reference transaction publication failed")]
    Publish {
        /// Exact completed effects in caller order; later operations can have packed removals.
        outcomes: Vec<RefEditOutcome>,
        /// Underlying error. A loose unlink after packed removal retains `PackedDeleted`.
        #[source]
        source: ReferenceError,
    },
}

impl References<'_> {
    /// Applies a conditional batch with explicit reflog policy.
    ///
    /// Reftable publishes references and logs atomically within each stack, with explicit partial
    /// effects across linked-worktree stacks; see [`References`]. The remaining storage details
    /// below describe the files backend.
    ///
    /// Preparation holds `packed-refs.lock`, discovers symbolic chains, locks their union in
    /// name-byte order, and rechecks every stored chain value and precondition. Reflog locks follow
    /// in name-byte order. Duplicate/overlapping chains and ancestor/descendant names are rejected,
    /// including delete/create namespace swaps. Existing packed conflicts are rejected. Contended
    /// locks are retried for Git's default durations ([`FilesTransactionOptions::GIT_DEFAULT`]);
    /// locks are never stolen. A changed chain fails rather than being retried.
    ///
    /// Publication first removes all selected packed records in one replacement. It then publishes
    /// refs in caller order, appending each operation's requested logs after its ref succeeds.
    /// All owned locks remain held until return. Readers can observe any intermediate state.
    /// An I/O error stops publication, returning per-ref and per-log effects; no rollback occurs.
    /// In particular, a ref can advance with a missing or partial reflog entry.
    ///
    /// Logs use append writes, never whole-file replacement. Ref locks coordinate writers of the
    /// same destination; log locks coordinate girt transactions. Git can append automatic HEAD logs
    /// without honoring those log locks, so ordering against such appends is not promised. Reflog
    /// expiry and external log rewriting must be excluded by the caller while writing.
    /// `Reflog::Delete` removes only the edited destination's log after reference deletion.
    /// Direct branch edits do not automatically log HEAD or discover aliases; use a resolved HEAD
    /// edit to log that chain. A stored direct replacement with append logging locks and resolves
    /// the old symbolic chain, recording its terminal ID (zero when unborn) in only the edited
    /// name's log. Its precondition still compares the original stored value, and the old branch
    /// and its log remain unchanged. A stored symbolic replacement additionally locks the new
    /// chain and records its terminal ID, or zero if unborn. Stored symbolic deletion logs the
    /// old terminal ID and zero, without deleting the target.
    ///
    /// No hooks, config/environment policy, object validation, fsync, crash recovery, or
    /// filesystem-wide atomic visibility is provided. Cleanup is best effort; termination or
    /// cleanup failure can leave locks/temporary files. See [`References`] for filesystem trust.
    ///
    /// # Errors
    ///
    /// [`TransactionError::Prepare`] preserves ref/log contents on malformed data, invalid edits,
    /// precondition mismatch, namespace conflicts, or lock failure. [`TransactionError::Publish`]
    /// reports effects at meaningful publication boundaries. An empty batch is a successful no-op.
    ///
    /// ```
    /// # use girt::refs::{Expected, RefEdit, RefName, Reflog, Target};
    /// # use girt::{Commit, CommitFields, InitKind, ObjectFormat, Repository, Signature, Tree};
    /// # let directory = tempfile::tempdir()?;
    /// # let repo = Repository::init(ObjectFormat::Sha1, directory.path().join("r.git"), InitKind::Bare)?;
    /// # let loose = repo.loose_objects();
    /// # let person = Signature { name: b"A. Writer".to_vec(), email: b"a@example.com".to_vec(),
    /// #                          seconds: 1_700_000_000, offset_minutes: 0 };
    /// # let tree = loose.write_tree(&Tree::new(ObjectFormat::Sha1, vec![])?)?;
    /// # let id = loose.write_commit(&Commit::new(CommitFields {
    /// #     tree, parents: vec![], author: person.clone(), committer: person.clone(),
    /// #     extra_headers: vec![], message: b"Initial snapshot\n".to_vec(),
    /// # })?)?;
    /// # let refs = repo.references()?;
    /// # let main = RefName::new("refs/heads/main")?;
    /// # let edit = RefEdit::new(main.clone(), Some(Target::Direct(id)), Expected::Absent,
    /// #     Reflog::Append { committer: person, message: b"commit (initial)".to_vec() });
    /// # refs.transaction(&[edit])?;
    /// // Publish a child only if the branch still has the stored value we observed.
    /// let observed = refs.read(&main)?.ok_or("branch missing")?;
    ///
    /// let mut fields = loose.read_commit(id, 4096)?.to_fields()?;
    /// fields.parents = vec![id];
    /// fields.message = b"Next snapshot\n".to_vec();
    /// let next = loose.write_commit(&Commit::new(fields)?)?;
    ///
    /// let advance = RefEdit::new(main.clone(), Some(Target::Direct(next)), Expected::Value(observed),
    ///     Reflog::Append { committer: Signature { name: b"A".to_vec(), email: b"a@example.com".to_vec(),
    ///         seconds: 1_700_000_001, offset_minutes: 0 }, message: b"commit: next".to_vec() });
    /// refs.transaction(&[advance])?;
    /// assert_eq!(refs.read(&main)?, Some(Target::Direct(next)));
    /// # Ok::<(), Box<dyn std::error::Error>>(())
    /// ```
    pub fn transaction(&self, edits: &[RefEdit]) -> Result<Vec<RefEditOutcome>, TransactionError> {
        #[cfg(feature = "tracing")]
        let span = tracing::debug_span!(
            target: "girt",
            "refs.transaction",
            outcome = "incomplete",
            failure_class = tracing::field::Empty,
            effects = tracing::field::Empty,
            edits = edits.len(),
        );

        let operation = || {
            if edits.is_empty() {
                return Ok(Vec::new());
            }
            for (index, edit) in edits.iter().enumerate() {
                validate_edit(self.object_format, edit).map_err(|source| {
                    TransactionError::Prepare {
                        operation: Some(index),
                        source,
                    }
                })?;
            }
            self.prepare_transaction(edits)?.publish()
        };
        #[cfg(feature = "tracing")]
        let result = span.in_scope(operation);
        #[cfg(not(feature = "tracing"))]
        let result = { operation }();
        #[cfg(feature = "tracing")]
        crate::trace::finish(&span, &result, |error| {
            crate::trace::transaction(error, &span)
        });

        result
    }

    /// Applies a files-only transaction with cancellable, per-acquisition lock waits.
    ///
    /// Holds the packed lock first, then reference locks in name-byte order, then reflog locks
    /// in name-byte order. Each packed/reference acquisition gets its own configured budget;
    /// earlier locks remain held. Reflog contention always fails immediately. This sorted order
    /// need not match another writer's edit order, so contention timing can differ.
    ///
    /// Cancellation is checked before acquisitions, during waits at intervals of at most 20 ms
    /// excluding scheduling/filesystem delays, and after preparation before publication. Callers
    /// choosing [`LockWait::UntilCancelled`] must arrange cancellation if an unbounded wait is
    /// unacceptable. Cancellation does not interrupt publication once it starts.
    ///
    /// Uses the same locked rechecks, expected values, cleanup and publication as
    /// [`Self::transaction`]. It never refreshes preconditions or retries preparation/publication.
    /// No configuration or environment is read. The ordinary transaction entry point uses
    /// [`FilesTransactionOptions::GIT_DEFAULT`]; no-reflog single-name operations fail immediately.
    ///
    /// # Errors
    ///
    /// Reftable returns [`TransactionError::Prepare`] with [`ReferenceError::Unsupported`] before
    /// effects. Cancellation, timeout and other preparation failures preserve ref/log contents.
    /// Publication failures retain their effects in [`TransactionError::Publish`]; never retry
    /// them without inspecting current state.
    ///
    /// ```
    /// use std::sync::atomic::AtomicBool;
    ///
    /// use girt::refs::{Expected, FilesTransactionOptions, RefEdit, RefName, Reflog, Target};
    /// use girt::{InitKind, ObjectFormat, Repository};
    ///
    /// let directory = tempfile::tempdir()?;
    /// let repo = Repository::init(
    ///     ObjectFormat::Sha1,
    ///     directory.path().join("r.git"),
    ///     InitKind::Bare,
    /// )?;
    ///
    /// let id = repo.loose_objects().write_blob(b"manifest")?;
    /// let name = RefName::new("refs/tags/exported")?;
    /// let edits = [RefEdit::new(
    ///     name.clone(),
    ///     Some(Target::Direct(id)),
    ///     Expected::Absent,
    ///     Reflog::Preserve,
    /// )];
    ///
    /// let options = FilesTransactionOptions::GIT_DEFAULT.with_reference_lock_wait(
    ///     girt::refs::LockWait::For(std::time::Duration::from_millis(25)),
    /// ); // Shorten loose-ref waits while retaining the one-second packed-refs wait.
    /// let outcomes = repo.references()?.transaction_files_with_options(
    ///     &edits,
    ///     options,
    ///     &AtomicBool::new(false),
    /// )?;
    /// assert_eq!(outcomes.len(), 1);
    /// # Ok::<(), Box<dyn std::error::Error>>(())
    /// ```
    pub fn transaction_files_with_options(
        &self,
        edits: &[RefEdit],
        options: FilesTransactionOptions,
        cancel: &AtomicBool,
    ) -> Result<Vec<RefEditOutcome>, TransactionError> {
        self.transaction_files_with_log_identity(edits, options, cancel, LogIdentity::Resolved)
    }

    /// Applies a files-only transaction whose reflogs identify stored values without resolving
    /// symbolic references.
    ///
    /// Every edit must use [`Dereference::Stored`] and a direct
    /// replacement or deletion. The old reflog ID is the stored direct ID, or null for a
    /// symbolic or absent value; the new ID is the replacement ID, or null for deletion.
    /// Symbolic chains are never traversed or locked. Only the edited name is rechecked under
    /// its reference lock, and the caller's exact expected value remains authoritative.
    /// Conditional append policies compare stored targets.
    ///
    /// Uses the same packed-reference coordination, reflog selection, lock waits, cancellation,
    /// cleanup and publication outcomes as [`Self::transaction_files_with_options`]. In particular,
    /// existing-log selection happens under the log lock, and cancellation cannot interrupt
    /// publication once it starts. No caller-supplied reflog IDs are accepted.
    ///
    /// # Errors
    ///
    /// Rejects reftable, dereferencing edits and symbolic replacements before acquiring locks.
    /// All edits are validated before preparation. Preparation errors preserve reference and log
    /// contents; [`TransactionError::Publish`] reports any partial publication and must not be
    /// retried without inspecting current state.
    ///
    /// ```
    /// use std::sync::atomic::AtomicBool;
    ///
    /// use girt::refs::{Expected, FilesTransactionOptions, RefEdit, RefName, Reflog, Target};
    /// use girt::{InitKind, ObjectFormat, Repository, Signature};
    ///
    /// let directory = tempfile::tempdir()?;
    /// let repo = Repository::init(
    ///     ObjectFormat::Sha1,
    ///     directory.path().join("r.git"),
    ///     InitKind::Bare,
    /// )?;
    ///
    /// let old = repo.loose_objects().write_blob(b"old")?;
    /// let new = repo.loose_objects().write_blob(b"replacement")?;
    ///
    /// let refs = repo.references()?;
    /// let base = RefName::new("refs/tags/base")?;
    /// let alias = RefName::new("refs/tags/alias")?;
    /// refs.update_without_reflog(&base, Target::Direct(old), Expected::Absent)?;
    /// refs.update_without_reflog(&alias, Target::Symbolic(base.clone()), Expected::Absent)?;
    ///
    /// let edit = RefEdit::new(
    ///     alias.clone(),
    ///     Some(Target::Direct(new)),
    ///     Expected::Value(Target::Symbolic(base.clone())),
    ///     Reflog::Append {
    ///         committer: Signature {
    ///             name: b"A".to_vec(),
    ///             email: b"a@example.com".to_vec(),
    ///             seconds: 1_700_000_000,
    ///             offset_minutes: 0,
    ///         },
    ///         message: b"replace alias".to_vec(),
    ///     },
    /// );
    ///
    /// let outcomes = refs.transaction_files_with_stored_log_ids(
    ///     &[edit],
    ///     FilesTransactionOptions::default(),
    ///     &AtomicBool::new(false),
    /// )?;
    /// assert_eq!(outcomes[0].name, alias);
    ///
    /// let log = refs.reflog(&alias)?.ok_or("log absent")?;
    /// assert!(log[0].old.is_null()); // The stored old value was symbolic, not the resolved `old` ID.
    /// assert_eq!(log[0].new, new);
    /// assert_eq!(refs.read(&base)?, Some(Target::Direct(old))); // The target was never edited.
    ///
    /// # Ok::<(), Box<dyn std::error::Error>>(())
    /// ```
    pub fn transaction_files_with_stored_log_ids(
        &self,
        edits: &[RefEdit],
        options: FilesTransactionOptions,
        cancel: &AtomicBool,
    ) -> Result<Vec<RefEditOutcome>, TransactionError> {
        self.transaction_files_with_log_identity(edits, options, cancel, LogIdentity::Stored)
    }

    fn transaction_files_with_log_identity(
        &self,
        edits: &[RefEdit],
        options: FilesTransactionOptions,
        cancel: &AtomicBool,
        identity: LogIdentity,
    ) -> Result<Vec<RefEditOutcome>, TransactionError> {
        #[cfg(feature = "tracing")]
        let span = tracing::debug_span!(
            target: "girt", "refs.transaction", outcome = "incomplete",
            failure_class = tracing::field::Empty, effects = tracing::field::Empty,
            edits = edits.len(),
        );
        let operation = || {
            if self.reference_backend != super::Backend::Files {
                return Err(TransactionError::Prepare {
                    operation: None,
                    source: ReferenceError::Unsupported(
                        "files transaction options require files backend",
                    ),
                });
            }
            check_cancelled(cancel).map_err(|source| TransactionError::Prepare {
                operation: None,
                source,
            })?;
            if edits.is_empty() {
                return Ok(Vec::new());
            }
            for (index, edit) in edits.iter().enumerate() {
                if identity == LogIdentity::Stored
                    && (edit.dereference == crate::refs::Dereference::Follow
                        || matches!(edit.target, Some(Target::Symbolic(_))))
                {
                    return Err(TransactionError::Prepare {
                        operation: Some(index),
                        source: ReferenceError::Unsupported(
                            "stored log identities require non-dereferencing direct edits or deletions",
                        ),
                    });
                }
                validate_edit(self.object_format, edit).map_err(|source| {
                    TransactionError::Prepare {
                        operation: Some(index),
                        source,
                    }
                })?;
            }
            let prepared =
                self.prepare_files_transaction_with_options(edits, options, cancel, identity)?;
            check_cancelled(cancel).map_err(|source| TransactionError::Prepare {
                operation: None,
                source,
            })?;
            prepared.publish()
        };
        #[cfg(feature = "tracing")]
        let result = span.in_scope(operation);
        #[cfg(not(feature = "tracing"))]
        let result = operation();
        #[cfg(feature = "tracing")]
        crate::trace::finish(&span, &result, |error| {
            crate::trace::transaction(error, &span)
        });
        result
    }

    pub(crate) fn prepare_transaction(
        &self,
        edits: &[RefEdit],
    ) -> Result<PreparedBackend, TransactionError> {
        if self.reference_backend == super::Backend::Reftable {
            super::reftable::backend::prepare(self, edits).map(PreparedBackend::Reftable)
        } else {
            self.prepare_files_transaction(edits)
                .map(Box::new)
                .map(PreparedBackend::Files)
        }
    }

    pub(super) fn prepare_files_transaction(
        &self,
        edits: &[RefEdit],
    ) -> Result<Prepared, TransactionError> {
        self.prepare_files_transaction_with_options(
            edits,
            FilesTransactionOptions::GIT_DEFAULT,
            &AtomicBool::new(false),
            LogIdentity::Resolved,
        )
    }

    fn prepare_files_transaction_with_options(
        &self,
        edits: &[RefEdit],
        options: FilesTransactionOptions,
        cancel: &AtomicBool,
        identity: LogIdentity,
    ) -> Result<Prepared, TransactionError> {
        #[cfg(feature = "tracing")]
        let span = tracing::debug_span!(
            target: "girt",
            "refs.prepare_transaction",
            outcome = "incomplete",
            failure_class = tracing::field::Empty,
            effects = tracing::field::Empty,
        );

        let operation = || {
            let batch_error = |source| TransactionError::Prepare {
                operation: None,
                source,
            };
            let packed_lock = Lock::acquire_wait(
                self.common_dir.join("packed-refs"),
                options.packed_refs_lock_wait,
                cancel,
            )
            .map_err(batch_error)?;
            let packed = self
                .packed_at(&packed_lock.destination)
                .map_err(batch_error)?;
            let mut plans = Vec::new();
            let mut names = BTreeSet::new();
            for (index, edit) in edits.iter().enumerate() {
                let error = |source| TransactionError::Prepare {
                    operation: Some(index),
                    source,
                };
                let chain = self
                    .discover_chain(edit, &packed, identity)
                    .map_err(error)?;
                let new_chain = if let Some(Target::Symbolic(target)) = &edit.target
                    && edit.reflog.append_fields().is_some()
                {
                    let dependency = RefEdit {
                        name: target.clone(),
                        dereference: crate::refs::Dereference::Follow,
                        target: None,
                        expected: Expected::Any,
                        reflog: Reflog::Preserve,
                    };
                    let new_chain = self
                        .discover_chain(&dependency, &packed, LogIdentity::Resolved)
                        .map_err(error)?;
                    if new_chain.iter().any(|(name, _)| name == &edit.name) {
                        return Err(error(ReferenceError::Cycle(edit.name.clone())));
                    }
                    new_chain
                } else {
                    Vec::new()
                };
                let dependencies: BTreeSet<_> = chain
                    .iter()
                    .chain(&new_chain)
                    .map(|(name, _)| name)
                    .collect();
                for name in dependencies {
                    if !names.insert(name.clone())
                        || names
                            .iter()
                            .any(|other: &RefName| conflicts(name.as_bytes(), other.as_bytes()))
                    {
                        return Err(error(ReferenceError::Conflict(
                            self.path(name).map_err(error)?,
                        )));
                    }
                }
                plans.push((chain, new_chain));
            }

            let mut locks = BTreeMap::new();
            for name in names {
                self.check_packed_namespace(&name, &packed)
                    .map_err(batch_error)?;
                locks.insert(
                    name.clone(),
                    Lock::acquire_wait(
                        self.path(&name).map_err(batch_error)?,
                        options.reference_lock_wait,
                        cancel,
                    )
                    .map_err(batch_error)?,
                );
            }
            let mut operations = Vec::new();
            let mut log_names = BTreeSet::new();
            for (index, (edit, (chain, new_chain))) in edits.iter().zip(plans).enumerate() {
                let error = |source| TransactionError::Prepare {
                    operation: Some(index),
                    source,
                };
                for (name, observed) in chain.iter().chain(&new_chain) {
                    check_expected(
                        self.read_locked(name, &packed).map_err(error)?,
                        match observed {
                            Some(target) => Expected::Value(target.clone()),
                            None => Expected::Absent,
                        },
                    )
                    .map_err(error)?;
                }
                let (name, actual) = if edit.dereference == crate::refs::Dereference::Follow {
                    chain.last().unwrap()
                } else {
                    chain.first().unwrap()
                };
                check_expected(actual.clone(), edit.expected.clone()).map_err(error)?;
                let mut logs = Vec::new();
                let logged_chain = if edit.dereference == crate::refs::Dereference::Follow {
                    &chain[..]
                } else {
                    &chain[..1]
                };
                if edit.reflog.append_fields().is_some() {
                    log_names.extend(logged_chain.iter().map(|(name, _)| name.clone()));
                }
                let skip_log = matches!(
                    edit.reflog,
                    Reflog::AppendIfChanged { .. } | Reflog::AppendExistingIfChanged { .. }
                ) && actual == &edit.target;
                if let Some((committer, message)) = edit.reflog.append_fields()
                    && !skip_log
                {
                    // Resolved mode includes the terminal old value; stored mode has only the
                    // edited name. Every discovered value was rechecked under its lock.
                    let old = log_id(
                        self.object_format,
                        chain.last().unwrap().1.as_ref(),
                        identity,
                    )
                    .map_err(error)?;
                    let new_target = new_chain
                        .last()
                        .map_or(edit.target.as_ref(), |(_, value)| value.as_ref());
                    let new = log_id(self.object_format, new_target, identity).map_err(error)?;
                    let record = ReflogEntry {
                        old,
                        new,
                        committer: committer.clone(),
                        message: message.to_vec(),
                    };
                    let record = record.encode().map_err(error)?;
                    for (log_name, _) in logged_chain {
                        logs.push((log_name.clone(), record.clone()));
                    }
                }
                if edit.reflog == Reflog::Delete {
                    log_names.insert(name.clone());
                    logs.push((name.clone(), Vec::new()));
                }
                operations.push(Operation {
                    name: name.clone(),
                    target: edit.target.clone(),
                    delete_log: edit.reflog == Reflog::Delete,
                    packed_removed: edit.target.is_none() && packed.contains_key(name),
                    logs,
                });
            }
            let mut log_locks = BTreeMap::new();
            for name in log_names {
                let path = self.reflog_path(&name).map_err(batch_error)?;
                let lock =
                    Lock::acquire_wait(path, LockWait::Immediate, cancel).map_err(batch_error)?;
                log_locks.insert(name, lock);
            }
            for (operation, edit) in operations.iter_mut().zip(edits) {
                if matches!(edit.reflog, Reflog::AppendExistingIfChanged { .. }) {
                    // Presence is a transaction decision, never a caller's pre-read.
                    let mut existing = Vec::new();
                    for (name, record) in std::mem::take(&mut operation.logs) {
                        if self.has_reflog(&name).map_err(batch_error)? {
                            existing.push((name, record));
                        }
                    }
                    operation.logs = existing;
                }
                if !operation.delete_log {
                    for (name, _) in &operation.logs {
                        reflog::check_append_tail(&log_locks[name].destination)
                            .map_err(batch_error)?;
                    }
                }
            }
            // Publication rewrites `packed-refs` only when an operation removes a record.
            let mut replacement = Vec::new();
            if operations.iter().any(|operation| operation.packed_removed) {
                replacement.clone_from(&packed.bytes);
                for operation in &operations {
                    if operation.packed_removed {
                        replacement =
                            packed::without_ref(self.object_format, &replacement, &operation.name);
                    }
                }
            }
            Ok(Prepared {
                packed_lock,
                replacement,
                locks,
                log_locks,
                operations,
            })
        };
        #[cfg(feature = "tracing")]
        let result = span.in_scope(operation);
        #[cfg(not(feature = "tracing"))]
        let result = { operation }();
        #[cfg(feature = "tracing")]
        crate::trace::finish(&span, &result, |error| {
            crate::trace::transaction(error, &span)
        });

        result
    }

    fn discover_chain(
        &self,
        edit: &RefEdit,
        packed: &packed::Packed,
        identity: LogIdentity,
    ) -> Result<Vec<(RefName, Option<Target>)>, ReferenceError> {
        let resolve_old = identity == LogIdentity::Resolved
            && (edit.dereference == crate::refs::Dereference::Follow
                || edit.reflog.append_fields().is_some());
        let mut chain = Vec::new();
        let mut name = edit.name.clone();
        loop {
            if chain.iter().any(|(seen, _)| seen == &name) {
                return Err(ReferenceError::Cycle(name));
            }
            let target = self.read_locked(&name, packed)?;
            chain.push((name.clone(), target.clone()));
            match target {
                Some(Target::Symbolic(next)) if resolve_old => {
                    if chain.len() > 32 {
                        return Err(ReferenceError::Depth(32));
                    }
                    name = next;
                }
                _ => return Ok(chain),
            }
        }
    }
}

pub(super) fn validate_edit(
    format: crate::ObjectFormat,
    edit: &RefEdit,
) -> Result<(), ReferenceError> {
    super::store::validate_expected(format, &edit.expected)?;
    if edit.reflog == Reflog::Delete && edit.target.is_some() {
        return Err(ReferenceError::Unsupported(
            "log deletion requires reference deletion",
        ));
    }
    if let Some(target) = &edit.target {
        validate_target(format, target)?;
        if edit.name.as_bytes() == b"HEAD"
            && matches!(target, Target::Symbolic(next) if next.as_bytes() == b"HEAD")
        {
            return Err(ReferenceError::InvalidHeadTarget);
        }
        if edit.dereference == crate::refs::Dereference::Follow
            && matches!(target, Target::Symbolic(_))
        {
            return Err(ReferenceError::Unsupported("resolved symbolic replacement"));
        }
    }
    if let Some((committer, message)) = edit.reflog.append_fields() {
        reflog::validate(committer, message)?;
    }
    Ok(())
}

#[derive(Clone, Copy, Eq, PartialEq)]
enum LogIdentity {
    Resolved,
    Stored,
}

fn log_id(
    format: crate::ObjectFormat,
    target: Option<&Target>,
    identity: LogIdentity,
) -> Result<ObjectId, ReferenceError> {
    match target {
        Some(Target::Symbolic(_)) if identity == LogIdentity::Stored => Ok(ObjectId::null(format)),
        None => Ok(ObjectId::null(format)),
        Some(Target::Direct(id)) => Ok(*id),
        Some(Target::Symbolic(_)) => Err(ReferenceError::Unsupported(
            "stored symbolic edits with reflogs",
        )),
    }
}

struct Operation {
    name: RefName,
    target: Option<Target>,
    packed_removed: bool,
    delete_log: bool,
    logs: Vec<(RefName, Vec<u8>)>,
}

pub(crate) struct Prepared {
    packed_lock: Lock,
    replacement: Vec<u8>,
    locks: BTreeMap<RefName, Lock>,
    log_locks: BTreeMap<RefName, Lock>,
    operations: Vec<Operation>,
}

impl Prepared {
    pub(crate) fn publish(self) -> Result<Vec<RefEditOutcome>, TransactionError> {
        let _lock_operation = crate::locks::operation();
        #[cfg(feature = "tracing")]
        let span = tracing::debug_span!(
            target: "girt",
            "refs.publish",
            outcome = "incomplete",
            failure_class = tracing::field::Empty,
            effects = tracing::field::Empty,
        );

        let operation = || {
            let mut outcomes: Vec<_> = self
                .operations
                .iter()
                .map(|op| RefEditOutcome {
                    name: op.name.clone(),
                    reference: RefOutcome::Unchanged,
                    logs: op
                        .logs
                        .iter()
                        .map(|(name, _)| (name.clone(), LogOutcome::NotAttempted))
                        .collect(),
                })
                .collect();
            for lock in std::iter::once(&self.packed_lock)
                .chain(self.locks.values())
                .chain(self.log_locks.values())
            {
                lock.check_owned()
                    .map_err(|source| TransactionError::Publish {
                        outcomes: outcomes.clone(),
                        source,
                    })?;
            }
            if self.operations.iter().any(|op| op.packed_removed) {
                self.packed_lock
                    .publish_retaining_lock(&self.replacement)
                    .map_err(|source| TransactionError::Publish {
                        outcomes: outcomes.clone(),
                        source,
                    })?;
                for (operation, outcome) in self.operations.iter().zip(&mut outcomes) {
                    if operation.packed_removed {
                        outcome.reference = RefOutcome::PackedRemoved;
                    }
                }
            }
            for (index, operation) in self.operations.iter().enumerate() {
                let lock = &self.locks[&operation.name];
                let result = match &operation.target {
                    Some(target) => {
                        let bytes = match target {
                            Target::Direct(id) => format!("{id}\n").into_bytes(),
                            Target::Symbolic(name) => {
                                let mut bytes = b"ref: ".to_vec();
                                bytes.extend_from_slice(name.as_bytes());
                                bytes.push(b'\n');
                                bytes
                            }
                        };
                        lock.publish_retaining_lock(&bytes)
                    }
                    None => lock
                        .check_owned()
                        .and_then(|()| remove_loose(&lock.destination, operation.packed_removed)),
                };
                if let Err(source) = result {
                    return Err(TransactionError::Publish { outcomes, source });
                }
                outcomes[index].reference = RefOutcome::Published;
                for (log_index, (name, record)) in operation.logs.iter().enumerate() {
                    let path = &self.log_locks[name].destination;
                    let result = self.log_locks[name]
                        .check_owned()
                        .map_err(|error| (0, error))
                        .and_then(|()| {
                            if operation.delete_log {
                                remove_loose(path, false).map_err(|error| (0, error))
                            } else {
                                append(path, record)
                            }
                        });
                    match result {
                        Ok(()) => {
                            outcomes[index].logs[log_index].1 = if operation.delete_log {
                                LogOutcome::Deleted
                            } else {
                                LogOutcome::Appended
                            }
                        }
                        Err((bytes_written, source)) => {
                            outcomes[index].logs[log_index].1 =
                                LogOutcome::Failed { bytes_written };
                            return Err(TransactionError::Publish { outcomes, source });
                        }
                    }
                }
            }
            Ok(outcomes)
        };
        #[cfg(feature = "tracing")]
        let result = span.in_scope(operation);
        #[cfg(not(feature = "tracing"))]
        let result = { operation }();
        #[cfg(feature = "tracing")]
        crate::trace::finish(&span, &result, |error| {
            crate::trace::transaction(error, &span)
        });

        result
    }
}

fn append(path: &std::path::Path, record: &[u8]) -> Result<(), (usize, ReferenceError)> {
    let mut file = OpenOptions::new()
        .append(true)
        .create(true)
        .open(path)
        .map_err(|source| (0, io_error(path, source)))?;
    append_record(&mut file, record).map_err(|(count, source)| (count, io_error(path, source)))
}

// Keep byte progress explicit: write_all discards it on a short write followed by an error.
fn append_record(writer: &mut impl Write, record: &[u8]) -> Result<(), (usize, io::Error)> {
    let mut count = 0;
    while count < record.len() {
        match writer.write(&record[count..]) {
            Ok(0) => return Err((count, io::Error::from(io::ErrorKind::WriteZero))),
            Ok(written) => count += written,
            Err(error) if error.kind() == io::ErrorKind::Interrupted => {}
            Err(error) => return Err((count, error)),
        }
    }
    Ok(())
}

#[cfg(test)]
#[path = "transaction_tests.rs"]
mod tests;

pub(crate) enum PreparedBackend {
    Files(Box<Prepared>),
    Reftable(super::reftable::backend::Prepared),
}

impl PreparedBackend {
    pub(crate) fn publish(self) -> Result<Vec<RefEditOutcome>, TransactionError> {
        let _lock_operation = crate::locks::operation();
        match self {
            Self::Files(prepared) => prepared.publish(),
            Self::Reftable(prepared) => prepared.publish(),
        }
    }
}