liboxen 0.49.1

Oxen is a fast, unstructured data version control, to help version large machine learning datasets written in Rust.
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
use crate::api;
use crate::api::client;
use crate::api::client::internal_types::LocalOrBase;
use crate::constants::{AVG_CHUNK_SIZE, max_retries};
use crate::error::OxenError;
use crate::model::{CommitEntry, LocalRepository, MerkleHash, RemoteRepository};
use crate::util::{self, concurrency, hasher};
use crate::view::versions::{
    CleanCorruptedVersionsResponse, CompleteVersionUploadRequest, CompletedFileUpload,
    CreateVersionUploadRequest, MultipartLargeFileUpload, MultipartLargeFileUploadStatus,
    VersionFile, VersionFileResponse,
};
use crate::view::{ErrorFileInfo, ErrorFilesResponse, FileWithHash};

use crate::core::progress::push_progress::PushProgress;
use async_compression::tokio::bufread::GzipDecoder;
use flate2::Compression;
use flate2::write::GzEncoder;
use futures_util::StreamExt;
use futures_util::stream::FuturesUnordered;
use http::Method;
use http::header::CONTENT_LENGTH;
use rand::{Rng, thread_rng};
use tokio_tar::Archive;
use tokio_util::codec::{BytesCodec, FramedRead};

use std::collections::{HashMap, HashSet};
use std::io::{SeekFrom, Write};
use std::path::{Path, PathBuf};
use std::sync::Arc;
use std::time::Duration;
use tokio::fs::OpenOptions;
use tokio::io::{AsyncReadExt, AsyncSeekExt};
use tokio::sync::Semaphore;
use tokio::time::sleep;

use crate::repositories;

// Multipart upload strategy, based off of AWS S3 Multipart Upload and huggingface hf_transfer
// https://docs.aws.amazon.com/AmazonS3/latest/userguide/mpuoverview.html
// https://github.com/huggingface/hf_transfer/blob/main/src/lib.rs#L104
const BASE_WAIT_TIME: usize = 300;
const MAX_WAIT_TIME: usize = 10_000;
const PARALLEL_FAILURES: usize = 63;

#[derive(Debug, Default)]
pub struct UploadResult {
    pub files_to_add: Vec<FileWithHash>,
    pub err_files: Vec<ErrorFileInfo>,
}

/// Get the size of a version
pub async fn get(
    repository: &RemoteRepository,
    version_id: MerkleHash,
) -> Result<Option<VersionFile>, OxenError> {
    let uri = format!("/versions/{version_id}/metadata");
    let url = api::endpoint::url_from_repo(repository, &uri)?;
    log::debug!("api::client::versions::get {url}");

    let client = client::new_for_url(&url)?;
    let res = client.get(&url).send().await?;
    if res.status() == 404 {
        return Ok(None);
    }

    let body = client::parse_json_body(&url, res).await?;
    let response: Result<VersionFileResponse, serde_json::Error> = serde_json::from_str(&body);
    match response {
        Ok(version_file) => Ok(Some(version_file.version)),
        Err(err) => Err(OxenError::basic_str(format!(
            "api::client::versions::get() Could not deserialize response [{err}]\n{body}"
        ))),
    }
}

pub async fn clean(
    remote_repo: &RemoteRepository,
) -> Result<CleanCorruptedVersionsResponse, OxenError> {
    let uri = "/versions";
    let url = api::endpoint::url_from_repo(remote_repo, uri)?;
    log::debug!("api::client::versions::clean {url}");

    let client = client::new_for_url(&url)?;
    let res = client.delete(&url).send().await?;
    let body = client::parse_json_body(&url, res).await?;
    let response: Result<CleanCorruptedVersionsResponse, serde_json::Error> =
        serde_json::from_str(&body);
    match response {
        Ok(response) => Ok(response),
        Err(err) => Err(OxenError::basic_str(format!(
            "api::client::versions::clean() Could not deserialize response [{err}]\n{body}"
        ))),
    }
}

/// Uploads a large file to the server in parallel and unpacks it in the versions directory
/// Returns the `MultipartLargeFileUpload` struct for the created upload
pub async fn parallel_large_file_upload(
    remote_repo: &RemoteRepository,
    file_path: impl AsRef<Path>,
    dst_dir: Option<impl AsRef<Path>>, // dst_dir is provided for workspace add workflow
    workspace_id: Option<String>,
    update_timestamp: bool,
    commit_entry: Option<CommitEntry>, // entry is provided for push workflow
    progress: Option<&Arc<PushProgress>>, // for push workflow
) -> Result<MultipartLargeFileUpload, OxenError> {
    log::debug!("multipart_large_file_upload path: {:?}", file_path.as_ref());

    let mut upload =
        create_multipart_large_file_upload(remote_repo, file_path, dst_dir, commit_entry).await?;

    log::debug!("multipart_large_file_upload upload: {:?}", upload.hash);

    let max_retries = max_retries();
    let results = upload_chunks(
        remote_repo,
        &mut upload,
        AVG_CHUNK_SIZE,
        PARALLEL_FAILURES,
        max_retries,
        progress,
    )
    .await?;
    let num_chunks = results.len();
    log::debug!("multipart_large_file_upload num_chunks: {num_chunks:?}");
    complete_multipart_large_file_upload(
        remote_repo,
        upload,
        num_chunks,
        workspace_id,
        update_timestamp,
    )
    .await
}

/// Creates a new multipart large file upload
/// Will reject the upload if the hash already exists on the server.
/// The rejection helps prevent duplicate uploads or parallel uploads of the same file.
/// Returns the `MultipartLargeFileUpload` struct for the created upload
async fn create_multipart_large_file_upload(
    remote_repo: &RemoteRepository,
    file_path: impl AsRef<Path>,
    dst_dir: Option<impl AsRef<Path>>,
    commit_entry: Option<CommitEntry>,
) -> Result<MultipartLargeFileUpload, OxenError> {
    let file_path = file_path.as_ref();
    let dst_dir = dst_dir.as_ref();

    let (file_size, hash) = match commit_entry {
        Some(commit_entry) => (commit_entry.num_bytes, commit_entry.hash.clone()),
        None => {
            // Figure out how many parts we need to upload
            let Ok(metadata) = file_path.metadata() else {
                return Err(OxenError::path_does_not_exist(file_path));
            };
            let file_size = metadata.len();
            let hash = util::hasher::hash_file_contents(file_path)?;
            (file_size, hash)
        }
    };

    let uri = format!("/versions/{hash}/create");
    let url = api::endpoint::url_from_repo(remote_repo, &uri)?;
    let client = client::new_for_url(&url)?;

    let body = CreateVersionUploadRequest {
        hash: hash.to_string(),
        file_name: file_path.file_name().unwrap().to_string_lossy().to_string(),
        size: file_size,
        dst_dir: dst_dir.map(|d| d.as_ref().to_path_buf()),
    };

    let body = serde_json::to_string(&body)?;
    let response = client
        .post(&url)
        .header("Content-Type", "application/json")
        .body(body)
        .send()
        .await?;
    response.error_for_status()?;

    Ok(MultipartLargeFileUpload {
        local_path: file_path.to_path_buf(),
        dst_dir: dst_dir.map(|d| d.as_ref().to_path_buf()),
        hash: hash.parse()?,
        size: file_size,
        status: MultipartLargeFileUploadStatus::Pending,
        reason: None,
    })
}

/// Batch download.
///
/// `entries` is a list of `(content_hash, source_path)` pairs — only the hash is sent over the wire
/// (the bulk endpoint identifies blobs by hash); the path is preserved purely for diagnostic
/// surfaces (errors, logs) so end users can identify which file(s) failed.
#[tracing::instrument(skip_all)]
pub async fn download_data_from_version_paths(
    remote_repo: &RemoteRepository,
    entries: &[(String, PathBuf)],
    local_repo: &LocalRepository,
) -> Result<u64, OxenError> {
    let total_retries = max_retries().try_into().unwrap_or(max_retries() as u64);
    let mut num_retries = 0;
    let mut last_err: Option<OxenError> = None;

    while num_retries < total_retries {
        match try_download_data_from_version_paths(remote_repo, entries, local_repo).await {
            Ok(val) => return Ok(val),
            Err(OxenError::Authentication(val)) => return Err(OxenError::Authentication(val)),
            Err(err) => {
                num_retries += 1;
                // Exponentially back off
                let sleep_time = num_retries * num_retries;
                log::warn!("Could not download content {err:?} sleeping {sleep_time}");
                last_err = Some(err);
                tokio::time::sleep(std::time::Duration::from_secs(sleep_time)).await;
            }
        }
    }

    // Preserve the failing batch's entries (path + hash) and last underlying error so callers
    // and server logs can identify which file(s) the server couldn't serve. Without this, the
    // symptom surfaces as a bare "failed to download N files" with no way to map back to
    // specific files.
    let last_error = last_err
        .as_ref()
        .map(|e| format!("{e}"))
        .unwrap_or_else(|| "(no attempts made)".to_string());
    let formatted_entries = entries
        .iter()
        .map(|(h, p)| format!("{} (hash: {h})", p.display()))
        .collect::<Vec<_>>()
        .join(", ");
    log::error!(
        "Bulk download exhausted {} retries for {} entries: [{}]. Last error: {}",
        total_retries,
        entries.len(),
        formatted_entries,
        last_error,
    );
    Err(OxenError::DownloadBatchExhausted {
        num_files: entries.len(),
        num_retries: total_retries,
        entries: entries.to_vec(),
        last_error,
    })
}

#[tracing::instrument(skip_all)]
pub async fn try_download_data_from_version_paths(
    remote_repo: &RemoteRepository,
    entries: &[(String, PathBuf)],
    local_repo: &LocalRepository,
) -> Result<u64, OxenError> {
    let mut encoder = GzEncoder::new(Vec::new(), Compression::default());
    for (hash, _path) in entries.iter() {
        let line = format!("{hash}\n");
        // log::debug!("download_data_from_version_paths encoding line: {} path: {:?}", line, path);
        encoder.write_all(line.as_bytes())?;
    }
    let body = encoder.finish()?;
    log::debug!("download_data_from_version_paths body len: {}", body.len());

    let url = api::endpoint::url_from_repo(remote_repo, "/versions")?;
    let client = client::new_for_url(&url)?;
    let query_method = Method::from_bytes(b"QUERY").unwrap();
    if let Ok(res) = client.request(query_method, &url).body(body).send().await {
        let res = client::handle_non_json_response(&url, res).await?;

        let stream = res.bytes_stream();
        let reader = tokio_util::io::StreamReader::new(
            stream.map(|result| result.map_err(std::io::Error::other)),
        );
        let buf_reader = tokio::io::BufReader::new(reader);
        let decoder = GzipDecoder::new(buf_reader);
        let mut archive = Archive::new(decoder);

        let version_store = local_repo.version_store()?;
        let mut size: u64 = 0;

        // Iterate over archive entries and stream them to version store
        let mut entries = archive.entries()?;
        while let Some(file) = entries.next().await {
            let file = match file {
                Ok(file) => file,
                Err(err) => {
                    let err = format!("Could not unwrap file -> {err:?}");
                    return Err(OxenError::basic_str(err));
                }
            };

            let file_hash = file
                .path()
                .map_err(|e| OxenError::basic_str(format!("Failed to get entry path: {e}")))?
                .to_string_lossy()
                .to_string();

            // Get file size from tar entry header
            let file_size = file.header().size()?;
            size += file_size;

            // Stream the file content directly to version store without loading into memory
            match version_store
                .store_version_from_reader(&file_hash, Box::new(file), file_size)
                .await
            {
                Ok(_) => {
                    log::debug!(
                        "Successfully stored file {file_hash} ({file_size} bytes) to version store"
                    );
                }
                Err(err) => {
                    let err =
                        format!("Could not store file {file_hash} to version store -> {err:?}");
                    return Err(OxenError::basic_str(err));
                }
            }
        }

        Ok(size)
    } else {
        let err =
            format!("api::entries::download_data_from_version_paths Err request failed: {url}");
        Err(OxenError::basic_str(err))
    }
}

async fn upload_chunks(
    remote_repo: &RemoteRepository,
    upload: &mut MultipartLargeFileUpload,
    chunk_size: u64,
    parallel_failures: usize,
    max_retries: usize,
    progress: Option<&Arc<PushProgress>>,
) -> Result<Vec<HashMap<String, String>>, OxenError> {
    let client = Arc::new(api::client::new_for_remote_repo(remote_repo)?);

    // Figure out how many parts we need to upload
    let file_size = upload.size;
    let num_chunks = file_size.div_ceil(chunk_size);

    let max_files = concurrency::num_threads_for_items(num_chunks as usize);
    let mut handles = FuturesUnordered::new();
    let semaphore = Arc::new(Semaphore::new(max_files));
    let parallel_failures_semaphore = Arc::new(Semaphore::new(parallel_failures));

    for chunk_number in 0..num_chunks {
        let remote_repo = remote_repo.clone();
        let upload = upload.clone();
        let client = Arc::clone(&client);

        let start = chunk_number * chunk_size;
        let semaphore = semaphore.clone();
        let parallel_failures_semaphore = parallel_failures_semaphore.clone();
        handles.push(tokio::spawn(async move {
                    let permit = semaphore
                        .clone()
                        .acquire_owned()
                        .await
                        .map_err(|err| OxenError::basic_str(format!("Error acquiring semaphore: {err}")))?;
                    let mut chunk = upload_chunk(&client, &remote_repo, &upload, start, chunk_size).await;
                    let mut i = 0;
                    if parallel_failures > 0 {
                        while let Err(ul_err) = chunk {
                            if i >= max_retries {
                                return Err(OxenError::basic_str(format!(
                                    "Failed after too many retries ({max_retries}): {ul_err}"
                                )));
                            }

                            let parallel_failure_permit = parallel_failures_semaphore.clone().try_acquire_owned().map_err(|err| {
                                OxenError::basic_str(format!(
                                    "Failed too many failures in parallel ({parallel_failures}): {ul_err} ({err})"
                                ))
                            })?;

                            let wait_time = exponential_backoff(BASE_WAIT_TIME, i, MAX_WAIT_TIME);
                            sleep(Duration::from_millis(wait_time as u64)).await;

                            chunk = upload_chunk(&client, &remote_repo, &upload, start, chunk_size).await;
                            i += 1;
                            drop(parallel_failure_permit);
                        }
                    }
                    drop(permit);
                    chunk
                    .map_err(|e| OxenError::basic_str(format!("Upload error {e}")))
                    .map(|chunk| (chunk_number, chunk, chunk_size))
                }));
    }

    let mut results: Vec<HashMap<String, String>> = vec![HashMap::default(); num_chunks as usize];

    while let Some(result) = handles.next().await {
        match result {
            Ok(Ok((chunk_number, headers, size))) => {
                log::debug!("Uploaded part {chunk_number} with size {size}");
                results[chunk_number as usize] = headers;
                if let Some(p) = progress {
                    p.add_bytes(size);
                }
            }
            Ok(Err(py_err)) => {
                return Err(py_err);
            }
            Err(err) => {
                return Err(OxenError::basic_str(format!(
                    "Error occurred while uploading: {err}"
                )));
            }
        }
    }
    if let Some(p) = progress {
        p.add_files(1);
    }
    Ok(results)
}

async fn upload_chunk(
    client: &reqwest::Client,
    remote_repo: &RemoteRepository,
    upload: &MultipartLargeFileUpload,
    start: u64,
    chunk_size: u64,
) -> Result<HashMap<String, String>, OxenError> {
    let path = &upload.local_path;
    let mut options = OpenOptions::new();
    let mut file = options.read(true).open(path).await?;

    let file_size = upload.size;
    let bytes_transferred = std::cmp::min(file_size - start, chunk_size);

    file.seek(SeekFrom::Start(start)).await?;
    let chunk = file.take(chunk_size);

    let file_hash = &upload.hash.to_string();

    let uri = format!("/versions/{file_hash}/chunks?offset={start}");
    let url = api::endpoint::url_from_repo(remote_repo, &uri)?;

    let response = client
        .put(url)
        .header(CONTENT_LENGTH, bytes_transferred)
        .body(reqwest::Body::wrap_stream(FramedRead::new(
            chunk,
            BytesCodec::new(),
        )))
        .send()
        .await?;
    let response = response.error_for_status()?;
    let mut headers = HashMap::new();
    for (name, value) in response.headers().into_iter() {
        headers.insert(
            name.to_string(),
            value
                .to_str()
                .map_err(|e| OxenError::basic_str(format!("Invalid header value: {e}")))?
                .to_owned(),
        );
    }
    Ok(headers)
}

async fn complete_multipart_large_file_upload(
    remote_repo: &RemoteRepository,
    upload: MultipartLargeFileUpload,
    num_chunks: usize,
    workspace_id: Option<String>,
    update_timestamp: bool,
) -> Result<MultipartLargeFileUpload, OxenError> {
    let file_hash = &upload.hash.to_string();

    let uri = format!("/versions/{file_hash}/complete");
    let url = api::endpoint::url_from_repo(remote_repo, &uri)?;
    log::debug!("complete_multipart_large_file_upload {url}");
    let client = client::new_for_url(&url)?;

    let body = CompleteVersionUploadRequest {
        files: vec![CompletedFileUpload {
            hash: file_hash.to_string(),
            file_name: upload
                .local_path
                .file_name()
                .unwrap()
                .to_string_lossy()
                .to_string(),
            dst_dir: upload.dst_dir.clone(),
            num_chunks: Some(num_chunks),
            upload_results: None,
        }],
        workspace_id,
        update_timestamp,
    };

    let body = serde_json::to_string(&body)?;
    let response = client.post(&url).body(body).send().await?;
    let body = client::parse_json_body(&url, response).await?;
    log::debug!("complete_multipart_large_file_upload got body: {body}");
    Ok(upload)
}

/// Multipart batch upload with retry
/// Uploads a batch of small files to the server in parallel and retries on failure
/// Returns a list of files that failed to upload
pub async fn multipart_batch_upload_with_retry(
    local_repo: &LocalRepository,
    remote_repo: &RemoteRepository,
    chunk: &[CommitEntry],
    client: &reqwest::Client,
) -> Result<(), OxenError> {
    let mut files_to_retry: Vec<ErrorFileInfo> = vec![];
    let mut first_try = true;
    let mut retry_count: usize = 0;
    let max_retries = max_retries();

    while (first_try || !files_to_retry.is_empty()) && retry_count < max_retries {
        first_try = false;
        retry_count += 1;

        files_to_retry =
            multipart_batch_upload(local_repo, remote_repo, chunk, client, files_to_retry).await?;

        if !files_to_retry.is_empty() {
            let wait_time = exponential_backoff(BASE_WAIT_TIME, retry_count, MAX_WAIT_TIME);
            sleep(Duration::from_millis(wait_time as u64)).await;
        }
    }
    if files_to_retry.is_empty() {
        Ok(())
    } else {
        Err(OxenError::basic_str(format!(
            "Failed to upload files: {files_to_retry:#?}"
        )))
    }
}

pub async fn multipart_batch_upload(
    local_repo: &LocalRepository,
    remote_repo: &RemoteRepository,
    chunk: &[CommitEntry],
    client: &reqwest::Client,
    files_to_retry: Vec<ErrorFileInfo>,
) -> Result<Vec<ErrorFileInfo>, OxenError> {
    let version_store = local_repo.version_store()?;
    let mut form = reqwest::multipart::Form::new();
    let mut err_files: Vec<ErrorFileInfo> = vec![];

    // if it's the first try, we don't have any files to retry
    let retry_hashes: HashSet<String> = if files_to_retry.is_empty() {
        HashSet::new()
    } else {
        files_to_retry.iter().map(|f| f.hash.clone()).collect()
    };

    for commit_entry in chunk {
        let file_hash = &commit_entry.hash;

        // if it's not the first try and the file is not in the retry list, skip
        if !files_to_retry.is_empty() && !retry_hashes.contains(file_hash) {
            continue;
        }

        let data = version_store.get_version(file_hash).await?;
        let mut encoder = GzEncoder::new(Vec::new(), Compression::default());
        std::io::copy(&mut data.as_slice(), &mut encoder)?;
        let compressed_bytes = match encoder.finish() {
            Ok(bytes) => bytes,
            Err(e) => {
                log::error!("Failed to finish gzip for file {}: {}", file_hash, e);
                err_files.push(ErrorFileInfo {
                    hash: file_hash.clone(),
                    path: None,
                    error: format!("Failed to finish gzip for file {}: {}", file_hash, e),
                });
                continue;
            }
        };

        let file_part = reqwest::multipart::Part::bytes(compressed_bytes)
            .file_name(commit_entry.hash.clone())
            .mime_str("application/gzip")?;
        form = form.part("file[]", file_part);
    }

    // If there are nodes to mark as synced, re-route API call
    let uri = ("/versions").to_string();

    let url = api::endpoint::url_from_repo(remote_repo, &uri)?;

    // Post the node hashes to sync on the first chunk upload

    let response = client.post(&url).multipart(form).send().await?;
    let body = client::parse_json_body(&url, response).await?;
    let response: ErrorFilesResponse = serde_json::from_str(&body)?;

    err_files.extend(response.err_files);

    Ok(err_files)
}

pub(crate) async fn workspace_multipart_batch_upload_versions(
    remote_repo: &RemoteRepository,
    local_or_base: Option<&LocalOrBase>,
    client: Arc<reqwest::Client>,
    paths: Vec<PathBuf>,
    result: UploadResult,
) -> Result<UploadResult, OxenError> {
    // save the errorred files info for retry
    let mut err_files: Vec<ErrorFileInfo> = vec![];
    // keep track of the files hash
    let mut files_to_add: Vec<FileWithHash> = vec![];

    // generate retry hashes if it's not the first try
    let retry_hashes: HashSet<String> = if result.err_files.is_empty() {
        HashSet::new()
    } else {
        result.err_files.iter().map(|f| f.hash.clone()).collect()
    };

    // generate a map of the file paths to hashes
    let path_to_hash: HashMap<PathBuf, String> = result
        .files_to_add
        .iter()
        .map(|f| (f.path.clone(), f.hash.clone()))
        .collect();

    let (repo_or_base_path, head_commit_local_repo_maybe) = match local_or_base {
        Some(LocalOrBase::Local(local_repo)) => {
            let head_commit_maybe = repositories::commits::head_commit_maybe(local_repo)?;
            (
                local_repo.path.clone(),
                head_commit_maybe.map(|head_commit| (head_commit, local_repo)),
            )
        }
        Some(LocalOrBase::Base(base_dir)) => (base_dir.clone(), None),
        None => (PathBuf::new(), None),
    };

    let form = {
        let mut form = reqwest::multipart::Form::new();

        for path in paths {
            let relative_path = util::fs::path_relative_to_dir(&path, &repo_or_base_path)?;
            // Skip adding files already present in tree
            if let Some((ref head_commit, local_repo)) = head_commit_local_repo_maybe
                && let Some(file_node) =
                    repositories::tree::get_file_by_path(local_repo, head_commit, &relative_path)?
                && !local_repo.is_modified_from_node(&path, &file_node).await?
            {
                continue;
            }

            // if it's not the first try
            if !result.err_files.is_empty() {
                // if the file doesn't have a hash it failed, so we need to retry it
                if let Some(hash) = path_to_hash.get(&path) {
                    // check if the file is in the retry list. if not, skip
                    if !retry_hashes.contains(hash) {
                        continue;
                    }
                }
            }

            let Some(_file_name) = path.file_name() else {
                return Err(OxenError::basic_str(format!("Invalid file path: {path:?}")));
            };

            let file = std::fs::read(&path).map_err(|e| {
                OxenError::basic_str(format!("Failed to read file '{path:?}': {e}"))
            })?;

            let hash = hasher::hash_buffer(&file);

            // Workspaces expect just the file name, while remote-mode repos expect the relative path
            // TODO: Refactor this into separate modules later, but for now, remote-mode repos will always have
            //       a local_repo, whereas workspaces will have local_repo be None
            files_to_add.push(FileWithHash {
                hash: hash.clone(),
                path: match local_or_base {
                    Some(_) => relative_path,
                    None => PathBuf::from(path.file_name().unwrap()),
                },
            });

            // gzip the file
            let compressed_bytes: Vec<u8> = {
                let mut encoder = GzEncoder::new(Vec::new(), Compression::default());
                std::io::copy(&mut file.as_slice(), &mut encoder)?;
                match encoder.finish() {
                    Ok(bytes) => bytes,
                    Err(e) => {
                        log::error!("Failed to finish gzip for file {}: {}", &hash, e);
                        // When uploading to the version store, we use the hash as the file identifier. The path is not needed.
                        err_files.push(ErrorFileInfo {
                            hash: hash.clone(),
                            path: None,
                            error: format!("Failed to finish gzip for file {}: {}", &hash, e),
                        });
                        continue;
                    }
                }
            };

            let file_part = reqwest::multipart::Part::bytes(compressed_bytes)
                .file_name(hash)
                .mime_str("application/gzip")?;

            form = form.part("file[]", file_part);
        }

        form
    };

    let url = api::endpoint::url_from_repo(remote_repo, "/versions")?;
    let response = client.post(&url).multipart(form).send().await?;
    let body = client::parse_json_body(&url, response).await?;

    let response: ErrorFilesResponse = serde_json::from_str(&body)?;
    log::debug!("workspace_multipart_batch_upload got response: {response:?}");
    err_files.extend(response.err_files);

    Ok(UploadResult {
        files_to_add,
        err_files,
    })
}

pub(crate) async fn workspace_multipart_batch_upload_parts_with_retry(
    remote_repo: &RemoteRepository,
    client: Arc<reqwest::Client>,
    form: reqwest::multipart::Form,
    files_to_retry: &mut Vec<FileWithHash>,
    local_or_base: Option<&LocalOrBase>,
) -> Result<Vec<ErrorFileInfo>, OxenError> {
    log::debug!("Beginning workspace multipart batch upload");
    let uri = ("/versions").to_string();
    let url = api::endpoint::url_from_repo(remote_repo, &uri)?;

    let mut retry_count: usize = 1;
    let max_retries = max_retries();

    // Upload the processed version files
    let response = client.post(&url).multipart(form).send().await?;
    let mut upload_result: UploadResult = match client::parse_json_body(&url, response).await {
        Ok(body) => {
            let result: ErrorFilesResponse = serde_json::from_str(&body)?;
            // Remove successfully uploaded files from files_to_retry
            let err_file_hashes: Vec<String> =
                result.err_files.iter().map(|f| f.hash.clone()).collect();
            files_to_retry.retain(|f| err_file_hashes.contains(&f.hash));

            UploadResult {
                files_to_add: vec![],
                err_files: result.err_files,
            }
        }
        Err(e) => {
            log::error!("failed to upload version files: {e:?}");
            UploadResult {
                files_to_add: files_to_retry.clone(),
                err_files: vec![],
            }
        }
    };

    // If files fail, rebuild parts for the err_files and retry
    while (!files_to_retry.is_empty()) && retry_count < max_retries {
        retry_count += 1;

        let paths = files_to_retry.iter().map(|f| f.path.clone()).collect();

        upload_result = match workspace_multipart_batch_upload_versions(
            remote_repo,
            local_or_base,
            client.clone(),
            paths,
            upload_result,
        )
        .await
        {
            Ok(upload_result) => {
                let err_file_hashes: Vec<String> = upload_result
                    .err_files
                    .iter()
                    .map(|f| f.hash.clone())
                    .collect();
                files_to_retry.retain(|f| err_file_hashes.contains(&f.hash));

                upload_result
            }
            Err(e) => {
                // TODO: Consider converting this to a debug log
                log::error!("failed to upload version files after {retry_count} retries: {e:?}");

                // Note: `files_to_add` and `err_files` aren't actually used by
                // workspace_multipart_batch_upload to process retry files differently
                // Hence, these fields can be empty
                UploadResult {
                    files_to_add: vec![],
                    err_files: vec![],
                }
            }
        };

        if !files_to_retry.is_empty() {
            let wait_time = exponential_backoff(BASE_WAIT_TIME, retry_count, MAX_WAIT_TIME);
            sleep(Duration::from_millis(wait_time as u64)).await;
        }
    }

    if !files_to_retry.is_empty() {
        return Err(OxenError::basic_str(format!(
            "Failed to upload version files after {max_retries} retries"
        )));
    }

    Ok(upload_result.err_files)
}

pub fn exponential_backoff(base_wait_time: usize, n: usize, max: usize) -> usize {
    log::debug!(
        "Exponential backoff got called with base_wait_time {base_wait_time}. n {n}, and max {max}"
    );
    (base_wait_time + n.pow(2) + jitter()).min(max)
}

fn jitter() -> usize {
    thread_rng().gen_range(0..=500)
}

#[cfg(test)]
mod tests {
    use std::path::PathBuf;

    use crate::api;
    use crate::error::OxenError;
    use crate::test;

    #[tokio::test]
    async fn test_upload_large_file_in_chunks() -> Result<(), OxenError> {
        test::run_remote_repo_test_bounding_box_csv_pushed(|_local_repo, remote_repo| async move {
            let path = test::test_30k_parquet();

            // Get original file size
            let metadata = path.metadata().unwrap();
            let original_file_size = metadata.len();

            // Just testing upload, not adding to workspace
            let workspace_id = None;
            let dst_dir: Option<PathBuf> = None;
            let result = api::client::versions::parallel_large_file_upload(
                &remote_repo,
                path,
                dst_dir,
                workspace_id,
                false,
                None,
                None,
            )
            .await;
            assert!(result.is_ok());

            let version = api::client::versions::get(&remote_repo, result.unwrap().hash).await?;
            assert!(version.is_some());
            assert_eq!(version.unwrap().size, original_file_size);

            Ok(remote_repo)
        })
        .await
    }
}