release-kit 0.2.18

A canonical release workflow: a technology-agnostic method, per-technology bindings, and the rk CLI that lands and serves them.
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
//! The fenced two-file transaction behind `rk devshell sync`.
//!
//! The tag in `flake.nix` and the `release-kit` node in `flake.lock`
//! move together or not at all. Before the first write both files are
//! copied under the state root and a marker names the target and this
//! process; a build inside the transaction is the fence, so a pin that
//! does not build against the consumer's own nixpkgs never reaches the
//! tree. Any failure restores both files through the `Drop` guard, which
//! covers every `?`, every early return, and a panic. The crate forbids
//! `unsafe`, so no signal handler exists: a terminal interrupt during
//! the build leaves the marker, and the next run recovers from it.

use std::fs;
use std::path::{Path, PathBuf};

use camino::Utf8Path;

use super::{backup_dir, marker_path};
use crate::error::RkError;
use crate::maintenance::{GIT_HOOK_VARS, last_line};
use crate::probes::nix_bin;

/// The two files the transaction guards, in restore order.
const FILES: [&str; 2] = ["flake.nix", "flake.lock"];

/// A marker older than this whose owner procfs cannot judge is recovered
/// anyway: a build does not take a day.
const PENDING_GRACE: std::time::Duration = std::time::Duration::from_secs(24 * 60 * 60);

/// One failed step: which, and the child's last stderr line.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct StepFailure {
    /// `flake-update`, `current-system`, or `build`.
    pub step: &'static str,
    /// The child's last non-empty stderr line, or why it did not run.
    pub detail: String,
}

/// An open transaction: the backups exist and the marker names this
/// process. Dropping it without `commit` restores both files.
#[derive(Debug)]
pub struct Txn {
    target: PathBuf,
    backup: PathBuf,
    marker: PathBuf,
    committed: bool,
}

/// Open a transaction over the target's two files.
///
/// # Errors
///
/// Returns [`RkError::Io`] where the state root is unknown, the backup
/// cannot be written, or `flake.nix` cannot be copied.
pub fn open(target: &Utf8Path, key: &str) -> Result<Txn, RkError> {
    let (Some(backup), Some(marker)) = (backup_dir(key), marker_path(key)) else {
        return Err(RkError::Io(std::io::Error::other(
            "neither XDG_STATE_HOME nor HOME is set, so the transaction has no backup root",
        )));
    };
    open_at(target, backup, marker)
}

/// [`open`] with the state paths named, which is what the unit tests
/// use in place of the environment.
fn open_at(target: &Utf8Path, backup: PathBuf, marker: PathBuf) -> Result<Txn, RkError> {
    fs::create_dir_all(&backup)?;
    for name in FILES {
        let source = target.join(name);
        let copy = backup.join(name);
        if source.exists() {
            fs::copy(&source, &copy)?;
        } else if copy.exists() {
            fs::remove_file(&copy)?;
        }
    }
    // The marker records which files existed, so a restore never reads a
    // missing backup as "the file was absent" and deletes a real file.
    let record = serde_json::json!({
        "target": target.as_str(),
        "pid": std::process::id(),
        "present": {
            FILES[0]: target.join(FILES[0]).exists(),
            FILES[1]: target.join(FILES[1]).exists(),
        },
    });
    crate::atomic::write(&marker, record.to_string().as_bytes())?;
    Ok(Txn {
        target: target.as_std_path().to_path_buf(),
        backup,
        marker,
        committed: false,
    })
}

impl Txn {
    /// Keep the new contents and finish the transaction.
    ///
    /// # Errors
    ///
    /// The finishing failure: the marker could be neither neutralized
    /// nor removed, so it is still active beside its backups, and the
    /// caller must name it, because the next recovery would roll the
    /// finished bump back.
    pub fn commit(mut self) -> Result<(), FinishFailure> {
        self.committed = true;
        finish(&self.backup, &self.marker)
    }

    /// Put both files back and finish the transaction; the names restored.
    ///
    /// # Errors
    ///
    /// Where a file cannot be put back, the marker and the backups stay
    /// active for the next run's recovery. Where the files are back and
    /// the marker cannot be finished, the error says so: an active marker
    /// beside its backups would overwrite later edits on the next
    /// recovery.
    pub fn abort(mut self) -> Result<Vec<String>, AbortFailure> {
        self.committed = true;
        let restored =
            restore(&self.target, &self.backup, &self.marker).map_err(AbortFailure::Restore)?;
        finish(&self.backup, &self.marker).map_err(AbortFailure::Finish)?;
        Ok(restored)
    }

    /// The marker's path, for a report that must name it.
    #[must_use]
    pub fn marker(&self) -> &Path {
        &self.marker
    }
}

impl Drop for Txn {
    fn drop(&mut self) {
        if !self.committed {
            // Best effort on an unwinding path: a restore that fails, or a
            // finish that fails, keeps the material for the next run.
            if restore(&self.target, &self.backup, &self.marker).is_ok() {
                let _ = finish(&self.backup, &self.marker);
            }
        }
    }
}

/// Why an abort did not leave the target clean.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum AbortFailure {
    /// A file is not back; the marker and backups stay for recovery.
    Restore(RestoreFailure),
    /// Both files are back, and the marker is still active.
    Finish(FinishFailure),
}

/// A marker that could be neither neutralized nor removed.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct FinishFailure {
    /// The marker still active.
    pub marker: PathBuf,
    /// Why, one line.
    pub detail: String,
}

impl std::fmt::Display for FinishFailure {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(
            f,
            "the transaction marker {} is still active and must be removed by hand: {}",
            self.marker.display(),
            self.detail
        )
    }
}

/// Finish a transaction whose files are final — new after a commit, old
/// after a restore. The order is the discipline: first neutralize the
/// marker durably in place, so an interruption anywhere after this
/// point leaves a marker every later run reads as finished; then drop
/// the backups; then remove the marker. Nothing is deleted before the
/// marker is safe.
///
/// # Errors
///
/// The neutralizing write's failure: nothing was deleted, the marker is
/// still active beside its backups, and the caller names it.
fn finish(backup: &Path, marker: &Path) -> Result<(), FinishFailure> {
    if marker.exists() {
        // Whole or not at all: a temp file and a rename, so no
        // interruption leaves a truncated marker. Where the directory
        // refuses the rename, the in-place write is the last resort, and
        // a malformed marker is read as recoverable anyway.
        let neutralized = crate::atomic::write(marker, FINISHED_MARKER).or_else(|_| {
            fs::write(marker, FINISHED_MARKER).and_then(|()| {
                fs::OpenOptions::new()
                    .write(true)
                    .open(marker)
                    .and_then(|file| file.sync_all())
            })
        });
        if let Err(source) = neutralized {
            return Err(FinishFailure {
                marker: marker.to_path_buf(),
                detail: source.to_string(),
            });
        }
    }
    for name in FILES {
        let _ = fs::remove_file(backup.join(name));
    }
    let _ = fs::remove_dir(backup);
    let _ = fs::remove_file(marker);
    if let Some(parent) = marker.parent() {
        let _ = fs::remove_dir(parent);
    }
    Ok(())
}

/// The bytes a finished marker holds; a recovery reads it as done.
const FINISHED_MARKER: &[u8] = br#"{"committed":true}"#;

/// Whether a marker names a run still to recover.
///
/// It exists and is not a finished one. A finished marker that could not
/// be removed is residue, never a pending run, so it blocks nothing. Only
/// an absent marker reads as not pending; a marker that exists and cannot
/// be read is pending, because nothing proves it finished.
#[must_use]
pub fn marker_is_pending(marker: &Path) -> bool {
    match fs::read(marker) {
        Ok(bytes) => {
            serde_json::from_slice::<serde_json::Value>(&bytes)
                .ok()
                .and_then(|record| record["committed"].as_bool())
                != Some(true)
        }
        Err(source) => source.kind() != std::io::ErrorKind::NotFound,
    }
}

/// A restore that could not put a file back; the backups stay.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct RestoreFailure {
    /// The file that is not back.
    pub file: &'static str,
    /// Why, one line.
    pub detail: String,
}

impl std::fmt::Display for RestoreFailure {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{} could not be restored: {}", self.file, self.detail)
    }
}

/// Restore both files from the backup. A backed-up file is copied back;
/// a file the marker records as absent is removed; a file the marker
/// records as present with no backup to read is corruption, and the
/// restore stops there with the material kept. The names touched.
fn restore(target: &Path, backup: &Path, marker: &Path) -> Result<Vec<String>, RestoreFailure> {
    let record: serde_json::Value = fs::read(marker)
        .ok()
        .and_then(|bytes| serde_json::from_slice(&bytes).ok())
        .unwrap_or(serde_json::Value::Null);
    let mut restored = Vec::new();
    for name in FILES {
        let copy = backup.join(name);
        let destination = target.join(name);
        let was_present = record["present"][name].as_bool();
        let outcome = if copy.exists() {
            fs::read(&copy).and_then(|bytes| crate::atomic::write(&destination, &bytes))
        } else {
            match was_present {
                Some(false) if destination.exists() => fs::remove_file(&destination),
                Some(true) => Err(std::io::Error::other(
                    "the backup is missing although the file existed before the run",
                )),
                // No marker knowledge and no backup: leave the file alone.
                _ => continue,
            }
        };
        match outcome {
            Ok(()) => restored.push(name.to_owned()),
            Err(source) => {
                return Err(RestoreFailure {
                    file: name,
                    detail: source.to_string(),
                });
            }
        }
    }
    Ok(restored)
}

/// What a recovery attempt found.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Recovery {
    /// Both files are back and the marker is cleared; the names restored.
    Restored(Vec<String>),
    /// A file could not be put back; the marker and backups stay.
    Failed(RestoreFailure),
    /// Both files are back, and the marker could not be finished: it is
    /// still active, and the next recovery would overwrite later edits.
    Unfinished(FinishFailure),
    /// A finished transaction's marker was still there; nothing was
    /// restored, and the marker is gone or stays as residue that never
    /// reads as pending.
    Finished,
}

/// Recover a transaction an earlier run left open, where its owner is
/// provably gone.
///
/// `Ok(None)` where no marker exists or the owner may still be running.
/// The caller holds the checkout's lock, so two runs never recover the
/// same marker at once.
///
/// # Errors
///
/// Returns [`RkError::Io`] where the marker exists and does not read.
pub fn recover_pending(target: &Utf8Path, key: &str) -> Result<Option<Recovery>, RkError> {
    let (Some(backup), Some(marker)) = (backup_dir(key), marker_path(key)) else {
        return Ok(None);
    };
    recover_at(target, &backup, &marker)
}

/// [`recover_pending`] with the state paths named.
fn recover_at(
    target: &Utf8Path,
    backup: &Path,
    marker: &Path,
) -> Result<Option<Recovery>, RkError> {
    if !marker.exists() {
        return Ok(None);
    }
    let record: serde_json::Value =
        serde_json::from_slice(&fs::read(marker)?).unwrap_or(serde_json::Value::Null);
    if record["committed"].as_bool() == Some(true) {
        // A finished transaction whose marker could not be removed at
        // the time: finish it now, and recover nothing. Where it still
        // cannot go, it stays as residue that never reads as pending.
        let _ = finish(backup, marker);
        return Ok(Some(Recovery::Finished));
    }
    // A marker with no readable owner is a marker no live run wrote —
    // an open transaction writes its record whole before any step, and
    // the caller holds the checkout's lock — so it is recovered now
    // rather than after the grace period.
    let pid = record["pid"].as_u64();
    if pid.is_some() && !owner_gone(pid, marker) {
        return Ok(None);
    }
    match restore(target.as_std_path(), backup, marker) {
        Ok(restored) => match finish(backup, marker) {
            Ok(()) => Ok(Some(Recovery::Restored(restored))),
            Err(failure) => Ok(Some(Recovery::Unfinished(failure))),
        },
        Err(failure) => Ok(Some(Recovery::Failed(failure))),
    }
}

/// Whether a recorded owner is provably gone. Only a readable procfs
/// answer decides; where it cannot, a marker past the grace period is
/// treated as abandoned.
pub(crate) fn owner_gone(pid: Option<u64>, marker: &Path) -> bool {
    owner_gone_after(pid, marker, PENDING_GRACE)
}

/// [`owner_gone`] with the grace period named, for the lock's shorter one.
pub(crate) fn owner_gone_after(
    pid: Option<u64>,
    marker: &Path,
    grace: std::time::Duration,
) -> bool {
    if let Some(pid) = pid {
        if Path::new("/proc/self").is_dir() {
            match Path::new(&format!("/proc/{pid}")).try_exists() {
                Ok(true) => return false,
                Ok(false) => return true,
                Err(_) => {}
            }
        }
    }
    fs::metadata(marker)
        .and_then(|meta| meta.modified())
        .ok()
        .and_then(|modified| modified.elapsed().ok())
        .is_some_and(|age| age > grace)
}

/// `nix flake update release-kit`, refreshing the one node.
///
/// # Errors
///
/// The failing step with nix's last stderr line.
pub fn flake_update(target: &Utf8Path) -> Result<(), StepFailure> {
    nix(target, "flake-update", &["flake", "update", "release-kit"]).map(|_| ())
}

/// The concrete system attribute this host builds for, from nix itself:
/// guessing it from the compile target would be wrong on the systems
/// that matter.
///
/// # Errors
///
/// The failing step with nix's last stderr line.
pub fn current_system(target: &Utf8Path) -> Result<String, StepFailure> {
    let output = nix(
        target,
        "current-system",
        &[
            "eval",
            "--raw",
            "--impure",
            "--expr",
            "builtins.currentSystem",
        ],
    )?;
    let system = String::from_utf8_lossy(&output.stdout).trim().to_owned();
    if system.is_empty() {
        return Err(StepFailure {
            step: "current-system",
            detail: "nix eval answered no system".to_owned(),
        });
    }
    Ok(system)
}

/// `nix build --no-link` of the default devshell: the fence. `--no-link`
/// keeps a directory entry from dropping a `result` symlink.
///
/// # Errors
///
/// The failing step with nix's last stderr line.
pub fn build_devshell(target: &Utf8Path, system: &str) -> Result<(), StepFailure> {
    let attribute = format!(".#devShells.{system}.default");
    nix(target, "build", &["build", "--no-link", &attribute]).map(|_| ())
}

/// One nix launch against the target, through the shared resolver, with
/// the git hook variables scrubbed like every other child this crate
/// spawns against a named target.
fn nix(
    target: &Utf8Path,
    step: &'static str,
    args: &[&str],
) -> Result<std::process::Output, StepFailure> {
    let mut command = std::process::Command::new(nix_bin());
    for var in GIT_HOOK_VARS {
        command.env_remove(var);
    }
    let output = command
        .args(args)
        .current_dir(target.as_std_path())
        .output()
        .map_err(|source| StepFailure {
            step,
            detail: format!("nix did not run: {source}"),
        })?;
    if output.status.success() {
        Ok(output)
    } else {
        Err(StepFailure {
            step,
            detail: last_line(&output.stderr),
        })
    }
}

#[cfg(test)]
mod tests {
    #![allow(clippy::expect_used)]

    use camino::Utf8PathBuf;

    use super::{Recovery, open_at, owner_gone, recover_at};

    fn scratch() -> (tempfile::TempDir, Utf8PathBuf) {
        let dir = tempfile::tempdir().expect("a scratch dir exists");
        let path = Utf8PathBuf::from_path_buf(dir.path().to_path_buf()).expect("utf-8");
        (dir, path)
    }

    /// The `Drop` guard restores; a commit keeps.
    #[test]
    fn a_dropped_transaction_restores_and_a_committed_one_keeps() {
        let (_state, state) = scratch();
        let (_target, target) = scratch();
        let backup = state.join("backup").into_std_path_buf();
        let marker = state.join("pending.json").into_std_path_buf();
        let lock = target.join("flake.lock");
        std::fs::write(target.join("flake.nix"), "old\n").expect("writes");
        let txn = open_at(&target, backup.clone(), marker.clone()).expect("opens");
        assert!(marker.exists(), "an open transaction leaves its marker");
        std::fs::write(target.join("flake.nix"), "new\n").expect("writes");
        std::fs::write(&lock, "{}\n").expect("writes");
        drop(txn);
        assert_eq!(
            std::fs::read_to_string(target.join("flake.nix")).expect("reads"),
            "old\n"
        );
        assert!(
            !lock.exists(),
            "a lock that did not exist before is removed"
        );
        assert!(!marker.exists());
        let txn = open_at(&target, backup.clone(), marker.clone()).expect("opens");
        std::fs::write(target.join("flake.nix"), "new\n").expect("writes");
        txn.commit().expect("the marker clears");
        assert_eq!(
            std::fs::read_to_string(target.join("flake.nix")).expect("reads"),
            "new\n"
        );
        assert!(!backup.exists(), "a committed transaction leaves no backup");
        assert!(!marker.exists());
    }

    #[test]
    fn a_marker_with_a_dead_owner_is_recovered() {
        let (_state, state) = scratch();
        let (_target, target) = scratch();
        let backup = state.join("backup").into_std_path_buf();
        let marker = state.join("pending.json").into_std_path_buf();
        std::fs::write(target.join("flake.nix"), "old\n").expect("writes");
        let txn = open_at(&target, backup.clone(), marker.clone()).expect("opens");
        std::fs::write(target.join("flake.nix"), "half\n").expect("writes");
        // Forget the guard: stand in for a killed process.
        std::mem::forget(txn);
        std::fs::write(&marker, r#"{"target":"t","pid":4294967295}"#).expect("writes");
        let restored = recover_at(&target, &backup, &marker).expect("recovers");
        assert_eq!(
            restored,
            Some(Recovery::Restored(vec!["flake.nix".to_owned()]))
        );
        assert!(!marker.exists());
        assert_eq!(
            recover_at(&target, &backup, &marker).expect("recovers"),
            None
        );
        assert_eq!(
            std::fs::read_to_string(target.join("flake.nix")).expect("reads"),
            "old\n"
        );
    }

    /// A marker that records a file as present with no backup to read is
    /// corruption — never a file to delete — so a second recovery racing
    /// the first cannot remove what the first just put back.
    #[test]
    fn a_missing_backup_for_a_present_file_deletes_nothing() {
        let (_state, state) = scratch();
        let (_target, target) = scratch();
        let backup = state.join("backup").into_std_path_buf();
        let marker = state.join("pending.json").into_std_path_buf();
        std::fs::write(target.join("flake.nix"), "kept\n").expect("writes");
        std::fs::create_dir_all(&backup).expect("creates");
        std::fs::write(
            &marker,
            r#"{"pid":4294967295,"present":{"flake.nix":true,"flake.lock":false}}"#,
        )
        .expect("writes");
        let outcome = recover_at(&target, &backup, &marker).expect("judges");
        assert!(
            matches!(outcome, Some(Recovery::Failed(ref failure)) if failure.file == "flake.nix"),
            "{outcome:?}"
        );
        assert_eq!(
            std::fs::read_to_string(target.join("flake.nix")).expect("reads"),
            "kept\n"
        );
        assert!(marker.exists(), "the marker stays for a later recovery");
    }

    /// A restore that cannot write keeps its backups and its marker, and
    /// says which file is not back.
    #[test]
    fn a_failed_restore_keeps_its_material() {
        let (_state, state) = scratch();
        let (_target, target) = scratch();
        let backup = state.join("backup").into_std_path_buf();
        let marker = state.join("pending.json").into_std_path_buf();
        std::fs::write(target.join("flake.nix"), "old\n").expect("writes");
        let txn = open_at(&target, backup.clone(), marker.clone()).expect("opens");
        // A directory where the file must go back: the rename fails.
        std::fs::remove_file(target.join("flake.nix")).expect("removes");
        std::fs::create_dir(target.join("flake.nix")).expect("blocks");
        let failure = txn.abort().expect_err("the restore fails");
        assert!(
            matches!(failure, super::AbortFailure::Restore(ref inner) if inner.file == "flake.nix"),
            "{failure:?}"
        );
        assert!(marker.exists(), "the marker stays");
        assert!(backup.join("flake.nix").exists(), "the backup stays");
    }

    /// A marker that cannot be removed is neutralized in place before
    /// any backup goes: a later recovery reads it as finished and never
    /// rolls the committed bump back, and never overwrites a later edit.
    #[cfg(unix)]
    #[test]
    fn an_unremovable_marker_is_neutralized_before_the_backups_go() {
        use std::os::unix::fs::PermissionsExt as _;
        let (_state, state) = scratch();
        let (_target, target) = scratch();
        let dir = state.join("txn");
        std::fs::create_dir_all(&dir).expect("creates");
        let backup = dir.join("backup").into_std_path_buf();
        let marker = dir.join("pending.json").into_std_path_buf();
        std::fs::write(target.join("flake.nix"), "old\n").expect("writes");
        let txn = open_at(&target, backup.clone(), marker.clone()).expect("opens");
        std::fs::write(target.join("flake.nix"), "new\n").expect("writes");
        std::fs::set_permissions(&dir, std::fs::Permissions::from_mode(0o555)).expect("locks");
        let outcome = txn.commit();
        assert!(
            outcome.is_ok(),
            "the marker was neutralized in place: {outcome:?}"
        );
        assert!(marker.exists(), "the marker could not be removed");
        assert!(
            !backup.join("flake.nix").exists(),
            "no backup survives a commit"
        );
        std::fs::write(target.join("flake.nix"), "edited later\n").expect("writes");
        assert_eq!(
            recover_at(&target, &backup, &marker).expect("judges"),
            Some(Recovery::Finished),
            "a neutralized marker is a finished run, not a pending one"
        );
        std::fs::set_permissions(&dir, std::fs::Permissions::from_mode(0o755)).expect("unlocks");
        assert_eq!(
            std::fs::read_to_string(target.join("flake.nix")).expect("reads"),
            "edited later\n",
            "a later edit is never overwritten"
        );
    }

    /// A truncated marker — an interruption mid-write — with its backups
    /// intact is recovered on the next run, not after the grace period.
    #[test]
    fn a_malformed_marker_with_backups_is_recovered_now() {
        let (_state, state) = scratch();
        let (_target, target) = scratch();
        let backup = state.join("backup").into_std_path_buf();
        let marker = state.join("pending.json").into_std_path_buf();
        std::fs::write(target.join("flake.nix"), "old\n").expect("writes");
        let txn = open_at(&target, backup.clone(), marker.clone()).expect("opens");
        std::fs::write(target.join("flake.nix"), "half\n").expect("writes");
        std::mem::forget(txn);
        std::fs::write(&marker, "").expect("truncates");
        assert_eq!(
            recover_at(&target, &backup, &marker).expect("recovers"),
            Some(Recovery::Restored(vec!["flake.nix".to_owned()]))
        );
        assert_eq!(
            std::fs::read_to_string(target.join("flake.nix")).expect("reads"),
            "old\n"
        );
        assert!(!marker.exists());
    }

    /// A finished marker is residue, never a pending run, whether or not
    /// it can be removed.
    #[test]
    fn a_finished_marker_is_not_pending() {
        let (_state, state) = scratch();
        let marker = state.join("pending.json").into_std_path_buf();
        std::fs::write(&marker, super::FINISHED_MARKER).expect("writes");
        assert!(!super::marker_is_pending(&marker));
        std::fs::write(&marker, r#"{"pid":1}"#).expect("writes");
        assert!(super::marker_is_pending(&marker));
        std::fs::write(&marker, "").expect("writes");
        assert!(
            super::marker_is_pending(&marker),
            "a truncated marker is pending"
        );
        std::fs::remove_file(&marker).expect("removes");
        assert!(!super::marker_is_pending(&marker));
        // A marker that exists and cannot be read proves nothing finished.
        std::fs::create_dir(&marker).expect("a directory where the marker is");
        assert!(
            super::marker_is_pending(&marker),
            "an unreadable marker is pending"
        );
    }

    /// A finished marker left behind is cleared and reported as such.
    #[test]
    fn a_finished_marker_is_cleared_and_named() {
        let (_state, state) = scratch();
        let (_target, target) = scratch();
        let backup = state.join("backup").into_std_path_buf();
        let marker = state.join("pending.json").into_std_path_buf();
        std::fs::create_dir_all(&state).expect("creates");
        std::fs::write(&marker, super::FINISHED_MARKER).expect("writes");
        std::fs::write(target.join("flake.nix"), "new\n").expect("writes");
        assert_eq!(
            recover_at(&target, &backup, &marker).expect("judges"),
            Some(Recovery::Finished)
        );
        assert!(!marker.exists());
        assert_eq!(
            std::fs::read_to_string(target.join("flake.nix")).expect("reads"),
            "new\n"
        );
    }

    /// A marker that can be neither removed nor rewritten keeps every
    /// backup and is reported as still active; nothing is deleted first.
    #[cfg(unix)]
    #[test]
    fn a_marker_that_cannot_be_finished_keeps_its_backups_and_is_reported() {
        use std::os::unix::fs::PermissionsExt as _;
        let (_state, state) = scratch();
        let (_target, target) = scratch();
        let dir = state.join("txn");
        std::fs::create_dir_all(&dir).expect("creates");
        let backup = dir.join("backup").into_std_path_buf();
        let marker = dir.join("pending.json").into_std_path_buf();
        std::fs::write(target.join("flake.nix"), "old\n").expect("writes");
        let txn = open_at(&target, backup.clone(), marker.clone()).expect("opens");
        std::fs::set_permissions(&marker, std::fs::Permissions::from_mode(0o444)).expect("locks");
        std::fs::set_permissions(&dir, std::fs::Permissions::from_mode(0o555)).expect("locks");
        let outcome = txn.abort();
        std::fs::set_permissions(&dir, std::fs::Permissions::from_mode(0o755)).expect("unlocks");
        std::fs::set_permissions(&marker, std::fs::Permissions::from_mode(0o644)).expect("unlocks");
        assert!(
            matches!(outcome, Err(super::AbortFailure::Finish(_))),
            "{outcome:?}"
        );
        assert!(backup.join("flake.nix").exists(), "nothing was deleted");
        assert!(marker.exists());
    }

    #[test]
    fn a_live_owner_is_left_alone() {
        let (_dir, dir) = scratch();
        let marker = dir.join("pending.json");
        std::fs::write(&marker, "{}").expect("writes");
        if std::path::Path::new("/proc/self").is_dir() {
            assert!(!owner_gone(
                Some(u64::from(std::process::id())),
                marker.as_std_path()
            ));
            assert!(owner_gone(Some(4_294_967_295), marker.as_std_path()));
        }
        assert!(
            !owner_gone(None, marker.as_std_path()),
            "with no pid the grace period alone decides"
        );
    }
}