hf-xet 1.5.1

Client library and tooling for the Hugging Face Xet data storage system.
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
//! XetSession - manages runtime and configuration

use std::collections::HashMap;
use std::sync::{Arc, Mutex, Weak};

use tracing::info;
use ulid::Ulid;
use xet_data::progress_tracking::UniqueID;
use xet_runtime::RuntimeError;
use xet_runtime::config::XetConfig;
use xet_runtime::core::XetRuntime;
#[cfg(feature = "fd-track")]
use xet_runtime::fd_diagnostics::{report_fd_count, track_fd_scope};

use super::download_stream_group::{
    XetDownloadStreamGroup, XetDownloadStreamGroupBuilder, XetDownloadStreamGroupInner,
};
use super::errors::SessionError;
use super::file_download_group::XetFileDownloadGroupBuilder;
use super::task_runtime::{TaskRuntime, XetTaskState};
use super::upload_commit::XetUploadCommitBuilder;

/// All shared state for a session.
/// Lives behind `Arc<XetSessionInner>` — do not use this type directly.
#[doc(hidden)]
pub struct XetSessionInner {
    // Independently cloned by background tasks, so needs its own Arc.
    pub(super) runtime: Arc<XetRuntime>,

    // Only accessed through &self; no independent cloning needed.
    pub(super) config: XetConfig,

    // Root of the cancellation tree. Child commits/groups create child TaskRuntimes via
    // task_runtime.child(), which links their cancellation tokens to this root. Calling
    // cancel_subtree() here propagates cancellation to all descendants automatically.
    //
    // IMPORTANT: Do NOT add maps of active commits or download groups to this struct.
    // Storing strong (or even Weak) references to child objects here creates a circular
    // dependency (session → child → session) that prevents cleanup and leaks file handles.
    // All abort propagation is handled through the TaskRuntime cancellation token tree.
    pub(super) task_runtime: Arc<TaskRuntime>,

    // Weak references so that dropping all user-held XetDownloadStreamGroup clones frees the group
    // immediately, without needing an explicit finalization call. abort() upgrades live weak refs
    // to cancel active streams.
    pub(super) active_download_stream_groups: Mutex<HashMap<UniqueID, Weak<XetDownloadStreamGroupInner>>>,

    // "id" is used to identify a group of activities on our server, and so needs to be globally unique
    pub(super) id: Ulid,
}

/// Builder for [`XetSession`].
///
/// All fields are optional; call [`build`](XetSessionBuilder::build) when done.
///
/// ## Runtime detection
///
/// [`build`](Self::build) auto-detects a suitable tokio runtime:
///
/// - **Inside `#[tokio::main]` or an existing tokio multi-thread runtime** and the runtime meets the requirements — the
///   session wraps the caller's handle; no second thread pool is created.  Both async and blocking methods work.
/// - **Outside any runtime** — an owned multi-thread runtime is created internally. Blocking methods (`_blocking`
///   suffix) work from any thread; async methods work via an internal bridge.
/// - **Explicit handle** — call [`with_tokio_handle`](Self::with_tokio_handle) to supply a handle directly.  If it
///   doesn't meet requirements (multi-thread, time + IO drivers), it is silently ignored and an owned runtime is
///   created instead.
///
/// ## Authentication
///
/// Auth tokens are configured per-operation on the builder returned by each factory method, not on the
/// session itself.  This lets uploads and downloads use different access-level
/// tokens from the same session:
///
/// ```rust,no_run
/// # use http::HeaderMap;
/// # use xet::xet_session::XetSessionBuilder;
/// let session = XetSessionBuilder::new().build()?;
///
/// // Upload token (write access)
/// let mut upload_headers = HeaderMap::new();
/// upload_headers.insert("Authorization", "Bearer hub-write-token".parse().unwrap());
/// let commit = session
///     .new_upload_commit()?
///     .with_endpoint("https://cas.example.com")
///     .with_token_info("CAS_WRITE_JWT", 900)
///     .with_token_refresh_url("https://huggingface.co/api/repos/token/write", upload_headers)
///     .build_blocking()?;
///
/// // File download token (read access)
/// let mut dl_headers = HeaderMap::new();
/// dl_headers.insert("Authorization", "Bearer hub-read-token".parse().unwrap());
/// let group = session
///     .new_file_download_group()?
///     .with_token_info("CAS_READ_JWT", 900)
///     .with_token_refresh_url("https://huggingface.co/api/repos/token/read", dl_headers)
///     .build_blocking()?;
///
/// // Streaming download token (read access, different group/pool)
/// let mut stream_headers = HeaderMap::new();
/// stream_headers.insert("Authorization", "Bearer hub-read-token".parse().unwrap());
/// let stream_group = session
///     .new_download_stream_group()?
///     .with_token_info("CAS_READ_JWT", 900)
///     .with_token_refresh_url("https://huggingface.co/api/repos/token/read", stream_headers)
///     .build_blocking()?;
/// # Ok::<(), xet::xet_session::SessionError>(())
/// ```
///
/// ## `XetConfig`
///
/// For most use cases, [`new`](Self::new) with the default [`XetConfig`] is
/// sufficient.  Use [`new_with_config`](Self::new_with_config) when you need to
/// override runtime settings such as cache directories or concurrency limits.
pub struct XetSessionBuilder {
    config: XetConfig,
    tokio_handle: Option<tokio::runtime::Handle>,
}

impl Default for XetSessionBuilder {
    fn default() -> Self {
        Self::new()
    }
}

impl XetSessionBuilder {
    /// Create a builder with default [`XetConfig`].
    pub fn new() -> Self {
        Self {
            config: XetConfig::new(),
            tokio_handle: None,
        }
    }

    /// Create a builder pre-populated with the given [`XetConfig`].
    pub fn new_with_config(config: XetConfig) -> Self {
        Self {
            config,
            tokio_handle: None,
        }
    }

    /// Attach to an existing tokio runtime handle.
    ///
    /// If the handle meets runtime requirements (multi-thread flavor, time driver, IO driver),
    /// the session will wrap it — no second thread pool is created. Only async
    /// methods (`new_upload_commit`, `new_file_download_group`) may be called; `_blocking` variants
    /// return [`SessionError::WrongRuntimeMode`] from `bridge_sync` (external runtime cannot run sync bridge).
    ///
    /// If the handle does **not** meet requirements (e.g. `current_thread` flavor or missing
    /// drivers), it is silently ignored and [`build`](Self::build) will fall back to creating
    /// an owned thread pool instead.
    ///
    /// If the handle is already in use by another live `XetSession`, [`build`](Self::build) will
    /// also fall back to creating an owned thread pool — the duplicate is logged at `INFO` level
    /// and no error is returned.
    pub fn with_tokio_handle(self, handle: tokio::runtime::Handle) -> Self {
        let accept = XetRuntime::handle_meets_requirements(&handle);
        if !accept {
            info!("supplied tokio handle rejected (missing drivers or wrong flavor); falling back to Owned mode");
        }
        Self {
            tokio_handle: accept.then_some(handle),
            ..self
        }
    }

    /// Consume the builder and create a [`XetSession`].
    ///
    /// If a tokio runtime handle is available (either from
    /// [`with_tokio_handle`](Self::with_tokio_handle) or auto-detected via
    /// `Handle::try_current()`), and it meets requirements, the session wraps
    /// it — no second thread pool is created. Otherwise, an owned multi-thread
    /// runtime is created; async methods use an internal bridge and work from
    /// any executor, and `_blocking` methods are available.
    ///
    /// If the detected or provided handle is already registered to another live `XetSession`,
    /// the duplicate attach is silently rejected and an owned runtime is created instead.
    /// This prevents two sessions from fighting over the same tokio runtime's task scheduler.
    pub fn build(self) -> Result<XetSession, SessionError> {
        #[cfg(feature = "fd-track")]
        let _fd_scope = track_fd_scope("XetSessionBuilder::build");

        let handle = self.tokio_handle.or_else(|| {
            tokio::runtime::Handle::try_current()
                .ok()
                .filter(XetRuntime::handle_meets_requirements)
        });

        let runtime = match handle {
            Some(h) => {
                info!("XetSession using External runtime (wrapping caller's tokio handle)");
                let result = XetRuntime::from_external_with_config(h, self.config.clone());
                match result {
                    Ok(runtime) => runtime,
                    Err(RuntimeError::ExternalAlreadyAttached(_)) => {
                        info!(
                            "An existing XetSession already wraps caller's tokio handle, switching to creating Owned runtime"
                        );
                        XetRuntime::new_with_config(self.config.clone())?
                    },
                    Err(e) => Err(e)?,
                }
            },
            None => {
                info!("XetSession creating Owned runtime (new thread pool)");
                XetRuntime::new_with_config(self.config.clone())?
            },
        };

        let session = XetSession::new(self.config, runtime);
        info!("Session created, session_id={}", session.inner.id);
        #[cfg(feature = "fd-track")]
        report_fd_count("XetSessionBuilder::build complete");
        Ok(session)
    }
}

/// Handle for managing file uploads and downloads.
///
/// `XetSession` is the top-level entry point for the xet-session API.  It
/// owns a `XetRuntime` (tokio thread pool) and shared HTTP settings (endpoint,
/// custom headers).  Auth tokens are configured per-operation on the builder
/// types returned by each factory method, not on the session itself, so uploads,
/// file downloads, and streaming downloads can each carry a different access-level
/// token from the same session.
///
/// # Cloning
///
/// Cloning is cheap — it simply increments an atomic reference count.
/// All clones share the same underlying runtime and configuration.
///
/// # Lifecycle
///
/// 1. Create a session with [`XetSessionBuilder`].
/// 2. Create operations:
///    - uploads via [`new_upload_commit`](Self::new_upload_commit) → [`XetUploadCommitBuilder`] → [`XetUploadCommit`]
///    - file downloads via [`new_file_download_group`](Self::new_file_download_group) → [`XetFileDownloadGroupBuilder`]
///      → [`XetFileDownloadGroup`]
///    - streaming downloads via [`new_download_stream_group`](Self::new_download_stream_group) →
///      [`XetDownloadStreamGroupBuilder`] → [`XetDownloadStreamGroup`]
/// 3. For an emergency stop, call [`XetSession::abort`].
#[derive(Clone)]
pub struct XetSession {
    pub(super) inner: Arc<XetSessionInner>,
}

impl XetSession {
    /// Low-level constructor used by [`XetSessionBuilder::build`].
    fn new(config: XetConfig, runtime: Arc<XetRuntime>) -> Self {
        let task_runtime = TaskRuntime::new_root(runtime.clone());
        Self {
            inner: Arc::new(XetSessionInner {
                runtime,
                config,
                task_runtime,
                active_download_stream_groups: Mutex::new(HashMap::new()),
                id: Ulid::new(),
            }),
        }
    }

    /// Create a [`XetUploadCommitBuilder`] for configuring and constructing an upload commit.
    ///
    /// Configure the builder with any combination of:
    /// - [`with_endpoint`](XetUploadCommitBuilder::with_endpoint) — CAS server URL (if omitted, resolved from the token
    ///   refresh response or the session default)
    /// - [`with_custom_headers`](XetUploadCommitBuilder::with_custom_headers) — extra HTTP headers forwarded with every
    ///   CAS request
    /// - [`with_token_info`](XetUploadCommitBuilder::with_token_info) — pre-seeded CAS token and expiry to skip the
    ///   initial refresh round-trip
    /// - [`with_token_refresh_url`](XetUploadCommitBuilder::with_token_refresh_url) — URL and auth headers for
    ///   refreshing the CAS token
    ///
    /// Then call [`build`](XetUploadCommitBuilder::build) (async) or
    /// [`build_blocking`](XetUploadCommitBuilder::build_blocking) (sync).
    ///
    /// Returns `Err(SessionError::UserCancelled)` if the session has been aborted.
    pub fn new_upload_commit(&self) -> Result<XetUploadCommitBuilder, SessionError> {
        self.inner.task_runtime.check_state("new_upload_commit")?;
        #[cfg(feature = "fd-track")]
        report_fd_count("XetSession::new_upload_commit");
        Ok(XetUploadCommitBuilder::new(self.clone()))
    }

    /// Create a [`XetFileDownloadGroupBuilder`] for configuring and constructing a file download group.
    ///
    /// Configure the builder with any combination of:
    /// - [`with_endpoint`](XetFileDownloadGroupBuilder::with_endpoint) — CAS server URL (if omitted, resolved from the
    ///   token refresh response or the session default)
    /// - [`with_custom_headers`](XetFileDownloadGroupBuilder::with_custom_headers) — extra HTTP headers forwarded with
    ///   every CAS request
    /// - [`with_token_info`](XetFileDownloadGroupBuilder::with_token_info) — pre-seeded CAS token and expiry to skip
    ///   the initial refresh round-trip
    /// - [`with_token_refresh_url`](XetFileDownloadGroupBuilder::with_token_refresh_url) — URL and auth headers for
    ///   refreshing the CAS token
    ///
    /// Then call [`build`](XetFileDownloadGroupBuilder::build) (async) or
    /// [`build_blocking`](XetFileDownloadGroupBuilder::build_blocking) (sync).
    ///
    /// Returns `Err(SessionError::UserCancelled)` if the session has been aborted.
    pub fn new_file_download_group(&self) -> Result<XetFileDownloadGroupBuilder, SessionError> {
        self.inner.task_runtime.check_state("new_file_download_group")?;
        #[cfg(feature = "fd-track")]
        report_fd_count("XetSession::new_file_download_group");
        Ok(XetFileDownloadGroupBuilder::new(self.clone()))
    }

    /// Create a [`XetDownloadStreamGroupBuilder`] for configuring and constructing a download stream group.
    ///
    /// Configure the builder with any combination of:
    /// - [`with_endpoint`](XetDownloadStreamGroupBuilder::with_endpoint) — CAS server URL (if omitted, resolved from
    ///   the token refresh response or the session default)
    /// - [`with_custom_headers`](XetDownloadStreamGroupBuilder::with_custom_headers) — extra HTTP headers forwarded
    ///   with every CAS request
    /// - [`with_token_info`](XetDownloadStreamGroupBuilder::with_token_info) — pre-seeded CAS token and expiry to skip
    ///   the initial refresh round-trip
    /// - [`with_token_refresh_url`](XetDownloadStreamGroupBuilder::with_token_refresh_url) — URL and auth headers for
    ///   refreshing the CAS token
    ///
    /// Then call [`build`](XetDownloadStreamGroupBuilder::build) (async) or
    /// [`build_blocking`](XetDownloadStreamGroupBuilder::build_blocking) (sync).
    ///
    /// Use the resulting [`XetDownloadStreamGroup`] to create individual streams via
    /// [`download_stream`](XetDownloadStreamGroup::download_stream) and
    /// [`download_unordered_stream`](XetDownloadStreamGroup::download_unordered_stream).
    ///
    /// Returns `Err(SessionError::UserCancelled)` if the session has been aborted.
    pub fn new_download_stream_group(&self) -> Result<XetDownloadStreamGroupBuilder, SessionError> {
        self.inner.task_runtime.check_state("new_download_stream_group")?;
        #[cfg(feature = "fd-track")]
        report_fd_count("XetSession::new_download_stream_group");
        Ok(XetDownloadStreamGroupBuilder::new(self.clone()))
    }

    pub fn status(&self) -> Result<XetTaskState, SessionError> {
        self.inner.task_runtime.status()
    }

    /// Abort the session and cancel all currently running tasks.
    ///
    /// This does not shut down the underlying runtime. Use
    /// [`sigint_abort`](Self::sigint_abort) for SIGINT-style runtime teardown.
    pub fn abort(&self) -> Result<(), SessionError> {
        #[cfg(feature = "fd-track")]
        let _fd_scope = track_fd_scope(format!("XetSession::abort({})", self.inner.id));

        info!("Session abort, session_id={}", self.inner.id);
        self.inner.task_runtime.cancel_subtree()?;

        let active_download_stream_groups = std::mem::take(&mut *self.inner.active_download_stream_groups.lock()?);
        for (_id, weak_group) in active_download_stream_groups {
            if let Some(inner) = weak_group.upgrade() {
                inner.abort();
            }
        }
        #[cfg(feature = "fd-track")]
        report_fd_count("XetSession::abort complete");
        Ok(())
    }

    /// SIGINT-style abort.
    ///
    /// Performs runtime SIGINT shutdown and clears session registrations.
    /// This does not call per-commit/group local abort hooks.
    pub fn sigint_abort(&self) -> Result<(), SessionError> {
        #[cfg(feature = "fd-track")]
        let _fd_scope = track_fd_scope(format!("XetSession::sigint_abort({})", self.inner.id));

        info!("Session SIGINT abort, session_id={}", self.inner.id);
        self.inner.runtime.perform_sigint_shutdown();

        let active_download_stream_groups = std::mem::take(&mut *self.inner.active_download_stream_groups.lock()?);
        for (_id, weak_group) in active_download_stream_groups {
            if let Some(inner) = weak_group.upgrade() {
                inner.abort();
            }
        }

        #[cfg(feature = "fd-track")]
        report_fd_count("XetSession::sigint_abort complete");
        Ok(())
    }

    #[cfg(test)]
    pub(super) fn check_alive(&self) -> Result<(), SessionError> {
        if self.inner.runtime.in_sigint_shutdown() {
            return Err(SessionError::KeyboardInterrupt);
        }
        self.inner.task_runtime.check_state("session")
    }

    pub(super) fn register_download_stream_group(&self, group: &XetDownloadStreamGroup) -> Result<(), SessionError> {
        self.inner
            .active_download_stream_groups
            .lock()?
            .insert(group.id(), Arc::downgrade(&group.inner));
        Ok(())
    }

    pub(super) fn id(&self) -> &Ulid {
        &self.inner.id
    }
}

#[cfg(test)]
mod tests {
    use tempfile::tempdir;
    use xet_data::processing::{Sha256Policy, XetFileInfo};
    use xet_runtime::core::{RuntimeMode, XetRuntime};

    use super::*;

    // ── Identity ─────────────────────────────────────────────────────────────

    #[test]
    // A clone refers to the same inner Arc, so their session IDs must match.
    fn test_session_clone_shares_state() {
        let s1 = XetSessionBuilder::new().build().unwrap();
        let s2 = s1.clone();
        assert_eq!(s1.inner.id, s2.inner.id);
    }

    #[test]
    // Two independently created sessions have distinct IDs.
    fn test_two_sessions_have_distinct_ids() {
        let s1 = XetSessionBuilder::new().build().unwrap();
        let s2 = XetSessionBuilder::new().build().unwrap();
        assert_ne!(s1.inner.id, s2.inner.id);
    }

    #[test]
    // Session ID is a Ulid, to guard future regressions.
    fn test_session_id_is_ulid() {
        let s = XetSessionBuilder::new().build().unwrap();
        assert!(s.inner.id.to_string().parse::<ulid::Ulid>().is_ok());
    }

    // ── Abort behavior ───────────────────────────────────────────────────────

    #[test]
    // After abort, check_alive returns UserCancelled.
    fn test_check_alive_after_abort() {
        let session = XetSessionBuilder::new().build().unwrap();
        session.abort().unwrap();
        let err = session.check_alive().unwrap_err();
        assert!(matches!(err, SessionError::UserCancelled(_)));
    }

    #[test]
    // After sigint_abort, check_alive returns KeyboardInterrupt.
    fn test_check_alive_after_sigint_abort() {
        let session = XetSessionBuilder::new().build().unwrap();
        session.sigint_abort().unwrap();
        let err = session.check_alive().unwrap_err();
        assert!(matches!(err, SessionError::KeyboardInterrupt));
    }

    #[test]
    // new_upload_commit on an aborted session returns UserCancelled.
    fn test_new_upload_commit_after_abort_returns_aborted() {
        let session = XetSessionBuilder::new().build().unwrap();
        session.abort().unwrap();
        let err = session.new_upload_commit().err().unwrap();
        assert!(matches!(err, SessionError::UserCancelled(_)));
    }

    #[test]
    // new_file_download_group on an aborted session returns UserCancelled.
    fn test_new_file_download_group_after_abort_returns_aborted() {
        let session = XetSessionBuilder::new().build().unwrap();
        session.abort().unwrap();
        let err = session.new_file_download_group().err().unwrap();
        assert!(matches!(err, SessionError::UserCancelled(_)));
    }

    // ── Async abort behavior ──────────────────────────────────────────────────

    #[tokio::test(flavor = "multi_thread")]
    // new_upload_commit / new_file_download_group on an aborted session both return UserCancelled.
    async fn test_async_new_after_abort_returns_aborted() {
        let session = XetSessionBuilder::new().build().unwrap();
        session.abort().unwrap();
        let commit_err = session.new_upload_commit().err().unwrap();
        let group_err = session.new_file_download_group().err().unwrap();
        assert!(matches!(commit_err, SessionError::UserCancelled(_)));
        assert!(matches!(group_err, SessionError::UserCancelled(_)));
    }

    // ── XetRuntime::handle_meets_requirements ────────────────────────────────

    #[test]
    // A multi-thread runtime with enable_all() meets all requirements.
    fn test_handle_multi_thread_all_features_returns_true() {
        let rt = tokio::runtime::Builder::new_multi_thread().enable_all().build().unwrap();
        assert!(XetRuntime::handle_meets_requirements(rt.handle()));
    }

    #[test]
    #[cfg(not(target_family = "wasm"))]
    // A current_thread runtime is rejected even when enable_all() is set.
    fn test_handle_current_thread_returns_false() {
        let rt = tokio::runtime::Builder::new_current_thread().enable_all().build().unwrap();
        assert!(!XetRuntime::handle_meets_requirements(rt.handle()));
    }

    #[test]
    // A multi-thread runtime with no drivers enabled returns false.
    fn test_handle_without_any_driver_returns_false() {
        let rt = tokio::runtime::Builder::new_multi_thread().build().unwrap();
        assert!(!XetRuntime::handle_meets_requirements(rt.handle()));
    }

    #[test]
    // A multi-thread runtime with only enable_time() is missing the IO driver.
    fn test_handle_without_io_driver_returns_false() {
        let rt = tokio::runtime::Builder::new_multi_thread().enable_time().build().unwrap();
        assert!(!XetRuntime::handle_meets_requirements(rt.handle()));
    }

    #[test]
    // A multi-thread runtime with only enable_io() is missing the time driver.
    fn test_handle_without_time_driver_returns_false() {
        let rt = tokio::runtime::Builder::new_multi_thread().enable_io().build().unwrap();
        assert!(!XetRuntime::handle_meets_requirements(rt.handle()));
    }

    // ── External-mode _blocking guard ────────────────────────────────────────

    #[tokio::test(flavor = "multi_thread")]
    // build_blocking on an External-mode session returns WrongRuntimeMode.
    async fn test_new_upload_commit_blocking_errors_in_external_mode() {
        let session = XetSessionBuilder::new().build().unwrap();
        assert_eq!(session.inner.runtime.mode(), RuntimeMode::External);
        let err = session.new_upload_commit().unwrap().build_blocking().err().unwrap();
        assert!(matches!(err, SessionError::WrongRuntimeMode(_)));
    }

    #[tokio::test(flavor = "multi_thread")]
    // build_blocking on an External-mode session returns WrongRuntimeMode.
    async fn test_new_file_download_group_blocking_errors_in_external_mode() {
        let session = XetSessionBuilder::new().build().unwrap();
        assert_eq!(session.inner.runtime.mode(), RuntimeMode::External);
        let err = session.new_file_download_group().unwrap().build_blocking().err().unwrap();
        assert!(matches!(err, SessionError::WrongRuntimeMode(_)));
    }

    // ── Owned-mode _blocking panic guard ─────────────────────────────────────

    #[test]
    // build_blocking panics when called from within a tokio runtime on an Owned-mode session.
    fn test_new_upload_commit_blocking_panics_in_async_context() {
        let session = XetSessionBuilder::new().build().unwrap();
        assert_eq!(session.inner.runtime.mode(), RuntimeMode::Owned);
        let rt = tokio::runtime::Builder::new_multi_thread().enable_all().build().unwrap();
        let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
            rt.block_on(async { session.new_upload_commit().unwrap().build_blocking() })
        }));
        assert!(result.is_err(), "build_blocking() must panic when called from async");
    }

    #[test]
    // build_blocking panics when called from within a tokio runtime on an Owned-mode session.
    fn test_new_file_download_group_blocking_panics_in_async_context() {
        let session = XetSessionBuilder::new().build().unwrap();
        assert_eq!(session.inner.runtime.mode(), RuntimeMode::Owned);
        let rt = tokio::runtime::Builder::new_multi_thread().enable_all().build().unwrap();
        let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
            rt.block_on(async { session.new_file_download_group().unwrap().build_blocking() })
        }));
        assert!(result.is_err(), "build_blocking() must panic when called from async");
    }

    #[test]
    // new_download_stream_group after abort returns UserCancelled.
    fn test_new_download_stream_group_after_abort_returns_aborted() {
        let session = XetSessionBuilder::new().build().unwrap();
        session.abort().unwrap();
        let err = session.new_download_stream_group().err().unwrap();
        assert!(matches!(err, SessionError::UserCancelled(_)));
    }

    #[test]
    // Aborting a session clears all registered stream groups.
    fn test_abort_clears_active_download_stream_groups() {
        let session = XetSessionBuilder::new().build().unwrap();
        let _g1 = session.new_download_stream_group().unwrap().build_blocking().unwrap();
        session.abort().unwrap();
        assert_eq!(session.inner.active_download_stream_groups.lock().unwrap().len(), 0);
    }

    // ── Streaming download round-trip tests ─────────────────────────────────

    async fn upload_bytes(
        session: &XetSession,
        endpoint: &str,
        data: &[u8],
        name: &str,
    ) -> Result<XetFileInfo, Box<dyn std::error::Error>> {
        let commit = session.new_upload_commit()?.with_endpoint(endpoint).build().await?;
        let _handle = commit
            .upload_bytes(data.to_vec(), Sha256Policy::Compute, Some(name.into()))
            .await?;
        let results = commit.commit().await?;
        let meta = results.uploads.into_values().next().expect("one uploaded file");
        Ok(meta.xet_info)
    }

    fn upload_bytes_blocking(
        session: &XetSession,
        endpoint: &str,
        data: &[u8],
        name: &str,
    ) -> Result<XetFileInfo, Box<dyn std::error::Error>> {
        let commit = session.new_upload_commit()?.with_endpoint(endpoint).build_blocking()?;
        let _handle = commit.upload_bytes_blocking(data.to_vec(), Sha256Policy::Compute, Some(name.into()))?;
        let results = commit.commit_blocking()?;
        let meta = results.uploads.into_values().next().expect("one uploaded file");
        Ok(meta.xet_info)
    }

    #[tokio::test(flavor = "multi_thread")]
    // Async streaming download round-trip: upload, stream, verify content.
    async fn test_download_stream_round_trip() {
        let temp = tempdir().unwrap();
        let session = XetSessionBuilder::new().build().unwrap();
        let endpoint = format!("local://{}", temp.path().join("cas").display());
        let original = b"Hello, streaming download!";
        let file_info = upload_bytes(&session, &endpoint, original, "stream.bin").await.unwrap();

        let mut stream = session
            .new_download_stream_group()
            .unwrap()
            .with_endpoint(&endpoint)
            .build()
            .await
            .unwrap()
            .download_stream(file_info, None)
            .await
            .unwrap();
        let mut collected = Vec::new();
        while let Some(chunk) = stream.next().await.unwrap() {
            collected.extend_from_slice(&chunk);
        }
        assert_eq!(collected, original);
    }

    #[test]
    // Blocking streaming download round-trip: upload, stream, verify content.
    fn test_download_stream_blocking_round_trip() {
        let temp = tempdir().unwrap();
        let session = XetSessionBuilder::new().build().unwrap();
        let endpoint = format!("local://{}", temp.path().join("cas").display());
        let original = b"Hello, blocking streaming download!";
        let file_info = upload_bytes_blocking(&session, &endpoint, original, "stream.bin").unwrap();

        let mut stream = session
            .new_download_stream_group()
            .unwrap()
            .with_endpoint(&endpoint)
            .build_blocking()
            .unwrap()
            .download_stream_blocking(file_info, None)
            .unwrap();

        let mut collected = Vec::new();
        while let Some(chunk) = stream.blocking_next().unwrap() {
            collected.extend_from_slice(&chunk);
        }
        assert_eq!(collected, original);
    }

    #[tokio::test(flavor = "multi_thread")]
    // progress() reports correct totals after consuming the stream.
    async fn test_download_stream_progress_reports_completion() {
        let temp = tempdir().unwrap();
        let session = XetSessionBuilder::new().build().unwrap();
        let endpoint = format!("local://{}", temp.path().join("cas").display());
        let original = b"progress tracking test data for streaming";
        let file_info = upload_bytes(&session, &endpoint, original, "progress.bin").await.unwrap();

        let mut stream = session
            .new_download_stream_group()
            .unwrap()
            .with_endpoint(&endpoint)
            .build()
            .await
            .unwrap()
            .download_stream(file_info, None)
            .await
            .unwrap();
        let initial = stream.progress();
        assert_eq!(initial.total_bytes, original.len() as u64);
        assert_eq!(initial.bytes_completed, 0);

        let mut collected = Vec::new();
        while let Some(chunk) = stream.next().await.unwrap() {
            collected.extend_from_slice(&chunk);
        }
        assert_eq!(collected, original);

        let final_progress = stream.progress();
        assert_eq!(final_progress.total_bytes, original.len() as u64);
        assert_eq!(final_progress.bytes_completed, original.len() as u64);
    }

    #[test]
    // progress() works correctly in blocking mode.
    fn test_download_stream_blocking_progress_reports_completion() {
        let temp = tempdir().unwrap();
        let session = XetSessionBuilder::new().build().unwrap();
        let endpoint = format!("local://{}", temp.path().join("cas").display());
        let original = b"blocking progress tracking test data";
        let file_info = upload_bytes_blocking(&session, &endpoint, original, "progress.bin").unwrap();

        let mut stream = session
            .new_download_stream_group()
            .unwrap()
            .with_endpoint(&endpoint)
            .build_blocking()
            .unwrap()
            .download_stream_blocking(file_info, None)
            .unwrap();

        let mut collected = Vec::new();
        while let Some(chunk) = stream.blocking_next().unwrap() {
            collected.extend_from_slice(&chunk);
        }
        assert_eq!(collected, original);

        let final_progress = stream.progress();
        assert_eq!(final_progress.total_bytes, original.len() as u64);
        assert_eq!(final_progress.bytes_completed, original.len() as u64);
    }

    #[tokio::test(flavor = "multi_thread")]
    // Multiple sequential streaming downloads share a single group's connection pool.
    async fn test_download_stream_multiple_sequential() {
        let temp = tempdir().unwrap();
        let session = XetSessionBuilder::new().build().unwrap();
        let endpoint = format!("local://{}", temp.path().join("cas").display());
        let data_a = b"first stream payload";
        let data_b = b"second stream payload";
        let info_a = upload_bytes(&session, &endpoint, data_a, "a.bin").await.unwrap();
        let info_b = upload_bytes(&session, &endpoint, data_b, "b.bin").await.unwrap();

        let group = session
            .new_download_stream_group()
            .unwrap()
            .with_endpoint(&endpoint)
            .build()
            .await
            .unwrap();

        let mut stream_a = group.download_stream(info_a, None).await.unwrap();
        let mut collected_a = Vec::new();
        while let Some(chunk) = stream_a.next().await.unwrap() {
            collected_a.extend_from_slice(&chunk);
        }
        assert_eq!(collected_a, data_a);

        let mut stream_b = group.download_stream(info_b, None).await.unwrap();
        let mut collected_b = Vec::new();
        while let Some(chunk) = stream_b.next().await.unwrap() {
            collected_b.extend_from_slice(&chunk);
        }
        assert_eq!(collected_b, data_b);
    }

    // ── Duplicate tokio handle rejection ─────────────────────────────────────

    #[test]
    // Building a second session with the same tokio handle while the first is alive must
    // fall back to Owned mode rather than returning an error — the duplicate is handled
    // gracefully so callers do not need to track handle ownership.
    fn test_build_with_same_handle_falls_back_to_owned() {
        let tokio_rt = tokio::runtime::Builder::new_multi_thread().enable_all().build().unwrap();
        let handle = tokio_rt.handle().clone();

        let first = XetSessionBuilder::new().with_tokio_handle(handle.clone()).build().unwrap();
        assert_eq!(first.inner.runtime.mode(), RuntimeMode::External, "first build must use External runtime");

        let second = XetSessionBuilder::new().with_tokio_handle(handle).build();
        assert!(second.is_ok(), "second build with the same tokio handle must still succeed");
        assert_eq!(
            second.unwrap().inner.runtime.mode(),
            RuntimeMode::Owned,
            "second build must fall back to Owned runtime when External handle is already in use"
        );
    }

    #[test]
    // After the first session is dropped (deregistering the handle), a new session can
    // attach to the same tokio handle successfully.
    fn test_build_with_same_handle_succeeds_after_first_is_dropped() {
        let tokio_rt = tokio::runtime::Builder::new_multi_thread().enable_all().build().unwrap();
        let handle = tokio_rt.handle().clone();

        let first = XetSessionBuilder::new().with_tokio_handle(handle.clone()).build().unwrap();
        drop(first);

        let second = XetSessionBuilder::new().with_tokio_handle(handle).build();
        assert!(second.is_ok(), "build must succeed after the previous session holding the same handle is dropped");
    }
}