Skip to content

imcp2-deploy: extract uploads as they arrive, bounded by the space they occupy - #252

Closed
raymondk wants to merge 1 commit into
deploy-5d-metricsfrom
deploy-5e-streaming
Closed

raymondk wants to merge 1 commit into
deploy-5d-metricsfrom
deploy-5e-streaming

Conversation

@raymondk

Copy link
Copy Markdown
Contributor

Stacked on #251. Third of four follow-ups preparing the hosted deploy tools for the gateway, whose state directory is a RAM filesystem.

Why

On a RAM filesystem everything the deploy tools write is memory. Before this change:

  • an uploaded archive was stored whole (up to 64 MiB), then read whole into the heap;
  • it could extract to as much as 1 GiB, a compile-time constant shared with the local server;
  • nothing counted what a running deploy added to its directory.

What changes

The upload is extracted as it arrives. The extractor now reads a stream (extract_bundle_from) under limits the server supplies (BundleLimits). The upload route feeds it the request body chunk by chunk, so the archive is never held whole in memory or on disk. The upload is stopped at the byte that takes either the archive or its extracted size past its limit. The local server streams bundle_path through the same code with its existing limits.

The store holds extracted bundles. A deploy takes its bundle by renaming the directory, with no second extraction. An upload now waits 5 minutes for its deploy (was 15).

Size is counted as space occupied. Each file counts in whole 4 KiB blocks plus 1 KiB per file and directory. Summing file sizes would call 250,000 one-byte files a quarter of a megabyte; on a RAM filesystem they are about a gigabyte of pages.

The deploy's own additions are bounded before they are made. The upstream library keeps a copy of each canister's module in the working directory, one per canister name. A bundle of one module and fifty canisters would have written it fifty times. Preflight now holds the bundle plus those copies to the same limit.

One budget covers a bundle from first byte to end of deploy. Arriving and deploying bundles are charged the full limit; waiting ones their actual size. A deploy with no room is refused and its upload is kept.

Configuration

Setting Env var (bundled binary) Default
max_upload_bytes MCP_DEPLOY_MAX_UPLOAD_BYTES 64 MiB
max_extracted_bytes (new) MCP_DEPLOY_MAX_EXTRACTED_BYTES 128 MiB
max_stored_bytes (was max_stored_upload_bytes) MCP_DEPLOY_MAX_STORED_BYTES (concurrent + 1) bundles = 384 MiB

The bundled binary refuses to start on contradictory values (archive cap above the extracted cap, a store smaller than one bundle).

Behaviour a client sees

  • 413 for either size limit; the body says which. A client still sending may see a closed connection instead; the tool description and the skill tell the agent to read that as "too large".
  • 422 when the upload is not a bundle. This used to surface at deploy.
  • A body idle for 30 seconds, or longer than 10 minutes in total, is given up on.
  • The upload answer reports bytes (extracted) and archive_bytes.

Metrics

New upload outcomes extracts_too_large and not_a_bundle, refusal reason no_room, and histogram imcp2_deploy_bundle_extracted_bytes. The store gauges now report extracted bytes.

Notes for review

  • crates/imcp2-deploy/src/uploads.rs is largely rewritten; reading the new file is easier than the diff.
  • A failed upload still replaces the bundle the session was holding, because replacement happens on admission. That was already the case; it matters a little more now that more uploads can fail validation.
  • Not bounded by this PR: what a deploy holds on the heap (the library reads each module into memory to build and install it), and a sync plugin's memory. The plugin allowlist is the next PR.
  • Root dev-dependencies gain tar and flate2 (both already in the tree) so the endpoint tests can upload a real bundle; Cargo.lock changes accordingly.

Testing

  • Extractor: both limits, occupancy counting, a source that fails mid-stream.
  • Store: extraction on arrival, early stop at the extracted limit without reading the rest of the body, budget charging at each stage, a refused replacement, stalled and abandoned uploads, leftovers cleared at start.
  • Pipeline: a bundle uploaded to the store and deployed from its extracted directory, offline as far as the create phase.
  • Preflight: five canisters naming one module, at and one byte under the limit.
  • Endpoint: status codes and each new metric through the router.
  • Workspace and deploy-feature tests pass; clippy clean with and without the feature; cargo publish --dry-run --workspace passes.
  • Not tested against a real HTTP client: how curl reports the early 413.

🤖 Generated with Claude Code

https://claude.ai/code/session_01XSXgo38kH12wagL3rstXfV

@raymondk
raymondk requested a review from a team as a code owner November 19, 2026 01:36
Copilot AI max review requested due to automatic review settings November 19, 2026 01:36

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🟡 Changes recommended

Unresolved storage-accounting and upload-lifecycle defects can exceed disk budgets, block runtime workers, retain abandoned uploads, and delete accepted bundles when deployment directories are on different filesystems.

5 open issues
What changed in this PR

Moves deployment uploads from stored archives to streamed extraction, reducing RAM-backed storage pressure and adding budget accounting across upload and deployment.

Changes:

  • Shares streaming extraction between hosted uploads and local bundle files.
  • Adds occupancy-based limits, shared storage reservations, upload timeouts, and five-minute retention.
  • Extends metrics, tests, configuration, and client guidance for the new upload flow.
File Description
src/​metrics/​deploy.rs Tracks extracted sizes, upload outcomes, and storage refusals.
src/​main.rs Parses and validates the revised deployment limits.
src/​deploy.rs Updates upload responses, error mapping, metrics, and router tests.
README.md Documents streaming uploads, budgets, configuration, and metrics.
deploy/​native/​README.md Updates native deployment limits and timeout guidance.
crates/​imcp2-deploy/​static/​skills/​deploy-with-mcp.md Updates upload retention and size-limit troubleshooting.
crates/​imcp2-deploy/​src/​uploads.rs Stores extracted bundles with reservations, timeouts, and lifecycle cleanup.
crates/​imcp2-deploy/​src/​observe.rs Adds the no_room deployment refusal reason.
crates/​imcp2-deploy/​src/​lib.rs Connects extracted uploads and limits to deployment tools.
crates/​imcp2-deploy/​src/​host.rs Adds streaming extraction, occupancy accounting, and module-copy preflight checks.
crates/​imcp2-deploy/​src/​deploy.rs Accepts extracted directories and streams local archive files.
Cargo.toml Adds archive-building dependencies for endpoint tests.
Cargo.lock Records the added root test dependencies.

Review effort: Max

Comment on lines +297 to +298
Bundle::Extracted { dir: from, bytes } => std::fs::rename(&from, &dir)
.map_err(|e| format!("the uploaded bundle could not be moved in: {e}"))
Comment on lines +728 to +729
directory = directory.saturating_add(occupies(module));
if directory > directory_bytes {
Comment on lines +1160 to +1162
total = total
.saturating_add(occupies(entry.size()))
.saturating_add(ENTRY_BYTES.saturating_mul(implied.len() as u64));
Comment on lines +484 to +502
let id = upload_id.clone();
// The guard goes to the thread with the body: see `Receiving`.
let extracting = tokio::task::spawn_blocking(move || {
make_private_dir(&root)
.and_then(|()| make_new_private_dir(&receiving.dir))
.map_err(|e| ReceiveError::Storage(e.to_string()))?;
let dir = Utf8PathBuf::from_path_buf(receiving.dir.clone()).map_err(|p| {
ReceiveError::Storage(format!("the upload path '{}' is not UTF-8", p.display()))
})?;
let body = Arriving { body, runtime, idle, deadline: Instant::now() + time, time };
let extracted = host::extract_bundle_from(body, &dir, &limits)?;
receiving.finish(&id, extracted.bytes);
Ok::<_, ReceiveError>((extracted.bytes, extracted.archive_bytes))
});
let outcome = extracting.await.unwrap_or_else(|e| {
Err(ReceiveError::Storage(format!("the extraction did not finish: {e}")))
});
match outcome {
Ok((bytes, archive_bytes)) => {
fn remove_upload(state: &mut State, upload_id: &str) {
if let Some(upload) = state.uploads.remove(upload_id) {
let _ = std::fs::remove_file(&upload.path);
let _ = std::fs::remove_dir_all(&upload.dir);
…eps to the bytes it occupies

A hosted server keeps what it extracts under its state directory, which may
be a RAM filesystem: a bundle is then memory. The archive used to be stored
whole (up to 64 MiB), read whole into the heap, and extracted to as much as
a gigabyte, with nothing counting what the deploy then added.

- The extractor reads a stream (`extract_bundle_from`), with the server's
  own limits (`BundleLimits`) and typed refusals. The upload route feeds it
  the request body a chunk at a time, on a thread that owns the body and
  cleans up after itself, so the archive is nowhere whole and the upload is
  stopped at the byte that takes the archive, or what it extracts to, past
  its limit. A local server streams the file the same way, with its limits.
- The store holds extracted bundles, which a deploy takes as its directory
  by a rename. An upload waits five minutes, not fifteen; a body that stalls
  for thirty seconds or takes ten minutes is given up on; what arrives and
  is not a bundle is refused on the upload (422).
- A bundle's size is what its files and directories occupy (whole 4 KiB
  blocks, 1 KiB an entry), since a quarter of a million one-byte files are a
  gigabyte of pages. `MCP_DEPLOY_MAX_EXTRACTED_BYTES` (default 128 MiB)
  holds one bundle to that — and, with it, the copy of each canister's
  module its deploy keeps beside it, checked before any is made: fifty
  canisters naming one module would have had it written fifty times.
- One budget, `MCP_DEPLOY_MAX_STORED_BYTES` (default a bundle per deploy at
  once and one more), covers every bundle from its first byte to the end of
  its deploy: arriving or deploying as the limit, waiting as what it came
  to. A deploy with no room to run in is refused and its upload kept.
- `DeployConfig` gains `max_extracted_bytes`; `max_stored_upload_bytes`
  becomes `max_stored_bytes: Option`. Metrics gain the `extracts_too_large`
  and `not_a_bundle` upload outcomes, the `no_room` refusal, and
  `imcp2_deploy_bundle_extracted_bytes`.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
Claude-Session: https://claude.ai/code/session_01XSXgo38kH12wagL3rstXfV

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Comment on lines +1077 to +1078
left: limits.stream_bytes(),
tripped: Some((meter, limits.extracted_bytes)),
Comment on lines +271 to +274
// Gone already when the deploy moved it in, which is the usual case.
let _ = std::fs::remove_dir_all(&self.dir);
let mut state = self.store.state();
state.bytes = state.bytes.saturating_sub(self.bytes);
state.bytes = state.bytes.saturating_sub(self.charged);
Comment on lines +1160 to +1162
total = total
.saturating_add(occupies(entry.size()))
.saturating_add(ENTRY_BYTES.saturating_mul(implied.len() as u64));
fn drop(&mut self) {
let _ = std::fs::remove_file(&self.path);
// Gone already when the deploy moved it in, which is the usual case.
let _ = std::fs::remove_dir_all(&self.dir);
Comment on lines +107 to +118
The server extracts the archive as it arrives, and stops the upload if
the archive, or what it extracts to, passes the limit the ticket's answer
names (`max_bytes`, `max_extracted_bytes`). It answers `413` and says
which, but `curl` is still sending and often reports only a failed
transfer: `Broken pipe`, `Connection reset`, exit code 55 or 56. Read an
upload that fails that way as a bundle that is too large, not as a
network fault to retry: check the archive's size, and what it extracts to
(`tar -tzvf <bundle.tar.gz>`), against the two limits. What a bundle
extracts to is counted as the space it occupies, so thousands of small
files weigh more than their bytes: each takes at least 5 KiB. An answer
of `422` means the server read the file and it is not a bundle; rebuild
it with `icp project bundle`. A new ticket is needed after any of these.
@raymondk

Copy link
Copy Markdown
Contributor Author

Superseded by the stack #254 → #259, which carries the same code in six PRs from main, with the deploy tools living in imcp2-core instead of a separate crate. Streaming extraction is part of #254 and #255.

@raymondk raymondk closed this Nov 19, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants