Plan: database degradation posture (#1599)
Status: In progress
Epic: &80
Issues: #1599 (parent, chaos plan U11) · #3481 U1 (w2) · #3482 U2 (w3) · #3483 U3 (w5) · #3484 U4 (w8) · #3485 U5 (w3) · #3486 U6 (w3)
Closes: #1599 (by U6)
Branches: docs/adr-053-db-degradation-posture, feat/db-error-taxonomy, feat/db-statement-ceiling, feat/db-typed-commit, feat/retry-after-honoured, test/pool-rig-enforces
This is a Design + Scope plan: GitLab owns tracking, the child issues carry the implementer brief, and the plan freezes when U1 starts. The decision record is ADR-053.
Context
canopy has no stated posture for a degraded database. What the code does today:
-
Pool exhausted.
ApiError::databaseandApiError::internal_database(crates/canopy-common/src/error.rs) turnsqlx::Error::PoolTimedOutintoApiError::ServiceUnavailable("database connection pool exhausted"), a 503 (#1296). The answer carries noRetry-After.ApiError::internal(context, err)does not reclassify, so a pool timeout that reaches it is a 500. -
Slow statement. The pool every service gets from
canopy_api::bootstrap(crates/canopy-api/src/bootstrap.rs) sets nostatement_timeout. A statement behind a lock or a sick database runs until the caller gives up; service clients give up at 30 s (DATA_PATH_TOTAL_TIMEOUT,crates/canopy-common/src/http.rs). The statement keeps its connection after the caller has gone. -
Local bounds exist in a few places, each a hand-written
SET LOCAL statement_timeoutstring or a pool session setting: the identity issuer pool (5 s,services/canopy-security/src/identity/registry.rs), the renewals drain (300 s,services/canopy-renewals/src/store.rs), the reporting ladder, the audit summary, the chain-staging router, the archive mover, the chain verifier, the extension host. -
Commit. A zero-argument
.commit()is called about 570 times in non-test files underservices/andcrates/(178 of them in canopy-applications, 14 in canopy-db itself). That count includes in-file test modules; U4's gate gives the exact production number. An error from it becomes an ordinary 500. The fault lega_commit_whose_answer_is_lost_errors_although_the_row_is_committed(crates/canopy-db/tests/db_test/contested.rs) shows the error does not mean "not committed". -
Callers.
canopy_api::retry::classify(crates/canopy-api/src/retry.rs) decides from the status alone, retries every 5xx with its own backoff, and reads noRetry-After. The retry loop drops a retryable response without reading its body. -
Measured. The pool-contention rig (
crates/canopy-db/tests/db_test/pool_contention.rs, #1598) shows a full pool lends what it has and times every other caller out at the 5 s acquire bound.
Rulings this plan implements (maintainer, 2026-11-20, recorded on #1599)
Each is the option the maintainer chose of those put to him.
-
"Introduce a fleet-wide statement timeout with route-class ceilings."
-
"Pool default of 30 s; long jobs raise it per transaction."
-
The typed commit: "Yes: fleet edit to the helper, plus the lint."
Design
The taxonomy (U2)
ApiError gains three variants, each with a fixed status, a fixed RFC 9457 code and fixed detail text. ApiError::ServiceUnavailable(String) and its other callers are untouched.
| Variant | Raised for | Status | Answer |
|---|---|---|---|
|
|
503 |
code |
|
a database error with SQLSTATE |
504 |
code |
|
|
500 |
code |
-
ApiError::databaseandApiError::internal_databasereturnPoolExhaustedwhere they returnpool_exhausted()today, andStatementTimeoutfor57014, before the integrity-class check. Integrity classes and the redacted 500 are as today. -
into_responsewrites theRetry-Afterheader forPoolExhausted. The value is the constant one second, the smallest the header can state and the hint the idempotency middleware already gives. Erratum (2026-11-20): the approved draft justified it by the rig showing a waiter served as soon as a connection returns; the rig does not measure that (its winners hold past the bound), so the value stands as a choice, not a measurement. -
The
pool_exhaustedfunction and its tests inerror.rsmove to the variant. One service maps a pool timeout by hand: canopy-rules's evaluate route (EvaluateError::Overloadedinservices/canopy-rules/src/engine.rs) answersServiceUnavailable("rules engine database pool exhausted"). U2 moves it toPoolExhausted, so that route answers the code and the hint too, and sends its other database errors throughApiError::databaseso a57014there is a 504. The rules client (crates/canopy-rules-client/src/lib.rs) maps any 503 from canopy-rules by status to its ownServiceUnavailable("rules engine overloaded: …")and stays as it is (it answers its caller 503 without the hint; forwarding the hint is out of scope). Erratum (2026-11-20): the approved draft said no other code maps pool exhaustion; the canopy-rules mapping was found in review of this page, and U2 gains it. U2 grepsPoolTimedOutacross production code to confirm there is no third. -
ApiError::internalkeeps not reclassifying; the convention page already says so.
The statement ceiling (U3)
-
canopy-dbgainsStatementBudget(Duration), a newtype, and two uses of it:-
DbPoolOpts::statement_budget: Option<StatementBudget>, sent as thestatement_timeoutsession setting, so it holds from a connection's first statement. -
canopy_db::set_statement_budget(tx, budget), which runsSET LOCAL statement_timeoutinside the caller's transaction. It sets the budget for that transaction, above or below the pool's.
-
-
canopy_api::bootstrapsets the application pool's budget from a new setting,db_statement_timeout_secs, default 30, validated at startup to lie in 1..=300. The migration pool (migration_phase) gets none: a migration may run long by design. -
Route classes, stated in the ADR and as named constants in canopy-db:
Class Ceiling Where Request (default)
30 s
every pool
canopy_api::bootstrapbuildsIdentity issuer
5 s
the issuer pool; its existing
statement_timeoutsession setting is re-expressed as aStatementBudget, value unchangedBatch
300 s
a background job's own transaction, set explicitly
-
set_statement_budgetreplaces the hand-written string at these sites, values unchanged:services/canopy-reporting/src/worker/ladder.rs,services/canopy-renewals/src/store.rs,services/canopy-security/src/store/mod.rs,services/canopy-security/src/chain_staging/router.rs,services/canopy-security/src/archive/mover.rs,crates/canopy-db/src/chain_verify.rs. -
Left as they are: the extension host (
crates/canopy-extension-host/src/sandbox.rs), which sets statement and lock timeouts together for a module call; canopy-test-lib; and canopy-web's session store, whose 2 sSTATEMENT_TIMEOUTis a client-side wait, not a server setting. -
A job that needs the batch ceiling is found by inventory in U3, not by waiting for it to fail: every statement the background workers run outside a transaction that already sets a budget is listed in the child issue with its measured or reasoned duration.
-
lock_timeoutis not part of this plan.
The typed commit (U4)
-
canopy-dbgainscommit(tx) → Result<(), CommitError>withCommitError::Refused(sqlx::Error)(the server answered with an error: nothing was committed) andCommitError::OutcomeUnknown(sqlx::Error)(no answer was read: I/O, protocol, closed connection).From<CommitError> for ApiErrormaps the first throughApiError::databaseand the second toCommitOutcomeUnknown. -
Every production
.commit()on a transaction becomescanopy_db::commit(tx); a site that wraps the future (canopy-web'sbounded(…, tx.commit())) wraps the helper's instead. -
The
db-poolsgate (xtask/src/cmd/db_pools.rs) gains a finding, bare-commit: a.commit()method call with no arguments, in production code. It follows the gate's existing rules: no allowlist;crates/canopy-test-lib/and test code are exempt. Within canopy-db only the module that defines the helper is exempt; canopy-db's own 14 sites use the helper too. The gate matches names, not types. The session stores'commit(key, claim, record, …)methods (canopy-auth, canopy-web) take arguments and are not matched; a production type that later gains a zero-argumentcommitwould be, and is renamed. -
What the idempotency middleware does with the new 500 is unchanged: it is a 5xx and is released to the failed cooldown as today. Making a keyed retry replay rather than re-run after an unknown commit is its own issue, #3487.
Callers (U5)
All decisions stay status-based; no response body is read.
-
canopy_api::retry::classifystops on 504. No canopy service answers 504 today (a search forGATEWAY_TIMEOUTin production code finds only a canopy-web client test of an upstream's 504). -
crates/canopy-api/src/idempotency.rsis_retryable_failurekeeps 504 in its set, so a 504 is never stored for replay under a key. Its comment, which says it mirrorsclassify, is corrected to say where the two now differ and why. -
The retry loop reads
Retry-After(delta-seconds only) from a 503 before it drops the response. When present, the wait before the next attempt is the hint, capped at the policy'smax_backoff, with jitter applied upward only so the caller never returns early. The existing overall-budget handling is unchanged: the wait is cut to the remaining budget and the next pass ends inRetryError::OverallTimeout. -
No client type changes: canopy-web's
ServiceError::upstream_codealready carries the RFC 9457 code. canopy-cli is out of scope.
The rig enforces (U6)
-
The pool-contention test asserts the shape more tightly: each winner that needed a new connection acquired under one second, and each timeout fell within 250 ms of the bound (two seconds today).
-
A second test drives a real service route with its pool held full and asserts the HTTP answer: 503,
Retry-After: 1, codedb_pool_exhausted.
Scope
In scope: ADR-053; the three ApiError variants and their codes; Retry-After on pool exhaustion; the statement budget type, the pool default and the per-transaction setter; the six hand-written timeout strings replaced; the typed commit, the fleet edit and the bare-commit finding; retry stopping on 504 and honouring Retry-After; the rig's promotion; the docs and CHANGELOG below.
Out of scope: lock_timeout; a second pool per service; replaying a keyed request after an unknown commit (#3487); a production knob for the acquire bound; changing any client's own timeout; canopy-cli; canopy-store; the extension host's timeouts.
Units
| Unit | What | Depends on |
|---|---|---|
U1 |
ADR-053. |
— |
U2 |
Taxonomy. |
U1 |
U3 |
Statement ceiling. |
U2 |
U4 |
Typed commit. |
U3 |
U5 |
Callers. |
U2 |
U6 |
Rig enforces. The two tests above; the chaos plan's U11 row marked done. |
U3, U4, U5 |
The units land in order, U2 to U6. Erratum (2026-11-20): the approved draft said U3, U4 and U5 touch disjoint code and may land in any order, and made U6 depend on U3 and U5 only. U3 and U4 both edit canopy-db and the transaction functions that set a statement budget, so U4 follows U3; and U6 closes the parent, so it follows U4 as well.
Erratum (2026-11-20, U4): the gate counted 282 production commits, not about 570 (the estimate included in-file test modules). 67 of them sit where the surrounding code expects a sqlx::Error (mostly store functions that return one), which the design did not provide for: CommitError converts to a sqlx::Error carrying a marker (canopy_common::error::CommitOutcomeUnknown), so those functions keep their signatures. ApiError::database, internal_database and, new in this unit, ApiError::internal read the marker, the last anywhere in its source's error chain; U2 had said internal never reclassifies, and it still does not for a pool timeout or a cancelled statement. Three surfaces with their own mapping were changed to keep the outcome: canopy-overpayments' ledger commits (now OverpaymentError::Store, not a ledger inconsistency), canopy-identity's admin writes (the coded 500, not a 503 that invites a retry) and canopy-web's composition API (the code in its own error body). Not done, and why U4's issue stays open: canopy-identity's session store and canopy-web's session and draft stores reduce a database error to their own fault types before any HTTP mapping, and the token endpoint answers in OAuth's error vocabulary; what an unknown commit should answer there is a design question. A background worker has no HTTP caller and reports the failure as before. canopy-mq, canopy-overpayments, canopy-extension-host (under its runtime feature) and canopy-verification gained a canopy-db dependency to reach the helper. A refused commit is pinned on a live database with a deferred constraint (a_commit_the_server_refuses_is_refused_not_unknown), which the plan's test list lacked.
Erratum (2026-11-20, U5): the budget test is named a_hint_past_the_overall_budget_ends_in_a_timeout_at_the_budget, because either of the loop's two timeouts can end the call (as the existing budget test already allows). a_503s_retry_after_sets_the_wait_before_the_next_attempt was added: it drives the loop end to end, which the two wait-calculation tests do not.
Erratum (2026-11-20, U6): U6's MR does not close #1599 or mark the chaos plan's U11 done, as this plan said it would: U4's issue is still open for the session stores, and the parent closes when that does. The route test is on canopy-rules' evaluation list, driven in-process over a real one-connection pool; it waits out the 5 s acquire bound once.
Risks
| Risk | Mode | Mitigation |
|---|---|---|
A background statement that legitimately runs longer than 30 s now fails with 57014. |
fail-closed |
U3's inventory lists every worker statement before the default lands and sets a batch budget where needed; the car's integration and e2e lanes run every worker at the new default; the setting can be raised per deployment. |
A migration is cut off by the ceiling. |
fail-closed |
The migration pool gets no budget. Test: |
A statement cancelled at 30 s leaves a half-done multi-statement job. |
fail-closed |
Cancellation aborts the transaction; the workers concerned commit per unit of work (the crash legs of #1597 pin it for four of them). No new behaviour. |
|
silent |
The retry loop adds upward jitter to the hint (U5 test |
A caller treats |
silent |
The code and the ADR say the outcome is unknown; the convention page tells callers to retry only under an idempotency key. The keyed-replay gap is its own issue (#3487); this plan does not claim to close it. |
A bare |
silent |
The bare-commit finding refuses it on the car. Tests: |
A 57014 raised by a deliberate cancel (not the timeout) is reported as a timeout. |
silent |
Postgres uses one SQLSTATE for both; the detail says "cancelled or timed out". Nothing in canopy cancels statements today. |
The ceiling is sent as a startup option and a pooler or proxy drops it. |
fail-open |
Test |
Not retrying a 504 hides a statement that would have succeeded on a second try. |
fail-closed |
The caller gets the 504 and its code and can retry deliberately; a keyed request is not stored, so the same key may run again. |
Tests
Unit (fixture-only):
-
U2:
a_pool_timeout_is_a_503_with_retry_after_and_its_code;a_statement_timeout_is_a_504_with_its_code_and_no_retry_after;internal_never_reclassifies_a_database_failure;the_integrity_classes_answer_as_before;the_evaluate_route_answers_pool_exhaustion_with_the_typed_503(canopy-rules); the rules client's existing overload test passes unchanged. -
U3:
a_statement_budget_reaches_the_connect_options;the_migration_pool_carries_no_statement_budget;a_budget_outside_one_to_three_hundred_seconds_refuses_to_start. -
U4:
a_refused_commit_maps_through_the_database_arm;an_unanswered_commit_is_the_coded_500;a_bare_commit_in_production_code_is_a_finding;a_commit_in_test_code_or_with_arguments_is_not_a_finding;the_workspace_has_no_bare_commit. -
U5:
a_504_is_not_retried;a_retry_after_hint_is_waited_with_upward_jitter;a_hint_is_capped_at_the_policys_longest_backoff;a_hint_past_the_overall_budget_ends_in_overall_timeout;a_504_under_an_idempotency_key_is_released_not_stored.
Contract (wire format): the RFC 9457 body's code member for the three codes and the Retry-After header are pinned in canopy-common's response tests, and the regenerated OpenAPI snapshots carry the 503 and 504 answers.
Integration (devstack, on the car):
-
U3:
a_pool_built_with_a_budget_reports_it_from_the_server;a_statement_past_the_budget_fails_with_57014_and_frees_its_connection(apg_sleeppast a one-second budget);a_budget_set_in_a_transaction_holds_for_that_transaction_only. -
U4: the fault leg
a_commit_whose_answer_is_lost_errors_although_the_row_is_committedis extended to assertCommitError::OutcomeUnknown(fault lane).
Concurrency: U6's two tests (the rig's tightened split, and a route answering 503 with Retry-After while its pool is held full).
Regression: each service's existing suites run unchanged at the 30 s default on the car; a worker statement the inventory missed fails there, not in production.
Delivery
-
Canonical doc pages: the ADR (U1); the database-error table of
coding-conventions.adoc(U2, U4);configuration-reference.adocfordb_statement_timeout_secs(U3);shared-crates.adocfor the canopy-db additions (U3, U4);tooling/xtask-catalog.adocfor the bare-commit finding (U4);testing.adocfor the rig's change (U6). -
CHANGELOG.adoc,== Unreleased: one entry per unit; U2, U3, U4 and U5 under=== Changed(answers, a default and retry behaviour change; pre-1.0, every consumer updated in the same MR). -
Each unit is its own MR against its child issue; U6's MR closes #1599 and marks U11 done in the chaos plan.
-
Lint counts are unchanged: bare-commit is a new finding inside the existing
db-poolsgate.
Review log
| round | vendor | resolved model | verdict |
|---|---|---|---|
1 |
anthropic |
claude-fable-5-2 |
FLAGS (P2): U4 cited an allowlist the |
2 |
gemini-4-carbon |
FLAGS (P2): the same allowlist; the retry loop cannot read a body; the over-budget hint was stated two ways; an |
The plan presented for approval carried those resolutions and four corrections from the author's own re-check of the code (the commit count, the rules client mapping by status, canopy-db's own commit sites, and the session stores' argument-taking commit). Neither reviewer read that version.