pushleft
Deploy your first app
Manual contents
Handbook
HandbookPushleftArchitecture
Operate
Install the control planeYour own serversFleetOperations and alertsAuthenticationAccess gateDomains and DNSUsage and budgetsScheduled jobsAbuse controlsAI provider proxyCustomer mailErrors and performanceLogs and metricsRetentionObject storageContainer registryGit server
Develop
The .pl.yaml manifestOnboard with an AI agentThe pl up demoBuild executorSource ingestionAgent gatewayManaged databasesSecurity findingsTunnels and shellsDev workspacesPrivate hostnamesMesh coordinatorsDesign baseline
Runbooks
Control-plane host failoverControl-plane PostgreSQL failoverControl-plane PostgreSQL restoreCustom domains and certificatesGateway key compromiseIngress host failureNode busyNode disk fullNode drain and replacementNode lostRegistry outageHetzner Robot hostsSecret rotationSecurity incidentStaging fleet on ProxmoxStaging build cacheStuck deploymentVault/OpenBao backup and recovery
More
CI pipelines
Manual · docs/architecture.md

Architecture

This page explains how Pushleft is built and which rules every change must keep. Read it before you change the control plane, the agent or the network. It covers the product boundary, core invariants, DNS, private networks, observability, manifest, managed databases and the delivery slices that took pl up to a live URL.

Product boundary

Pushleft turns a local checkout or a Git revision into an isolated preview or a production release. The managed service runs on Hetzner: on Robot (dedicated) servers since 2026-11-03 (Robot hosts), and on Cloud nodes in fsn1 and hel1. Customer-owned VMs follow. Kubernetes can come later as an adapter, and is not the first runtime abstraction.

pl / Git hooks / web
          │
          ▼
  Rust control plane ─── PostgreSQL (desired state, events, leases, usage)
       │      │
       │      ├──────── Vault/OpenBao (secret values; control plane stores refs)
       │      ├──────── OCI registry + object storage
       │      ├──────── Cloudflare (authoritative DNS, proxy/WAF, certificates)
       │      ├──────── Headscale (management plane + isolated environment control planes)
       │      └──────── ClickHouse (90-day telemetry and web analytics)
       │
       ▼ outbound mTLS pull
  VM agents ── management tailnet
       │
       └──── environment bridge + namespaced mesh gateway ── web/worker/cron/data

Core invariants

  1. A deployment is desired state plus an immutable release. Traffic assignment is mutable and auditable.
  2. Every mutating API call and agent job carries an idempotency key.
  3. Every row, query, event and usage record is organization-scoped. Production database roles use RLS. Application predicates stay mandatory as defence in depth.
  4. Every public API route resolves exactly one organization from the credential (AuthContext), checks a minimum role, and sets app.org_id from that context. Production credentials are looked up by hash on every request. Nothing about the tenant comes from the request body or path. Development auth is loopback-only. See authentication.
  5. Secret values live in Vault/OpenBao. Manifests and PostgreSQL contain references only.
  6. Agents open outbound mTLS connections. The agent gateway verifies the client CA and an active certificate fingerprint, then leases only work targeted to that node. Agents run a versioned allowlist of typed jobs, never arbitrary shell strings from the control plane.
  7. Deployment events are append-only. Log and event streams resume from a cursor.
  8. Resource limits, budgets, expiry, placement and pricing checks happen before work is leased.
  9. Teardown is a reconciled state transition. Traffic is removed, processes stop, ephemeral resources are deleted, persistent resources follow the retention policy, and the audit trail remains.
  10. Preview hosts are flattened as <branch>--<project>--<handle>.<base>, so one *.<base> wildcard certificate covers them (see Ingress publication).
  11. Domain purchases use Openprovider from the backend. Authoritative DNS uses zones in one configured Cloudflare account. Customer ownership, registrant consent, accepted prices, payment state, delegation and retries stay durable Pushleft state. Provider credentials never reach the browser.
  12. Mail, DKIM, SPF, MX and provider-verification records are always DNS-only. Only eligible A, AAAA and CNAME web records can turn on the Cloudflare proxy.
  13. Every deployment environment has a dedicated Headscale instance and database. A shared Headscale instance plus tags is not a tenant boundary. The host agent never joins these workload tailnets.
  14. Public-port declarations name an exact workload role and destination port. Only 80/443 can implicitly target the managed ingress router. Deployment admission stays closed until the provider and host firewall generations, and the selected node’s environment attachment, are ready.
  15. The node agent and the local OpenTelemetry collector never receive arbitrary shell or SQL from the control plane. Typed operations, digest-pinned images, Vault references and fencing tokens are mandatory. The one exception is a developer session (pl exec, the console’s Shell). An Admin’s command runs inside one tenant container through docker exec. Every session is recorded.
  16. Tenant containers are never host root. Nodes run Docker with userns-remap (container uid 0 is a dockremap subordinate uid), with every capability dropped. The build container is the one documented --userns=host exception (rootless BuildKit or a Kata VM). The remap is one range for the whole daemon. So an escape still reaches files that every container on that host owns (colocated tenants’ volumes and mesh state), but not host credentials. An environment’s firewall exists before any of its containers runs, also after a reboot. See workload hardening.

Fleet nodes move through provisioning → active ⇄ unhealthy → draining → retired (plus the older offline/revoked). See the fleet substrate.

  • Only active nodes can lease.
  • unhealthy (missed heartbeats) keeps allocations. Drain is the only path that moves work.
  • Retirement revokes every certificate and keeps all history.
  • Enrollment uses a one-time, 15-minute secret on a separate listener that does server auth only.
  • Client certificates are short-lived (24 h by default) and rotate through the mTLS gateway. The old certificate is revoked on the first lease with the new one.

The placement scheduler reserves CPU, memory and persistent disk before it targets a job. A node is eligible only when all of these are true:

  • it is active and explicitly schedulable,
  • it was seen within 60 seconds,
  • it is in the requested region and pool,
  • it advertises the required capability,
  • Pushleft manages it, or the requesting organization owns it.

When capacity runs out, work stays queued for later reconciliation. Malformed or currently unsafe requests fail closed. Allocations stay durable until an explicit teardown or move releases them.

DNS and domain ownership

Openprovider supplies availability, authoritative prices, registrant handles, registration, renewal data and nameserver delegation (domain registration).

  • The controller creates a new full Cloudflare zone only after registration is confirmed. It records the exact account, zone ID and assigned nameservers, and waits for delegation before it makes the domain active.
  • It never adopts an existing zone only because the name matches.
  • Cloudflare tokens are restricted to the configured account, with Zone and DNS edit permissions.

Record changes are reconciled from desired state. Cloudflare batch operations reduce partial updates. Propagation across its distributed store is not atomic, so migrations must accept old and new answers during the convergence window. Pushleft tags the records it owns and never deletes records it does not own.

Provider presets generate record sets that you can review, for Microsoft 365, Google Workspace, and Amazon SES. Tenant-specific verification, MX and DKIM values stay required inputs. SPF is merged into the existing single SPF record. Pushleft never publishes multiple SPF TXT records.

Private deployment networks

Every application node needs br_netfilter loaded and net.bridge.bridge-nf-call-iptables=1. Without it, frames that the bridge switches between the mesh gateway port and workload containers bypass the environment firewall below. The agent fails closed without it (fleet firewall).

Tailnets and the environment gateway

The host agent joins exactly one private, self-hosted management tailnet. It uses that identity only for fleet administration, and never attaches it to a workload bridge. Global tailscale up for a deployment is forbidden, because one ordinary host daemon cannot be active in several isolated tailnets at once.

Each environment gets a dedicated Headscale control server and data store, and so a distinct workload tailnet (mesh coordinators).

  • On every selected host, the agent reconciles one digest-pinned Tailscale subnet-router container in its own namespace.
  • That gateway attaches only to the environment-specific Docker bridge. It advertises only that host’s globally unique private /24.
  • Releases in the same environment share the bridge and stable service discovery. Cross-host traffic uses the environment mesh.
  • Peer routes and return paths are reconciled from durable node attachments.
  • Different environments have separate Headscale state, gateway namespaces, bridges, routes and firewall identities.

Enrollment. The pre-authentication key is one-use and short-lived, read from a Vault reference scoped to the tenant and environment. The agent delivers the key as a 0600 file and passes it to tailscale up through file:. The key stays out of process arguments and Docker environment metadata. Tailscale SSH, exit-node advertisement, management-tailnet routes and unrelated route acceptance are off. Subnet routing needs kernel mode. The gateway gets only NET_ADMIN, NET_RAW and /dev/net/tun, with no Docker socket, host network or agent credentials.

Gateway admission verifies the effective runtime state, and not only the desired labels.

  • The agent inspects the pinned image, entrypoint, command, environment, sole static bridge attachment, private namespaces, exact capabilities and TUN device. It also checks the read-only filesystem, exact private mounts and tmpfs, unpublished ports, bounded CPU/RAM/swap/PIDs, and rotating local logs.
  • After Tailscale reports Running, the agent reads the effective preferences itself. It rejects foreign control URLs, extra advertised routes, SSH/web/DNS enablement, exit-node use and weakened forwarding filters.
  • Health also requires the exact local state ownership marker.
  • Reconciliation is serialized per environment. Stopped containers keep their configured static IP for pre-start validation, and later live health requires the actual IP.
  • Starts and restarts use inspected container IDs. An ambiguous create failure never removes a container by name.

The gateway runs with TS_DEBUG_FIREWALL_MODE=nftables. Its root filesystem is read-only without a writable /run. In iptables mode, tailscaled cannot take /run/xtables.lock and never opens its control socket. The failure showed on Ubuntu 24.04 with ip_tables loaded. Docker Desktop picked nftables by itself. Gateways created before this variable existed still verify. ensure_gateway recreates them on their own state directory, so enrollment is kept and TS_AUTH_ONCE skips a new login.

First-enrollment recovery.

  • The agent records first-enrollment provenance durably before key retrieval and start. It clears it only after verified health and key removal.
  • A failed first login keeps the short-lived key. A stopped pending runtime refreshes the key from the authorized Vault reference before start.
  • A running NeedsLogin runtime can recover only with the expected coordinator, or with an uninitialized default profile backed by matching pending provenance.
  • The agent never reauthenticates an already connected profile as a recovery shortcut.
  • Normal enrolled restarts need no bootstrap Vault reads.

test:network-agent exercises real Docker runtime and preference readbacks, stopped static-IP validation, live preference drift and stopped pending-key refresh. test:mesh (in test:all) also proves real TLS enrollment through production-generated proxy handlers and untrusted-CA rejection. It covers expired-first-key recovery of the same stopped container, consumed-key cleanup, and enrolled restart during a Vault read outage. These suites do not prove cross-host workload routing, public DNS/ACME or a production fleet rollout.

Coordinator trust. Publicly trusted coordinator certificates need no extra agent setting. Self-hosted private authorities use the operator-only PUSHLEFT_MESH_CA_FILE (or --mesh-ca-file). Manifests cannot select trust roots or turn off TLS checks.

  • The agent validates PEM and X.509 data. It rejects private keys, mixed blocks, and source files that are non-regular, relative, or group/world-writable.
  • It creates an immutable content-addressed trust snapshot. Only that exact snapshot can be mounted read-only with the expected TLS trust setting.
  • A changed operator trust bundle changes its snapshot path. Existing runtime inspection then fails until an explicit fenced replacement. A CA rotation never reaches a running gateway silently.

Firewall and route evidence

Firewall identity binds the gateway’s runtime specification hash and the resolved ingress policy. It leaves out the bootstrap credential reference. So a reissued one-use key cannot invalidate firewall enforcement that is otherwise unchanged. The environment_firewall_v2 renderer admits declared peer replies only when all of these hold. The traffic is IPv4, both interfaces equal the environment bridge, the destination is local, and conntrack is reply-direction established/related. Unsolicited peer traffic stays denied. Existing persisted firewall fences and desired records need an explicit newer generation on upgrade. Do not rewrite or bypass an old fence at the same generation.

The typed network task validates pinned images, immutable generations, canonical private subnets, non-overlapping peers, credential-free HTTPS Headscale origins, state paths and Vault tenant scope. The agent can:

  • reconcile an owned Docker bridge with a deterministic host interface,
  • run a constrained kernel-mode Tailscale gateway with a file-backed one-use key, persistent state, exact Docker labels and health checks,
  • apply and independently verify scoped environment nftables policies and host peer routes.

The isolated Headscale runtime, HTTPS publication, scoped Vault enrollment recovery and the durable coordinator worker are implemented (coordinator operations). Migration 0059 moves a segment to ready only when every sealed member host has fresh evidence (segment activation). Gap: complete recovery from a partial agent enrollment, a host-wide input policy and provider firewall enforcement are not built.

Admission evidence. Database placement, reconciliation of existing allocations, logical database and user operations, and agent leasing all need a host-specific network_attachments record.

  • Gateway, firewall, host routes and coordinator-approved provider routes must each match the desired generation and the separately hashed policy. Each must be verified within the last 120 seconds. Future timestamps are rejected.
  • The shared ready_network_attachments view uses invoker security. So tenant RLS stays effective, and the view does not expose the global fleet inventory.
  • Coordinator health is projected separately, with an expiry no later than its observed fleet heartbeat plus 60 seconds. Revocation and coordinator replacement invalidate cached health.
  • There is no readiness backfill.
  • Authenticated network-job results update only the matching host, environment, gateway, generation, durable desired specification hash and the exact pl_<segment UUID> bridge that database placement uses.
  • Database triggers prevent attachment identity changes, generation rollback and specification changes without a generation increase.
  • Health tasks carry the complete expected gateway specification. The agent checks the actual environment and specification labels (including generation), sole bridge attachment and IP, bridge ownership and IPAM, and Tailscale state.
  • Gateway health cannot certify an unapplied generation, or mark firewall or routes ready.
  • Route leasing and successful route results also need fresh matching gateway and firewall evidence. Check-only jobs cannot certify unapplied routes.
  • A retry failure invalidates its own evidence.
  • Agents that advertise network_local_checks also check their own firewall, gateway and host routes every 30 s. They run the stored Check form of their last successful job of each family and send one batch to POST /v1/agent/network/evidence (at most 256 reports). The gateway applies a report with the same fences as a check job, plus the credential revision. A report never moves a generation: it refreshes evidence only where an Ensure job already set the desired generation. A failed check clears that family’s evidence, and the agent never repairs drift itself. The families of one attachment are written in one update.
  • The durable mesh worker periodically verifies the exact persisted provider-route intents and repairs failed checks.

Admission prevents new work. To stop existing traffic after network drift, you still need host enforcement.

Host routing uses a numeric table that the agent owns exclusively. The table number derives from the environment UUID. Rules use protocol 196 and priority 1000, restricted to the local source subnet and the incoming environment bridge.

  • The agent never changes the main, local, default or management-tailnet tables.
  • Numeric JSON reads stop operator table or protocol aliases from hiding foreign state.
  • Root-owned locks, table ownership records and durable generation and hash fences prevent adoption, collisions and rollback, also after kernel rule loss.
  • Validation rejects overlapping policies at higher or equal priority and local-table peer collisions, then verifies actual kernel lookups.
  • Route hash environment_routes_v2 binds the priority and protocol. Upgrades need a newer generation.
  • Online route tasks attest gateway health first. The offline manage-routes diagnostic command only verifies host routing and does not attest mesh enrollment.

npm run test:linux-routes proves real TCP/UDP peer replies, denial of unsolicited peers, environment isolation, numeric aliases and narrow source/destination shadow detection. It also proves refusal of local-table collisions, unchanged main and unrelated tables, drift repair, peer removal and durable fencing. Its decrypted remote link is simulated. Real multi-host Tailscale transport, route approval and SNAT are separate release proofs. Linux CI runs this gate with the firewall and quota gates. Remote CI execution has not been verified locally.

Upgrade from v1 routes. v2 rejects a v1 priority-10000 route rule as foreign, even with a newer desired generation. There is no automatic in-place migration of v1 rules. To upgrade:

  1. Keep the attachment closed and quiesce its workloads.
  2. Verify the persisted environment and table ownership, and the exact old rule.
  3. Remove only that old rule through operator maintenance.
  4. Apply the newer v2 generation, then restore admission.

Never clear ownership or fence files, flush shared tables or bypass readiness to do an upgrade.

Environment firewall

Public traffic reaches only the Cloudflare proxy and router path, or explicitly selected workload ports. NetworkPolicy rejects custom ports without a destination role and port. It also rejects source CIDRs that overlap private, shared-overlay, documentation, benchmark, multicast or reserved space.

The agent owns one nftables table per environment:

  • It leaves Docker’s tables and other owners’ tables alone, and checks ownership.
  • It validates a complete transaction, atomically replaces its table, and compares the normalized kernel readback with the desired rules.
  • A root-owned persistent generation and hash fence, and an exclusive per-environment file lock, stop stale retries from restoring older rules, also after table loss.
  • Workload-to-host access, private and metadata egress, source spoofing and IPv6 are denied.
  • The input chain accepts from the bridge only reply-direction established/related packets. So host-initiated flows work (the ingress Caddy dialling a container). A container that opens anything on the host (Caddy admin 2019, otelcol, the agent) is dropped.
  • New flows from the bridge are capped at ENVIRONMENT_CONNECTION_LIMIT (8192) tracked connections per environment (ct count over). So one tenant cannot fill the conntrack table of the host.
  • Same-environment traffic and public IPv4 egress are allowed.
  • Public ingress needs an exact interface, protocol, source range, translated destination IP and port, DNAT status and original published port. Direct routing and undeclared ports are denied.
  • The firewall specification has its own durable hash and cannot refresh gateway readiness. Stale network jobs cannot get an agent lease.

npm run test:linux-firewall builds a Linux agent and runs real namespace packet tests in a disposable Docker worker, without host networking, host devices or writable host mounts. It covers:

  • TCP/DNAT allow and deny,
  • cross-environment and host/metadata isolation,
  • same-environment traffic and internet egress,
  • source ranges, replay and drift repair, generation rollback,
  • fence persistence after table loss, and ownership refusal,
  • host-to-container replies,
  • the saved boot copy (/var/lib/pushleft/firewalls/<table>.nft.json), which restores exactly the verified table.

Boot ordering. The agent saves each table after it verifies it. pushleft-firewall-restore.service loads every saved table before Docker starts (Docker Requires= it). So unless-stopped containers never restart unfiltered.

Gaps: broader UDP, IPv6 and spoofing validation, and coexistence with native Docker rules. The host-wide public-input policy and provider firewall reconciliation are separate requirements, and this scoped table does not certify them. The local Docker Desktop kernel has XFS but no XFS quota support, so the real XFS quota release gate needs a Linux worker with quotas.

Observability and analytics

Every node runs pushleft-agent and one OpenTelemetry Collector Contrib system service (service output and instance metrics).

  • The agent renders and validates the node-scoped collector configuration from its authenticated mTLS identity. It reconciles the systemd unit, with rollback on a failed activation.
  • Host metrics and application OTLP signals enter over loopback.
  • The collector runs under a dedicated UID with a telemetry-only client certificate. It has no access to the Docker socket or to the agent and Vault credential directory.
  • The agent also collects each web, private and worker instance’s output and its CPU, memory and network use. The console’s Logs and Metrics pages show them (service output and instance metrics).

The telemetry gateway is a Rust mTLS OTLP gateway. It:

  • accepts protobuf over HTTP from telemetry-purpose certificates only,
  • resolves revocation against the control-plane database,
  • admits only nodes that are active, unhealthy or draining (telemetry matters most from an unhealthy node). It refuses provisioning, offline, lost, revoked and retired nodes. The agent gateway still authenticates every node except revoked and retired, so a lost node can fetch its cleanup list,
  • reloads its certificate, key and client CA within 2 s of a change (a set that fails to load keeps the previous one),
  • overwrites node and region identity, and rejects tenant and deployment claims,
  • applies per-node request and byte limits,
  • forwards to a collector on loopback only.

The collector has a persistent retry queue. It batches logs, metrics and traces into ClickHouse with a 90-day TTL. Workload-scoped OTLP ingestion stays closed until deployment identity can be validated against scheduler placement. Gap: there is no attribute or body redaction policy yet, so applications must not put secrets in telemetry. Control-plane audit retention is separate and longer (audit trail).

Web analytics. The built-in analytics ingress accepts events only when the telemetry certificate’s node, deployment and hostname match an active ingress_analytics_routes assignment. Organization, environment, service and region come from trusted state. Before an event goes into the 90-day ClickHouse table, the gateway:

  • drops query strings and fragments,
  • reduces referrers to hostnames and user agents to coarse families,
  • replaces the source address with a daily HMAC.
  • keeps the visitor’s country and discards the address: the country Cloudflare named, else the country of the address’s range in a local file (see Countries below).

Raw IP addresses and full referrers are never written. Duplicate event_id values converge through ReplacingMergeTree.

Where the events come from (built 2026-11-10, the small version decided 2026-11-09):

  1. Each node’s ingress Caddy writes its access log as JSON lines to the agent on 127.0.0.1:9466 (PUSHLEFT_ACCESS_LOG_LISTEN). The agent sets this up through the Caddy admin API at start and every hour. Caddy’s encoder drops query strings before anything is written.
  2. The agent sends them in batches of up to 500, or every 5 seconds, to /v1/access/batch with the node’s telemetry certificate. The event names no deployment: the gateway takes it from the node’s active route for the hostname.
  3. It is best effort: there is no queue on disk. Events are dropped when the gateway is unreachable, when a batch is refused, or when the agent is not listening. While the agent is away, Caddy writes the lines (without query strings) to its own journal.

PUSHLEFT_WEB_ANALYTICS=0 on a node turns it off.

The console shows the result in two places (the organization page since 2026-11-12):

  • Traffic in the organization menu. It lists every hostname with its requests, visitors and server errors, busiest first. Above the list are the totals with their hourly lines. Below it are the top pages, referrers and countries. Select a hostname to see its figures alone. The period is 24 hours, 7 days or 30 days (GET /v1/analytics?hours=&hostname=, up to 720 hours). Guests do not see this page.
  • Traffic on the deployment page, for a live, published deployment: the same figures for that deployment over 24 hours (GET /v1/deployments/{id}/analytics?hours=, up to 720 hours).

A visitor is counted once a day, because the hash changes every day.

Countries. Cloudflare names the visitor’s country for the traffic it fronts. For other traffic the gateway looks up the address in a local file of address ranges (PUSHLEFT_ANALYTICS_GEOIP_FILE: lines of first,last,CC, IPv4 and IPv6 in one file). No request leaves the gateway for a lookup, and the address is not stored.

  • install-control-plane.sh prepare downloads the user-country files of ip-location-db once. They are in the public domain (PDDL) and built daily. Each file is checked against the SHA-256 the project publishes.
  • install-control-plane.sh geoip downloads them again. The gateway reads the file at start, so restart pushleft-telemetry-gateway afterwards.
  • Without the file, only Cloudflare traffic has a country. Requests without a country are counted in the totals and left out of the country list.

The console shows each country with its flag.

Application manifest

.pl.yaml (manifest reference) describes the build (build: { dockerfile, context, target }, paths inside the checkout) and each role:

  • kind,
  • command (shell form /bin/sh -c, or exec form without a shell; either replaces the image ENTRYPOINT),
  • port and health,
  • plain env and environment secrets,
  • the databases it uses, volumes and bounded tmpfs,
  • resources (a bounded CPU and memory list, capped per trust tier, reserved exactly at placement),
  • startup_timeout.

The planner merges top-level env/secrets into every role. The role spec carries the names only. So a changed variable or secret list is a new plan and a new release.

Secrets. You set secret values per environment through the API (pl secrets, console Settings). They go into Vault, where the API can write and delete them but never read them (secrets).

  • The agent gateway puts single-use wrapped tokens for exactly the role’s secrets and database logins into its ensure_application/run_application lease. The tokens are scoped to the lease’s organization and environment.
  • The node writes file secrets into a per-container read-only /run/secrets mount.
  • It writes as: env secrets and database variables into a 0600 --env-file, and deletes the file after docker run. Variables stay visible to host root through docker inspect, so files are the default.

Databases. Logical databases and logins declared under data.<engine>.databases are created with the instance (databases). The gateway generates the password of each login (create-only). A role that uses a database is targeted only when the instance, database and login are ready. It gets the instance’s fixed address with the lease (x.126 PostgreSQL, x.125 ClickHouse on the environment /24 of its host). Applications on another host reach it over the environment mesh. The first multi-VM run timed out there until gateways ran Tailscale without stateful filtering (2026-10-20). Staging’s db-app has done this since 2026-10-21.

Managed databases

The managed host image installs Docker Engine, XFS tooling and the agent. Database jobs do not install host software. The agent then runs PostgreSQL, ClickHouse and Valkey as digest-pinned containers (managed databases). Each has explicit CPU, memory, XFS project-quota disk limits, data path and private-network policy.

  • Database container roots are read-only. ClickHouse configuration and logs live inside its quota tree. Temporary files are bounded tmpfs mounts, and Docker stdout/stderr logs rotate.
  • Quota project IDs are durable and globally unique. Startup fails closed unless accounting and enforcement are active. The scheduler requires and revalidates the matching node capability.
  • The online executor supports idempotent ensure and install, restart, health checks, database and user creation, and least-privilege grant reconciliation.
  • Credential rotation and removal exist as typed and local maintenance operations. The online lease loop rejects them until database-level fencing exists.
  • The agent fetches secret values just in time from Vault/OpenBao KV v2. It supplies bootstrap credentials through root-only bind-mounted files. User credentials travel only over child-process stdin.
  • Values never appear in command arguments, Docker labels, jobs, events or control-plane rows.

The control plane keeps one durable database instance per environment and engine, separate from releases. Logical databases and principals are idempotent desired-state resources. PostgreSQL owners are explicit. ClickHouse users get a normalized allowlist of grants. The agent refuses floating images, unowned containers, paths outside its configured roots, implicit specification upgrades, and data deletion without a path-bound removal task. Database containers publish no host ports and attach only to the environment network.

Backups and restore (backups, PITR and restore drills):

  • The agent runs PostgreSQL WAL archiving, verified base backups and point-in-time restore. It also runs ClickHouse native backups.
  • A restore always creates a new generation (<instance>_g<N>). A restore request (pl db restore) creates the new generation beside the source, which keeps serving.
  • Daily restore drills verify both engines and record their results as fenced instance evidence (migration 0030).
  • Backups are sealed with the organization’s key. The agent keeps 1 day on the host and hard-links each backup into a spool that pushleft-offsite ships to R2 (off-host spool).
  • An operator relocation moves writers to a new generation behind a write fence, on the same node or another one (PostgreSQL relocation).
  • An operator moves containers from before runtime policy 5 onto the current policy, and customers upgrade PostgreSQL to a newer major. Both go into a new generation (PostgreSQL upgrades).
  • Replica bootstrap and HA promotion stay rejected.

Application roles can declare host-local persistent volumes with one writer and read-only readers in the same environment. Volumes are quota-bound, kept on teardown, backed up nightly, and released only explicitly or after a retention window.

PostgreSQL relocation

Pushleft does not promise multi-writer PostgreSQL. A relocation is a controlled single-writer handoff into a new generation. The scheduler’s operation state machine and the agent’s relocation steps implement it (migration 0075, restore requests and relocation):

  1. The source takes a fresh sealed base. On another node, the target gets it through the backup blob store (sealed bytes only, write-once). The same hash and AEAD checks apply as for a spool import.
  2. The target generation starts as a standby. It replays the source’s sealed WAL archive as the agent stages it. Archive shipping needs no replication connection, so the source’s pg_hba stays closed.
  3. A catch-up step switches and archives the source’s WAL. The standby replays to that LSN.
  4. The source is fenced. A fenced pg_hba rejects every tenant login. default_transaction_read_only is set with ALTER SYSTEM. Every client backend is terminated, and the step waits until they are gone. A marker in the data directory makes the agent keep the fence through restarts, re-ensures and recreation. The source then archives up to the fenced LSN.
  5. The target replays to the fenced LSN, promotes and takes the instance’s fixed address (x.126 of the host’s environment /24). Every acknowledged commit is at or below that LSN, so none is lost. Writes during the fence fail without an acknowledgement.
  6. The control plane cuts over in one transaction: serving generation, result fence, quota project, node and capacity key. Every later lease names the new generation and address. After a cross-node move, every running instance that uses PostgreSQL is re-ensured, one at a time, at its generation. The agent recreates it in place with the new address (same name and fixed address, so ingress routes hold). Only then is the move cut_over.
  7. The source drains and is retired after a grace period. Its sealed archive stays. A failure before promotion rolls back (the standby is removed and the source unfenced). A failed promotion fails closed with the source still fenced.

The endpoint is the fixed per-host address that leases carry, with no DNS name. A same-node move keeps it, so applications reconnect unchanged. A cross-node move changes it, so step 6 restarts the applications that use it. Gap: a stable per-environment address that would avoid those restarts is not built.

A planned relocation targets zero loss of acknowledged writes through the write fence. npm run test:database-relocation checks every acknowledged write of a continuous writer across the fences. An unplanned regional failure uses asynchronous replication, so it has a non-zero RPO target. A witness in a third failure domain owns quorum. The database controller owns fencing and must revoke the old writer before promotion. Gap: that HA path is not built.

PostgreSQL upgrades

Both upgrades reuse the generations, fence, cutover and grace period of the relocation, on the instance’s own node (migration 0078, upgrades). The control plane records each instance’s PostgreSQL major (engine_version) and runtime policy. It builds every task with the image of the instance’s own major.

  • Runtime policy. pushleft-controller fleet upgrade-database-runtimes --apply moves each instance from before runtime policy 5, one at a time, through a same-node relocation. The agent accepts such a container only for these fenced steps, after it checks the data marker and the organization’s WAL archive mount. It fences the container through the pg_hba.conf in its PGDATA.

  • Major versions. pl db upgrade --plan restores the source’s schema into a throwaway container of the target image. It checks extensions, disk headroom and the runtime policy. The upgrade:

    1. starts the new generation empty and fences the source,
    2. copies the data with pg_dumpall into the new major (dump and restore, no pg_upgrade). It uses only reviewed one-major images, the source is never written, and every index is rebuilt,
    3. analyzes, compares exact row counts and takes the address.

    Writes fail for the length of the copy. The previous generation stays fenced for a grace period. pl db upgrade --rollback --confirm-data-loss cuts back to it and discards the writes made since the upgrade.

Delivery slices

Slice 1: control-plane contract (implemented)

  • .pl.yaml parser, validation, inference and deterministic planner.
  • Rust API with idempotent deployment creation, immutable events, job enqueueing, teardown and SSE cursors.
  • pl up, pl list, pl down, pl logs and pl plan.
  • Production authentication: hashed API tokens, console sessions with a CSRF header, owner/admin/member/viewer roles on every route, bootstrap onboarding and immediate revocation. It also has an append-only auth audit and pl login/whoami/logout. It requires a trusted TLS proxy. Later work added TOTP, passkeys and organization SSO. There are no passwords, so there is no password reset (authentication).
  • Agent host safety checks, a secure management-Headscale join, node-scoped telemetry reconciliation and mTLS typed-job leasing.
  • PostgreSQL migration and the local developer stack.
  • Dedicated desired-state tables with RLS for network segments, DNS record sets and telemetry tenants.
  • Cloudflare zone and owned-record execution, DNS provider preset validation and 90-day ClickHouse schemas.
  • Managed PostgreSQL/ClickHouse instance, catalog and principal state with RLS. Online typed agent execution for install, health, users and grants.
  • A mandatory-mTLS agent gateway with certificate revocation, node-targeted leases, heartbeat fencing, bounded results, retry backoff and append-only execution records.
  • Immutable persistence for source snapshots and release artifacts, private lease-bound build publication, and application intents per role and replica. Slice 2 wired source ingestion, isolated builds and application execution onto this foundation.

Slice 2: single-node runtime

  • Automated agent enrollment, short-lived certificate issuance and rotation, and drain workflows, as private operator tooling (fleet substrate). Hetzner provisioning is tested only against a local API stub, and no live Hetzner run has been made. Capacity-bounded placement covers databases and application roles.
  • OCI build, registry push, typed Docker lifecycle jobs, resource limits, health checks and local volumes.
  • Wildcard preview DNS and TLS, and router configuration that is safe to roll back.
  • Environment mesh gateway, readiness of the selected node’s attachment, host route reconciliation, and atomic provider and nftables firewall enforcement.
  • Structured stdout/stderr and OTLP ingestion with bounded disk queues and cursor persistence.

The target of this slice is an authenticated, single-node stateless preview, from a real pl up to a verified HTTPS URL. The CLI uploads a verified immutable source bundle when ingestion is configured. Generic application-role reservations prepare their own environment membership, so a web-only application needs no dummy database.

Source snapshots and release artifacts

Migration 0021 binds one immutable archive to an active deployment in source_snapshots. The row holds its digest and object key, byte and file bounds, project, plan hash and scoped image repository. With migration 0023, the configured API ingester:

  1. verifies the bounded archive bytes and manifest,
  2. reserves one exact digest and a stable artifact identity under organization quotas,
  3. stores the archive privately without overwrite,
  4. attaches the verified provenance to the queued build atomically.

SQL metadata alone cannot prove the contents of an object, so the isolated builder checksum-verifies downloaded objects. See source ingestion for limits, cancellation and replay behaviour, and local-storage assumptions. A deployment’s manifest, plan and source identity cannot be edited in place. A changed checkout needs a new deployment.

publish_release_artifact is a private invoker-security function, with PUBLIC execution revoked. The agent gateway gets the database privileges for it. An untrusted build container or a browser never does. The function accepts only:

  • an exact digest under the snapshot’s organization- and project-scoped repository,
  • a matching targeted build job, source snapshot, plan and preassigned artifact_id,
  • an active, fresh, authorized build-pool node with the isolated-build capability.

Ingestion persists the output artifact identity before dispatch, so retries never invent another identity after a lost response. Authorization and the wall-clock lease are checked again after waits. An exact replay is allowed only under current authorization. Substitutions are rejected. The artifact, the immutable role and replica intents, and untargeted ensure_application jobs commit together. They do not allocate capacity, start containers, publish routes or signal ready. There is no public endpoint that adopts an image. The configured ingester selects the registry origin. A scoped repository suffix alone is not registry trust.

The scheduler targets verified builds to isolated build-pool nodes. The agent builds them with rootless BuildKit and pushes the exact digest. The gateway calls this function inside the completing transaction. See the build executor for the isolation decision, the registry credential boundary and the native Linux proof.

Tenant policies allow reading these records. They do not allow asserting verification, inserting artifacts or creating runtime intents. npm run test:release-artifact (in test:all) uses a disposable migrated database. It tests atomic publication and replay, invalid build, source, image and tenant provenance, and immutable input and history. It also tests tenant read and write isolation and real resource-lock waits that cross lease and node-freshness boundaries.

Typed ApplicationTask contracts reject unknown nested role fields, tags and unscoped images, unsafe resource limits and health paths, and mismatched execution identities. Their scope must come from authenticated durable placement state. Validation of the intrinsic shape is not authorization.

Application placement

Migration 0022 and the scheduler reserve application-pool capacity plus one gateway allocation per host and environment. They prepare immutable membership without running workloads. An idle member of a sealed network leaves it after a day, and its gateway capacity is released (member removal, migrations 0147 and 0148).

  • Each role replica reserves its manifest resources (default 500 millicores/512 MiB), plus 500 millicores/256 MiB gateway overhead per host and environment.
  • A role larger than every application node is refused at once.
  • Existing reservations do not move silently when a host becomes unavailable.
  • Initial topology eligibility covers the application and database pools.
  • Sealing waits for active deployment artifacts and all application-role reservations, as well as database reservations. So a fast database reservation cannot seal before a slower build produces application intents.

Migrated PostgreSQL tests cover application-only bootstrap, mixed build and placement barriers, capacity accounting, exclusion of other organizations’ hosts, and reservation replay without permission to execute. A sealed network adds an application host through a fenced topology revision. Gap: resizing, and adding a database host.

Application runtime admission

The scheduler targets an ensure_application job to the host that holds its deployment_role reservation. It does this only when ready_network_attachments holds fresh independent evidence for that host and environment, the same predicate that database work uses. Targeting activates the role and gateway allocations, marks the instance deploying with that active_node_id, and publishes a typed EnsureInstance task.

The agent gateway (crates/pushleft-agent-gateway/src/applications.rs) leases, renews and completes the job only for the node that owns the active allocation of a live deployment. It rebuilds the task from durable instance, artifact, snapshot, segment and allocation state, and requires exact payload equality. Leasing also requires fresh admission. Results update the instance only for the matching generation and owning node (healthy success is ready, everything else is error). The gateway alone decides instance status.

The agent (crates/pushleft-agent/src/application.rs) validates the task and its leased tenant envelope, and pulls only repo@sha256: images. It runs one container per generation, pl-app-<instance>-g<generation>:

  • labelled with organization, environment, deployment, instance, generation and spec hash,
  • attached only to pl_<segment>,
  • with --cpus, --memory, --memory-swap and --pids-limit (threads count too: 128 up to 512 MiB of memory, then one per 4 MiB, at most 4096),
  • --read-only plus bounded noexec tmpfs mounts (/tmp and the role’s tmpfs),
  • --cap-drop ALL, no-new-privileges and no published ports,
  • no mounts other than the role’s declared volumes and its read-only /run/secrets (see Application manifest).

Health. A role with a health check is healthy after an in-network HTTP probe (busybox wget). For health: tcp, the probe is a busybox nc -z connect to the role’s port. The probe runs from the digest-pinned PUSHLEFT_APPLICATION_PROBE_IMAGE in deploy/images.lock.env (Alpine 3.24.2, scanned by scripts/runtime-image-scan.sh; --application-probe-image overrides it). Workers and private roles without a health path are healthy after process liveness. Both must pass within the role’s startup_timeout (default 60 seconds). A missed deadline is a permanent unhealthy failure, because the same release would fail the same way. Docker and pull errors stay retryable.

Replay and lease loss.

  • Replay adopts an exact matching container, replaces a drifted one of the same generation, and refuses a stale generation.
  • Older generations are removed only after the new one is healthy.
  • On lease loss, a heartbeat conflict or a completion conflict, the agent may stop the container. It stops it only if this attempt created or started it and it was not yet healthy (an unfinished rollout). An adopted running or already-healthy generation keeps serving, and the agent only logs the loss (application::stop_on_lease_loss).

npm run test:application-runtime exercises this on real Docker with a local registry and a per-run private network. Its control-plane admission is out of scope. The migrated tests in npm run test:application-placement stub admission evidence in SQL, as scripts/scheduler-e2e.sh does. The PID limit (128) is fixed. The staging fleet covers secrets, resources and cross-host database access (scripts/staging/staging.sh smoke and isolation, staging runbook).

One-shot roles

Cron, job and release roles reserve their own resources envelope the same way. They wait for the same admission and for their databases. On admission, the scheduler marks the instance ready on its host and keeps the durable container spec on the completed placement job. It publishes no service task.

crates/pushleft-scheduler/src/runs.rs then enqueues run_application jobs (typed RunApplicationTask, run_id = job id) targeted to that host:

  • release and job run once per deployment.
  • cron runs on its five-field UTC schedule (CronSchedule, Vixie day-of-month/day-of-week OR). A second run of the role is never queued or leased at the same time (overlap prevention under the instance row lock). After downtime or overlap, only the most recent missed tick runs.
  • Long-lived roles are not targeted until the deployment’s release run has completed successfully. A terminal release failure fails the deployment.

The gateway (src/runs.rs) leases runs only to the owning node, with fresh admission and a spec equal to durable placement. The agent (src/runs.rs) runs the same hardened container for at most MAX_RUN_SECONDS (3600). The container runs with --restart no, read-only, cap-drop ALL, limits, environment network only, no ports, and the same secrets and volumes.

  • It captures a bounded 16 KiB log tail and reports the exit code, duration and log.
  • It removes the container on every exit path, lease loss included.
  • A non-zero exit or a timeout is a permanent failure, and is never retried automatically. Agent and infrastructure errors retry, so delivery is at-least-once.
  • Every result is an application_run_succeeded/application_run_failed deployment event.
  • If the agent restarts while the run’s container exists, the run is adopted and not repeated.

Teardown

pl down sets teardown_queued. Traffic is removed first: the scheduler waits until no ingress route of the deployment is still publishing, active or draining. It then:

  • enqueues one teardown_application per targeted instance and recorded generation (idempotency application:<id>:teardown:<generation>), aimed at active_node_id,
  • marks the instance draining,
  • cancels its queued ensure and run work.

The gateway leases the teardown only to that node, only for the recorded generation, and only while the deployment is teardown_queued. Stopping containers needs no network admission. The agent removes every container of that instance up to that generation, plus its probe and run containers. It refuses a newer generation, or a container labelled for another organization or deployment.

Only an accepted removal marks the instance removed and releases its deployment_role allocation. The other paths to removed are:

  • pre-seal reservation reclaim,
  • a stopped superseded or failed release,
  • a finished release or job run. When the agent reports the run’s final attempt, the scheduler marks that instance removed, releases its allocation and appends application_removed with code: run_finished.

A terminal failure leaves the instance error, with capacity held. Artifacts, snapshots, events and allocation history are kept. Only the environment network teardown below releases the environment gateway capacity and membership.

npm run test:application-lifecycle (scripts/application-lifecycle-e2e.sh) drives the real scheduler, mTLS gateway, agent and Docker. It runs release-before-web, a failing job (exit 7) and a cron run that skips the next minute while it runs. It ends with a teardown mid-run that leaves no labelled Docker objects. Admission evidence is stubbed in SQL.

Gaps: cron catch-up beyond “latest missed tick”, time zones and @macros, per-role resource plans and runtime limits, and release of cron capacity between runs. Parallel runs and live log streaming are also gaps. The agent workload lane is serial, so a long run delays other work on that host.

Environment network teardown

Migration 0035, crates/pushleft-scheduler/src/network_teardown.rs, crates/pushleft-agent-gateway/src/network_teardown.rs and NetworkManager::teardown in the agent implement this. The order is: routes removed, then containers (above), then the network.

When it starts. The scheduler looks at the environment’s current segment once every instance of a teardown_queued deployment is removed. None of its routes may be publishing/active/draining.

  • If another deployment of the environment is still active (queued through degraded), or one of its database instances holds capacity, the shared network is kept. The deployment becomes destroyed at once (deployment_destroyed, environment_network: retained).
  • If another torn-down deployment is still removing containers, the scheduler waits, so both share one network teardown.
  • Otherwise, in one transaction:
    • the segment becomes destroying (irreversible; a trigger refuses any other move),
    • queued network work for its attachments fails,
    • each unreleased attachment gets one manage_network job targeted at its node, with idempotency network:<attachment>:teardown. Its task remove_environment_gateway comes from the SQL function network_teardown_task (gateway name, bridge pl_<segment>, state path from the prepared gateway task or none, generation).

Lease checks. The gateway leases, renews and accepts the job only while network_teardown_authorized holds:

  • the authenticated node owns the unreleased attachment,
  • the segment is destroying,
  • environment, generation, credential revision and the task equal durable state,
  • no deployment of the environment is active,
  • no other network attempt for the attachment holds a live lease.

What the agent removes. The agent’s network lane removes these, in order, and only when they are labelled for this environment:

  1. the gateway container (after a best-effort tailscale logout),
  2. host routes and the nftables table (Linux only): owned-protocol rules and routes and the pushleft:<environment> table, then their fences, so a later network starts fresh,
  3. the bridge (Docker refuses while a running container is attached, which is a retryable failure),
  4. the mesh state directory (marker-checked, confined to the state root) and key material.

Each step treats “already gone” as done. So a crash between steps, and a new lease, converge. Foreign objects are refused (container, state) or left and reported (bridge: foreign_retained).

The receipt. The receipt (status: removed plus per-step evidence) sets the attachment’s gateway_status='removed', released_at and teardown_evidence. When no unreleased attachment remains, finish_environment_network_teardown:

  • releases the memberships (network_attachment_requests.released_at) and their network_attachment capacity. The subnet slot is kept, and the sequence never rewinds,
  • marks the segment destroyed,
  • moves every finished teardown_queued deployment of the environment to destroyed, with deployment_destroyed.

A segment without attachments never dispatched host work. It is released the same way without a job.

Failure. The job’s attempts bound the retries. A terminal failure, or an expired final lease, runs fail_environment_network_teardown. The deployments become teardown_failed (deployment_teardown_failed), the segment stays destroying and capacity stays held. A repeated pl down does not hide it. Released rows refuse any update or delete.

After teardown. A destroyed segment is history. network_segments is unique per environment only while not destroyed. So the next deployment of the environment gets a new segment, with a new bridge, new gateway names and new subnet slots. A deployment created while the segment is destroying is refused with 409.

Tests.

  • npm run test:application-placement: scheduling waits for removal, the shared network is kept, attachment-free release and lease fencing against other nodes. It also covers forged tasks and active siblings, receipt release and slot burning, bounded failure.
  • The agent unit test teardown_is_replay_safe_and_owner_scoped: an interrupted teardown converges, and foreign state is refused.
  • npm run test:application-lifecycle (live): a labelled gateway stand-in and the bridge are removed, destroyed, slot burned.
  • npm run test:pl-up-demo: destroyed, then a redeploy on a new segment with a higher slot.

Gaps: deleting the node record on the Headscale coordinator (the agent only logs the gateway out) and any Linux run of nftables and route removal. Operator retry of teardown_failed is missing, and so is release of role capacity held by failed deployments. pl down does not finish for a deployment whose instances were never placed. They stay pending_placement/reserved, so the deployment stays teardown_queued.

Ingress publication

The scheduler (crates/pushleft-scheduler/src/ingress.rs) publishes only after durable health. Every web instance of a deployment, across all web roles, must be ready on the node that holds its active deployment_role allocation. The gateway writes ready from a fenced result.

Hostnames. The hostname is derived, never taken from the manifest:

  • previews: <branch>--<project>--<handle>.<base>. The preview/ prefix of the environment slug is stripped. Over-long labels keep the organization handle and a stable hash suffix.
  • production: <project>--<handle>.<base>.

<handle> is the organization’s immutable unique handle (migration 0046; environments that claimed a name before it keep that name). <base> is the operator’s PUSHLEFT_PREVIEW_BASE_DOMAIN. Without that variable, nothing is published. The first environment to publish a hostname owns it in ingress_hostnames (migration 0025). Any other environment or organization that derives the same name gets ingress_rejected and a failed deployment. Each web role is routed as its route: sets (routes), and its replicas are the upstreams.

Publication. Each publication takes the next route generation for the hostname. It writes one publishing row in ingress_analytics_routes and one typed publish_ingress job per node, which holds the exact task.

The agent gateway (crates/pushleft-agent-gateway/src/ingress.rs) leases and completes that job only while:

  • the payload equals the durable task,
  • the route is still publishing,
  • no newer generation for the host and node was ever active,
  • the node is not owned by another organization,
  • each upstream instance is still ready at the routed generation on that node, with an active allocation.

A lease that fails these checks makes the job, the route and the not-yet-live deployment fail (ingress_failed). A completion that fails them returns 409 and records nothing.

The agent (crates/pushleft-agent/src/ingress.rs, --caddy-admin) inspects each pl-app-<instance>-g<generation> container. It requires its organization, environment, deployment, instance and generation labels and running state, and reads its address on pl_<segment>. It writes the route through CaddyClient (ETag compare-and-swap plus exact readback) into the operator bucket pushleft-ingress-router.

  • Caddy route IDs are pl-ingress-<hostname>-g<generation>-o<org>. The Caddy client refuses to publish or remove a hostname whose route carries another organization.
  • A newer generation already in Caddy makes the task permanently stale.
  • A new generation goes in front of older ones (first match wins). So the old route keeps serving until its own exact-generation removal.

Activation. On success, the gateway demotes the previous active route to draining and activates the new one. A trigger rejects activation behind a newer generation, identity rewrites and backward status moves. A unique index allows one active route per host and node. When all of the deployment’s routes are active, the gateway sets the deployment live and appends deployment_url_ready with the URL.

  • The previous live deployment becomes superseded.
  • Older deployments of the environment that are still building become cancelled, so they can never publish later.
  • A held deployment (pl up --hold, migration 0251) is built and has its instances, but placement skips them until pl release sets released_at, so it takes no capacity and the live release keeps serving. The scheduler marks it held once its artifact exists, and cancels it when hold_expires_at (24 hours) passes. held counts as active (deployment_is_active). A newer production deploy cancels it; a newer held deploy cancels only held deployments not yet released (release after tests).
  • The scheduler then queues an exact-generation remove_ingress for each draining route, or for a failed publication that may have run. After the route is removed, it queues one stop_application per node.
  • A failed release is stopped the same way. An unfinished publication of it is marked failed. Its roles that never reached a node are released at once when the network is already sealed (before that, reap_unstarted_application does it).
  • No stop is queued while an ensure or run of the release is leased on that node.
  • The agent stops the owned containers with docker stop and does not delete them. The gateway marks the instances removed and releases their role capacity.
  • The previous live release keeps its own instances and capacity. Artifacts, instances, routes and events stay as history.
  • Teardown (teardown_queued) drains active routes first. The fenced teardown work stops the containers of a torn-down deployment.
  • A release that fails before live never touches the previous route.

What you see. The API returns url on GET /v1/deployments[/{id}] only from an active route row, and pl list prints it. The tenant RLS policy on routes is read-only. pl up follows the SSE stream by default (--detach returns after queueing). It prints build_*, application_ready/application_failed (appended by the gateway), ingress_* and the final URL. It exits non-zero with the bounded log tail on a terminal build_failed, application_placement_rejected, application_failed, ingress_failed or ingress_rejected.

Rolling releases

A new deployment is blue/green (since 2026-10-25):

  • Its instances start beside the old release’s instances.
  • Every web replica must be healthy before its route publishes. Every worker and private instance must be ready too (since 2026-11-13).
  • A route generation is activated before the older one on that node drains.
  • When every route of the new release is active, the older releases of the environment drain for the same hostnames. They drain on every node, including nodes that the new release does not use. They are then superseded.
  • A release without a web role goes live when every worker and private instance is ready. It supersedes the older ones the same way.
  • A superseded release keeps running for a drain of 30 s (DRAIN_SECONDS in crates/pushleft-scheduler/src/ingress.rs) after its last route is removed. It then gets SIGTERM and the 10 s stop timeout.

Removing a route reconfigures Caddy gracefully, so requests already in flight finish. Every route’s reverse_proxy has passive health checks: an upstream that refuses connections twice is skipped for 30 s. Its own 502–504 answers do not count: an app may pass on another server’s 502 (an image proxy), and its only replica would then be skipped too. It retries a request whose dial failed on another replica for up to 5 s. Caddy retries only requests that it could not send. A repoint after a database move replaces instances the same way, one at a time (relocation).

Gaps: weighted canaries, per-service deploys (every deployment replaces every role) and active health checks.

Ingress TLS

This covers custom domains and wildcard previews (migration 0036). The ingress Caddy runs the base configuration that pushleft-agent ingress-caddy-config prints (ingress_base_config in crates/pushleft-mesh/src/caddy.rs):

  • One server, pushleft-ingress, listens only on :443. Its routes are the pushleft-ingress-router bucket, then a terminal 404.
  • Automatic HTTPS stays on. So Caddy adds the TLS connection policy, and a port-80 server that only answers ACME HTTP-01 and redirects everything else with 308 to https://.
  • apps.tls.certificates.load_files and .automate start empty and belong to the agent.
  • On-demand TLS is never configured, so no SNI name can make Caddy order a certificate by itself.

--acme-ca/--acme-email/--acme-trusted-root/--acme-challenge set the issuer for custom domains (default: Caddy’s Let’s Encrypt, then ZeroSSL). With PUSHLEFT_INGRESS_TLS=1 or the wildcard files, the agent fails a publication closed (ingress_tls_unconfigured). The exception is a server that holds the bucket and listens only on the HTTPS port, with automatic HTTPS and redirects on. It never falls back to plain HTTP.

  • Preview wildcard, mode (a), implemented and tested. PUSHLEFT_INGRESS_WILDCARD_CERT_FILE/_KEY_FILE are absolute paths that the agent and Caddy both read. Before every preview publication, and every 30 s in pushleft-agent run, the agent parses the certificate. It refuses an expired one, or one whose DNS SANs do not cover the hostname (wildcard_certificate, RFC 6125 single-label *). It keeps exactly one load_files entry tagged pushleft-ingress-wildcard plus sha256:<certificate digest>. A renewed file changes the tag, and Caddy then reloads both files. The agent never reads, logs or sends the key through the admin API. Names that a loaded certificate covers are never ACME-managed.

  • Preview wildcard, mode (b), an operator option that Pushleft does not implement. The pinned image (caddy@sha256:13b7fb…, v2.11.6) has no dns.providers.* module (caddy list-modules). DNS-01 cannot run in it. An operator who wants Caddy to get the wildcard:

    1. builds xcaddy build v2.11.6 --with github.com/caddy-dns/cloudflare (zone-scoped Zone.DNS:Edit token),
    2. adds *.<base> to apps.tls.certificates.automate with an automation policy {"subjects":["*.<base>"],"issuers":[{"module":"acme","challenges":{"dns":{"provider":{"name":"cloudflare","api_token":"{env.CF_API_TOKEN}"}}}}]},
    3. runs the agent with PUSHLEFT_INGRESS_TLS=1 and no wildcard files.

    Pushleft then checks only that the server is HTTPS-only. The repo’s pushleft-cloudflare client is not wired into Caddy.

  • Custom domains (custom domains on an environment).

    • POST /v1/custom-domains {hostname, project, environment} (member+, admin+ for production, pl domain add) records a pending_verification claim with a random 128-bit token. GET/DELETE and pl domain list|show|remove read and remove it. RLS lets the tenant only insert pending claims and set removed.
    • The scheduler runs its own loop (crates/pushleft-scheduler/src/domains.rs, every 5 s, at most 8 checks, outside placement ticks). It asks the resolver in PUSHLEFT_DOMAIN_VERIFY_NAMESERVER (default: /etc/resolv.conf, then 1.1.1.1). It uses UDP with a random query ID, a 3 s timeout and 2 tries. It looks for TXT _pushleft-challenge.<host> equal to the token, or else a CNAME from the host to the environment’s derived preview hostname.
    • Failures back off from 15 s to 10 min. The claim fails after verify_by (72 h). Each distinct reason, the verification and the failure are custom_domain_events.
    • A verified claim is unique across organizations (partial unique index). A name that is another environment’s preview hostname, or is under the preview base domain, fails. Both sides of a custom/preview collision take one advisory lock.
    • Verified names go with every new release (one route per hostname and node, managed_certificate: true in the task). A name verified after go-live is attached to the live release once.
    • The gateway leases such a route only while the claim is still verified/active for that organization and environment. The route fence accepts custom-domain ownership on insert and on activation only.
    • Activation sets the claim active. Only then does the agent add the name to Caddy’s automate list, and Caddy gets the certificate with HTTP-01 or TLS-ALPN-01.
    • A generation switch never touches automate, so the certificate is not issued again. Removing the last route of a name removes it from automate.
    • DELETE sets removed. The scheduler drains (or fails) its routes, the deployment stays live on its preview URL, and the claim’s history is kept.
    • deployment_url_ready and pl up/pl list keep the derived preview URL.
    • A custom route that fails on a release that is already live leaves the release live and records custom_domain_route_failed.
  • Uploaded origin certificates. An exact custom domain can take an uploaded certificate too (pl domain certificate). An example is Cloudflare’s Origin CA behind its proxy, where ACME cannot run before DNS points here. When one exists, its routes carry origin_certificate in place of ACME automation, and an earlier automate entry for that name is dropped. The rest of the next item applies to exact names too.

  • Wildcard custom domains (migration 0099). A claim can be *.<name>, which covers exactly one label.

    • Only the TXT record on <name> proves it. A CNAME cannot, because the name is often Cloudflare-proxied.
    • It is routed (with the release, or attached later) only after its organization has uploaded an origin certificate: PUT /v1/custom-domains/{id}/certificate (member+, admin+ for production, pl domain certificate).
    • The API accepts the upload only when the leaf passes three checks. It names the wildcard itself, is valid for at least another 7 days, and carries the key’s public key.
    • The PEM goes into custom_domain_certificates (append-only, and the newest row is served). The key goes to Vault at origin_key_secret_ref(org, certificate).
    • The route task carries managed_certificate: true plus origin_certificate {certificate_pem, key_secret_ref}. IngressRoute::validate refuses a wildcard without it, or with a key reference outside the route’s organization.
    • Before it wraps the key for the node at lease time, the gateway checks that the reference and the PEM are that claim’s upload.
    • The agent loads the pair into apps.tls.certificates.load_pem before the route. Caddy’s automatic HTTPS skips names that a loaded certificate covers, so a wildcard never reaches ACME.
    • A newer upload republishes the live routes at a new generation, and activation drains the old one. A failed republication is not retried until the next upload or release. Removing the last route drops the entry.
    • Exact hostnames always go ahead of wildcard routes in the bucket, so a wildcard never shadows a.<name> routed on its own.
    • The key is in Caddy’s config (admin API on loopback, autosave beside Caddy’s own ACME keys).
    • Behind Cloudflare, the edge serves Cloudflare’s certificate, and the origin leg is verified against Cloudflare’s Origin CA.
    • Gap: a tenant whose zone is not on Cloudflare needs a publicly trusted wildcard certificate of its own, because no DNS-01 issuance is built. Abuse lookups by exact hostname (0052) do not resolve a name under a wildcard yet (abuse reports).

Operator duties:

  • with one application node, the DNS record *.<base> (A/AAAA) to it, created by hand. With more, the controller writes one A record per platform hostname to the node holding its route (PUSHLEFT_PLATFORM_DNS_ZONE_ID, built 2026-11-03). The wildcard can stay as the fallback for names not yet recorded,
  • ports 80 and 443 reachable from the internet for custom-domain ACME,
  • renewal of the wildcard certificate (mode a), until platform certificates replace it,
  • Caddy’s reachability to the environment bridges (not yet proven on native Linux with the environment nftables policy).

URLs use https://. Only the RFC 6761 .localhost development domain stays plain HTTP, unless the scheduler runs with PUSHLEFT_INGRESS_HTTPS=1.

Tests.

  • npm run test:ingress: plain HTTP on .localhost, routing and generation fencing.
  • npm run test:ingress-tls (scripts/ingress-tls-e2e.sh): the generated config in the pinned Caddy, fail-closed on a plain-HTTP listener, the wildcard served and verified with curl --cacert, the 308 redirect, refusal of uncovered names, hot reload, the scheduler’s DNS check against scripts/fixtures/dns-stub.py, no certificate for unrouted SNI names, a real ACME HTTP-01 order from a local ACME CA (a second pinned Caddy running acme_server, rooted in a per-run CA), a generation switch without a new issuance, and automation removed with the last route.
  • npm run test:pl-up-demo runs the whole path over HTTPS, including pl domain add → stub TXT → verified → attached → ACME → HTTPS → pl domain remove.
  • The migrated tests (npm run test:application-placement, domains_tests and gateway ingress::) cover the verification state machine, cross-tenant collision, unverified or removed names that are never leased, and drain, supersede and rollback with custom routes.

Platform certificates

Each platform hostname (one label under the preview base, <name>.apps.pushleft.dev) gets its own certificate on each application node that routes it (decided 2026-11-06, migration 0150). This replaces the shared *.<base> wildcard, whose private key every application node held: root on one node could serve any tenant’s platform hostname. Now a node holds keys only for the hostnames it routes, and a key never leaves its node.

Browsers connect straight to the node (the per-hostname A record is not proxied), so the certificate must be publicly trusted. Cloudflare’s Origin CA cannot be used. The certificates come from Let’s Encrypt through ACME with a DNS-01 challenge in the platform zone.

  • Agent (PUSHLEFT_INGRESS_PLATFORM_CERTS=1). Before it publishes a route for a platform hostname, the agent loads or creates <PUSHLEFT_INGRESS_KEY_DIR>/<hostname>.key (default /var/lib/pushleft/ingress-keys, the directory 0700, the key 0600, ECDSA P-256). It sends a CSR with exactly that one DNS name and no subject to POST /v1/agent/ingress/certificate {hostname, csr_pem}.

  • Agent gateway (mTLS agent listener, PUSHLEFT_PREVIEW_BASE_DOMAIN set). It refuses a node that is not active or not in the application pool, a hostname that is not exactly one label under the base, a hostname this node has no publishing or active route for (of a plain platform route: not a custom domain, no uploaded certificate), and a CSR that does not verify, is not P-256, is over 4 KiB or names anything but the hostname. Then it records a pending row in platform_certificates (one live row per hostname and node). It answers 200 {certificate_pem, not_after} when that node’s row is issued and valid for more than 7 days, else 202 {status: "pending"}. A changed CSR (the node lost its key) puts the row back to pending. A certificate goes only to the node its row names. Without the base setting, or on an older gateway, the answer is 404, and the agent keeps the wildcard path.

  • Controller (crates/pushleft-controller/src/platform_certificates.rs, PUSHLEFT_PLATFORM_CERTIFICATES=1, its own task every 10 s, at most 4 rows a pass). It needs the platform DNS settings (zone id, zone, base) and Vault. The ACME account key is at vault://platform/acme/<directory hash>#credentials (KV v2 mount platform), created on first use. The ACME client is instant-acme over the workspace’s rustls reqwest. For a due row, the controller creates an order, writes TXT _acme-challenge.<hostname> with its own Cloudflare token, waits PUSHLEFT_ACME_DNS_WAIT_SECONDS (10), marks the challenge ready and polls. Then it finalizes with the stored CSR and deletes the TXT record (also after a failure). It stores the chain and not_after only if the row’s CSR is still the one it ordered with.

    • A failure backs off 5 minutes, doubling to 6 hours. Let’s Encrypt allows 5 failed validations per hostname an hour.
    • Renewal: an issued row is ordered again at 30 days left, with the same CSR.
    • Moves: a node keeps its key and certificate when the hostname’s route moves to another node. A move back reuses them, with no new issuance. The controller renews a certificate only while its node routes the hostname. This applies to platform and customer-owned nodes (decided 2026-11-10: issuance on every move reached the weekly limit).
    • Revocation: when the hostname has had no publishing, active or draining route on any node, and no route of it changed for 10 minutes, the controller revokes every node’s certificate for it (reason cessationOfOperation) and marks the rows revoked. After 5 failed revocations it marks it anyway; the certificate expires on its own. A pending row whose route went away becomes failed.
  • Publication. An issued certificate is checked (it names the hostname, has not expired, and matches the node’s key) and loaded into Caddy’s load_pem as for an uploaded origin certificate (one entry tagged host:<hostname>). Caddy prefers an exact-name certificate to the wildcard. While the certificate is pending:

    • with the wildcard files configured (the rollout bridge), the route is published under the wildcard;
    • without them, the job asks every 5 s for up to a minute, then fails retryably, so the route stays publishing and never activates without a certificate. The job has 5 attempts, about 8 minutes in total.

    So a route moving to another node has its certificate before it activates there, and before the controller points DNS at that node.

  • The 30 s loop. Every hostname with a key on the node, and no certificate valid for 30 more days (<hostname>.crt beside the key), asks again. This loads the first certificate after the wildcard bridge, and each renewal.

  • Removal. When the last route generation of a hostname is removed from a node, the agent drops its load_pem entry and deletes the key and certificate files.

  • Limits. Let’s Encrypt allows 50 new certificates per registered domain (pushleft.dev) a week. The platform_certificates_weekly_limit alert pages at 40, and the controller logs a warning. A Public Suffix List entry for apps.pushleft.dev (planned) makes each tenant hostname its own registered domain. What remains then is 5 certificates per exact hostname a week: a hostname that moves to new nodes more often than that waits (on the wildcard while it exists). platform_certificate_stuck opens a ticket for a row pending over 30 minutes, or an issued one within 14 days of expiry.

  • Accepted: every platform hostname, including branch names in preview hostnames, appears in public Certificate Transparency logs (decided 2026-11-06).

  • Not used: Caddy on-demand TLS stays absent, and base_config_is_https_only_without_on_demand_tls keeps it so. No SNI name can make a node order a certificate.

Rollout, then wildcard removal (a later step). The wildcard code paths stay until every application node has run with the flag:

  1. Control plane: migrate (0150); enable the platform KV v2 mount in OpenBao if it is missing, and rewrite the pushleft-controller policy; set PUSHLEFT_PREVIEW_BASE_DOMAIN in agent-gateway.env and PUSHLEFT_PLATFORM_CERTIFICATES=1 (plus PUSHLEFT_ACME_CONTACT) in controller.env; restart both.
  2. Each application node, one at a time: PUSHLEFT_INGRESS_PLATFORM_CERTS=1 with the wildcard files kept; restart the agent. Check that every hostname the node routes serves its own certificate: openssl s_client -connect <node ip>:443 -servername <hostname> </dev/null 2>/dev/null | openssl x509 -noout -subject -ext subjectAltName -issuer -enddate shows only that hostname.
  3. When every node serves per-hostname certificates: remove the wildcard settings (PUSHLEFT_INGRESS_WILDCARD_*) from the agents, delete the wildcard files on the nodes, remove the apps entry from wildcard.env and the gateway’s wildcard settings, and revoke the apps wildcard at Let’s Encrypt (lego ... revoke). Then remove GET /v1/agent/ingress/wildcard, refresh_wildcard and the apps part of scripts/wildcard-renew.sh from the code.

Tests. Gateway ingress:: (migrated PostgreSQL): no route, another node of the same or another organization, wrong or extra SAN, wrong key type, a name not one label under the base, a custom domain, a draining or non-application node are refused; an issued certificate goes only to its node and only while it is valid for more than 7 days; a second node gets its own row; a new key asks again. Controller (migrated PostgreSQL, a mocked ACME CA and Cloudflare): failure and backoff, issuance, no work while far from expiry, renewal at 30 days, kept 10 minutes after the route went away and then revoked, and a pending row failed without an order. npm run test:ingress-tls also orders a real certificate from Pebble over DNS-01: the TXT records go through a Cloudflare API stub into pebble-challtestsrv, the certificate is for the CSR’s key, the records are deleted, and it is revoked once. Agent unit tests: key and directory modes, a CSR with one DNS name and the same key on every request, pending publications under the wildcard or failing retryably, and removal deleting the files.

The tests do not prove public DNS, Let’s Encrypt/ZeroSSL, 80/443 reachable from the internet, or DNS-01.

Gaps:

  • A custom domain is active once it is routed. Caddy issues its certificate asynchronously. ingress_certificate_invalid/_expiring (scripts/ops-alerts.sh with PUSHLEFT_OPS_INGRESS_ADDRESS) is the evidence that it was issued and renews.
  • A verified custom-domain claim blocks every other organization until its owner removes it. There is no takeover by re-verification.
  • TXT proves control of the zone. It does not prove that the name points at the ingress. ACME keeps failing (Caddy retries) until A/AAAA or the CNAME is in place.
  • Pushleft does not create the tenant’s DNS records, even for zones that it manages in Cloudflare.
  • A restarted container whose bridge IP changes needs a new publication. There is no periodic route reconciliation.
  • The agent verifies by admin readback, and not by an HTTP probe through Caddy.
  • Hostname ownership is first-claim. A managed service needs reserved project namespaces per organization.

Reservation recovery for terminal deployments

The scheduler has a narrow recovery path for terminal deployments. It can release reserved application capacity only when all of these hold:

  • the topology is not sealed yet,
  • no network attachment or enrollment exists anywhere in the segment,
  • the instance has no execution target, lease history, attempt, executable task or agent result.

It then marks the unused instance removed and keeps the released allocation history. Shared gateway capacity and membership stay until no database or application allocation remains for that environment on the host. Subnet sequence slots are never recycled. Sealed or prepared networks and previously dispatched workloads still need fenced teardown. Tests cover shared live deployments, rejection of an unsupported second role, refusal after dispatch or sealing, concurrent capacity reservation, and an uncommitted membership transaction that races topology sealing.

Completion criteria

The slice is complete when it has:

  • production-capable authentication and tenant authorization,
  • isolated source ingestion and build with immutable image provenance,
  • capacity-bounded application placement,
  • private networking with independent firewall and admission evidence,
  • healthy ingress, DNS and TLS publication,
  • streamed real build and runtime events.

Verify it with a web-only repository from the real CLI and tenant-negative tests. Also verify rollback after a failed build, start, health or route, restart and reconciliation replay, and fenced teardown. Do not call pl up operational only because a job is queued or an image-only fixture is green. The existing credential and network safety gates stay required. They do not replace this vertical slice.

npm run test:pl-up-demo (pl up demo) runs this verification on real processes. The run uses production auth behind the TLS-evidence proxy, pl login/up/list/down, rootless BuildKit to a token-auth registry, scheduler placement, the mTLS gateway, the Docker runtime and Caddy ingress. It covers:

  • a URL that serves the built image,
  • agent and scheduler kills, including one mid-rollout that the leased-again task adopts,
  • a second release that drains the old route and keeps its artifact,
  • cross-organization, viewer and revoked-token refusals,
  • failed build, start, health, hostname and tampered-source cases that leave the live route untouched,
  • fenced teardown back to Caddy’s 404.

Gaps in the demo: network admission is stubbed in SQL (no Headscale, gateways, nftables or host routes). The run uses Docker Desktop and not native Linux. There is one host per pool and no multi-host transport. Traffic is HTTPS with a per-run wildcard and a local ACME CA (no public DNS, Let’s Encrypt or 80/443 reachable from the internet). All services share one database role. Environment network teardown runs only against stub networks (no nftables, host routes or Headscale). The staging fleet covers the real network admission chain on five VMs.

Slice 3: production substrate

  • Two-region placement, canary (weighted) traffic, quotas and metering.
  • Managed PostgreSQL/ClickHouse backup and restore, PITR, restore drills, control-plane restore requests, fenced PostgreSQL relocation, the runtime policy upgrade and PostgreSQL major upgrades with rollback. All of them are implemented and proven on Docker Desktop. Sealed backups and the off-host copy to R2 are built. Plan: ClickHouse upgrades, an upgrade path for large clusters, and a volume replication and migration policy.
  • Vault/OpenBao transit and dynamic credentials.
  • Cloudflare proxy and WAF automation, custom-domain ACME, and outbound MTA/ESP routing (customer mail). Openprovider registration and Cloudflare DNS onboarding were implemented in slice 1.
  • An AI provider gateway with BYOK and metered-proxy modes.
Rendered from the repository at build time. Edit docs/architecture.md to change it.