Skip to content

About

No description, website, or topics provided.

Resources

Security policy

Stars

0 stars

Watchers

0 watching

Forks

Latest commit

 

History

190 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 owners, the sweep and the capacity gate against a faulty fake cloud; 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 owners, the tag sweep and the capacity gate against a fake cloud, all from one seed, on a clock that jumps to the next event. Owners run the same cloudlease_provider::owner rules as the Worker glue, and the sweep is the same cloudlease_provider::sweep::run_sweep. Around them the simulation models the app (admission through the gate, permit return and presence checks, as in the machines run object), the calls between objects, and the cloud. Each seed runs six simulated hours of work and four of drain.

The fake cloud loses create responses after acting, keeps new resources out of tag searches and inventories for up to 85 seconds (inside the 120 second TAG_SEARCH_SETTLE), answers lists from a snapshot taken any time during the call, deletes slowly, reclaims servers, refuses creates for stock, and goes through seeded spells of degraded service and outage. Gate and owner calls fail or lose their answers, and owner objects are reset mid-handler. Deletes and reads by ID reach only the endpoint of the kind they name, so cleanup that mixes up kinds leaves the resource running. With DST_FAULTS=id-read-lag, deletes and reads by ID also miss a new resource for up to 20 seconds, as EC2's may answer InvalidInstanceID.NotFound right after a launch; cleanup must wait out TAG_SEARCH_SETTLE after the lease's end before such a read counts as absence, and just test runs the fixed seeds with it 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 owner holds is counted for or held by another owner, that every running billed server is counted by a permit, that no resource outlives a holding released as gone, that every owner with work pending 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, and every holding must be released and every permit returned.

just test   # includes 64 fixed seeds, about three seconds
just dst    # 10,000 more seeds in release mode, about a minute; 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 carries any setting the run changed: DST_FAULTS, DST_SABOTAGE, DST_ACTIVE_MS or DST_DRAIN_MS. Add a seed that once failed to REGRESSIONS in crates/cloudlease-sim/tests/dst.rs after fixing it.

Not covered yet

  • 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 machines run object itself in the simulation. It calls Durable Object storage and alarms directly, so the simulation runs a model of its admission and permit return instead; Storage and Alarm traits under apps/machines/src/app/run.rs would let it run the real one. The provider adapters' HTTP retries are not simulated either; the fake cloud sits at the CloudProvider boundary
  • 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