hf-xet 1.6.0

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
use std::future::Future;
use std::pin::Pin;
use std::sync::{Arc, Mutex, Weak};

use tokio::task::JoinHandle;
use tokio_util::sync::CancellationToken;
#[cfg(target_family = "wasm")]
use tokio_with_wasm::alias as tokio;
use xet_runtime::core::XetRuntime;

use crate::error::XetError;

#[derive(Clone, Debug, PartialEq, Eq)]
pub enum XetTaskState {
    Running,
    Finalizing,
    Completed,
    Error(String),
    UserCancelled,
}

#[derive(Debug)]
pub(super) enum BackgroundTaskState<T> {
    Running {
        join_handle: Option<JoinHandle<Result<T, XetError>>>,
    },
    Success(T),
    Error(String),
}

impl<T: Clone> BackgroundTaskState<T> {
    pub(super) async fn finish(&mut self) -> Result<T, XetError> {
        match self {
            BackgroundTaskState::Success(value) => Ok(value.clone()),
            BackgroundTaskState::Error(msg) => Err(XetError::PreviousTaskError(msg.clone())),
            BackgroundTaskState::Running { join_handle } => {
                let handle = join_handle
                    .take()
                    .ok_or_else(|| XetError::TaskError("task already being resolved".into()))?;
                match handle.await {
                    Ok(Ok(value)) => {
                        *self = BackgroundTaskState::Success(value.clone());
                        Ok(value)
                    },
                    Ok(Err(e)) => {
                        let msg = e.to_string();
                        *self = BackgroundTaskState::Error(msg);
                        Err(e)
                    },
                    Err(join_err) => {
                        if join_err.is_cancelled() {
                            let msg = "background task cancelled by user".to_string();
                            *self = BackgroundTaskState::Error(msg.clone());
                            return Err(XetError::UserCancelled(msg));
                        }
                        let msg = join_err.to_string();
                        *self = BackgroundTaskState::Error(msg.clone());
                        Err(XetError::TaskError(msg))
                    },
                }
            },
        }
    }
}

pub(super) struct TaskRuntime {
    #[cfg_attr(target_family = "wasm", allow(dead_code))]
    runtime: Arc<XetRuntime>,
    cancellation_token: CancellationToken,
    state: Mutex<XetTaskState>,
    children: Mutex<Vec<Weak<TaskRuntime>>>,
}

impl TaskRuntime {
    pub(super) fn new_root(runtime: Arc<XetRuntime>) -> Arc<Self> {
        Arc::new(Self {
            runtime,
            cancellation_token: CancellationToken::new(),
            state: Mutex::new(XetTaskState::Running),
            children: Mutex::new(Vec::new()),
        })
    }

    pub(super) fn child(self: &Arc<Self>) -> Result<Arc<Self>, XetError> {
        let child = Arc::new(Self {
            runtime: self.runtime.clone(),
            cancellation_token: self.cancellation_token.child_token(),
            state: Mutex::new(self.status()?),
            children: Mutex::new(Vec::new()),
        });

        self.children.lock()?.push(Arc::downgrade(&child));
        Ok(child)
    }

    pub(super) fn status(&self) -> Result<XetTaskState, XetError> {
        Ok(self.state.lock()?.clone())
    }

    fn set_state(&self, new_state: XetTaskState) -> Result<(), XetError> {
        *self.state.lock()? = new_state;
        Ok(())
    }

    fn transition_to_finalizing(&self, task_name: &'static str, allow_repeat: bool) -> Result<(), XetError> {
        let mut state = self.state.lock()?;
        match &*state {
            XetTaskState::Running => {
                *state = XetTaskState::Finalizing;
                Ok(())
            },
            XetTaskState::Finalizing | XetTaskState::Completed => {
                if allow_repeat {
                    Ok(())
                } else {
                    Err(XetError::AlreadyCompleted)
                }
            },
            XetTaskState::UserCancelled => Err(XetError::UserCancelled(format!("{task_name} cancelled by user"))),
            XetTaskState::Error(msg) => Err(XetError::PreviousTaskError(msg.clone())),
        }
    }

    fn set_state_recursive(&self, new_state: XetTaskState) -> Result<(), XetError> {
        self.set_state(new_state.clone())?;
        for child in self.live_children()? {
            child.set_state_recursive(new_state.clone())?;
        }
        Ok(())
    }

    pub(super) fn cancel_subtree(&self) -> Result<(), XetError> {
        // TaskRuntime cancellation is token-driven: cancel the subtree token,
        // then mark the local state tree as UserCancelled. Child tasks observe
        // the token in bridge paths and exit cooperatively.
        self.cancellation_token.cancel();
        self.set_state_recursive(XetTaskState::UserCancelled)
    }

    pub(super) fn cancellation_token(&self) -> CancellationToken {
        self.cancellation_token.clone()
    }

    pub(super) fn check_state(&self, task_name: &'static str) -> Result<(), XetError> {
        match self.status()? {
            XetTaskState::Running => Ok(()),
            XetTaskState::Finalizing => Err(XetError::AlreadyCompleted),
            XetTaskState::UserCancelled => Err(XetError::UserCancelled(format!("{task_name} cancelled by user"))),
            XetTaskState::Completed => Err(XetError::AlreadyCompleted),
            XetTaskState::Error(msg) => Err(XetError::PreviousTaskError(msg)),
        }
    }

    fn update_state_on_error(&self, err: &XetError) -> Result<(), XetError> {
        match err {
            XetError::UserCancelled(_) => self.set_state(XetTaskState::UserCancelled),
            other => self.set_state(XetTaskState::Error(other.to_string())),
        }
    }

    // ── Background task helpers ──────────────────────────────────────────────

    pub(super) fn status_from_background_task<T>(
        &self,
        state: &tokio::sync::Mutex<BackgroundTaskState<T>>,
    ) -> Result<XetTaskState, XetError> {
        let runtime_state = self.status()?;
        if !matches!(runtime_state, XetTaskState::Running | XetTaskState::Finalizing) {
            return Ok(runtime_state);
        }
        let state_guard = match state.try_lock() {
            Ok(guard) => guard,
            Err(_) => return Ok(XetTaskState::Running),
        };
        let status = match &*state_guard {
            BackgroundTaskState::Running { .. } => XetTaskState::Running,
            BackgroundTaskState::Success(_) => XetTaskState::Completed,
            BackgroundTaskState::Error(msg) => XetTaskState::Error(msg.clone()),
        };
        Ok(status)
    }

    pub(super) fn background_success<T: Clone>(&self, state: &tokio::sync::Mutex<BackgroundTaskState<T>>) -> Option<T> {
        let guard = state.try_lock().ok()?;
        match &*guard {
            BackgroundTaskState::Success(value) => Some(value.clone()),
            _ => None,
        }
    }

    // Used only by native-only handle accessors (e.g. `_blocking` variants);
    // intentionally retained on wasm so handles keep the same shape.
    #[cfg_attr(target_family = "wasm", allow(dead_code))]
    pub(super) fn background_result<T: Clone>(
        &self,
        state: &tokio::sync::Mutex<BackgroundTaskState<T>>,
    ) -> Option<Result<T, XetError>> {
        let guard = state.try_lock().ok()?;
        match &*guard {
            BackgroundTaskState::Success(value) => Some(Ok(value.clone())),
            BackgroundTaskState::Error(msg) => Some(Err(XetError::TaskError(msg.clone()))),
            BackgroundTaskState::Running { .. } => None,
        }
    }

    // Cancellation entrypoint for per-handle abort methods.
    // We intentionally rely on subtree token propagation (plus bridge select
    // points) instead of mutating per-handle background state directly.
    pub(super) fn cancel_background_task(&self) {
        let _ = self.cancel_subtree();
    }

    fn live_children(&self) -> Result<Vec<Arc<TaskRuntime>>, XetError> {
        let mut guard = self.children.lock()?;
        let mut live = Vec::with_capacity(guard.len());
        guard.retain(|weak| {
            if let Some(child) = weak.upgrade() {
                live.push(child);
                true
            } else {
                false
            }
        });
        Ok(live)
    }

    // Plain (non-async) fn: boxing `fut` before the async block is constructed keeps its
    // captured type small, no matter how large `F` is. Boxing inside an `async fn` body
    // instead doesn't work - the parameter's full type is still part of that fn's own
    // generator state regardless of what the body does with it. `check_state`/
    // `update_state_on_error` stay inside the block so they still only run on first poll.
    pub(super) fn bridge_async<T, F>(
        &self,
        task_name: &'static str,
        fut: F,
    ) -> impl Future<Output = Result<T, XetError>> + MaybeSend + '_
    where
        F: Future<Output = Result<T, XetError>> + MaybeSend + 'static,
        T: MaybeSend + 'static,
    {
        let fut: BoxedBridgeFuture<T> = Box::pin(fut);
        async move {
            self.check_state(task_name)?;
            let result = self.run_inner_async(task_name, fut).await;
            if let Err(ref e) = result {
                self.update_state_on_error(e)?;
            }
            result
        }
    }

    pub(super) fn bridge_async_finalizing<T, F>(
        &self,
        task_name: &'static str,
        allow_repeat: bool,
        fut: F,
    ) -> impl Future<Output = Result<T, XetError>> + MaybeSend + '_
    where
        F: Future<Output = Result<T, XetError>> + MaybeSend + 'static,
        T: MaybeSend + 'static,
    {
        let fut: BoxedBridgeFuture<T> = Box::pin(fut);
        async move {
            self.transition_to_finalizing(task_name, allow_repeat)?;

            let result = self.run_inner_async(task_name, fut).await;
            match &result {
                Ok(_) => self.set_state(XetTaskState::Completed)?,
                Err(XetError::UserCancelled(_)) => {
                    self.set_state(XetTaskState::UserCancelled)?;
                },
                Err(e) => self.set_state(XetTaskState::Error(e.to_string()))?,
            }
            result
        }
    }
}

// `MaybeSend` can't be used as an extra marker on a `dyn` trait object (it isn't an auto
// trait), so this spells out the same native/wasm split as a concrete type instead.
#[cfg(not(target_family = "wasm"))]
type BoxedBridgeFuture<T> = Pin<Box<dyn Future<Output = Result<T, XetError>> + Send>>;
#[cfg(target_family = "wasm")]
type BoxedBridgeFuture<T> = Pin<Box<dyn Future<Output = Result<T, XetError>>>>;

// `Send` on native, unconstrained on wasm: lets the shared bridge methods
// above state one set of bounds while wasm futures stay `!Send`.
#[cfg(not(target_family = "wasm"))]
pub(super) trait MaybeSend: Send {}
#[cfg(not(target_family = "wasm"))]
impl<T: Send> MaybeSend for T {}
#[cfg(target_family = "wasm")]
pub(super) trait MaybeSend {}
#[cfg(target_family = "wasm")]
impl<T> MaybeSend for T {}

// Native task bridging internals: routes futures through XetRuntime's
// multithreaded executor and requires Send + 'static bounds. Sync bridging
// only exists here — wasm has no blocking model.
#[cfg(not(target_family = "wasm"))]
impl TaskRuntime {
    fn run_inner_async<T, F>(
        &self,
        task_name: &'static str,
        fut: F,
    ) -> impl Future<Output = Result<T, XetError>> + Send + 'static
    where
        F: Future<Output = Result<T, XetError>> + Send + 'static,
        T: Send + 'static,
    {
        let token = self.cancellation_token.clone();
        let runtime = self.runtime.clone();
        async move {
            runtime
                .bridge_async(task_name, async move {
                    tokio::select! {
                        _ = token.cancelled() => Err(XetError::UserCancelled(
                            format!("{task_name} cancelled by user"),
                        )),
                        result = fut => result,
                    }
                })
                .await
                .map_err(XetError::from)?
        }
    }

    pub(super) fn bridge_sync<T, F>(&self, task_name: &'static str, fut: F) -> Result<T, XetError>
    where
        F: Future<Output = Result<T, XetError>> + Send + 'static,
        T: Send + 'static,
    {
        self.check_state(task_name)?;
        let token = self.cancellation_token.clone();
        let result = self
            .runtime
            .bridge_sync(async move {
                tokio::select! {
                    _ = token.cancelled() => Err(XetError::UserCancelled(
                        format!("{task_name} cancelled by user"),
                    )),
                    result = fut => result,
                }
            })
            .map_err(XetError::from)?;
        if let Err(ref e) = result {
            self.update_state_on_error(e)?;
        }
        result
    }

    pub(super) fn bridge_sync_finalizing<T, F>(
        &self,
        task_name: &'static str,
        allow_repeat: bool,
        fut: F,
    ) -> Result<T, XetError>
    where
        F: Future<Output = Result<T, XetError>> + Send + 'static,
        T: Send + 'static,
    {
        self.transition_to_finalizing(task_name, allow_repeat)?;

        let token = self.cancellation_token.clone();
        let result = self
            .runtime
            .bridge_sync(async move {
                tokio::select! {
                    _ = token.cancelled() => Err(XetError::UserCancelled(
                        format!("{task_name} cancelled by user"),
                    )),
                    result = fut => result,
                }
            })
            .map_err(XetError::from)?;
        match &result {
            Ok(_) => self.set_state(XetTaskState::Completed)?,
            Err(XetError::UserCancelled(_)) => {
                self.set_state(XetTaskState::UserCancelled)?;
            },
            Err(e) => self.set_state(XetTaskState::Error(e.to_string()))?,
        }
        result
    }
}

// Wasm task bridging internals: runs futures inline on the single-threaded
// executor (no XetRuntime offload), dropping the Send bound. There is no
// sync counterpart on wasm.
#[cfg(target_family = "wasm")]
impl TaskRuntime {
    fn run_inner_async<T, F>(
        &self,
        task_name: &'static str,
        fut: F,
    ) -> impl Future<Output = Result<T, XetError>> + 'static
    where
        F: Future<Output = Result<T, XetError>> + 'static,
        T: 'static,
    {
        let token = self.cancellation_token.clone();
        async move {
            tokio::select! {
                _ = token.cancelled() => Err(XetError::UserCancelled(
                    format!("{task_name} cancelled by user"),
                )),
                result = fut => result,
            }
        }
    }
}