Skip to content

fix(shutdown): stop taking jobs first and fit the teardown in its budget - #854

Merged
cjorge-thegraph merged 4 commits into
mainfrom
cjorge/shut-down-in-order
Nov 23, 2026
Merged

cjorge-thegraph merged 4 commits into
mainfrom
cjorge/shut-down-in-order

Conversation

@cjorge-thegraph

@cjorge-thegraph cjorge-thegraph commented Nov 19, 2026 •

Copy link
Copy Markdown
Contributor

Makes dipper's shutdown finish inside its own time budget, and stops the worker taking new jobs at the start of a shutdown rather than near the end.

Why:

  • main's stop sequence no longer fits its budget. It stops 15 services one at a time, each capped at 5s, then flushes events and closes the pool. Its worst case is about 85s, past the 75s TEARDOWN_GRACE. A slow shutdown then ends with the supervisor aborting whatever is left, instead of finishing in order: the DB pool close is skipped, and lifecycle events still in the in-memory queue may never reach Kafka.
  • The worker is 13th in line. It keeps taking new jobs for most of a shutdown, then gets 5s to finish them. A job started during shutdown is usually cut off part-way, which wastes its IISA and RPC calls and gives it a retry on the next start.

What changes:

  1. The worker drains while its feeders stop. It stops taking jobs and gets 45s (WORKER_DRAIN) to finish the ones it is running. A job still running then is cut off: it is dropped, which rolls its queue transaction back, so it runs again on the next start, and the loops exit at once (CUT_OFF_WAIT, 2s at most). Meanwhile the services that feed the worker or call it stop together: the admin RPC, reassignment, expiration, the liveness checker, the DIPs info watcher, the chain listener, cancel retry, the escrow reconciler and the indexing request consumer. A job queued meanwhile stays in the database queue for the next start.
  2. Then the services the jobs read from stop together: indexer URLs, the RCA domain refresh, the entity count cache and the suggested minimums.
  3. The health endpoint, the event flush and the pool close follow as before.
  4. A stop that panics is logged with its service's name, and its panic carried on once the others in its wave have stopped, so the teardown fails rather than reading as clean.

The ceiling is 45s for the drain, 2s for a cut-off, then 4 steps of 5s: 67s. A compile-time assert keeps it under TEARDOWN_GRACE, so adding a step can't silently push shutdown past its budget again.

What this is not: a safety mechanism. The drain saves work, but a job can be cut off at any point anyway: by a crash, a kill, or by running longer than the drain (jobs may run up to 420s). Re-running a job that was cut off must therefore be safe however shutdown behaves. That belongs in the jobs themselves, through recorded intents and transactional state in Postgres, not in shutdown ordering.

Tests:

  • The stop helpers: services_stopped_together_take_as_long_as_the_slowest, wedged_services_stopped_together_cost_1_cap, the_worker_gets_its_own_limit, a_panicking_stop_fails_the_sequence_once_the_others_have_stopped.
  • The worker's stop, over loops the tests play: a_stop_lets_running_jobs_finish_within_the_drain, a_stop_cuts_off_jobs_still_running_at_the_end_of_the_drain, a_job_runs_to_its_end_unless_cut_off.
  • The budget is checked at compile time.
  • On current main (sqlx 0.9, Rust 1.94): cargo +nightly fmt, cargo clippy --all-targets --all-features -D warnings and cargo nextest run --all-features pass locally.

The tests cover the stop helpers and the worker's stop, not which wave each service is in.

🤖 Generated with Claude Code

Shutdown stopped the services 1 at a time, each given up to 5s, and the worker 13th: until its
turn it kept taking new jobs, and then it had 5s to finish the one it was running, which a job
seldom does, so the job was dropped part-way and the DB pool close skipped. With the services
added since, the sequence could take 85s, past the 75s after which the supervisor stops waiting
for it and aborts what is left.

Shutdown now goes in 2 waves. First the worker stops taking jobs and gets 45s to finish the ones
it is running, while the services that feed it work or call it (the admin RPC, reassignment,
expiration, the liveness checker, the DIPs info watcher, the chain listener, cancel retry, the
escrow reconciler and the indexing request consumer) stop alongside. The queue is in the
database, so a job queued meanwhile waits there for the next start. Then the services the
running jobs read from (indexer URLs, the RCA domain refresh, the entity count cache and the
suggested minimums) stop together. The health endpoint, the event flush and the pool close
follow as before. The ceiling is the 45s drain and 4 steps of 5s, 65s, and a compile-time check
keeps it under the supervisor's 75s.

A job still running after 45s is dropped as before, rolling its queue transaction back so it runs
again on the next start.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@cjorge-thegraph cjorge-thegraph changed the title fix(shutdown): stop taking jobs first and stop the rest alongside fix(shutdown): stop taking jobs first and fit the teardown in its budget Nov 20, 2026
cjorge-thegraph and others added 2 commits November 23, 2026 19:42
… ends

The worker's 45-second drain only stopped the teardown waiting for it: a job still
running went on alongside the rest of the stop, losing the events it queued after the
flush and keeping the pool from closing, until the supervisor aborted it at 75s.

- At the end of the drain the stop now cuts the loops' jobs off. A cut-off job is
  dropped, which rolls its queue transaction back, so it runs again on the next start,
  and the loops exit at once. The stop sequence's ceiling counts the cut-off's wait.
- A stop that panics in a wave is logged with its service's name, and its panic is
  carried on once the others have stopped, so the teardown fails instead of reading
  as clean.
- The k8s README and a comment on the health endpoint's step said otherwise; they
  now describe what happens.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@cjorge-thegraph
cjorge-thegraph marked this pull request as ready for review November 23, 2026 19:49
@cjorge-thegraph
cjorge-thegraph merged commit a1bc47d into main Nov 23, 2026
13 checks passed
cjorge-thegraph added a commit that referenced this pull request Nov 23, 2026
Every test's temporary Postgres now listens on its Unix socket only, so
a parallel test run can no longer start it on a port another process has
just taken.

**The failure:** main's CI on the merge of #854 failed in
`dipper-pgregistry::it_registry_postgres::a_dips_info_block_denies_an_indexer_until_it_lapses_or_the_indexer_answers`
with `Failed to connect to temporary database: PoolTimedOut` after 30s
([run](https://github.com/graphprotocol/dipper/actions/runs/45253035363/job/137967456797)).
The same kind of failure, a different test each time, has shown up in
local runs.

**Why it happens:** pgtemp 0.6 picks a free TCP port by binding port 0
and closing it, then starts Postgres on that port a moment later (its
source marks this as a race). In a parallel run, another process can
take the port in between, a test's wiremock server for instance.
Postgres then can't bind it and exits, and the test waits out its pool's
30-second timeout on a server that never started.

**The fix:** each test's Postgres starts with `listen_addresses=''` and
is reached through the socket pgtemp already puts in its data directory.
With no TCP port involved, there is nothing to lose.
- `dipper-service`: `test_support::temp_postgres`, `temp_postgres_from`,
`temp_postgres_options` and `temp_postgres_url`, used by the `db`,
`telemetry` and Studio consumer tests. The password-checking server in
the `db` tests checks passwords on its socket.
- `dipper-pgregistry` and `dipper-pgmq`: their test helpers start and
reach the server the same way.

**Tests:**
- `it_a_temp_postgres_answers_when_its_port_is_taken` holds the port
first. With pgtemp's default server it fails (Postgres can't start, so
its socket never appears), and it passes with this change.
- `cargo +nightly fmt`, `cargo clippy --all-targets --all-features -D
warnings`, and 3 full runs of `cargo nextest run --all-features` (1,268
tests each) pass locally.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-authored-by: Claude Opus 5.5 <[email protected]>
cjorge-thegraph added a commit that referenced this pull request Nov 23, 2026
The handover becomes the 5th capped step after the worker's drain; the stop's ceiling
counts it (72s, under the 75s grace). The k8s README keeps the writer fence's text.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
cjorge-thegraph added a commit that referenced this pull request Nov 23, 2026
…858)

## Why

Dipper's flows assume a single process acts. The signer's nonce, the
reassessment lock and the Studio consumer's ordering all live in the
process, and its sweeps and chain listener are built to repair what a
crash of that 1 process leaves behind. Nothing enforced that there is
only 1. `strategy: Recreate` covers rollouts only: when a pod is
evicted, deleted or its node drained, Kubernetes starts the replacement
while the old pod still has up to 90 seconds to stop, and for that time
2 processes act. They can hand out the same nonce, both register
agreements for 1 request, apply Studio records out of order, or land an
offer after dipper cancelled it.

## What this does

The database enforces the single writer, with a **writer fence**:

- Every session of a dipper process carries a random token of that
process: the setting `dipper.writer`, and the name `dipper/<token>` in
`pg_stat_activity`. Both are set once, in `db::connect`; every
connection dipper opens derives from the pool's options.
- `dipper_writer` holds the current writer's token. A statement-level
trigger on every table takes a shared advisory lock, then reads the
token, and refuses a write from any other session with SQLSTATE `DP001`.
A replaced process is refused however late it learns of it, so 2
processes overlapping behave like the older one crashing.
- **Taking over**, just before the services start: wait while another
process is the healthy writer; take over once it has handed over or been
silent for 20 seconds; wait (up to 15 s) for the statements and
broadcasts it had in flight; then end every session still named for
another dipper process, which rolls back what it had open and frees the
jobs and session locks it held.
- **Staying the writer**: a heartbeat every 5 seconds, on its own
connection, from the takeover to the last step of the stop, which hands
over so the next process starts at once. A process that finds it has
been replaced, at a heartbeat or at its first refused write, stops
through the usual teardown.
- **Chain broadcasts** aren't database writes, so `send_transaction`
asks the database before each attempt, inside a READ COMMITTED
transaction a takeover waits for, on a 1-connection pool of its own. A
replaced process starts no new attempt. The 1 exception: an attempt
already in flight when its process froze can still land after the
takeover. `chain_client.request_timeout` is held at 12 s or less, so
otherwise an attempt in flight ends within the takeover's 15 s wait.
- Migrations run on a session marked `operator`, which the fence lets
through, as it does manual work. Startup fences every table that lacks
the trigger, so a table a later migration adds is fenced without anyone
having to remember.
- `SELECT dipper_fence_set(false)` switches the fence off, and it stays
off across restarts until switched on again.

For database writes, timing only decides how soon a handover happens. If
every timing value were wrong, the worst outcomes would be a takeover
from a process that was still healthy (that process then behaves as
crashed) or a late takeover (downtime), never 2 writers. For chain
broadcasts, there is the 1 exception above: a transaction a frozen
process had already started sending.

## Changes

| Where | Change |
| --- | --- |
| `dipper-pgregistry/migrations/20261120000000_add_writer_fence.sql` |
The 2 tables and 12 functions |
| `dipper-pgregistry/src/writer_fence.rs` | What a process asks of the
fence: take, drain, cut, beat, release, attach, and the broadcast guard
|
| `bin/dipper-service/src/writer.rs` | Fencing the tables at start, the
takeover, the heartbeat and handover, the exit when replaced, and the
broadcast gate |
| `db.rs`, `main.rs` | The pool carries the token; migrations on an
`operator` session; the takeover before the services start; a
1-connection pool for the broadcast check; the handover as the stop's
last step, counted in the stop's ceiling (72 s, under the 75 s grace) |
| `chain_client` | `AlloyChainClient::new` takes a `BroadcastGate`;
`send_transaction` checks it before each attempt |
| Registry error conversion, worker settle paths | A refused write tells
the heartbeat, which checks at once |
| Studio consumer lock | Its session is named under the process
(`dipper/<token>/studio-request-lock`), so a takeover frees it |
| `config.rs` | `chain_client.request_timeout` at most 12 s; the writer
events alerted on by default. The main pool's sizing is unchanged |
| `k8s/README.md`, `deployment.yaml` | The planned-window advice for
evictions and drains is withdrawn; how to operate the fence |

## Operating it

Manual SQL that writes needs `SET dipper.writer = 'operator';` first, or
`PGOPTIONS='-c dipper.writer=operator'`. `k8s/README.md` lists how to
see the writer, hand over from a writer that won't stop, and switch the
fence off. New log events: `writer_taken`, `writer_waiting`,
`writer_superseded`, `writer_drain_blocked`, `writer_fence_off`,
`writer_fence_attach_waiting`, `writer_refused_while_writer`.

Requirements: Postgres 14 or later (both environments run 16), READ
COMMITTED (the fence refuses writes at any other level), sessions that
keep their settings (direct or the Cloud SQL Auth Proxy, not a
transaction-mode pooler), dipper's sessions on 1 database role, no
prepared transactions, and `chain_client.request_timeout` of 12 s or
less (default 10 s).

## Rollout and rollback

- **First deploy:** the migration seeds the fence as released, so the
first process takes over at once. From the moment startup attaches the
triggers, a process of the previous release can't write, as its sessions
carry no token; it has no broadcast guard either, so this 1 rollout
relies on `Recreate` stopping the old pod first, as every rollout does
today.
- **Rollback:** `SELECT dipper_fence_set(false);` as dipper's database
role, then deploy the previous release. Its migrator already tolerates a
newer schema.
- **Before deploying:** check that the deployed config's
`chain_client.request_timeout` is 12 s or less (startup refuses more),
and don't drain nodes until the fenced release is the one running, since
an older pod has no broadcast guard.
- **Operators:** manual writes, such as through a `psql` client pod,
need `SET dipper.writer = 'operator';` first; they are refused
otherwise.
- **Before mainnet:** confirm nothing else writes to dipper's database,
and, once dipper is behind the Cloud SQL Auth Proxy, that a setting
given at connect reaches the session (`PGOPTIONS='-c
dipper.writer=operator' psql …` then `SHOW dipper.writer`).

## Testing

- The SQL was first built as a prototype and pressure-tested on Postgres
16.16 and 18.4. Its test suite, run against this migration, gives the
same outcome on every check. In its stress run of 14 takeovers under
load, with every replaced generation still writing, 0 rows landed
outside their writer's turn and 0 transactions were half-applied. A
takeover under 4 to 48 clients writing without pause waited 11 to 24 ms;
the fence adds about 0.02 ms per write.
- The existing registry integration suite (134 tests) now runs through
the fence: its databases are set up as dipper's start leaves them, with
the test pool as the writer.
- New tests against a real Postgres: who may write; takeover, handover
and silence; the drain and the cut; the broadcast guard; every table
fenced, the queue's without the lock; sessions carrying their token and
name; a replaced writer stopping at its first refused write; a running
job of the replaced writer going back to the queue; a broadcast stopping
at its first attempt after a takeover.
- Since review: a write already queued behind a takeover is refused once
the takeover commits (the lock is taken before the token is read);
writes and broadcast checks outside READ COMMITTED are refused with
`DP002`; a broadcast guard sees a takeover whatever the database's
default isolation; a broadcast whose check fails sends nothing; the
request-timeout bound.
- On current `main` (sqlx 0.9, Rust 1.94, with #854): `cargo +nightly
fmt --check`, `cargo clippy --all-targets --all-features -D warnings`,
and `cargo nextest run --all-features` pass locally.

## Not in this PR

- **A crash gap that can cost money**, independent of the fence: an
agreement marked `Unresponsive` whose offer, queued before a crash,
lands and is accepted on chain is neither applied by the listener nor
ended by its repair path (`ended_but_accepted` covers only `Rejected`
and `CanceledByRequester`). A separate small PR.
- **An end-to-end test with 2 real dipper processes**, and a crash test
that kills dipper at random moments to find the remaining crash gaps.
- **graph-infra's operator notes** for the `psql` client pod should say
to `SET dipper.writer = 'operator'` before a manual write.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

---------

Co-authored-by: Claude Opus 5.5 <[email protected]>
MoonBoi9001 pushed a commit that referenced this pull request Nov 23, 2026
🤖 I have created a release *beep* *boop*
---


##
[0.3.4](v0.3.3...v0.3.4)
(2026-11-23)


### Added

* **config:** type secrets as such and read config from several files
([#857](#857))
([fe92407](fe92407))
* **db:** connect to Postgres over TLS
([#847](#847))
([2673181](2673181))
* **db:** let only 1 dipper process write, enforced by the database
([#858](#858))
([6f88900](6f88900))
* **db:** make the database password optional
([#850](#850))
([cb5d3b1](cb5d3b1))
* **metrics:** serve Prometheus metrics and optionally log as JSON
([#851](#851))
([523819e](523819e))
* **rpc:** expose effective indexing targets and chain identity
([#860](#860))
([aafc0ce](aafc0ce))
* **startup:** wait for Postgres and IISA instead of exiting
([#849](#849))
([d1406d4](d1406d4))


### Fixed

* **db:** sslmode=verify-ca skips the hostname check, as libpq does
([#859](#859))
([5fec97d](5fec97d))
* **k8s:** roll dipper out one pod at a time
([#846](#846))
([de57e46](de57e46))
* **shutdown:** stop taking jobs first and fit the teardown in its
budget ([#854](#854))
([a1bc47d](a1bc47d))


### Tests

* run each test's Postgres on its Unix socket only
([#861](#861))
([bc9e2b2](bc9e2b2))

---
This PR was generated with [Release
Please](https://github.com/googleapis/release-please). See
[documentation](https://github.com/googleapis/release-please#release-please).

Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
@MoonBoi9001
MoonBoi9001 deleted the cjorge/shut-down-in-order branch November 26, 2026 13:00
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