Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,8 @@ clap = { version = "4.6", features = ["derive", "env"] }
crossterm = "0.29"
futures-util = { version = "0.3", features = ["sink"] }
httpdate = "1.0"
hex = "0.4"
sha2 = "0.11"
reqwest = { version = "0.12", default-features = false, features = ["json", "rustls-tls", "stream"] }
serde = { version = "1.0", features = ["derive"] }
serde_json = "1.0"
Expand All @@ -33,8 +35,6 @@ uuid = { version = "1.27", features = ["v4", "serde"] }

[target.'cfg(unix)'.dependencies]
flate2 = "1"
hex = "0.4"
sha2 = "0.11"
tar = "0.4"
libc = "0.2"

Expand Down
5 changes: 4 additions & 1 deletion docs/cli-reference.md
Original file line number Diff line number Diff line change
Expand Up @@ -397,7 +397,10 @@ adapt files get SANDBOX_ID /app/result.bin ./result.bin
adapt files get SANDBOX_ID /app/result.bin - > result.bin
```

The transfer limit is 16 MiB per file.
For local regular files larger than 16 MiB, `files put` hashes the file and streams
it to the sandbox in 8 MiB ranges. On a brief disconnect it asks the node which
bytes arrived and resumes there. This requires a node with large-upload support.
Downloads and uploads from stdin have a 16 MiB limit.
Parent directories must exist in the sandbox.
Use `-` for the local path to read stdin or write stdout.
The CLI writes a download to its destination file only after the transfer completes.
Expand Down
2 changes: 1 addition & 1 deletion skills/adapt/SKILL.md
Original file line number Diff line number Diff line change
Expand Up @@ -113,7 +113,7 @@ adapt endpoints get ENDPOINT_ID
adapt endpoints request ENDPOINT_ID /path --new-token
```

File transfers are limited to 16 MiB and guest parent directories must exist.
Large regular files upload in resumable ranges. Downloads and stdin uploads are limited to 16 MiB. Guest parent directories must exist.
Downloads refuse to overwrite local files unless `--force` is given. Hosted apps
must listen on `0.0.0.0`. Endpoint tokens authenticate the hosted app with
`X-Adapt-Authorization: Bearer TOKEN`; they are not Platform API credentials.
Expand Down
2 changes: 1 addition & 1 deletion src/api.rs
Original file line number Diff line number Diff line change
Expand Up @@ -218,7 +218,7 @@ impl Api {
}
}

fn read_retry_delay(error: &anyhow::Error, backoff: Duration) -> Option<Duration> {
pub(crate) fn read_retry_delay(error: &anyhow::Error, backoff: Duration) -> Option<Duration> {
if let Some(error) = error.downcast_ref::<ApiError>() {
if !matches!(error.status.as_u16(), 408 | 429 | 500 | 502 | 503 | 504) {
return None;
Expand Down
7 changes: 7 additions & 0 deletions src/commands.rs
Original file line number Diff line number Diff line change
Expand Up @@ -605,6 +605,13 @@ pub(crate) async fn files(api: &Api, command: FileCommand) -> Result<Value> {
local,
remote,
} => {
if local != Path::new("-")
&& std::fs::metadata(&local)
.is_ok_and(|m| m.is_file() && m.len() > input::MAX_FILE_BYTES)
{
let id = crate::upload::put(api, &sandbox, &local, &remote).await?;
return Ok(json!({"uploaded":remote,"sandboxId":id}));
}
let data = input::bytes(&local, input::MAX_FILE_BYTES)?;
let response = api
.request(Method::PUT, &format!("/v1/sandboxes/{sandbox}/files"))?
Expand Down
1 change: 1 addition & 0 deletions src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ mod runtime;
mod shell;
mod skill;
mod stream;
mod upload;

use clap::{CommandFactory, Parser};
use cli::Cli;
Expand Down
117 changes: 117 additions & 0 deletions src/upload.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,117 @@
//! A seekable file can be checksummed once and replayed at the node's byte offset.
use crate::{
api::{self, Api},
input::ResourceRef,
};
use anyhow::{Context, Result, ensure};
use reqwest::Method;
use serde::Deserialize;
use serde_json::json;
use sha2::{Digest, Sha256};
use std::{
fs::File,
io::{Read, Seek, SeekFrom},
path::Path,
time::Duration,
};
use uuid::Uuid;

const PART_BYTES: usize = 8 * 1024 * 1024;
#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
struct Progress {
offset: u64,
complete: bool,
sandbox_id: Uuid,
}

pub(crate) async fn put(
api: &Api,
sandbox: &ResourceRef,
local: &Path,
remote: &str,
) -> Result<Uuid> {
let path = local.to_path_buf();
let (mut file, size, digest) = tokio::task::spawn_blocking(move || -> Result<_> {
let mut file = File::open(path)?;
let size = file.metadata()?.len();
let mut hash = Sha256::new();
let mut block = vec![0; 256 * 1024];
loop {
let n = file.read(&mut block)?;
if n == 0 {
break;
}
hash.update(&block[..n]);
}
Ok((file, size, hex::encode(hash.finalize())))
})
.await??;
let route = format!("/v1/sandboxes/{sandbox}/file-uploads/{}", Uuid::new_v4());

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[P1] Must fix: Pin the resolved sandbox throughout the upload

Every request re-resolves the original prefix. If its sandbox is deleted and another matches, the 404/reopen path uploads into that other sandbox (reproduced). Pin subsequent requests to the first acknowledged sandboxId.

let input = json!({"path":remote,"size":size,"sha256":digest});
let mut progress: Option<Progress> = None;
let mut retries = 0;
loop {
let attempt: Result<Progress> = async {
let Some(current) = &progress else {
return Ok(serde_json::from_value(
api.json(Method::PUT, &route, Some(&input), &[], None)
.await?,
)?);
};
let length = (size - current.offset).min(PART_BYTES as u64) as usize;
file.seek(SeekFrom::Start(current.offset))?;
let mut data = vec![0; length];
file.read_exact(&mut data)
.context("Local file changed during upload")?;
let response = api
.request(Method::PUT, &format!("{route}/data"))?
.query(&[("offset", current.offset), ("length", length as u64)])
.header("Content-Type", "application/octet-stream")
.body(data)
.timeout(api.timeout)
.send()
.await?;
let bytes = api::limited_bytes(api::ensure_success(response).await?, 8192).await?;
let next: Progress = serde_json::from_slice(&bytes)?;
ensure!(
next.complete || next.offset > current.offset,
"The upload made no progress"
);
Ok(next)
}
.await;
match attempt {
Ok(next) => {
ensure!(
next.offset <= size && (!next.complete || next.offset == size),
"Invalid upload acknowledgement"
);
if next.complete {
return Ok(next.sandbox_id);
}
if progress.is_some() {

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[P2] Must fix: Reset retries when reconciliation confirms progress

Reopening clears progress, so confirmed offset advances never reset retries. Four lost range acknowledgements abort a 32 MiB upload—even after commit (reproduced). Reset the budget when reconciliation confirms forward progress.

retries = 0;
}
progress = Some(next);
}
Err(error) => {
let backoff = Duration::from_millis(250 << retries);
let conflict = error
.downcast_ref::<api::ApiError>()
.is_some_and(|e| matches!(e.status.as_u16(), 404 | 409));
let delay = if conflict {
Some(backoff)
} else {
api::read_retry_delay(&error, backoff)
};
let Some(delay) = delay.filter(|delay| retries < 3 && *delay < api.timeout) else {
return Err(error);
};
retries += 1;
tokio::time::sleep(delay).await;
progress = None;
}
}
}
}
68 changes: 68 additions & 0 deletions tests/cli.rs
Original file line number Diff line number Diff line change
Expand Up @@ -884,3 +884,71 @@ fn missing_default_profile_and_profile_listing_do_not_warn() {
success(&output);
assert!(output.stderr.is_empty(), "{:?}", output.stderr);
}

#[test]
fn large_files_resume_at_acknowledged_bytes_and_return_full_sandbox_id() {
use sha2::{Digest, Sha256};
const CHUNK: usize = 8 * 1024 * 1024;
const SIZE: usize = 2 * CHUNK + 3;
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("large.bin");
let data = vec![0x7a; SIZE];
std::fs::write(&path, &data).unwrap();
let digest = hex::encode(Sha256::digest(&data));
let receipt = |offset: usize| {
Reply::json(
200,
json!({"offset":offset,"complete":offset==SIZE,"sandboxId":ID}),
)
};
let server = Server::start(vec![
Box::new(move |r| {
assert_eq!(r.method, "PUT");
assert!(r.target.starts_with("/v1/sandboxes/11111111/file-uploads/"));
assert_eq!(
r.json(),
json!({"path":"/tmp/a","size":SIZE,"sha256":digest})
);
receipt(0)
}),
Box::new(move |r| {
assert_eq!(r.body.len(), CHUNK);
assert!(r.target.ends_with("/data?offset=0&length=8388608"));
Reply::json(
502,
json!({"error":{"code":"BACKEND_ERROR","message":"response lost"}}),
)
}),
Box::new(move |r| {
assert!(!r.target.contains("/data"));
receipt(CHUNK)
}),
Box::new(move |r| {
assert!(r.target.ends_with("/data?offset=8388608&length=8388608"));
assert!(r.body.iter().all(|b| *b == 0x7a));
receipt(2 * CHUNK)
}),
Box::new(move |r| {
assert_eq!(r.body, vec![0x7a; 3]);
receipt(SIZE)
}),
]);
let result = run(
dir.path(),
&server.url,
&[
"--json",
"files",
"put",
"11111111",
path.to_str().unwrap(),
"/tmp/a",
],
);
success(&result);
assert_eq!(
serde_json::from_slice::<Value>(&result.stdout).unwrap(),
json!({"uploaded":"/tmp/a","sandboxId":ID})
);
server.finish();
}
Loading