ADR-062: Transactional Idempotency Claims — Atomic Effects at Both Ingress Boundaries
Status
Accepted (2026-07-31). Program: epic &77 (Plan::TX-IDEMPOTENCY); anchors #1178 (inbox) and
#1182 (HTTP) — both closed 2026-08-02 with the program complete. Plan (archived):
Transactional Idempotency Claims.
Supersessions (named — the superseded documents are NOT edited, per the immutable-ADR rule):
-
ADR-022 §D3.2 (the inbox three-statement claim/stamp shape and its at-least-once caveats) is superseded by this document’s single- transaction attempt machine; ADR-022 §D5 (the persistent idempotency middleware) is superseded in full — the middleware is deleted, and no stored-response replay survives anywhere in the platform. ADR-022’s outbox, retention, occurrence-token, and admin-replay decisions stand unchanged; its §D4 admin-replay at-least-once contract now rests on the handler atomicity this ADR provides, closing the loop its amendments left open.
-
ADR-055's F8 client-keyed idempotency is NOT superseded — it is grandfathered as a conforming specialization of this doctrine (its pair columns are an in-transaction claim with domain provenance) and becomes the platform-wide pattern’s reference implementation.
-
ADR-059's re-route of the retry-ladder question to #1053 is resolved here: pacing belongs to the broker and the parking tier; the inbox owns the total counted-attempt budget and the terminal state.
-
ADR-051's "every
ssnwrite resets verification — same-value included" policy is superseded by §G1 (#1266): the reset now keys on the DETERMINISTIC digest actually changing (ssn_full_hmac IS DISTINCT FROMthe incoming sibling). ADR-051 chose the unconditional reset to keep re-entry from re-verifying; under this program’s replay doctrine the same rule made a RETRIED identicalPUTdestroy a verification granted in between — precisely the stale-replay hazard §G exists to kill. The hmac gate preserves ADR-051’s real intent (a different SSN can never stay verified) while making the identical replay a no-op; the value-bound attestation, revoke, and clear writes gain the matching state predicates (ssn_verified = false/= true/ SSN-data-on-file), so their replays re-stamp and re-audit nothing. All other ADR-051 decisions stand.
Context
Two platform primitives promised more than they delivered, verified by an external review (2026-07-27) and an adversarial confirmation workflow (&74):
-
The event inbox (
craig_mq::inbox::handle_idempotently) commits its claim, the handler’s domain effects, and theprocessed_atstamp as three separate autocommit statements. A crash between handler success and the stamp re-runs a committed handler; concurrent deliveries re-run it in parallel past an unlocked read. Real semantics were at-least-once with idempotency delegated to each handler — and a handler-by-handler audit (2026-07-31, both audit reports transplanted into the plan’s §R ledger) found consumers with no fallback idempotency at all, plus 30 non-create HTTP routes whose "convergent" guards live only in pre-read validators (or nowhere), and 4 routes that stage a fresh outbox envelope per replay. -
The HTTP idempotency middleware held a 30-second lease with no ownership fencing (#1182), a 500-window between logical expiry and physical cleanup (#1194) — and was opt-in with zero senders: no client this repository owns (BFF, CLI, SDKs, e2e, k6) ever sent the
idempotency-keyheader. It protected nothing while carrying two open defects.
Meanwhile the one mechanism proven in production shape — financial’s F8 — already embodied the correct design: a client-supplied key and canonical request hash bound by a partial unique index, written inside the ONE domain transaction, with replay re-derived from domain state.
Decision
Doctrine: the platform provides atomic effects + bounded-horizon deduplication + convergent external effects. An idempotency claim commits inside the same database transaction as the domain effects, at both ingress boundaries. Dedup horizons are finite and named per class (the plan’s horizon table, "Doctrine and horizons"); object-store effects converge through generation-fenced immutable attempts rather than pretending to be transactional. The platform never claims unqualified "exactly-once".
MQ inbox — the single-transaction attempt machine
One dedicated pooled connection per attempt; the whole attempt (claim → savepoint → handler → completion or failure accounting → commit) is ONE transaction:
-
The claim
INSERT … ON CONFLICT DO NOTHINGprecedes aSAVEPOINT; the handler receives&mut Transaction; success stampsprocessed_atand commits claim + effects + stamp together. Failure rolls back TO the savepoint — the claim row survives as the accounting row, anderror_count/last_errorcommit in the same transaction while the row lock is still held. There is no separately-committed accounting statement to race, so the five-attempt cap is hard over counted attempts (crash-class failures — process crash, task abort, drop/render panics, accounting-commit failure — are uncounted and documented). -
Timeout hierarchy: the claim/lock-wait runs under the default 30 s statement timeout (that budget IS a duplicate’s lock-wait allowance);
SET LOCAL statement_timeout = '5s'applies only AFTER the lock is held; a 15 s attempt deadline bounds the handler future. Worst-case winner hold ≈ 21 s < the 30 s waiter budget. -
Panic containment is two-tier: construction and poll panics are caught around the handler call and consume an attempt via savepoint accounting; drop-of-future and error-render panics escape to the task boundary as uncounted crash-class failures. The
AssertUnwindSafejustification is scoped honestly: the savepoint discards database state; non-database captured state carries the same exposure the existing #1203 spawn boundary already accepts. -
Envelope identity is the effect-bearing triple
(source_service, event_type, payload_hash); a reused envelope id with different content is recorded in a dedicated collision ledger with its own deterministic token and watchdog — the canonical row’s processed/failed state and occurrence token are never mutated or reused. -
The DLX surface is mandatory-published with a basic.return verdict, built entirely from durable row state (occurred_at := stored received_at), so repeat and cross-replica surfaces are byte-identical and the security consumer’s equivalence comparison absorbs them. A failed or unroutable surface nacks
requeue: true— the source-queue copy is the durable envelope;failed_atis stamped only after a confirmed surface. -
One retry policy (#1053): pacing = broker 2-strike + ADR-022 §D4 admin replay; the inbox owns the total counted-attempt budget, terminal at
INBOX_MAX_RETRIES = 5.
HTTP — in-transaction request claims
-
Every convert-class mutation (the plan’s §R ledger is the binding, individually-audited classification — there is no verb-based blanket) requires a client-supplied
client_request_id: Uuidbody field and computes a versioned intent hash over an envelope of version, claim scope constant, jurisdiction, effective actor, ordered path params and a body. The body is the request itself under the scope’s revision, or an intent struct where the intent differs from the request (§Amendments #2310, which replaced the original "immutable per-endpoint projection, never raw DTO serialization"). -
claim_firstis the FIRST statement of the domain transaction — one lockingINSERT … ON CONFLICT DO UPDATE … RETURNING— and the claim row (scope, intent hash, entity kind/id, effective actor) commits atomically with the effects. Replay re-runs the endpoint’s current entity authorization and re-derives the response from domain state (effects are deduplicated; responses are not immutable — later mutations show, a soft-deleted entity replays as the tombstoned row (200, its soft-delete markers included), a hard-deleted entity yields a typed 409REPLAY_ENTITY_GONE, and each endpoint returns its own success shape; §Amendments #1289). Any scope/actor/entity-kind/intent mismatch is a typed 409IDEMPOTENCY_CONFLICTwith a leak-free body. -
The effective actor owns the claim:
claims.acting_worker().sub— under BFF impersonation the worker, not the shared service principal. -
One-time secrets (partner key issue/rotate) use lifetime per-entity pair columns with a partial unique index — a 30-day claim expiring must never permit a second live secret; replay names the key id, never the secret — including when the partner was since suspended or soft-deleted, or the issued key itself since revoked (the named 409 outranks lifecycle and is never
REPLAY_ENTITY_GONE; §Amendments #1289); rotation inserts the new claimed row before conditionally revoking the old. -
Uploads and exports move to generation-fenced, digest-verified immutable attempt rows (
upload_attempts) with a shared finalizer emitting events atomically with readiness on both the request and reconciler paths; entity rows are never created pending, and export artifacts are pure functions of source rows plus a pinned generation date. -
The lease-based middleware, its cache table, cleanup worker, constants, invariant, and tests are deleted. Client key minting follows a per-surface lifecycle (browser: mint-at-render, held across validation rerenders; CLI: per-invocation with
--request-id; SDKs: held-per-builder; load tooling: per-iteration, documented non-goal). -
Background jobs (#1571, ADR-068 § Amendment — #1571, Accepted 2026-09-18 at the plan’s close-out #1940; as-built on all eight kinds across placement / security / rules / reporting / financial): a job’s enqueue IS the claim transaction —
claim_firstfirst, the consent gates in the same tx, the job row insertedqueuedwith the claim’sentity_idas its id;Replay { entity_id }returns the same job (202 again, whatever its state); a freshclient_request_idis a new job admitted by thededup_keyarbiter only when none is active; the job row is pruned only after its claim (claim-joined retention).
Alternatives considered
-
Lease fencing the existing middleware (claim generations, heartbeats, owner columns): narrows the double-execution window without closing it — the claim and the effects still commit separately, which is the disease itself. Rejected.
-
Stored-response replay (middleware-style, inside the tx): re-introduces body caps, header projection, staleness, and finalize fencing. F8’s re-derive-from-domain-state model needs none of it. Rejected everywhere, including uploads.
-
Per-entity pair columns fleet-wide instead of
request_claims: ~35 bespoke migrations and store changes for no correctness gain; retained only where the horizon must be entity lifetime (one-time secrets,create_report). Rejected as the general mechanism. -
A transaction-aware handler trait (RPITIT) instead of the boxed-future closure: saves one box per event at the cost of a public trait surface under
deny(missing_docs). Rejected. -
Persisting terminal envelopes in the inbox for unroutable DLX surfaces: the source-queue copy already IS durable if the delivery is requeued instead of rejected. Rejected in favor of requeue-durability.
-
A forensics-only attempt counter with no cap: unbounded poison-replay ping-pong with no terminal state. Rejected (#1053 resolution).
Consequences
-
Pre-1.0 breaking wire changes, CHANGELOG’d per unit: mandatory
client_request_idon every convert-class route; two required multipart text fields on upload routes; a wrapper body onimport_rule_setand a JSON body onrotate_key; the middleware’sIdempotency-Keyheader, replay-marker headers, and 422-mismatch status are gone (mismatch is 409). -
The inbox handler contract changes from
Fn(EventEnvelope)toFnOnce(EventEnvelope, &mut Transaction); every consumer service converts under a stop-then-start deployment barrier (no mixed-binary window). -
30 audited stale-replay-hazard routes (plus 4 event-dup routes and the ICPC TOCTOU) gain SQL status/version predicates and success-gated event staging in-program (§G) — including the SSN attestation lifecycle, federal report chains, and live ruleset content.
-
The dedup horizons are explicit operator knobs (
CRAIGREQUEST_CLAIMSWINDOW_DAYS, inbox retention) with named post-horizon behavior; the records-retention schedule remains DFCS-blocked (#1073) and these knobs do not pre-empt it. -
Non-goals: event ordering (#1214 stays open); SHINES-bound intake submissions remain at-least-once (no receiving identity — the ADR-042 boundary); load-tooling dedup.
Interior-mutability and unsafe-adjacent notes: AssertUnwindSafe usage is confined to the
inbox attempt machine with the two-tier justification above; no other new unsafe or
interior-mutability surface is introduced.
Amendments
-
#1304 (2026-08-02) — consumer pool isolation. The §G4 cases events consumer is the fleet’s only inbox handler that makes NESTED pool acquisitions: the substrate’s claim connection is held for the whole attempt while the auto-link pass opens the report read and the per-link #799 own-transactions from the same pool. Sharing the 10-connection service pool made battery-load starvation reproducible (HTTP
PoolTimedOut500s
acquire convoys past the 120 s test kill + rollup-oracle misses, first seen 2026-08-02 — the contention is a feedback loop, since a failed nested acquire counts arank_failuresrefusal and the redelivery adds load), and would let a retry-looping consumer eat HTTP request capacity in production. Rule, binding fleet-wide: an inbox handler that acquires connections beyond its claim connection MUST run on a dedicated pool; handlers that work purely on the claim transaction stay on the service pool. As built in cases:EVENTS_CONSUMER_POOL_CONNS = 3(1 claim + 1 sequential nested acquisition + headroom), sessions taggedapplication_name=craig-cases-events, the wiring pinned live by the battery viapg_stat_activity. -
1034 (2026-08-04) — the rule generalizes to VOLUME-based starvation. craig-security’s
audit subscriber works purely on its claim transaction, but it is the system’s highest-volume consumer (it ingests every event every service emits): under full-battery load its attempt cadence alone competed the 10-connection service pool away from HTTP handlers — the 2026-07-14 transient 500 cluster with flakyhealthz, invisible in isolation. Amended rule: a dedicated pool is ALSO required when a consumer’s sustained volume can saturate the shared pool, nested acquisitions or not; the claim-tx-only stay-on-the-service-pool default applies to ordinary-volume consumers. As built in security: one 3-connection pool (application_name=craig-security-events) feeds BOTH the audit and DLQ subscribers (each attempt holds one claim connection; 2 structural
headroom); the audit leg is battery-pinned viapg_stat_activityand the DLQ leg rides the same pool object by construction. -
#1326 (2026-08-04) — the rule generalizes to ALL co-located domain workers. craig-exchange stacked FOUR worker classes on its 10-connection HTTP pool — the events subscriber (one claim connection per in-flight delivery), the
ExchangeSendWorker(up to 8 semaphore-bounded dispatches, each a brief post-adapter finalize tx), and the upload-attempt reconciler, beside the outbox drain. No single class saturates the pool, but under battery-peak pressure (a 7.7 sINSERTstall) every held connection stretches and the AGGREGATE starves HTTP: icpc uploads and transaction GETs 500’d onPoolTimedOutwhile the acquire probe reported session exhaustion (2026-08-04). Amended rule: a service’s long-running domain workers ride dedicated pools sized structural-requirement-plus-headroom; the shared service pool is for request handlers (and the outbox drain, whose failed pass is retried next tick and 500s no one). As built in exchange:craig-exchange-events(3),craig-exchange-send(3 — finalize txs open AFTER the adapter send, so holds are brief and the pool bounds DB concurrency below the dispatch semaphore),craig-exchange-reconciler(2); events + send are battery-pinned viapg_stat_activity(the reconciler’s 5-minute first pass puts its tag outside any test budget; it rides the same constructor). -
#1363 (2026-08-08) — cheap losers: same-key claim racers no longer hold blocked connections. The original
claim_firstmade N same-key racers serialize ON THE WINNER’S UNCOMMITTED CLAIM ROW: each loser’sINSERT … ON CONFLICTwaited inside its own open domain transaction, pinning a pooled connection for the winner’s whole transaction duration — an 8-way duplicate volley held 8 of the 10 default connections, and under load the acquire timeout surfaced as raw 500s that broke the all-succeed contract (battery-observed onPOST /v1/security/admin/units). A bounded in-transaction lock wait was REJECTED: any in-tx shed fires exactly when the winner is slow, turning contract-guaranteed 200s into refusals. As built:claim_firstopens with apg_try_advisory_xact_lockprelude (a dedicated 2-arg classid — a keyspace disjoint from every 1-arghashtextfleet user — keyed on a fold of theclient_request_id; cross-id collisions cost one spurious retry, never correctness). The winner proceeds — among prelude-running writers its INSERT can then only meet COMMITTED rows, so classification never blocks (two recorded residuals degrade to the OLD blocking behavior, never to corruption: a mixed-version rolling deploy where an old binary claims without the lock, and an uncommitted pruner DELETE briefly blocking the arbiter). A concurrent racer receives an INTERNAL contended sentinel; its transaction aborts in ~milliseconds (zero effects ran —claim_firstis contractually the first statement) andAppState::execute_claimed_tx(the claim-bearing replacement entry forexecute_within_tx;AsyncFnMut, so the closure re-runs with per-attempt clones) retries the whole domain closure after a POOL-FREE exponential backoff (25 ms doubling to a 400 ms cap, ~8 s budget). The re-run classifies against the committed winner (Replay — all-succeed holds, however slow the winner) or wins the lock itself if the winner rolled back. Recorded bound (§H-class guarantee): an N-way same-key volley sustains ONE held connection (the winner’s) plus millisecond-scale probes; budget exhaustion and pool-acquire timeouts on the transaction runners surface as typed 503 (SERVICE_UNAVAILABLE), never raw 500s. Pool RESIZING is explicitly not the fix — it moves the exhaustion cliff without unbinding loser holds from winner latency.
#1338 — the A4 cases-S2S bound decided at 8 s (2026-08-09)
A4’s CASES_S2S_DEADLINE (the bound wrapping financial’s cases DOB
lookup inside the inbox attempt — token mint + GET + decode) is DECIDED
at 8 s, narrowed from the plan’s 10 s. Battery-peak measurement
(2026-08-05, the #1304 concentration class) showed the 10 s bound firing
correctly inside a 15.56 s attempt total — ~5.5 s of substrate work
(claim + same-tx accounting + pool acquisition) on top of 10 s exceeds
the 15 s attempt deadline, letting a hung dependency ride into the
deadline-drop path this bound exists to prevent. 8 s + peak-measured
overhead ≈ 13.5 s restores ~1.5 s of headroom; the healthy path is
milliseconds. Enforced by a compile-time pin at the constant
(as_millis() ⇐ 8_000); the truth test’s floor follows (≥ 7 s) and its
bound-vs-deadline attribution stays message-based (load-independent).
The headroom is measured, not bounded — a future battery showing attempt
totals creeping past ~13.5 s re-opens this margin.
#1289 — replay-after-soft-delete decided: tombstone-replay (2026-08-16)
The Decision text above left the soft-delete arm of "re-derives the response from domain state" implicit; the fleet inventory (all 44 claim scopes, grep-complete) found the implementations had already converged, and the semantic is now DECIDED and pinned rather than incidental:
-
Tombstone-replay. A replay whose entity was SOFT-deleted after the original success returns 200 with the row as it stands — its soft-delete markers (
active = false/deleted_at/status = 'deleted') included. The replay branch re-derives through the endpoint’s UNFILTERED point-read; a live-row-filtered replay read is a conformance defect. Only a HARD-deleted entity yields the typed 409REPLAY_ENTITY_GONE. -
One-time-secret carve-out.
issue_key/rotate_keynever re-derive: a matching replay is the fixed 409one-time-secret-already-issuednaming the key id and never the secret — including for a since-suspended or since-deleted partner, and after the issued key’s own revocation. The gone arm does not exist on these routes. -
Deviation resolved (#1482, 2026-08-17).
placement.create_kinship_optionread its replay through a live-row-filtered getter, answering the gone 409 after its soft delete (deliberately pinned by the #1215 test). #1482 moved the replay arm to a dedicated unfiltered getter and rewrote the pin to the tombstone-200 semantic; the GET endpoint keeps the #1215 live-row 404. The fleet is now deviation-free. -
Inventory (44 scopes). 17 conforming tombstone slices (kinship since #1482), 3 correct hard-delete 409s (cases
person_link, exchange draftagreement, financial pendingadjustment), 22 no-delete N/A, 2 one-time-secret. The #1289 characterization legs pin every tombstone ENTITY (the two rules scopes share one rule-set entity and one leg; financial’s pre-existing rate leg pre-dates this amendment), the two untested gone arms, the revoked-key replay, and an authz-on-replay 403 (authorization re-runs on the CURRENT request before any claim answer).
#1273 — event_inbox.payload_hash NOT NULL (2026-09-02)
The §A identity triple’s third leg landed nullable on 2026-07-31 with a documented legacy
trust window: rows claimed before the identity migration carried NULL, the collision check
skipped the hash leg for them, and the first success stamp backfilled whichever
matching-source/type delivery completed first. The inbox retention horizon (31 days) closed
that window on 2026-08-31; every live writer has bound the hash at claim since #1053; pre-1.0
CRAIG has no production deployment. The ratchet: SET NOT NULL ×8 (one migration per
inbox-bearing service; SET NOT NULL is outside the ADR-063 D3 destructive class and the
N−1 boundary binary already writes the column, so no schema_compat_floor bump), the
CanonicalRow hash is a String, the NULL-skip in mismatches() and the COALESCE
backfill in the success stamp are gone, and a hashless row is pinned unrepresentable
(schema_refuses_a_hashless_inbox_row). The known-issues entry is retired.
#1745 — create_report projection V2; the V1 digest is accepted for the row’s lifetime (2026-09-09)
CreateReportRequest.received_at (the attested staff receipt, #895 MR-C) joined the report’s
intent projection as ReportIntentV2 (schema: "v2" + received_at; the #1672 tag precedent),
so a replay of the same received_request_id with a different receipt is the identity-mismatch
409. create_report is a LIFETIME-identity class (§Alternatives: the digest lives on the row, not
in request_claims), so there is NO horizon after which the pre-cutover digest can be retired:
ReportIntentV1 stays frozen and its digest is accepted FOREVER for a body WITHOUT a receipt
(dual-decode — no V1 row ever carried one, so a body WITH a receipt compares V2-only). A future
V3 inherits the same obligation for V1 and V2.
#648 — create_report projection V3; the V1 / V2 digests retire with the rows (2026-09-10)
CreateReportRequest.report_source (the NCANDS #10 RptSrc source, REQUIRED — #648 MR-A) joined
the report’s intent projection as ReportIntentV3 (schema: "v3", report_source after
reporter_type), and ReportIntentV1 / ReportIntentV2 / report_intent_hash_legacy + the
two-hash persist_or_replay compare were DELETED rather than carried as a third dual-decode. The
LIFETIME class keeps its no-horizon rule — what changed is that no pre-cutover row survives to be
replayed against: migration 20260913120000_report_source REFUSES while any reports / referrals
row exists (no backfill — the source is a captured fact the reporter status does not determine), so
a database that passed the gate holds no row digested under V1 or V2, and a pre-cutover body lacks
the required report_source, so the JSON extractor refuses it (422) before any digest compare. The
#1745 forever clause above is superseded for V1 and V2; ONE digest (schema: "v3") is compared. A
future V4 inherits the #1745 obligation for V3 unless it, too, ships behind a refuse-on-data cutover.
#2370 — a blind-index field enters a projection as its keyed digest (2026-10-13)
intent_hash_v1 is an unkeyed SHA-256 stored in request_claims, so a plaintext ADR-048-encrypted field in a
projection is enumerable from a dump the column’s encryption defeats. PersonIntentV4 hashed date_of_birth
(≤ 366 trials beside the plaintext birth_year), ssn_last_four and ssn. The rule: an ADR-048 blind-index field
enters a projection ONLY as its blind-index digest from the compiled registry spec (blind_digest; keyless, the
plaintext the column holds), over the canonical input, so the same value replays — the one exception to the
byte-as-submitted / no-derivation normalization pin, as the money .rescale(2) is. PersonIntentV5
(schema: "v5") applies it; V4 is deleted, not dual-decoded, and V4 claims age out with the window. Accepted
residual, filed as #2375: the LIFETIME create_report digest still covers Opaque fields as plaintext — an Opaque
field has no blind digest, and the preimage carries the encrypted free-text narrative, so it confirms a guessed whole
submission but enumerates no field.
#2522 — the acting identity is a type; the bearer is read only through bearer_*() (2026-10-19)
The effective actor (§Decision, HTTP) is read through a type, not by convention. claims.acting_worker() returns
craig_auth::ActingWorker, a Copy view over the lifted actor when one was verified, else the bearer, and every
recorded or claimed actor reads it (claims.acting_worker().sub()); the sites the acting-identity census first
pinned to an owner issue (#2320, #2321, #2472) read it too since each issue landed.
request_claims::parse_actor_sub takes the view, not &Claims, so a claim cannot be keyed to the carrying service
principal.
-
Every
Claimsfield is private. The token on the wire is read only throughClaims::bearer_sub,Claims::bearer_username,Claims::bearer_email,Claims::bearer_name,Claims::bearer_roles,Claims::bearer_has_role,Claims::bearer_is_service,Claims::bearer_is_portal_principalandClaims::bearer_require_service_caller; the non-identity facts have same-named getters (aud(),azp(), …). -
The role gates (
require_role,require_admin,require_caseworker_or_above, …) live onActingWorker, so a relay is judged on its worker. -
Claims::is_direct_service(a service bearer with nothing lifted) is the one "evaluates as a service" predicate: the authz input, the unit lookup and the craig-rules bootstrap fallback all read it. -
The guard is
crates/craig-test-lib/tests/acting_identity_census.rs: a hermetic token census in which everybearer_*()read is pinned by exact text with its reason. A pin owned by an open issue is deleted by that issue’s commit, and a stale pin fails the census. It replaces the #2214 / #2250 per-servicerecorder_census.rscensuses, retired by #2542.
#2375 — create_report projection V4: the Opaque columns enter as one keyed digest (2026-10-21)
ReportIntentV3 hashed the seven ADR-048 Opaque report columns as plaintext into the unkeyed intent_hash_v1,
and reports.received_request_hash keeps the digest for the row’s lifetime, so a dump confirmed a guessed whole
submission (the residual the #2370 amendment accepted). ReportIntentV4 (schema: "v4") carries the plaintext
columns as submitted and the Opaque ones ONLY as pii_digest: keyed_token_digest under the domain
report_intent_pii over the canonical JSON of the frozen ReportPiiV1 sub-projection (volatile raw_submission
keys stripped inside it); keyless, that JSON, the plaintext the columns hold. The stored grammar stays
v1:<64 hex>. The #1745 obligation for V3 is discharged the #648 way: migration
20261019120000_report_digest_keyed REFUSES while any reports row carries a digest (a NULL one carries none and
passes), ReportIntentV3 is deleted, not dual-decoded, and the floor moves so an N−1 binary cannot boot against the
migrated schema (a still-running N−1 replica would keep writing V3 digests, so the window stops them first). Consequence: the digest is bound to the field-encryption key and cannot be re-derived from the row
(the envelope’s actor is not stored on the intake path), so the deferred key-rotation path (ADR-048 Scope) must
keep the retired key for this compare or accept that a pre-rotation retry answers 409 (#2510). A future V5 inherits
the #1745 obligation for V4 unless it, too, ships behind a refuse-on-data cutover.
Two residuals are recorded, not fixed. Keyless stacks (dev only) digest the canonical JSON itself, the plaintext the
columns hold. The signed SHINES and partner channels keep craig-intake-keyring signing_receipts.payload_sha256, an
unkeyed SHA-256 of the whole signed submission beside its detached JWS: non-repudiation evidence, whose confirmation
is its purpose (a DFCS policy question, not this class).
#2707 — a replayed 2xx says so: Idempotent-Replayed: true, and the one task-local replay marker (2026-10-25)
A 2xx that answers a stored claim’s outcome now carries Idempotent-Replayed: true
(request_claims::IDEMPOTENT_REPLAYED), so a client and the runtime coverage matrix’s replay axis (plan
runtime-coverage-matrix D4) can tell a replay from a first run. The two replay arms mark the request: classify
on a full match (it serves claim_first, precheck and the contended fast path) and the upload attempt’s
resolve_claim on FetchPromoted / FetchSuperseded. A fresh resolution clears the mark: claim_first’s insert,
and an upload claimed fresh, resumed or reopened. So the marker holds the request’s latest claim decision. A
lookup-only `precheck (craig-placement’s adoptive-slot check, exit_facts.rs) that matches a claim the retention
prune then deletes is overridden by the fresh claim that follows, and an upload pass that loses its finalize race and
then answers the stored result is marked. A key conflict or an intent mismatch never marks. One
apply_global_layers layer, immediately outside the request ceiling, adds the header to a marked 2xx only, so a
marked replay that ends in a refusal (its re-authorization fails, or its entity is gone and it answers 409) carries
none. No handler is edited, and craig-intake’s edge relays the header on its two proxied uploads. Both CORS builders
expose it to cross-origin browser clients. §Consequences records the deleted middleware’s replay-marker headers as
gone; this is a new header, set from the claim’s own verdict rather than a response cache, and the only one.
The marker is project-authored interior mutability, which the coding conventions (§ Concurrency Primitives) allow only by an ADR. This amendment is that ADR, and it narrows §Consequences' "no other interior-mutability surface" by exactly this one marker:
-
What:
crates/craig-api/src/replay_marker.rsholds onetokio::task_local! { static REPLAYED: Cell<bool> }. -
Why a marker: the claim code reaches neither the request nor the response, and the header must not need an edit in every claim and upload handler.
-
Bounds:
-
the layer opens a fresh scope per request;
-
only
mark_replayed()andmark_fresh()write it, each a no-op outside a scope; -
the value never leaves the request’s task: a spawned task does not inherit it, and the request ceiling spawns nothing;
-
it carries one bit, never data;
-
an atomic would be interior mutability too, so it is not an alternative.
-
Three replay paths bypass both arms and carry no header yet (#2764): case report creation’s
received_request_id resubmission, craig-intake’s report submission, and the cases SSA-screening forward.
#2765 — an opted-in subscriber commits a batch per transaction (2026-10-26)
§Decision’s MQ inbox runs one transaction per attempt. For a subscriber that opts in through
Subscriber::subscribe_idempotent_batched, that is re-decided: one transaction claims and handles up to K immediately
available deliveries (K ≤ PREFETCH, 16) and commits once, so a single commit’s WAL flush covers many envelopes. The
first caller is craig-security’s # audit subscriber, which every fleet event passes through (#2699 measured 1289
envelopes/s at baseline and 8–60/s once WAL load stretched commit latency). Every other subscribe_idempotent consumer
keeps the single-envelope path, its SQL unchanged. The design is plan Audit
Batched Claims (D1–D10), implemented by #2773, #2774 and #2765.
The lock bound is conditional, on both paths. §Decision’s timeout hierarchy states a worst-case winner hold of about
21 s against a duplicate’s 30 s wait. That bound covers interruptible work only: two waits are outside it on the
single path as well as in a batch. Correction (2026-10-27, #2775): until #2775 the single path had a third, the deferred constraint triggers run unbounded inside its COMMIT; it now runs them under the attempt’s 5 s cap before COMMIT (§ #2775 below).
-
The WAL flush inside
COMMITruns in a critical section no timeout cancels. -
A transport stall the server has not noticed leaves the backend holding its locks until it sees the client gone.
A batch holds every claimed row’s lock until its commit, so the batch, not each envelope, fits the bound. Admission stops at 5 s of hold. Each phase sets its own timeouts:
-
claim: a 50 ms lock wait and a 1 s statement cap;
-
other statements: 2 s;
-
the handler: 5 s;
-
an explicit commit phase: 1 s for deferred triggers and constraints.
Every statement also carries a client-side round-trip timeout of its server timeout plus 1 s. An envelope admitted at
5 s therefore ends its worst path by 18 s, and the commit phase’s interruptible work by 19 s. Beyond the bound a
duplicate’s claim fails at its 30 s timeout, uncounted, and dedups once the commit lands. A client-side COMMIT
timeout leaves the outcome uncertain, since no client timer undoes a commit in progress.
Inside the batch, each envelope keeps this ADR’s accounting:
-
its claim and handler run under their own savepoints, and a failure rolls back to the handler’s savepoint and is counted inside the batch;
-
a contended or timed-out claim, and an envelope that exceeds the batch’s own limits, defer uncounted to a solo run on the single path’s budgets, where a deadline still counts;
-
before any rollback that follows a dropped handler statement, the connection is drained (
resync, the helper #2770 added to the single path’s failure accounting).
Settlement and a failed batch. Outcomes stay provisional until COMMIT returns Ok. After that, each delivery is
settled individually, plain acks first, then each delivery that needs post-commit work (a terminal surface, a
collision record) with a heartbeat between them. When the batch fails (a statement error, a lost connection, any
COMMIT error, a client timeout, or a panic before the commit), it is arbitrated locally. The consumer keeps the
batch’s deliveries unacked and runs each one solo through the single-envelope path, whose claim arbitrates: a commit
that landed dedups, and a rolled-back one runs again under its own strike ladder. No nack, strike or marker touches a
sibling. A broker requeue would need credit that does not survive a hand-off to another consumer or version, so
arbitration stays on the consumer that held the batch (#2765’s constraint, amended). A panic in a delivery’s
post-commit work leaves its effects durable; that delivery is requeued and its redelivery dedups. Correction (2026-10-26, #2774): a post-commit panic’s redelivery re-claims the durable row; only a processed one dedups.
Times. In a batch now() is the batch’s start, so the batch’s inbox stamps and craig-security’s audit_log.timestamp
and archive_records.archived_at take clock_timestamp(). A threshold detection rule counts rows stamped within its
window W before each scan, and scans run every I seconds. A row stamped at T becomes visible only at its commit, T + d,
so a cluster of rows is guaranteed to fire only when its span ≤ W − I − d. Batching makes d up to the rest of the batch
(milliseconds typically, 19 s of interruptible work at worst). Amended (2026-11-26, #2771): detection no longer depends on
d. Each scan evaluates the rows committed since the last scan, found by transaction id, so a cluster under W fires at
the first scan that sees all of it (Data Model: Security & Compliance § detection_rules).
Rejected alternatives.
-
synchronous_commit = off: a crash after the ack would lose audit rows that were already acked. -
Parallel consumers: PostgreSQL’s group commit does let concurrent transactions share a WAL flush. But parallel consumers add connections and lock holders, give up ordering, and leave the gain to commit tuning, where a batch amortizes explicitly.
#2764 — a service-owned replay marks itself through craig_api::mark_replayed (2026-10-27)
The #2707 marker’s writers now cross the crate boundary. mark_replayed() is re-exported at craig-api’s root for a
replay a service resolves outside request_claims, on the request’s own task; outside an ApiServer request it is a
no-op. Two call sites use it: craig-cases' report resubmission, when its received_request_id UNIQUE answers the stored
row, and the cases SSA-screening forward, when exchange’s answer to its one claim carries Idempotent-Replayed: true.
craig-intake has no ApiServer, so its cases-backed sink reads cases' header on a report submission and its public
and partner confirmations carry it; the SHINES sink’s own receipt replay carries none yet (#2783). Accepted residual: the cases-profile honeypot’s
silent drop sends no header, so a bot that retries one body can tell a real replay from a dropped submission; the
stateless edge cannot close it, and the dropped answer’s fresh submitted_at against a replay’s stored one already
differs the same way (#1258, #1284). mark_fresh() stays
crate-private: a service’s request scope opens unmarked, so a service never needs to clear the mark, and could
otherwise erase a substrate’s genuine one. The #2707 bounds hold unchanged. A stray call would stamp a false header and
game the coverage gate’s replay evidence, so the call sites stay few and named here. Correction (2026-10-27, #2783):
the SHINES sink now marks its own replays. When it answers a request from a receipt that request did not claim, a
stored one or the winner of a receipt claim it lost, it sets AcceptedReport.replayed, and the public and signed
confirmations carry the header; on Garage, which ignores If-None-Match, two simultaneous first attempts may each
claim, and neither is marked. The honeypot residual above now holds under either profile: the SHINES-profile public
form drops silently too. Correction (2026-11-08, #2109): the dropped answer’s submitted_at no longer differs on a
retry that reaches the same edge process, which memoises its first answer (ADR-042, the tracking-reference bullet); the
missing header remains the residual.
#2775 — the single path runs its deferred constraint checks under the attempt’s cap (2026-10-27)
Before #2775, deferred constraint triggers were a third wait outside the single path’s ≈21 s bound. A handler’s
writes can queue DEFERRABLE INITIALLY DEFERRED constraint triggers, which ran at the attempt’s COMMIT. PostgreSQL
disables statement_timeout before it processes a COMMIT (postgres.c finish_xact_command), and lock_timeout
was unset, so slow check work or a lock wait there held the claim row’s lock with no bound, past a duplicate’s 30 s
wait. A deferred violation was an uncounted COMMIT error that left no inbox row.
Now, when the handler returns Ok, the attempt runs SET CONSTRAINTS ALL IMMEDIATE inside SAVEPOINT attempt,
before the savepoint’s release, as the batched path’s commit phase (§ #2765) does.
-
It is an ordinary statement, so the attempt’s 5 s
statement_timeoutbounds it, lock waits included. The cap is still at most 5 s there because no handler may raise it (the #2770 handler contract). No separatelock_timeoutis set: under the 5 s cap it would add nothing. -
ALL IMMEDIATEoutlives the savepoint release, soCOMMIThas no deferred constraint work left. -
Its failure is counted. Any database error (a violation,
57014,55P03,40P01) takes the handler error’s accounting: the rollback to the savepoint discards the handler’s writes and the checks they queued,error_countandlast_error(the database error’s text) commit under the held lock, and the cap and strike ladder are unchanged. A client-side error there stays uncounted, as a statement error at that point always was. One more case changes with it: a handler that swallows a statement error and returnsOkused to fail uncounted at theRELEASE; it now fails the checks with25P02and is counted. -
The attempt’s other commits need no such step. The dedup, terminal and collision commits run no handler. The failure accounting’s commit follows the savepoint rollback, which restores DEFERRED mode, so its
event_inboxwrites are bounded only because no service’sevent_inboxcarries a deferrable constraint. That stays an invariant.
The worst-case winner hold is max(15 s deadline + 6 s resync drain, 15 s handler + 5 s checks) ≈ 21 s. The waits
that remain outside it are the WAL flush inside COMMIT (synchronous-replication waits included) and a transport stall
the server has not noticed. Batched consumers' solo runs go through the single path, so they inherit the change.
No consumer is affected today, so the change is preventive. The deferrable triggers are craig-cases'
ck_custody_episode_current_instants and craig-placement’s ck_episode_current_instants and
ck_arrangement_in_episode. The only inbox handler writing any of their tables is craig-placement’s case-assignment
handler, and it updates placements and removal_episodes only in columns those triggers' UPDATE OF lists leave out.
#2498 — the SSA run-start claim is the relayed worker’s (2026-11-07)
craig-cases relayed the SSA run start to craig-exchange (POST /v1/exchange/ssa-screening-runs) with its own service
bearer and no X-Craig-Actor, so the effective actor the claim recorded was service:craig-cases, while the run’s
exchange.screening_run_staged event named the body’s requested_by.
-
craig-cases now attaches an
X-Craig-Actorit mints for the acting worker (ADR-028) to the start and to the cancel. With no actor-token issuer provisioned, it refuses the forward (its 503) and never sends one without the actor. -
craig-exchange takes the verified worker from
claims.worker_subject(), never the service. A start or cancel with no worker lifted is the 403worker-required. A bodyrequested_bythat names a different worker is the 403forbidden. The claim’screated_by_subis therefore the worker the act event names. -
The start no longer passes a #2740 legacy comparison (ADR-085 D3): that comparison applies only to a service actor, and a start no longer has one.
-
In-flight consequence: a start claimed before the deploy stored
service:craig-casesand a digest over it, so replaying it on the sameclient_request_idafter the deploy is theIDEMPOTENCY_CONFLICT409, not a replay. This is accepted because staging stays dark until B4 (the knob is off by default and nossa_solqpartner is active), so no such claim is expected. A caller who gets the 409 reads the case’s run status, which shows the run that the first start staged.
#2310 — the hashed body is the request; an intent struct only where the intent differs (2026-11-18)
The decision gave every endpoint an immutable IntentV<n> projection struct, on the ground that a request type’s
evolution would add an IntentV2 and compare both digests across the claim horizon. That never happened: each of
the 18 projections above V1 replaced its predecessor outright, and the one dual compare ever written (#1745) was
deleted at the next change (#648). What remained was a struct per endpoint that copied its request field for field.
-
The hashed body of a claim is the request as the handler holds it when it builds the claim, nested under the scope’s revision (
craig_api::request_claims::request_spec,RequestScope). The envelope is unchanged. -
A scope’s revision starts at 1. It is raised when the meaning of an unchanged body changes. A changed request type moves the hash by itself.
-
An endpoint keeps a separate intent struct only where the intent differs from the request, and the struct’s doc comment names which reason applies:
-
Secret: a field is stored encrypted or is credential material, and enters the hash only as a keyed digest (§#2370, §#2375). Those two amendments stand unchanged.
-
Normalised: two requests that mean the same thing must hash the same, and the request type cannot say so (money rescaled to 2, a set hashed in dictionary order).
-
Not the client’s: the request carries a field the server ignores or derives, or the hashed value is not in the body.
-
-
No intent struct carries a
V<n>suffix, and no endpoint compares against an earlier digest. The ledger acts (ADR-078) keep their projections and their pinned digests. -
A request type’s field order is now hash input for the scopes that hash it; each service pins one digest per such scope so a reorder fails a test.
-
In-flight consequence, accepted pre-1.0: as each service adopts the rule, the digest of every scope it converts moves once. A request first sent before that deploy and retried after it on the same
client_request_idis theIDEMPOTENCY_CONFLICT409, not a replay. Stored claims are not rewritten and age out with the window.
Every service has adopted the rule (the plan, done 2026-11-18): forty acts hash their request, and the intent structs that remain each name their reason.