gs-hf 0.4.6

Fork of hf-hub. This crates aims ease the interaction with huggingface It aims to be compatible with the huggingface_hub python package, but only implements a smaller subset of functions.
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
//! Protocol logic shared by the `sync` and `tokio` backends, written
//! sans-io: nothing in this module performs network or disk access (the
//! `fs` submodule excepted), it only decides what the drivers should do
//! next. Keeping the decisions here means redirect policy, header
//! parsing, resume formats and retry schedules exist exactly once and
//! are unit-testable without a server.

use http::uri::Uri;
use http::HeaderMap;
#[cfg(any(feature = "tokio", test))]
use std::cmp::Reverse;
#[cfg(any(feature = "tokio", test))]
use std::collections::BinaryHeap;
use std::num::ParseIntError;
use thiserror::Error;

/// Current version (used in user-agent)
const VERSION: &str = env!("CARGO_PKG_VERSION");
/// Current name (used in user-agent)
const NAME: &str = env!("CARGO_PKG_NAME");

pub(crate) const LOCATION: &str = "location";
pub(crate) const LINK: &str = "link";
pub(crate) const ETAG: &str = "etag";
pub(crate) const X_LINKED_ETAG: &str = "x-linked-etag";
pub(crate) const X_REPO_COMMIT: &str = "x-repo-commit";
pub(crate) const CONTENT_RANGE: &str = "content-range";

/// Mirrors the redirect cap used by browsers and reqwest's default policy.
const MAX_REDIRECTS: u8 = 10;

#[derive(Debug, Error, PartialEq)]
pub(crate) enum MetadataError {
    #[error("Header {0} is missing")]
    MissingHeader(&'static str),

    #[error("Header {0} is invalid")]
    InvalidHeader(&'static str),

    #[error("Too many redirects (max {MAX_REDIRECTS})")]
    TooManyRedirects,

    #[error("Cannot parse int")]
    ParseIntError(#[from] ParseIntError),
}

/// Metadata about a remote file, resolved from the response headers of a
/// `Range: bytes=0-0` probe on the `resolve` endpoint.
#[derive(Debug, Clone, PartialEq)]
pub(crate) struct FileMetadata {
    pub(crate) commit_hash: String,
    pub(crate) etag: String,
    pub(crate) size: usize,
}

/// What the driver should do next while resolving [`FileMetadata`].
#[derive(Debug, PartialEq)]
pub(crate) enum MetadataStep {
    /// Fetch this URL with `Range: bytes=0-0` on a client that does NOT
    /// follow redirects (the flow decides redirect policy itself).
    FetchNoRedirect { url: String },
    /// The Hub redirected to an absolute URL (S3/CDN); fetch it with
    /// `Range: bytes=0-0` to learn the file size from `Content-Range`.
    /// Redirects may be followed by the client on this hop.
    Probe { url: String },
    /// Resolution finished.
    Done(FileMetadata),
}

/// Drives metadata resolution: follows relative redirects on the Hub
/// itself (matching `huggingface_hub`'s policy, see
/// <https://github.com/huggingface/huggingface_hub/blob/9c6af39cdce45b570f0b7f8fad2b311c96019804/src/huggingface_hub/file_download.py#L411>),
/// then extracts the etag/commit from the final Hub response, then sizes
/// the file through the CDN redirect if there is one.
pub(crate) struct MetadataFlow {
    current_url: String,
    hops: u8,
    /// `(commit_hash, etag)` parked while the size probe is in flight.
    probing: Option<(String, String)>,
}

impl MetadataFlow {
    pub(crate) fn new(url: &str) -> Self {
        Self {
            current_url: url.to_string(),
            hops: 0,
            probing: None,
        }
    }

    pub(crate) fn first_step(&self) -> MetadataStep {
        MetadataStep::FetchNoRedirect {
            url: self.current_url.clone(),
        }
    }

    pub(crate) fn on_response(
        &mut self,
        status: u16,
        headers: &HeaderMap,
    ) -> Result<MetadataStep, MetadataError> {
        if let Some((commit_hash, etag)) = self.probing.take() {
            let size = parse_content_range(headers)?;
            return Ok(MetadataStep::Done(FileMetadata {
                commit_hash,
                etag,
                size,
            }));
        }

        if is_followable_redirect(status) {
            if let Some(location) = get_str(headers, LOCATION)? {
                if let Some(next_url) = merge_relative_location(&self.current_url, location)? {
                    self.hops += 1;
                    if self.hops > MAX_REDIRECTS {
                        return Err(MetadataError::TooManyRedirects);
                    }
                    self.current_url = next_url.clone();
                    return Ok(MetadataStep::FetchNoRedirect { url: next_url });
                }
            }
        }

        let etag = match get_str(headers, X_LINKED_ETAG)? {
            Some(etag) => etag,
            None => get_str(headers, ETAG)?.ok_or(MetadataError::MissingHeader(ETAG))?,
        }
        // Cleaning extra quotes
        .replace('"', "");
        let commit_hash = get_str(headers, X_REPO_COMMIT)?
            .ok_or(MetadataError::MissingHeader(X_REPO_COMMIT))?
            .to_string();

        // The response was redirected to S3 most likely which will
        // know about the size of the file
        if (300..400).contains(&status) {
            let url = get_str(headers, LOCATION)?
                .ok_or(MetadataError::MissingHeader(LOCATION))?
                .to_string();
            self.probing = Some((commit_hash, etag));
            Ok(MetadataStep::Probe { url })
        } else {
            let size = parse_content_range(headers)?;
            Ok(MetadataStep::Done(FileMetadata {
                commit_hash,
                etag,
                size,
            }))
        }
    }
}

fn is_followable_redirect(status: u16) -> bool {
    matches!(status, 301 | 302 | 303 | 307 | 308)
}

fn get_str<'h>(
    headers: &'h HeaderMap,
    name: &'static str,
) -> Result<Option<&'h str>, MetadataError> {
    match headers.get(name) {
        None => Ok(None),
        Some(value) => Ok(Some(
            value
                .to_str()
                .map_err(|_| MetadataError::InvalidHeader(name))?,
        )),
    }
}

fn parse_content_range(headers: &HeaderMap) -> Result<usize, MetadataError> {
    let content_range =
        get_str(headers, CONTENT_RANGE)?.ok_or(MetadataError::MissingHeader(CONTENT_RANGE))?;
    Ok(content_range
        .split('/')
        .next_back()
        .ok_or(MetadataError::InvalidHeader(CONTENT_RANGE))?
        .parse()?)
}

/// Resolves `location` against `base`: returns the merged URL for
/// relative locations (no host), `None` for absolute ones.
fn merge_relative_location(base: &str, location: &str) -> Result<Option<String>, MetadataError> {
    let uri: Uri = location
        .parse()
        .map_err(|_| MetadataError::InvalidHeader(LOCATION))?;
    if uri.host().is_some() {
        return Ok(None);
    }
    let mut parts = base
        .parse::<Uri>()
        .map_err(|_| MetadataError::InvalidHeader(LOCATION))?
        .into_parts();
    parts.path_and_query = uri.into_parts().path_and_query;
    let merged = Uri::from_parts(parts).map_err(|_| MetadataError::InvalidHeader(LOCATION))?;
    Ok(Some(merged.to_string()))
}

/// Fully qualified URL of a file within a repo.
pub(crate) fn file_url(endpoint: &str, repo_id: &str, revision: &str, filename: &str) -> String {
    format!("{endpoint}/{repo_id}/resolve/{revision}/{filename}")
}

/// Percent-encodes a bucket path into a single URL segment, like
/// Python's `quote(path, safe="")` used by `huggingface_hub`: slashes
/// become `%2F`, only unreserved characters pass through.
pub(crate) fn percent_encode_path(path: &str) -> String {
    let mut encoded = String::with_capacity(path.len());
    for byte in path.bytes() {
        match byte {
            b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'_' | b'.' | b'~' => {
                encoded.push(byte as char)
            }
            _ => encoded.push_str(&format!("%{byte:02X}")),
        }
    }
    encoded
}

/// Fully qualified URL of a file within a bucket. Buckets are
/// unversioned, so there is no revision component, and the route has no
/// `/api` prefix.
pub(crate) fn bucket_resolve_url(endpoint: &str, bucket_id: &str, path: &str) -> String {
    format!(
        "{endpoint}/buckets/{bucket_id}/resolve/{}",
        percent_encode_path(path)
    )
}

/// URL of the bucket tree listing. The prefix is one encoded path
/// segment (slashes become `%2F`), matching `huggingface_hub`.
pub(crate) fn bucket_tree_url(
    endpoint: &str,
    bucket_id: &str,
    prefix: Option<&str>,
    recursive: bool,
) -> String {
    let base = format!("{endpoint}/api/buckets/{bucket_id}/tree");
    match prefix {
        Some(prefix) => format!(
            "{base}/{}?recursive={recursive}",
            percent_encode_path(prefix)
        ),
        None => format!("{base}?recursive={recursive}"),
    }
}

/// Extracts the `rel="next"` URL from a `Link` header; the Hub
/// paginates bucket tree listings this way. The next URL carries a
/// server-generated cursor and must be fetched verbatim.
pub(crate) fn parse_next_link(headers: &HeaderMap) -> Result<Option<String>, MetadataError> {
    let Some(link) = get_str(headers, LINK)? else {
        return Ok(None);
    };
    for entry in link.split(',') {
        let (url, params) = entry
            .split_once(';')
            .ok_or(MetadataError::InvalidHeader(LINK))?;
        let url = url
            .trim()
            .strip_prefix('<')
            .and_then(|url| url.strip_suffix('>'))
            .ok_or(MetadataError::InvalidHeader(LINK))?;
        if params
            .split(';')
            .any(|param| param.trim() == "rel=\"next\"")
        {
            return Ok(Some(url.to_string()));
        }
    }
    Ok(None)
}

pub(crate) fn default_user_agent() -> Vec<(String, String)> {
    vec![
        ("unknown".to_string(), "None".to_string()),
        (NAME.to_string(), VERSION.to_string()),
        ("rust".to_string(), "unknown".to_string()),
    ]
}

pub(crate) fn user_agent_string(parts: &[(String, String)]) -> String {
    parts
        .iter()
        .map(|(key, value)| format!("{key}/{value}"))
        .collect::<Vec<_>>()
        .join("; ")
}

fn jitter() -> usize {
    use rand::RngExt;
    rand::rng().random_range(0..=500)
}

pub(crate) fn exponential_backoff(base_wait_time: usize, n: usize, max: usize) -> usize {
    (base_wait_time + n.pow(2) + jitter()).min(max)
}

/// Number of bytes appended to the chunked-download part file to record
/// the committed watermark.
#[cfg(any(feature = "tokio", test))]
pub(crate) const TRAILER_LEN: usize = size_of::<u64>();

/// On-disk length of a chunked-download part file for a file of
/// `content_len` bytes.
#[cfg(any(feature = "tokio", test))]
pub(crate) fn part_file_len(content_len: u64) -> u64 {
    content_len + TRAILER_LEN as u64
}

#[cfg(any(feature = "tokio", test))]
pub(crate) fn encode_trailer(committed: u64) -> [u8; TRAILER_LEN] {
    committed.to_le_bytes()
}

#[cfg(any(feature = "tokio", test))]
pub(crate) fn decode_trailer(buf: [u8; TRAILER_LEN]) -> u64 {
    u64::from_le_bytes(buf)
}

/// Start offset for resuming a sequential (append-style) part file, or
/// `None` if the part file cannot belong to a file of `total_len` bytes.
#[cfg(any(feature = "ureq", test))]
pub(crate) fn sequential_resume_start(part_len: u64, total_len: u64) -> Option<u64> {
    if part_len > total_len {
        None
    } else {
        Some(part_len)
    }
}

/// Splits `start..length` into `(start, stop)` ranges of `chunk_size`
/// bytes suitable for `Range: bytes={start}-{stop}` requests.
#[cfg(any(feature = "tokio", test))]
pub(crate) fn chunk_ranges(
    start: usize,
    length: usize,
    chunk_size: usize,
) -> impl Iterator<Item = (usize, usize)> {
    (start..length).step_by(chunk_size).map(move |chunk_start| {
        let stop = std::cmp::min(chunk_start + chunk_size - 1, length);
        (chunk_start, stop)
    })
}

/// Tracks which prefix of the file is fully downloaded while chunks
/// complete out of order. [`CommitTracker::advance`] returns the new
/// watermark whenever it moves, so the driver knows when to persist it
/// to the part-file trailer.
#[cfg(any(feature = "tokio", test))]
pub(crate) struct CommitTracker {
    committed: u64,
    pending: BinaryHeap<Reverse<(usize, usize)>>,
}

#[cfg(any(feature = "tokio", test))]
impl CommitTracker {
    pub(crate) fn new(start: u64) -> Self {
        Self {
            committed: start,
            pending: BinaryHeap::new(),
        }
    }

    pub(crate) fn advance(&mut self, start: usize, stop: usize) -> Option<u64> {
        self.pending.push(Reverse((start, stop)));
        let mut modified = false;
        while let Some(Reverse((min, max))) = self.pending.pop() {
            if min as u64 == self.committed {
                self.committed = max as u64 + 1;
                modified = true;
            } else {
                self.pending.push(Reverse((min, max)));
                break;
            }
        }
        modified.then_some(self.committed)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use http::header::HeaderValue;

    fn headers(pairs: &[(&'static str, &str)]) -> HeaderMap {
        let mut map = HeaderMap::new();
        for (name, value) in pairs {
            map.insert(*name, HeaderValue::from_str(value).unwrap());
        }
        map
    }

    const URL: &str = "https://huggingface.co/gpt2/resolve/main/model.safetensors";

    #[test]
    fn metadata_direct_response() {
        let mut flow = MetadataFlow::new(URL);
        assert_eq!(
            flow.first_step(),
            MetadataStep::FetchNoRedirect {
                url: URL.to_string()
            }
        );
        let step = flow
            .on_response(
                206,
                &headers(&[
                    ("etag", "\"abc123\""),
                    ("x-repo-commit", "deadbeef"),
                    ("content-range", "bytes 0-0/5342"),
                ]),
            )
            .unwrap();
        match step {
            MetadataStep::Done(metadata) => {
                assert_eq!(metadata.etag, "abc123");
                assert_eq!(metadata.commit_hash, "deadbeef");
                assert_eq!(metadata.size, 5342);
            }
            step => panic!("unexpected step {step:?}"),
        }
    }

    #[test]
    fn metadata_prefers_linked_etag() {
        let mut flow = MetadataFlow::new(URL);
        let step = flow
            .on_response(
                200,
                &headers(&[
                    ("etag", "\"weak\""),
                    ("x-linked-etag", "\"lfs-sha\""),
                    ("x-repo-commit", "deadbeef"),
                    ("content-range", "bytes 0-0/22"),
                ]),
            )
            .unwrap();
        match step {
            MetadataStep::Done(metadata) => assert_eq!(metadata.etag, "lfs-sha"),
            step => panic!("unexpected step {step:?}"),
        }
    }

    #[test]
    fn metadata_follows_relative_redirect() {
        let mut flow = MetadataFlow::new(URL);
        let step = flow
            .on_response(
                302,
                &headers(&[("location", "/gpt2/resolve/abc/model.safetensors")]),
            )
            .unwrap();
        assert_eq!(
            step,
            MetadataStep::FetchNoRedirect {
                url: "https://huggingface.co/gpt2/resolve/abc/model.safetensors".to_string()
            }
        );
        let step = flow
            .on_response(
                200,
                &headers(&[
                    ("etag", "\"abc\""),
                    ("x-repo-commit", "abc"),
                    ("content-range", "bytes 0-0/10"),
                ]),
            )
            .unwrap();
        assert!(matches!(step, MetadataStep::Done(_)));
    }

    #[test]
    fn metadata_probes_absolute_redirect() {
        let mut flow = MetadataFlow::new(URL);
        let step = flow
            .on_response(
                302,
                &headers(&[
                    ("location", "https://cdn-lfs.huggingface.co/some/blob"),
                    ("etag", "\"abc\""),
                    ("x-linked-etag", "\"lfs-sha\""),
                    ("x-repo-commit", "deadbeef"),
                ]),
            )
            .unwrap();
        assert_eq!(
            step,
            MetadataStep::Probe {
                url: "https://cdn-lfs.huggingface.co/some/blob".to_string()
            }
        );
        let step = flow
            .on_response(206, &headers(&[("content-range", "bytes 0-0/987654")]))
            .unwrap();
        match step {
            MetadataStep::Done(metadata) => {
                assert_eq!(metadata.etag, "lfs-sha");
                assert_eq!(metadata.commit_hash, "deadbeef");
                assert_eq!(metadata.size, 987654);
            }
            step => panic!("unexpected step {step:?}"),
        }
    }

    #[test]
    fn metadata_redirect_loop_is_capped() {
        let mut flow = MetadataFlow::new(URL);
        let redirect = headers(&[("location", "/loop")]);
        for _ in 0..10 {
            let step = flow.on_response(302, &redirect).unwrap();
            assert!(matches!(step, MetadataStep::FetchNoRedirect { .. }));
        }
        assert_eq!(
            flow.on_response(302, &redirect),
            Err(MetadataError::TooManyRedirects)
        );
    }

    #[test]
    fn metadata_missing_headers() {
        assert_eq!(
            MetadataFlow::new(URL).on_response(200, &headers(&[])),
            Err(MetadataError::MissingHeader(ETAG))
        );
        assert_eq!(
            MetadataFlow::new(URL).on_response(200, &headers(&[("etag", "\"x\"")])),
            Err(MetadataError::MissingHeader(X_REPO_COMMIT))
        );
        assert_eq!(
            MetadataFlow::new(URL)
                .on_response(200, &headers(&[("etag", "\"x\""), ("x-repo-commit", "c")])),
            Err(MetadataError::MissingHeader(CONTENT_RANGE))
        );
        // Absolute redirect without a Location for the size probe used to
        // panic; now it is a proper error.
        assert_eq!(
            MetadataFlow::new(URL)
                .on_response(303, &headers(&[("etag", "\"x\""), ("x-repo-commit", "c")])),
            Err(MetadataError::MissingHeader(LOCATION))
        );
    }

    #[test]
    fn percent_encoding() {
        assert_eq!(percent_encode_path("a/b.txt"), "a%2Fb.txt");
        assert_eq!(
            percent_encode_path("sub dir/héllo.txt"),
            "sub%20dir%2Fh%C3%A9llo.txt"
        );
        assert_eq!(percent_encode_path("AZaz09-_.~"), "AZaz09-_.~");
        assert_eq!(percent_encode_path("100%?#"), "100%25%3F%23");
    }

    #[test]
    fn bucket_urls() {
        assert_eq!(
            bucket_resolve_url("https://huggingface.co", "myorg/mybucket", "data/file.bin"),
            "https://huggingface.co/buckets/myorg/mybucket/resolve/data%2Ffile.bin"
        );
        assert_eq!(
            bucket_tree_url("https://huggingface.co", "myorg/mybucket", None, false),
            "https://huggingface.co/api/buckets/myorg/mybucket/tree?recursive=false"
        );
        assert_eq!(
            bucket_tree_url(
                "https://huggingface.co",
                "myorg/mybucket",
                Some("data/sub"),
                true
            ),
            "https://huggingface.co/api/buckets/myorg/mybucket/tree/data%2Fsub?recursive=true"
        );
    }

    #[test]
    fn next_link() {
        assert_eq!(parse_next_link(&headers(&[])), Ok(None));
        assert_eq!(
            parse_next_link(&headers(&[(
                "link",
                "<https://huggingface.co/api/buckets/a/b/tree?cursor=x>; rel=\"next\""
            )])),
            Ok(Some(
                "https://huggingface.co/api/buckets/a/b/tree?cursor=x".to_string()
            ))
        );
        assert_eq!(
            parse_next_link(&headers(&[(
                "link",
                "<https://x/prev>; rel=\"prev\", <https://x/next>; rel=\"next\""
            )])),
            Ok(Some("https://x/next".to_string()))
        );
        assert_eq!(
            parse_next_link(&headers(&[("link", "<https://x/prev>; rel=\"prev\"")])),
            Ok(None)
        );
        assert_eq!(
            parse_next_link(&headers(&[("link", "garbage")])),
            Err(MetadataError::InvalidHeader(LINK))
        );
    }

    #[test]
    fn content_range_parsing() {
        assert_eq!(
            parse_content_range(&headers(&[("content-range", "bytes 0-0/123")])),
            Ok(123)
        );
        assert!(matches!(
            parse_content_range(&headers(&[("content-range", "bytes 0-0/xyz")])),
            Err(MetadataError::ParseIntError(_))
        ));
    }

    #[test]
    fn relative_location_merge() {
        assert_eq!(
            merge_relative_location(URL, "/other/path?q=1").unwrap(),
            Some("https://huggingface.co/other/path?q=1".to_string())
        );
        assert_eq!(
            merge_relative_location(URL, "https://elsewhere.com/x").unwrap(),
            None
        );
    }

    #[test]
    fn chunk_ranges_cover_the_file() {
        let ranges: Vec<_> = chunk_ranges(0, 30, 10).collect();
        assert_eq!(ranges, vec![(0, 9), (10, 19), (20, 29)]);

        // Resume from a watermark mid-file.
        let ranges: Vec<_> = chunk_ranges(10, 30, 10).collect();
        assert_eq!(ranges, vec![(10, 19), (20, 29)]);

        // NOTE: on the last chunk the historical behavior requests one
        // byte past the end (`stop == length`); servers clamp the range,
        // so this is preserved bug-for-bug.
        let ranges: Vec<_> = chunk_ranges(0, 25, 10).collect();
        assert_eq!(ranges, vec![(0, 9), (10, 19), (20, 25)]);

        assert_eq!(chunk_ranges(30, 30, 10).count(), 0);
    }

    #[test]
    fn commit_tracker_watermark() {
        let mut tracker = CommitTracker::new(0);
        // Out-of-order completion: nothing commits until the gap fills.
        assert_eq!(tracker.advance(10, 19), None);
        assert_eq!(tracker.advance(20, 29), None);
        assert_eq!(tracker.advance(0, 9), Some(30));
    }

    #[test]
    fn commit_tracker_resumed_start() {
        let mut tracker = CommitTracker::new(10);
        assert_eq!(tracker.advance(10, 19), Some(20));
        assert_eq!(tracker.advance(30, 39), None);
        assert_eq!(tracker.advance(20, 29), Some(40));
    }

    #[test]
    fn trailer_round_trip() {
        assert_eq!(decode_trailer(encode_trailer(0)), 0);
        assert_eq!(decode_trailer(encode_trailer(123456789)), 123456789);
        assert_eq!(part_file_len(100), 108);
    }

    #[test]
    fn sequential_resume() {
        assert_eq!(sequential_resume_start(0, 100), Some(0));
        assert_eq!(sequential_resume_start(50, 100), Some(50));
        assert_eq!(sequential_resume_start(100, 100), Some(100));
        assert_eq!(sequential_resume_start(101, 100), None);
    }

    #[test]
    fn backoff_is_bounded() {
        for n in 0..10 {
            let wait = exponential_backoff(300, n, 10_000);
            assert!(wait >= (300 + n.pow(2)).min(10_000));
            assert!(wait <= (300 + n.pow(2) + 500).min(10_000));
        }
    }

    #[test]
    fn user_agent() {
        let parts = default_user_agent();
        assert_eq!(
            user_agent_string(&parts),
            format!("unknown/None; {NAME}/{VERSION}; rust/unknown")
        );
    }
}