Managed databases
Pushleft runs PostgreSQL, ClickHouse and Valkey for each environment of your project. You declare the databases in .pl.yaml, and every role that lists one gets its connection variables. The data outlives each deployment, and Pushleft backs it up every day.
Quick start
-
Declare a database in
.pl.yamland list it on the roles that use it (manifest):roles: web: databases: [app] data: postgres: plan: starter databases: [{ name: app }] -
Read the connection from the environment. A role that uses exactly one PostgreSQL database gets
DATABASE_URLand thePG*variables. -
Deploy. The first deployment creates the database, its owner and its login:
pl up --production -
Find the database ID and its last backup:
pl db list -
Optional: load existing data from another host with a
pg_dump -Fcarchive:pg_dump -Fc -f app.dump "$SOURCE_DATABASE_URL" pl db import <db> app.dump -
Optional: take a backup now, or restore to a point in time:
pl db backup <db> pl db restore <db> --at 2026-10-29T12:00:00Z pl db status <db>A restore creates a new copy beside the running database. Your application keeps writing to the source (Restore requests and relocation).
-
Optional: connect from your machine (admin). It forwards the database’s port to
localhostuntil you press Ctrl-C, for up to four hours. It prints the address without the password (connect to a database):$ pl db connect <db> postgres://[email protected]:54012/appPoint
psqlor a database GUI at that address, with the password from the role’sDATABASE_URL.
Features
- Plans from
devtoxlarge(Plans). You can set a larger initial disk withdata.postgres.disk, up to 1 TiB (Placement and lifecycle state). - Data that stays when a deployment goes.
pl downleaves the databases in place (Deleting a database). - A preview database is released 7 days (by default) after its last deployment ends. A production database stays until you run
pl db delete. - In production, a daily base backup, encrypted with your organization’s key and checked by a restore drill. Backups are kept 1 day on the database’s host and longer in the off-host bucket (R2) (Backups, PITR and restore drills).
- Point-in-time restore for PostgreSQL in production. Archived WAL bounds the recovery point to five minutes on an idle server.
- Named datasets that switch a test environment’s data with
pl db load(Named datasets). - Checkpoints of a test environment: save every database, and later restore the checkpoint or production dumps with the services stopped (Environment checkpoints).
- Access from your machine with
pl db connect, forpsqlor a database GUI, without a public port (developer access). - Major-version upgrades for PostgreSQL with
pl db upgrade, with a rollback window (Upgrades). - Size, connections, transactions per second, cache hit ratio, largest tables and slowest statements on the database’s console page (Insights).
- A mail to the organization’s owners when a database is 80% and 95% full (usage alerts).
- Persistent volumes for application roles, with online resize (Application volumes).
- Valkey per environment, with sealed daily backups (Valkey).
Plan: high availability. A request for HA fails at placement today (Placement and lifecycle state).
The sections from How it works on are for operators.
Deleting a database
pl down leaves an environment’s databases in place, because their data outlives any one deployment. A database goes in one of three ways (migration 0090):
pl db delete <db> --yes(DELETE /v1/database-instances/{id}, admin role).- It is refused (
409) while a deployment of the environment is active, or while a restore, relocation or upgrade of the database is open. - A repeated request answers
200with the current state. - The audit trail records
database_deleted. --no-backup(?backup=false) skips the final base backup.
- It is refused (
- Preview expiry. A database of a preview environment with no active deployment gets a retention window (
PUSHLEFT_DATABASE_PREVIEW_RETENTION_DAYS, default 7 days).- This covers PostgreSQL and ClickHouse, also on a node that is in
erroror stillprovisioning. A database on aprovisioningnode goes without a final backup. GET /v1/database-instancesshows the window asretain_until.- A new deployment clears it. When it passes, Pushleft releases the database.
- Pushleft never releases production databases automatically.
- This covers PostgreSQL and ClickHouse, also on a node that is in
- Never placed. In an environment with no active deployment, Pushleft releases a database that never reached a node after ten idle minutes. Its state is
pending_placement,provisioning, or anerrorbefore placement. It has no container or data, only a reservation. This applies to production too. A placed production database stays untilpl db delete.
What a release does.
- The request sets
destroyingwith the next resource generation, so results of earlier work no longer apply. - The scheduler (
release_databases, once a minute) runs a final base backup on the active node whenever the instance has one, unless you skipped it. A container can hold data, whatever its status. - Removal waits for evidence as well as a completed job. The gateway must have recorded the final backup on the instance:
last_backup_id, at this generation, newer than the backup job. Otherwise the release stops aterror. retire_generationchecks that the container belongs to the organization. It then removes the container, its secrets and its data directory.- The gateway’s accepted removal marks the instance
destroyedand releases its allocation.
Earlier backups and the sealed archive stay for the normal local retention period (1 day by default, PUSHLEFT_DATABASE_BACKUP_RETENTION_DAYS) after the removal. The agent stamps the archive removed-at. Its once-a-minute sweep deletes an archive whose stamp is older than that. The sweep takes only removed instances (a deleted database, a retired generation). A live database whose backups keep failing keeps its last ones. Until 2026-11-01 nothing removed them.
A failed final backup stops the release at error and removes nothing. It does not restart on its own. The preview expiry skips it, also after --no-backup. Run pl db delete again to retry it, final backup included.
While only a database uses an environment network, the mesh controller keeps checking it. Its jobs lease only on fresh host evidence. After ten minutes with no deployment and no database, Pushleft tears the network down as after pl down. The capacity of its gateways goes back.
A deploy into an environment whose database is still destroying is refused with 409. Once the database is destroyed, it stays destroyed and is kept as history. The next deployment creates a new, empty database, with a new id, runtime name and backup history (migration 0117). It creates the catalogs and logins again. The deleted database’s backups do not carry over to it.
While a role or a database waits for capacity, its deployment’s event stream shows waiting_for_capacity once. The event names the request and the pool. short lists each resource (cpu, memory, disk) that no active node of the pool has free. message says the same in words, with the most that one node has free and that node’s name. An empty short means that each resource is free on some node, but no eligible node has all of it. The region, the capabilities or the environment’s network limit the choice.
Importing a database
pl db import <db> <file> [--database <name>] loads a pg_dump -Fc archive into a running PostgreSQL database. Use it to move data in from another host. The target database must be empty; to replace data that is already there, upload it as a named dataset and use pl db load. The API is PUT /v1/database-instances/{id}/import, admin role, with the header x-pushleft-import-sha256.
The API streams the upload to a temp file. It refuses anything that is not a custom-format archive (PGDMP) or does not match its digest. The cap is PUSHLEFT_DATABASE_IMPORT_MAX_BYTES (default 64 GiB). It stores the archive in the backup blob store and records it in database_imports (migration 0093). One manage_database job on the database’s node then does these steps:
- fetches the archive from the agent gateway under its lease (
POST /v1/agent/jobs/{id}/import), checking its digest and size; - reads the archive’s extensions (
pg_restore --list) and refuses one that the image does not ship. The admin creates the others first (vectoris not a trusted extension); - restores it as the database’s manifest login, never as the admin, over the container’s loopback:
pg_restore --single-transaction --exit-on-error --no-owner --no-privileges --no-comments. An archive is tenant SQL, so it gets no more than the rights of that login. The database owner (the login’s role there) owns the objects. A failed restore changes nothing; - reports every table with its exact row count.
On the node, the agent can run the same import from a local file with pushleft-agent manage-database --task-file <import task> --archive <file>. It checks the file against the task’s sha256 and size, as it checks a download, and restores it with the same code. npm run test:database-agent imports a dump this way, as the database’s own login. It checks the row counts and both refusals: a database that is not empty, and a digest that does not match. staging.sh import-drill runs the whole path on the staging fleet. The CLI uploads a dump, the API stores it, and the database node’s agent leases the import and downloads the archive through the gateway. The drill then checks the row counts in the report, and that a second import into the same database is refused. pl db import waits for the report and prints it. GET /v1/database-instances/{id}/imports lists the latest imports with their status, report or error. Comments in the archive (COMMENT ON) are not restored. The API deletes the archive from the blob store about ten minutes after the import completed or failed (migration 0109). A load from a named dataset keeps the dataset’s object.
Operators. The API and the agent gateway must use the same backup blob store. For services on the same host, set PUSHLEFT_BACKUP_LOCAL_ROOT to a shared private directory on both. deploy/systemd/backup-local.conf.example supplies the setting and systemd write access. This setting is for backups only, and leaves the source, cache and registry stores as they are. S3 settings take precedence. This local handoff store gives no off-host backup protection.
Named datasets
A test environment that switches data often loads a named dataset. You upload the dump only once (migration 0101). Examples are a customer copy, a performance set or an empty schema.
Upload. pl db dataset upload <name> <file> [--engine postgres|clickhouse] [--source-database <x>] stores the archive once, write-once, in the backup blob store under datasets/<org>/. In production that store is the R2 bucket pushleft-datasets (EU jurisdiction, since 2026-11-06), so datasets and checkpoints do not fill the control-plane disk. A dataset stays until you delete it. Spent pl db import and pl volume import archives are deleted after use, and R2 removes any left behind after 7 days. The API is PUT /v1/database-datasets/{name}?engine=&source_database= (admin). Two engines take an archive:
- PostgreSQL: a
pg_dump -Fcarchive. - ClickHouse: a
BACKUP DATABASE <x> TO File('<name>.zip')archive (ZIP) of one database, with--source-database <x>.
Datasets are per organization, so every environment can load them. pl db dataset list lists them. To replace a name, run pl db dataset delete <name> first. The delete is refused while a load of the dataset runs.
Load. pl db load <db> --dataset <name> [--database <name>] empties the database and loads the dataset in one manage_database import job (reset). The API is POST /v1/database-instances/{id}/load (admin). One import or load runs per database at a time, and the engine must match. pl db load waits and prints the row count of each table.
Progress. While a load runs, pl db load, pl db status <db> and the console’s Operations panel show its phase, tables and indexes done of the total, the database size and the elapsed time. During an index build they also show the rows done on that table. The agent sends a new sample every 15 seconds. pl db import shows the phase, the index build and the elapsed time only, because its single transaction hides the counts until the end.
-
PostgreSQL. The agent copies the archive onto the data volume, outside
PGDATA, where it counts against the disk quota. The agent removes it when the load ends. All steps run as the database’s manifest login.- It drops every object the owner holds, and keeps the members of an extension. It drops schemas other than
publicfirst, then the tables, views, sequences, routines and types ofpublic. This step commits alone. pg_restore --jobscreates the tables and loads their data, with one job for each CPU of the instance (at most 8).pg_restore --section=post-databuilds the indexes one at a time. Each index gets the memory left after shared buffers and a reserve for the server, at most 75% of the instance’s memory. It uses every CPU, up to 7 parallel workers. A container created without a/dev/shmas large as that budget builds on one CPU.
The admin creates extensions first, as for an import. The app sees the database empty and then partly loaded until the load ends. If a load fails, the database stays partly loaded. Run the load again.
- It drops every object the owner holds, and keeps the members of an extension. It drops schemas other than
-
ClickHouse. The agent copies the archive into the instance’s backup disk as the
clickhouseuser. The admin restores it into a scratch database. The load is refused, and the target stays as it was, unless that database:- is Atomic;
- has no dictionaries;
- holds only plain table engines: the MergeTree family, Log, Memory, Null, Set, Join, View, MaterializedView. URL, File, S3, Kafka, MySQL and PostgreSQL tables are refused.
The target’s ownership comment moves onto the scratch database, which is then renamed over the target. Grants are kept by name, so they still apply. Between the two renames, the database is absent for a short time.
Tested on 2026-10-29:
- the API, against migrated PostgreSQL;
- the exact reset and restore pipeline, against PostgreSQL 17. A broken archive changes nothing. A load replaces schemas, tables, views, types and functions and keeps the admin’s extension. A reload works;
- the ClickHouse steps, on the pinned image with a real
BACKUP ... TO Filezip. A URL-engine archive is refused, the ownership comment carries over, the grants of an app login survive, and no scratch databases remain.
The agent’s job has not run end to end on a node yet.
PostgreSQL with pgvector, pg_textsearch and PostGIS. deploy/images/postgres-pgvector.Dockerfile builds the pinned image with pgvector 0.8.7, pg_textsearch 1.5.1 and PostGIS 3.6.4 from checksummed releases. pgvector was built and checked locally on 2026-10-26: CREATE EXTENSION vector, an HNSW index and a nearest-neighbour query. The other two were added on 2026-11-06 and checked locally on both majors (18.6 and 17.11, arm64): every extension in the list created, a bm25 index built and ranked, and a WGS84 point transformed to RD New (EPSG:28992). Both majors were published and pinned on 2026-11-06 for amd64 and arm64, with agent 0.1.0-6fcca25 on every box (it preloads pg_textsearch). Trivy found the same HIGH and CRITICAL findings as their bases on both architectures, none added. A running database stays on its old image until fleet upgrade-database-runtimes moves it. It replaces PUSHLEFT_POSTGRES_IMAGE after it is published, scanned on both architectures and pinned (with the images of the CVE gate). See extensions for how a manifest asks for it and how running databases move to it.
Environment checkpoints
Use a checkpoint to rebuild a test environment to a known state, as often as you need. You can also start a test environment from production dumps. Checkpoints and restores are for preview and other non-production environments only. The API refuses them on production. Admins and owners take and restore them. Everyone in the organization can see them.
Take a checkpoint. pl env checkpoint <name> copies every ready PostgreSQL, ClickHouse and Valkey database of the environment, then waits until the copies are stored:
$ pl env checkpoint before-migration
Note: pg_dump holds share locks until it ends; migrations and other schema changes on shop/preview/checkout-v2's PostgreSQL databases wait for it.
checkpoint before-migration of shop/preview/checkout-v2: copying shop (postgres), events (clickhouse)
shop 1405318144 bytes
events 441966592 bytes
checkpoint before-migration is ready; restore it with pl env restore before-migration
- PostgreSQL is copied with
pg_dump -Fcas the database’s own login, on the database’s node. The copy is consistent, and the application keeps reading and writing.pg_dumpholds a share lock on every table until it ends. A migration or otherALTERon the database waits for the whole copy. Large databases take minutes per GiB. Do not take a checkpoint while a deploy runs migrations. - ClickHouse is copied with
BACKUP DATABASE. It does not lock. - Valkey is copied as an RDB file with
valkey-cli --rdb, as the admin. It does not lock. Its database name in checkpoints and restores isvalkey. - Each copy is uploaded through the agent gateway to the backup blob store, as
datasets/<org>/<item>.dumpor.zip. The node holds no bucket credential. - The checkpoint is
readywhen every copy is stored. If one copy fails, the checkpoint isfailedand names the database and the error.
Restore a checkpoint. pl env restore <name> --yes puts the environment’s data back:
- The environment’s
web,workerandprivateroles are fenced and their containers stop. Requests get an error while the services are down. - Each database in the checkpoint is emptied and loaded, as
pl db loaddoes: a parallel restore for PostgreSQL, a scratch database renamed over the target for ClickHouse. For Valkey, the agent checks the file withvalkey-check-rdb, makes it the base of a new append-only file set and restarts the Valkey container. An instance withappendonly yesloads its append-only files at start, and neverdump.rdb. - The same release starts again. The roles are replaced at generation + 1 from the same image, and the routes move to them when they are ready. Nothing is rebuilt, and no new deployment is created.
Before it stops anything, the restore waits for roles that are starting, runs in progress and an older release’s containers that are still draining. After 15 minutes it gives up and changes nothing. While a restore runs, no new role is placed and no release, job or cron run starts in the environment. Queued runs are cancelled, and cron runs again on its next schedule. One restore runs per environment at a time.
- If a database does not load, the others still load. The services start again, and the restore is
failedwith the reason. - If a role does not stop, nothing is loaded and the services stay stopped, because the old container could still be running. The restore is
failedand says so. Check the node, then runpl upto start the services again.
Restore from dumps. pl env restore --dump <database>=<file> --yes loads dump files. For example, start a test environment from production dumps:
pl env restore --dump shop=shop-prod.dump --dump events=events-prod.zip --yes
- A
.zipfile is a ClickHouseBACKUP DATABASE <database> TO File('x.zip')archive. A.rdbfile is a Valkey RDB, for example--dump valkey=dump.rdb. Any other file is apg_dump -Fcarchive. - Each file is uploaded first as a named dataset, named
dump-<database>-<time>. --dataset <database>=<name>uses a dataset that is already uploaded.- Databases you do not list keep their data.
In the console. Open the Data page of a non-production environment. The Checkpoints panel lists the environment’s checkpoints and latest restores. Admins can take a checkpoint, restore or delete one, and restore from dumps: choose a dataset or a file for each database. The console reads the whole file into memory to hash it, so use pl env restore --dump for large dumps.
Other commands. pl env checkpoints lists the checkpoints and the latest restores. pl env delete-checkpoint <name> deletes a checkpoint and its stored copies. The API is:
POST /v1/environments/{id}/checkpoints {"name"};GET /v1/environments/{id}/checkpoints;DELETE /v1/environments/{id}/checkpoints/{name};POST /v1/environments/{id}/restoreswith{"checkpoint"}or{"datasets": {"<database>": "<dataset>"}};GET /v1/environments/{id}/restores/{restore}.
Taking, deleting and restoring a checkpoint are audit events (migration 0143).
Decisions (2026-11-06).
- A checkpoint is a logical copy, and a restore loads it like a dataset. Checkpoints and production dumps use the same restore path.
- Restore stops the roles and starts the same release again. The source does not need to be kept, and nothing is rebuilt.
- Valkey is part of checkpoints and restores (Waseem, 2026-11-06), so cached and queued data goes back with the databases (migration
0146). - Pinning a daily backup was considered and left for later. The backups are physical copies. A PITR restore goes into a new generation without a cut-over, so a pinned backup cannot replace the data in place yet.
Later: named backups (planned, Waseem, 2026-11-06). A named backup is a daily base backup with a name, kept out of rotation, that a restore can return to. It needs no pg_dump, so it takes no table locks. With archived WAL, it can also restore to any moment after it. A physical restore is faster than replaying a dump for a large database. It cannot load into another environment, so checkpoints and dumps stay for copies of production. The work:
- A table of named backups, and a keep-list in the agent’s backup pruning, which today prunes by age only.
- The same exemption off-host: copy a named base to a prefix that the 45-day R2 lifecycle rule does not cover.
- A cut-over: a restore makes the restored generation the serving one, as an upgrade does with its fixed address. It runs inside the restore flow of this section: stop the roles, restore and cut over, start them again.
- A ClickHouse restore from its daily
BACKUPzip (all databases, encrypted). None exists today.
Build it when a test environment’s databases are too large for pg_dump, or when its locks get in the way.
Tested: scripts/env-restore-e2e.sh runs the scheduler’s restore steps against a migrated PostgreSQL: stop, load, then the same release again at generation + 1. It also runs a failed stop, the production refusal and a checkpoint that fails on one database. A gateway test checks that a stop of a live release is accepted only for instances a restore fenced. Rehearsed on production on 2026-11-06, on a customer’s preview environment (PostgreSQL, 84 MB, and ClickHouse), with agent 0.1.0-51299ca on the database host:
- The checkpoint took about 30 seconds: a 5.7 MB dump and a 1.1 MB zip.
- Restoring the checkpoint took 34 seconds from request to
completed. A marker table made after the checkpoint was gone in both engines, and the table count matched. - Restoring two uploaded dumps (
{"datasets": …}) took 36 seconds, with the same checks. - The site answered 200 about 75 seconds after each restore ended, while the five roles started again from the same release. Part of that time was the image pull: a stopped release’s image was removed from the node. Since then a restore keeps the images of the roles it stops, so the roles start again without a pull.
- The first run found that the gateway gave export jobs no database login (fixed in
90641bb). - Valkey (2026-11-06, agent
0.1.0-d349634): the checkpoint copied 49,890 keys as a 39 MB RDB. The restore took 37 seconds. A marker key set after the checkpoint was gone, the append-only file was on again, and no staged or old files were left in/data. - Re-test of all three engines (2026-11-06 afternoon). The first run found a bug: the Valkey export then used
valkey-cli --rdb -, which leaves the replication stream’s 40-byte end mark after the RDB.valkey-check-rdbaccepts that file, but loaded as an AOF base it fails, so Valkey crash-looped and develop was down about 12 minutes until the mark was cut by hand. Fixed inb9a3b56: the export runsBGSAVEand streams/data/dump.rdb, a restore checks the staged files withvalkey-check-aoffirst, and it rolls back as soon as Valkey restarts. The second run passed: develop was down 73 seconds (from about 100), and the roles were back 50 seconds after the restore completed, as a restore now keeps their images.
Extensions
A manifest asks for PostgreSQL extensions per database (decided 2026-11-05):
data:
postgres:
databases: [{ name: app, extensions: [vector] }]
pushleft_core::POSTGRES_EXTENSIONS is the list a manifest may name. The agent creates them as pushleft_admin, a superuser, so the list is the boundary. Each one must ship in both pinned PostgreSQL images.
| Extension | What it is for | Where it comes from |
|---|---|---|
vector | Vector similarity search (pgvector 0.8.7) | Built in deploy/images/postgres-pgvector.Dockerfile |
pg_textsearch | BM25 ranked full-text search, CREATE INDEX … USING bm25 (Tiger Data, 1.5.1) | Built in the same Dockerfile; preloaded (below) |
postgis | Geometry and geography types, spatial indexes, vector tiles (PostGIS 3.6.4, no raster) | Built in the same Dockerfile, with Alpine’s GEOS, PROJ, json-c and protobuf-c |
pg_trgm, citext, pgcrypto, uuid-ossp, hstore, unaccent, btree_gin, btree_gist, fuzzystrmatch, pg_stat_statements | Common contrib extensions | The stock image |
vector, pg_textsearch, postgis and pg_stat_statements are not trusted extensions, so the database’s login cannot create them. pg_textsearch, PostGIS and the contrib set from uuid-ossp on were added on 2026-11-06 (Waseem). PostGIS is built without raster, which would pull in GDAL and its dependency tree. Build it with gdal-dev when a tenant needs postgis_raster.
Preloaded libraries. Every PostgreSQL container starts with shared_preload_libraries=pg_stat_statements (database insights). pg_textsearch must be preloaded too. A library the image lacks stops PostgreSQL at start, so the image says what it carries: the agent reads the image’s dev.pushleft.postgres.preload label after the pull and adds the names it holds that are in the agent’s PRELOADABLE list (pg_textsearch today). It ignores any other name. An image without the label (the stock images) keeps pg_stat_statements alone. The backup drill and the upgrade check start their throwaway containers with the same setting, so a schema with a bm25 index restores there too. Like the other start arguments, it is not in the spec hash. A running container keeps its arguments and takes the new setting when next created (relocation, restore or runtime upgrade).
- The API records the list on the catalog (
database_catalogs.extensions, migration0132) and sends it in the catalog’screate_databasetask. The agent then runsCREATE EXTENSION IF NOT EXISTS <name> WITH SCHEMA publicin that database, after it has created the database. The application’s ownCREATE EXTENSION IF NOT EXISTS vectorthen finds the extension and does nothing. - An extension added to an existing database: the next deployment sets the catalog back to
pendingunder a new generation. It sends one morecreate_databasewith every extension asked for so far. Roles that use the database wait for it, as for a new database. - Before it creates anything, the agent checks
pg_available_extensions. A container that still runs an image withoutvectorfails the task. The error is “this database’s image has no vector extension; move the instance to the current PostgreSQL image first”. The catalog is thenerrorand the deployment fails. After the instance’s runtime upgrade, the next deployment asks again. - Removing an extension from the manifest drops nothing, as with databases.
- Older agents refuse a
create_databasetask that names extensions (the task’s fields are closed). Tasks without extensions are serialized as before. Upgrade the agents before a manifest asks for one.
Moving to the pgvector image
The image comes from our registry. Its repository differs from the postgres repository on Docker Hub that the agent allows today. The agent therefore accepts a list of PostgreSQL repositories: --postgres-repository or PUSHLEFT_POSTGRES_REPOSITORIES in /etc/pushleft/agent.env, comma-separated, default postgres. A requested image must be in one of them. The agent keeps a running container whose image is in any of them and that otherwise matches the specification exactly. It reports the container update_pending (image updates within a major). Pinning the new image is therefore not specification drift, and deploys go on.
The agent pulls an image whose name starts with a registry host (registry.pushleft.dev/...) with a token from the agent gateway, as it pulls application images. The gateway grants pull on each repository in PUSHLEFT_PLATFORM_IMAGE_REPOSITORIES (comma-separated host/name, in /etc/pushleft/agent-gateway.env) to every active or draining node. Docker Hub images are pulled as before, without a token.
Rollout:
- Publish both images (PostgreSQL 17 and 18 with pgvector) and scan them on both architectures.
- Set
PUSHLEFT_PLATFORM_IMAGE_REPOSITORIESon the gateway and restart it. - Upgrade the agents, with
PUSHLEFT_POSTGRES_REPOSITORIES=postgres,<new repository>on every database node. - Pin
PUSHLEFT_POSTGRES_IMAGEandPUSHLEFT_POSTGRES_17_IMAGEto the new digests and restart the scheduler. New databases start on the new image. Each existing one reportsimage update pendingon its next ensure. pushleft-controller fleet upgrade-database-runtimes --applymoves them one at a time, through the fenced same-node relocation.- When the list is empty, set
PUSHLEFT_POSTGRES_REPOSITORIESto the new repository only. A container still on the old one would then count as drift.
Since 2026-11-09 the images are on GitHub Container Registry, pinned by digest. Databases not yet moved still run the images in one organization’s registry space (2026-11-05). Do not clean or delete that space until every database has moved.
Backups, PITR and restore drills
Pushleft takes a base backup of every database each day, seals it with your organization’s key and checks it with a restore drill. For PostgreSQL it also archives WAL, so you can restore to a point in time. Take a backup now with pl db backup <db>, and request a restore with pl db restore (Restore requests and relocation).
A database or volume on a server that you manage yourself (your own servers) gets no daily backup and no restore drill. Its disk is yours to back up. pl db backup <db> still takes a backup on demand.
A database or volume in a preview environment gets no daily backup and no restore drill either. Its PostgreSQL keeps no WAL archive, so a preview has no point-in-time restore (since 2026-11-16). The scheduler reads each node’s reported backup store and queues one stop_archive job (manage_backups) per preview database that still holds sealed WAL. The job deletes that WAL and marks the source with .no-archive. From then on, the agent deletes each new segment instead of sealing it. The same happens on your own servers for every database, without the mark. Bases that are already there stay. pl db backup <db> still takes one, and it restores on its own. Sealed WAL that is still linked in the off-host spool frees after pushleft-offsite has shipped it.
The daily backup is one per serving generation per day (job key database-backup-<instance id>-<runtime name>-<day>, since 2026-11-05). When the serving generation changes, the new generation gets its own base on the next scheduler tick. Examples are a relocation or a major-version upgrade. Before, the old generation had already used the day’s key, and the new one had no base until the next day.
The archive. Every managed instance gets a private archive at PUSHLEFT_DATABASE_BACKUP_ROOT/<organization>/<instance>/. The default is /var/backups/pushleft/tenant, on the backup partition next to the spool, outside the / filesystem. Some hosts still have the store from before 2026-11-01 (/var/lib/pushleft/backups, a real directory) and no explicit PUSHLEFT_DATABASE_BACKUP_ROOT. Such a host keeps using it with a warning, and its spool copies as before. To move the store:
- Stop the agent and the database containers.
- Link each file the spool already holds into the new store, and copy the rest.
- Replace the old directory with a symlink to the new one for the running containers’ WAL mounts.
- Set the variable.
The archive has these rules:
- Every level is a non-symlink
0700directory, created with the same rules as the source store. - Only one subdirectory is mounted into the engine container:
wal/for PostgreSQL andbase/for ClickHouse. - The agent assigns it to the engine user inside the container (
chownthroughdocker exec), so the image’s UID mapping holds.
Runtime policy. The instance specification hash carries runtime_policy: 5. Policy 4 added WAL archiving and the ClickHouse backup disk. Policy 5 added the container-local admin pg_hba, no ClickHouse network admin, the read-only users.d, the table-engine grant rule, ownership labels and sealed archives. A container created before policy 5 reports specification drift. It needs the explicit runtime policy upgrade, and Pushleft does not swap it silently.
WAL archiving. PostgreSQL runs with archive_mode=on. Its archive_command copies each segment, fsyncs it and renames it into wal/. If a segment of the same name is already there and is identical, the command succeeds. If it differs, the command fails and PostgreSQL keeps retrying. archive_timeout=300 bounds the recovery point to five minutes on an idle server. For a lower RPO, add pg_receivewal streaming. The agent seals each archived segment into sealed-wal/ (see encryption below) and only then deletes the plaintext copy. A segment that PostgreSQL archives again after a crash must match its sealed copy byte for byte. Otherwise the agent refuses and keeps both, so archived history stays. sealed-wal/ is not mounted into the container.
Base backups. The backup task inserts a marker row (public.pushleft_backup_marker in the postgres database). It then streams pg_basebackup --format tar --wal-method fetch --manifest-checksums SHA256 through the agent into base/<YYYYMMDDTHHMMSSZ>/base.tar.sealed. A physical replication slot (pushleft_backup) holds the WAL while it runs, because fetch needs every segment from the start checkpoint to the end. The agent drops the slot afterwards, and replaces one that a crashed run left behind. The agent seals the stream as it goes. The plaintext tar never touches the disk. The container never gets write access to base backups. The agent reads the sealed tar back through the decryption, and checks every data file against PostgreSQL’s own SHA-256 backup_manifest. PostgreSQL 17 pg_verifybackup cannot read tar format, so the agent uses this read-back. The agent then writes manifest.json last and atomically. It holds format: 2 (sealed), the sealed file’s size and SHA-256, the start and end LSN, the first needed WAL segment and the server version. Format 1 bases from before encryption are still readable. A base directory without that manifest is an interrupted attempt. The agent discards it and does not restore it.
Restore and PITR. The restore task is for PostgreSQL only. It always creates a new generation <instance>_g<N> (N from 2 to 9999) beside the source. The generation has its own data path, quota project, secret directory, archive and container. The steps:
- It selects the newest base that ends before the target, or a named
backup_id. - It seals any WAL still in the source’s
wal/, and computes every file hash again. - It decrypts and unpacks the base. It accepts regular files and directories only, so tablespaces are not supported.
- It writes
recovery.signal. - It decrypts the source’s sealed WAL into
<restored generation>/restore-wal/, and mounts that directory read-only. - It appends
restore_command(reading that directory), the target andrecovery_target_action = 'promote'. The target isrecovery_target_time,recovery_target_lsn, or none for latest. - It waits until recovery has finished and the server has promoted.
- It proves an authenticated read. It reports the new timeline and the stop point from the timeline history file, for example
before 2026-10-16 22:33:43+00 (timeline 1 switched at 0/6000000). - It empties
restore-wal/.
- If PostgreSQL reports that recovery ended before the target, the agent removes the crash-looping container, keeps the data for inspection and fails.
- A replay never unpacks over a generation that has already promoted.
- A
latesttarget replays the WAL that was archived when the restore started.
The source generation keeps running and keeps its writers, because a restore never cuts over. You request a restore with pl db restore (Restore requests and relocation). The scheduler allocates the generation number, quota ID and capacity, and sends the restore task. The fenced relocation below moves writers to a new generation. pushleft-agent manage-database on the node stays the offline path.
Restore drills. The verify_backup task restores the latest base into a throwaway PostgreSQL container. The container is networkless, with a read-only root, the same capability set and the source container’s exact image. It waits for consistency and runs pg_amcheck --all --heapallindexed. It requires sum(checksum_failures) = 0 and the base’s own marker row. Data checksums depend on the cluster’s initdb setting. PostgreSQL 17 leaves them off by default. The drill always removes the container and its scratch directory. For ClickHouse, the drill runs RESTORE DATABASE ... AS pushleft_verify_<nonce>_<n> for every backed-up database on the live instance. It counts the rows, requires the marker row in pushleft_backup.marker and drops the throwaway databases. pushleft_backup and pushleft_verify* are reserved catalog names.
ClickHouse backups. A backups local disk is configured on the per-instance base/ directory through a read-only config.d file. The backup task runs BACKUP DATABASE ... TO Disk('backups', '<id>/data.zip') SETTINGS password = '...' for every non-system database. ClickHouse writes one WinZip-AES archive (every entry encrypted, method 99). The password is a per-instance HKDF derivation of the organization key, so the engine does not see the organization key itself. The agent sends the password on stdin and keeps it out of argv. A failed Docker command fed on stdin reports only its exit status in the job result, without its output. A query_masking_rules entry replaces the password with [HIDDEN] in system.query_log and the server log. The agent hashes the archive into manifest.json. Database and table names inside the zip are plaintext. Their contents are encrypted. Retention rules are the same as for PostgreSQL, without WAL.
Retention. The agent keeps every base started within PUSHLEFT_DATABASE_BACKUP_RETENTION_DAYS (default 1, since 2026-11-01). Older backups are restored from the off-host copy in R2. It always keeps the newest base, and all WAL from the oldest kept base onward. Timeline .history and .partial files are never pruned. The agent prunes after each backup. It deletes only after re-verifying every file hash of the oldest base that will remain. A single base is never pruned, however old.
Schedule and evidence. The scheduler queues one backup per ready instance per day, and one verify_backup per committed base. Both run in the agent’s durability lane (agent gateway), beside deploys and not ahead of them.
A member can also take a backup now of a preview database, and an admin of a production database: pl db backup <id>, Back up now on the database’s console page, or POST /v1/database-instances/{id}/backups.
- It queues the same job, one at a time per instance (
409while one is queued or running). - The audit trail records
database_backup_requested. pl db listand the console show the last backup and whether one is running.
Both jobs have idempotency keys, and the normal readiness and network-admission path places them. The agent returns a typed DatabaseBackupReport, with no secrets or host paths. The full report stays in the append-only agent_job_results table. The gateway also keeps a fenced summary on database_instances (migration 0030):
last_backup_id,last_backup_atandlast_backup_bytes;backup_verification(passedorfailed),backup_verified_idandbackup_verified_at.
The gateway ignores a result from an older instance generation.
Encryption at rest. Each organization has one 256-bit backup key in Vault at vault://organizations/<org>/backup-key#key (hex). The agent gateway creates it on the first request with a create-only write (cas: 0). A race or retry therefore cannot replace a key that has sealed archives. The gateway hands the key to a node only while the organization is placed there (node secrets). If the gateway refuses, or Vault can neither read nor create the key, every backup, drill and restore fails. Nothing is written unsealed. Offline manage-database with an operator token creates the key the same way.
The agent’s sealed format (crates/pushleft-agent/src/seal.rs) is PLSEAL1. It has a key ID, a random 32-byte salt and AES-256-GCM records of 64 KiB. Each file gets its own key, HKDF-SHA256 from the organization key and the salt. The nonce is the record counter plus a last-record flag. The additional data is the file’s archive path (<org>/<source>/base/<id>/<file> or .../wal/<segment>). A file that is edited, truncated, reordered, swapped for another file, or opened with another key fails authentication. The agent seals the PostgreSQL base tar, every archived WAL segment and timeline file, and application volume tars (volume.tar.sealed). ClickHouse archives use the engine’s native AES zip with the derived password. Manifests stay plaintext. They hold sizes, hashes, LSNs and timestamps, but no data. Hash checks run over the sealed bytes, so retention can re-verify a base without the key. Every restore checks both the manifest hash and the AEAD tags.
PostgreSQL writes WAL itself, so a segment is plaintext in wal/ until the agent seals it. The agent loop seals every source each minute, and each backup and restore seals first. The plaintext window is therefore about a minute after each archive. To open a volume tar for a manual restore, run pushleft-agent open-backup --organization <org> --source volume-<environment>-<name> --backup-id <id> --output <file>. It re-verifies the manifest hash first.
What this protects:
- Nobody can read an off-host copy, a disposed disk or a leaked backup directory without Vault.
- Root on the database host can still read the archives of organizations placed there, because the gateway hands it their keys. It can read the live data directories anyway.
- Root on a host cannot get the keys of organizations that are not placed on it.
Off-host spool
The agent hard-links the sealed store into a local spool on the same partition, so each backup is stored once on the host. pushleft-offsite.timer ships the spool to R2 (Robot hosts runbook). Configuration: PUSHLEFT_DATABASE_SPOOL_ROOT (default /var/backups/pushleft/offsite/tenant, on the /var/backups/pushleft partition of every Robot box).
- Layout. The spool mirrors the local archive:
<root>/<organization>/<source>/base/<backup id>/<file>plusmanifest.json, and<root>/<organization>/<source>/wal/<segment>(the localsealed-wal/). A source is an instance, a restored generation (<instance>_g<N>) or a volume (volume-<environment>-<name>). A restored generation is its own source because its AEAD context names it. PostgreSQL bases, sealed WAL and timeline files, ClickHouse AES zips and volume tars are all linked. The agent does not link plaintext bases from before sealing (format 1) or the plaintextwal/directory. - When. After each
commit_base(backup jobs for PostgreSQL, ClickHouse and volumes), the agent links the base’s files and checks them against the manifest. It linksmanifest.jsonlast. A spool base directory without a manifest is incomplete. The same pass links every sealed WAL file that is not in the spool yet. The agent loop repeats the pass for every source each minute after sealing, so the spool catches up after an outage. Retention also runs before each backup, best effort. Bases past retention that fill the partition therefore cannot block the backup that would prune them. This early pass keeps the newest base. The agent logs a failure there, and the backup goes on. After the new base, the spool pass runs before retention again. A failed link fails the backup job before that pruning can remove anything, and the base stays committed locally. - Writes. The agent hard-links each file into place without replacing anything, and fsyncs the directory. The store does not rewrite a file in place. The link puts the same bytes under a second name. The agent refuses to spool when the store is on another filesystem (
PUSHLEFT_DATABASE_BACKUP_ROOT), since every backup would then be stored twice.restore-from-spoolcopies from an off-host copy on another filesystem: a temporary name, fsync, a no-clobber link. A file that is already there with the same SHA-256 is skipped. The agent refuses a file with a different hash loudly and keeps the old file. The agent does not move or delete files in the spool.pushleft-offsiteskips.*temporaries andlast-success. It removes a shipped tenant file as soon as its link count is 1, and any other shipped file after 40 days. A link count of 1 means the store’s retention (1 day by default) has dropped the file. A tenant file that is not in R2 yet stays, so a shipper outage keeps it on the host. The bucket owns retention there. - Sealed bytes only. The spool holds what the archive holds, already sealed under the organization key. Copying never needs the key.
- Fail closed. The agent refuses to spool unless the spool root is on a different filesystem (device) than the data root and than
/. A bind mount of the data partition has the same device, so it is refused too. A missing mount point resolves to the filesystem below it and is refused.pushleft-agent doctorreports the result. The spool root must not overlap the data, archive or secret roots, which the agent bind-mounts into containers. It must not lie inside one of them or contain one. Every directory is a non-symlink0700directory and every file is0600, owned by the agent (root).PUSHLEFT_DATABASE_SPOOL_MODE=disabledturns the spool off on development hosts only. Backups then share the host’s fate. - Status. Each pass writes
<root>/<organization>/<source>/last-success(<epoch seconds> <files copied>).scripts/ops-alerts.shfirestenant_backup_spool_stale(ticket) whenPUSHLEFT_OPS_TENANT_SPOOL_ROOTis set and a source’s record is stale. Stale means older thanPUSHLEFT_OPS_TENANT_SPOOL_MAX_AGE_SECONDS(default 600), unreadable, or absent. The spool is root-only, so the probe runs as root on the node. It reports the copy into the spool, not the off-host copy.offsite_copy_stalereports the copy in R2. Each agent also reports its host’spushleft-offsitelast-successwith every lease (fleet_nodes.host_offsite_last_success_at,host_offsite_files). The fleet admin app’s Backups page shows the value beside each database’s and volume’s last backup, restore drill and last failure (fleet admin APIGET /v1/backups). - Restore from the spool.
pushleft-agent restore-from-spool --organization <org> --source <source> <spool root>reads<org>/<source>from a spool or from an off-host copy of it. It checks every base against its manifest hash and decrypts it to nothing (AEAD tags, PostgreSQL and volume bases). It authenticates every WAL file and copies the files into the local archive with the same no-overwrite rule. Bases without a manifest are skipped. A tampered file stops the import. The usualrestoretask then creates a new generation from it, with its own hash and AEAD checks. The same path restores a base that local retention has already pruned. ClickHouse zips are copied back, and they restore through the engine in a separate step.
What is proven where. npm run test:database-backup (scripts/database-backup-e2e.sh) runs the real agent and the pinned engine images on Docker Desktop. The run covers these checks:
- private store modes and archived WAL;
- the manifest hash;
- PITR into generation 2: rows written before the target are kept. A row written after it is absent, while the source still has it;
- read-only source WAL and a converging replay;
- both engines’ drills, with no leftover containers or databases;
- refusal of a tampered archive;
- retention pruning of a backdated base and exactly the WAL only it needed;
- the volume lifecycle (below);
- sealed bases and WAL (no plaintext in the files,
PLSEAL1header, WAL moved out ofwal/); - the ClickHouse AES zip, the sealed volume tar opened with
open-backupand the emptiedrestore-wal/; - a backup refused for a task naming another organization;
- the off-host spool on a filesystem of its own (a sparse APFS image on macOS), with byte-identical bases and sealed WAL after each backup for PostgreSQL, ClickHouse and volumes;
- in that spool,
manifest.jsonwritten after its file,0700/0600modes and a freshlast-success; - nothing removed from the spool by local retention, and no container mount source in the spool;
- a host loss: the spool copied off the node, and the source container and its whole local archive removed;
restore-from-spoolfrom the copy (idempotent, with a tampered WAL file refused);- then PITR into generation 3 from a base that only the spool still had (rows 1 and 2, without row 3);
- a spool on the data filesystem refused (the job fails, nothing is written to it) and reported by
doctor; tenant_backup_spool_stalequiet on fresh records and firing on a stale one.
npm run test:database-agent proves that pg_hba rejects a TCP login as pushleft_admin from another container on the environment network, while a tenant principal logs in. It proves the same for every ClickHouse admin name (pushleft_admin, default, pushleft_local_admin). It also checks the read-only users.d mount and the ownership labels. A migrate principal can create a MergeTree table and is refused a URL table. Unit tests cover the sealed format (round trip at record boundaries, truncation, edits, swapped context, wrong key) and WAL sealing and staging.
The same suite runs the migrated scheduler and gateway durability tests on a disposable database. Quotas are disabled in that run. XFS enforcement for restored generations and volumes uses the same code path as npm run test:linux-database-quota, which still has to run on native Linux. No end-to-end test exercises the minute-by-minute sealing in the agent loop. The suites drive one-shot manage-database commands, which seal on backup and restore. Unit tests cover the spool’s no-overwrite hard link, layout, manifest-last order, size and hash refusal, the device check and the import’s AEAD refusal. The shipper (pushleft-offsite) has a unit test against a local store. The shipper has not run against the real R2 bucket yet, and no restore drill from it has run.
Restore requests and relocation
Migration 0075 adds database_operations and its append-only database_operation_events, both under organization RLS. An operation is one restore or relocation of one PostgreSQL instance. Both kinds of request go through request_database_operation(org, instance, kind, target, backup_id, node, idempotency_key, actor). It is idempotent per key, and it refuses a reused key with other parameters (409). It also refuses an instance that is not ready, ClickHouse, and a second open operation on the same instance. It takes the next generation number and a new XFS project ID from the shared sequence. A generation number is used once, also after a rollback.
Generations. database_instances.runtime_generation is the generation that serves. Generation 1 keeps the instance’s name. Generation N runs as <name>_g<N> with the data directory <data root>/<instance id>-g<N>, its own secret directory, archive source and quota project. active_runtime_name (a generated column) is the only name the API, the scheduler (placement, backups, catalog and principal work) and the agent tasks use. generation is a separate column and stays the result fence. A cutover advances both, so results of work sent to the old generation are ignored. Each restore or standby generation binds its base and target in .pushleft-restore.json in its data directory. The container’s specification hash no longer includes these inputs, so the generation keeps its container once it serves.
Restore request. pl db restore <db> [--at <RFC 3339>] [--backup <id>] (POST /v1/database-instances/{id}/restore, admin role, Idempotency-Key required). The API refuses a point in the future. The scheduler reserves the new generation’s CPU, memory and disk on the instance’s node, where the archive is. Otherwise it records that the restore waits for room. It then sends the restore task described above, with a source field when the serving generation is not generation 1. States: requested, restoring, restored, and completed after the restored generation is retired. Retirement comes after PUSHLEFT_DATABASE_RESTORE_RETAIN_SECONDS (default seven days) and keeps the archive. A failed restore is discarded (container and data removed, archive kept) and ends failed. pl db status <db> (GET /v1/database-instances/{id}/operations) lists operations with their events. pl db list shows each instance’s serving generation and latest operation.
Relocation. An operator runs pushleft-controller fleet relocate-database <instance> [--to-node <node>]. Without --to-node, the scheduler picks the best-fitting database node with room in the source’s region. It tries another node first and uses the source node (a new generation in place) only when no other node fits. For a new host it records the environment attachment request. The relocation starts only once network admission holds there. The instance is moving meanwhile: new placements, backups and catalog/principal work wait. Each step is one job, keyed database-op:<id>:<step> and targeted at its node:
base(source): a fresh sealed, verified base.follow(target): generation N starts as a standby from that base (standby.signal,restore_commandreading WAL the agent opens intorestore-wal/, a one-second retry). The source’spg_hbastays closed, so no replication connection exists.catch_up(source):pg_switch_wal(), wait until it is archived, seal; reports the LSN.sync(target): replay to that LSN.fence(source), in this order. A fencedpg_hba(written in place, so the bind mount sees it) admitspushleft_adminonly, locally and on loopback; every tenant login is rejected.ALTER SYSTEM SET default_transaction_read_only = onand a reload. Every client backend is terminated, and the step waits until they are gone. A.pushleft-fencedmarker goes into the source’s data directory. Then it reads the insert LSN, switches, waits for the archive and seals. Every commit that a client saw acknowledged was flushed before its backend exited. Each such commit lies at or below that fenced LSN.promote(target): replay to the fenced LSN and runpg_promote(). Prove reads, take the instance’s fixed address and emptyrestore-wal/. On the same node the fenced source still holds x.126. The agent disconnects only that exact container, and only while its fence marker exists, then pins the new generation to the address.- Cutover (control plane, one transaction):
runtime_generation,generation,quota_project_idandactive_node_idmove to the target; the instance isready. Backup evidence is cleared, so the new generation gets its own base on the next scheduler tick. The instance’s capacity key moves to the new generation. The source holds the operation’s key until it is released. - Applications (cross-node only, step
apps): each running web, private or worker instance whose role uses PostgreSQL gets the new address. They change one at a time.- A role without a volume rolls. The scheduler places a replacement instance at the next generation (
replaces_instance_id, jobapplication:<replacement>:ensure:<generation>:database-op:<op>). Its lease carries the new address. It must report healthy while the old one keeps serving. The ingress pass then publishes the deployment’s hostnames again without the old instance. Each node gets a new route generation, activated before the old one drains. It stops the old instance once no route has carried it for the drain (30 s). A worker has no route, so it stops as soon as its replacement is ready. - A role with a volume cannot have two writers. The scheduler re-ensures it in place at its current generation (job
application:<id>:ensure:<generation>:database-op:<op>). The agent recreates the container under the same name and fixed address, and that instance is down for a short time. - An instance that does not become healthy fails the operation. With a rolling replacement, the old instance is still serving then.
- A role without a volume rolls. The scheduler places a replacement instance at the next generation (
retire(source), afterPUSHLEFT_DATABASE_RETIRE_GRACE_SECONDS(default 3600): container, data and secrets go; its sealed archive stays.
States customers see: requested, relocating, fenced, cut_over, completed; on failure rolling_back, rolled_back or failed. A failure before promote was sent rolls back. The standby is removed, then the source is unfenced (marker removed, normal pg_hba, default_transaction_read_only reset). A failed promote may have promoted, so it fails closed: the source stays fenced, the instance goes to error, and an operator decides. Writes during the fence window fail cleanly and get no acknowledgement. The login is refused, or the transaction is aborted.
The fence survives restarts. ensure_instance checks the marker. A fenced instance that is restarted, re-ensured or recreated gets the fenced pg_hba again. It does not get the fixed address back. ALTER SYSTEM lives in PGDATA.
Between nodes. A target on another node gets the sealed archive through the backup blob store (pushleft_blob, Use::Backups: PUSHLEFT_BACKUP_S3_*, PUSHLEFT_BLOB_S3_* or PUSHLEFT_BLOB_LOCAL_ROOT), under relocation/<org>/<source>/{base/<id>/,wal/}. The store is write-once and holds sealed bytes only, with each base’s manifest written last. The source exports after base, catch_up and fence. The target downloads only new objects into <backup root>/.relocation/. It imports them with the same manifest-hash and AEAD checks as restore-from-spool. The agent needs those blob settings only on nodes that relocate across hosts.
Service endpoint. Applications reach PostgreSQL at the fixed address x.126 of the database host’s environment /24. The gateway derives it from active_node_id for every application lease and bakes it into DATABASE_URL/PGHOST. A same-node relocation keeps that address, so applications reconnect to the new generation unchanged. A cross-node relocation changes it. Step 7 gives every running instance that uses PostgreSQL the new address before the operation counts as cut_over. A role without a volume gets a rolling replacement (no gap). A role with a volume is recreated in place (down briefly). Until then, its writes to the fenced address fail and get no acknowledgement.
What is proven where. npm run test:database-relocation (scripts/database-relocation-e2e.sh, not in test:all) covers the control plane and the Docker path:
- Through the API and
pl: a restore request with a PITR target, and the replay returning the same operation (200). A reused key with another target is refused (409), and so is a point in the future (400). A relocation is refused while the restore is open. The suite also runspl db list/statusand the operator request with its next generation. - The scheduler’s migrated test covers:
- restore → generation 2 job, capacity and quota;
- the full relocation step sequence on the right nodes, with blob export/import only across nodes;
- the application rollout: only the instance whose role uses PostgreSQL, the same durable task at the same generation, and
cut_overonly after it completed; - the cutover: generation, fence counter, node, quota, capacity key, queued work and the backup schedule follow the new runtime;
- retire after the grace period, rollback, a failed promotion failing closed, and generation numbers used once.
- Two agent “nodes” (their own data, secret and backup roots and environment bridges) and a local blob store. A writer inserts continuously through the application login and records every acknowledged id:
- a rolled-back attempt: writes refused during the fence, and the fence surviving
docker restart, a re-ensure and a retried fence step, then a clean unfence; - a same-node relocation, with agents killed with SIGKILL mid-replay and mid-promotion and retried, and the address moving to the new generation;
- generation 1 retired, its archive kept;
- a cross-node relocation through the blob store (sealed objects only);
- an application run by the agent (
manage-application --lease-file, standing in for the gateway’s lease) that writes through itsDATABASE_URL. The fenced old address refuses it, then it is re-ensured with the new one. The container is recreated in place (same name and fixed address, new container ID) and keeps writing. A replayed ensure changes nothing; - a restore of the relocated generation;
- zero missing acknowledged writes, the writer’s and the application’s, at the end.
- a rolled-back attempt: writes refused during the fence, and the fence surviving
npm run test:database-relocation also proves the role and catalog markers across a cutover. Markers in the old runtime-name format from generation 1 carry over. A new catalog reuses the owner role, and a new principal and the existing login work on generation 3. All are restamped with the instance ID, and a role marked by another instance is refused. Unit tests cover:
- the marker identity: generations up to the serving one, with another instance, a later generation or another kind refused;
- the database addresses in the application container hash;
- the fenced
pg_hba(only the local admin) and LSN comparison; - the blob round trip: write-once, only new objects, a nested key refused;
- the standby settings and the task validation.
Upgrades
Migration 0078 adds two kinds of upgrade to database_operations:
runtime_upgrademoves a container from before runtime policy 5 onto the current policy.upgrade, with its planupgrade_check, moves to a newer PostgreSQL major.
Both run on the instance’s own node. They use the same generations, write fence, cutover and grace period as a relocation. They also use the same request function (request_database_operation, now with a major version argument). It is idempotent per key, allows one open operation per instance and uses each generation number once. pl db status shows their steps, checks and events. Neither upgrades ClickHouse (see known limits).
database_instances gains two columns. engine_version is the PostgreSQL major of the serving generation. Its default is the major of PUSHLEFT_POSTGRES_IMAGE (pushleft_core::POSTGRES_DEFAULT_VERSION). The two move together in one reviewed change. Migration 0078 set it to 17. Migration 0080 sets it to 18. New instances are created on 18, and existing rows keep their major. runtime_policy is the agent policy of the serving container. It is 5 for instances created from now on. It is NULL for instances created before the migration until an upgrade confirms them. Every cutover (relocation, runtime upgrade, upgrade) sets it to 5, because the agent creates each new generation under the current policy.
The scheduler now builds every PostgreSQL task with the image of the instance’s own major. The tasks are the ensure that each deployment sends, relocations and restores. The default major (18) uses PUSHLEFT_POSTGRES_IMAGE, and any other uses PUSHLEFT_POSTGRES_<major>_IMAGE (digest-pinned). Without that image the scheduler refuses the work and does not run it on another major. deploy/images.lock.env pins PUSHLEFT_POSTGRES_17_IMAGE. The scheduler’s environment (deploy/systemd/scheduler.env.example) must set it while any instance runs 17. Otherwise the ensure, relocation, restore and upgrade of those instances fail.
Runtime policy upgrade
A container from runtime policy 4 has no ownership labels and reads the pg_hba.conf in its PGDATA. The specification fence (the data marker and the spec-hash label) and the label check refuse it. Ensure reports specification drift. Backups and catalog work report labels that do not match.
pushleft-controller fleet upgrade-database-runtimes lists every instance whose runtime_policy is below 5 or not confirmed. --org <id> limits it to one organization. With --apply, it requests one runtime_upgrade per PostgreSQL instance, one at a time. A ClickHouse instance with a pending image update gets an image_update instead (ClickHouse image updates). A ClickHouse instance from before runtime policy 5 is listed and skipped. It waits until each is cut_over (or completed) before the next. It stops at the first that rolls back, fails or exceeds --timeout (default 7200 seconds). The request key is runtime-upgrade:<instance>:<generation>, so running it again resumes the same operation. ClickHouse instances are listed and skipped.
A runtime_upgrade is a relocation pinned to the instance’s node: base, follow, catch_up, sync, fence, promote, cutover, grace period, retire. It has the same rollback before promotion and the same zero acknowledged-write loss. The base step reports the container’s policy. When it is already 5, the operation ends completed at once (“nothing to move”), and the instance is marked.
The agent accepts a policy-4 container only for these fenced steps: relocation source steps, retirement and the upgrade steps. All of the following must hold:
- It carries the managed label.
- The data marker in its mounted data directory names this instance.
- Its mounted WAL archive is
<backup root>/<organization>/<instance>/walof the task’s organization.
A task for another organization is refused. A container from before runtime policy 4 has no WAL archive. The agent refuses it with that reason and does not upgrade it automatically.
The fence writes the fenced rules into the pg_hba.conf that the server reads (SHOW hba_file, in place in PGDATA). The fence therefore works and survives restarts as for a current container. A rollback writes the policy-5 rules there: the admin only, over the local socket and loopback. The container’s original rules do not come back. The new generation is an ordinary policy-5 container: labels, the mounted read-only pg_hba.conf, sealed archive.
Image updates within a major
The ensure that each deployment sends does not apply a new digest of the same engine repository. An example is a patch release promoted in deploy/images.lock.env. Sometimes an existing container differs from the requested specification only in its image digest. The agent then keeps it running on its image and reports update_pending with the running and the desired digest. Any other difference (resources, quota, network, data path, policy) is still refused as specification drift. The gateway records the flag on the instance (database_instances.image_update_pending, migration 0079, fenced by the instance generation). pl db list shows “image update pending”. pushleft-controller fleet upgrade-database-runtimes lists these instances too. --apply moves each PostgreSQL instance, one at a time, through the same fenced same-node relocation as a runtime upgrade. ClickHouse instances update in place (ClickHouse image updates). The new generation is created from the current digest, and the cutover clears the flag.
The scheduler does no rolling update, because Pushleft replaces the engine under a database only with an operator. An automatic relocation of every instance on each promotion would:
- put a write window on every customer database at a time nobody chose;
- double the capacity of each instance on its node meanwhile;
- spread a bad digest across the fleet before anyone checked one. A digest of another major, promoted by mistake, would not start on the existing data.
With the pending state, deployments keep working on the reviewed old digest. The operator upgrades one instance, checks it, then applies the rest. The cost: a security fix reaches running databases only when the operator applies it. The list and pl db list show the backlog.
ClickHouse image updates
ClickHouse has no replication here, so a new digest of the same engine version cannot move through a fenced relocation. The operator updates it in place instead. Each instance restarts once.
pushleft-controller fleet upgrade-database-runtimes --apply handles each ClickHouse instance with image_update_pending. It handles them one at a time, in the same list as the PostgreSQL work, and it keeps --org. It waits for each instance to finish before the next. It stops at the first refusal, rollback, failure or --timeout. A later run with --apply waits for an open update. After a failure, it starts a new attempt, first on the instance that failed.
What happens to an instance. The instance is moving from the request until the end, so new ensures, backups and catalog work wait. One agent job (update_image) does the following on the instance’s node:
- The agent verifies the container: this instance’s labels and data marker, this specification with the running digest, and an allowed repository.
- The agent pulls the target digest, if the host does not have it yet.
- A networkless throwaway container of the target digest reports its engine version. The running server reports its own. The agent refuses a target with another version. Nothing has changed at this point.
- The agent writes a journal to the data directory (
.pushleft-image-update.json). It names the old digest and the engine version. - The agent stops the old container and removes it. The engine gets up to 120 seconds to flush. This is the start of the downtime.
- The agent creates the container on the target digest: the same data directory, data marker, fixed address, resources and quota. The runtime generation does not change.
- The agent waits until the engine answers and reports the expected version. It waits up to 300 seconds, and less for a crash loop. The journal then goes.
The instance is unavailable from step 5 until step 7 ends. On a nearly empty instance on a development machine, the whole job took 10 seconds. The downtime on a large instance depends on how long the engine takes to stop and load its tables. It can be minutes, and it has not been measured.
Failure. Writers stop before the new container starts. Docker’s container name admits one container per instance, so a racing start fails on the name. Two containers never run on one data directory.
- A refused update (another version, drift, a failed pull) changes nothing. The operation ends
failedand the old container keeps serving. - If the new digest does not start, is unhealthy or reports another version, the agent removes it and recreates the old digest on the same data. The operation ends
rolled_back.image_update_pendingstays set. The old digest is local, so a rollback needs no registry. - If the old digest does not come back either, the journal stays and the instance is
degraded. A retry of the same job, or a later--apply, resumes from the journal. An ensure refuses to run while the journal exists.
A backup that runs while the container stops fails and runs again.
Repositories. The agent allows PUSHLEFT_CLICKHOUSE_REPOSITORIES, default clickhouse/clickhouse-server,ghcr.io/pushleft/clickhouse. Images on ghcr.io pull without a token. Keep a repository in the list while any instance still runs from it.
Rollout.
- Upgrade the agents.
- Apply the database migration (
0188). - Upgrade the control plane and the scheduler.
- Promote the digest in
deploy/images.lock.env. Each deployment’s ensure then marks its instance as pending. An instance with no deployment since the promotion stays unmarked. - Run
fleet upgrade-database-runtimesto review the list, then--apply.
Tested on 2026-11-09: npm run test:database-agent runs the update on a live container: a refused wrong-version digest, a rollback from an image that does not start, then the patched digest with its rows, version, labels and principal login intact, and an ensure that keeps the container afterwards. npm run test:database-relocation covers the state machine and the operator loop against a migrated database: one instance at a time, a stop at the first failure and a resumed run. The agent’s unit tests cover a failed rollback and a resumed update after a crash.
Role and catalog markers
The agent marks the PostgreSQL roles and databases it creates with a comment: pushleft-managed:<instance ID>:owner, :principal or :catalog. The instance ID comes from the generation’s own data directory (<data root>/<instance ID> or <instance ID>-g<N>). It stays the same across relocations and upgrades, so a later generation keeps owning what an earlier one created. Markers written before this named the runtime of the generation that created them (<name> or <name>_g<M>). The agent still accepts them for this instance’s generations up to the serving one. It restamps them with the instance ID when it next ensures the role or database. Another instance’s marker, a later generation’s or another kind’s is refused. Where the data directory is not named after an instance ID (local fixtures), the markers name the runtime as before.
Major-version upgrades
pl db upgrade <db> --to <major> --plan runs the compatibility checks only. The API is POST /v1/database-instances/{id}/upgrade {"to":18,"plan":true}, admin role, Idempotency-Key required. pl db upgrade <db> --to <major> runs the same checks and then the upgrade. A major that is not newer than the running one is refused (400). Any newer major is accepted, because a dump restores across several majors. The control plane must have the major’s image (PUSHLEFT_POSTGRES_<major>_IMAGE). deploy/images.lock.env pins two production majors: 18 (the default, PUSHLEFT_POSTGRES_IMAGE) and 17 (PUSHLEFT_POSTGRES_17_IMAGE). The upgrade target is 18. Any other target needs its own reviewed digest first: the remote scans, the live engine suites and this suite. Until then the request ends failed with “no reviewed image for PostgreSQL 19”.
Dump and restore. Pushleft upgrades with a dump and restore. The official images carry one major each. pg_upgrade needs the binaries of both majors in one container, which means a combined image that nobody has reviewed. A logical copy needs only the two pinned images. It reads the source and does not write to its files, so the previous generation stays intact for the rollback window. pg_upgrade --copy would also leave the files intact, and --link would not. It rebuilds every index, so a collation change between the two images cannot carry a corrupt index across. The cost is time proportional to the data, all of it inside the write fence. The method suits the plans’ sizes (tens of GiB at most). Multi-TiB clusters need another method (see known limits).
The plan. The check step runs on the instance’s node, against the serving generation, while writes continue. It reports seven checks, kept on the operation (checks):
version: the target major is newer than the running one;runtime_policy: the container is on policy 5 (otherwise, run the runtime upgrade first);quota: the data (sum ofpg_database_size) plus 20% fits the new generation’s disk;host_disk: the data plus 20% is free on the data filesystem, for the copy beside the source;image: the target image runs the requested major;extensions: every extension installed in any database is available in the target (pg_available_extensions);schema:pg_dumpall --schema-only --no-role-passwordsof the source restores withON_ERROR_STOPinto the target image. The check is the dump-and-restore counterpart ofpg_upgrade --check: roles, databases and every object, without rows.
The target image runs in a throwaway container: networkless, read-only root, the database container’s capability set, a 1 GiB tmpfs data directory, removed afterwards. A plan reserves nothing and changes nothing. It takes a generation number. A failed check ends the plan, or the upgrade, as failed. The error names the failing checks (“plan refused: extensions: not available in PostgreSQL 18: adminpack (database postgres)”).
The upgrade. Each step is one idempotency-keyed job, as for a relocation:
-
check(source node): the plan above. -
prepare(same node): the new generation<name>_g<N>starts empty from the target image, without the fixed address. It has its own data directory, secrets, archive and quota project. Writes continue meanwhile, so its start is not part of the write window. -
fence(source): as relocation step 4. The instance ismoving. -
upgrade(same node): refused unless the source is fenced. The agent streamspg_dumpallof the source (as the local admin, role passwords included) intopsqlwithON_ERROR_STOPin the new generation. It removes two things of the bootstrap:- the new generation’s empty
pushleft_admindatabase, because the source’s copy arrives with the dump; - in the roles section only, the dump’s
CREATE ROLE pushleft_admin, which exists already.
Then it runs
vacuumdb --all --analyze-only. Then it compares the databases between the source and the copy, with the exact row count of every table and materialized view. Then it writes a completion marker and takes the fixed address from the fenced source. An interrupted copy has a marker written before the copy and no completion marker. It starts over in a fresh generation. The agent first discards that generation’s container, data, secrets and archive contents, because it never served. A replay after completion only takes the address. - the new generation’s empty
-
Cutover (control plane, one transaction): as for a relocation, and
engine_versionmoves to the target. The event records how long writes were fenced. Backup evidence is cleared, so the new generation gets its own base on the next tick. -
Grace period (
PUSHLEFT_DATABASE_UPGRADE_GRACE_SECONDS, default 86400): the previous generation stays, fenced and read-only, for a rollback. Thenretireremoves its container, data and secrets. Its sealed archive stays. The operation iscompleted.
A failed prepare, fence or upgrade rolls back like a relocation: the new generation is removed and the source is unfenced (rolled_back). Nothing was cut over.
Downtime. Writes fail from the fence until the new generation holds the address. The window holds the fence (switch and archive the current WAL), the copy, the analyze, the row count and the address move. All but the fence grow with the data. npm run test:database-upgrade measures it on Docker Desktop (arm64). For about 40 MB of data, the copy took 0.6 s and writes were refused for 2.5 s. Expect minutes for a few GiB and tens of minutes for tens of GiB. The plan shows the data size. Writes during the window fail cleanly and get no acknowledgement, as for a relocation.
Rollback. pl db upgrade <db> --rollback --confirm-data-loss goes back to the previous major while it is kept. The API is POST /v1/database-instances/{id}/upgrade/rollback {"confirm_data_loss":true}, admin role. Every write made on the new major after the cutover is lost. Without the confirmation the request is refused (400). The API accepts it only while the latest upgrade is cut_over and the scheduler has not started to retire the previous generation. Otherwise it answers 409. A repeated request returns the rollback in progress. pl db status shows the deadline. The steps:
fence_new: the upgraded generation is fenced (as relocation step 4), so no write lands on either side meanwhile.revert(previous generation): it is unfenced and takes the fixed address back.- Cut back (control plane): serving generation, result fence, quota project, capacity key and
engine_versionreturn to the previous generation. retire_new: the upgraded generation is removed (its archive stays). The operation isrolled_back.
A failed fence_new or revert fails closed: the instance goes to error and an operator decides.
Known limits of upgrades
- ClickHouse has neither a runtime upgrade nor major upgrades. It has no fenced generation workflow, with no restore into a new generation and no fence. A new digest of the same engine version updates in place (ClickHouse image updates), after a same-version check (
npm run test:clickhouse-image). The instance restarts, and it is down for that time. Pre-5 ClickHouse containers stay refused. - Containers from before runtime policy 4 (no WAL archive) are not upgraded automatically.
- The production upgrade path is 17 to 18. It is proven on Docker Desktop only. It has not run on a real database host yet.
- The write window grows with the data. Large clusters need
pg_upgradefrom a reviewed two-major image, or logical replication with a short final cutover. Neither is built. - Like relocation, the upgrade is proven on Docker Desktop. It has not run on native Linux with XFS quotas yet.
What is proven where. npm run test:database-upgrade (scripts/database-upgrade-e2e.sh, not in test:all):
- Through the API,
pland the controller:- a plan request and its replay, and a same-major refusal;
- a rollback refused without confirmation and outside the window, then accepted (and replayed) inside it;
- the rollback deadline in
pl db status, and versions and runtime policy inpl db list(an instance created without a major shows 18); fleet upgrade-database-runtimeslisting an unconfirmed instance, requesting its runtime upgrade on its own node and resuming it on a re-run.
- The scheduler’s migrated tests:
- the runtime upgrade (same node, no blob copy, no application rollout, policy confirmed), completed at once when already on policy 5;
- a plan without a reviewed image refused (19);
- the image of each major (18 from
PUSHLEFT_POSTGRES_IMAGE, 17 only fromPUSHLEFT_POSTGRES_17_IMAGE, a tag refused); - a plan with a failing check (nothing reserved, nothing changed);
- the upgrade’s step sequence and cutover (generation, major, policy, capacity key, window event);
- the rollback (fence, revert, cut back, retire, capacity released), a failed copy rolled back, and no rollback after the grace period.
- Real agents and pinned engines on Docker, with writers that record every acknowledged id:
- a policy-4 container on PostgreSQL 17 (no labels,
pg_hbain PGDATA, the policy-4 spec hash). Ensure, backup and another organization’s fence refuse it. It is fenced across a restart and unfenced. Then it moves onto policy 5 in place (labels, mountedpg_hba, ensure and backup accepted) and is retired, with every acknowledged write present; - an image update within the major, with the 17 image under its platform manifest digest as the patch release. The ensure keeps the running container and reports
update_pending. A changed quota with the new digest is still refused. A fenced same-node relocation moves the instance onto the new digest with every acknowledged write present. The gateway’s migrated test records the flag only for a current generation’s successful ensure. The scheduler’s test moves an up-to-date-policy instance whose update is pending and clears the flag at the cutover; - a plan from PostgreSQL 16 (
PUSHLEFT_E2E_POSTGRES_16_IMAGE, test only) to 18, refused becauseadminpackis gone in 17 and 18. Every extension of the 17 image is in 18; - an existing 17 database ensured on
PUSHLEFT_POSTGRES_17_IMAGE, and a replayed ensure that keeps its container; - PostgreSQL 17 to 18 (the production path). The plan passes, and the copy is refused from an unfenced source. The empty generation starts before the fence, and an interrupted copy starts over. The fenced copy runs with the write window measured. Every write acknowledged by 17 is present in 18. Sequences, indexes, views, extensions, the analyze and the application login carry over;
- a rollback inside the grace period: 17 serves again with every write it acknowledged, and the writes made on 18 are absent, as documented.
- a policy-4 container on PostgreSQL 17 (no labels,
Insights
ClickHouse and Valkey have no insights page. The agent measures the size of their data directory every 10 minutes (Valkey: every minute), and the database lists show it.
The node agent samples each managed PostgreSQL instance on its node about once a minute. It runs one docker exec psql as the socket-only admin, with a 5 second statement timeout. It reports the samples to the gateway (POST /v1/agent/databases). The gateway keeps only instances placed on the reporting node (database_telemetry_admit, migration 0088). It writes them to ClickHouse (deploy/observability/clickhouse/004_databases.sql) with the instance’s organization and environment. ClickHouse instances are not sampled yet.
What is collected:
-
Every minute:
- the size of all its databases;
- client connections against
max_connections; - transactions per second and the buffer cache hit ratio, both over the interval since the previous sample. The first sample has neither;
- the replay lag of its replicas.
Pushleft keeps these for the tier’s log retention, like instance samples.
-
Every 10 minutes: its 10 largest tables across its databases (one
\cper database), with size and estimated rows. -
Every 5 minutes, where
pg_stat_statementsis loaded: the 20 statements with the most total execution time since the last statistics reset. Each comes with calls, mean and total time and rows. The agent leaves out the admin’s own databases and queries (the agent’s). It skips a standby or a source fenced for relocation, becauseCREATE EXTENSIONwould fail there. PostgreSQL normalises the query text, but it can still contain identifiers and some literals. Pushleft therefore keeps statements for 7 days.
pg_stat_statements must be in shared_preload_libraries, which takes effect only when the server starts. The agent passes it to every PostgreSQL container it creates. The specification hash leaves this argument out, so a running container keeps its arguments and does not restart for it. An existing database gets it when its container is next created (a relocation, restore or runtime upgrade). An operator can also set it sooner, in place. Until then, the console says that statements are not collected.
Operator procedure. Nothing runs this automatically.
- On the database host, connect as
pushleft_adminover the container’s socket:docker exec --user postgres <container> psql -U pushleft_admin -d postgres. - Run
ALTER SYSTEM SET shared_preload_libraries = 'pg_stat_statements'. The setting persists in the data directory. - Run
docker restarton that same container. Connections drop and writes fail until it is back: about 2.5 s on staging (2026-10-25, all four databases).
The agent creates the extension at its next sample. Change settings in place like this, without a relocation. Version upgrades can take downtime.
GET /v1/database-instances/{id}/insights?hours=24 (1 to 720 hours, viewer and up, the caller’s organization only) returns:
latest: the newest sample;series: about 48 points over the window, with maximum size, connections and lag, and average tps and cache hit;tablesandstatements, from the newest report that had them;step_seconds.
The console shows them on a database’s page, with its catalogs, roles and operations. The gateway’s ClickHouse user needs INSERT on the three tables. Its database role needs EXECUTE on database_telemetry_admit (deploy/README.md).
Usage alerts
Every managed database is checked in every organization and environment. There is nothing to turn on.
- Disk, every 10 minutes (Valkey: every minute): the size of the data directory on the host, WAL included, against the plan’s disk.
- Memory (Valkey), every minute:
used_memoryagainstmaxmemory. With thenoevictionpolicy, a full Valkey refuses every write.
At 80% and at 95%, the owners of the organization get a mail with the database, its environment and the usage. Each level mails at most once a day per database while it stays over (migration 0230).
Valkey
data.valkey (manifest) runs one Valkey instance (the pinned PUSHLEFT_VALKEY_IMAGE, Valkey 8.1) per environment on the database pool. It goes through the same placement, capacity, quota and teardown as the other engines (migration 0102).
-
Runtime. The agent writes
valkey.confandusers.aclon the instance’s quota volume (/data):- AOF (
appendfsync everysec) and RDB save points are on. maxmemoryis 75% of the plan’s memory, so the fork that writes the RDB fits.maxmemory-policycomes from the manifest (desired_spec.eviction), the one already there, ornoeviction, in that order.defaultis off.pushleft_adminis checked against the SHA-256 of its Vault password, and only a read-only secret file in the container holds that password. The agent’sdocker execreads it there and does not pass it as an argument.- The image’s entrypoint drops to the
valkeyuser. Health isPING.
- AOF (
-
Logins. The agent runs
ACL SETUSER <login> … #<sha256>from the login’s grants, thenACL SAVE. The plaintext password is in no command. Rotation resets the hash. Logins live inusers.aclon the volume, so they survive restarts and come back with a backup. -
Backups. The agent runs
BGSAVEand waits untilLASTSAVEmoves past the start and the save reports ok. It streamsdump.rdb,users.aclandvalkey.confout of the container as one tar intovalkey.tar.sealed. The stream goes through the organization’s seal, with no plaintext on the host. The base is committed, spooled and pruned like the other engines’ bases, so it reaches R2. The drill opens the base into a private scratch directory and runsvalkey-check-rdbfrom the instance’s own image in a container without network. It reports the keys read, and a tampered base fails authentication. -
Restore (built 2026-11-10, migration
0209).pl db restore <valkey> [--backup <id>]loads a daily backup, the latest when none is named, in place. The instance keeps its generation and data directory, and showsmovingmeanwhile.- The agent checks the base’s files and seal, and takes only
dump.rdbfrom it. Logins andvalkey.confstay as they are now, so a login revoked since the backup stays revoked. - It loads the RDB as a checkpoint restore does:
valkey-check-rdb, the file as the base of a new append-only file set,valkey-check-aof, a restart. - If Valkey does not come up on the new files, the old ones go back and the operation is
failed.
Writes made after the backup are lost, and clients reconnect after the restart. A point in time (
--at) is refused: Valkey has daily bases only. With AOF on, Valkey ignores adump.rdbwhen no AOF exists, which is why the RDB becomes the AOF base. - The agent checks the base’s files and seal, and takes only
-
Tests.
scripts/valkey-e2e.shruns the real agent on the pinned image. It covers ensure, health and a login per grant: SET, EVAL, BLPOP and PUBLISH pass, and FLUSHALL, CONFIG, ACL, MIGRATE, BGSAVE and SHUTDOWN are refused. It also covers a sealed backup spooled byte for byte with no plaintext and the drill. A tampered base is refused, and data and logins survive a restart. A restore of the base in place drops later writes, keeps today’s logins and turns AOF back on. The API provisioning test is indatabase_release_tests. -
Planned: relocation (PostgreSQL-only machinery today, which ClickHouse lacks too), insights, and a run with a .NET app using Hangfire and SignalR.
Application volumes
A role may declare volumes: in .pl.yaml:
roles:
web:
port: 8080
volumes: [{ name: uploads, size: 20GiB, mount: /data }] # the one writer
worker:
volumes: [{ name: uploads, mount: /uploads, read_only: true }] # same environment, read-only
pushleft-core validates this. Each volume has one read-write role, and that role runs exactly one replica. Readers declare no size and refer to a writer in the same manifest. Names containing :, / or . are refused as cross-environment references. Sizes run from 1GiB to 1TiB and are given in GiB or TiB. Mounts must be normalized absolute paths outside /proc, /sys, /dev, /etc, /run and /tmp. Only web, private and worker roles may mount volumes. Pushleft still parses the older manifest-level data.volumes map into the plan, and does not execute it.
Shared writers (decided 2026-11-01, for an app whose web and worker roles write the same files). Several roles of one release may write one volume when each sets shared: true and declares the same size. Each still runs one replica:
roles:
backend:
port: 8080
volumes: [{ name: data, size: 5GiB, mount: /var/www/storage, shared: true }]
worker:
volumes: [{ name: data, size: 5GiB, mount: /var/www/storage, shared: true }]
They run together on the volume’s host, so the app’s own file locking holds (one kernel, one remapped uid). The writer whose role name sorts first creates the volume. The others wait for its host, like readers. On a release, the first new writer to be ready stops every old writer of the volume. The others start once those are gone. Writers of the same release do not stop each other, and two releases do not write at once. Migration and import fence every role that mounts the volume, as before.
The scheduler binds a volume to the host of its writer’s first placement. It reserves disk as a fleet_allocations row of kind volume with zero CPU and memory. It records the volume in application_volumes with a quota ID from the shared XFS project sequence. Then it queues a targeted manage_volume ensure job. Readers wait for the writer and then run on the same host. An instance is targeted only once all its volumes are ready and network admission holds. The agent creates PUSHLEFT_APPLICATION_DATA_ROOT/<organization>/<environment>/<name> (default /var/lib/pushleft/data/applications, on the XFS data mount). It has 0700 parents, an ownership marker and an XFS project quota. The data directory itself is 0777, because the image user is unknown. Only those parents lead to it. The application executor mounts exactly the declared volumes: read-write for the writer, readonly for readers. It labels each container with com.pushleft.volume.<name>. It refuses to start if a volume is not provisioned for that tenant and environment.
Teardown removes containers and keeps volumes. A volume that no live instance declares gets a retention window (PUSHLEFT_VOLUME_RETENTION_DAYS, default 30). An admin ends the window early with pl volume delete <environment> <volume> --yes (DELETE /v1/environments/{id}/volumes/{name}, which calls release_application_volume). It is refused while a role of a live release still mounts the volume: remove the volume from the manifest and deploy first. When the window ends, a release job refuses if a running container still mounts the volume. Otherwise it takes a final backup, removes the directory and releases the disk reservation. A nightly backup job writes volume.tar plus its SHA-256 to the same backup store (key volume-<environment>-<name>) under the same retention rules.
Backup files in Fleet
Each agent reports its local backup store about every 10 minutes (fleet_nodes.host_backups, migration 0227). Per source, the report holds every base with its size, the sealed WAL (count and bytes) and the WAL that only older bases need. Fleet’s Backup files page shows it per node (GET /v1/backup-files) and deletes the bases that an operator selects (POST /v1/backup-files/delete, audited as delete_backups). Each source becomes one manage_backups job on its node, in the durability lane, so it never runs during a backup of that source. The agent refuses to delete the newest base of a live source. It re-verifies the oldest base that stays, then deletes the selected bases and the WAL older than that base. A removed source (removed-at) can lose every base, and its directory then goes as a whole. The R2 copies stay until the bucket’s lifecycle rule expires them.
Resize
pl volume resize <environment> <name> <size> (POST /v1/environments/{id}/volumes/{name}/resize {"size":"40GiB"}, members and up) changes the quota of a running volume. The container keeps running. The API only records the request (202). The same size again answers 200. A request for another size while one is in flight, or during a migration, answers 409. The scheduler then does the work:
- Grow. The scheduler checks the host’s disk accounting first. Free disk is
capacity_disk_gbless every reserved or active allocation on that host, this volume included. If the host lacks room, the scheduler refuses the resize. The refusal gives the free and needed GiB and points topl volume migrate ... --size. Otherwise the growth is reserved on the volume’s allocation at once. Then amanage_volumeresizejob raises the XFS project limit (limit -p bsoft=Ng bhard=Ng, read back like at creation). Only then does it rewrite the marker. A replay applies the same limit again. - Shrink. The agent refuses unless the used bytes leave 20% of the new size free. Used bytes come from the XFS project report. A host without quotas uses the apparent file sizes, and there a sparse file counts in full. After a refusal, the size and the reservation stay as they were. A shrink lowers the reservation only after the agent succeeded.
- Manifest. A writer’s
sizeis a floor. A larger size than the volume has grows it before the new release’s role starts. A smaller size is ignored, because only the explicit, checkedpl volume resizestep shrinks. A refused grow fails that deployment with the reason (“cannot grow to N GiB: …”). The scheduler does not request it again on every tick.
The CLI waits for the outcome. Each outcome is an event on the volume: volume_resized or volume_resize_refused with reason. pl volume list <environment> (GET /v1/environments/{id}/volumes) shows the size, the last reported usage and any operation in flight. It also shows the last error and the ten latest events.
Migration between hosts
pl volume migrate <environment> <name> [--size N] (POST .../migrate) moves a volume to another host, and can grow it on the way. Volumes are single-writer, so the roles that mount the volume stop while it is copied:
- The scheduler picks a target: another active, schedulable, fresh application host in the source’s region. The target must have the disk (the target size), CPU and memory for the roles that mount the volume. A host new to the environment also needs the environment-gateway share. Once the environment’s network is sealed, only hosts already in it qualify. Among the hosts that qualify, the environment’s placement node comes first, then the host with the most free disk. The scheduler reserves the target’s disk under a migration ID. It marks every instance that mounts the volume
lost(fenced). It fails their queued work and releases their role capacity. It then queues anexporton the source. While a role that mounts the volume is still being placed, the request waits. - Export (source agent). It removes every container whose mounts include this volume’s data directory. It checks labels first and then the actual mount source, so only containers of this host count. It refuses if one is still running. Then it takes a sealed
volume.tarbackup through the normal backup path (local store, spool). It computes a tree digest of the data: every path, kind and permission bits, plus each file’s size and SHA-256. It uploads the sealed archive through the agent gateway (PUT /v1/agent/jobs/{id}/volume). The gateway takes the lease’s ownexportjob and migration ID and checks the SHA-256. It stores the archive write-once in the blob store’sbackupsuse asvolumes/<org>/<migration>/<backup id>.tar.sealed. Hosts hold no bucket credential. - Import (target agent). It downloads the archive for its
importlease (POSTon the same path) and checks the SHA-256. The backup ID and digest come from the task. It commits the archive as a base in the target’s own backup store. Then it creates the quota directory and marker at the target size. It decrypts and unpacks the archive intoincoming/, and checks the tree digest against the source’s. Only then does it swapincoming/in for the emptydata/. The unpack accepts regular files, directories and symlinks, and refuses hard links and devices. A directory that this import created is removed if any step fails. The agent does not adopt a non-empty directory without a marker. - Cutover (scheduler). The volume’s host becomes the target and the target’s reservation becomes the volume’s. Each fenced instance is replaced with a new ID at the next generation, as for a lost node. Placement binds the replacement to the volume’s new host. The source copy and its disk reservation stay for
PUSHLEFT_VOLUME_MIGRATION_GRACE_SECONDS(default 86400). After that, the normalreleasejob runs on the source. It refuses while a container mounts the copy, takes a final backup and removes the directory. The scheduler then frees the reservation (volume_source_removedwithfinal_backup_id). A failed release is retried every hour. If the source host is lost or retired, the scheduler frees its reservation. - Rollback. If the export or the import fails, the target reservation is released. The volume stays on its source, untouched, and the fenced instances are replaced there (
volume_migration_failedwith the reason). A cordoned source (schedulable=false, still active) still takes the roles bound to its volumes.
These requests are refused up front (volume_migration_refused):
- a volume that a web role mounts, because moving the public ingress route of a live web role is not automated yet;
- a role that mounts more than one volume;
- no host with room;
- a second migration while the previous source copy is still in its grace period. Nightly backups and the retention release skip a volume while it is resized or migrated.
Operators can move every volume off a host before maintenance with pushleft-controller fleet migrate-volumes <node>. It cordons the host and requests one migration per volume. Run it before fleet drain, because a draining node takes no leases and so cannot export. fleet drain warns while volumes are still bound to the host.
Import
pl volume import <environment> <name> <file.tar> replaces a volume’s contents with a tar archive, for data that comes from another platform. The API is PUT /v1/environments/{id}/volumes/{name}/import (admins), with the archive as the body and the header x-pushleft-import-sha256. Make the archive with tar -C <dir> -cf data.tar .. It must be uncompressed, with paths relative to the volume’s root. The volume must exist (deploy once first), be ready and have no resize, migration or import in flight. The archive may be at most the volume’s size.
- The API streams the upload to a temp file and checks the tar header and the SHA-256. It stores the archive in the backup blob store as
volume-imports/<org>/<volume>/<id>.tar. It records avolume_importsrow (migration 0100) and sets the volume’s operation toload_requested. The upload is audited asvolume_imported. - The scheduler fences every instance that mounts the volume, exactly as a migration does. Web roles are included, because the volume stays on its host. It then queues one
manage_volumeloadjob on the volume’s host. - The agent:
- removes every container that mounts the volume;
- takes a sealed safety backup of the current contents through the normal backup path (local store, spool);
- downloads the archive through the agent gateway for its
loadlease, and checks the digest. The directory is beside the volumes and outside the quota; - reads the archive’s entry headers and refuses it if an entry has uid or gid 1 to 999 (see Owners below), unless the import was made with
--keep-owner; - unpacks it into
incoming/, accepting the same entry types as a migration. Owners are shifted into the containers’ user namespace. Archive uid 1000 becomes the host uid that container uid 1000 maps to. Ids at or above 65536 are refused; - swaps
incoming/in fordata/. A failure before the swap leavesdata/untouched.
- Either way the fenced instances are replaced and start on the same host. The outcome on the volume is
volume_imported(withsafety_backup_id,tree_digest,used_bytes) orvolume_import_failed(withreason). Thevolume_importsrow gets itsstatus,reportanderror. The CLI waits for it.
Owners. The default is to refuse an archive in which an entry is owned by uid or gid 1 to 999. Such an archive usually comes from a workstation: a Mac tar keeps its user’s ids (uid 501, gid 20 staff). A container that runs as uid 10001 cannot write those files, and its health check can still pass (gliph’s /data, imported 2026-11-04). Owners 0 (root) and 1000 or higher are accepted. A refused import fails before data/ is replaced. The error names the uid and gid and one example path. To fix it, re-create the tar with the container’s user, tar --owner=<container uid> --group=<container gid> --numeric-owner -C <dir> -cf data.tar . (GNU tar; bsdtar on macOS takes --uid <uid> --gid <gid>). Or run pl volume import ... --keep-owner to import the owners as they are. The flag is sent as x-pushleft-import-keep-owner: true and stored as volume_imports.keep_owner (migration 0163). The scheduler puts it in the load task.
To undo an import, restore the safety backup the same way as any volume backup.
Usage and capacity alerts
Every minute, each agent’s workload lease carries volume_usage (PUSHLEFT_VOLUME_USAGE_INTERVAL_SECONDS): one {project, used_bytes} per marked volume, at most 200. The values come from one xfs_quota report -p on quota hosts and from apparent file sizes elsewhere. The gateway stores them as used_bytes and usage_at, matched by quota project ID and the volume’s current host. It ignores a malformed report, and the lease goes on. Host facts also gain data_disk_total_gb (fleet_nodes.host_data_disk_total_gb). Above PUSHLEFT_VOLUME_NEAR_QUOTA_PERCENT (default 90), the tenant gets one volume_near_quota event per day. scripts/ops-alerts.sh fires these alerts (operations):
node_disk_high(ticket) andnode_disk_full(page): a filesystem over 80% or 95% full, next to the existing under-10-GB page. The agent reports/, the data partition and/var/backups/pushleft(fleet_nodes.host_filesystems, migration 0119). An older agent reports the data disk alone;volume_near_quota: over 90% of quota, with fresh usage;volume_operation_stuck: a resize unmoved for 30 minutes, a migration for 6 hours, or a source copy 2 hours past its grace period.
Tests:
- Agent unit tests cover the quota and marker order and the shrink headroom (
resize_moves_the_quota_then_the_marker_and_refuses_a_tight_shrink). They run against a recordingxfs_quota, because XFS project quotas do not run on Docker Desktop. Other unit tests cover the usage report parser, and the tar round trip with equal tree digests and refused hard links. - Migrated-PostgreSQL scheduler tests cover the capacity and agent refusals, the manifest floor, the fence, the rollback, the cutover and the retirement.
npm run test:volume-migration(scripts/volume-migration-e2e.sh) runs the real API,pl, scheduler, gateway and two agents on one Docker daemon with separate roots. It covers:- an online grow with the same container, a refused shrink and an over-capacity grow;
- a rolled-back migration: the writer comes back on the source with equal data;
- a migration with equal digests, where the writer restarts only after the import;
- the removal of the source copy after the grace period, with a final backup;
- the usage report, the near-quota event and both alerts.
Known limits:
- A writer’s release is stop before start. The new release’s writer starts only after every other instance writing that volume has stopped. The scheduler stops those once the new writer is otherwise ready, after the release run. Two writers therefore do not share a volume. The role is down in between. If the new release then fails, the previous writer stays stopped until the next deployment.
- The tar of a live writer is crash-consistent per file only. A migration’s tar is of a stopped writer.
- Restoring an older volume backup in place is a manual untar.
- Volumes of web roles do not migrate (no ingress relocation for a live host move). Roles that mount two volumes do not migrate. Volumes do not migrate automatically off a draining or lost node. Run
fleet migrate-volumesbefore the drain. A lost node’s volumes stay stranded with it. - A deployment placed during a migration of its volume reserves on the old host and is rejected at cutover (“on different hosts”). Deploy again after the migration.
- Migration archives stay in the blob store (
volumes/prefix). Expire them with a bucket lifecycle rule. - The gateway stages each uploaded or downloaded archive in a temporary file. A 1 TiB volume therefore needs 1 TiB of temporary space on the gateway host.
- IOPS accounting and automatic expansion are not implemented.
Internals
Pushleft treats PostgreSQL and ClickHouse as environment resources, separate from release roles. A new application release reuses the environment’s database instance. Teardown can keep the data path apart from the database container.
The managed host image installs and patches Docker Engine, XFS tooling, the node agent and its systemd unit (fleet). Database jobs never install operating-system packages or run package-manager commands. To “install PostgreSQL or ClickHouse”, the agent reconciles a reviewed, digest-pinned engine image and its durable storage on an enrolled host. The remote job protocol therefore stays typed and cannot become a general-purpose root shell. Jobs reach the node through the agent gateway.
Implemented lifecycle
The control plane stores database instances, logical databases and principals under row-level security per organization. A deployment with data.postgres or data.clickhouse creates or updates the durable instance record. The database APIs are idempotent:
GET /v1/database-instancesGET /v1/database-instances/{id}/catalogsPOST /v1/database-instances/{id}/catalogsGET /v1/database-instances/{id}/principalsPOST /v1/database-instances/{id}/principalsPOST /v1/database-instances/{id}/restoreandGET /v1/database-instances/{id}/operations(restore requests and relocation)POST /v1/database-instances/{id}/upgradeandPOST /v1/database-instances/{id}/upgrade/rollback(upgrades)
The control plane stores only vault:// credential references. The node task is a closed DatabaseTask enum with strict identifiers. It has no raw SQL or shell field.
A manifest can declare the logical databases instead: data.postgres.databases: [{ name, owner_login }], and the same for ClickHouse (manifest: databases). The deployment then creates, once per instance:
- each catalog, with the PostgreSQL owner
<name>_owner; - one login with
connect,read,writeandmigrate. Its credential reference isvault://organizations/<org>/environments/<env>/databases/<engine>/logins/<login>#password.
Later deployments find them and change nothing. Dropping one from the manifest deletes nothing. Roles that list the database get its connection variables. The scheduler targets them only once the instance, catalog and login are ready.
On a host, pushleft-agent manage-database can:
- pull and start a SHA-256 digest-pinned PostgreSQL or ClickHouse image;
- accept images only from the configured engine-specific repository (official repositories by default, configurable for a private mirror);
- enforce CPU, memory, PID, capability, network and data-root boundaries, with a read-only container root filesystem;
- enforce the purchased persistent-disk size with an XFS project quota on managed Linux nodes;
- keep ClickHouse configuration and server logs inside that quota-backed tree, and rotate Docker stdout/stderr logs;
- reconcile only containers that carry Pushleft ownership and specification-hash labels. It acts on one (catalogs, users, health, backups, drills) only after its organization and instance labels match the task;
- start an existing matching instance, and reject silent image or resource drift;
- create a logical database and PostgreSQL owner;
- create or reconcile a user with
connect,read,writeand/ormigrategrants, and revoke grants that are no longer in the desired state; - run an engine-native health check;
- keep data by default, or remove only the exact validated data path from a path-bound task;
- archive PostgreSQL WAL continuously and take verified base backups;
- restore to a point in time into a new generation, and run restore drills (see Backups, PITR and restore drills);
- relocate PostgreSQL to a new generation behind a write fence, on the same node or another one (see Restore requests and relocation);
- move a container from before runtime policy 5 onto the current policy;
- upgrade PostgreSQL to a newer major by dump and restore into a new generation, with a rollback window (upgrades);
- take ClickHouse native backups and verify them by restoring into throwaway databases.
The local maintenance command also does credential rotation and confined removal, for recovery and testing. The online lease loop rejects both operations. Dropping a future is not a database-level fence. Pushleft therefore does not claim that a destructive or credential-changing command stopped because its lease expired.
The command stays an entry point for operations and tests. In normal operation, pushleft-agent run gets the same typed task through the short-lived mTLS lease protocol:
pushleft-agent manage-database \
--task-file /run/pushleft/task.json \
--vault-address https://vault.internal \
--vault-token-file /run/pushleft/vault-token
- The token for this offline command is the operator’s, for that one run. It never stays on the node.
- The Vault token file must be mode
0600or stricter. - HTTPS is mandatory, except for a loopback Vault Agent or OpenBao proxy.
- References use KV v2 paths bound to the organization and environment, such as
vault://organizations/<org>/environments/<environment>/applications/invoice#password. A missing fragment defaults to thevaluefield.
Node secrets
Nodes hold no Vault token (C3). pushleft-agent run needs only PUSHLEFT_VAULT_ADDR. It ignores PUSHLEFT_VAULT_TOKEN_FILE with a warning. The agent gateway brokers every secret.
-
Per lease. The agent gateway holds the only token (
deploy/vault/pushleft-agent-gateway.hcl).- It fences a lease to the node: target node, lease token, organization and placement.
- It checks the task and its secret scope (
validate_secret_scope). - It reads the secret that the task names with
X-Vault-Wrap-TTL(5 minutes).
The secret per task:
ensure_instanceandrestore: the admin password;create_userandrotate_credential: the principal password;ensure_environment_gateway: the pre-auth key, only undermesh/<this node>/;ensure_applicationandrun_application: the role’s environment secrets (…/secrets/<name>) and database login passwords, only when the task’s organization and environment are the lease’s.
The wrapping token goes into the lease response (
wrapped_secrets), never into the stored job. The gateway does not see wrapped values. -
Unwrap. When the task first needs the secret, the agent looks the token up (unauthenticated
sys/wrapping/lookup). It refuses the token unless itscreation_pathis exactly the KV path of the reference. It then unwraps it once. A second unwrap, or one after the TTL, fails. The agent still runsvalidate_secret_scopeitself (defence in depth). -
Customer-owned nodes never reach Vault (decided 2026-11-07). Their bootstrap sets
PUSHLEFT_UNWRAP_VIA_GATEWAY=1and noPUSHLEFT_VAULT_ADDR. The agent then sends each wrapping token with its reference toPOST /v1/agent/secrets/unwrap, and the gateway runs the same lookup and single unwrap against Vault. The token already gave the node the secret, so the route gives it nothing more. The gateway sees the value once, in transit. -
Backup keys.
POST /v1/agent/secrets/backup-keyreturns a wrapped organization key in two cases only. The organization has a live database instance or volume on the node, or a leased database or volume job there. The agent keeps unwrapped keys in memory, because the WAL sealer runs between jobs. One refused organization does not stop the WAL sealing of the others. -
Creation. The gateway creates a missing secret with a random 256-bit hex value and CAS 0. The rule covers a backup key and a database admin password (
databases/<engine>#admin_password). It also covers a manifest-declared login password (databases/<engine>/logins/<login>#password), only for thecreate_usertask of that exact login. The gateway’s policy has noupdate, so it cannot replace an existing value. Any other principal password must already exist. Without Vault on the gateway, or when a read fails, the lease carries no secret, and the job fails on the node.
A compromised node reaches the secrets of work placed on it, and the backup keys of organizations placed on it. It cannot reach the secrets of other tenants, or the mesh pre-auth key of another node.
Disk quotas
Managed database nodes dedicate an XFS filesystem to the configured data root, mounted with project-quota accounting and enforcement. Every database instance gets a durable, globally unique project ID. Before the agent starts the container, it does these steps:
- It assigns the directory tree to the project.
- It applies the plan’s GiB limit.
- It checks the project assignment of every inode.
- It reads the soft and hard limits back exactly.
It fails closed if XFS quota accounting or enforcement is not available, or the report differs. The local one-shot command for integration tests can opt out explicitly; the online lease loop cannot. The scheduler selects and checks again only nodes that advertise database_disk_quota: xfs_project.
The shipped systemd unit does not start unless /var/lib/pushleft/data is a separate mount point. The agent then verifies XFS project-quota accounting and enforcement before it accepts a lease. The environment file holds only certificate and key paths and internal service origins (including PUSHLEFT_VAULT_ADDR). It must never hold an admin password, and no node has a Vault token. See deploy/systemd/agent.env.example.
The release pipeline must also run npm run test:linux-database-quota as root, on a disposable Linux worker with XFS tooling and systemd. It creates only a temporary loopback XFS filesystem. It proves exact limit readback, project inheritance, kernel EDQUOT, reconciliation replay, quota-off refusal and unit-file verification. This gate cannot run on the macOS development host, and is separate from test:all on purpose.
Engine images
Production and integration-test runtime images come from deploy/images.lock.env. PostgreSQL, ClickHouse, Tailscale and Headscale are pinned by multi-architecture manifest digest. Updating a database version is an explicit reviewed change of a pinned digest.
The scan gate. scripts/runtime-image-scan.sh, called by npm run security, fetches and scans both linux/amd64 and linux/arm64 remotely. A locally cached image cannot stand in for the other architecture.
- Every run gets a fresh artifact directory under
output/security/runtime-images/, with per-platform JSON and CycloneDX SBOMs from that same inventory. - The gate validates identity, platform and package inventory.
- It fails on HIGH/CRITICAL findings, failed or incomplete scans, and invalid SBOMs.
- It does not inherit scanner environment or configuration filters, VEX, or ignore inputs.
npm run test:security-policytests failure and ambient-configuration regressions without network access.- The release scanner requires versioned, architecture-correct dpkg records for ClickHouse server/client/common-static, libc6 and libssl3, plus the engine executable, in the package inventory. APK-only scans cannot pass by leaving out copied components.
ClickHouse Alpine variant. The official ClickHouse 26.9.19.9 Alpine variant is an unpromoted candidate.
- The selected Ubuntu variant has a HIGH finding in
libssl3. - Both Alpine architecture scans report no HIGH/CRITICAL findings in their APK inventory. That inventory does not cover components copied outside APK, including glibc and ClickHouse itself.
- Do not treat this smaller inventory as a clean replacement, and do not bypass the release gate.
- A provisional lockfile change was reverted during local review. No live workloads changed.
- Promotion needs more evidence of component provenance and security.
The real agent management suite passed against the Alpine candidate.
ClickHouse compatibility check. npm run test:clickhouse-image is a separate compatibility check. It uses a fixed original Ubuntu baseline and disposable, networkless host-bind containers. Across Ubuntu → candidate → Ubuntu, including a candidate restart and writes, it verifies:
- root and file-secret bootstrap, and the non-root server UID/GID;
- zero effective, permitted and ambient capabilities, and
NoNewPrivs; - no published ports;
- persisted Unicode/JSON data, RBAC and a 90-day TTL.
Both architectures ran locally. A run on native Linux is still required. The check proves same-version variant compatibility only. Security approval, backup/PITR, replication and major-version upgrades need their own checks. No vulnerability exceptions were added. Pushleft does not replace existing managed instances automatically.
- Run
npm run test:clickhouse-image -- linux/amd64or-- linux/arm64to select an architecture. The default matches the Docker worker architecture. PUSHLEFT_CLICKHOUSE_CANDIDATE_IMAGEselects another local or registry test candidate. It never changes the production lockfile.- The baseline is still vulnerable, and only these tests use it. Production release stays blocked; Pushleft does not claim that the selected image is safe.
ClickHouse libssl candidate. deploy/images/clickhouse-libssl.Dockerfile is the preferred unpromoted patch candidate. It keeps the pinned Ubuntu image and updates only signed Ubuntu packages, to exact versions: libssl3 to 3.0.2-0ubuntu1.30, and apt with libapt-pkg6.0 to 2.4.15ubuntu0.1. The install runs with Acquire::Retries=0, because the vulnerable apt installs its own fix.
-
Scan evidence, 2026-11-09: Trivy 0.76.0 finds 0 HIGH or CRITICAL on amd64 and arm64 (
Pushleft/imagesrun 42601267843). The published image isghcr.io/pushleft/clickhouse@sha256:7325fe640733825f38c7eb0abbc771e63f20baac4a4cb42286e1a16482f79527. -
The compatibility results below are from the
libssl3-only candidate of 2026-10-17. They need a rerun on the published digest before promotion. -
Both local architecture builds keep 111 inventoried packages and have no HIGH/CRITICAL findings in their Trivy reports.
-
Compatibility tests on both architectures also require byte-identical
/usr/bin/clickhouseand/entrypoint.sh. -
The fixture authenticates the bootstrap file password and rejects wrong or empty passwords. It verifies that a reader can SELECT and cannot INSERT or run DDL. It compares records captured before a restart.
-
It attests UID/GID 101, zero capabilities and NoNewPrivs for PID 1 and the ClickHouse processes.
-
The candidate is published to GitHub Container Registry, and
images.lock.envdoes not select it yet. A promotion review and the compatibility suite on the published digest are still required.
docker build --platform linux/arm64 -f deploy/images/clickhouse-libssl.Dockerfile -t pushleft-clickhouse-libssl-candidate:arm64 .
PUSHLEFT_CLICKHOUSE_CANDIDATE_IMAGE=pushleft-clickhouse-libssl-candidate:arm64 PUSHLEFT_CLICKHOUSE_REQUIRE_IDENTICAL_BINARIES=1 npm run test:clickhouse-image -- linux/arm64
Repeat for amd64. The candidate has an expiring, path-only DS002/static-analysis exception for its root bootstrap. The reason and the residual bootstrap risk are the same as for the PostgreSQL candidate below. The upstream entrypoint must drop daemon privileges. Do not add untrusted init scripts or extra mounts. This exception does not suppress package findings or authorize promotion.
For promotion evidence, also set PUSHLEFT_CLICKHOUSE_SCAN_REPORT to the matching per-architecture Trivy JSON.
- The fixture then requires the scanned image ID and platform to match the actual candidate container.
- Successful output includes a JSON evidence record. It holds the baseline and candidate immutable IDs, the selected platform manifests and the engine and entrypoint SHA-256 hashes. It also holds the platform, the engine version, the SHA-256 of the scan report, and whether strict byte identity and scan binding were on.
- The fixture refuses optimized Python execution before any runtime action, so assertions cannot disappear.
- It needs a Docker API that exposes the container
ImageManifestDescriptor. It does not accept an ambiguous index-default architecture. - A compatibility log without those bindings is not enough promotion evidence.
PostgreSQL gosu candidate. deploy/images/postgres-gosu.Dockerfile is an unpromoted security candidate. It takes the pinned PostgreSQL 17 or 18 base through BASE and keeps its entrypoint. It rebuilds upstream gosu 1.19 from checksum-pinned source, with digest-pinned Go 1.27.3. It also upgrades the Alpine packages that the 2026-11-09 scan names: brotli-libs, libcurl, musl, musl-utils and zlib. Pushleft/images publishes both majors, with 0 HIGH or CRITICAL on amd64 and arm64 (Trivy 0.76.0). images.lock.env selects them since 2026-11-09. New databases use them at once. An existing instance moves with fleet upgrade-database-runtimes.
Evidence, 2026-11-09: postgres-image-probes.py passed on arm64 for both majors, plain and with pgvector, against the published digests. test:database-backup, test:database-relocation and test:database-upgrade passed on arm64 against them. On amd64, a production instance moved with fleet upgrade-database-runtimes and passed its restore drill. Local candidate builds have separate reports in output/security/. To build a candidate and run its compatibility test for an architecture:
docker build --platform linux/arm64 -f deploy/images/postgres-gosu.Dockerfile -t pushleft-postgres-gosu-candidate:arm64 .
python3 scripts/fixtures/postgres-image-probes.py "$PWD" pushleft-postgres-gosu-candidate:arm64 linux/arm64
Repeat for linux/amd64 with the matching tag. The fixture uses only disposable host-bind data and password files with unique scopes, and networkless containers. It verifies:
- root-owned PGDATA and root-only file-secret bootstrap;
- the final TCP postmaster (not the temporary socket server of initdb);
- the UID/GID of all PostgreSQL processes;
- zero effective, permitted and ambient capabilities, and
NoNewPrivs=1, before and after a restart; - an unchanged engine version;
- a Unicode/JSON/index/grant/identity dump and restore.
It then removes its own resources. It does not verify backup/PITR, online migration or HA. Promotion still needs a registry-hosted immutable multi-platform digest, agent-managed XFS integration, upgrade compatibility and all release scans. Do not bypass existing instance specification fences to install it.
The candidate has narrow Trivy DS002 and Opengrep last-user-is-root exceptions on its USER root bootstrap instruction, reviewed through 2026-11-15. The Trivy exception expires automatically.
- The exceptions keep the upstream entrypoint’s ownership setup for root-owned host binds and root-only file secrets that the agent creates. The daemon and workers must then run non-root, with the constraints above.
- They do not suppress package vulnerabilities.
- A residual risk remains during the root bootstrap: compromised bootstrap code could change its mounted data with the bounded ownership and UID capabilities. Do not add untrusted init scripts, extra mounts or command overrides to that path.
- The exceptions are not approval to promote the image. Review them again or remove them before they expire.
Image promotion evidence (2026-10-17)
No digest was promoted, and deploy/images.lock.env is unchanged. Scans used Trivy 0.72.0 with the release policy of scripts/runtime-image-scan.sh (remote, per platform, full inventory, no ignore file). Reports are in output/security/runtime-images/ and output/security/candidates/ (local, ignored by git).
| Image | Pinned (unchanged) | Newest upstream checked | Upstream result (amd64 and arm64) | Local candidate |
|---|---|---|---|---|
| PostgreSQL | 17.11-alpine3.24 b0f9560a… | Alpine: none newer. 17.11 (Debian trixie) 2d2b8998… | Pinned: 25 HIGH/CRITICAL, all Go stdlib in gosu 1.19 (go1.24.6). Trixie: worse (same gosu plus unfixed Debian libxml2, ncurses, gnupg, systemd, util-linux, acl findings); rejected. Alpine to glibc also changes collation. | postgres-gosu.Dockerfile rebuilt: 0 HIGH/CRITICAL on both, 45 APK + 4 Go packages inventoried; postgres-image-probes.py passed on both. |
| ClickHouse | 26.9.19.9 bdb5c911… | 26.9.20.23 83243a00… | Both: CVE-2026-84782 in libssl3 3.0.2-0ubuntu1.29 (fixed in Ubuntu 1.30, not yet in any upstream ClickHouse image). Not promoted, no gain. | clickhouse-libssl.Dockerfile rebuilt: 0 HIGH/CRITICAL on both, required dpkg inventory present; clickhouse-image-e2e.sh passed on both with scan binding and byte-identical engine/entrypoint. |
| Tailscale | v1.104.1 87c55d6b… | v1.104.1 is the newest stable | Both: CVE-2026-78667, CVE-2026-78669, CVE-2026-97031 (Go 1.27.1 stdlib, x/net 0.59.0). Fixed in Go 1.27.2 / x/net 0.60.0; the 1.104 release branch has not shipped it. unstable-v1.105.59 (924f6a5d…) scans clean but is an unstable track; not promoted. | none |
| Headscale | v0.29.5 780ed2f9… | v0.29.5 is the newest release | Both: 8 IDs (CVE-2026-56852, CVE-2026-56854, CVE-2026-78667, CVE-2026-78669, CVE-2026-84304, CVE-2026-84445, CVE-2026-97031, GHSA-hrxh-6v49-42gf) in Go 1.26.8 stdlib, x/text, x/crypto, x/net, grpc 1.81.1. Fixed versions exist; Headscale main has the Go/x fixes but still pins grpc 1.81.1. | none |
Update 2026-11-09. This table holds the results of 2026-10-17. Both Dockerfiles have changed since, and Pushleft/images now builds and scans them. The candidate sections above have the current evidence.
The two local candidates were clean on 2026-10-17. Promotion still needs:
- immutable registry publication with provenance;
- the remote per-platform gate, run against the published digest;
- the live agent suites, which take only registry digests.
A local tag must not go into the lock file. No Trivy exception was added for any package vulnerability. The findings are accepted, time-boxed to 2026-11-16, in deploy/security/image-risk-register.json. The file is a decision log only. The scanner does not read it.
PostgreSQL 18 (2026-10-21)
Decision (2026-10-21): PostgreSQL 18 is the default major for new managed databases and a reviewed upgrade target. Databases on 17 keep 17 until an operator upgrades them. The control plane’s own PostgreSQL stays on 17.
PUSHLEFT_POSTGRES_IMAGEispostgres:18-alpine(18.6, Alpine 3.24), index digest77f58511…. The previous pin, 17.11-alpine3.24b0f9560a…, is nowPUSHLEFT_POSTGRES_17_IMAGE. The flavour is the same as before (Alpine), so the collation provider does not change between the two majors.- Scan (Trivy 0.72.0, release policy of
scripts/runtime-image-scan.sh,linux/amd64andlinux/arm64): 1 CRITICAL and 24 HIGH, all Go stdlib IDs ingosu1.19 (go1.24.6). The 17 image has the same 25 IDs. There are none in PostgreSQL or in the Alpine packages. The gate stays red for both images. Both are accepted, time-boxed to 2026-11-16, indeploy/security/image-risk-register.json. The scan gate now also scansPUSHLEFT_POSTGRES_17_IMAGE. - The 18 images declare
VOLUME /var/lib/postgresql, the parent of the data mount (17 declared the data mount itself). Without a mount there, Docker adds an anonymous volume to each container: writable outside the XFS quota, and left behind bydocker rm. The agent mounts a 1 MiB tmpfs there in each PostgreSQL container that it starts (serving generations, restore drills, upgrade checks). The data stays in/var/lib/postgresql/data/pgdata(an explicitPGDATA), so the 18 entrypoint’s check for the old data layout does not apply. deploy/images/postgres-gosu.Dockerfilebuilds 17 and 18 throughBASE.scripts/fixtures/postgres-image-probes.pytests each major against its own pin.
Security model
Containers.
- The agent writes the PostgreSQL bootstrap password atomically to a root-only file, and mounts it read-only at
/run/secrets/admin_password. - Containers use a read-only root filesystem, bounded tmpfs mounts and a rotating local Docker log driver.
- They drop the Docker default capability set. For official-image initialization they get back only
CHOWN,DAC_OVERRIDE,FOWNER,SETGIDandSETUID. - PostgreSQL database-owner and login-principal roles have separate ownership markers. The API and the agent both reject reuse of an owner or login across catalogs.
- The agent escapes user passwords into fixed engine-specific SQL templates and sends them on stdin.
- Docker arguments, task JSON, logs, labels and the control-plane database hold no secret values.
Admin roles are container-local. pushleft_admin is a PostgreSQL superuser. A superuser can run COPY ... PROGRAM, which is a shell in the database container.
- The agent writes a fixed
pg_hba.confnext to the instance’s secrets and mounts it read-only at/etc/pushleft/pg_hba.conf. It starts PostgreSQL with-c hba_file=pointing at it. The engine and the entrypoint’s append toPGDATA/pg_hba.conftherefore cannot widen it. pushleft_admincan log in only over the container-local socket (trust; the agent’sdocker exec) and over loopback (SCRAM; the health check).- PostgreSQL rejects any other TCP login for it, and every replication login over TCP, before authentication. Nobody on the environment network can brute-force it.
- Tenant principals keep SCRAM over the network.
ClickHouse has no network admin at all:
- The container starts with
CLICKHOUSE_SKIP_USER_SETUP=1, so the entrypoint writes nodefault-user.xml(which admits a password admin from::/0). - The agent’s read-only
users.dremoves the image’sdefaultuser. It defines onlypushleft_local_admin, with no password and limited to127.0.0.1and::1. Onlydocker execreaches it, anddocker execalready equals host root. access_control_improvements.table_engines_require_grantis on. Amigrateprincipal getsTABLE ENGINEgrants for the MergeTree family,Memory,NullandJoinonly.Joincame on 2026-11-05, because lightweightUPDATEbuilds one. Existing logins got it by hand. It cannot createURL,File,S3or other remote-access tables.
Ownership labels. Database containers carry com.pushleft.organization, com.pushleft.network (the environment segment) and com.pushleft.database-instance, next to the managed, engine and specification-hash labels. The organization and network are also part of the specification hash.
Before the agent acts on an existing container, it checks that the container is managed and carries the task’s instance label. When the task names an organization, the label must match it too. This applies to catalogs, users, credential rotation, health, backup, drill and re-ensure. The agent refuses a container without these labels (created before runtime_policy: 5). Only the fenced steps that move it onto the current policy accept it (runtime policy upgrade).
Network. Database containers do not publish ports. They join the environment’s private container bridge at a fixed address in the host’s environment /24:
- x.126 for PostgreSQL;
- x.125 for ClickHouse;
- x.3 to x.119 for applications.
The next ensure moves a container created before this rule to its address. The gateway derives the address from the instance’s node and sends it with an application lease. Applications on other hosts connect over the environment mesh (mesh coordinators). This needs --stateful-filtering=false on the gateways: Tailscale’s stateful filtering dropped every forwarded flow (G4). On staging, db-app in scripts/staging/staging.sh smoke checks the cross-host path.
Database placement and agent leasing enforce selected-host attachment and firewall-generation gates. The agent can apply and verify environment nftables rules. Before production admission can open, these still need to be connected: Headscale provisioning, host route publication, host-wide input and provider policy, and recurring attachment verification.
Placement and lifecycle state
pushleft-scheduler reserves the CPU, memory and persistent disk of an eligible node first. Only then does it turn an ensure_database_service intent into a validated, digest-pinned DatabaseTask::EnsureInstance.
- The task carries the disk limit and its durable project-quota ID, so placement accounting and host enforcement describe the same resource.
- Catalog and principal operations stay untargeted until the instance reports
ready. They then follow its active node. - Successful or terminal agent results update the instance, catalog or principal state in the same transaction as the append-only result.
Disk size. A manifest can choose a larger initial disk with data.postgres.disk or data.clickhouse.disk, for example 300GiB or 75GiB (manifest: databases).
- CPU and memory stay at the chosen plan.
- Sizes are whole GiB or TiB, at least the plan floor and at most 1 TiB.
- The scheduler stores and reserves the canonical GiB value, and passes it to the quota-enforced provisioning task. Later restore, relocation and upgrade generations use it too.
- An API request cannot change a disk that is already reserved. It returns
409before it changes durable intent. A manifest withoutdiskkeeps the reserved disk.
Plans
Set the plan in data.postgres.plan. Manifests reject other names. These are the PostgreSQL sizes:
| Plan | vCPU | Memory | Disk from |
|---|---|---|---|
dev | 0.5 | 512 MiB | 10 GiB |
starter | 1 | 2 GiB | 20 GiB |
standard | 2 | 4 GiB | 50 GiB |
performance | 4 | 8 GiB | 100 GiB |
large | 8 | 24 GiB | 100 GiB |
xlarge | 16 | 48 GiB | 200 GiB |
ClickHouse and Valkey have the plans dev, starter, standard and performance, with their own sizes. large and xlarge are for PostgreSQL only.
Change a plan. Edit the plan and deploy.
- The scheduler checks that the database’s node has room for the extra CPU and memory. If it does not, the deployment waits. The database keeps running.
- The agent replaces the container on the same data. The database restarts once, with a stop limit of 120 seconds.
- PostgreSQL gets
shared_buffersof a quarter of the plan’s memory and/dev/shmas large as the plan’s memory.
A plan change keeps the reserved disk, even when the disk is under the new plan’s floor. To choose a different disk, deploy into a new environment.
On Pushleft Cloud, the plan’s CPU and memory are billed by the compute meters. On your own servers, the plan sets the size only and costs nothing. When the fleet has no room, the scheduler retries, and the service is not marked failed. See fleet capacity.
High availability. HA requests fail closed at placement. Pushleft does not create two unrelated writable databases and call that HA. Before this gate opens, replication, a quorum witness in a third failure domain and writer fencing must exist. Backups and PITR do not change that.
Required before production
The following remain fail-closed or missing, and are not advertised as working:
- automated node enrollment and certificate issuance/rotation;
- a run of
pushleft-offsiteagainst the real R2 bucket, with its lifecycle and lock rules, and a restore drill from R2 on staging; - relocation leftovers (Restore requests and relocation):
- a stable per-environment database address, so a cross-node move needs no application restart. Today each instance is recreated once and is down for a short time;
- relocating off a node that is already draining (it leases nothing);
- operator recovery of a failed promotion;
- a way for customers to reach or promote a restored generation;
- proof on native Linux with XFS quotas, and between real hosts;
- replica bootstrap, quorum/witness policy and promotion fencing (
promote_replicastill returns an explicit error); - upgrade leftovers (see known limits of upgrades): a reviewed production digest for a second PostgreSQL major and ClickHouse upgrades;
- a large-cluster upgrade path (
pg_upgradeor logical replication), and upgrade proof on native Linux with XFS quotas; - IOPS accounting, automatic disk expansion, and migration of web-role and multi-volume roles’ volumes;
- proof of volume resize and migration on native Linux with XFS quotas between real hosts. Storage capacity alerts, volume resize and migration exist (Application volumes);
- successful execution of the quota-enabled Linux host release gate, including restored generations and volumes (live pinned-engine integration tests are already scheduled in CI).
Related
- The manifest: databases: declare databases and volumes in
.pl.yaml. - Agent gateway: leases and brokered secrets.
- Mesh coordinators: how applications reach a database on another host.
- Robot hosts runbook: the off-host backup copy.
- Architecture: managed databases