dora-core 1.0.0

`dora` goal is to be a low latency, composable, and distributed data flow.
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
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
use crate::build::{BuildLogger, PrevGitSource};
use dora_message::{DataflowId, SessionId, common::LogLevel};
use eyre::{ContextCompat, WrapErr, bail};
use git2::FetchOptions;
use itertools::Itertools;
use std::{
    collections::{BTreeMap, BTreeSet},
    path::{Path, PathBuf},
    sync::{
        Arc, Mutex,
        atomic::{AtomicU64, Ordering},
    },
};
use url::Url;

#[derive(Default)]
pub struct GitManager {
    /// Directories that are currently in use by running dataflows.
    pub clones_in_use: BTreeMap<PathBuf, BTreeSet<DataflowId>>,
    /// Builds that are prepared, but not done yet.
    prepared_builds: BTreeMap<SessionId, PreparedBuild>,
    /// Clone dirs that some `GitFolder` is actively writing into right now,
    /// process-wide, across every build session, with a count of how many
    /// writers claimed each dir. A `NewClone`/`CopyAndFetch`/`RenameAndFetch`
    /// claims its target dir here as soon as it's chosen and releases it once
    /// that `GitFolder` is dropped (its clone/fetch task finished, failed, or
    /// got cancelled). `prepared_builds` alone can't answer "is anyone
    /// writing to this dir right now": it's scoped by SessionId and a
    /// session's entries linger until that same session happens to build
    /// again, which for a one-shot session never happens. Gating the Reuse
    /// HEAD-check on that instead would let a stale dir shed verification
    /// forever the moment any session had ever planned it (#2711).
    ///
    /// This counts instead of tracking membership because two sessions can
    /// both choose a writing arm for the same dir before it exists on disk;
    /// with a plain set the first claim to drop would strip the protection
    /// while the second writer is still going.
    clones_in_progress: Arc<Mutex<BTreeMap<PathBuf, usize>>>,
    // reuse_for: BTreeMap<PathBuf, PathBuf>,
}

/// Releases a `clones_in_progress` claim when the owning `GitFolder` is
/// dropped, whatever the reason (clone finished, failed, or was cancelled).
struct InProgressClaim {
    dir: PathBuf,
    claims: Arc<Mutex<BTreeMap<PathBuf, usize>>>,
}

impl Drop for InProgressClaim {
    fn drop(&mut self) {
        let mut claims = lock_in_progress(&self.claims);
        if let Some(count) = claims.get_mut(&self.dir) {
            *count -= 1;
            if *count == 0 {
                claims.remove(&self.dir);
            }
        }
    }
}

/// Locks `clones_in_progress`, recovering from poisoning instead of
/// panicking. A panic elsewhere while this lock was held must not leave the
/// map stuck: `InProgressClaim::drop` runs during unwinding, where a panic
/// here would abort the process, and any panic-on-poison here would also
/// leave the dir's claim permanently unreleased, exempting it from
/// verification forever.
fn lock_in_progress(
    claims: &Mutex<BTreeMap<PathBuf, usize>>,
) -> std::sync::MutexGuard<'_, BTreeMap<PathBuf, usize>> {
    claims
        .lock()
        .unwrap_or_else(|poisoned| poisoned.into_inner())
}

#[derive(Default)]
struct PreparedBuild {
    /// Clone dirs that will be created during the build process.
    ///
    /// This allows subsequent nodes to reuse the dirs.
    planned_clone_dirs: BTreeSet<PathBuf>,
}

impl GitManager {
    pub fn choose_clone_dir(
        &mut self,
        session_id: SessionId,
        repo: String,
        commit_hash: String,
        prev_git: Option<PrevGitSource>,
        target_dir: &Path,
    ) -> eyre::Result<GitFolder> {
        let repo_url = Url::parse(&repo).context("failed to parse git repository URL")?;
        let clone_dir = Self::clone_dir_path(target_dir, &repo_url, &commit_hash)?;

        let prev_commit_hash = prev_git
            .as_ref()
            .filter(|p| p.git_source.repo == repo)
            .map(|p| &p.git_source.commit_hash);

        if let Some(using) = self.clones_in_use.get(&clone_dir)
            && !using.is_empty()
        {
            // The directory is currently in use by another dataflow. Rebuilding
            // while a dataflow is running could lead to unintended behavior.
            eyre::bail!(
                "the build directory is still in use by the following \
                    dataflows, please stop them before rebuilding: {}",
                using.iter().join(", ")
            )
        }

        let reuse = if self.clone_dir_ready(session_id, &clone_dir) {
            // The directory already contains a checkout of the commit we're interested in.
            // So we can simply reuse the directory without doing any additional git
            // operations.
            //
            // Only hand down a commit to verify (see the Reuse arm) when nobody is
            // actively writing to this dir right now. A dir that's still being
            // cloned into -- by a sibling node in this session, or by an entirely
            // different, concurrently-running session sharing this daemon's
            // GitManager -- must never have its HEAD checked or be deleted, so I
            // skip verification and just reuse it, same as before this change.
            let in_progress = lock_in_progress(&self.clones_in_progress).contains_key(&clone_dir);
            ReuseOptions::Reuse {
                dir: clone_dir.clone(),
                verify_commit: (!in_progress).then_some(commit_hash),
            }
        } else if let Some(previous_commit_hash) = prev_commit_hash {
            // we might be able to update a previous clone
            let prev_clone_dir = Self::clone_dir_path(target_dir, &repo_url, previous_commit_hash)?;

            if prev_clone_dir.exists() {
                let still_needed = prev_git
                    .map(|g| g.still_needed_for_this_build)
                    .unwrap_or(false);
                let used_by_others = self
                    .clones_in_use
                    .get(&prev_clone_dir)
                    .map(|ids| !ids.is_empty())
                    .unwrap_or(false);
                if still_needed || used_by_others {
                    // previous clone is still in use -> we cannot rename it, but we can copy it
                    ReuseOptions::CopyAndFetch {
                        from: prev_clone_dir,
                        target_dir: clone_dir.clone(),
                        commit_hash,
                    }
                } else {
                    // there is an unused previous clone that is no longer needed -> rename it
                    ReuseOptions::RenameAndFetch {
                        from: prev_clone_dir,
                        target_dir: clone_dir.clone(),
                        commit_hash,
                    }
                }
            } else {
                // no existing clone associated with previous build id
                ReuseOptions::NewClone {
                    target_dir: clone_dir.clone(),
                    repo_url,
                    commit_hash,
                }
            }
        } else {
            // no previous build that we can reuse
            ReuseOptions::NewClone {
                target_dir: clone_dir.clone(),
                repo_url,
                commit_hash,
            }
        };
        self.register_ready_clone_dir(session_id, clone_dir.clone());

        // Claim the dir as in-progress for every arm that's about to write
        // into it, so a concurrent Reuse elsewhere skips verification instead
        // of racing the write.
        let claim = matches!(
            reuse,
            ReuseOptions::NewClone { .. }
                | ReuseOptions::CopyAndFetch { .. }
                | ReuseOptions::RenameAndFetch { .. }
        )
        .then(|| {
            *lock_in_progress(&self.clones_in_progress)
                .entry(clone_dir.clone())
                .or_insert(0) += 1;
            InProgressClaim {
                dir: clone_dir,
                claims: self.clones_in_progress.clone(),
            }
        });

        Ok(GitFolder {
            reuse,
            _claim: claim,
        })
    }

    pub fn clone_dir_ready(&self, session_id: SessionId, dir: &Path) -> bool {
        self.prepared_builds
            .get(&session_id)
            .map(|p| p.planned_clone_dirs.contains(dir))
            .unwrap_or(false)
            || dir.exists()
    }

    pub fn register_ready_clone_dir(&mut self, session_id: SessionId, dir: PathBuf) -> bool {
        self.prepared_builds
            .entry(session_id)
            .or_default()
            .planned_clone_dirs
            .insert(dir)
    }

    fn clone_dir_path(
        base_dir: &Path,
        repo_url: &Url,
        commit_hash: &String,
    ) -> eyre::Result<PathBuf> {
        // file:// URLs (local mirrors, air-gapped setups, tests) have no
        // hostname — group their clones under a "localhost" directory
        let host = repo_url.host_str().unwrap_or("localhost");
        let mut path = base_dir.join(sanitize_dir_component(host));
        // A `file:///C:/...` URL parses with the drive letter (`C:`) as its
        // first path segment; the colon makes that an unnameable directory on
        // Windows (#2742). Sanitize every component so the cache path is legal
        // on all platforms — a no-op for normal `https://host/owner/repo` URLs,
        // whose segments carry no reserved characters.
        path.extend(
            repo_url
                .path_segments()
                .context("no path in git URL")?
                .map(sanitize_dir_component),
        );
        let path = path.join(commit_hash);
        Ok(dunce::simplified(&path).to_owned())
    }

    pub fn clear_planned_builds(&mut self, session_id: SessionId) {
        self.prepared_builds.remove(&session_id);
    }
}

pub struct GitFolder {
    /// Specifies whether an existing repo should be reused.
    reuse: ReuseOptions,
    /// Held for as long as this `GitFolder` is writing to its clone dir;
    /// releases the `clones_in_progress` claim on drop. `None` for the Reuse
    /// arm, which never writes.
    _claim: Option<InProgressClaim>,
}

impl GitFolder {
    pub async fn prepare(self, logger: &mut impl BuildLogger) -> eyre::Result<PathBuf> {
        let GitFolder { reuse, _claim } = self;

        tracing::info!("reuse: {reuse:?}");
        let clone_dir = match reuse {
            ReuseOptions::NewClone {
                target_dir,
                repo_url,
                commit_hash,
            } => {
                logger
                    .log_message(
                        LogLevel::Info,
                        format!(
                            "cloning {repo_url}#{commit_hash} into {}",
                            target_dir.display()
                        ),
                    )
                    .await;

                // Clone into a temporary sibling dir and only atomically
                // `rename` it into `target_dir` once the checkout has fully
                // succeeded (see `promote_clone`). A crash mid-clone then leaves
                // a half-written repo under the temp name, never at `target_dir`.
                let tmp_dir = partial_clone_path(&target_dir);

                let clone_target = tmp_dir.clone();
                let checkout_result = match tokio::task::spawn_blocking(move || {
                    let repository = clone_into(repo_url.clone(), &clone_target)
                        .with_context(|| format!("failed to clone git repo from `{repo_url}`"))?;
                    checkout_tree(&repository, &commit_hash)
                        .with_context(|| format!("failed to checkout commit `{commit_hash}`"))
                    // `repository` is dropped here, before the rename in
                    // `promote_clone`, so no git2 handles remain open on the temp
                    // dir (Windows refuses to rename a dir with open handles).
                })
                .await
                {
                    Ok(result) => result,
                    // A panic in the blocking clone/checkout task must not abort the
                    // whole build: route it through the same cleanup + `bail!` arm as
                    // an ordinary clone error so we don't leave a half-written clone
                    // behind for the next build to reuse (#2480).
                    Err(join_err) => {
                        Err(eyre::Report::new(join_err)).context("git clone/checkout task panicked")
                    }
                };

                match checkout_result {
                    Ok(()) => promote_clone(logger, &tmp_dir, &target_dir).await?,
                    Err(err) => {
                        logger
                            .log_message(LogLevel::Error, format!("{err:?}"))
                            .await;
                        cleanup_failed_clone(logger, &tmp_dir).await;
                        bail!(err)
                    }
                }
            }
            ReuseOptions::CopyAndFetch {
                from,
                target_dir,
                commit_hash,
            } => {
                // Copy + fetch + checkout into a temp sibling and promote it
                // into `target_dir` only once every step succeeds. That keeps
                // the whole operation all-or-nothing: a crash mid-copy (or a
                // failed fetch) leaves a half-copied dir under the temp name,
                // never a broken `.git` at `target_dir` that a later build would
                // reuse and build the wrong commit from (#2480) or wedge on
                // (#2808).
                let tmp_dir = partial_clone_path(&target_dir);
                let from_clone = from.clone();
                let to = tmp_dir.clone();

                let result: eyre::Result<()> = async {
                    tokio::task::spawn_blocking(move || {
                        std::fs::create_dir_all(&to)
                            .context("failed to create directory for copying git repo")?;
                        fs_extra::dir::copy(
                            &from_clone,
                            &to,
                            &fs_extra::dir::CopyOptions::new().content_only(true),
                        )
                        .with_context(|| {
                            format!(
                                "failed to copy repo clone from `{}` to `{}`",
                                from_clone.display(),
                                to.display()
                            )
                        })
                    })
                    .await??;

                    logger
                        .log_message(
                            LogLevel::Info,
                            format!("fetching changes after copying {}", from.display()),
                        )
                        .await;

                    let repository = fetch_changes(&tmp_dir, None).await?;
                    checkout_tree(&repository, &commit_hash)?;
                    Ok(())
                    // `repository` is dropped at the end of this block, before
                    // the rename in `promote_clone` (Windows-safe).
                }
                .await;

                match result {
                    Ok(()) => promote_clone(logger, &tmp_dir, &target_dir).await?,
                    Err(err) => {
                        cleanup_failed_clone(logger, &tmp_dir).await;
                        bail!(err)
                    }
                }
            }
            ReuseOptions::RenameAndFetch {
                from,
                target_dir,
                commit_hash,
            } => {
                // Rename the old clone into a temp sibling (not straight onto
                // `target_dir`), fetch + checkout there, and promote it into
                // place only once both succeed. If the fetch or checkout fails
                // -- or the process is killed -- the half-updated repo sits at
                // the temp name, never at `target_dir`, so a later build never
                // reuses an old-commit or broken checkout (#2480, #2808).
                let tmp_dir = partial_clone_path(&target_dir);
                tokio::fs::rename(&from, &tmp_dir)
                    .await
                    .context("failed to rename repo clone")?;

                logger
                    .log_message(
                        LogLevel::Info,
                        format!("fetching changes after renaming {}", from.display()),
                    )
                    .await;

                let result: eyre::Result<()> = async {
                    let repository = fetch_changes(&tmp_dir, None).await?;
                    checkout_tree(&repository, &commit_hash)?;
                    Ok(())
                    // `repository` is dropped at the end of this block, before
                    // the rename in `promote_clone` (Windows-safe).
                }
                .await;

                match result {
                    Ok(()) => promote_clone(logger, &tmp_dir, &target_dir).await?,
                    Err(err) => {
                        cleanup_failed_clone(logger, &tmp_dir).await;
                        bail!(err)
                    }
                }
            }
            ReuseOptions::Reuse { dir, verify_commit } => {
                // Belt and braces for #2480: even with the cleanup above, a stale
                // dir could still slip through if remove_dir_all itself failed or
                // we got killed mid-checkout. So for a clone left by a prior build
                // (verify_commit is Some) that's pinned to a full commit hash, I
                // check that HEAD actually points there. verify_commit is None when
                // a sibling node in this build owns the dir and may still be cloning
                // into it, so I leave those completely untouched. Branch and tag
                // pins I can't verify offline, so those pass through too.
                if let Some(commit_hash) = verify_commit
                    && dir.exists()
                    && is_full_commit_hash(&commit_hash)
                {
                    let repo_dir = dir.clone();
                    let head = tokio::task::spawn_blocking(move || -> eyre::Result<String> {
                        let repo =
                            git2::Repository::open(&repo_dir).context("failed to open git repo")?;
                        let id = repo
                            .head()
                            .context("failed to read HEAD")?
                            .peel_to_commit()
                            .context("failed to resolve HEAD commit")?
                            .id()
                            .to_string();
                        Ok(id)
                    })
                    .await
                    .context("HEAD read task panicked")?;

                    match head {
                        // A valid repo sitting on the commit we asked for.
                        Ok(h) if h.eq_ignore_ascii_case(&commit_hash) => {}
                        // A valid repo concretely on some *other* commit, so a
                        // genuine stale leftover. Drop it so the next build
                        // re-clones from scratch, then fail loudly instead of
                        // quietly building the old source.
                        Ok(h) => {
                            cleanup_failed_clone(logger, &dir).await;
                            bail!(
                                "clone dir {} is not on the requested commit {commit_hash} \
                                 (found {h}); I removed it, please rebuild",
                                dir.display()
                            );
                        }
                        // HEAD didn't resolve, so I can't tell a broken leftover
                        // from a clone another process is still writing. My
                        // in-progress set only covers one GitManager and the CLI
                        // builds with its own, so deleting here is how #2711
                        // wipes out a live build. Fail loudly, leave the dir.
                        Err(err) => bail!(
                            "couldn't verify clone dir {} is on commit {commit_hash}: {err:?}; \
                             leaving it in place in case another build is writing it, \
                             please retry",
                            dir.display()
                        ),
                    }
                }

                logger
                    .log_message(
                        LogLevel::Info,
                        format!("reusing up-to-date {}", dir.display()),
                    )
                    .await;
                dir
            }
        };
        Ok(clone_dir)
    }
}

#[derive(Debug)]
enum ReuseOptions {
    /// Create a new clone of the repository.
    NewClone {
        target_dir: PathBuf,
        repo_url: Url,
        commit_hash: String,
    },
    /// Reuse an existing up-to-date clone of the repository.
    ///
    /// `verify_commit` is `Some(hash)` only for a clone left by a prior build,
    /// where it's safe to check HEAD against `hash`. It's `None` when a sibling
    /// node in this same build owns the dir (it may still be cloning into it),
    /// in which case the reuse is a plain read with no HEAD check.
    Reuse {
        dir: PathBuf,
        verify_commit: Option<String>,
    },
    /// Copy an older clone of the repository and fetch changes, then reuse it.
    CopyAndFetch {
        from: PathBuf,
        target_dir: PathBuf,
        commit_hash: String,
    },
    /// Rename an older clone of the repository and fetch changes, then reuse it.
    RenameAndFetch {
        from: PathBuf,
        target_dir: PathBuf,
        commit_hash: String,
    },
}

/// Wipe a half-prepared clone dir after a failed clone/fetch/checkout so a
/// later build doesn't pick it up and treat it as a good clone of the commit
/// it was meant to become (#2480). A dir that was never created is fine, I only
/// grumble if a real directory refuses to go away.
async fn cleanup_failed_clone(logger: &mut impl BuildLogger, dir: &Path) {
    match tokio::fs::remove_dir_all(dir).await {
        Ok(()) => {}
        Err(err) if err.kind() == std::io::ErrorKind::NotFound => {}
        Err(err) => {
            logger
                .log_message(
                    LogLevel::Error,
                    format!(
                        "couldn't remove clone dir after a failed build: {}",
                        err.kind()
                    ),
                )
                .await;
        }
    }
}

/// A unique temp path (a sibling of `target`) that a write arm clones, copies,
/// or renames into before atomically promoting it (see `promote_clone`). The
/// name is `.<target-basename>.partial-<pid>-<counter>`: it sits alongside
/// `target` so the promoting rename stays on one filesystem, begins with a dot
/// so it's visually distinct from real clone dirs, and can never collide with a
/// sibling commit-hash dir. The `pid` keeps it distinct across processes sharing
/// a working dir and the process-wide counter keeps concurrent operations on the
/// same commit apart. That uniqueness (rather than a fixed `.partial` name) is
/// what keeps this cross-process safe -- no build ever writes into, or reclaims,
/// another live build's temp dir.
fn partial_clone_path(target: &Path) -> PathBuf {
    static COUNTER: AtomicU64 = AtomicU64::new(0);
    let n = COUNTER.fetch_add(1, Ordering::Relaxed);
    let pid = std::process::id();
    let name = target
        .file_name()
        .map(|n| n.to_string_lossy())
        .unwrap_or_default();
    target.with_file_name(format!(".{name}.partial-{pid}-{n}"))
}

/// Atomically move a fully-prepared clone from `tmp` into `target`, so `target`
/// is only ever created by this single rename -- never written into in place.
///
/// This is the shared tail of every write arm (`NewClone`, `CopyAndFetch`,
/// `RenameAndFetch`). Because each arm does all of its fallible work (clone /
/// copy, fetch, checkout) in `tmp` first and only calls this once that work has
/// fully succeeded, a crash (SIGKILL / power loss) at any earlier point leaves a
/// half-written repo under the temp name, *never* at `target`. So any directory
/// that exists at `target` is, by construction, a complete checkout -- which is
/// what lets a later build's `clone_dir_ready` check (which trusts
/// `dir.exists()`) and the Reuse arm trust it, instead of wedging forever on an
/// un-resolvable HEAD (#2808) or silently reusing a broken checkout.
///
/// `tmp` must be a sibling of `target` (see `partial_clone_path`) so the rename
/// stays on one filesystem and is atomic. Callers must drop any open
/// `git2::Repository` on `tmp` before calling this (Windows refuses to rename a
/// directory with open handles).
///
/// On the concurrent-winner race -- another build already promoted a complete
/// clone to `target`, so the rename onto a populated dir fails -- the redundant
/// `tmp` is dropped and the existing `target` reused.
async fn promote_clone(
    logger: &mut impl BuildLogger,
    tmp: &Path,
    target: &Path,
) -> eyre::Result<PathBuf> {
    match tokio::fs::rename(tmp, target).await {
        Ok(()) => Ok(target.to_owned()),
        Err(_) if target.exists() => {
            cleanup_failed_clone(logger, tmp).await;
            Ok(target.to_owned())
        }
        Err(err) => {
            logger
                .log_message(LogLevel::Error, format!("{err:?}"))
                .await;
            cleanup_failed_clone(logger, tmp).await;
            bail!(
                "failed to move finished clone from {} into {}: {err}",
                tmp.display(),
                target.display()
            )
        }
    }
}

/// True for a full-length hex commit id (40 chars for SHA-1, 64 for SHA-256).
/// Branch and tag names are shorter or non-hex, and I can't resolve those to a
/// commit without hitting the network, so those pins skip the HEAD check.
fn is_full_commit_hash(s: &str) -> bool {
    matches!(s.len(), 40 | 64) && s.bytes().all(|b| b.is_ascii_hexdigit())
}

/// Map one git-URL component (host or path segment) onto a single directory
/// name by replacing the characters Windows forbids in a path component with
/// `_`. The one that bites in practice is the `:` of a `file:///C:/...` drive
/// letter, which otherwise lands mid-path as an unnameable `C:` directory
/// (#2742). This is a no-op for normal `https://host/owner/repo` URLs, whose
/// components have no reserved characters; a collision here only means two
/// repos share a parent cache dir, and the commit hash still keeps their
/// clones apart. Not handled (they don't occur in real git URLs): reserved
/// device names like `CON`/`NUL` and trailing dot/space components.
fn sanitize_dir_component(component: &str) -> String {
    component
        .chars()
        .map(|c| {
            if c.is_control() || matches!(c, '<' | '>' | ':' | '"' | '|' | '?' | '*' | '\\' | '/') {
                '_'
            } else {
                c
            }
        })
        .collect()
}

fn clone_into(repo_addr: Url, clone_dir: &Path) -> eyre::Result<git2::Repository> {
    if let Some(parent) = clone_dir.parent() {
        std::fs::create_dir_all(parent)
            .context("failed to create parent directory for git clone")?;
    }

    let clone_dir = clone_dir.to_owned();

    let mut builder = git2::build::RepoBuilder::new();
    let mut fetch_options = git2::FetchOptions::new();
    fetch_options.download_tags(git2::AutotagOption::All);
    builder.fetch_options(fetch_options);
    builder
        .clone(repo_addr.as_str(), &clone_dir)
        .context("failed to clone repo")
}

async fn fetch_changes(
    repo_dir: &Path,
    refname: Option<String>,
) -> Result<git2::Repository, eyre::Error> {
    let repo_dir = repo_dir.to_owned();
    let fetch_changes = tokio::task::spawn_blocking(move || {
        let repository = git2::Repository::open(&repo_dir).context("failed to open git repo")?;

        {
            let mut remote = repository
                .find_remote("origin")
                .context("failed to find remote `origin` in repo")?;
            remote
                .connect(git2::Direction::Fetch)
                .context("failed to connect to remote")?;
            let default_branch = remote
                .default_branch()
                .context("failed to get default branch for remote")?;
            let fetch = match &refname {
                Some(refname) => refname,
                None => default_branch
                    .as_str()
                    .context("failed to read default branch as string")?,
            };
            let mut fetch_options = FetchOptions::new();
            fetch_options.download_tags(git2::AutotagOption::All);
            remote
                .fetch(&[&fetch], Some(&mut fetch_options), None)
                .context("failed to fetch from git repo")?;
        }
        Result::<_, eyre::Error>::Ok(repository)
    });
    let repository = fetch_changes.await??;
    Ok(repository)
}

fn checkout_tree(repository: &git2::Repository, commit_hash: &str) -> eyre::Result<()> {
    // Reject arbitrary rev-spec expressions; only allow hex commit hashes and branch/tag names.
    // This must stay a denylist of every rev-spec operator `revparse_ext` understands, not just
    // the ones above: `~`/`@` enable ancestor/reflog/upstream navigation (e.g. `HEAD~3`,
    // `main@{upstream}`) just as much as `..`, `:`, and `^` do. We reject `@`/`{`/`}` wholesale
    // rather than only the `@{…}` sequence; that also turns away the rare valid ref name that
    // embeds one of these characters, but a hard error is the safe failure mode for this guard.
    if commit_hash.contains("..")
        || commit_hash.contains(':')
        || commit_hash.contains('^')
        || commit_hash.contains('~')
        || commit_hash.contains('@')
        || commit_hash.contains('{')
        || commit_hash.contains('}')
    {
        eyre::bail!(
            "invalid commit reference '{commit_hash}': rev-spec expressions are not allowed"
        );
    }
    let (object, reference) = repository
        .revparse_ext(commit_hash)
        .context("failed to parse ref")?;
    repository
        .checkout_tree(&object, None)
        .context("failed to checkout ref")?;
    match reference {
        Some(reference) => repository
            .set_head(reference.name().context("failed to get reference_name")?)
            .context("failed to set head")?,
        None => repository
            .set_head_detached(object.id())
            .context("failed to set detached head")?,
    }

    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;
    use dora_message::common::LogLevelOrStdout;

    // A logger that throws everything away. I don't care what gets logged in
    // these tests, only what happens to the files on disk.
    struct TestLogger;
    impl BuildLogger for TestLogger {
        type Clone = TestLogger;
        async fn log_message(
            &mut self,
            _level: impl Into<LogLevelOrStdout> + Send,
            _message: impl Into<String> + Send,
        ) {
        }
        async fn try_clone(&self) -> eyre::Result<Self::Clone> {
            Ok(TestLogger)
        }
    }

    // Spin up a real local git repo with a single commit and hand back the
    // commit id. There's deliberately no `origin` remote, so any fetch against
    // it fails right away and I can exercise the failure path without a network.
    fn init_repo_with_commit(path: &Path) -> String {
        let repo = git2::Repository::init(path).unwrap();
        std::fs::write(path.join("file.txt"), b"A").unwrap();
        let mut index = repo.index().unwrap();
        index.add_path(Path::new("file.txt")).unwrap();
        index.write().unwrap();
        let tree_id = index.write_tree().unwrap();
        let tree = repo.find_tree(tree_id).unwrap();
        let sig = git2::Signature::now("t", "t@t").unwrap();
        repo.commit(Some("HEAD"), &sig, &sig, "A", &tree, &[])
            .unwrap()
            .to_string()
    }

    // A `file://` URL for a local absolute path. `format!("file://{}", p.display())`
    // is not portable: on Windows it yields `file://C:\...`, which puts the drive
    // letter in the authority and leaves the backslashes as non-separators, so
    // libgit2 refuses to resolve it (#3137). `Url::from_file_path` emits the
    // well-formed `file:///C:/...` on every platform.
    fn file_url(path: &Path) -> Url {
        Url::from_file_path(path).expect("test repo path must be absolute")
    }

    #[test]
    fn clone_dir_path_keeps_a_file_url_drive_letter_out_of_the_on_disk_path() {
        // A `file://` URL to a Windows-style absolute path parses with the
        // drive letter as its first path segment (`C:`). Colon is illegal in a
        // Windows path component, so if it survives into the cache path the
        // clone destination can't be created on Windows -- exactly the failure
        // `reuse_still_verifies_a_dir_left_by_a_different_finished_session` hit
        // on the nightly Windows runner (#2742). The check is
        // platform-independent: `clone_dir_path` must never emit a component
        // carrying a colon, whatever OS builds it.
        let url = Url::parse("file:///C:/Users/runner/repo").unwrap();
        let dir = GitManager::clone_dir_path(Path::new("base"), &url, &"a".repeat(40)).unwrap();
        for component in dir.components() {
            let name = component.as_os_str().to_string_lossy();
            assert!(
                !name.contains(':'),
                "component `{name}` keeps a colon Windows rejects, in {}",
                dir.display()
            );
        }
    }

    #[tokio::test]
    async fn rename_and_fetch_removes_dir_when_fetch_fails() {
        let base = tempfile::tempdir().unwrap();
        let from = base.path().join("from");
        let target = base.path().join("target");
        init_repo_with_commit(&from);

        let folder = GitFolder {
            reuse: ReuseOptions::RenameAndFetch {
                from,
                target_dir: target.clone(),
                // 40 hex chars, but we never get that far: the fetch blows up first.
                commit_hash: "deadbeef".repeat(5),
            },
            _claim: None,
        };
        assert!(folder.prepare(&mut TestLogger).await.is_err());
        assert!(
            !target.exists(),
            "a failed rename+fetch must not leave the dir behind"
        );
    }

    #[tokio::test]
    async fn copy_and_fetch_removes_dir_when_fetch_fails() {
        let base = tempfile::tempdir().unwrap();
        let from = base.path().join("from");
        let target = base.path().join("target");
        init_repo_with_commit(&from);

        let folder = GitFolder {
            reuse: ReuseOptions::CopyAndFetch {
                from,
                target_dir: target.clone(),
                commit_hash: "deadbeef".repeat(5),
            },
            _claim: None,
        };
        assert!(folder.prepare(&mut TestLogger).await.is_err());
        assert!(
            !target.exists(),
            "a failed copy+fetch must not leave the dir behind"
        );
    }

    #[tokio::test]
    async fn reuse_bails_and_removes_dir_on_head_mismatch() {
        let base = tempfile::tempdir().unwrap();
        let dir = base.path().join("clone");
        init_repo_with_commit(&dir); // HEAD sits at commit A

        let folder = GitFolder {
            reuse: ReuseOptions::Reuse {
                dir: dir.clone(),
                // Well-formed full hash that is definitely not commit A.
                verify_commit: Some("0".repeat(40)),
            },
            _claim: None,
        };
        assert!(folder.prepare(&mut TestLogger).await.is_err());
        assert!(
            !dir.exists(),
            "a clone on the wrong commit must be removed so the next build re-clones"
        );
    }

    #[tokio::test]
    async fn reuse_ok_when_head_matches() {
        let base = tempfile::tempdir().unwrap();
        let dir = base.path().join("clone");
        let oid = init_repo_with_commit(&dir);

        let folder = GitFolder {
            reuse: ReuseOptions::Reuse {
                dir: dir.clone(),
                verify_commit: Some(oid),
            },
            _claim: None,
        };
        assert_eq!(folder.prepare(&mut TestLogger).await.unwrap(), dir);
        assert!(dir.exists());
    }

    #[tokio::test]
    async fn reuse_leaves_the_dir_alone_when_head_wont_resolve() {
        // My in-progress set only covers one GitManager, and the CLI builds
        // with its own, so it can't see a clone another process is writing.
        // That clone isn't a valid repo yet, so HEAD won't resolve, and if I
        // treat that as a wrong commit I delete a live build's work all over
        // again (#2711). Only a HEAD that resolves to a different commit is
        // safe to delete.
        let base = tempfile::tempdir().unwrap();
        let dir = base.path().join("clone");
        // Exists but isn't a repo, so Repository::open fails the same way it
        // would against a half-written clone.
        std::fs::create_dir_all(&dir).unwrap();
        std::fs::write(dir.join("partial.txt"), b"mid-clone").unwrap();

        let folder = GitFolder {
            reuse: ReuseOptions::Reuse {
                dir: dir.clone(),
                verify_commit: Some("0".repeat(40)),
            },
            _claim: None,
        };
        assert!(folder.prepare(&mut TestLogger).await.is_err());
        assert!(
            dir.exists(),
            "an unresolvable HEAD must not delete the dir, another build may be writing it"
        );
    }

    #[tokio::test]
    async fn reuse_skips_verification_for_branch_ref() {
        let base = tempfile::tempdir().unwrap();
        let dir = base.path().join("clone");
        init_repo_with_commit(&dir);

        // "main" isn't a full hash, so I skip the HEAD check and just reuse.
        let folder = GitFolder {
            reuse: ReuseOptions::Reuse {
                dir: dir.clone(),
                verify_commit: Some("main".into()),
            },
            _claim: None,
        };
        assert!(folder.prepare(&mut TestLogger).await.is_ok());
    }

    #[tokio::test]
    async fn reuse_does_not_verify_a_dir_a_concurrent_session_is_cloning_into() {
        // Regression test for #2711. The daemon shares one GitManager across
        // concurrently-spawned build sessions (binaries/daemon/src/lib.rs:290,
        // :1562). The old guard only skipped verification for a dir *this
        // session's own* planned_clone_dirs contains, so it couldn't see a
        // different, concurrently-running session's in-flight NewClone. Two
        // sessions building the same repo@commit at the same time would let
        // the second session's HEAD check run against a directory the first
        // is still writing, fail to resolve HEAD, and delete it out from
        // under the first session's clone.
        let repo_dir = tempfile::tempdir().unwrap();
        let repo_path = repo_dir.path().join("repo");
        let commit = init_repo_with_commit(&repo_path);
        let repo_url = file_url(&repo_path);
        let repo_url_str = repo_url.to_string();
        let target_dir = tempfile::tempdir().unwrap();

        let mut manager = GitManager::default();

        // Session A picks NewClone for repo@commit; its GitFolder claims the
        // dir as in-progress even though it hasn't cloned into it yet.
        let session_a = SessionId::generate();
        let folder_a = manager
            .choose_clone_dir(
                session_a,
                repo_url_str.clone(),
                commit.clone(),
                None,
                target_dir.path(),
            )
            .unwrap();
        assert!(matches!(folder_a.reuse, ReuseOptions::NewClone { .. }));

        // The directory now exists on disk mid-clone (libgit2 creates it
        // before it's a valid, HEAD-resolvable repo). Session B must see
        // this as owned by an in-flight build, not as a finished clone to
        // verify.
        let clone_dir = GitManager::clone_dir_path(target_dir.path(), &repo_url, &commit).unwrap();
        std::fs::create_dir_all(&clone_dir).unwrap();

        let session_b = SessionId::generate();
        let folder_b = manager
            .choose_clone_dir(session_b, repo_url_str, commit, None, target_dir.path())
            .unwrap();
        assert!(
            matches!(
                &folder_b.reuse,
                ReuseOptions::Reuse {
                    verify_commit: None,
                    ..
                }
            ),
            "a dir a concurrent session is still cloning into must be reused without verification"
        );

        // folder_a is still alive, holding its in-progress claim. Dropping it
        // now releases the claim, same as when its real clone finishes.
        drop(folder_a);
    }

    #[tokio::test]
    async fn a_dir_stays_protected_while_any_overlapping_claim_is_alive() {
        // Two sessions can both pick a writing arm for the same dir: the
        // daemon's choose phase is synchronous in the event loop while the
        // prepare tasks are spawned, so B's choose can run before A's clone
        // has created the dir on disk. With plain set membership the two
        // claims collapse into one entry, and whichever drops first strips
        // the protection while the other is still writing. The claims have
        // to count.
        let repo_dir = tempfile::tempdir().unwrap();
        let repo_path = repo_dir.path().join("repo");
        let commit = init_repo_with_commit(&repo_path);
        let repo_url = file_url(&repo_path);
        let repo_url_str = repo_url.to_string();
        let target_dir = tempfile::tempdir().unwrap();

        let mut manager = GitManager::default();

        // A and B both choose before the dir exists, so both get NewClone
        // and both claim it.
        let folder_a = manager
            .choose_clone_dir(
                SessionId::generate(),
                repo_url_str.clone(),
                commit.clone(),
                None,
                target_dir.path(),
            )
            .unwrap();
        let folder_b = manager
            .choose_clone_dir(
                SessionId::generate(),
                repo_url_str.clone(),
                commit.clone(),
                None,
                target_dir.path(),
            )
            .unwrap();
        assert!(matches!(folder_a.reuse, ReuseOptions::NewClone { .. }));
        assert!(matches!(folder_b.reuse, ReuseOptions::NewClone { .. }));

        // The dir shows up on disk, then A finishes and drops its claim.
        // B is still writing, so a third session must not get a commit to
        // verify.
        let clone_dir = GitManager::clone_dir_path(target_dir.path(), &repo_url, &commit).unwrap();
        std::fs::create_dir_all(&clone_dir).unwrap();
        drop(folder_a);

        let folder_c = manager
            .choose_clone_dir(
                SessionId::generate(),
                repo_url_str.clone(),
                commit.clone(),
                None,
                target_dir.path(),
            )
            .unwrap();
        assert!(
            matches!(
                &folder_c.reuse,
                ReuseOptions::Reuse {
                    verify_commit: None,
                    ..
                }
            ),
            "dropping one of two overlapping claims must not expose the dir to verification"
        );

        // Once B drops too, the next session verifies again as normal.
        drop(folder_b);
        drop(folder_c);
        let folder_d = manager
            .choose_clone_dir(
                SessionId::generate(),
                repo_url_str,
                commit,
                None,
                target_dir.path(),
            )
            .unwrap();
        assert!(
            matches!(
                &folder_d.reuse,
                ReuseOptions::Reuse {
                    verify_commit: Some(_),
                    ..
                }
            ),
            "once every claim is gone the dir must be verified again"
        );
    }

    #[tokio::test]
    async fn reuse_still_verifies_a_dir_left_by_a_different_finished_session() {
        // Regression test for #2711. `prepared_builds` entries are keyed by
        // SessionId and only ever get cleared at the top of *that same
        // session's* next build (see `clear_planned_builds`). A one-shot
        // session -- the normal case, one SessionId per `dora start` -- never
        // calls `build_dataflow` again, so its `planned_clone_dirs` entry
        // sits in `GitManager` forever. A verify_commit gate keyed on "did
        // any session ever plan this dir" would then permanently skip the
        // HEAD check for that dir the moment a second session touches it,
        // silently reusing a stale wrong-commit clone -- exactly what #2482
        // was written to stop. The gate has to track dirs that are actually
        // being written *right now*, not dirs some session once planned.
        let repo_dir = tempfile::tempdir().unwrap();
        let repo_path = repo_dir.path().join("repo");
        let old_commit = init_repo_with_commit(&repo_path);
        let repo_url = file_url(&repo_path).to_string();

        let target_dir = tempfile::tempdir().unwrap();
        let mut manager = GitManager::default();

        // Session A clones the repo and finishes. Nobody ever calls
        // clear_planned_builds(session_a) again, matching a real one-shot
        // daemon session.
        let session_a = SessionId::generate();
        let folder_a = manager
            .choose_clone_dir(
                session_a,
                repo_url.clone(),
                old_commit.clone(),
                None,
                target_dir.path(),
            )
            .unwrap();
        let clone_dir = folder_a.prepare(&mut TestLogger).await.unwrap();

        // The clone on disk drifts to a different commit -- a stale leftover,
        // exactly the case the #2482 HEAD check exists to catch. Scope every
        // git2 handle to this block so they're all dropped before prepare()
        // tries to delete the dir: on Windows an open repo handle keeps a lock
        // on the .git files and blocks remove_dir_all, leaving the stale clone
        // behind and failing the assertion below.
        std::fs::write(clone_dir.join("file.txt"), b"B").unwrap();
        {
            let repo = git2::Repository::open(&clone_dir).unwrap();
            let parent = repo.head().unwrap().peel_to_commit().unwrap();
            let mut index = repo.index().unwrap();
            index.add_path(Path::new("file.txt")).unwrap();
            index.write().unwrap();
            let tree_id = index.write_tree().unwrap();
            let tree = repo.find_tree(tree_id).unwrap();
            let sig = git2::Signature::now("t", "t@t").unwrap();
            repo.commit(Some("HEAD"), &sig, &sig, "B", &tree, &[&parent])
                .unwrap();
        }

        // Session B (a fresh SessionId -- a second, unrelated `dora start`)
        // asks for the same old commit and is handed the same dir. Session
        // A's planned entry is still sitting in `prepared_builds`, but
        // nothing is actively cloning into this dir right now, so
        // verification must still run and catch the mismatch.
        let session_b = SessionId::generate();
        let folder_b = manager
            .choose_clone_dir(session_b, repo_url, old_commit, None, target_dir.path())
            .unwrap();
        assert!(
            matches!(
                &folder_b.reuse,
                ReuseOptions::Reuse {
                    verify_commit: Some(_),
                    ..
                }
            ),
            "a dir left by a different, finished session must still be verified, not silently reused"
        );
        assert!(folder_b.prepare(&mut TestLogger).await.is_err());
        assert!(
            !clone_dir.exists(),
            "the stale wrong-commit clone must be removed"
        );
    }

    #[tokio::test]
    async fn reuse_without_verify_leaves_a_sibling_clone_alone() {
        // verify_commit = None models the case where a sibling node in this same
        // build owns the dir and might still be cloning into it. Even though HEAD
        // sits at commit A and not whatever the pin is, I must not read or delete
        // it — deleting a clone another thread is writing is exactly the race the
        // dir.exists() guard alone didn't cover.
        let base = tempfile::tempdir().unwrap();
        let dir = base.path().join("clone");
        init_repo_with_commit(&dir);

        let folder = GitFolder {
            reuse: ReuseOptions::Reuse {
                dir: dir.clone(),
                verify_commit: None,
            },
            _claim: None,
        };
        assert_eq!(folder.prepare(&mut TestLogger).await.unwrap(), dir);
        assert!(dir.exists(), "a sibling-owned clone must never be deleted");
    }

    /// Repo with two commits, so `HEAD~1` / `HEAD^` resolve to a real (but
    /// forbidden) ancestor commit.
    fn repo_with_two_commits() -> (tempfile::TempDir, git2::Repository) {
        let dir = tempfile::tempdir().unwrap();
        let repository = git2::Repository::init(dir.path()).unwrap();
        let signature = git2::Signature::now("test", "test@dora.rs").unwrap();
        {
            let tree_id = repository.index().unwrap().write_tree().unwrap();
            let tree = repository.find_tree(tree_id).unwrap();
            let first = repository
                .commit(Some("HEAD"), &signature, &signature, "first", &tree, &[])
                .unwrap();
            let first_commit = repository.find_commit(first).unwrap();
            repository
                .commit(
                    Some("HEAD"),
                    &signature,
                    &signature,
                    "second",
                    &tree,
                    &[&first_commit],
                )
                .unwrap();
        }
        (dir, repository)
    }

    #[test]
    fn rejects_rev_spec_navigation_operators() {
        let (_dir, repository) = repo_with_two_commits();

        // These are genuine, resolvable rev-specs, not typos: without the guard
        // `revparse_ext` would happily walk them to the first commit. The guard
        // must reject them anyway.
        for resolvable in ["HEAD~1", "HEAD^"] {
            assert!(
                repository.revparse_ext(resolvable).is_ok(),
                "test setup: `{resolvable}` should resolve in a two-commit repo"
            );
        }

        for commit_hash in [
            "HEAD~1",
            "main~1",
            "HEAD@{1}",
            "main@{upstream}",
            "@",
            "HEAD^",
            "main..HEAD",
            "HEAD:foo",
        ] {
            let err = checkout_tree(&repository, commit_hash).unwrap_err();
            assert!(
                format!("{err:#}").contains("rev-spec expressions are not allowed"),
                "expected `{commit_hash}` to be rejected as a rev-spec, got: {err:#}"
            );
        }
    }

    #[test]
    fn accepts_branch_name_and_commit_hash() {
        let (_dir, repository) = repo_with_two_commits();
        let head = repository.head().unwrap();
        let branch_name = head.shorthand().unwrap().to_string();
        let head_commit = head.peel_to_commit().unwrap().id();
        checkout_tree(&repository, &branch_name).unwrap();
        checkout_tree(&repository, &head_commit.to_string()).unwrap();
    }

    // The prefix `partial_clone_path` gives a target's temp siblings, recomputed
    // independently so a drift in the naming scheme trips the assertions below.
    fn partial_prefix(target: &Path) -> String {
        format!(
            ".{}.partial-",
            target.file_name().unwrap().to_string_lossy()
        )
    }

    // True if any temp sibling for `target` survives in its parent dir.
    fn has_partial_leftover(target: &Path) -> bool {
        let prefix = partial_prefix(target);
        std::fs::read_dir(target.parent().unwrap())
            .unwrap()
            .filter_map(|e| e.ok())
            .any(|e| e.file_name().to_string_lossy().starts_with(&prefix))
    }

    // Clone `origin` into `dest` so `dest` carries an `origin` remote that
    // `fetch_changes` can pull from — the shape the Copy/Rename arms expect.
    fn clone_from_origin(origin: &Path, dest: &Path) {
        git2::Repository::clone(file_url(origin).as_str(), dest).unwrap();
    }

    fn head_commit(dir: &Path) -> String {
        git2::Repository::open(dir)
            .unwrap()
            .head()
            .unwrap()
            .peel_to_commit()
            .unwrap()
            .id()
            .to_string()
    }

    // A partial-clone temp path is a sibling of the target (not the target
    // itself), carries the target's basename, and every call is unique -- so it
    // is never picked up by `clone_dir_ready`/Reuse and never collides with a
    // concurrent clone of the same commit.
    #[test]
    fn partial_clone_path_is_a_unique_sibling() {
        let target = Path::new("/base/localhost/org/repo").join("a".repeat(40));
        let p1 = partial_clone_path(&target);
        let p2 = partial_clone_path(&target);

        assert_ne!(p1, target);
        assert_ne!(p1, p2, "each call must produce a distinct temp path");
        assert_eq!(p1.parent(), target.parent(), "temp must be a sibling");
        let name = p1.file_name().unwrap().to_string_lossy();
        assert!(name.starts_with(&partial_prefix(&target)));
    }

    // `promote_clone` moves the temp dir onto an absent target with a single
    // rename. This is the atomic step that guarantees `target` is never written
    // in place, so a crash before it leaves only a temp dir.
    #[tokio::test]
    async fn promote_clone_moves_temp_into_absent_target() {
        let base = tempfile::tempdir().unwrap();
        let target = base.path().join("clone");
        let tmp = partial_clone_path(&target);
        std::fs::create_dir_all(&tmp).unwrap();
        std::fs::write(tmp.join("f"), b"data").unwrap();

        let out = promote_clone(&mut TestLogger, &tmp, &target).await.unwrap();
        assert_eq!(out, target);
        assert!(!tmp.exists(), "temp must be consumed by the rename");
        assert_eq!(std::fs::read(target.join("f")).unwrap(), b"data");
    }

    // On the concurrent-winner race — another build already promoted a complete
    // clone to `target` — `promote_clone` must drop our redundant temp and reuse
    // the winner's clone untouched, rather than clobbering it or erroring.
    #[tokio::test]
    async fn promote_clone_reuses_winner_and_drops_temp_on_race() {
        let base = tempfile::tempdir().unwrap();
        let target = base.path().join("clone");
        let tmp = partial_clone_path(&target);
        std::fs::create_dir_all(&tmp).unwrap();
        std::fs::write(tmp.join("mine"), b"mine").unwrap();
        // The winner's finished (non-empty) clone already sits at target.
        std::fs::create_dir_all(&target).unwrap();
        std::fs::write(target.join("winner"), b"winner").unwrap();

        let out = promote_clone(&mut TestLogger, &tmp, &target).await.unwrap();
        assert_eq!(out, target);
        assert!(!tmp.exists(), "our redundant temp must be dropped");
        assert!(
            target.join("winner").exists() && !target.join("mine").exists(),
            "the winner's clone must be reused untouched"
        );
    }

    // A `NewClone` must land at `target_dir` atomically and leave no temp dir
    // behind on success -- the property that stops a crashed build's half-clone
    // from ever sitting at `target_dir` and wedging future reuse (#2808).
    #[tokio::test]
    async fn new_clone_promotes_temp_into_target_and_cleans_up() {
        let repo_dir = tempfile::tempdir().unwrap();
        let repo_path = repo_dir.path().join("repo");
        let commit = init_repo_with_commit(&repo_path);
        let repo_url = file_url(&repo_path);

        let base = tempfile::tempdir().unwrap();
        let target = base.path().join("localhost").join(&commit);

        let folder = GitFolder {
            reuse: ReuseOptions::NewClone {
                target_dir: target.clone(),
                repo_url,
                commit_hash: commit.clone(),
            },
            _claim: None,
        };
        let out = folder.prepare(&mut TestLogger).await.unwrap();
        assert_eq!(out, target);
        assert_eq!(head_commit(&target), commit);
        assert!(
            !has_partial_leftover(&target),
            "temp dir must be gone after promotion"
        );
    }

    // A `NewClone` whose clone fails must leave *nothing* at `target_dir` (and
    // no temp sibling), so a later build never mistakes a failed attempt for a
    // reusable clone (#2808).
    #[tokio::test]
    async fn new_clone_failure_leaves_no_target_dir() {
        let base = tempfile::tempdir().unwrap();
        let target = base.path().join("localhost").join("a".repeat(40));
        std::fs::create_dir_all(target.parent().unwrap()).unwrap();
        // A file:// URL to a path that isn't a git repo -> clone fails.
        let missing = base.path().join("does-not-exist");
        let repo_url = file_url(&missing);

        let folder = GitFolder {
            reuse: ReuseOptions::NewClone {
                target_dir: target.clone(),
                repo_url,
                commit_hash: "a".repeat(40),
            },
            _claim: None,
        };
        assert!(folder.prepare(&mut TestLogger).await.is_err());
        assert!(
            !target.exists(),
            "a failed clone must never leave a dir at the target path"
        );
        assert!(!has_partial_leftover(&target), "temp must be cleaned up");
    }

    // A `CopyAndFetch` must copy + fetch + checkout in a temp sibling and
    // promote it into `target_dir` only on full success — never write `.git`
    // into `target_dir` in place (#2808).
    #[tokio::test]
    async fn copy_and_fetch_promotes_into_target() {
        let base = tempfile::tempdir().unwrap();
        let origin = base.path().join("origin");
        let commit = init_repo_with_commit(&origin);
        // `from` is a prior clone (with an `origin` remote) to be copied.
        let from = base.path().join("localhost").join("prev");
        clone_from_origin(&origin, &from);

        let target = base.path().join("localhost").join(&commit);
        let folder = GitFolder {
            reuse: ReuseOptions::CopyAndFetch {
                from: from.clone(),
                target_dir: target.clone(),
                commit_hash: commit.clone(),
            },
            _claim: None,
        };
        let out = folder.prepare(&mut TestLogger).await.unwrap();
        assert_eq!(out, target);
        assert_eq!(head_commit(&target), commit);
        assert!(from.exists(), "the source clone must be left in place");
        assert!(!has_partial_leftover(&target), "temp must be gone");
    }

    // A `CopyAndFetch` whose fetch fails (no reachable `origin`) must leave
    // nothing at `target_dir` and no temp sibling behind.
    #[tokio::test]
    async fn copy_and_fetch_failure_leaves_no_target_dir() {
        let base = tempfile::tempdir().unwrap();
        // `from` has a commit but no `origin` remote, so the fetch fails.
        let from = base.path().join("localhost").join("prev");
        init_repo_with_commit(&from);

        let target = base.path().join("localhost").join("a".repeat(40));
        let folder = GitFolder {
            reuse: ReuseOptions::CopyAndFetch {
                from,
                target_dir: target.clone(),
                commit_hash: "deadbeef".repeat(5),
            },
            _claim: None,
        };
        assert!(folder.prepare(&mut TestLogger).await.is_err());
        assert!(!target.exists(), "a failed copy+fetch must leave no target");
        assert!(!has_partial_leftover(&target), "temp must be cleaned up");
    }

    // A `RenameAndFetch` must rename the old clone into a temp sibling, fetch +
    // checkout there, and promote into `target_dir` only on success.
    #[tokio::test]
    async fn rename_and_fetch_promotes_into_target() {
        let base = tempfile::tempdir().unwrap();
        let origin = base.path().join("origin");
        let commit = init_repo_with_commit(&origin);
        let from = base.path().join("localhost").join("prev");
        clone_from_origin(&origin, &from);

        let target = base.path().join("localhost").join(&commit);
        let folder = GitFolder {
            reuse: ReuseOptions::RenameAndFetch {
                from: from.clone(),
                target_dir: target.clone(),
                commit_hash: commit.clone(),
            },
            _claim: None,
        };
        let out = folder.prepare(&mut TestLogger).await.unwrap();
        assert_eq!(out, target);
        assert_eq!(head_commit(&target), commit);
        assert!(!from.exists(), "the source clone is consumed by the rename");
        assert!(!has_partial_leftover(&target), "temp must be gone");
    }

    // A `RenameAndFetch` whose fetch fails must leave nothing at `target_dir`
    // and no temp sibling behind (regression for the pre-fix in-place rename).
    #[tokio::test]
    async fn rename_and_fetch_failure_leaves_no_target_dir() {
        let base = tempfile::tempdir().unwrap();
        let from = base.path().join("localhost").join("prev");
        init_repo_with_commit(&from); // no `origin` remote -> fetch fails

        let target = base.path().join("localhost").join("a".repeat(40));
        let folder = GitFolder {
            reuse: ReuseOptions::RenameAndFetch {
                from,
                target_dir: target.clone(),
                commit_hash: "deadbeef".repeat(5),
            },
            _claim: None,
        };
        assert!(folder.prepare(&mut TestLogger).await.is_err());
        assert!(
            !target.exists(),
            "a failed rename+fetch must leave no target"
        );
        assert!(!has_partial_leftover(&target), "temp must be cleaned up");
    }
}