sdx 1.13.0

Native Xet client library for Shardline's Xet frontend.
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
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
//! Stream-group layer (M2b2, `docs/SDX_PLAN.md` §4.4.3).
//!
//! Mirrors `hf-xet-1.5.4/src/xet_session/` (`session.rs`,
//! `download_stream_group.rs`, `download_stream_handle.rs`, `task_runtime.rs`),
//! download side only:
//!
//! - [`XetStreamGroup`] owns shared session state (the client's
//!   `DownloadSessionInner`, and through it the dedicated blocking runtime and
//!   the byte-denominated buffer semaphore) and manages multiple concurrent
//!   streams with **abort-all** and per-stream **status** probes
//!   ([`XetTaskState`]). Create one via
//!   [`crate::XetClient::new_download_stream_group`].
//! - Each group holds its own root [`CancellationToken`]; every stream is
//!   created with a **child** token (mirror `TaskRuntime::child`) and
//!   registered in a weak-reference map, so dropping the stream unregisters it
//!   and `abort()` cancels the whole subtree.
//! - Streams are the M2b1 [`DownloadStream`] / [`UnorderedDownloadStream`]
//!   wrapped as [`GroupedDownloadStream`] / [`GroupedUnorderedDownloadStream`]:
//!   spawned paused, auto-start on the first `next()`, unregister on `Drop`.
//!
//! # Blocking / async-runtime trap (upstream, `docs/SDX_PLAN.md` §4.4.3)
//!
//! Upstream `xet-data` `blocking_next()` **panics inside an async runtime**
//! (upstream asserts no-runtime context). sdx's
//! [`GroupedDownloadStream::blocking_next`] runs the async `next()` future on
//! the client-owned dedicated runtime (M2b1's bridge), so group streams block
//! safely from plain CLI threads — but calling `blocking_next()` from within
//! an async context still blocks that executor thread until a chunk arrives;
//! prefer `next()` there. `blocking_next()` is compiled only on non-wasm
//! targets (wasm has no multi-thread runtime).
//!
//! # Upload side (M3b, §4.4.3)
//!
//! [`XetUploadCommit`] is the upload counterpart: it owns an
//! [`UploadSession`] and manages concurrent
//! streaming uploads ([`GroupedUploadStream`]) with abort-all and per-upload
//! status, mirroring `hf-xet` `upload_commit.rs` / `upload_stream_handle.rs`.
//! Create one via [`crate::XetClient::new_upload_group`]. The shared session
//! is finalized by [`XetUploadCommit::commit`] (uploads the session shard).

use std::collections::HashMap;
use std::ops::Range;
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
use std::sync::{Arc, Mutex, Weak};

use bytes::Bytes;
use tokio::sync::Notify;
use tokio_util::sync::CancellationToken;

use crate::{
    error::SdxError,
    session::DownloadSessionInner,
    stream::{DownloadStream, RunState, UnorderedDownloadStream},
    upload::{UploadFileInfo, UploadReport, UploadSession, UploadStreamHandle},
};

/// Per-stream task state for the group status probe.
///
/// Mirrors hf-xet `XetTaskState` (`task_runtime.rs`), adapted to the CLI's
/// vocabulary (`docs/SDX_PLAN.md` §4.4.3): `queued/in_progress/completed/
/// failed/cancelled`.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum XetTaskState {
    /// Stream created but not yet started (no `next()`/`start()` yet).
    Queued,
    /// Stream started and reconstruction is in flight.
    InProgress,
    /// Stream finished normally (the consumer observed end of stream).
    Completed,
    /// A background task failed; the error message is attached.
    Failed(String),
    /// The stream (or its group) was cancelled/aborted.
    Cancelled,
}

/// Group-unique stream id source.
static NEXT_GROUP_ID: AtomicU64 = AtomicU64::new(0);

/// A session-level group managing concurrent downloads with abort-all and
/// per-stream status.
///
/// Clone is cheap: all clones share the underlying group state. Groups are
/// independent of each other; each has its own cancellation tree.
#[derive(Clone)]
pub struct XetStreamGroup {
    inner: Arc<XetStreamGroupInner>,
}

/// All shared state owned by one [`XetStreamGroup`].
struct XetStreamGroupInner {
    session: Arc<DownloadSessionInner>,
    id: u64,
    /// Root of this group's cancellation tree; `abort()` cancels it, which
    /// propagates to every stream's child token.
    token: CancellationToken,
    aborted: AtomicBool,
    /// Weak references so dropping a stream unregisters it immediately
    /// (mirror `XetSession::active_download_stream_groups`).
    active: Mutex<HashMap<u64, Weak<StreamRegistration>>>,
    next_id: AtomicU64,
}

/// Per-stream bookkeeping shared between the group and the stream wrapper.
struct StreamRegistration {
    id: u64,
    run_state: Arc<RunState>,
    /// The paused task's start signal, so `abort()` can wake it promptly.
    start_signal: Option<Arc<Notify>>,
    started: AtomicBool,
    finished: AtomicBool,
    explicitly_cancelled: AtomicBool,
    observed_failure: Mutex<Option<String>>,
}

impl StreamRegistration {
    fn new(id: u64, stream: &DownloadStream) -> Arc<Self> {
        Arc::new(Self {
            id,
            run_state: stream.run_state(),
            start_signal: stream.pending_start_signal(),
            started: AtomicBool::new(false),
            finished: AtomicBool::new(false),
            explicitly_cancelled: AtomicBool::new(false),
            observed_failure: Mutex::new(None),
        })
    }

    fn new_unordered(id: u64, stream: &UnorderedDownloadStream) -> Arc<Self> {
        Arc::new(Self {
            id,
            run_state: stream.run_state(),
            start_signal: stream.pending_start_signal(),
            started: AtomicBool::new(false),
            finished: AtomicBool::new(false),
            explicitly_cancelled: AtomicBool::new(false),
            observed_failure: Mutex::new(None),
        })
    }

    /// Cancels this stream only (never the group or its siblings).
    fn cancel(&self) {
        self.explicitly_cancelled.store(true, Ordering::Relaxed);
        self.run_state.cancel();
        if let Some(signal) = &self.start_signal {
            signal.notify_one();
        }
    }

    fn observe_result<T>(&self, result: &Result<Option<T>, SdxError>) {
        if let Err(error) = result {
            self.observed_failure
                .lock()
                .unwrap_or_else(|poisoned| poisoned.into_inner())
                .get_or_insert_with(|| error.to_string());
        }
        if result.as_ref().is_ok_and(Option::is_none) {
            self.finished.store(true, Ordering::Relaxed);
        }
    }

    /// Computes this stream's status snapshot.
    fn state(&self, group_aborted: bool) -> XetTaskState {
        if group_aborted || self.explicitly_cancelled.load(Ordering::Relaxed) {
            return XetTaskState::Cancelled;
        }
        let observed = self
            .observed_failure
            .lock()
            .unwrap_or_else(|poisoned| poisoned.into_inner())
            .clone();
        if let Some(message) = observed.or_else(|| self.run_state.error_message()) {
            return XetTaskState::Failed(message);
        }
        if self.run_state.is_cancelled() {
            return XetTaskState::Cancelled;
        }
        if self.finished.load(Ordering::Relaxed) {
            return XetTaskState::Completed;
        }
        if self.started.load(Ordering::Relaxed) {
            return XetTaskState::InProgress;
        }
        XetTaskState::Queued
    }
}

impl XetStreamGroupInner {
    /// Registers a stream; streams created after an abort start cancelled.
    fn register(&self, registration: &Arc<StreamRegistration>) {
        if self.aborted.load(Ordering::Relaxed) {
            registration.cancel();
        }
        let mut active = self
            .active
            .lock()
            .unwrap_or_else(|poisoned| poisoned.into_inner());
        active.insert(registration.id, Arc::downgrade(registration));
    }

    /// Unregisters a stream by id (called from the wrapper's `Drop`).
    fn unregister(&self, id: u64) {
        let mut active = self
            .active
            .lock()
            .unwrap_or_else(|poisoned| poisoned.into_inner());
        active.remove(&id);
    }
}

impl XetStreamGroup {
    /// Creates a group over the client's shared session state.
    pub(crate) fn new(session: Arc<DownloadSessionInner>) -> Self {
        Self {
            inner: Arc::new(XetStreamGroupInner {
                session,
                id: NEXT_GROUP_ID.fetch_add(1, Ordering::Relaxed),
                token: CancellationToken::new(),
                aborted: AtomicBool::new(false),
                active: Mutex::new(HashMap::new()),
                next_id: AtomicU64::new(0),
            }),
        }
    }

    /// Returns the unique group id.
    #[must_use]
    pub fn id(&self) -> u64 {
        self.inner.id
    }

    /// Returns `true` after [`abort`](Self::abort) has been called.
    #[must_use]
    pub fn is_aborted(&self) -> bool {
        self.inner.aborted.load(Ordering::Relaxed)
    }

    /// Creates a sequential streaming download of `file_id` (optionally
    /// restricted to `range`), registered with this group.
    ///
    /// The background reconstruction task is spawned paused and auto-starts on
    /// the first [`GroupedDownloadStream::next`] /
    /// [`GroupedDownloadStream::blocking_next`]; dropping the stream cancels
    /// it and unregisters it from the group. Aborting the group stops the
    /// stream promptly.
    ///
    /// # Errors
    ///
    /// Returns [`SdxError`] when `file_id` is malformed, `range` is inverted,
    /// token issuance fails, or the blocking runtime cannot be resolved.
    pub async fn download_stream(
        &self,
        file_id: &str,
        range: Option<Range<u64>>,
    ) -> Result<GroupedDownloadStream, SdxError> {
        let id = self.inner.next_id.fetch_add(1, Ordering::Relaxed);
        let stream_token = self.inner.token.child_token();
        let mut reconstructor = self
            .inner
            .session
            .build_reconstructor(file_id, range)
            .await?;
        reconstructor = reconstructor.with_cancellation_token(stream_token.clone());
        let stream = reconstructor.reconstruct_to_stream();
        let registration = StreamRegistration::new(id, &stream);
        self.register(&registration);
        Ok(GroupedDownloadStream::new(
            stream,
            id,
            registration,
            Arc::downgrade(&self.inner),
        ))
    }

    /// Creates an unordered streaming download of `file_id` (optionally
    /// restricted to `range`), registered with this group.
    ///
    /// See [`download_stream`](Self::download_stream) for the lifecycle.
    ///
    /// # Errors
    ///
    /// Returns [`SdxError`] when `file_id` is malformed, `range` is inverted,
    /// token issuance fails, or the blocking runtime cannot be resolved.
    pub async fn download_unordered_stream(
        &self,
        file_id: &str,
        range: Option<Range<u64>>,
    ) -> Result<GroupedUnorderedDownloadStream, SdxError> {
        let id = self.inner.next_id.fetch_add(1, Ordering::Relaxed);
        let stream_token = self.inner.token.child_token();
        let mut reconstructor = self
            .inner
            .session
            .build_reconstructor(file_id, range)
            .await?;
        reconstructor = reconstructor.with_cancellation_token(stream_token.clone());
        let stream = reconstructor.reconstruct_to_unordered_stream();
        let registration = StreamRegistration::new_unordered(id, &stream);
        self.register(&registration);
        Ok(GroupedUnorderedDownloadStream::new(
            stream,
            id,
            registration,
            Arc::downgrade(&self.inner),
        ))
    }

    /// Aborts every active stream in this group and cancels the group's
    /// cancellation subtree.
    ///
    /// Subsequent `next()`/`blocking_next()` on any stream created by this
    /// group return `Ok(None)` promptly; the group status probe reports every
    /// stream as [`XetTaskState::Cancelled`]. Streams created after the abort
    /// start already-cancelled.
    pub fn abort(&self) {
        self.inner.aborted.store(true, Ordering::Relaxed);
        self.inner.token.cancel();
        let active = self
            .inner
            .active
            .lock()
            .unwrap_or_else(|poisoned| poisoned.into_inner());
        for weak in active.values() {
            if let Some(registration) = weak.upgrade() {
                registration.cancel();
            }
        }
    }

    /// Returns a snapshot of every live stream's status as `(stream_id,
    /// state)` pairs, ordered by stream id.
    #[must_use]
    pub fn status(&self) -> Vec<(u64, XetTaskState)> {
        let aborted = self.inner.aborted.load(Ordering::Relaxed);
        let active = self
            .inner
            .active
            .lock()
            .unwrap_or_else(|poisoned| poisoned.into_inner());
        let mut states = Vec::with_capacity(active.len());
        for (id, weak) in active.iter() {
            let Some(registration) = weak.upgrade() else {
                continue;
            };
            states.push((*id, registration.state(aborted)));
        }
        states.sort_by_key(|(id, _)| *id);
        states
    }

    /// Number of live (not-yet-dropped) streams registered with this group.
    #[must_use]
    pub fn active_stream_count(&self) -> usize {
        let active = self
            .inner
            .active
            .lock()
            .unwrap_or_else(|poisoned| poisoned.into_inner());
        active
            .values()
            .filter(|weak| weak.upgrade().is_some())
            .count()
    }

    /// Registers a stream; streams created after an abort start cancelled.
    fn register(&self, registration: &Arc<StreamRegistration>) {
        self.inner.register(registration);
    }
}

/// A group-scoped sequential streaming download handle.
///
/// Wraps the M2b1 [`DownloadStream`] with group registration: `Drop`
/// unregisters the stream, [`cancel`](Self::cancel) stops only this stream,
/// and [`task_id`](Self::task_id) identifies it in the group status probe.
pub struct GroupedDownloadStream {
    inner: DownloadStream,
    id: u64,
    registration: Arc<StreamRegistration>,
    group: Weak<XetStreamGroupInner>,
}

impl GroupedDownloadStream {
    const fn new(
        inner: DownloadStream,
        id: u64,
        registration: Arc<StreamRegistration>,
        group: Weak<XetStreamGroupInner>,
    ) -> Self {
        Self {
            inner,
            id,
            registration,
            group,
        }
    }

    /// Returns the unique stream id within its group.
    #[must_use]
    pub const fn task_id(&self) -> u64 {
        self.id
    }

    /// Unblocks the reconstruction task so it begins producing data.
    ///
    /// If already started, this is a no-op. Called automatically on the first
    /// [`next`](Self::next) / [`blocking_next`](Self::blocking_next). This
    /// method is non-async and does not require a tokio runtime context.
    pub fn start(&mut self) {
        self.registration.started.store(true, Ordering::Relaxed);
        self.inner.start();
    }

    /// Returns the next chunk of downloaded data asynchronously.
    ///
    /// Returns `Ok(None)` when the download is complete or cancelled.
    ///
    /// # Errors
    ///
    /// Returns [`SdxError`] when a background reconstruction task failed.
    pub async fn next(&mut self) -> Result<Option<Bytes>, SdxError> {
        self.registration.started.store(true, Ordering::Relaxed);
        let result = self.inner.next().await;
        self.registration.observe_result(&result);
        result
    }

    /// Returns the next chunk of downloaded data, blocking the current thread
    /// until data is available.
    ///
    /// Returns `Ok(None)` when the download is complete or cancelled.
    ///
    /// # Runtime requirements
    ///
    /// Runs the async [`next`](Self::next) on the client-owned dedicated
    /// runtime, so it works from plain CLI threads and from
    /// [`tokio::task::spawn_blocking`] **without** panicking (upstream
    /// `xet-data` panics inside an async runtime). Calling it from within an
    /// async context is supported but blocks that executor thread — prefer
    /// [`next`](Self::next) there.
    ///
    /// # Errors
    ///
    /// Returns [`SdxError`] when a background reconstruction task failed.
    #[cfg(not(target_family = "wasm"))]
    pub fn blocking_next(&mut self) -> Result<Option<Bytes>, SdxError> {
        self.registration.started.store(true, Ordering::Relaxed);
        let result = self.inner.blocking_next();
        self.registration.observe_result(&result);
        result
    }

    /// Cancels this stream only (the group and sibling streams continue).
    ///
    /// Subsequent calls to [`next`](Self::next) /
    /// [`blocking_next`](Self::blocking_next) return `Ok(None)`.
    pub fn cancel(&mut self) {
        self.registration.cancel();
        self.inner.cancel();
    }
}

impl Drop for GroupedDownloadStream {
    fn drop(&mut self) {
        if let Some(group) = self.group.upgrade() {
            group.unregister(self.id);
        }
    }
}

/// A group-scoped unordered streaming download handle.
///
/// Yields `(file_offset, Bytes)` pairs in completion order; the lifecycle
/// matches [`GroupedDownloadStream`].
pub struct GroupedUnorderedDownloadStream {
    inner: UnorderedDownloadStream,
    id: u64,
    registration: Arc<StreamRegistration>,
    group: Weak<XetStreamGroupInner>,
}

impl GroupedUnorderedDownloadStream {
    const fn new(
        inner: UnorderedDownloadStream,
        id: u64,
        registration: Arc<StreamRegistration>,
        group: Weak<XetStreamGroupInner>,
    ) -> Self {
        Self {
            inner,
            id,
            registration,
            group,
        }
    }

    /// Returns the unique stream id within its group.
    #[must_use]
    pub const fn task_id(&self) -> u64 {
        self.id
    }

    /// Unblocks the reconstruction task so it begins producing data.
    ///
    /// If already started, this is a no-op. Called automatically on the first
    /// [`next`](Self::next) / [`blocking_next`](Self::blocking_next).
    pub fn start(&mut self) {
        self.registration.started.store(true, Ordering::Relaxed);
        self.inner.start();
    }

    /// Returns the next `(file_offset, chunk)` pair asynchronously.
    ///
    /// Returns `Ok(None)` when the download is complete or cancelled.
    ///
    /// # Errors
    ///
    /// Returns [`SdxError`] when a background reconstruction task failed.
    pub async fn next(&mut self) -> Result<Option<(u64, Bytes)>, SdxError> {
        self.registration.started.store(true, Ordering::Relaxed);
        let result = self.inner.next().await;
        self.registration.observe_result(&result);
        result
    }

    /// Returns the next `(file_offset, chunk)` pair, blocking the current
    /// thread until data is available.
    ///
    /// Returns `Ok(None)` when the download is complete or cancelled.
    ///
    /// # Runtime requirements
    ///
    /// See [`GroupedDownloadStream::blocking_next`] for the dedicated-runtime
    /// bridge and the upstream panic-in-async-runtime documentation.
    ///
    /// # Errors
    ///
    /// Returns [`SdxError`] when a background reconstruction task failed.
    #[cfg(not(target_family = "wasm"))]
    pub fn blocking_next(&mut self) -> Result<Option<(u64, Bytes)>, SdxError> {
        self.registration.started.store(true, Ordering::Relaxed);
        let result = self.inner.blocking_next();
        self.registration.observe_result(&result);
        result
    }

    /// Cancels this stream only (the group and sibling streams continue).
    ///
    /// Subsequent calls to [`next`](Self::next) /
    /// [`blocking_next`](Self::blocking_next) return `Ok(None)`.
    pub fn cancel(&mut self) {
        self.registration.cancel();
        self.inner.cancel();
    }
}

impl Drop for GroupedUnorderedDownloadStream {
    fn drop(&mut self) {
        if let Some(group) = self.group.upgrade() {
            group.unregister(self.id);
        }
    }
}

// ============================================================================
// Upload side (§4.4.3): XetUploadCommit + GroupedUploadStream
// ============================================================================

/// A session-level group managing concurrent streaming uploads with abort-all
/// and per-upload status (mirror `hf-xet` `upload_commit.rs` /
/// `upload_stream_handle.rs`).
///
/// The group owns one [`UploadSession`]. [`XetUploadCommit::upload_stream`]
/// returns a [`GroupedUploadStream`] handle whose `write`/`finish` fan into
/// that shared pipeline; [`XetUploadCommit::commit`] finalizes the session
/// (uploads the session shard, xorbs-before-shard). All handles must be
/// finished before `commit`.
///
/// Clone is cheap: all clones share the underlying group state and session.
#[derive(Clone)]
pub struct XetUploadCommit {
    inner: Arc<XetUploadCommitInner>,
}

/// All shared state owned by one [`XetUploadCommit`].
struct XetUploadCommitInner {
    session: UploadSession,
    id: u64,
    token: CancellationToken,
    aborted: AtomicBool,
    active: Mutex<HashMap<u64, Weak<UploadRegistration>>>,
    next_id: AtomicU64,
    #[cfg(test)]
    registration_gate: Option<Arc<std::sync::Barrier>>,
}

/// Per-upload bookkeeping shared between the group and the handle wrapper.
struct UploadRegistration {
    handle: UploadStreamHandle,
}

impl UploadRegistration {
    fn state(&self, group_aborted: bool) -> XetTaskState {
        let flags = self.handle.status_flags();
        if group_aborted || flags.aborted {
            return XetTaskState::Cancelled;
        }
        if let Some(message) = flags.error {
            return XetTaskState::Failed(message);
        }
        if flags.finished {
            return XetTaskState::Completed;
        }
        if flags.started {
            return XetTaskState::InProgress;
        }
        XetTaskState::Queued
    }
}

impl XetUploadCommit {
    /// Creates an upload group over the client's shared session state.
    ///
    /// # Errors
    ///
    /// Returns [`SdxError`] when the group's upload session cannot be built.
    pub(crate) fn new(session: &Arc<DownloadSessionInner>) -> Result<Self, SdxError> {
        let upload_session = UploadSession::new(session)?;
        Ok(Self {
            inner: Arc::new(XetUploadCommitInner {
                session: upload_session,
                id: NEXT_GROUP_ID.fetch_add(1, Ordering::Relaxed),
                token: CancellationToken::new(),
                aborted: AtomicBool::new(false),
                active: Mutex::new(HashMap::new()),
                next_id: AtomicU64::new(0),
                #[cfg(test)]
                registration_gate: None,
            }),
        })
    }

    /// Returns the unique group id.
    #[must_use]
    pub fn id(&self) -> u64 {
        self.inner.id
    }

    /// Returns `true` after [`abort`](Self::abort) has been called.
    #[must_use]
    pub fn is_aborted(&self) -> bool {
        self.inner.aborted.load(Ordering::Relaxed)
    }

    /// Creates a streaming upload handle registered with this group.
    ///
    /// Feed data with [`GroupedUploadStream::write`] and finalize with
    /// [`GroupedUploadStream::finish`]; every handle must be finished before
    /// [`commit`](Self::commit). Dropping the handle cancels it and unregisters
    /// it from the group.
    ///
    /// # Errors
    ///
    /// Returns [`SdxError`] when the group has been aborted.
    pub fn upload_stream(&self) -> Result<GroupedUploadStream, SdxError> {
        let id = self.inner.next_id.fetch_add(1, Ordering::Relaxed);
        #[cfg(test)]
        if let Some(gate) = &self.inner.registration_gate {
            gate.wait();
            gate.wait();
        }
        // Serialize the abort check with registration: abort must either see
        // this handle in the registry, or prevent its creation altogether.
        let mut active = self
            .inner
            .active
            .lock()
            .unwrap_or_else(|poisoned| poisoned.into_inner());
        if self.inner.aborted.load(Ordering::Relaxed) {
            return Err(SdxError::UploadSession(
                "upload group aborted; cannot start new streams".to_owned(),
            ));
        }
        let handle = self.inner.session.upload_stream_handle_with_id(id);
        let registration = Arc::new(UploadRegistration {
            handle: handle.clone(),
        });
        active.insert(id, Arc::downgrade(&registration));
        Ok(GroupedUploadStream::new(
            handle,
            id,
            registration,
            Arc::downgrade(&self.inner),
        ))
    }

    /// Finalizes the shared upload session: joins all xorb uploads, then
    /// uploads the session shard.
    ///
    /// # Errors
    ///
    /// Returns [`SdxError`] when the group is already aborted, a xorb upload
    /// failed, the shard cannot be built, or the shard POST fails. Calling
    /// twice fails. An abort after commit begins does not roll back a commit
    /// already in progress.
    pub async fn commit(&self) -> Result<UploadReport, SdxError> {
        if self.inner.aborted.load(Ordering::Relaxed) {
            return Err(SdxError::UploadSession(
                "upload group aborted; cannot commit".to_owned(),
            ));
        }
        self.inner.session.finalize().await
    }

    /// Aborts every active upload in this group and cancels the group's
    /// cancellation subtree.
    ///
    /// Active [`GroupedUploadStream`] handles report [`XetTaskState::Cancelled`];
    /// handles created after the abort fail immediately.
    pub fn abort(&self) {
        self.inner.aborted.store(true, Ordering::Relaxed);
        self.inner.token.cancel();
        let active = self
            .inner
            .active
            .lock()
            .unwrap_or_else(|poisoned| poisoned.into_inner());
        for weak in active.values() {
            if let Some(registration) = weak.upgrade() {
                registration.handle.abort();
            }
        }
    }

    /// Returns a snapshot of every live upload's status as `(upload_id, state)`
    /// pairs, ordered by upload id.
    #[must_use]
    pub fn status(&self) -> Vec<(u64, XetTaskState)> {
        let aborted = self.inner.aborted.load(Ordering::Relaxed);
        let active = self
            .inner
            .active
            .lock()
            .unwrap_or_else(|poisoned| poisoned.into_inner());
        let mut states = Vec::with_capacity(active.len());
        for (id, weak) in active.iter() {
            let Some(registration) = weak.upgrade() else {
                continue;
            };
            states.push((*id, registration.state(aborted)));
        }
        states.sort_by_key(|(id, _)| *id);
        states
    }

    /// Number of live (not-yet-dropped) upload handles registered with this
    /// group.
    #[must_use]
    pub fn active_upload_count(&self) -> usize {
        let active = self
            .inner
            .active
            .lock()
            .unwrap_or_else(|poisoned| poisoned.into_inner());
        active
            .values()
            .filter(|weak| weak.upgrade().is_some())
            .count()
    }
}

impl XetUploadCommitInner {
    /// Unregisters an upload by id (called from the wrapper's `Drop`).
    fn unregister(&self, id: u64) {
        let mut active = self
            .active
            .lock()
            .unwrap_or_else(|poisoned| poisoned.into_inner());
        active.remove(&id);
    }
}

/// A group-scoped streaming upload handle.
///
/// Wraps the M3b [`UploadStreamHandle`] with group registration: `Drop`
/// unregisters (and cancels) the upload, [`cancel`](Self::cancel) stops only
/// this upload, and [`task_id`](Self::task_id) identifies it in the group
/// status probe.
pub struct GroupedUploadStream {
    handle: UploadStreamHandle,
    id: u64,
    registration: Arc<UploadRegistration>,
    group: Weak<XetUploadCommitInner>,
}

impl GroupedUploadStream {
    const fn new(
        handle: UploadStreamHandle,
        id: u64,
        registration: Arc<UploadRegistration>,
        group: Weak<XetUploadCommitInner>,
    ) -> Self {
        Self {
            handle,
            id,
            registration,
            group,
        }
    }

    /// Returns the unique upload id within its group.
    #[must_use]
    pub const fn task_id(&self) -> u64 {
        self.id
    }

    /// Feeds data into this upload's ingest pipeline.
    ///
    /// # Errors
    ///
    /// Returns [`SdxError`] when the upload is finished/aborted or a dedup /
    /// staging step fails.
    pub async fn write(&self, data: impl Into<Bytes>) -> Result<(), SdxError> {
        self.handle.write(data).await
    }

    /// Blocking version of [`write`](Self::write), bridged onto the
    /// client-owned dedicated blocking runtime (works from plain threads; the
    /// upstream `write_blocking` panics inside an async runtime — sdx's bridge
    /// does not).
    ///
    /// # Errors
    ///
    /// Returns [`SdxError`] when the blocking runtime cannot be resolved or the
    /// write fails.
    #[cfg(not(target_family = "wasm"))]
    pub fn write_blocking(&self, data: impl Into<Bytes>) -> Result<(), SdxError> {
        self.handle.write_blocking(data)
    }

    /// Finalizes this upload and returns its file result.
    ///
    /// Must be called before the group's [`commit`](XetUploadCommit::commit).
    ///
    /// # Errors
    ///
    /// Returns [`SdxError`] when the upload is already finished/aborted or a
    /// xorb cut fails.
    pub async fn finish(&self) -> Result<UploadFileInfo, SdxError> {
        self.handle.finish().await
    }

    /// Returns the finished result without finalizing, if available.
    #[must_use]
    pub fn try_finish(&self) -> Option<UploadFileInfo> {
        self.handle.try_finish()
    }

    /// Returns this upload's status snapshot.
    #[must_use]
    pub fn status(&self) -> XetTaskState {
        // The handle owns its upload session; dropping the parent group does
        // not abort it. Explicit abort is also retained in the handle flags.
        let aborted = self
            .group
            .upgrade()
            .is_some_and(|group| group.aborted.load(Ordering::Relaxed));
        self.registration.state(aborted)
    }

    /// Cancels this upload only (the group and sibling uploads continue).
    pub fn cancel(&self) {
        self.handle.abort();
    }
}

impl Drop for GroupedUploadStream {
    fn drop(&mut self) {
        self.handle.abort();
        if let Some(group) = self.group.upgrade() {
            group.unregister(self.id);
        }
    }
}

#[cfg(test)]
mod tests {
    use std::time::Duration;

    use serde_json::json;
    use tokio::time::timeout;
    use wiremock::{
        Mock, MockServer, ResponseTemplate,
        matchers::{header, method, path},
    };

    use super::*;
    use crate::{Auth, RepositoryId, XetClientBuilder};

    const FILE_ID: &str = "0000000000000000000000000000000000000000000000000000000000000000";
    const XORB_HASH: &str = "1111111111111111111111111111111111111111111111111111111111111111";
    const READ_TOKEN: &str = "read-token";

    async fn upload_controls_inside_runtime() {
        // These controls never make a request: even an untouched upload must
        // be safe to inspect, cancel, abort, and drop on an executor thread.
        let auth = Auth::new(
            "http://127.0.0.1:1",
            RepositoryId {
                provider: "github".to_owned(),
                owner: "team".to_owned(),
                repo: "assets".to_owned(),
                revision: "main".to_owned(),
            },
        )
        .unwrap()
        .with_api_key("local-test".to_owned());
        let client = XetClientBuilder::new()
            .endpoint("xet://127.0.0.1:1/github/team/assets/main")
            .auth(auth)
            .build()
            .unwrap();
        let direct = client.upload_session().unwrap().upload_stream_handle();
        direct.abort();
        assert!(direct.write(Bytes::from_static(b"late")).await.is_err());
        assert!(direct.finish().await.is_err());

        let group = client.new_upload_group().unwrap();
        let first = group.upload_stream().unwrap();
        let second = group.upload_stream().unwrap();
        assert_eq!(first.status(), XetTaskState::Queued);
        assert_eq!(group.status().len(), 2);
        first.cancel();
        assert_eq!(first.status(), XetTaskState::Cancelled);
        assert_eq!(second.status(), XetTaskState::Queued);
        drop(first);
        assert_eq!(group.active_upload_count(), 1);
        group.abort();
        assert_eq!(second.status(), XetTaskState::Cancelled);
        assert!(group.upload_stream().is_err());
        drop(second);
        assert_eq!(group.active_upload_count(), 0);
        assert!(group.status().is_empty());
    }

    #[tokio::test]
    async fn upload_controls_are_safe_in_current_thread_runtime() {
        upload_controls_inside_runtime().await;
    }

    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
    async fn upload_controls_are_safe_in_multithread_runtime() {
        upload_controls_inside_runtime().await;
    }

    async fn upload_client(server: &MockServer, shard_delay: Duration) -> crate::XetClient {
        Mock::given(method("GET"))
            .and(path("/api/github/team/assets/xet-write-token/main"))
            .respond_with(ResponseTemplate::new(200).set_body_json(json!({
                "casUrl": server.uri(), "exp": 4_000_000_000u64, "accessToken": "write-token",
            })))
            .mount(server)
            .await;
        Mock::given(method("POST"))
            .and(wiremock::matchers::path_regex(r"/v1/xorbs/default/.*"))
            .respond_with(ResponseTemplate::new(200).set_body_json(json!({"was_inserted": true})))
            .mount(server)
            .await;
        Mock::given(method("POST"))
            .and(path("/v1/shards"))
            .respond_with(
                ResponseTemplate::new(200)
                    .set_delay(shard_delay)
                    .set_body_json(json!({"result": 1})),
            )
            .mount(server)
            .await;
        client(server).await
    }

    #[tokio::test]
    async fn retained_upload_status_survives_parent_drop() {
        let server = MockServer::start().await;
        let client = upload_client(&server, Duration::ZERO).await;
        let group = client.new_upload_group().unwrap();
        let handle = group.upload_stream().unwrap();
        let group_clone = group.clone();
        drop(group);
        assert_eq!(handle.status(), XetTaskState::Queued);
        drop(group_clone);
        assert_eq!(handle.status(), XetTaskState::Queued);
        handle
            .write(Bytes::from_static(b"ordinary payload"))
            .await
            .unwrap();
        assert_eq!(handle.status(), XetTaskState::InProgress);
        let info = handle.finish().await.unwrap();
        assert_eq!(info.total_bytes, 16);
        assert_eq!(handle.try_finish(), Some(info));
        assert_eq!(handle.status(), XetTaskState::Completed);
        handle.cancel();
        assert_eq!(handle.status(), XetTaskState::Cancelled);
        assert!(handle.write(Bytes::new()).await.is_err());
        assert!(handle.finish().await.is_err());

        let aborted_group = client.new_upload_group().unwrap();
        let aborted = aborted_group.upload_stream().unwrap();
        aborted_group.abort();
        drop(aborted_group);
        assert_eq!(aborted.status(), XetTaskState::Cancelled);
        assert!(aborted.write(Bytes::new()).await.is_err());
        assert!(aborted.finish().await.is_err());
        tokio::task::unconstrained(async { drop(server) }).await;
    }

    #[tokio::test]
    async fn failed_upload_status_survives_parent_drop() {
        let server = MockServer::start().await;
        let client = upload_client(&server, Duration::ZERO).await;
        Mock::given(method("GET"))
            .and(wiremock::matchers::path_regex(
                r"/v1/chunks/default-merkledb/.*",
            ))
            .respond_with(
                ResponseTemplate::new(400).set_body_json(json!({"error": "owned failure"})),
            )
            .mount(&server)
            .await;
        let group = client.new_upload_group().unwrap();
        let handle = group.upload_stream().unwrap();
        handle
            .write(Bytes::from_static(b"ordinary payload"))
            .await
            .unwrap();
        assert!(matches!(
            handle.finish().await,
            Err(SdxError::Transfer(crate::error::TransferError::BadRequest(
                _
            )))
        ));
        let failed = handle.status();
        assert!(matches!(failed, XetTaskState::Failed(_)));
        drop(group);
        assert_eq!(handle.status(), failed);
        handle.cancel();
        assert_eq!(handle.status(), XetTaskState::Cancelled);
        tokio::task::unconstrained(async { drop(server) }).await;
    }

    #[tokio::test]
    async fn upload_constructor_resuming_after_abort_cannot_register() {
        let server = MockServer::start().await;
        let client = client(&server).await;
        let mut group = client.new_upload_group().unwrap();
        let gate = Arc::new(std::sync::Barrier::new(2));
        Arc::get_mut(&mut group.inner).unwrap().registration_gate = Some(gate.clone());
        let constructing = group.clone();
        let task = std::thread::spawn(move || constructing.upload_stream());
        // The constructor started, but has not acquired the registry lock.
        // Complete abort before allowing that acquisition to proceed.
        gate.wait();
        group.abort();
        gate.wait();
        assert!(
            matches!(task.join().unwrap(), Err(SdxError::UploadSession(message))
            if message == "upload group aborted; cannot start new streams")
        );
        assert!(group.is_aborted());
        assert_eq!(group.active_upload_count(), 0);
        assert!(group.status().is_empty());
        assert!(server.received_requests().await.unwrap().is_empty());
    }

    #[tokio::test]
    async fn pre_aborted_upload_commit_withholds_completed_and_empty_files() {
        for payload in [Vec::new(), b"ordinary payload".to_vec()] {
            for aborted in [false, true] {
                let server = MockServer::start().await;
                let client = upload_client(&server, Duration::ZERO).await;
                let group = client.new_upload_group().unwrap();
                let handle = group.upload_stream().unwrap();
                handle.write(payload.clone()).await.unwrap();
                let info = handle.finish().await.unwrap();
                if aborted {
                    group.abort();
                    assert!(
                        matches!(group.commit().await, Err(SdxError::UploadSession(message)) if message == "upload group aborted; cannot commit")
                    );
                    assert_eq!(handle.status(), XetTaskState::Cancelled);
                    assert!(group.upload_stream().is_err());
                } else {
                    let report = group.commit().await.unwrap();
                    assert_eq!(report.files, vec![info]);
                    assert_eq!(report.shard_posts, 1);
                }
                let requests = server.received_requests().await.unwrap();
                assert_eq!(
                    requests
                        .iter()
                        .filter(|request| request.method.as_str() == "POST"
                            && request.url.path() == "/v1/shards")
                        .count(),
                    usize::from(!aborted)
                );
            }
        }
    }

    #[tokio::test]
    async fn pre_aborted_empty_group_cannot_commit_healthy_empty_group_can() {
        let server = MockServer::start().await;
        let client = upload_client(&server, Duration::ZERO).await;
        let healthy = client.new_upload_group().unwrap();
        let report = healthy.commit().await.unwrap();
        assert!(report.files.is_empty());
        assert_eq!(report.shard_posts, 0);
        let aborted = client.new_upload_group().unwrap();
        aborted.abort();
        assert!(
            matches!(aborted.commit().await, Err(SdxError::UploadSession(message)) if message == "upload group aborted; cannot commit")
        );
        assert!(server.received_requests().await.unwrap().is_empty());
    }

    #[tokio::test]
    async fn abort_does_not_roll_back_an_upload_commit_already_posting() {
        let server = MockServer::start().await;
        let client = upload_client(&server, Duration::from_millis(100)).await;
        let group = client.new_upload_group().unwrap();
        let handle = group.upload_stream().unwrap();
        let info = handle.finish().await.unwrap();
        let committing_group = group.clone();
        let committing = tokio::spawn(async move { committing_group.commit().await });
        timeout(Duration::from_secs(5), async {
            loop {
                if server
                    .received_requests()
                    .await
                    .unwrap()
                    .iter()
                    .any(|request| request.url.path() == "/v1/shards")
                {
                    break;
                }
                tokio::task::yield_now().await;
            }
        })
        .await
        .unwrap();
        group.abort();
        let report = committing.await.unwrap().unwrap();
        assert_eq!(report.files, vec![info]);
        assert_eq!(report.shard_posts, 1);
    }

    fn serialize_payload(chunks: &[&[u8]]) -> Vec<u8> {
        use xet_core_structures::xorb_object::{CompressionScheme, serialize_chunk};
        let mut payload = Vec::new();
        for chunk in chunks {
            serialize_chunk(chunk, &mut payload, CompressionScheme::None).unwrap();
        }
        payload
    }

    fn v2_response_body(
        offset: u64,
        terms: serde_json::Value,
        xorbs: serde_json::Value,
    ) -> serde_json::Value {
        let mut body = serde_json::Map::new();
        body.insert(
            "offset_into_first_range".to_owned(),
            serde_json::Value::from(offset),
        );
        body.insert("terms".to_owned(), terms);
        body.insert("xorbs".to_owned(), xorbs);
        serde_json::Value::Object(body)
    }

    fn test_limits() -> crate::StreamLimits {
        crate::StreamLimits {
            min_reconstruction_fetch_size: 4096,
            max_reconstruction_fetch_size: 4096,
            min_prefetch_buffer: 8192,
            ..crate::StreamLimits::default()
        }
    }

    /// Mounts the token route and builds a client pointed at `server`.
    async fn client(server: &MockServer) -> crate::XetClient {
        Mock::given(method("GET"))
            .and(path("/api/github/team/assets/xet-read-token/main"))
            .respond_with(ResponseTemplate::new(200).set_body_json(json!({
                "casUrl": server.uri(),
                "exp": 4_000_000_000u64,
                "accessToken": READ_TOKEN,
            })))
            .mount(server)
            .await;
        let auth = Auth::new(
            &server.uri(),
            RepositoryId {
                provider: "github".to_owned(),
                owner: "team".to_owned(),
                repo: "assets".to_owned(),
                revision: "main".to_owned(),
            },
        )
        .unwrap()
        .with_api_key("bootstrap".to_owned())
        .with_subject("user".to_owned());
        let port = server.uri().split(':').next_back().unwrap().to_owned();
        XetClientBuilder::new()
            .endpoint(format!("xet://127.0.0.1:{port}/github/team/assets/main"))
            .auth(auth)
            .with_stream_limits(test_limits())
            .build()
            .unwrap()
    }

    /// Mounts a 200 reconstruction response scoped to `bytes=0-4095` plus a
    /// 416 fallback, and a 206 xorb range response (optionally delayed).
    async fn mocks(server: &MockServer, delay: Option<Duration>) {
        let payload = serialize_payload(&[&[7u8; 64], &[9u8; 64]]);
        let end = payload.len().checked_sub(1).expect("nonempty xorb fixture");
        Mock::given(method("GET"))
            .and(path(format!("/v2/reconstructions/{FILE_ID}")))
            .and(header("authorization", format!("Bearer {READ_TOKEN}")))
            .and(header("range", "bytes=0-4095"))
            .respond_with(ResponseTemplate::new(200).set_body_json(v2_response_body(
                0,
                json!([
                    {"hash": XORB_HASH, "unpacked_length": 64, "range": {"start": 0, "end": 1}},
                    {"hash": XORB_HASH, "unpacked_length": 64, "range": {"start": 1, "end": 2}}
                ]),
                json!({
                    XORB_HASH: [{
                        "url": format!("{}/transfer/xorb/default/{XORB_HASH}", server.uri()),
                        "ranges": [
                            {"chunks": {"start": 0, "end": 2}, "bytes": {"start": 0, "end": end}}
                        ]
                    }]
                }),
            )))
            .mount(server)
            .await;
        Mock::given(method("GET"))
            .and(path(format!("/v2/reconstructions/{FILE_ID}")))
            .and(header("authorization", format!("Bearer {READ_TOKEN}")))
            .respond_with(ResponseTemplate::new(416).set_body_json(json!({"error": "past eof"})))
            .mount(server)
            .await;
        let mut template = ResponseTemplate::new(206)
            .insert_header("Content-Range", format!("bytes 0-{end}/{}", payload.len()))
            .set_body_raw(payload, "application/octet-stream");
        if let Some(delay) = delay {
            template = template.set_delay(delay);
        }
        Mock::given(method("GET"))
            .and(path(format!("/transfer/xorb/default/{XORB_HASH}")))
            .and(header("authorization", format!("Bearer {READ_TOKEN}")))
            .and(header("range", format!("bytes=0-{end}")))
            .respond_with(template)
            .mount(server)
            .await;
    }

    async fn drain(stream: &mut GroupedDownloadStream) -> Vec<u8> {
        let mut out = Vec::new();
        while let Some(chunk) = stream.next().await.unwrap() {
            out.extend_from_slice(&chunk);
        }
        out
    }

    #[tokio::test]
    async fn status_transitions_queued_to_in_progress_to_completed() {
        let server = MockServer::start().await;
        mocks(&server, None).await;
        let group = client(&server).await.new_download_stream_group();

        let mut stream = group.download_stream(FILE_ID, None).await.unwrap();
        let id = stream.task_id();
        assert_eq!(group.active_stream_count(), 1);
        assert!(group.status().contains(&(id, XetTaskState::Queued)));

        let chunk = stream.next().await.unwrap().unwrap();
        assert_eq!(chunk.as_ref(), vec![7u8; 64]);
        assert!(group.status().contains(&(id, XetTaskState::InProgress)));

        // The first chunk was consumed above; the rest is the second chunk.
        let out = drain(&mut stream).await;
        assert_eq!(out, vec![9u8; 64]);
        assert!(group.status().contains(&(id, XetTaskState::Completed)));
    }

    #[tokio::test]
    async fn pending_reconstruction_block_is_in_progress_until_observed_eof() {
        for unordered in [false, true] {
            let server = MockServer::start().await;
            let payload = serialize_payload(&[&[7u8; 64]]);
            let end = payload.len().checked_sub(1).expect("nonempty fixture");
            let body = v2_response_body(
                0,
                serde_json::Value::Array(vec![
                    json!({
                        "hash": XORB_HASH, "unpacked_length": 64,
                        "range": {"start": 0, "end": 1}
                    });
                    64
                ]),
                json!({XORB_HASH: [{
                    "url": format!("{}/transfer/xorb/default/{XORB_HASH}", server.uri()),
                    "ranges": [{"chunks": {"start": 0, "end": 1},
                                "bytes": {"start": 0, "end": end}}]
                }]}),
            );
            let entered = Arc::new(Notify::new());
            let release = Arc::new(Notify::new());
            let entered_handler = entered.clone();
            let release_handler = release.clone();
            let second_body = body.clone();
            let app = axum::Router::new().route(
                "/second",
                axum::routing::get(move || {
                    let entered = entered_handler.clone();
                    let release = release_handler.clone();
                    let body = second_body.clone();
                    async move {
                        entered.notify_one();
                        release.notified().await;
                        axum::Json(body)
                    }
                }),
            );
            let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
            let address = listener.local_addr().unwrap();
            let gate_server = tokio::spawn(async move { axum::serve(listener, app).await });
            Mock::given(method("GET"))
                .and(path(format!("/v2/reconstructions/{FILE_ID}")))
                .and(header("range", "bytes=0-4095"))
                .respond_with(ResponseTemplate::new(200).set_body_json(body))
                .mount(&server)
                .await;
            Mock::given(method("GET"))
                .and(path(format!("/v2/reconstructions/{FILE_ID}")))
                .and(header("range", "bytes=4096-8191"))
                .respond_with(
                    ResponseTemplate::new(307)
                        .insert_header("Location", format!("http://{address}/second")),
                )
                .mount(&server)
                .await;
            Mock::given(method("GET"))
                .and(path(format!("/v2/reconstructions/{FILE_ID}")))
                .respond_with(ResponseTemplate::new(416))
                .mount(&server)
                .await;
            Mock::given(method("GET"))
                .and(path(format!("/transfer/xorb/default/{XORB_HASH}")))
                .respond_with(
                    ResponseTemplate::new(206)
                        .insert_header("Content-Range", format!("bytes 0-{end}/{}", payload.len()))
                        .set_body_raw(payload, "application/octet-stream"),
                )
                .mount(&server)
                .await;
            let group = client(&server).await.new_download_stream_group();
            let mut out = Vec::new();
            if unordered {
                let mut stream = group
                    .download_unordered_stream(FILE_ID, None)
                    .await
                    .unwrap();
                for _ in 0..64 {
                    let (_, chunk) = stream.next().await.unwrap().unwrap();
                    out.extend_from_slice(&chunk);
                }
                timeout(Duration::from_secs(3), entered.notified())
                    .await
                    .unwrap();
                assert_eq!(out, vec![7u8; 4096]);
                assert!(
                    group
                        .status()
                        .contains(&(stream.task_id(), XetTaskState::InProgress))
                );
                release.notify_one();
                while let Some((_, chunk)) = stream.next().await.unwrap() {
                    out.extend_from_slice(&chunk);
                }
                assert!(
                    group
                        .status()
                        .contains(&(stream.task_id(), XetTaskState::Completed))
                );
            } else {
                let mut stream = group.download_stream(FILE_ID, None).await.unwrap();
                for _ in 0..64 {
                    out.extend_from_slice(&stream.next().await.unwrap().unwrap());
                }
                timeout(Duration::from_secs(3), entered.notified())
                    .await
                    .unwrap();
                assert_eq!(out, vec![7u8; 4096]);
                assert!(
                    group
                        .status()
                        .contains(&(stream.task_id(), XetTaskState::InProgress))
                );
                release.notify_one();
                while let Some(chunk) = stream.next().await.unwrap() {
                    out.extend_from_slice(&chunk);
                }
                assert!(
                    group
                        .status()
                        .contains(&(stream.task_id(), XetTaskState::Completed))
                );
            }
            assert_eq!(out, vec![7u8; 8192]);
            assert!(group.status().is_empty());
            gate_server.abort();
            assert!(gate_server.await.unwrap_err().is_cancelled());
            tokio::task::unconstrained(async { drop(server) }).await;
        }
    }

    #[tokio::test]
    async fn blocking_download_wrappers_complete_only_after_eof() {
        for unordered in [false, true] {
            let server = MockServer::start().await;
            mocks(&server, None).await;
            let group = client(&server).await.new_download_stream_group();
            if unordered {
                let mut stream = group
                    .download_unordered_stream(FILE_ID, None)
                    .await
                    .unwrap();
                let group_probe = group.clone();
                tokio::task::spawn_blocking(move || {
                    let id = stream.task_id();
                    let mut out = Vec::new();
                    for _ in 0..2 {
                        let (_, chunk) = stream.blocking_next().unwrap().unwrap();
                        out.extend_from_slice(&chunk);
                    }
                    assert!(
                        group_probe
                            .status()
                            .contains(&(id, XetTaskState::InProgress))
                    );
                    assert!(stream.blocking_next().unwrap().is_none());
                    assert!(
                        group_probe
                            .status()
                            .contains(&(id, XetTaskState::Completed))
                    );
                    out.sort_unstable();
                    assert_eq!(out, [vec![7u8; 64], vec![9u8; 64]].concat());
                })
                .await
                .unwrap();
            } else {
                let mut stream = group.download_stream(FILE_ID, None).await.unwrap();
                let group_probe = group.clone();
                tokio::task::spawn_blocking(move || {
                    let id = stream.task_id();
                    let mut out = Vec::new();
                    for _ in 0..2 {
                        out.extend_from_slice(&stream.blocking_next().unwrap().unwrap());
                    }
                    assert!(
                        group_probe
                            .status()
                            .contains(&(id, XetTaskState::InProgress))
                    );
                    assert!(stream.blocking_next().unwrap().is_none());
                    assert!(
                        group_probe
                            .status()
                            .contains(&(id, XetTaskState::Completed))
                    );
                    assert_eq!(out, [vec![7u8; 64], vec![9u8; 64]].concat());
                })
                .await
                .unwrap();
            }
            assert!(group.status().is_empty());
            tokio::task::unconstrained(async { drop(server) }).await;
        }
    }

    #[tokio::test]
    async fn download_failure_status_survives_typed_error_consumption_and_eof() {
        for unordered in [false, true] {
            for blocking in [false, true] {
                let server = MockServer::start().await;
                let group = client(&server).await.new_download_stream_group();
                Mock::given(method("GET"))
                    .and(wiremock::matchers::path_regex(r".*/reconstructions/.*"))
                    .respond_with(
                        ResponseTemplate::new(404)
                            .set_body_json(json!({"error": "owned reconstruction failure"})),
                    )
                    .mount(&server)
                    .await;
                if unordered {
                    let mut stream = group
                        .download_unordered_stream(FILE_ID, None)
                        .await
                        .unwrap();
                    let id = stream.task_id();
                    stream.start();
                    timeout(Duration::from_secs(5), async {
                        while stream.registration.run_state.error_message().is_none() {
                            tokio::task::yield_now().await;
                        }
                    })
                    .await
                    .unwrap();
                    assert!(group.status().contains(&(
                        id,
                        XetTaskState::Failed(
                            "not found (404): owned reconstruction failure".to_owned()
                        )
                    )));
                    let result = if blocking {
                        let (returned, result) = tokio::task::spawn_blocking(move || {
                            let result = stream.blocking_next();
                            (stream, result)
                        })
                        .await
                        .unwrap();
                        stream = returned;
                        result
                    } else {
                        stream.next().await
                    };
                    assert!(
                        matches!(result, Err(SdxError::Transfer(crate::error::TransferError::NotFound(message)))
                        if message == "owned reconstruction failure")
                    );
                    assert!(stream.next().await.unwrap().is_none());
                    assert!(group.status().contains(&(
                        id,
                        XetTaskState::Failed(
                            "not found (404): owned reconstruction failure".to_owned()
                        )
                    )));
                    stream.cancel();
                    assert!(group.status().contains(&(id, XetTaskState::Cancelled)));
                } else {
                    let mut stream = group.download_stream(FILE_ID, None).await.unwrap();
                    let id = stream.task_id();
                    stream.start();
                    timeout(Duration::from_secs(5), async {
                        while stream.registration.run_state.error_message().is_none() {
                            tokio::task::yield_now().await;
                        }
                    })
                    .await
                    .unwrap();
                    assert!(group.status().contains(&(
                        id,
                        XetTaskState::Failed(
                            "not found (404): owned reconstruction failure".to_owned()
                        )
                    )));
                    let result = if blocking {
                        let (returned, result) = tokio::task::spawn_blocking(move || {
                            let result = stream.blocking_next();
                            (stream, result)
                        })
                        .await
                        .unwrap();
                        stream = returned;
                        result
                    } else {
                        stream.next().await
                    };
                    assert!(
                        matches!(result, Err(SdxError::Transfer(crate::error::TransferError::NotFound(message)))
                        if message == "owned reconstruction failure")
                    );
                    assert!(stream.next().await.unwrap().is_none());
                    assert!(group.status().contains(&(
                        id,
                        XetTaskState::Failed(
                            "not found (404): owned reconstruction failure".to_owned()
                        )
                    )));
                    stream.cancel();
                    assert!(group.status().contains(&(id, XetTaskState::Cancelled)));
                }
            }
        }
    }

    #[tokio::test]
    async fn group_abort_prevents_a_new_read_after_a_delivered_chunk() {
        for unordered in [false, true] {
            let server = MockServer::start().await;
            mocks(&server, None).await;
            let group = client(&server).await.new_download_stream_group();
            if unordered {
                let mut stream = group
                    .download_unordered_stream(FILE_ID, None)
                    .await
                    .unwrap();
                let id = stream.task_id();
                assert_eq!(stream.next().await.unwrap().unwrap().1.len(), 64);
                group.abort();
                assert!(stream.next().await.unwrap().is_none());
                assert!(group.status().contains(&(id, XetTaskState::Cancelled)));
            } else {
                let mut stream = group.download_stream(FILE_ID, None).await.unwrap();
                let id = stream.task_id();
                assert_eq!(stream.next().await.unwrap().unwrap().len(), 64);
                group.abort();
                assert!(stream.next().await.unwrap().is_none());
                assert!(group.status().contains(&(id, XetTaskState::Cancelled)));
            }
        }
    }

    #[tokio::test]
    async fn abort_mid_stream_stops_promptly() {
        let server = MockServer::start().await;
        mocks(&server, Some(Duration::from_secs(30))).await;
        let group = client(&server).await.new_download_stream_group();

        let mut stream = group.download_stream(FILE_ID, None).await.unwrap();
        let id = stream.task_id();
        // The xorb fetch is delayed, so next() blocks until the group aborts.
        let abort = {
            let group = group.clone();
            tokio::spawn(async move {
                tokio::time::sleep(Duration::from_millis(100)).await;
                group.abort();
            })
        };
        let next = timeout(Duration::from_secs(5), stream.next())
            .await
            .expect("abort must stop the stream promptly")
            .unwrap();
        assert!(next.is_none());
        abort.await.unwrap();
        assert!(group.is_aborted());
        assert!(group.status().contains(&(id, XetTaskState::Cancelled)));
    }

    #[tokio::test]
    async fn abort_cancels_queued_streams_too() {
        let server = MockServer::start().await;
        mocks(&server, Some(Duration::from_secs(30))).await;
        let group = client(&server).await.new_download_stream_group();

        // A queued (never started) stream alongside a running one.
        let mut queued = group.download_stream(FILE_ID, None).await.unwrap();
        let queued_id = queued.task_id();
        let mut running = group.download_stream(FILE_ID, None).await.unwrap();
        let running_id = running.task_id();

        group.abort();
        let next = timeout(Duration::from_secs(5), running.next())
            .await
            .expect("abort must stop the running stream")
            .unwrap();
        assert!(next.is_none());
        let next = timeout(Duration::from_secs(5), queued.next())
            .await
            .expect("abort must stop the queued stream")
            .unwrap();
        assert!(next.is_none());

        let status = group.status();
        assert!(status.contains(&(queued_id, XetTaskState::Cancelled)));
        assert!(status.contains(&(running_id, XetTaskState::Cancelled)));
    }

    #[tokio::test]
    async fn drop_unregisters_stream_from_group() {
        let server = MockServer::start().await;
        mocks(&server, None).await;
        let group = client(&server).await.new_download_stream_group();

        let stream = group.download_stream(FILE_ID, None).await.unwrap();
        assert_eq!(group.active_stream_count(), 1);
        drop(stream);
        assert_eq!(group.active_stream_count(), 0);
        assert!(group.status().is_empty());
    }

    #[tokio::test]
    async fn two_concurrent_streams_are_byte_identical() {
        let server = MockServer::start().await;
        mocks(&server, None).await;
        let group = client(&server).await.new_download_stream_group();
        let expected = [vec![7u8; 64], vec![9u8; 64]].concat();

        let mut a = group.download_stream(FILE_ID, None).await.unwrap();
        let mut b = group
            .download_unordered_stream(FILE_ID, None)
            .await
            .unwrap();
        let task_a = tokio::spawn(async move { drain(&mut a).await });
        let task_b = tokio::spawn(async move {
            let mut pieces = Vec::new();
            while let Some((offset, chunk)) = b.next().await.unwrap() {
                pieces.push((offset, chunk));
            }
            pieces.sort_by_key(|(offset, _)| *offset);
            let mut out = Vec::new();
            for (_, chunk) in pieces {
                out.extend_from_slice(&chunk);
            }
            out
        });
        let out_a = task_a.await.unwrap();
        let out_b = task_b.await.unwrap();
        assert_eq!(out_a, expected);
        assert_eq!(out_b, expected);
        assert_eq!(group.active_stream_count(), 0);
    }

    #[tokio::test]
    async fn stream_cancel_does_not_cancel_siblings() {
        let server = MockServer::start().await;
        mocks(&server, None).await;
        let group = client(&server).await.new_download_stream_group();
        let expected = [vec![7u8; 64], vec![9u8; 64]].concat();

        let mut a = group.download_stream(FILE_ID, None).await.unwrap();
        let mut b = group.download_stream(FILE_ID, None).await.unwrap();
        a.cancel();
        assert!(a.next().await.unwrap().is_none());
        // b is untouched and still completes.
        let out = drain(&mut b).await;
        assert_eq!(out, expected);
    }

    #[test]
    fn xet_task_state_is_comparable() {
        assert_eq!(XetTaskState::Queued, XetTaskState::Queued);
        assert_ne!(XetTaskState::Queued, XetTaskState::InProgress);
        assert_ne!(
            XetTaskState::Failed("x".to_owned()),
            XetTaskState::Failed("y".to_owned())
        );
    }
}