Skip to content

About

No description, website, or topics provided.

Resources

Security policy

Stars

0 stars

Watchers

0 watching

Forks

Latest commit

 

History

212 Commits

Folders and files

Repository files navigation

cloudlease

Leases and cleanup for short-lived cloud machines that a Cloudflare Worker creates. A Durable Object holds each lease, deletes what it created once the lease ends, and keeps retrying until the provider confirms the resources are gone. A scheduled sweep deletes any tagged resource that no live lease claims. That includes resources whose owner object never existed, such as leftovers from a crashed create.

Crates

Crate What it holds Runtime
cloudlease-core Lease, holding, tag, capacity and sweep rules. No I/O, no clock any
cloudlease-provider The CloudProvider trait, the reaper, the owner's save, create and alarm rules over any OwnerStore, the sweep over any owners and gate, the DigitalOcean, phoenixNAP, Latitude.sh, AWS and Vast.ai adapters, and the IngressPolicy firewall extension any, given an HTTP transport
cloudlease-worker workers-rs glue: the owner store and alarm over Durable Object storage, the capacity gate, the sweep's calls to owner and gate objects, and building the DigitalOcean, phoenixNAP, Latitude.sh, AWS and Vast.ai adapters from bindings Cloudflare Workers (worker =0.8.5)
cloudlease-queue The leased-work queue: units, leases, progress, artifacts, capability handshakes, worker profiles, managed pools with optional spend caps, the external adapter contract, and the Vast.ai profile-to-VastInstanceSpec conversion. Work protocols v2 and v3 match CloudDeck's byte for byte any, including wasm32-unknown-unknown
cloudlease-client Async HTTP client for workers and operators over the work protocols, including managed bootstrap native
cloudlease-worker-runtime A reusable worker loop: claim, renew, heartbeat, artifacts, observations and log push. See its README native
cloudlease-cli The cloudlease binary: the operator commands for queues, workers, units, pools, profiles and provider cleanup, and the operations commands for staging and pulling runs, scratch disks on AWS machines and the guarded machines Worker deploy. See its README native Linux and macOS
cloudlease-smoke cloudlease-smoke, which drives a live queue deployment over real HTTP native
cloudlease-sim Deterministic simulation of the machines run objects, the sweep and the capacity gate over the real provider adapters and faulty fake provider APIs; tests only any

infra/ holds the AWS side as Terraform: aws-machines (the machines Worker's network, launch template and IAM user), aws-operator (permissions boundaries and the operator's IAM grants) and aws-staging (a private S3 bucket and a signed CloudFront distribution that machines stage outputs through). The cloudlease CLI drives the operational side of it: minting a run's credentials, staging, pulling and mounting scratch.

The app declares its own Durable Object classes and wraps the handlers in cloudlease-worker, so it keeps its own class names, bindings and settings. tests/worker is a minimal example.

Apps

The workspace deploys two Workers that share no secrets, plus a dashboard and a Modal adapter:

App Trust What it is
apps/machines (cloudlease-machines, rules in crates/cloudlease-machines) trusted Temporary DigitalOcean, phoenixNAP, Latitude.sh and AWS Spot machines for client apps such as homebased: runs, leases renewed by the machine, a provider per machine class, spend caps, an operator spend report across runs (GET /v1/spend) and ntfy alerts. See its README
apps/queue (cloudlease-queue, rules in crates/cloudlease-queue) untrusted CloudDeck's leased-work queues and the managed Vast.ai and Modal worker pools that drain them, with an hourly spend gate, per-pool spend caps, a 5-minute Vast.ai label sweep and ntfy alerts. See its README
apps/queue-dashboard operator The SvelteKit queue dashboard, behind Cloudflare Access, which reads apps/queue with the operator token. See its README
providers/modal untrusted The command-only Modal adapter apps/queue calls with four operations: ensure, inspect, terminate and prove absence. See its README

The trusted Worker holds the keys of providers whose machines run with secrets in their boot data. The queue Worker rents only hosts that must be treated as hostile, so it holds none of those keys: a leaked worker credential or a malicious Vast.ai host reaches at most the queue Worker's own state. SECURITY.md has the rules for what an untrusted worker may receive.

Lifetime rules

  • A lease has a heartbeat deadline and a hard deadline. Clients extend it with heartbeat (sequenced) or renew (unsequenced), and neither can pass the hard deadline. The first heartbeat may be given a boot grace, and the hard deadline can be capped (not_after) by a run deadline.
  • A holding is one owner generation's resources. It moves from leased to releasing to released. It leaves releasing only after the provider reports every resource absent, deleting in rank order (a Latitude.sh server before the user data record it boots from). A resource whose create response was lost is found by its tags. An empty tag search counts as absence only when it was sent two minutes or more after the lease ended, so a create still in flight is not missed.
  • Leases end when released, when a heartbeat is missed, at the hard deadline, or when the owner revokes them.
  • The sweep lists every resource carrying the managed tag and asks each owner object which ones a live lease of the same generation claims. Anything not claimed is deleted. An owner object with no record of the resource claims nothing. An owner whose call fails or times out is not counted as claiming nothing, so it keeps its resources until the next sweep. A resource past its until ceiling tag is deleted before any owner is asked, so a stalled owner never delays a hard deadline; SweepConfig::owner_timeout bounds each owner call.
  • Each owner also says which of the asked generations it ended itself: still releasing, or released after the sweep listed the inventory. A sweep delete of such a generation is the owner's own cleanup racing the sweep; every other delete, including a resource still listed after its owner confirmed it gone, is reported with ownerEnded: false, which apps use to alert on orphans.
  • Capacity permits count against a global limit until the owner proves its resources absent. A permit takes one unit by default; a gate that caps spend weighs each permit by its price, such as cents per hour. A suspect permit is released only by a sweep whose inventory was complete.

Tags

With prefix cl, a managed droplet carries exactly:

cl-managed  cl-owner-<owner>  cl-gen-<n>  cl-kind-droplet  [cl-until-<unix secs>]

Providers whose tags are keys and values carry the same set as pairs. With prefix cl, an AWS Spot instance, its root volume and the instant fleet that launched it carry exactly:

cl-managed=true  cl-owner=<owner>  cl-gen=<n>  cl-kind=instance  [cl-until=<unix secs>]  Name=<name>

The AWS adapter leaves Name out when it classifies tags, so the name is free text, and AWS's own aws: tags too: EC2 adds aws:ec2launchtemplate:id, aws:ec2launchtemplate:version and aws:ec2:fleet-id to every instance a fleet launches, and no caller can set or remove an aws: key. A fleet cannot tag the Spot request it opens (both live fleets' requests on 2026-11-25 had no tags), so cleanup accepts an untagged one-time request as its instance's own and tries to cancel it after the terminate if EC2 left it open, never waiting on that cancel; a request with any managed tag must carry exactly the instance's.

Vast.ai has no tags, so a Vast.ai instance carries the same set as its label, joined by single spaces. A label whose words include cl-managed but are separated by anything else is unrecognized.

A resource with the managed tag but any other tag shape is reported as unrecognized and left alone. The exception is a malformed until tag on an otherwise exact set: the sweep never reads it as a deadline or as the absence of one, and asks the owner instead.

Trust zones

Every CloudProvider names a TrustZone, and its create spec must take that zone's boot data, so the compiler refuses a mismatch:

Zone Providers Boot data
Trusted DigitalOcean, phoenixNAP, Latitude.sh, AWS, and the machines app's Providers TrustedBoot: files to write and commands to run as root, read only by the cloud account and the machine
Untrusted Vast.ai UntrustedBoot: a digest-pinned ImageRef, its command, an optional pull-only ImageLogin, and a BootstrapEnv

A Vast.ai host and every holder of the account key can read an instance's image, command and environment, so an untrusted boot has no field for secrets. Its environment is exactly the four BootstrapEnv variables: CLOUDECK_BOOTSTRAP_URL (HTTPS without credentials or a query, or HTTP to a loopback host for tests), the one-time CLOUDECK_BOOTSTRAP_TOKEN, CLOUDECK_WORK_QUEUE_ID and CLOUDECK_WORKER_ID. The worker fetches anything else after it bootstraps. Debug output redacts the token, the registry credentials, the command arguments and the URL path, and only the adapter can send a rent request, so nothing bypasses UntrustedBoot. Two things stay the caller's job: the registry token must be scoped to pulls, and neither the command nor the URL path may carry a secret.

The zone trait is sealed, so no other crate can add a zone. The compile_fail examples in cloudlease_provider::trust check that Vast.ai cannot satisfy a Trust = Trusted bound, DigitalOcean and AWS cannot satisfy Trust = Untrusted, a Vast.ai spec cannot take a TrustedBoot, a provider cannot pair an untrusted zone with a trusted spec, and an UntrustedBoot has no allowed_secrets field.

Queue compatibility

The queue crates came from CloudDeck, and existing workers and callers keep working:

  • Work protocols v2 and v3 (/v1/work, /v1/work/handshake, /v1/work/bootstrap), artifact access, capability digests and mutation replay keep CloudDeck's wire bytes. Golden fixtures in crates/cloudlease-queue/fixtures pin them.
  • Workers still read CLOUDECK_API_BASE_URL, CLOUDECK_WORK_QUEUE_ID, CLOUDECK_WORKER_ID and CLOUDECK_WORK_CREDENTIAL, or CLOUDECK_BOOTSTRAP_URL and CLOUDECK_BOOTSTRAP_TOKEN when managed.
  • The cloudlease CLI reads CLOUDLEASE_CONFIG, CLOUDLEASE_PROFILE, CLOUDLEASE_API_BASE_URL, CLOUDLEASE_ADMIN_TOKEN, CLOUDLEASE_OPERATOR_TOKEN and CLOUDLEASE_CLEANUP_CONFIG, and falls back to the CLOUDECK_* name of each when the new one is unset. Its config file lives in the cloudlease config directory, and the cloudeck one is read while only that exists.
  • Managed workers run a command only. The Modal private-IPv6 service workers are gone, so the egress_private_ipv6 network policy no longer parses, and a pool request or inspection whose service or service_endpoint is anything but null or omitted is refused. Requests still serialize "service": null, so their digests do not change.
  • A managed pool request may carry spend_cap_cents. It is omitted when absent, so a request without one keeps its bytes and digest. Only Vast.ai pools take one.
  • Worker profiles must name the egress network policy. An isolated worker could never reach its bootstrap URL, so that policy no longer parses.

Queue state does not move between deployments. The cloudlease-queue Worker starts with empty Durable Objects, so cut over from a CloudDeck queue Worker by draining instead of migrating:

  1. stop creating queues and managed pools on the CloudDeck Worker
  2. let its queues finish, or cancel their pools, until every pool reports exact absence; external workers keep using the CloudDeck URL, queue IDs and credentials until then
  3. deploy cloudlease-queue and re-register worker profiles
  4. create each queue anew on cloudlease-queue (POST /v1/queues or /v1/managed-queues), which gives it a new queue ID and worker credentials. New queues take work protocol v3 only, so callers, workers and worker images must speak v3 first; the queue Worker answers a v2-only worker with unsupported_version
  5. point callers and the dashboard at the new Worker, and start external workers with the new URL, queue IDs and credentials; old ones are unknown there

A v3 queue whose artifact access is not disabled needs an ARTIFACT_ISSUER service binding, which the committed wrangler.jsonc does not have: without it every artifact request answers issuer_unavailable, so create such queues only on a deployment that binds one.

Running both Workers side by side is safe meanwhile: neither reads the other's state, and the cloudlease sweep deletes only Vast.ai instances labelled with its own CLOUDLEASE_TAG_PREFIX (clq), so no CloudDeck instance may carry that prefix.

  • A Vast.ai worker profile cannot name allowed_secrets, since its host can read them, and the queue renders it only through WorkerProfile::vast_instance_spec into a VastInstanceSpec with an UntrustedBoot. Modal profiles keep naming Modal-side secrets, never their values.

Wiring an app

  1. An owner Durable Object per owner ID. It stores holdings in a HoldingStore, calls owner::save after each change, creates resources with owner::create, calls owner::run_alarm from alarm(), and answers POST owner::SWEEP_PATH with owner::answer_sweep. owner::create saves the create intent before calling the provider, so a sweep that runs mid-create, or after the object dies before recording the ID, still sees the resource as claimed. The resource's ceiling tag is the lease's hard deadline.
  2. Optionally, a capacity Durable Object wrapping capacity::CapacityGate, used by the app through capacity::CapacityClient.
  3. A cron trigger that calls sweep::run_sweep with a SweepConfig naming the owner namespace and the capacity object.
  4. A provider built with digitalocean::from_env, or phoenixnap::from_env, latitude::from_env or vast::from_env, which return None when the Worker has no settings for them.

Development

Requirements: stable Rust with the wasm32-unknown-unknown target, worker-build 0.8.5 (cargo install worker-build --version 0.8.5 --locked), Node 22 and pnpm.

The Modal adapter also needs uv.

just fmt             # check formatting (just fmt-write applies it)
just clippy          # native and wasm32, warnings as errors
just test            # Rust unit and integration tests, the cloudlease CLI's included
just test-worker     # builds tests/worker, apps/machines and apps/queue and runs their miniflare suites
just test-modal      # the Modal adapter's pytest, ruff, ruff format and mypy
just test-dashboard  # the dashboard's svelte-check, lint, unit tests and build
just check           # all of the above, as CI runs it

The miniflare suites run against fake provider APIs, installed over fetch, and need no account or token; tests/worker/test, apps/machines/test and apps/queue/test hold them. The dashboard's Playwright suite (pnpm --dir apps/queue-dashboard test:e2e) needs a browser and is not part of just check.

Deterministic simulation

crates/cloudlease-sim runs the machines app's run objects, the tag sweep and the capacity gate against a fake cloud, all from one seed, on a clock that jumps to the next event. The run objects are the real handlers of cloudlease_machines::object, which the Worker's Run Durable Object wraps, over simulated storage, alarms, gate and network. They create through the real DigitalOcean, phoenixNAP, Latitude.sh and EC2 adapters, which send their requests to fake provider APIs over a seeded HTTP transport, and the sweep is the same cloudlease_provider::sweep::run_sweep. Clients open runs of a random class, ask for machines, renew and release leases with the token hashes the objects stored, and release runs. Each seed runs six simulated hours of work and four of drain.

Run object storage behaves like a Durable Object's: writes land in memory at once and reach durable storage in batches, each committing the writes made before it started, all or none, and nothing an object sends leaves before the writes ahead of it are committed. A failed write or batch resets the object, as do seeded evictions, and a reset drops its running handlers and every write not yet committed. Alarms fire only once committed, are consumed when they fire, and may fire late, at a time they were since moved from, or twice. A failed or interrupted handler is retried as Cloudflare retries it, except an interrupted handler that had committed an alarm change of its own: a set alarm then stands instead of the retry, and a deleted one leaves none, as Cloudflare may skip the retry.

The HTTP transport fails requests with 5xx, 429 with Retry-After, refused connections and timeouts before the provider acts, and loses the answer to a reset or timeout after it acts, so every adapter meets creates that succeeded upstream with their response lost. A request that gets no answer, or is slower than its timeout, fails at the adapter's timeout, while the provider acts at its own pace up to that timeout, as TAG_SEARCH_SETTLE assumes; a create that lands later is the sweep's. Requests that are not creates may be delivered twice. The fake APIs keep new resources out of lists for up to 85 seconds (inside the 120 second TAG_SEARCH_SETTLE), answer lists from a snapshot taken any time during the call, page, delete slowly, refuse creates for stock and reclaim servers, and the weather goes through spells of degraded service and outage. Calls between objects fail or lose their answers. The fake phoenixNAP API fails the run on a deprovision that does not ask to delete the server's IP blocks, which would go on billing.

Two faults break the provider contract cloudlease relies on, so they are off by default and show what the gap costs:

  • DST_FAULTS=id-read-lag: EC2's reads and deletes by ID miss a new instance for up to 20 seconds, as InvalidInstanceID.NotFound may follow a launch. Cleanup must wait out TAG_SEARCH_SETTLE after the lease's end before such a read counts as absence
  • DST_FAULTS=twin-creates: a create delivered twice makes a second resource, even after a first delivery refused for stock. No holding records the twin, so it may outlive its holding's release, and a billed twin may run after its permit is returned, until the sweep deletes it as unclaimed. The checks then require every twin gone within 20 minutes of the later of healthy weather and its holding last claiming it, as a slot whose create answer was lost claims every resource of its kind. EC2 makes no twins, since its client token returns the first answer

just test runs the fixed seeds with each of them on as well.

After every step the run checks that the gate stays within its limit with one permit per generation, that no permit an object holds is counted for or held by another, that every running billed server belongs to an admitted machine and is counted by that machine's permit at the run's units, that no machine bills for two servers, that no resource outlives a holding released as gone, that every object with work pending, a pending create included, has an alarm in time and ends expired leases before its first provider call, and that no lease stays leased more than 15 minutes past its expiry. After the drain nothing may still be taking a permit or creating a resource, nothing may be left in the cloud, no create may still be pending, and every holding must be released and every permit returned.

just test   # includes 64 fixed seeds per mode, about 30 seconds in a debug build
just dst    # 10,000 more seeds in release mode, about six minutes; just dst 50000 for more
DST_SEED=42 cargo test -p cloudlease-sim --test dst -- --exact replay --nocapture

A failure prints its seed, the broken invariant, the last 80 events and a replay command like the last line, which prints every event of that seed. The command also sets DST_ACTIVE_MS, DST_DRAIN_MS, DST_FAULTS and DST_SABOTAGE, empty ones too, so nothing exported in the shell changes the replay, and just dst takes DST_FAULTS and DST_SABOTAGE too. The sabotages (return-permit-on-release, keep-permits, alarm-never-earlier) break the app on purpose to show the checks catch it. Add a seed that once failed to REGRESSIONS in crates/cloudlease-sim/tests/dst.rs after fixing it.

Not covered yet

  • A create that outlasts cleanup's settle. An adapter's calls before its create request, such as phoenixNAP's token and tag lookups, each wait up to their 30 second timeout and retry, so a create can send its request more than TAG_SEARCH_SETTLE (120 seconds) after its lease ended. Cleanup has by then found no server by tag and released the holding and permit, and the server runs untracked until the tag sweep deletes it. Seed 2782 of just dst shows it; bounding a create's total time and waiting out the settle from that bound would close it
  • Some live paths. Each provider has run a live machine through the machines Worker, but heartbeat-lapse and hard-deadline deletes ran live only on DigitalOcean, and out-of-stock fall-through only on Latitude.sh. How long EC2 keeps a ClientToken is unconfirmed
  • Vast.ai through a deployed Worker. The adapter's REST calls were probed live, and apps/queue runs a managed pool end to end in miniflare against a fake Vast.ai API, but no pool has rented a live instance through a deployed queue Worker, and gpu_name filtering is unprobed: the adapter sends underscores as spaces, the form offers report
  • Firewalls on DigitalOcean, phoenixNAP and Latitude.sh. firewall::IngressPolicy has only the AWS shared security group implementation
  • Batch-job records and exit status. These belong to the app, which builds on holdings and the sweep report
  • The Worker glue around the run object in the simulation: request authentication, routing and the run index are left out, and a client call is the RunCall the public Worker sends the object. The queue app and its Vast.ai adapter are not simulated
  • A tag search after a lost create discards a resource whose tags are not exactly the scheme's, such as a droplet someone tagged by hand in the minutes before cleanup. Cleanup then proves the resource absent and returns its permit; the sweep leaves it running but reports it as unrecognized in the log

About

No description, website, or topics provided.

Resources

Security policy

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages