Skip to content

feat(cli): run the application tier as a colour replica set - #3277

Merged
larryro merged 9 commits into
mainfrom
feat/stateless-color-replica-set
Sep 7, 2026
Merged

larryro merged 9 commits into
mainfrom
feat/stateless-color-replica-set

Conversation

@larryro

@larryro larryro commented Sep 7, 2026

Copy link
Copy Markdown
Contributor

Folds platform, backend-api and backend-worker into one stateless
colour 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-set plan. Two of that plan's core
mechanisms 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 — default 1, clamped 1-16. Default
    topology is unchanged: 1+1+1.
  • The config volume becomes config-data. The first tale deploy /
    tale dev after this copies convex-data across and never deletes it.
  • A deploy briefly runs two application tiers. Documented, with the sizing
    consequence.
  • The first deploy also removes the pre-upgrade tale-backend-api /
    tale-backend-worker containers, 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 /ready on
backend-api:3005 eject draining replicas. A static hostname upstream is ONE
upstream to Caddy — the probe lands on a random replica and the verdict marks
the whole upstream, so it flaps rather than converges. dynamic a gives
per-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. /ready still exists, consumed by the CLI.

The drain flag was deployment-wide. app.backend_control held one
draining row that every replica read, so the plan's beginDrain before the
flip would have refused chats on the new colour too, for the whole drain
window. Migration 0085 adds draining_colour; NULL keeps the old meaning so
an 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 disconnect it: that severs live
connections, 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.generations row the api's drain waits on, so killing the worker first
makes the drain burn its full budget on a generation nothing is advancing.

Found by running it against a real daemon

  • docker compose build bakes com.docker.compose.project/service into
    the image.
    Anything docker run from it answers a project+service filter
    — a throwaway tale-db for an integration run is indistinguishable from the
    real 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 container
    creation) is the discriminator.
  • The pre-upgrade backend tier would have been orphaned — it lives in the
    stateful project, so neither colour's teardown sees it, and it would keep
    answering backend-api on the old image.
  • An integration probe that had never passed. Three lanes deleted a
    SANDBOX_TOKEN they had only overridden, so the task-agent watchdog's
    exec-cancel probe reported cancels=none on every invocation. Fixed, and
    the class is now guarded per lane rather than the instance patched.

Verification

Gate Result
bun run check 40/40 tasks
bun run --filter @tale/platform backend:integration 530 pass / 0 fail
Generated colour compose, real docker compose config parses; no container_name, no cross-project depends_on
--scale on it platform-1, backend-api-1/2, backend-worker-1/2/3
Shared alias resolves to both api replicas; stops resolving after the disconnect
Volume copy tree + .history carried, mode 600 / owner 1001 preserved on a secrets file, old volume intact, idempotent
Env guard red-proved, then green

Not verified: a full tale deploy flip against published images. The
mechanics 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, because
ensureVolumes pre-creates the target on every deploy and an existence check
would skip the copy on exactly the upgrade that needs it.

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.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant