grit-lib 0.5.21

Core library for the grit Git implementation
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
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
//! Integration test for the smart-HTTP transport: `SmartHttpTransport` +
//! `http_fetch` over the default `ureq`-backed `HttpClient` (feature `http-ureq`).
//!
//! A bare source repo (two commits on `main`, a `topic` branch, an annotated
//! tag) is built with the system `git` under a temp root. The `grit-http-server`
//! crate's binary is spawned over that root on a free localhost port; an empty
//! local repo then fetches `http://127.0.0.1:<port>/repo.git` via
//! `SmartHttpTransport::connect` (advertisement) + `http_fetch` (negotiation).
//! We assert the tracking refs + tag land, the objects arrive, the fetched main
//! tip matches `git rev-parse`, and the pack `fsck`s clean.
//!
//! The test skips gracefully (returns early) when `git` or the
//! `grit-http-server` binary is unavailable, or the server fails to bind —
//! the server itself does not require `grit` on `PATH`.
//! the happy path is otherwise real end-to-end HTTP wire I/O.
//!
//! Gated on the `http-ureq` feature (the default `UreqHttpClient` lives there):
//!   cargo test -p grit-lib --features http-ureq --test transport_http

#![cfg(feature = "http-ureq")]

use std::net::{TcpListener, TcpStream};
use std::path::{Path, PathBuf};
use std::process::{Child, Command, Stdio};
use std::sync::{Arc, Mutex};
use std::time::{Duration, Instant};

use grit_lib::config::ConfigSet;
use grit_lib::error::{Error, Result as GritResult};
use grit_lib::objects::odb::Odb;
use grit_lib::objects::ObjectId;
use grit_lib::refs::resolve_ref;
use grit_lib::remote::fetch::NoProgress;
use grit_lib::remote::push::push_http;
use grit_lib::remote::push_report::PushRefStatus;
use grit_lib::remote::transfer::{FetchOptions, PushOptions, PushRefSpec, TagMode, UpdateMode};
use grit_lib::remote::transport::http::{http_client_arc, ureq_client::UreqHttpClient};
use grit_lib::remote::transport::http::{http_fetch, HttpClient, SmartHttpTransport};
use grit_lib::remote::transport::{ConnectOptions, Service, Transport};

fn git(dir: &Path, args: &[&str]) -> String {
    let out = Command::new("git")
        .current_dir(dir)
        .args(args)
        .env("GIT_AUTHOR_NAME", "T")
        .env("GIT_AUTHOR_EMAIL", "t@example.com")
        .env("GIT_AUTHOR_DATE", "2005-04-07T22:13:13 +0200")
        .env("GIT_COMMITTER_NAME", "T")
        .env("GIT_COMMITTER_EMAIL", "t@example.com")
        .env("GIT_COMMITTER_DATE", "2005-04-07T22:13:13 +0200")
        .env("GIT_CONFIG_GLOBAL", "/dev/null")
        .env("GIT_CONFIG_SYSTEM", "/dev/null")
        .output()
        .expect("run git");
    assert!(
        out.status.success(),
        "git {args:?} failed: {}",
        String::from_utf8_lossy(&out.stderr)
    );
    String::from_utf8(out.stdout).expect("utf8 git output")
}

fn rev_parse(dir: &Path, rev: &str) -> ObjectId {
    ObjectId::from_hex(git(dir, &["rev-parse", rev]).trim()).expect("valid oid")
}

fn open_odb(git_dir: &Path) -> Odb {
    Odb::new(&git_dir.join("objects")).with_config_git_dir(git_dir.to_path_buf())
}

/// Build a source repo: two commits on `main`, a `topic` branch, an annotated tag.
fn build_source(dir: &Path) {
    git(dir, &["init", "-q", "-b", "main", "."]);
    std::fs::write(dir.join("a.txt"), "one\n").unwrap();
    git(dir, &["add", "a.txt"]);
    git(dir, &["commit", "-q", "-m", "c1"]);
    std::fs::write(dir.join("b.txt"), "two\n").unwrap();
    git(dir, &["add", "b.txt"]);
    git(dir, &["commit", "-q", "-m", "c2"]);
    git(dir, &["tag", "-a", "v1", "-m", "release one"]);
    git(dir, &["branch", "topic"]);
}

/// Extend [`build_source`] with many branch refs and a large blob (exercises v2
/// `ls-refs` + a non-trivial pack over smart-HTTP).
fn build_heavy_source(dir: &Path, extra_refs: usize) {
    build_source(dir);
    let tip = git(dir, &["rev-parse", "HEAD"]).trim().to_owned();
    for i in 0..extra_refs {
        git(
            dir,
            &[
                "update-ref",
                &format!("refs/heads/branch-{i}"),
                tip.as_str(),
            ],
        );
    }
    std::fs::write(dir.join("large.bin"), vec![b'L'; 512 * 1024]).unwrap();
    git(dir, &["add", "large.bin"]);
    git(dir, &["commit", "-q", "-m", "large blob"]);
}

/// Pick a currently-free localhost port by binding then dropping a listener.
fn free_port() -> Option<u16> {
    // Dedup port handout per process so a concurrent caller never accepts a
    // port another test already reserved (closes the bind-before-spawn TOCTOU
    // that let two servers share a port under high test parallelism).
    static USED: std::sync::Mutex<Vec<u16>> = std::sync::Mutex::new(Vec::new());
    let mut used = USED.lock().unwrap_or_else(|e| e.into_inner());
    for _ in 0..200 {
        let l = TcpListener::bind(("127.0.0.1", 0)).ok()?;
        let p = l.local_addr().ok()?.port();
        drop(l);
        if !used.contains(&p) {
            used.push(p);
            return Some(p);
        }
    }
    None
}

/// Locate a sibling binary (`grit`, `grit-http-server`) in the cargo target
/// directory. The test executable lives at `target/<profile>/deps/<exe>`, so the
/// binaries are one directory up.
fn find_binary(name: &str) -> Option<PathBuf> {
    let exe = std::env::current_exe().ok()?;
    // .../target/<profile>/deps/transport_http-<hash>
    let deps = exe.parent()?; // deps
    let profile = deps.parent()?; // <profile>
    for cand in [profile.join(name), deps.join(name)] {
        if cand.is_file() {
            return Some(cand);
        }
    }
    None
}

/// Spawn `grit-http-server --root <root> --bind 127.0.0.1:<port>` (in-process
/// upload-pack/receive-pack; no `GRIT_BIN` or `grit` on `PATH` required).
fn spawn_server(server_bin: &Path, root: &Path, port: u16) -> Option<Child> {
    Command::new(server_bin)
        .arg("--root")
        .arg(root)
        .arg("--bind")
        .arg(format!("127.0.0.1:{port}"))
        .env_remove("GRIT_BIN")
        .stdout(Stdio::null())
        .stderr(Stdio::null())
        .spawn()
        .ok()
}

/// Wait until the HTTP server answers a TCP connect on `port`, or time out.
fn wait_ready(port: u16) -> bool {
    let addr = std::net::SocketAddr::from(([127, 0, 0, 1], port));
    let deadline = Instant::now() + Duration::from_secs(10);
    while Instant::now() < deadline {
        if TcpStream::connect_timeout(&addr, Duration::from_millis(200)).is_ok() {
            return true;
        }
        std::thread::sleep(Duration::from_millis(50));
    }
    false
}

struct ServerGuard(Child);
impl Drop for ServerGuard {
    fn drop(&mut self) {
        let _ = self.0.kill();
        let _ = self.0.wait();
    }
}

#[test]
fn fetch_over_smart_http_lands_refs_and_objects() {
    let Some(server_bin) = find_binary("grit-http-server") else {
        eprintln!("SKIP: `grit-http-server` binary not found (build grit-http-server first)");
        return;
    };

    // Build a source repo, then mirror it into a bare repo under the server root
    // (served at `/repo.git`).
    let tmp = tempfile::tempdir().expect("tempdir");
    let work = tmp.path().join("work");
    std::fs::create_dir_all(&work).unwrap();
    build_source(&work);

    let root = tmp.path().join("srv");
    std::fs::create_dir_all(&root).unwrap();
    let source = root.join("repo.git");
    git(
        &work,
        &[
            "clone",
            "-q",
            "--bare",
            ".",
            source.to_str().expect("utf8 path"),
        ],
    );
    git(&source, &["symbolic-ref", "HEAD", "refs/heads/main"]);

    let main_oid = rev_parse(&source, "refs/heads/main");
    let topic_oid = rev_parse(&source, "refs/heads/topic");
    let c1_oid = rev_parse(&work, "HEAD~1");
    let tag_oid = rev_parse(&source, "refs/tags/v1");

    let Some(port) = free_port() else {
        eprintln!("SKIP: could not allocate a free port");
        return;
    };
    let Some(child) = spawn_server(&server_bin, &root, port) else {
        eprintln!("SKIP: could not spawn grit-http-server");
        return;
    };
    let _guard = ServerGuard(child);
    if !wait_ready(port) {
        eprintln!("SKIP: grit-http-server did not become ready on port {port}");
        return;
    }

    let url = format!("http://127.0.0.1:{port}/repo.git");

    // Empty local repo.
    let local = tmp.path().join("local");
    std::fs::create_dir_all(&local).unwrap();
    git(&local, &["init", "-q", "-b", "main", "."]);
    let local_git = local.join(".git");

    // 1. Connect via the trait and check the advertisement.
    let client = http_client_arc(UreqHttpClient::new());
    let transport = SmartHttpTransport::new(client);
    let conn = match transport.connect(&url, Service::UploadPack, &ConnectOptions::default()) {
        Ok(c) => c,
        Err(e) => {
            eprintln!("SKIP: could not connect to grit-http-server: {e}");
            return;
        }
    };
    assert!(
        conn.advertised_refs()
            .iter()
            .any(|(n, o)| n == "refs/heads/main" && *o == main_oid),
        "advertisement missing refs/heads/main = {}",
        main_oid.to_hex()
    );
    assert_eq!(conn.head_symref(), Some("refs/heads/main"));
    assert_eq!(conn.protocol_version(), 0);
    drop(conn);

    // 2. Fetch via http_fetch over a recording client (no Git-Protocol header).
    let client = Arc::new(RecordingClient::new_default());
    let mut opts = FetchOptions {
        refspecs: vec!["+refs/heads/*:refs/remotes/origin/*".to_owned()],
        tags: TagMode::All,
        ..Default::default()
    };
    let outcome = http_fetch(client.clone(), &local_git, &url, &mut opts, &mut NoProgress)
        .expect("http_fetch over grit-http-server");

    // PROVE this is genuinely the v0/v1 stateless RPC (not a silent v2 upgrade):
    // the POST bodies carry a bare `want <oid>` line and NEVER `command=ls-refs`
    // / `command=fetch`, and no request sent a `Git-Protocol` header.
    let v1_commands = client.post_commands.lock().unwrap().clone();
    assert!(
        v1_commands.iter().any(|c| c.starts_with("want ")),
        "v0/v1 fetch must POST a bare `want` body; saw {v1_commands:?}"
    );
    assert!(
        !v1_commands
            .iter()
            .any(|c| c == "command=ls-refs" || c == "command=fetch"),
        "v0/v1 fetch must NOT POST any v2 command body; saw {v1_commands:?}"
    );
    let v1_protocols = client.git_protocols.lock().unwrap().clone();
    assert!(
        v1_protocols.iter().all(|p| p.is_none()),
        "v0/v1 fetch must not send a Git-Protocol header; saw {v1_protocols:?}"
    );

    // Tracking refs written.
    let got_main = resolve_ref(&local_git, "refs/remotes/origin/main").expect("origin/main");
    let got_topic = resolve_ref(&local_git, "refs/remotes/origin/topic").expect("origin/topic");
    assert_eq!(got_main, main_oid, "origin/main oid mismatch vs source");
    assert_eq!(got_topic, topic_oid, "origin/topic oid mismatch vs source");

    // Annotated tag arrived (TagMode::All).
    let got_tag = resolve_ref(&local_git, "refs/tags/v1").expect("tag v1 written");
    assert_eq!(got_tag, tag_oid, "tag v1 oid mismatch vs source");

    // Objects landed in the local odb.
    let local_odb = open_odb(&local_git);
    for oid in [main_oid, topic_oid, c1_oid, tag_oid] {
        assert!(
            local_odb.exists(&oid),
            "object {} missing from local odb after http fetch",
            oid.to_hex()
        );
        local_odb
            .read(&oid)
            .unwrap_or_else(|e| panic!("read {}: {e}", oid.to_hex()));
    }

    // Per-ref update modes.
    let main_update = outcome
        .updates
        .iter()
        .find(|u| u.remote_ref == "refs/heads/main")
        .expect("update for main");
    assert_eq!(main_update.mode, UpdateMode::New);
    assert_eq!(main_update.new_oid, Some(main_oid));

    // Default branch from the server's HEAD symref.
    assert_eq!(outcome.default_branch.as_deref(), Some("main"));

    // Cross-check the fetched main tip against git's view of the source.
    assert_eq!(
        got_main.to_hex(),
        git(&source, &["rev-parse", "refs/heads/main"]).trim()
    );

    // The fetched pack re-indexes / fsck's clean in the local repo.
    let fsck = Command::new("git")
        .current_dir(&local)
        .args(["fsck", "--no-dangling"])
        .output()
        .expect("run git fsck");
    assert!(
        fsck.status.success(),
        "git fsck failed after http fetch: {}",
        String::from_utf8_lossy(&fsck.stderr)
    );
}

/// An [`HttpClient`] that wraps [`UreqHttpClient`] and records the first line of
/// every POST body. A protocol-v2 fetch must POST a `command=ls-refs` body and a
/// `command=fetch` body; capturing them proves the v2 code path ran (rather than
/// a v0/v1 advertisement fetch) directly from the wire, not from a self-report.
struct RecordingClient {
    inner: UreqHttpClient,
    /// `Git-Protocol` header values seen on each request (GET + POST).
    git_protocols: Mutex<Vec<Option<String>>>,
    /// First pkt-line (command) of each POST body.
    post_commands: Mutex<Vec<String>>,
    /// For each `command=fetch` POST, the object count read from the `PACK`
    /// header of the demuxed `packfile` section of the *response* (or `None`
    /// when that response carried no packfile, e.g. a pure negotiation round).
    /// This is wire evidence of pack minimality: an incremental fetch that
    /// offers `have`s must yield a far smaller object count than a from-scratch
    /// full-closure fetch.
    fetch_pack_object_counts: Mutex<Vec<Option<u32>>>,
    /// Whether any `command=fetch` POST *body* carried at least one `have <oid>`
    /// line — wire evidence the negotiator actually offered local history.
    fetch_sent_haves: Mutex<bool>,
}

impl RecordingClient {
    fn new(git_protocol: &str) -> Self {
        Self::from_inner(UreqHttpClient::new().with_git_protocol(git_protocol.to_owned()))
    }

    /// A recording client with NO default `Git-Protocol` header — used to prove a
    /// v0/v1 fetch genuinely runs the classic stateless RPC (bare `want`/`have`
    /// bodies, no `command=fetch`) and never silently upgrades to v2.
    fn new_default() -> Self {
        Self::from_inner(UreqHttpClient::new())
    }

    /// Client built like grit-cli (`UreqHttpClient::from_config` on default config).
    fn from_default_config() -> GritResult<Self> {
        let inner = UreqHttpClient::from_config(&ConfigSet::new())?;
        Ok(Self::from_inner(inner))
    }

    fn from_inner(inner: UreqHttpClient) -> Self {
        Self {
            inner,
            git_protocols: Mutex::new(Vec::new()),
            post_commands: Mutex::new(Vec::new()),
            fetch_pack_object_counts: Mutex::new(Vec::new()),
            fetch_sent_haves: Mutex::new(false),
        }
    }

    /// Whether the request `body` (a v2 `command=fetch`) contained a `have <oid>`
    /// pkt-line. Scans the pkt-line stream for a payload starting with `have `.
    fn body_has_have_line(body: &[u8]) -> bool {
        let mut i = 0usize;
        while i + 4 <= body.len() {
            let Ok(len_str) = std::str::from_utf8(&body[i..i + 4]) else {
                return false;
            };
            let Ok(len) = usize::from_str_radix(len_str, 16) else {
                return false;
            };
            if len < 4 {
                i += 4;
                continue;
            }
            if i + len > body.len() {
                return false;
            }
            let payload = &body[i + 4..i + len];
            if payload.starts_with(b"have ") {
                return true;
            }
            i += len;
        }
        false
    }

    /// Extract the payload of the first pkt-line in `body` (e.g. `command=ls-refs`).
    fn first_pkt_line(body: &[u8]) -> String {
        if body.len() < 4 {
            return String::new();
        }
        let Ok(len_str) = std::str::from_utf8(&body[..4]) else {
            return String::new();
        };
        let Ok(len) = usize::from_str_radix(len_str, 16) else {
            return String::new();
        };
        if len <= 4 || len > body.len() {
            return String::new();
        }
        String::from_utf8_lossy(&body[4..len]).trim_end().to_owned()
    }

    /// Demux the side-band-64k `packfile` section out of a v2 `command=fetch`
    /// response and return the object count from the `PACK` header (bytes 8..12,
    /// big-endian). Returns `None` when the response has no packfile section.
    ///
    /// This walks the pkt-line stream looking for the `packfile` section header,
    /// then concatenates band-1 payloads (the pack bytes) until the section
    /// boundary, and parses the standard 12-byte pack header.
    fn pack_object_count(resp: &[u8]) -> Option<u32> {
        let mut i = 0usize;
        let mut in_packfile = false;
        let mut pack: Vec<u8> = Vec::new();
        while i + 4 <= resp.len() {
            let Ok(len_str) = std::str::from_utf8(&resp[i..i + 4]) else {
                break;
            };
            let Ok(len) = usize::from_str_radix(len_str, 16) else {
                break;
            };
            // 0000 flush / 0001 delim / 0002 response-end: section boundaries.
            if len < 4 {
                i += 4;
                if in_packfile && len == 0 {
                    // End of the packfile section.
                    break;
                }
                continue;
            }
            if i + len > resp.len() {
                break;
            }
            let payload = &resp[i + 4..i + len];
            i += len;
            let header = if !payload.is_empty() && payload[0] == 1 {
                String::from_utf8_lossy(&payload[1..]).trim_end().to_owned()
            } else {
                String::from_utf8_lossy(payload).trim_end().to_owned()
            };
            if matches!(
                header.as_str(),
                "acknowledgments" | "shallow-info" | "wanted-refs" | "packfile-uris" | "packfile"
            ) {
                in_packfile = header == "packfile";
                continue;
            }
            if in_packfile && !payload.is_empty() && payload[0] == 1 {
                // Band 1 = pack data.
                pack.extend_from_slice(&payload[1..]);
            }
        }
        if pack.len() >= 12 && &pack[0..4] == b"PACK" {
            Some(u32::from_be_bytes([pack[8], pack[9], pack[10], pack[11]]))
        } else {
            None
        }
    }

    /// The recorded per-`command=fetch` pack object counts, in POST order.
    fn fetch_object_counts(&self) -> Vec<Option<u32>> {
        self.fetch_pack_object_counts.lock().unwrap().clone()
    }
}

impl HttpClient for RecordingClient {
    fn get(&self, url: &str, git_protocol: Option<&str>) -> GritResult<Vec<u8>> {
        let gp = git_protocol.or_else(|| self.inner.git_protocol_header());
        self.git_protocols
            .lock()
            .unwrap()
            .push(gp.map(str::to_owned));
        self.inner.get(url, git_protocol)
    }

    fn post(
        &self,
        url: &str,
        content_type: &str,
        accept: &str,
        body: &[u8],
        git_protocol: Option<&str>,
    ) -> GritResult<Vec<u8>> {
        let gp = git_protocol.or_else(|| self.inner.git_protocol_header());
        self.git_protocols
            .lock()
            .unwrap()
            .push(gp.map(str::to_owned));
        let command = Self::first_pkt_line(body);
        self.post_commands.lock().unwrap().push(command.clone());
        if command == "command=fetch" && Self::body_has_have_line(body) {
            *self.fetch_sent_haves.lock().unwrap() = true;
        }
        let resp = self
            .inner
            .post(url, content_type, accept, body, git_protocol)?;
        // For a v2 `command=fetch`, record the object count of any packfile the
        // response carried — direct wire evidence of how minimal the pack was.
        if command == "command=fetch" {
            self.fetch_pack_object_counts
                .lock()
                .unwrap()
                .push(Self::pack_object_count(&resp));
        }
        Ok(resp)
    }

    fn git_protocol_header(&self) -> Option<&str> {
        self.inner.git_protocol_header()
    }
}

/// Wraps an HTTP client and fails `git-upload-pack` POSTs with an I/O error
/// (simulates a truncated response body read).
struct IoFailUploadPackClient<C> {
    inner: C,
}

impl<C: HttpClient> HttpClient for IoFailUploadPackClient<C> {
    fn get(&self, url: &str, git_protocol: Option<&str>) -> GritResult<Vec<u8>> {
        self.inner.get(url, git_protocol)
    }

    fn post(
        &self,
        url: &str,
        content_type: &str,
        accept: &str,
        body: &[u8],
        git_protocol: Option<&str>,
    ) -> GritResult<Vec<u8>> {
        if url.contains("git-upload-pack") {
            return Err(Error::Io(std::io::Error::new(
                std::io::ErrorKind::UnexpectedEof,
                "failed to fill whole buffer",
            )));
        }
        self.inner
            .post(url, content_type, accept, body, git_protocol)
    }

    fn git_protocol_header(&self) -> Option<&str> {
        self.inner.git_protocol_header()
    }
}

#[test]
fn fetch_over_smart_http_v2_lands_refs_and_objects() {
    let Some(server_bin) = find_binary("grit-http-server") else {
        eprintln!("SKIP: `grit-http-server` binary not found (build grit-http-server first)");
        return;
    };

    let tmp = tempfile::tempdir().expect("tempdir");
    let work = tmp.path().join("work");
    std::fs::create_dir_all(&work).unwrap();
    build_source(&work);

    let root = tmp.path().join("srv");
    std::fs::create_dir_all(&root).unwrap();
    let source = root.join("repo.git");
    git(
        &work,
        &[
            "clone",
            "-q",
            "--bare",
            ".",
            source.to_str().expect("utf8 path"),
        ],
    );
    git(&source, &["symbolic-ref", "HEAD", "refs/heads/main"]);

    let main_oid = rev_parse(&source, "refs/heads/main");
    let topic_oid = rev_parse(&source, "refs/heads/topic");
    let c1_oid = rev_parse(&work, "HEAD~1");
    let tag_oid = rev_parse(&source, "refs/tags/v1");

    let Some(port) = free_port() else {
        eprintln!("SKIP: could not allocate a free port");
        return;
    };
    let Some(child) = spawn_server(&server_bin, &root, port) else {
        eprintln!("SKIP: could not spawn grit-http-server");
        return;
    };
    let _guard = ServerGuard(child);
    if !wait_ready(port) {
        eprintln!("SKIP: grit-http-server did not become ready on port {port}");
        return;
    }

    let url = format!("http://127.0.0.1:{port}/repo.git");

    // Confirm the server actually speaks v2: a system `git -c protocol.version=2`
    // clone over the same URL succeeds (and the server returns a `version 2`
    // advertisement under the `Git-Protocol: version=2` header). If the server
    // does not speak v2, skip rather than report a false pass.
    let xcheck = tmp.path().join("v2xcheck");
    let xclone = Command::new("git")
        .args([
            "-c",
            "protocol.version=2",
            "clone",
            "-q",
            &url,
            xcheck.to_str().expect("utf8 path"),
        ])
        .env("GIT_CONFIG_GLOBAL", "/dev/null")
        .env("GIT_CONFIG_SYSTEM", "/dev/null")
        .output()
        .expect("run git v2 clone");
    if !xclone.status.success() {
        eprintln!(
            "SKIP: server does not speak protocol v2 (git v2 clone failed: {})",
            String::from_utf8_lossy(&xclone.stderr)
        );
        return;
    }

    // Empty local repo.
    let local = tmp.path().join("local");
    std::fs::create_dir_all(&local).unwrap();
    git(&local, &["init", "-q", "-b", "main", "."]);
    let local_git = local.join(".git");

    // 1. Connect requesting v2 and confirm the advertisement is a v2 capability
    // block (no refs on connect; protocol_version == 2).
    let recording = Arc::new(RecordingClient::new("version=2"));
    let transport = SmartHttpTransport::new(Arc::clone(&recording));
    let opts_v2 = ConnectOptions {
        protocol_version: 2,
        ..Default::default()
    };
    let conn = match transport.connect(&url, Service::UploadPack, &opts_v2) {
        Ok(c) => c,
        Err(e) => {
            eprintln!("SKIP: could not connect to grit-http-server over v2: {e}");
            return;
        }
    };
    assert_eq!(
        conn.protocol_version(),
        2,
        "expected a v2 advertisement from the server"
    );
    assert!(
        conn.advertised_refs().is_empty(),
        "v2 connect carries no refs (they come from ls-refs)"
    );
    // The v2 capability block was advertised.
    assert!(
        conn.capabilities()
            .iter()
            .any(|c| c.starts_with("fetch=") || c.starts_with("ls-refs")),
        "v2 capability block missing: {:?}",
        conn.capabilities()
    );
    drop(conn);

    // 2. Fetch over v2 via http_fetch with the recording client.
    let mut opts = FetchOptions {
        refspecs: vec!["+refs/heads/*:refs/remotes/origin/*".to_owned()],
        tags: TagMode::All,
        ..Default::default()
    };
    let outcome = http_fetch(
        recording.clone(),
        &local_git,
        &url,
        &mut opts,
        &mut NoProgress,
    )
    .expect("v2 http_fetch over grit-http-server");

    // PROVE v2: the recorded POSTs include a `command=ls-refs` and a
    // `command=fetch` body (the v2 stateless flow), not a v0/v1 want/have body.
    let commands = recording.post_commands.lock().unwrap().clone();
    assert!(
        commands.iter().any(|c| c == "command=ls-refs"),
        "expected a `command=ls-refs` POST (v2 path); saw {commands:?}"
    );
    assert!(
        commands.iter().any(|c| c == "command=fetch"),
        "expected a `command=fetch` POST (v2 path); saw {commands:?}"
    );
    assert!(
        !commands.iter().any(|c| c.starts_with("want ")),
        "v2 path must not POST a bare v0/v1 want body; saw {commands:?}"
    );
    // Every request carried `Git-Protocol: version=2`.
    let protocols = recording.git_protocols.lock().unwrap().clone();
    assert!(
        protocols.iter().all(|p| p.as_deref() == Some("version=2")),
        "expected version=2 on every request; saw {protocols:?}"
    );

    // PROVE the from-scratch pack carried the FULL closure. The empty local repo
    // offers no `have`s, so the server packs every object reachable from the
    // wanted tips (2 commits + 2 trees + 2 blobs + the annotated tag = 7). Read
    // the object count straight from the demuxed `PACK` header of the response.
    let scratch_counts: Vec<u32> = recording
        .fetch_object_counts()
        .into_iter()
        .flatten()
        .collect();
    assert_eq!(
        scratch_counts.len(),
        1,
        "expected exactly one packfile-bearing command=fetch response on a from-scratch v2 fetch; saw {scratch_counts:?}"
    );
    let scratch_objs = scratch_counts[0];
    assert!(
        scratch_objs >= 6,
        "from-scratch v2 fetch should pack the full closure (>= 6 objects), packed {scratch_objs}"
    );

    // Tracking refs written.
    let got_main = resolve_ref(&local_git, "refs/remotes/origin/main").expect("origin/main");
    let got_topic = resolve_ref(&local_git, "refs/remotes/origin/topic").expect("origin/topic");
    assert_eq!(got_main, main_oid, "origin/main oid mismatch vs source");
    assert_eq!(got_topic, topic_oid, "origin/topic oid mismatch vs source");

    // Annotated tag arrived (TagMode::All).
    let got_tag = resolve_ref(&local_git, "refs/tags/v1").expect("tag v1 written");
    assert_eq!(got_tag, tag_oid, "tag v1 oid mismatch vs source");

    // Objects landed in the local odb.
    let local_odb = open_odb(&local_git);
    for oid in [main_oid, topic_oid, c1_oid, tag_oid] {
        assert!(
            local_odb.exists(&oid),
            "object {} missing from local odb after v2 http fetch",
            oid.to_hex()
        );
        local_odb
            .read(&oid)
            .unwrap_or_else(|e| panic!("read {}: {e}", oid.to_hex()));
    }

    // Per-ref update mode + default branch.
    let main_update = outcome
        .updates
        .iter()
        .find(|u| u.remote_ref == "refs/heads/main")
        .expect("update for main");
    assert_eq!(main_update.mode, UpdateMode::New);
    assert_eq!(main_update.new_oid, Some(main_oid));
    assert_eq!(outcome.default_branch.as_deref(), Some("main"));

    // Cross-check the fetched main tip against git's view of the source.
    assert_eq!(
        got_main.to_hex(),
        git(&source, &["rev-parse", "refs/heads/main"]).trim()
    );

    // The fetched pack fsck's clean in the local repo.
    let fsck = Command::new("git")
        .current_dir(&local)
        .args(["fsck", "--no-dangling"])
        .output()
        .expect("run git fsck");
    assert!(
        fsck.status.success(),
        "git fsck failed after v2 http fetch: {}",
        String::from_utf8_lossy(&fsck.stderr)
    );

    // 3. Incremental v2 fetch: advance the source's main by one commit, then
    // fetch again. Now the local repo holds history, so the v2 `command=fetch`
    // negotiation sends `have` lines — exercising the stateless acknowledgments
    // round (not just the empty-clone `wants + done` shortcut).
    std::fs::write(work.join("c.txt"), "three\n").unwrap();
    git(&work, &["add", "c.txt"]);
    git(&work, &["commit", "-q", "-m", "c3"]);
    // Refresh the served bare repo from the work tree.
    git(
        &work,
        &["push", "-q", source.to_str().expect("utf8 path"), "main"],
    );
    let new_main_oid = rev_parse(&source, "refs/heads/main");
    assert_ne!(new_main_oid, main_oid, "source main should have advanced");

    let recording2 = Arc::new(RecordingClient::new("version=2"));
    let outcome2 = http_fetch(
        recording2.clone(),
        &local_git,
        &url,
        &mut opts,
        &mut NoProgress,
    )
    .expect("incremental v2 http_fetch");
    let commands2 = recording2.post_commands.lock().unwrap().clone();
    assert!(
        commands2.iter().any(|c| c == "command=ls-refs"),
        "incremental fetch missing ls-refs; saw {commands2:?}"
    );
    assert!(
        commands2.iter().any(|c| c == "command=fetch"),
        "incremental fetch missing command=fetch; saw {commands2:?}"
    );
    let got_main2 = resolve_ref(&local_git, "refs/remotes/origin/main").expect("origin/main");
    assert_eq!(
        got_main2, new_main_oid,
        "incremental v2 fetch did not advance origin/main"
    );
    assert!(
        local_odb.exists(&new_main_oid),
        "new commit object missing after incremental v2 fetch"
    );
    let main_update2 = outcome2
        .updates
        .iter()
        .find(|u| u.remote_ref == "refs/heads/main")
        .expect("incremental update for main");
    assert_eq!(main_update2.mode, UpdateMode::FastForward);

    // PROVE the negotiation offered local history: at least one `command=fetch`
    // POST body carried a `have <oid>` line (otherwise the "minimal pack" below
    // would be meaningless — it would just be a from-scratch fetch).
    assert!(
        *recording2.fetch_sent_haves.lock().unwrap(),
        "incremental v2 fetch must POST `have` lines so the server can trim the pack"
    );

    // PROVE pack minimality: advancing `main` by exactly one commit, the server
    // must pack only that commit's new objects (commit + tree + blob = 3), NOT
    // the full closure. Compare the demuxed `PACK` object count against the
    // from-scratch count captured earlier — it must be a small constant and far
    // below the full closure. This is the decisive wire evidence that the
    // `have` negotiation actually shrank the pack.
    let inc_counts: Vec<u32> = recording2
        .fetch_object_counts()
        .into_iter()
        .flatten()
        .collect();
    assert_eq!(
        inc_counts.len(),
        1,
        "expected exactly one packfile-bearing command=fetch response on the incremental v2 fetch; saw {inc_counts:?}"
    );
    let inc_objs = inc_counts[0];
    assert!(
        inc_objs <= 4,
        "incremental v2 fetch (one new commit) must send a minimal pack (<= 4 objects), sent {inc_objs}"
    );
    assert!(
        inc_objs < scratch_objs,
        "incremental pack ({inc_objs} objects) must be smaller than the from-scratch closure ({scratch_objs})"
    );

    let fsck2 = Command::new("git")
        .current_dir(&local)
        .args(["fsck", "--no-dangling"])
        .output()
        .expect("run git fsck");
    assert!(
        fsck2.status.success(),
        "git fsck failed after incremental v2 http fetch: {}",
        String::from_utf8_lossy(&fsck2.stderr)
    );
}

/// Regression for #911: grit-cli uses `UreqHttpClient::from_config` without
/// manually calling `with_git_protocol`. Default config must negotiate v2 and
/// complete a many-ref / large-pack fetch (the v0/v1 path mis-handles this).
#[test]
fn fetch_from_config_client_v2_many_refs_and_large_pack() {
    let Some(server_bin) = find_binary("grit-http-server") else {
        eprintln!("SKIP: `grit-http-server` binary not found (build grit-http-server first)");
        return;
    };

    let tmp = tempfile::tempdir().expect("tempdir");
    let work = tmp.path().join("work");
    std::fs::create_dir_all(&work).unwrap();
    build_heavy_source(&work, 1500);

    let root = tmp.path().join("srv");
    std::fs::create_dir_all(&root).unwrap();
    let source = root.join("repo.git");
    git(
        &work,
        &[
            "clone",
            "-q",
            "--bare",
            ".",
            source.to_str().expect("utf8 path"),
        ],
    );
    git(&source, &["symbolic-ref", "HEAD", "refs/heads/main"]);

    let Some(port) = free_port() else {
        eprintln!("SKIP: could not allocate a free port");
        return;
    };
    let Some(child) = spawn_server(&server_bin, &root, port) else {
        eprintln!("SKIP: could not spawn grit-http-server");
        return;
    };
    let _guard = ServerGuard(child);
    if !wait_ready(port) {
        eprintln!("SKIP: grit-http-server did not become ready on port {port}");
        return;
    }

    let url = format!("http://127.0.0.1:{port}/repo.git");
    let local = tmp.path().join("local");
    std::fs::create_dir_all(&local).unwrap();
    git(&local, &["init", "-q", "-b", "main", "."]);
    let local_git = local.join(".git");

    let recording = Arc::new(
        RecordingClient::from_default_config().expect("from_config client for #911 regression"),
    );
    assert_eq!(
        recording.git_protocol_header(),
        Some("version=2"),
        "from_config must default to Git-Protocol version=2 (grit-cli path)"
    );
    assert!(
        UreqHttpClient::new().git_protocol_header().is_none(),
        "sanity: bare new() must not imply v2 — regression targets from_config"
    );

    let mut opts = FetchOptions {
        refspecs: vec!["+refs/heads/*:refs/remotes/origin/*".to_owned()],
        tags: TagMode::All,
        ..Default::default()
    };
    let outcome = http_fetch(
        recording.clone(),
        &local_git,
        &url,
        &mut opts,
        &mut NoProgress,
    )
    .expect("from_config v2 http_fetch over many-ref repo");

    let commands = recording.post_commands.lock().unwrap().clone();
    assert!(
        commands.iter().any(|c| c == "command=ls-refs"),
        "from_config fetch must use v2 ls-refs; saw {commands:?}"
    );
    assert!(
        commands.iter().any(|c| c == "command=fetch"),
        "from_config fetch must use v2 command=fetch; saw {commands:?}"
    );
    let branch_updates = outcome
        .updates
        .iter()
        .filter(|u| u.remote_ref.starts_with("refs/heads/branch-"))
        .count();
    assert!(
        branch_updates >= 1500,
        "expected >=1500 branch ref updates, got {branch_updates}"
    );

    let main_oid = rev_parse(&source, "refs/heads/main");
    assert_eq!(
        resolve_ref(&local_git, "refs/remotes/origin/main").expect("origin/main"),
        main_oid
    );
    let fsck = Command::new("git")
        .current_dir(&local)
        .args(["fsck", "--no-dangling"])
        .output()
        .expect("run git fsck");
    assert!(
        fsck.status.success(),
        "git fsck failed after from_config v2 fetch: {}",
        String::from_utf8_lossy(&fsck.stderr)
    );
}

#[test]
fn http_fetch_surfaces_io_error_from_upload_pack_read_failure() {
    let Some(server_bin) = find_binary("grit-http-server") else {
        eprintln!("SKIP: `grit-http-server` binary not found (build grit-http-server first)");
        return;
    };

    let tmp = tempfile::tempdir().expect("tempdir");
    let work = tmp.path().join("work");
    std::fs::create_dir_all(&work).unwrap();
    build_source(&work);

    let root = tmp.path().join("srv");
    std::fs::create_dir_all(&root).unwrap();
    let source = root.join("repo.git");
    git(
        &work,
        &[
            "clone",
            "-q",
            "--bare",
            ".",
            source.to_str().expect("utf8 path"),
        ],
    );
    git(&source, &["symbolic-ref", "HEAD", "refs/heads/main"]);

    let Some(port) = free_port() else {
        eprintln!("SKIP: could not allocate a free port");
        return;
    };
    let Some(child) = spawn_server(&server_bin, &root, port) else {
        eprintln!("SKIP: could not spawn grit-http-server");
        return;
    };
    let _guard = ServerGuard(child);
    if !wait_ready(port) {
        eprintln!("SKIP: grit-http-server did not become ready on port {port}");
        return;
    }

    let url = format!("http://127.0.0.1:{port}/repo.git");
    let local = tmp.path().join("local");
    std::fs::create_dir_all(&local).unwrap();
    git(&local, &["init", "-q", "-b", "main", "."]);
    let local_git = local.join(".git");

    let inner = UreqHttpClient::from_config(&ConfigSet::new()).expect("from_config");
    let client = http_client_arc(IoFailUploadPackClient { inner });
    let mut opts = FetchOptions {
        refspecs: vec!["+refs/heads/*:refs/remotes/origin/*".to_owned()],
        tags: TagMode::None,
        ..Default::default()
    };
    let err = http_fetch(client, &local_git, &url, &mut opts, &mut NoProgress).expect_err("I/O");
    assert!(
        matches!(err, Error::Io(_)),
        "truncated upload-pack read must surface as Io error, got {err:?}"
    );
}

/// Create an empty bare repo under `root` that receive-pack can push into, with a
/// default branch symref. Returns its on-disk path.
fn make_bare_target(root: &Path, name: &str) -> PathBuf {
    let bare = root.join(name);
    std::fs::create_dir_all(&bare).unwrap();
    git(&bare, &["init", "-q", "--bare", "."]);
    git(&bare, &["symbolic-ref", "HEAD", "refs/heads/main"]);
    bare
}

fn build_deep_history_repo(dir: &Path, commits: usize) {
    git(dir, &["init", "-q", "-b", "main", "."]);
    for i in 0..commits {
        std::fs::write(dir.join(format!("f{i:03}.txt")), format!("content {i}\n")).unwrap();
        std::fs::write(dir.join("shared.txt"), format!("shared rev {i}\n")).unwrap();
        git(dir, &["add", "-A"]);
        git(dir, &["commit", "-q", "-m", &format!("commit {i}")]);
    }
}

/// Count delta entries in a pack index the way `git verify-pack -v` reports them.
fn verify_pack_delta_count(pack_idx: &Path) -> usize {
    let out = Command::new("git")
        .args(["verify-pack", "-v"])
        .arg(pack_idx)
        .output()
        .expect("verify-pack");
    assert!(
        out.status.success(),
        "verify-pack failed: {}",
        String::from_utf8_lossy(&out.stderr)
    );
    String::from_utf8_lossy(&out.stdout)
        .lines()
        .filter(|line| line.split_whitespace().count() == 7)
        .count()
}

fn first_pack_idx(bare: &Path) -> Option<PathBuf> {
    let pack_dir = bare.join("objects/pack");
    let mut idxs: Vec<_> = std::fs::read_dir(&pack_dir)
        .ok()?
        .filter_map(|e| e.ok())
        .map(|e| e.path())
        .filter(|p| p.extension().is_some_and(|x| x == "idx"))
        .collect();
    idxs.sort();
    idxs.into_iter().next()
}

#[test]
fn push_over_smart_http_initial_pack_is_delta_compressed() {
    let Some(server_bin) = find_binary("grit-http-server") else {
        eprintln!("SKIP: `grit-http-server` binary not found (build grit-http-server first)");
        return;
    };

    let tmp = tempfile::tempdir().expect("tempdir");
    let local = tmp.path().join("local");
    std::fs::create_dir_all(&local).unwrap();
    build_deep_history_repo(&local, 50);
    git(&local, &["repack", "-adf"]);
    let local_git = local.join(".git");
    let main_oid = rev_parse(&local, "refs/heads/main");

    let root = tmp.path().join("srv");
    std::fs::create_dir_all(&root).unwrap();
    let bare = make_bare_target(&root, "delta.git");
    git(&bare, &["config", "receive.unpacklimit", "1"]);

    let Some(port) = free_port() else {
        eprintln!("SKIP: could not allocate a free port");
        return;
    };
    let Some(child) = spawn_server(&server_bin, &root, port) else {
        eprintln!("SKIP: could not spawn grit-http-server");
        return;
    };
    let _guard = ServerGuard(child);
    if !wait_ready(port) {
        eprintln!("SKIP: grit-http-server did not become ready on port {port}");
        return;
    }

    let url = format!("http://127.0.0.1:{port}/delta.git");
    let client = http_client_arc(UreqHttpClient::new());
    let spec = PushRefSpec {
        src: Some(main_oid),
        src_ref: None,
        dst: "refs/heads/main".to_owned(),
        force: false,
        delete: false,
        expected_old: None,
        expect_absent: false,
        ..Default::default()
    };
    let outcome = push_http(
        client,
        &local_git,
        &url,
        &[spec],
        &PushOptions::default(),
        &mut NoProgress,
        &grit_lib::progress::NeverCancel,
    )
    .expect("push_http initial deep history");
    assert_eq!(outcome.results[0].status, PushRefStatus::Ok);

    let Some(idx) = first_pack_idx(&bare) else {
        panic!("remote bare repo has no pack after push");
    };
    let deltas = verify_pack_delta_count(&idx);
    assert!(
        deltas > 0,
        "http push pack must contain delta objects (got {deltas})"
    );
}

#[test]
fn push_over_smart_http_lands_ref_and_objects_and_reports_rejection() {
    let Some(server_bin) = find_binary("grit-http-server") else {
        eprintln!("SKIP: `grit-http-server` binary not found (build grit-http-server first)");
        return;
    };

    // Local source repo with two commits on main.
    let tmp = tempfile::tempdir().expect("tempdir");
    let local = tmp.path().join("local");
    std::fs::create_dir_all(&local).unwrap();
    build_source(&local);
    let local_git = local.join(".git");
    let main_oid = rev_parse(&local, "refs/heads/main");
    let c1_oid = rev_parse(&local, "HEAD~1");

    // Empty bare receive target served at `/push.git` under the server root.
    let root = tmp.path().join("srv");
    std::fs::create_dir_all(&root).unwrap();
    let bare = make_bare_target(&root, "push.git");

    let Some(port) = free_port() else {
        eprintln!("SKIP: could not allocate a free port");
        return;
    };
    let Some(child) = spawn_server(&server_bin, &root, port) else {
        eprintln!("SKIP: could not spawn grit-http-server");
        return;
    };
    let _guard = ServerGuard(child);
    if !wait_ready(port) {
        eprintln!("SKIP: grit-http-server did not become ready on port {port}");
        return;
    }

    let url = format!("http://127.0.0.1:{port}/push.git");

    // Confirm the server actually offers receive-pack: GET the receive-pack
    // advertisement and require a smart-HTTP body. If it 404s / lacks the service,
    // skip rather than fail (matches the fetch test's graceful-skip policy).
    let client = http_client_arc(UreqHttpClient::new());
    let probe_url = format!("{url}/info/refs?service=git-receive-pack");
    match client.get(&probe_url, None) {
        Ok(body) if body.windows(20).any(|w| w == b"# service=git-receiv") => {}
        Ok(_) => {
            eprintln!("SKIP: server returned a non-smart receive-pack advertisement");
            return;
        }
        Err(e) => {
            eprintln!("SKIP: server does not offer receive-pack: {e}");
            return;
        }
    }

    // --- 1. Push refs/heads/main (create) -------------------------------------
    let spec = PushRefSpec {
        src: Some(main_oid),
        src_ref: None,
        dst: "refs/heads/main".to_owned(),
        force: false,
        delete: false,
        expected_old: None,
        expect_absent: false,
        ..Default::default()
    };
    let outcome = push_http(
        client.clone(),
        &local_git,
        &url,
        &[spec],
        &PushOptions::default(),
        &mut NoProgress,
        &grit_lib::progress::NeverCancel,
    )
    .expect("push_http over grit-http-server");

    assert_eq!(outcome.results.len(), 1);
    let r = &outcome.results[0];
    assert_eq!(
        r.status,
        PushRefStatus::Ok,
        "push of new ref should be accepted, got {:?} ({:?})",
        r.status,
        r.message
    );
    assert_eq!(r.new_oid, Some(main_oid));
    assert!(r.old_oid.is_none(), "new ref has no old value");

    // The remote ref now points at our main, and the objects are present.
    let remote_main = resolve_ref(&bare, "refs/heads/main").expect("remote main written");
    assert_eq!(
        remote_main, main_oid,
        "remote main oid mismatch after http push"
    );

    let remote_odb = open_odb(&bare);
    for oid in [main_oid, c1_oid] {
        assert!(
            remote_odb.exists(&oid),
            "object {} missing from remote odb after http push",
            oid.to_hex()
        );
        remote_odb
            .read(&oid)
            .unwrap_or_else(|e| panic!("read {}: {e}", oid.to_hex()));
    }

    // The bare repo fscks clean after receiving the pushed pack (cross-check with
    // system git).
    let fsck = Command::new("git")
        .current_dir(&bare)
        .args(["fsck", "--no-dangling"])
        .output()
        .expect("run git fsck");
    assert!(
        fsck.status.success(),
        "git fsck failed after http push: {}\n{}",
        String::from_utf8_lossy(&fsck.stdout),
        String::from_utf8_lossy(&fsck.stderr)
    );
    // System git agrees on the pushed tip.
    assert_eq!(
        remote_main.to_hex(),
        git(&bare, &["rev-parse", "refs/heads/main"]).trim()
    );

    // --- 2. Push a second branch (new ref over an already-populated remote) ----
    // This exercises the thin/delta pack against the advertised remote tips: the
    // remote already has main's history, so pushing `topic` (sharing that history
    // plus one new commit) should send a minimal pack and still fsck clean.
    git(&local, &["checkout", "-q", "-b", "feature"]);
    std::fs::write(local.join("t.txt"), "feature\n").unwrap();
    git(&local, &["add", "t.txt"]);
    git(&local, &["commit", "-q", "-m", "feature1"]);
    let topic_oid = rev_parse(&local, "refs/heads/feature");

    let spec_topic = PushRefSpec {
        src: Some(topic_oid),
        src_ref: None,
        dst: "refs/heads/feature".to_owned(),
        force: false,
        delete: false,
        expected_old: None,
        expect_absent: false,
        ..Default::default()
    };
    let outcome_topic = push_http(
        client.clone(),
        &local_git,
        &url,
        &[spec_topic],
        &PushOptions::default(),
        &mut NoProgress,
        &grit_lib::progress::NeverCancel,
    )
    .expect("push_http topic over grit-http-server");
    assert_eq!(outcome_topic.results[0].status, PushRefStatus::Ok);
    let remote_topic = resolve_ref(&bare, "refs/heads/feature").expect("remote feature written");
    assert_eq!(remote_topic, topic_oid);
    let fsck_topic = Command::new("git")
        .current_dir(&bare)
        .args(["fsck", "--no-dangling"])
        .output()
        .expect("run git fsck");
    assert!(
        fsck_topic.status.success(),
        "git fsck failed after second http push: {}",
        String::from_utf8_lossy(&fsck_topic.stderr)
    );

    // --- 3. Non-fast-forward push (no force) is rejected ----------------------
    // Rewrite local main onto a divergent history so it is no longer a descendant
    // of the just-pushed tip; pushing it without force must be rejected and must
    // NOT move the remote ref.
    git(&local, &["checkout", "-q", "-b", "diverge", "HEAD~2"]);
    std::fs::write(local.join("d.txt"), "diverge\n").unwrap();
    git(&local, &["add", "d.txt"]);
    git(&local, &["commit", "-q", "-m", "divergent"]);
    let diverged = rev_parse(&local, "HEAD");
    assert_ne!(diverged, main_oid);

    let nonff = PushRefSpec {
        src: Some(diverged),
        src_ref: None,
        dst: "refs/heads/main".to_owned(),
        force: false,
        delete: false,
        expected_old: None,
        expect_absent: false,
        ..Default::default()
    };
    let outcome2 = push_http(
        client.clone(),
        &local_git,
        &url,
        &[nonff],
        &PushOptions::default(),
        &mut NoProgress,
        &grit_lib::progress::NeverCancel,
    )
    .expect("non-ff push_http completes");
    assert_eq!(outcome2.results.len(), 1);
    let r2 = &outcome2.results[0];
    assert!(
        r2.status.is_error(),
        "non-fast-forward push must be rejected, got {:?}",
        r2.status
    );
    assert!(
        matches!(
            r2.status,
            PushRefStatus::RejectNonFastForward | PushRefStatus::RemoteRejected
        ),
        "expected non-ff/remote rejection, got {:?} ({:?})",
        r2.status,
        r2.message
    );

    // The remote ref must be unchanged by the rejected push.
    let remote_main_after = resolve_ref(&bare, "refs/heads/main").expect("remote main still set");
    assert_eq!(
        remote_main_after, main_oid,
        "rejected non-ff push must not move the remote ref"
    );

    // --- 4. Forced non-ff push moves the ref (cross-check with system git) -----
    let forced = PushRefSpec {
        src: Some(diverged),
        src_ref: None,
        dst: "refs/heads/main".to_owned(),
        force: true,
        delete: false,
        expected_old: None,
        expect_absent: false,
        ..Default::default()
    };
    let outcome3 = push_http(
        client.clone(),
        &local_git,
        &url,
        &[forced],
        &PushOptions::default(),
        &mut NoProgress,
        &grit_lib::progress::NeverCancel,
    )
    .expect("forced push_http completes");
    assert_eq!(
        outcome3.results[0].status,
        PushRefStatus::Ok,
        "forced non-ff push should be accepted: {:?}",
        outcome3.results[0].message
    );
    let remote_main_forced = resolve_ref(&bare, "refs/heads/main").expect("remote main moved");
    assert_eq!(
        remote_main_forced, diverged,
        "forced push should move the remote ref to the divergent tip"
    );
    assert_eq!(
        remote_main_forced.to_hex(),
        git(&bare, &["rev-parse", "refs/heads/main"]).trim()
    );
    let fsck_forced = Command::new("git")
        .current_dir(&bare)
        .args(["fsck", "--no-dangling"])
        .output()
        .expect("run git fsck");
    assert!(
        fsck_forced.status.success(),
        "git fsck failed after forced http push: {}",
        String::from_utf8_lossy(&fsck_forced.stderr)
    );
}

/// Round-trip over HTTP: push a repo to the server over `git-receive-pack`, then
/// fetch it back over `git-upload-pack` into a fresh empty repo, and assert the
/// fetched refs/objects equal what was pushed. Also drives a *server-side*
/// rejection (`receive.denyNonFastForwards=true`) to prove an `ng` report-status
/// line surfaces as [`PushRefStatus::RemoteRejected`] — the server, not the
/// client-side gate, declines the update.
#[test]
fn push_then_fetch_roundtrip_and_server_side_rejection_over_http() {
    let Some(server_bin) = find_binary("grit-http-server") else {
        eprintln!("SKIP: `grit-http-server` binary not found (build grit-http-server first)");
        return;
    };

    // Local source repo (two commits on main, a topic branch, an annotated tag).
    let tmp = tempfile::tempdir().expect("tempdir");
    let local = tmp.path().join("local");
    std::fs::create_dir_all(&local).unwrap();
    build_source(&local);
    let local_git = local.join(".git");
    let main_oid = rev_parse(&local, "refs/heads/main");
    let topic_oid = rev_parse(&local, "refs/heads/topic");
    let c1_oid = rev_parse(&local, "HEAD~1");

    // Empty bare receive target served at `/rt.git`.
    let root = tmp.path().join("srv");
    std::fs::create_dir_all(&root).unwrap();
    let bare = make_bare_target(&root, "rt.git");

    let Some(port) = free_port() else {
        eprintln!("SKIP: could not allocate a free port");
        return;
    };
    let Some(child) = spawn_server(&server_bin, &root, port) else {
        eprintln!("SKIP: could not spawn grit-http-server");
        return;
    };
    let _guard = ServerGuard(child);
    if !wait_ready(port) {
        eprintln!("SKIP: grit-http-server did not become ready on port {port}");
        return;
    }

    let url = format!("http://127.0.0.1:{port}/rt.git");

    let client = http_client_arc(UreqHttpClient::new());
    // Skip cleanly if the server lacks receive-pack (matches the other tests).
    let probe_url = format!("{url}/info/refs?service=git-receive-pack");
    match client.get(&probe_url, None) {
        Ok(body) if body.windows(20).any(|w| w == b"# service=git-receiv") => {}
        Ok(_) => {
            eprintln!("SKIP: server returned a non-smart receive-pack advertisement");
            return;
        }
        Err(e) => {
            eprintln!("SKIP: server does not offer receive-pack: {e}");
            return;
        }
    }

    // --- Push main + topic over HTTP ------------------------------------------
    let specs = [
        PushRefSpec {
            src: Some(main_oid),
            src_ref: None,
            dst: "refs/heads/main".to_owned(),
            force: false,
            delete: false,
            expected_old: None,
            expect_absent: false,
            ..Default::default()
        },
        PushRefSpec {
            src: Some(topic_oid),
            src_ref: None,
            dst: "refs/heads/topic".to_owned(),
            force: false,
            delete: false,
            expected_old: None,
            expect_absent: false,
            ..Default::default()
        },
    ];
    let push_outcome = push_http(
        client.clone(),
        &local_git,
        &url,
        &specs,
        &PushOptions::default(),
        &mut NoProgress,
        &grit_lib::progress::NeverCancel,
    )
    .expect("push_http main+topic over grit-http-server");
    for r in &push_outcome.results {
        assert_eq!(
            r.status,
            PushRefStatus::Ok,
            "push of {} should be accepted, got {:?} ({:?})",
            r.remote_ref,
            r.status,
            r.message
        );
    }
    assert_eq!(
        resolve_ref(&bare, "refs/heads/main").unwrap(),
        main_oid,
        "remote main mismatch after push"
    );
    assert_eq!(
        resolve_ref(&bare, "refs/heads/topic").unwrap(),
        topic_oid,
        "remote topic mismatch after push"
    );

    // --- Fetch the pushed repo back over HTTP into a fresh empty repo ----------
    let back = tmp.path().join("back");
    std::fs::create_dir_all(&back).unwrap();
    git(&back, &["init", "-q", "-b", "main", "."]);
    let back_git = back.join(".git");

    let mut fetch_opts = FetchOptions {
        refspecs: vec!["+refs/heads/*:refs/remotes/origin/*".to_owned()],
        tags: TagMode::None,
        ..Default::default()
    };
    let client2 = http_client_arc(UreqHttpClient::new());
    let fetch_outcome = http_fetch(
        client2.clone(),
        &back_git,
        &url,
        &mut fetch_opts,
        &mut NoProgress,
    )
    .expect("http_fetch back the just-pushed repo");

    // The round-tripped refs equal what we pushed (byte-for-byte oid equality).
    assert_eq!(
        resolve_ref(&back_git, "refs/remotes/origin/main").unwrap(),
        main_oid,
        "round-trip: fetched origin/main != pushed main"
    );
    assert_eq!(
        resolve_ref(&back_git, "refs/remotes/origin/topic").unwrap(),
        topic_oid,
        "round-trip: fetched origin/topic != pushed topic"
    );
    // And the actual objects round-tripped through push-pack -> fetch-pack.
    let back_odb = open_odb(&back_git);
    for oid in [main_oid, topic_oid, c1_oid] {
        assert!(
            back_odb.exists(&oid),
            "round-trip: object {} missing after fetch-back",
            oid.to_hex()
        );
    }
    assert!(
        fetch_outcome
            .updates
            .iter()
            .any(|u| u.remote_ref == "refs/heads/main" && u.new_oid == Some(main_oid)),
        "round-trip fetch did not report the main update"
    );
    // fsck the fetched-back repo for good measure.
    let fsck = Command::new("git")
        .current_dir(&back)
        .args(["fsck", "--no-dangling"])
        .output()
        .expect("run git fsck");
    assert!(
        fsck.status.success(),
        "git fsck failed after fetch-back: {}",
        String::from_utf8_lossy(&fsck.stderr)
    );

    // --- Server-side rejection: deny non-fast-forwards on the remote ----------
    // Turn on `receive.denyNonFastForwards` in the bare repo, then push a
    // divergent tip WITH force (so the client-side gate accepts it). The *server*
    // must decline it via an `ng <ref> non-fast-forward` report-status line,
    // which `push_http` folds into `RemoteRejected`. This exercises the
    // report-status `ng` path end-to-end over real HTTP — distinct from the
    // client-side `RejectNonFastForward` gate covered elsewhere.
    let cfg = Command::new("git")
        .current_dir(&bare)
        .args(["config", "receive.denyNonFastForwards", "true"])
        .output()
        .expect("set denyNonFastForwards");
    assert!(cfg.status.success(), "failed to set denyNonFastForwards");

    // Build a divergent commit that is not a descendant of remote main: branch
    // off c1 (main's first commit) and add a new commit, so the resulting tip is
    // a sibling of remote main (c2), never its descendant.
    git(
        &local,
        &["checkout", "-q", "-b", "rt-diverge", "refs/heads/main~1"],
    );
    std::fs::write(local.join("rt.txt"), "rt-diverge\n").unwrap();
    git(&local, &["add", "rt.txt"]);
    git(&local, &["commit", "-q", "-m", "rt-divergent"]);
    let diverged = rev_parse(&local, "HEAD");
    assert_ne!(diverged, main_oid);

    let forced_spec = PushRefSpec {
        src: Some(diverged),
        src_ref: None,
        dst: "refs/heads/main".to_owned(),
        force: true, // client accepts; server must decline (denyNonFastForwards)
        delete: false,
        expected_old: Some(main_oid),
        expect_absent: false,
        ..Default::default()
    };
    let reject_outcome = push_http(
        client.clone(),
        &local_git,
        &url,
        &[forced_spec],
        &PushOptions::default(),
        &mut NoProgress,
        &grit_lib::progress::NeverCancel,
    )
    .expect("forced push against denyNonFastForwards completes");
    assert_eq!(reject_outcome.results.len(), 1);
    let rr = &reject_outcome.results[0];
    assert_eq!(
        rr.status,
        PushRefStatus::RemoteRejected,
        "server-side denyNonFastForwards must surface as RemoteRejected, got {:?} ({:?})",
        rr.status,
        rr.message
    );
    // The remote ref must be unchanged by the server-rejected push.
    assert_eq!(
        resolve_ref(&bare, "refs/heads/main").unwrap(),
        main_oid,
        "server-rejected push must not move the remote ref"
    );
}

/// Child entry for [`http_clone_peak_rss_bounded_for_large_pack`]: reads
/// `GRIT_HTTP_RSS_URL` and `GRIT_HTTP_RSS_GIT_DIR`, runs one `http_fetch`.
#[test]
#[ignore = "spawned by http_clone_peak_rss_bounded_for_large_pack via grit-bench measure-rss"]
fn http_fetch_rss_child_process() {
    let url = std::env::var("GRIT_HTTP_RSS_URL").expect("GRIT_HTTP_RSS_URL");
    let work = PathBuf::from(std::env::var("GRIT_HTTP_RSS_WORK").expect("GRIT_HTTP_RSS_WORK"));
    let index_threads = std::env::var("GRIT_HTTP_RSS_INDEX_THREADS")
        .ok()
        .and_then(|s| s.parse().ok());
    std::fs::create_dir_all(&work).expect("work dir");
    git(&work, &["init", "-q", "-b", "main", "."]);
    let git_dir = work.join(".git");
    let mut opts = FetchOptions {
        refspecs: vec!["+refs/heads/*:refs/remotes/origin/*".to_owned()],
        initial_remote_fetch: true,
        remote_name: Some("origin".to_owned()),
        index_pack_threads: index_threads.or(Some(1)),
        pack_spool_only: true,
        ..Default::default()
    };
    let client = http_client_arc(UreqHttpClient::new());
    http_fetch(client, &git_dir, &url, &mut opts, &mut NoProgress).expect("http_fetch");
}

/// Streaming HTTP fetch must not hold the full pack in memory (peak RSS well below pack size).
#[test]
fn http_clone_peak_rss_bounded_for_large_pack() {
    const MEASURE_CMD_ENV: &str = "GRIT_BENCH_MEASURE_CMD";
    let Some(server_bin) = find_binary("grit-http-server") else {
        eprintln!("SKIP: grit-http-server binary not found");
        return;
    };
    let Some(bench_bin) = find_binary("grit-bench") else {
        eprintln!("SKIP: grit-bench binary not found (build grit-utils)");
        return;
    };
    let test_exe = std::env::current_exe().expect("current test exe");

    let tmp = tempfile::tempdir().expect("tempdir");
    let work = tmp.path().join("work");
    std::fs::create_dir_all(&work).unwrap();
    git(&work, &["init", "-q", "-b", "main", "."]);
    // Many ~1 MiB blobs (not one giant object) so index-pack can stay bounded with
    // `index_pack_threads = 1` while the on-disk pack stays ~100 MiB.
    for i in 0..100 {
        let blob = work.join(format!("blob-{i}.bin"));
        let status = Command::new("dd")
            .args([
                "if=/dev/urandom",
                &format!("of={}", blob.display()),
                "bs=1M",
                "count=1",
            ])
            .status()
            .expect("dd");
        assert!(status.success(), "dd must create blob {i}");
        git(&work, &["add", blob.file_name().unwrap().to_str().unwrap()]);
        git(&work, &["commit", "-q", "-m", &format!("c{i}")]);
    }

    let root = tmp.path().join("srv");
    std::fs::create_dir_all(&root).unwrap();
    let source = root.join("repo.git");
    git(
        &work,
        &[
            "clone",
            "-q",
            "--bare",
            ".",
            source.to_str().expect("utf8 path"),
        ],
    );
    git(&source, &["repack", "-adf"]);
    git(&source, &["prune-packed"]);

    let pack_size = std::fs::read_dir(source.join("objects/pack"))
        .expect("pack dir")
        .filter_map(|e| e.ok())
        .filter(|e| e.path().extension().is_some_and(|x| x == "pack"))
        .map(|e| e.metadata().map(|m| m.len()).unwrap_or(0))
        .max()
        .unwrap_or(0);
    assert!(
        pack_size >= 90 * 1024 * 1024,
        "expected ~100 MiB pack, got {pack_size} bytes"
    );

    let Some(port) = free_port() else {
        eprintln!("SKIP: no free port");
        return;
    };
    let Some(child) = spawn_server(&server_bin, &root, port) else {
        eprintln!("SKIP: could not spawn grit-http-server");
        return;
    };
    let _guard = ServerGuard(child);
    if !wait_ready(port) {
        eprintln!("SKIP: server not ready");
        return;
    }

    let url = format!("http://127.0.0.1:{port}/repo.git");
    let work = tmp.path().join("fetch-work");
    let measure_cmd = format!(
        "{} http_fetch_rss_child_process --ignored --exact --nocapture",
        test_exe.display()
    );
    let tmp_cwd = tmp.path().to_path_buf();
    let mut cmd = Command::new(&bench_bin);
    cmd.arg("measure-rss")
        .arg("--cwd")
        .arg(&tmp_cwd)
        .env(MEASURE_CMD_ENV, &measure_cmd)
        .env("GRIT_HTTP_RSS_URL", &url)
        .env("GRIT_HTTP_RSS_WORK", "fetch-work")
        .env("GRIT_HTTP_RSS_INDEX_THREADS", "1");
    let out = cmd.output().expect("measure-rss");
    assert!(
        out.status.success(),
        "measure-rss failed: {}",
        String::from_utf8_lossy(&out.stderr)
    );
    let peak_rss: u64 = String::from_utf8_lossy(&out.stdout)
        .trim()
        .parse()
        .expect("peak RSS bytes on stdout");
    assert!(
        peak_rss <= pack_size / 2,
        "peak RSS {peak_rss} must not scale with pack size {pack_size} (streaming ingest)"
    );
    let git_dir = work.join(".git");
    assert!(git_dir.is_dir(), "fetch must create a git dir");
    let incoming_dir = git_dir.join("objects/incoming");
    let spooled: Vec<_> = std::fs::read_dir(&incoming_dir)
        .expect("objects/incoming spool dir")
        .filter_map(|e| e.ok())
        .filter(|e| {
            e.path()
                .file_name()
                .and_then(|n| n.to_str())
                .is_some_and(|n| n.starts_with("pack-receive-") && n.ends_with(".tmp"))
        })
        .collect();
    assert_eq!(
        spooled.len(),
        1,
        "pack_spool_only fetch must leave exactly one pack-receive temp file under the repo"
    );
    let _ = std::fs::remove_file(spooled[0].path());
}

/// `git http-backend` behind the grit-bench CGI wrapper (not grit-http-server).
#[test]
fn fetch_over_git_http_backend_cgi() {
    let Some(bench_bin) = find_binary("grit-bench") else {
        eprintln!("SKIP: `grit-bench` binary not found (build grit-utils first)");
        return;
    };

    let tmp = tempfile::tempdir().expect("tempdir");
    let work = tmp.path().join("work");
    std::fs::create_dir_all(&work).unwrap();
    build_source(&work);

    let root = tmp.path().join("http-root");
    std::fs::create_dir_all(&root).unwrap();
    let bare = root.join("repo.git");
    git(
        &work,
        &[
            "clone",
            "-q",
            "--bare",
            ".",
            bare.to_str().expect("utf8 path"),
        ],
    );
    git(&bare, &["symbolic-ref", "HEAD", "refs/heads/main"]);
    let main_oid = rev_parse(&bare, "refs/heads/main");

    let Some(port) = free_port() else {
        eprintln!("SKIP: could not allocate a free port");
        return;
    };
    let Ok(child) = Command::new(&bench_bin)
        .args([
            "serve-git-http",
            "--root",
            root.to_str().expect("utf8"),
            "--bind",
            &format!("127.0.0.1:{port}"),
        ])
        .stdout(Stdio::null())
        .stderr(Stdio::null())
        .spawn()
    else {
        eprintln!("SKIP: could not spawn grit-bench serve-git-http");
        return;
    };
    let _guard = ServerGuard(child);
    if !wait_ready(port) {
        eprintln!("SKIP: git http-backend wrapper did not become ready on port {port}");
        return;
    }

    let local = tmp.path().join("local.git");
    git(
        tmp.path(),
        &["init", "-q", "--bare", local.to_str().expect("utf8")],
    );

    let url = format!("http://127.0.0.1:{port}/repo.git");
    let client = http_client_arc(UreqHttpClient::new());
    let upload_url = format!("{url}/git-upload-pack");
    let want = format!("want {main_oid} multi_ack thin-pack side-band side-band-64k");
    let mut req_body = Vec::new();
    grit_lib::remote::pkt_line::write_line_to_vec(&mut req_body, &want).unwrap();
    grit_lib::remote::pkt_line::write_flush(&mut req_body).unwrap();
    grit_lib::remote::pkt_line::write_line_to_vec(&mut req_body, "done").unwrap();
    grit_lib::remote::pkt_line::write_flush(&mut req_body).unwrap();
    let post_body = client
        .post(
            &upload_url,
            "application/x-git-upload-pack-request",
            "application/x-git-upload-pack-result",
            &req_body,
            None,
        )
        .expect("POST git-upload-pack");
    assert!(
        post_body.starts_with(b"0008"),
        "upload-pack body should start with a pkt-line, got {:?}",
        &post_body[..post_body.len().min(24)]
    );
    let mut progress = NoProgress;
    let mut fetch_opts = FetchOptions {
        refspecs: vec!["+refs/heads/*:refs/remotes/origin/*".into()],
        tags: TagMode::Following,
        ..Default::default()
    };
    http_fetch(client.clone(), &local, &url, &mut fetch_opts, &mut progress)
        .expect("http_fetch over git http-backend CGI wrapper");

    assert_eq!(
        resolve_ref(&local, "refs/remotes/origin/main").unwrap(),
        main_oid
    );
}