Skip to content

Lease files on a worker: upload, download, list and delete a lease's files #1356

Closed

Description

@V3RON

Part of #1351.

Scope

A lease holder on a standalone worker (or an operator) can upload a file to its lease's folder with PUT /v1/leases/{id}/files/{name}, download it whole or by one byte range, list the folder and delete a file. The limits, names and refusal codes are the feature's Shared values. The folder is deleted when the lease ends, and startup deletes the folders of leases that are no longer live. On a gateway these routes answer 501 UNSUPPORTED_IN_GATEWAY_MODE until #1358.

In short

A holder sends raw bytes to its lease and gets them back, on one worker. Nothing is held in memory: the body streams to a temporary file in the lease folder, which is renamed into place once the whole body has arrived. New terms: the lease folder, <data dir>/lease-files/<folder key>/, and its folder key, the lease id's bytes in lowercase hex, -, the grant time in ms: lease ci granted at 1762419161000 → ~/.simlock/lease-files/6369-1762419161000/fixture.tar. File names match ignoring case: A.tar and a.tar are one file. An upload has no total time limit; one whose body brings no byte for 330 s ends 408 UPLOAD_STALLED No bytes of <name> arrived for 330 s.

flowchart LR
  C[HTTP caller] -->|PUT / GET / list / DELETE| H[worker HTTP app]
  H -->|lease.get: owner or operator| D[dispatcher]
  H -->|"changed: files routes"| F["lease files (new)"]
  F --> FS[(lease folder)]
  L[lease end] -->|"participant (new)"| F
  S[startup] -->|"sweep (new)"| F
Loading

Before and after, on a worker at $W:

$ curl -X PUT "$W/v1/leases/$LEASE/files/fixture.tar" -H "Authorization: Bearer $T" --data-binary @fixture.tar
404 Not Found                                                 (before: no route)
{"name":"fixture.tar","size":70000000}                        (after: 201)

$ curl "$W/v1/leases/$LEASE/files/fixture.tar" -H "Range: bytes=0-99" -H "Authorization: Bearer $T" -o head.bin
(after: 206, Content-Range: bytes 0-99/70000000, 100 bytes)

$ curl -X PUT "$W/v1/leases/$LEASE/files/big.bin" -H "Authorization: Bearer $T" -H "Content-Length: 3000000000" ...
{"error":{"code":"FILE_TOO_LARGE","message":"File big.bin is over the 2 GiB limit for one file","name":"big.bin"}}   (after: 413)

Quantities: 2 GiB per file, counted on the worker as bytes received in one PUT; 4 GiB per lease folder, counted over every stored file plus the bytes other running PUTs of the same lease have received, the file being replaced not counted; the disk check reads free bytes on the folder's disk once, when the PUT starts; the silence bound is 330 s with no byte of the body received, counted from the request's start or the last byte. Messages, word for word, are the feature's Shared values rows FILE_TOO_LARGE, LEASE_FILES_FULL, UNKNOWN_FILE, FILE_BUSY, UPLOAD_STALLED, INSUFFICIENT_DISK_SPACE and File name.

A user would notice if this goes wrong: an upload that answers 201 but a GET returns other bytes, or a lease's files still on disk after its release.

Technical spec

Facts

Commit 5aedc2d.

# Fact Source
F1 A module's lease route is one exact path, /v1/leases/:id/<name>, resolved with lease.get (owner or operator; else 404 UNKNOWN_LEASE) before its handler runs src/http/app.ts:832-848, :873-880
F2 HttpGatewayDeps takes mounts and leaseRoutes; no file dependency exists src/http/app.ts:108-121
F3 declareRoute has no raw or binary request body: its inputs are params, query and JSON src/http/routes.ts (no octet, binary or raw body; searched octet|binary|rawBody)
F4 Module names exec, renew, rotate are refused as core lease sub-routes, with Optional module "<name>": the name is reserved for a core route src/modules/host.ts:113-114, :131-133
F5 A test already pins that refusal for renew, exec, rotate src/daemon/optional-modules.test.ts:283-284
F6 The Filesystem port has rename, rm, mkdirp, readdir, stat, diskFree, but no streaming read or write src/ports/filesystem.ts:76-98; grep for createReadStream|createWriteStream in src/ finds none
F7 The worker's data directory is <root>, a gateway's <root>/gateway src/ports/paths.ts:107-109
F8 A lease id is ^[A-Za-z0-9][A-Za-z0-9_-]{0,63}$, case-sensitive, and free again once its lease ends src/contract/operations.ts:127-132; src/leasing/lease-request-book.ts:325-329
F9 diskPressure.freeBytesThreshold defaults to 10 GiB src/core/config.ts:996
F10 INSUFFICIENT_DISK_SPACE carries {platform, requiredBytes, availableBytes} and answers 422 src/contract/errors.ts:68-72, :340-345
F11 Lease-end participants get {leaseId, ownerId, deviceId, platform, reason} with reason explicit, killed, expired or device-lost; the worker passes [leaseInputs.leaseEnd, ...moduleHost.leaseEndParticipants] src/leasing/lease-ports.ts:32-42; src/daemon/worker-composition.ts:336
F12 Under maintenance (nuke) a participant gets an aborted signal and nothing waits for it src/leasing/lease-release-coordinator.ts:330-332
F13 Startup runs sweepWriteLeftovers, then leasing.reconcile(read), then core.converge(read), stopping early on stopping src/daemon/worker-composition.ts:404-445
F14 A JSON answer under /v1 gets Cache-Control: no-store; streams are skipped src/http/AGENTS.md (How a request runs, step 2) and the middleware in src/http/app.ts
F15 The HTTP test harness builds the app over a FakeDispatcher and takes mounts as an override src/http/test-app.ts:15-30
F16 CORE_ROUTE_SEGMENTS holds the first segment of each core route; leases is in it, so files under it needs no new segment src/contract/protocol.ts:82-97
F17 The relay target name pattern is ^[a-z][a-z0-9-]{0,31}$; files passes src/contract/status-schemas.ts:316
F18 A worker's disk on this Mac is case-insensitive: touch $d/Ab; ls $d/aB lists the file command on this machine
F19 A lease record carries grantedAt (ms) src/core/domain.ts:398-409
F20 The HTTP listener calls serve({fetch, hostname, port}) with no server options, so Node's default requestTimeout of 300 s cuts any longer request src/http/server.ts:174-186; node -e 'require("http").createServer().requestTimeout' prints 300000
F21 /v1/leases/L/files/.. is normalized to /v1/leases/L/ before routing node -e 'new URL("/v1/leases/L/files/..","http://x").pathname' prints /v1/leases/L/
F22 The app's ETag step buffers any application/json answer under /v1 and sets no-store only on those src/http/app.ts:251-263
F23 Leasing builds each EndedLease from the released lease and device, where the lease record carries grantedAt src/leasing/lease-release-coordinator.ts:399-404; src/core/domain.ts:398-409
F24 A Linux ext4 disk is case-sensitive, and CI's fast lane runs on ubuntu-24.04 docs/internal/agent-rules/toolchain.md (CI's fast lane)

Modules touched

Searches: EndedLease (leasing and its participants), leaseRoutes, HttpGatewayDeps, CORE_LEASE_SUBROUTES, leaseEndParticipants, sweepWriteLeftovers, ErrorDetailsMap, ERROR_TABLE, Filesystem (interface and MemoryFilesystem), declareRoute, LEASE_ROUTES.

  • src/lease-files/ (new): index.ts → createLeaseFiles; the store (folder, names, limits, temp-then-rename writes, one writer per name, in-flight byte counts), its HTTP handler, the lease-end participant, the startup sweep; AGENTS.md.
  • src/ports/filesystem.ts: a streaming write to a path and a streaming read of a byte range, in the adapter and MemoryFilesystem.
  • src/contract/errors.ts: FILE_TOO_LARGE, LEASE_FILES_FULL, UNKNOWN_FILE, FILE_BUSY, UPLOAD_STALLED; protocol.ts bump.
  • src/http/: routes.ts (a raw body in a declaration), lease-declarations.ts (four routes), app.ts (leaseFiles dependency; 501 when absent), server.ts (requestTimeout: 0), openapi.ts if the raw body needs it.
  • src/modules/host.ts: files joins CORE_LEASE_SUBROUTES.
  • src/leasing/lease-ports.ts, src/leasing/lease-release-coordinator.ts: EndedLease gains grantedAt, filled from the ended lease (released.lease, src/leasing/lease-release-coordinator.ts:399-401); every existing participant ignores it.
  • src/daemon/worker-composition.ts: build createLeaseFiles (with the registry's lease lookup), pass its participant and handler, run its sweep after leasing.reconcile with the live grants.
  • src/daemon/main.ts: the gateway's app gets no leaseFiles (501 until Lease files through a gateway #1358).
  • .dependency-cruiser.mjs, docs/internal/ARCHITECTURE.md: the new component.
  • Docs: website/src/content/docs/docs/using-devices/remote-agents.mdx, website/src/content/docs/docs/reference/errors.mdx.
flowchart LR
  WC["daemon/worker-composition (changed)"] --> LF["lease-files (new)"]
  WC --> HTTP["http app (changed)"]
  HTTP --> LF
  LF --> FS["ports/filesystem (changed)"]
  LF --> C["contract errors (changed)"]
  WC --> LEAS[leasing participants]
  MH["modules/host (changed)"]
Loading
sequenceDiagram
  participant C as Caller
  participant H as Worker HTTP
  participant F as lease-files
  C->>H: PUT /v1/leases/L1/files/fixture.tar
  H->>H: lease.get L1 (404 UNKNOWN_LEASE if not owner/operator)
  H->>F: put(L1, name, body, contentLength)
  F-->>C: 400 / 409 / 413 / 422 before reading, if refused
  F->>F: stream body to .upload-<id>, count bytes
  alt body passes a limit or is cut
    F->>F: remove .upload-<id>, keep previous file
    F-->>C: 413 (cut: no answer)
  else complete
    F->>F: rename to fixture.tar
    F-->>C: 201 {name, size}
  end
Loading

Surface and extension points

src/lease-files/index.ts (F23 for grantedAt) exports createLeaseFiles({ filesystem, dataDirectory, diskPressureThreshold, clock, logger, idGenerator, findGrant, limits? }) returning a LeaseFiles handle. findGrant(leaseId) answers the live grant {id, grantedAt, platform} from the worker's registry (the platform from the lease's device), or none. limits ({fileBytes, leaseBytes, silenceMs}) is for tests only and defaults to 2 GiB, 4 GiB and 330 s; nothing in config sets it.

  • handle(request, identity, lease, name | undefined): the HTTP routes' handler, with lease = {id, deviceId, workerId?, workerLeaseId?} as the app resolved it (the feature's Shared values row File routes' handler). On a worker it serves lease.id through findGrant; Lease files through a gateway #1358 gives a gateway its own handler of the same type.
  • folderOf(grant): makes the folder when missing and answers its path; an ended grant → UNKNOWN_LEASE. Every folderOf, PUT and rename of a grant is registered as in flight before its ended-check; the lease-end participant marks the grant ended, aborts its PUTs, waits for the grant's in-flight operations to settle, and only then removes the folder, so a mkdir or rename that was already running cannot recreate it afterwards.
  • openFile(grant, name): the lookup of the File name rule (exact spelling, else ignoring case, first in byte order), opened before it returns: {name, size, read(): ReadableStream<Uint8Array>} over the open file; none → UNKNOWN_FILE.
  • leaseEnd: a LeaseEndParticipant that names the grant by EndedLease.leaseId and grantedAt.
  • sweep(liveGrants: {id, grantedAt}[]).

#1357 calls findGrant, folderOf and openFile; #1358 serves handle as the relay target. No second implementation; no registry.

Contract and event changes

This PR bumps the protocol by one: five error codes, each with declared details, added to ErrorDetailsMap, ERROR_TABLE and CODES_WITH_DECLARED_DETAILS as the feature's Shared values give them. No operation changes. No event (feature Non-goals); no EVENTS.md entry.

New wire fields:

  • Path name: string, URL-decoded, the File name rule of the feature's Shared values; anything else 400 BAD_REQUEST.
  • Content-Length (optional): a non-negative integer; over 2,147,483,648 → 413 FILE_TOO_LARGE before any byte is read.
  • Downloads answer Content-Type: application/octet-stream, Cache-Control: no-store, Accept-Ranges: bytes, Content-Length and simlock-content-length, both the bytes of this body (the range's on a 206) (F22: a JSON type would be buffered whole).
  • Range (GET only): one bytes=a-b, bytes=a- or bytes=-n range. b at or past the size reads to the end; n over the size reads the whole file as a 206; any range on a 0-byte file → 416; a start at or past the size, or bytes=-0, → 416 with Content-Range: bytes */<size>; b < a, several ranges, another unit or a malformed value are ignored (200 whole).
  • The lease total walks the folder's entries (subfolders walked, symlinks not followed) and skips the .upload-* temp files, whose bytes are counted once, as running PUTs' bytes.

Other code on the same state

Searches: lease-files and dataDirectory across src/ (0 hits for lease-files; dataDirectory 14 hits in daemon/, all for state.db, instance.json, logs and the socket); sweepWriteLeftovers (1 call, F13); leaseEndParticipants (1 list, F11).

Component State When both act Which wins
sweepWriteLeftovers removes .tmp files and .staging folders under the data directory it runs before this task's sweep; .upload-* names do not end in .tmp each removes only its own names
Lease-end participants (input, stream, tunnel, agent-device) their own sockets and sessions all run after the lease's end commit, in parallel independent; none touches the folder
A running PUT of the same lease when the lease ends its .upload-* file the participant aborts every running PUT of the lease, then removes the folder; the PUT answers 404 UNKNOWN_LEASE the lease end
Two PUTs to one name (any case) the name's writer slot, keyed by the lowercased name the second gets 409 FILE_BUSY at once the first
A new lease with an ended lease's id its own folder (another grantedAt) the old folder's removal never touches the new one each grant its own
A write for a grant the participant marked ended the folder refused 404 UNKNOWN_LEASE; one already in flight finishes before the participant's remove, which then deletes what it wrote; a PUT caught in its rename answers 404 UNKNOWN_LEASE the lease end
DELETE while a PUT to the name runs the stored file DELETE removes the stored file (404 if none); the PUT then stores its own the later finish
GET while a PUT replaces the name the stored file the GET reads the file it opened; the rename never changes an open file the opened file
#1357 exec reads the folder as working folder and stdinFile — —

Failure modes

Call Outcome What happens Limit, counted from
lease.get ok the route goes on the dispatcher's own
lease.get error 404 UNKNOWN_LEASE, nothing read or written —
Filesystem.diskFree below threshold 422 INSUFFICIENT_DISK_SPACE, nothing written read once at PUT start
Filesystem.diskFree throws 500 INTERNAL, logged, nothing written —
streaming write ok renamed into place, 201 none: the caller's body sets the pace
streaming write throws (disk full, I/O) temp removed, previous file kept, 500 INTERNAL, logged —
request body cut by the caller temp removed, previous file kept, no answer —
request body no byte for 330 s reading stops, temp removed, previous file kept, 408 UPLOAD_STALLED the store's clock, from the start or the last byte read
Node's listener a request past 300 s in total not cut: requestTimeout is 0 (F20); headers still bounded by Node's headersTimeout —
request body passes 2 GiB or the lease total reading stops, temp removed, 413 counted per byte received
streaming read throws mid-body the response body errors; nothing changes on disk —
rm of the folder at lease end throws warn logged; the startup sweep removes it later not bounded by the participant's signal (F12): a local remove
sweep at startup rm throws warn logged; startup goes on —

State written: the lease folder and its files. A restart in the middle of a PUT leaves a .upload-* file; the startup sweep removes every .upload-* file in live folders and every folder of a lease no longer live. Two PUTs to one name: the second 409; to two names: both run, each counted against the other in the lease total.

Rules in play

  • Architecture rule 18 (factory and handle): createLeaseFiles returns LeaseFiles.
  • Ports rule "Application code never imports fs" (src/ports/AGENTS.md): every read and write goes through Filesystem.
  • ADR 0024, "participants … before reclaim": the folder is removed by a participant.
  • ADR 0067 §1–4: folder per grant, routes, names ignoring case, limits; §6: no total limit, the silence bound; §7: files reserved as a module name.
  • Documentation rule 9: the routes and codes are public surface; remote-agents.mdx and errors.mdx change in this PR.
  • Contract manual, "Every change to a contract shape bumps it by one".

Tests

Seam: the worker's HTTP app (buildHarness in src/http/test-app.ts, given createLeaseFiles over a temporary folder, NodeFilesystem, the harness's FakeClock and lowered limits where a case says so), modelled on src/http/app-leases.test.ts; the same harness without leaseFiles for the gateway's 501; the lease end and the sweep through the whole worker (src/daemon/test-main.ts), modelled on src/daemon/main.test.ts; the module name in src/daemon/optional-modules.test.ts; the listener in src/http/server.test.ts, on the HttpGateway it starts.

  • A lease holder PUTs a file and gets 201 with its name and size; a GET returns the same bytes. Cases: new name; same name again replaces it; empty body (size 0); 3 MiB body; 70 MB body.
  • A lease holder PUTs a bad file name and gets 400 BAD_REQUEST with the name rule. Cases: each row of the feature's names table.
  • A lease holder PUTs past a limit and gets the limit's code, with nothing stored and the previous file kept. Cases: Content-Length over 2 GiB (refused before any byte); no Content-Length, body past 2 GiB (store built with the limit lowered for the test); folder plus upload past 4 GiB, a command-written file counted; two running PUTs that pass it only together; replacing a file is not counted twice; disk free below threshold.
  • A lease holder whose PUT is cut or goes silent keeps the previous file or none; a second PUT to a name being uploaded gets 409 FILE_BUSY. Cases: cut with no previous file; cut with a previous file; silent for 330 s → 408 UPLOAD_STALLED; still moving past 330 s total succeeds; two PUTs at once, A.tar and a.tar included.
  • A lease holder's file names match ignoring case. Cases: PUT A.tar then GET a.tar; PUT a.tar replaces A.tar and the list shows a.tar; DELETE A.TAR; a command left A.tar and a.tar (case-sensitive disk): GET a.tar exact, GET A.TAR the first in byte order, both listed, then DELETE a.tar removes both spellings (decided in delivery, pending the maintainer) (on a case-insensitive disk the case is skipped, as the test finds the disk).
  • A lease holder GETs a file and gets it whole or the range it asked for. Cases: no Range; bytes=0-99; bytes=900-; bytes=-100; bytes=1000- 416; bytes=-5 on a 0-byte file 416; two ranges; unknown name 404 UNKNOWN_FILE.
  • A lease holder lists the lease's files and deletes one. Cases: empty folder []; two files sorted; a subfolder and a my file.png a command wrote are not listed; DELETE 204 then gone from the list; DELETE unknown 404 UNKNOWN_FILE.
  • A caller that does not hold the lease gets 404 UNKNOWN_LEASE on every file route, and an operator is served. Cases: another agent; unknown lease; operator token.
  • A lease's files are gone once it ends, a new lease with the same id starts empty, and startup removes the folders of leases that are no longer live. Cases: released; expired; killed; device lost; a PUT running when the lease ends answers 404 UNKNOWN_LEASE and leaves nothing; a folderOf whose mkdir is still running when the lease ends leaves no folder; lease ids CI and ci live at once; the same id leased again; startup with one live and one gone lease and an upload temp file.
  • A module named files is refused when the module host loads. Cases: files; stream still loads. (Extends the test at src/daemon/optional-modules.test.ts:283.)
  • On a gateway, before the gateway relays them, the file routes answer 501 UNSUPPORTED_IN_GATEWAY_MODE. Cases: each route.
  • The HTTP listener of a worker and of a gateway has no total request time limit. Cases: worker; gateway (the server handed to HttpGateway's existing onServerCreated hook, src/http/server.ts:49, has requestTimeout 0).

Done when

  • pnpm exec vitest run --project unit src/http/app-leases.test.ts, … src/daemon/main.test.ts, … src/daemon/optional-modules.test.ts and … src/http/server.test.ts pass with the Tests lines above.
  • pnpm --dir website install && pnpm --dir website build && node website/scripts/check-openapi.mjs passes, and the built HTTP API page lists PUT, GET and DELETE on /v1/leases/{id}/files/{name} and GET on /v1/leases/{id}/files.
  • remote-agents.mdx has a section on lease files with the curl session of In short, and errors.mdx lists the five new codes.
  • CI's checks pass on the PR, the protocol-bump check included.

Out of scope

Depends on

Written by an agent.

Activity

  1. added
    task:draft
    on Nov 6, 2026
  2. added
    task:ready
    and removed
    task:draft
    on Nov 6, 2026
  3. self-assigned this
    on Nov 6, 2026
  4. 4 remaining items

  5. added a commit that references this issue on Nov 6, 2026
    a8461df
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

task:ready

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions