Skip to content

feat(db): let only 1 dipper process write, enforced by the database - #858

Merged
cjorge-thegraph merged 5 commits into
mainfrom
cjorge/fence-the-writer
Nov 23, 2026
Merged

cjorge-thegraph merged 5 commits into
mainfrom
cjorge/fence-the-writer

Conversation

@cjorge-thegraph

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

Copy link
Copy Markdown
Contributor

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 fix(shutdown): stop taking jobs first and fit the teardown in its budget #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

cjorge-thegraph and others added 5 commits November 20, 2026 16:57
Dipper's flows assume a single process acts: the signer's nonce and the
locks that keep 2 jobs off the same agreement live in the process. Nothing
enforced it. When a pod is evicted, deleted or its node drained, Kubernetes
starts the replacement while the old pod is still shutting down, and for
that time 2 processes act.

The writer fence makes the database enforce it. Every session of a dipper
process carries a random token of that process (the setting `dipper.writer`
and the name `dipper/<token>`). The table `dipper_writer` names the process
allowed to write, and a statement trigger on every table refuses a write
from any other session with SQLSTATE DP001. A process another one has
taken over from is refused however late it finds out, so 2 processes
overlapping behave like the older one crashing, which the flows survive.

- A migration adds the 2 tables and the functions; startup fences every
  table that lacks the trigger, so a table a later migration adds is fenced
  without anyone having to remember. Migrations run on a session marked
  `operator`, which the fence lets through, as it does manual work.
- Just before the services start, the process waits while another one is
  the healthy writer, takes over once it hands over or has been silent for
  20 seconds, waits for the statements the old one had in flight, and ends
  its sessions, which frees the jobs and session locks it held.
- A heartbeat keeps the writer the writer until the last step of its stop,
  which hands over. 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 transaction a takeover waits for.
- `SELECT dipper_fence_set(false)` switches the fence off, across restarts.

Tests: the existing registry suite now runs through the fence, and new
tests cover who may write, takeover and handover, the cut, the broadcast
guard and the exit of a replaced process, against a real Postgres.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…ITTED, and bound the RPC timeout

- A broadcast's writer check runs on a 1-connection pool of its own, as the heartbeat
  has a connection of its own, so the main pool's sizing is what it was: a config sized
  exactly for its worker loops keeps starting.
- The check's transaction is opened as READ COMMITTED whatever the database's default,
  and the guard function refuses any other level, as the write fence does: under
  REPEATABLE READ each check would have read the token as the first one did and missed
  a takeover.
- `chain_client.request_timeout` is held to at most 12s, below the 15s a takeover waits
  for a broadcast attempt of the process it replaces, so no attempt can outlast it
  unless its process is frozen.
- Tests: a write already queued behind a takeover is refused once it 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
  default isolation; a broadcast whose check fails sends nothing; the timeout bound.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
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 <noreply@anthropic.com>
The writer fence's tests start their Postgres on its Unix socket only, as #861 does
for the rest, and the registry's test databases keep the operator session and the
writer pool on top of it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@cjorge-thegraph
cjorge-thegraph marked this pull request as ready for review November 23, 2026 20:32
@cjorge-thegraph
cjorge-thegraph merged commit 6f88900 into main Nov 23, 2026
13 checks passed
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>
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