From e0ba117471b39b8397d09af3ca76c86a3d0edef8 Mon Sep 17 00:00:00 2001 From: miqui Date: Wed, 18 Nov 2026 16:06:08 -0500 Subject: [PATCH 1/3] Add a command to show sandbox CPU and memory usage `adapt sandbox usage ID [--hours 1|24]` reads GET /v1/sandboxes/{id}/usage. A terminal gets one table row: status, observed time, CPU-hours, average vCPUs, GiB-hours and average resident memory. Piped output and --json pass the API response through unchanged, keeping exact decimal-string totals. Values with no observed time show as a dash rather than zero, separately for CPU and memory, because zero coverage is not evidence of idle usage. Co-Authored-By: Claude Opus 5.5 --- docs/api-coverage.md | 4 +- docs/cli-reference.md | 14 ++++- skills/adapt/SKILL.md | 1 + src/cli.rs | 8 +++ src/commands.rs | 120 +++++++++++++++++++++++++++++++++++++ tests/cli.rs | 2 + tests/sandbox_usage/mod.rs | 44 ++++++++++++++ 7 files changed, 191 insertions(+), 2 deletions(-) create mode 100644 tests/sandbox_usage/mod.rs diff --git a/docs/api-coverage.md b/docs/api-coverage.md index beb0b72..722684b 100644 --- a/docs/api-coverage.md +++ b/docs/api-coverage.md @@ -2,7 +2,8 @@ Based on the resource OpenAPI document from `../platform` at `f20ded3`, plus its dashboard auth integrations. The `query` filter on `GET /v1/sandboxes` and the `name` and `status` -filters on `GET /v1/images` come from platform `2396647`. +filters on `GET /v1/images` come from platform `2396647`. `GET /v1/sandboxes/{id}/usage` +comes from platform `d3b6c77`. Every resource operation has a named command. `adapt api METHOD PATH` also exposes same-origin JSON requests for less common account operations. @@ -20,6 +21,7 @@ one from the CLI, or reuse the UUID supplied with `--idempotency-key`. | `POST /v1/sandboxes` | `sandbox create` | | `GET /v1/sandboxes` | `sandbox list [--query TEXT]` | | `GET /v1/sandboxes/{id}` | `sandbox get ID` | +| `GET /v1/sandboxes/{id}/usage` | `sandbox usage ID [--hours 1\|24]` | | `DELETE /v1/sandboxes/{id}` | `sandbox delete ID` | | `POST /v1/sandboxes/{id}/start` | `sandbox start ID` | | `POST /v1/sandboxes/{id}/stop` | `sandbox stop ID` | diff --git a/docs/cli-reference.md b/docs/cli-reference.md index 3e008a1..74eb084 100644 --- a/docs/cli-reference.md +++ b/docs/cli-reference.md @@ -32,7 +32,7 @@ For example, use `adapt org members ls` or `adapt sandbox ls --all`. | `org` | `list`, `use`, `current`, `create`, `update`, `delete` | | `org members` | `list`, `role`, `remove` | | `org invitations` | `list`, `create`, `cancel`, `accept`, `reject` | -| `sandbox` | `list`, `get`, `create`, `sh`, `start`, `stop`, `delete`, `wait` | +| `sandbox` | `list`, `get`, `usage`, `create`, `sh`, `start`, `stop`, `delete`, `wait` | | `exec` | Run a command in a sandbox | | `execs` | `get`, `cancel`, `logs`, `attach` | | `files` | `put`, `get` | @@ -230,6 +230,18 @@ The `--env` and `--label` options merge entries with the JSON data. The `--no-expiry` option sets `ttlSeconds` to null. The `--run-image` option runs the image's ENTRYPOINT/CMD at startup. +### Sandbox usage + +```sh +adapt sandbox usage SANDBOX_ID +adapt sandbox usage SANDBOX_ID --hours 24 +``` + +Shows measured CPU and resident memory for the last hour (default) or 24 hours. +`OBSERVED` is the measured time that the totals cover, which can be shorter than the window. +A dash means nothing was measured, not zero usage. +Use `--json` for the exact Platform totals and chart points. + ### Executions in an existing sandbox ```sh diff --git a/skills/adapt/SKILL.md b/skills/adapt/SKILL.md index a5558fb..1bfc05d 100644 --- a/skills/adapt/SKILL.md +++ b/skills/adapt/SKILL.md @@ -51,6 +51,7 @@ adapt images list --name IMAGE_NAME --status ready --all --json adapt sandbox sh --image ubuntu:24.04 -- uname -a adapt sandbox sh --image-id IMAGE_ID --cpu 2 --memory 2048 -- /bin/sh -lc 'echo hello; uname -a' adapt sandbox create --image-id IMAGE_ID --wait +adapt sandbox usage SANDBOX_ID --hours 24 --json adapt exec SANDBOX_ID --cwd /app -- /bin/sh -lc 'npm test' ``` diff --git a/src/cli.rs b/src/cli.rs index 26c11b7..61b7597 100644 --- a/src/cli.rs +++ b/src/cli.rs @@ -256,6 +256,14 @@ pub enum SandboxCommand { /// Full sandbox UUID or an unambiguous ID prefix id: ResourceRef, }, + /// Show measured CPU and resident memory over the last hour or day + Usage { + /// Full sandbox UUID or an unambiguous ID prefix + id: ResourceRef, + /// Measurement window in hours + #[arg(long, default_value = "1", value_parser = ["1", "24"])] + hours: String, + }, Create(SandboxCreate), /// Run a login shell or command in a temporary sandbox, then delete it #[command( diff --git a/src/commands.rs b/src/commands.rs index a1b62db..e32c6f0 100644 --- a/src/commands.rs +++ b/src/commands.rs @@ -164,6 +164,7 @@ pub async fn run(cli: Cli) -> Result { }, Command::Sandbox(SandboxCommand::Sh(args)) => return shell::run(&api, args, cli.json).await, Command::Sandbox(SandboxCommand::List(args)) => return list_sandboxes(&api, args, cli.json).await, + Command::Sandbox(SandboxCommand::Usage { id, hours }) => return sandbox_usage(&api, id, hours, cli.json).await, Command::Sandbox(command) => sandbox(&api, command).await?, Command::Exec(args) => return execute(&api, args, cli.json).await, Command::Execs(command) => match command { @@ -364,6 +365,77 @@ async fn sandbox(api: &Api, command: SandboxCommand) -> Result { } } SandboxCommand::Sh(_) => unreachable!("Interactive shell is dispatched separately"), + SandboxCommand::Usage { .. } => unreachable!("Sandbox usage is dispatched separately"), + } +} + +async fn sandbox_usage(api: &Api, id: input::ResourceRef, hours: String, json: bool) -> Result { + let path = format!("/v1/sandboxes/{id}/usage"); + let usage = api + .json( + Method::GET, + &path, + None, + &[("hours".into(), hours.clone())], + None, + ) + .await?; + if output::tables(json) { + let row = usage_row(&usage, &hours); + output::table(&mut io::stdout().lock(), &USAGE_COLUMNS, &[row])?; + } else { + output::print(&usage, json)?; + } + Ok(0) +} + +const USAGE_COLUMNS: [&str; 6] = [ + "status", + "observed", + "cpu", + "avg cpu", + "memory", + "avg memory", +]; + +/// Converts exact usage totals to readable units. Values without any observed +/// time are null (shown as —), because zero coverage is not evidence of idling. +fn usage_row(usage: &Value, hours: &str) -> Value { + let totals = &usage["totals"]; + let exact = |key: &str| { + totals[key] + .as_str() + .and_then(|text| text.parse::().ok()) + .unwrap_or(0.0) + }; + let (cpu, ram) = (exact("cpuNanoseconds"), exact("residentByteMilliseconds")); + let observed = totals["observedMs"].as_f64().unwrap_or(0.0); + let ram_observed = totals["memoryObservedMs"].as_f64().unwrap_or(0.0); + let gib = f64::from(1u32 << 30); + json!({ + "status": usage["status"], + "observed": format!("{} of {hours}h", duration(observed)), + "cpu": (observed > 0.0).then(|| format!("{:.2} CPU-h", cpu / 3.6e12)), + "avg cpu": (observed > 0.0).then(|| format!("{:.2} vCPU", cpu / (observed * 1e6))), + "memory": (ram_observed > 0.0).then(|| format!("{:.2} GiB-h", ram / (gib * 3.6e6))), + "avg memory": (ram_observed > 0.0).then(|| { + let bytes = ram / ram_observed; + if bytes < gib { + format!("{:.0} MiB", bytes / f64::from(1u32 << 20)) + } else { + format!("{:.1} GiB", bytes / gib) + } + }), + }) +} + +fn duration(ms: f64) -> String { + let seconds = (ms / 1000.0) as u64; + match (seconds / 3600, seconds % 3600 / 60) { + (0, 0) => format!("{seconds}s"), + (0, minutes) => format!("{minutes}m"), + (hours, 0) => format!("{hours}h"), + (hours, minutes) => format!("{hours}h {minutes}m"), } } @@ -911,3 +983,51 @@ async fn invitations(api: &Api, command: InvitationCommand) -> Result { InvitationCommand::Reject { id } => api.post("/v1/auth/organization/reject-invitation", &json!({"invitationId":id.to_string()})).await, } } + +#[cfg(test)] +mod tests { + use super::*; + + fn render(usage: Value, hours: &str) -> String { + let mut out = Vec::new(); + output::table(&mut out, &USAGE_COLUMNS, &[usage_row(&usage, hours)]).unwrap(); + String::from_utf8(out).unwrap() + } + + #[test] + fn usage_converts_exact_totals_to_readable_units() { + let usage = json!({"status":"complete","totals":{ + "cpuNanoseconds":"27007200000000", + "residentByteMilliseconds":"43138651521024000", + "observedMs":22320000, + "memoryObservedMs":22320000 + }}); + assert_eq!( + render(usage, "24"), + concat!( + "STATUS OBSERVED CPU AVG CPU MEMORY AVG MEMORY\n", + "complete 6h 12m of 24h 7.50 CPU-h 1.21 vCPU 11.16 GiB-h 1.8 GiB \n", + ) + ); + } + + #[test] + fn usage_without_observations_shows_dashes_instead_of_zero() { + let empty = json!({"status":"pending","totals":{ + "cpuNanoseconds":"0","residentByteMilliseconds":"0","observedMs":0,"memoryObservedMs":0 + }}); + assert_eq!( + render(empty, "1").lines().nth(1), + Some("pending 0s of 1h — — — — ") + ); + // CPU can be observed while memory sampling is still unavailable. + let no_memory = json!({"status":"incomplete","totals":{ + "cpuNanoseconds":"1513600000000","residentByteMilliseconds":"0", + "observedMs":3520000,"memoryObservedMs":0 + }}); + assert_eq!( + render(no_memory, "1").lines().nth(1), + Some("incomplete 58m of 1h 0.42 CPU-h 0.43 vCPU — — ") + ); + } +} diff --git a/tests/cli.rs b/tests/cli.rs index 0a3dea6..b573335 100644 --- a/tests/cli.rs +++ b/tests/cli.rs @@ -11,6 +11,7 @@ mod retries; mod sandbox_list; mod sandbox_prefixes; mod sandbox_sh; +mod sandbox_usage; #[test] fn help_and_argument_validation() { @@ -25,6 +26,7 @@ fn help_and_argument_validation() { vec!["sandbox", "create", "--image", "alpine", "--image-id", ID], vec!["exec", ID], vec!["volumes", "quota", ID], + vec!["sandbox", "usage", ID, "--hours", "6"], vec!["endpoints", "bind", ID, ID, "--port", "0"], ] { assert_eq!( diff --git a/tests/sandbox_usage/mod.rs b/tests/sandbox_usage/mod.rs new file mode 100644 index 0000000..2078cad --- /dev/null +++ b/tests/sandbox_usage/mod.rs @@ -0,0 +1,44 @@ +use crate::support::*; +use serde_json::json; + +#[test] +fn usage_sends_the_window_and_passes_json_through() { + let usage = json!({"status":"live","totals":{"cpuNanoseconds":"1513600000000"},"points":[]}); + let server = Server::start(vec![ + step( + "GET", + format!("/v1/sandboxes/{ID}/usage?hours=1"), + None, + usage.clone(), + ), + step( + "GET", + format!("/v1/sandboxes/{ID}/usage?hours=24"), + None, + usage.clone(), + ), + ]); + let dir = tempfile::tempdir().unwrap(); + for args in [ + vec!["sandbox", "usage", ID], + vec!["sandbox", "usage", ID, "--hours", "24"], + ] { + assert_eq!(success(&run(dir.path(), &server.url, &args)), usage); + } + server.finish(); +} + +#[test] +fn usage_of_an_unknown_sandbox_reports_the_api_error() { + let server = Server::start(vec![Box::new(|_| { + Reply::json( + 404, + json!({"error":{"code":"NOT_FOUND","message":"Sandbox not found."}}), + ) + })]); + let dir = tempfile::tempdir().unwrap(); + let output = run(dir.path(), &server.url, &["sandbox", "usage", ID]); + assert!(!output.status.success()); + assert!(String::from_utf8_lossy(&output.stderr).contains("404 NOT_FOUND: Sandbox not found.")); + server.finish(); +} From 977d23b704f17c7b85bc7178dd1cacc26123ad68 Mon Sep 17 00:00:00 2001 From: miqui Date: Wed, 18 Nov 2026 16:18:05 -0500 Subject: [PATCH 2/3] Show CPU and memory coverage in separate columns Memory sampling can cover less time than CPU, so a single OBSERVED column misdescribed the memory totals. The table now shows CPU OBSERVED and MEMORY OBSERVED, each from its own coverage total. A new unit test covers an hour of CPU with six minutes of memory. The integration test also passes --json explicitly for one window. Co-Authored-By: Claude Opus 5.5 --- docs/cli-reference.md | 4 +++- src/commands.rs | 35 ++++++++++++++++++++++++++++------- tests/sandbox_usage/mod.rs | 9 +++++++-- 3 files changed, 38 insertions(+), 10 deletions(-) diff --git a/docs/cli-reference.md b/docs/cli-reference.md index 74eb084..3db3aba 100644 --- a/docs/cli-reference.md +++ b/docs/cli-reference.md @@ -238,7 +238,9 @@ adapt sandbox usage SANDBOX_ID --hours 24 ``` Shows measured CPU and resident memory for the last hour (default) or 24 hours. -`OBSERVED` is the measured time that the totals cover, which can be shorter than the window. +`CPU OBSERVED` and `MEMORY OBSERVED` show the measured time covered by their respective totals. +Each can be shorter than the requested window, and memory coverage can differ from CPU coverage. +For example, one hour of CPU data and six minutes of memory data show `1h of 1h` and `6m of 1h`, respectively. A dash means nothing was measured, not zero usage. Use `--json` for the exact Platform totals and chart points. diff --git a/src/commands.rs b/src/commands.rs index e32c6f0..a5d85d7 100644 --- a/src/commands.rs +++ b/src/commands.rs @@ -389,11 +389,12 @@ async fn sandbox_usage(api: &Api, id: input::ResourceRef, hours: String, json: b Ok(0) } -const USAGE_COLUMNS: [&str; 6] = [ +const USAGE_COLUMNS: [&str; 7] = [ "status", - "observed", + "cpu observed", "cpu", "avg cpu", + "memory observed", "memory", "avg memory", ]; @@ -414,9 +415,10 @@ fn usage_row(usage: &Value, hours: &str) -> Value { let gib = f64::from(1u32 << 30); json!({ "status": usage["status"], - "observed": format!("{} of {hours}h", duration(observed)), + "cpu observed": format!("{} of {hours}h", duration(observed)), "cpu": (observed > 0.0).then(|| format!("{:.2} CPU-h", cpu / 3.6e12)), "avg cpu": (observed > 0.0).then(|| format!("{:.2} vCPU", cpu / (observed * 1e6))), + "memory observed": format!("{} of {hours}h", duration(ram_observed)), "memory": (ram_observed > 0.0).then(|| format!("{:.2} GiB-h", ram / (gib * 3.6e6))), "avg memory": (ram_observed > 0.0).then(|| { let bytes = ram / ram_observed; @@ -1005,8 +1007,25 @@ mod tests { assert_eq!( render(usage, "24"), concat!( - "STATUS OBSERVED CPU AVG CPU MEMORY AVG MEMORY\n", - "complete 6h 12m of 24h 7.50 CPU-h 1.21 vCPU 11.16 GiB-h 1.8 GiB \n", + "STATUS CPU OBSERVED CPU AVG CPU MEMORY OBSERVED MEMORY AVG MEMORY\n", + "complete 6h 12m of 24h 7.50 CPU-h 1.21 vCPU 6h 12m of 24h 11.16 GiB-h 1.8 GiB \n", + ) + ); + } + + #[test] + fn usage_shows_memory_coverage_separately_from_cpu() { + let usage = json!({"status":"complete","totals":{ + "cpuNanoseconds":"3600000000000", + "residentByteMilliseconds":"386547056640000", + "observedMs":3600000, + "memoryObservedMs":360000 + }}); + assert_eq!( + render(usage, "1"), + concat!( + "STATUS CPU OBSERVED CPU AVG CPU MEMORY OBSERVED MEMORY AVG MEMORY\n", + "complete 1h of 1h 1.00 CPU-h 1.00 vCPU 6m of 1h 0.10 GiB-h 1.0 GiB \n", ) ); } @@ -1018,7 +1037,7 @@ mod tests { }}); assert_eq!( render(empty, "1").lines().nth(1), - Some("pending 0s of 1h — — — — ") + Some("pending 0s of 1h — — 0s of 1h — — ") ); // CPU can be observed while memory sampling is still unavailable. let no_memory = json!({"status":"incomplete","totals":{ @@ -1027,7 +1046,9 @@ mod tests { }}); assert_eq!( render(no_memory, "1").lines().nth(1), - Some("incomplete 58m of 1h 0.42 CPU-h 0.43 vCPU — — ") + Some( + "incomplete 58m of 1h 0.42 CPU-h 0.43 vCPU 0s of 1h — — " + ) ); } } diff --git a/tests/sandbox_usage/mod.rs b/tests/sandbox_usage/mod.rs index 2078cad..9af2bbb 100644 --- a/tests/sandbox_usage/mod.rs +++ b/tests/sandbox_usage/mod.rs @@ -3,7 +3,12 @@ use serde_json::json; #[test] fn usage_sends_the_window_and_passes_json_through() { - let usage = json!({"status":"live","totals":{"cpuNanoseconds":"1513600000000"},"points":[]}); + let usage = json!({"status":"live","totals":{ + "cpuNanoseconds":"1513600000000", + "residentByteMilliseconds":"386547056640000", + "observedMs":3600000, + "memoryObservedMs":360000 + },"points":[]}); let server = Server::start(vec![ step( "GET", @@ -21,7 +26,7 @@ fn usage_sends_the_window_and_passes_json_through() { let dir = tempfile::tempdir().unwrap(); for args in [ vec!["sandbox", "usage", ID], - vec!["sandbox", "usage", ID, "--hours", "24"], + vec!["sandbox", "usage", ID, "--hours", "24", "--json"], ] { assert_eq!(success(&run(dir.path(), &server.url, &args)), usage); } From a190c22f8a00510849f4f59785f57e288fab9fe0 Mon Sep 17 00:00:00 2001 From: miqui Date: Wed, 18 Nov 2026 16:29:56 -0500 Subject: [PATCH 3/3] Flag allocation estimates under the usage table Platform counts migrated allocation estimates (basis "allocated") in usage totals and reports them only through estimatedIntervals. Without a mark, reserved capacity read as measured utilization. When estimatedIntervals is above zero, the terminal view now adds a note under the table with the count. JSON output already includes the field and is unchanged. Co-Authored-By: Claude Opus 5.5 --- docs/cli-reference.md | 1 + src/commands.rs | 39 ++++++++++++++++++++++++++++++++++++--- 2 files changed, 37 insertions(+), 3 deletions(-) diff --git a/docs/cli-reference.md b/docs/cli-reference.md index 3db3aba..13c946a 100644 --- a/docs/cli-reference.md +++ b/docs/cli-reference.md @@ -242,6 +242,7 @@ Shows measured CPU and resident memory for the last hour (default) or 24 hours. Each can be shorter than the requested window, and memory coverage can differ from CPU coverage. For example, one hour of CPU data and six minutes of memory data show `1h of 1h` and `6m of 1h`, respectively. A dash means nothing was measured, not zero usage. +A note under the table counts intervals that Platform estimated from allocated resources instead of measuring. Use `--json` for the exact Platform totals and chart points. ### Executions in an existing sandbox diff --git a/src/commands.rs b/src/commands.rs index a5d85d7..4b3f66b 100644 --- a/src/commands.rs +++ b/src/commands.rs @@ -381,8 +381,7 @@ async fn sandbox_usage(api: &Api, id: input::ResourceRef, hours: String, json: b ) .await?; if output::tables(json) { - let row = usage_row(&usage, &hours); - output::table(&mut io::stdout().lock(), &USAGE_COLUMNS, &[row])?; + write_usage(&mut io::stdout().lock(), &usage, &hours)?; } else { output::print(&usage, json)?; } @@ -399,6 +398,22 @@ const USAGE_COLUMNS: [&str; 7] = [ "avg memory", ]; +/// Writes one table row, then a note when the totals include migrated allocation +/// estimates, which would otherwise look the same as measurements. +fn write_usage(out: &mut impl Write, usage: &Value, hours: &str) -> io::Result<()> { + output::table(out, &USAGE_COLUMNS, &[usage_row(usage, hours)])?; + match usage["totals"]["estimatedIntervals"].as_u64() { + None | Some(0) => Ok(()), + Some(n) => { + let plural = if n == 1 { "" } else { "s" }; + writeln!( + out, + "\nIncludes {n} interval{plural} estimated from allocated resources, not measured." + ) + } + } +} + /// Converts exact usage totals to readable units. Values without any observed /// time are null (shown as —), because zero coverage is not evidence of idling. fn usage_row(usage: &Value, hours: &str) -> Value { @@ -992,7 +1007,7 @@ mod tests { fn render(usage: Value, hours: &str) -> String { let mut out = Vec::new(); - output::table(&mut out, &USAGE_COLUMNS, &[usage_row(&usage, hours)]).unwrap(); + write_usage(&mut out, &usage, hours).unwrap(); String::from_utf8(out).unwrap() } @@ -1013,6 +1028,24 @@ mod tests { ); } + #[test] + fn usage_flags_allocation_estimates_under_the_table() { + let usage = |estimated: u64| { + json!({"status":"complete","totals":{ + "cpuNanoseconds":"3600000000000","residentByteMilliseconds":"0", + "observedMs":3600000,"memoryObservedMs":0,"estimatedIntervals":estimated + }}) + }; + let note = "\nIncludes 3 intervals estimated from allocated resources, not measured.\n"; + assert!(render(usage(3), "24").ends_with(note)); + assert!( + render(usage(1), "24").ends_with( + "Includes 1 interval estimated from allocated resources, not measured.\n" + ) + ); + assert_eq!(render(usage(0), "24").lines().count(), 2); + } + #[test] fn usage_shows_memory_coverage_separately_from_cpu() { let usage = json!({"status":"complete","totals":{