Repository navigation
feat(cli): run the application tier as a colour replica set - #3277
Merged
Merged
Conversation
The org config store is files, and `atomicWrite` makes a single file's replacement atomic — temp file, fsync, rename. What it cannot make atomic is a READ-MODIFY-WRITE, and nearly every config write is one: read the current file, snapshot it into `.history/`, prune the trail, write the new content, delete a superseded sibling. Two writers interleaving there lose an update or strand a half-written pair — an SSO connection is `connection.yml` plus `connection.secrets.json`, and committing one writer's config against the other's secrets authenticates against the identity provider with a mismatched credential pair. A per-process mutex cannot cover this. The api and the worker have always both mounted the store read-write, and a colour flip runs two api replicas at once. The database is the one thing every writer shares, so the lock lives there — on `pg_advisory_xact_lock` rather than a lock file, so a deployment that moves the config volume onto a network filesystem keeps working. `withConfigWriteLock` takes it per `(org, domain)`, which is exactly the granularity of the directories it protects. It handles both postgres.js handle shapes: the root `sql` has `begin` and a transaction handle has `savepoint`, never both, and a `xact` lock taken on the root without opening a transaction is released by the implicit one before the work runs. The governance writers pass their audit transaction, so the file write and the audit row commit together. Covered: SSO, governance policies, object storage, knowledge, branding, agents, the deployment config's compare-and-set, and the org scaffolder. Skills already held a finer per-(org, slug) lock of the same shape. Also fixes the `org.scaffold` dedup this leans on: the queue carried no `policy`, so `standard` treated `singletonKey` as a throttling label and the key deduped nothing. Set `short`, and key the reprovision sweep's enqueue too — a keyless job on a keyed queue shares the default key with every other one.
`app.backend_control` carried ONE `draining` flag for the whole deployment and every api replica read it. That was right while the api was a singleton rolled in place: the CLI set the flag, the chat doors refused new turns, the container was recreated, the flag was cleared. It is wrong the moment two colours of the api serve at once. A blue-green flip starts the new colour, drains the OLD one and waits for its in-flight generations — so a deployment-wide flag refuses chats on the colour the flip just promoted, for the whole drain window. That is exactly the outage the overlap exists to avoid. `draining_colour` (0085) names the colour a drain is aimed at, and a replica refuses new turns only when it matches its own `TALE_COLOR`. NULL keeps the old meaning — every replica — deliberately, which is what makes it safe in both directions of a rolling deploy: an older CLI writes no colour and drains everything as before, a newer CLI's extra column is ignored by an older backend, and the tiers that are not colour-rolled want exactly that. Adds `GET /ready`, separate from `/ping` on purpose. `/ping` is liveness and stays 200 while a replica drains, so Docker does not kill a container that is deliberately finishing the in-flight work the drain is waiting for. `/ready` is the deploy's question — 503 once a drain names this replica — and is not proxied: it is not the internet's business. `backend:integration` covers it: a drain aimed at another colour leaves this replica at `ready=200 ping=200`, its own colour flips to `ready=503 ping=200`, and an unaimed drain still applies.
Two changes that cannot be separated, because the second is what makes the
first mount the right volume.
THE CONFIG VOLUME IS RENAMED. `convex-data` was named when Convex owned the
store; the runtime is gone, the backend tier owns every write, and the name
misleads everyone who reads a compose file. Docker cannot rename a volume, so
changing the string alone silently mounts a NEW, EMPTY one and the deployment
comes up with no organization configuration at all. `migrate-config-volume.ts`
copies the contents across before anything remounts, deciding on CONTENT and
not existence — `ensureVolumes` pre-creates the target on every run, so an
existence check would skip the copy on the very upgrade that needs it. The
writers are paused for the copy, `cp -a` keeps the mode and ownership the
secrets sidecars need, a failure aborts the deploy with the old volume intact,
and `convex-data` is never deleted. Restore honours BOTH archive names and now
says so when a snapshot carries neither.
THE APPLICATION TIER BECOMES ONE COLOUR. `platform`, `backend-api` and
`backend-worker` share an image and their wire contracts, so they must never
version-skew: they now deploy together as a colour, sized by
TALE_{PLATFORM,BACKEND_API,BACKEND_WORKER}_REPLICAS (default 1, clamped 1-16).
None pins a `container_name` — a pinned name and `--scale` are mutually
exclusive — so every lookup goes through the compose project/service LABELS,
which also finds the pre-upgrade containers the first deploy has to retire.
The flip is ordered, and only this order is safe: bring the idle colour up (a
booting replica is not listening, so the resolver falls through to the live
one), wait for EVERY replica, record the switch, drain the old colour's api
for its colour alone, let the web tier's window elapse, and only THEN
`docker network disconnect` it — that severs live connections, so doing it
before the drains would drop exactly what the drain protects. Caddy is
untouched: a static hostname upstream is ONE upstream to it, and its dynamic
upstreams disable active health checks entirely, so neither can pick healthy
replicas.
Two things found by running it against a real daemon:
- `docker compose build` BAKES `com.docker.compose.project`/`service` into the
image, so anything `docker run` from it answers a project+service filter —
and what the lister returns is what a teardown STOPS. `container-number`
(never an image label, always stamped at creation) is the discriminator.
- The pre-upgrade `backend-api`/`backend-worker` live in the stateful project
and belong to neither colour, so nothing else sweeps them; left running they
answer the same alias on the old image. `retireLegacyBackendTier` removes
them once, after the new colour is serving.
Three sandbox lanes ended their `finally` with `delete process.env.SANDBOX_TOKEN` — deleting a variable they had only OVERRIDDEN. By the time the task-agent watchdog lane ran, forty lanes later, the token was gone no matter what the runner exported, the exec-cancel client refused to send an unsigned request, and its probe reported `cancels=none`. That probe could not pass on any invocation. It was not flaky; it was dead, and it named the watchdog while the cause sat elsewhere entirely. `overrideEnv` puts the previous value back, including "it was absent". The watchdog lane additionally mints its own token: it runs its own stub spawner, so it should not depend on the runner's environment at all — which is why the probe failed even on the documented invocation, that sets none. The class is now guarded rather than the instance patched. `runLanes` diffs `process.env` around every lane and fails THAT lane, by name, when it destroys a value that existed before it. A variable a lane introduces and tidies away is deliberately not reported: that restores the true prior state and harms nobody. Red-proved by re-injecting the delete with the runner supplying the token — "checkTaskAgentTurnDrive leaves the environment as it found it — SANDBOX_TOKEN (deleted)" — then green. Also makes the object-store bootstrap probe say why it failed. It deletes the bucket to simulate a vanished store, and S3 refuses to delete a non-empty one, which is what a REUSED store looks like; a bare `dropped=false` read as a product bug and cost a full investigation. README now states that BOTH the database and the object store must be throwaway — a reused database truncates the run at the first lane that recreates a fixture user.
The upgrades page claimed "a database constraint enforces single-active". No such constraint has ever existed. The real mechanism — both colours holding the same alias, a colour-scoped drain, then a network disconnect — is now written out step by step, including the overlap window where the host runs two application tiers and what that costs on a single box. New page: Customize Compose, in all three locales. It replaces the draft that said the api is a singleton and that `tale deploy` does not take `--scale`; both are now false. It covers which role to raise for which symptom, what raising one does NOT fix, the four services that stay singletons and why each, and the overlay path per install kind. Also: the config volume is `config-data` everywhere (overview, backups), the container-architecture failure notes stop calling the api a single point of failure by design, and the environment reference gains the replica knobs.
Four exports written while building the colour replica set that no caller ever reached: a `ROTATABLE_SERVICES` spread helper, a `BackendTierService` type guard, a re-export of `backendApiContainers` from the drain lane, and `listContainersUsingVolume`, which only its own module calls. Caught by knip, which `bun run check` does not include — `bun run verify` does.
Write the drain through a new-image replica, snapshot the live convex-data store, retire leftover singletons before the long drain, and resume an interrupted flip instead of reversing it.
The Linux server page taught Docker and host hardening the product does not own. Operators now get tale init/dev/deploy or a compose contract; contributor overlays move to Develop.
This was referenced Sep 7, 2026
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Folds
platform,backend-apiandbackend-workerinto one statelesscolour replica set, renames the config volume, and makes the deploy drain
colour-aware so a flip cannot silence the colour it just promoted.
Implements the
stateless_color_replica-setplan. Two of that plan's coremechanisms turned out not to work and were redesigned — both are called out
below, because reviewing this without them is reviewing the wrong design.
What changes for an operator
TALE_PLATFORM_REPLICAS,TALE_BACKEND_API_REPLICAS,TALE_BACKEND_WORKER_REPLICAS— default1, clamped1-16. Defaulttopology is unchanged: 1+1+1.
config-data. The firsttale deploy/tale devafter this copiesconvex-dataacross and never deletes it.consequence.
tale-backend-api/tale-backend-workercontainers, which belong to neither colour.Two plan mechanisms that do not work, and what replaced them
Caddy cannot pick healthy replicas. The plan had
health_uri /readyonbackend-api:3005eject draining replicas. A static hostname upstream is ONEupstream to Caddy — the probe lands on a random replica and the verdict marks
the whole upstream, so it flaps rather than converges.
dynamic agivesper-replica upstreams but disables active health checks entirely (Caddy's own
docs). Caddy is therefore untouched: the flip drains the old colour and then
docker network disconnects it./readystill exists, consumed by the CLI.The drain flag was deployment-wide.
app.backend_controlheld onedrainingrow that every replica read, so the plan'sbeginDrainbefore theflip would have refused chats on the new colour too, for the whole drain
window. Migration
0085addsdraining_colour; NULL keeps the old meaning soan older CLI and the non-colour tiers are unaffected.
The flip, and why only this order
Bring the idle colour up — a booting replica is not listening, so the resolver
falls through to the live colour. Wait for every replica. Record the
switch. Drain the old colour's api, for its colour alone. Let the web tier's
window elapse. Only then
docker network disconnectit: that severs liveconnections, so doing it any earlier drops exactly the requests the drain
exists to protect.
Deviation from the plan, deliberate
The plan said stop the old workers immediately at flip. They come down with
the rest instead: an agent turn's job is what heartbeats the
app.generationsrow the api's drain waits on, so killing the worker firstmakes the drain burn its full budget on a generation nothing is advancing.
Found by running it against a real daemon
docker compose buildbakescom.docker.compose.project/serviceintothe image. Anything
docker runfrom it answers a project+service filter— a throwaway
tale-dbfor an integration run is indistinguishable from thereal one. Since what the lister returns is what a colour teardown stops,
that was a false positive that could stop an unrelated container.
container-number(never an image label, always stamped at containercreation) is the discriminator.
stateful project, so neither colour's teardown sees it, and it would keep
answering
backend-apion the old image.SANDBOX_TOKENthey had only overridden, so the task-agent watchdog'sexec-cancel probe reported
cancels=noneon every invocation. Fixed, andthe class is now guarded per lane rather than the instance patched.
Verification
bun run checkbun run --filter @tale/platform backend:integrationdocker compose configcontainer_name, no cross-projectdepends_on--scaleon itplatform-1,backend-api-1/2,backend-worker-1/2/3.historycarried, mode600/ owner1001preserved on a secrets file, old volume intact, idempotentNot verified: a full
tale deployflip against published images. Themechanics above were each exercised directly instead.
Reviewing
Read the commits in order. The riskiest change is the volume copy in
migrate-config-volume.ts— it decides on content, not existence, becauseensureVolumespre-creates the target on every deploy and an existence checkwould skip the copy on exactly the upgrade that needs it.