Deployment Guide
- Architecture
- Environment Variables
- Identity capacity
- Public report routing
- Upload limits
- SHINES conversion cutover (#1071 / ADR-057)
- Below-floor subsidy backpay (#1115 / plan backpay-import-path)
- Investigation response deadlines rollout (#895)
- Partner modules in the configuration layer (#3200 / ADR-090)
- Outbound partner authentication (#1813 / ADR-083)
- Asking a person index (#3192)
- Taking a partner’s calls (#3193 / ADR-091)
- Outbound trigger rollout (#1828, #1835, #1829 / ADR-075)
- Administrative-authority bootstrap (#1786 / ADR-074)
- Admin-unit scoping rollout (#1086 / ADR-077)
- Background jobs rollout (#1933 / ADR-068 § Amendment — #1571)
- Streaming downloads rollout (#1946 / #1947 / ADR-068 § Amendment — #1572)
- AFCARS federal ruleset bootstrap (#1972 / plan afcars-federal-ruleset)
- AFCARS cases capture rollout (#1964)
- AFCARS placement capture rollout (#1963)
- U3 — removal episodes and episode-bound arrangements (#2018)
- U4 — exits, re-entry and the historical episode (#2019)
- U5 — retract, historical record and replacement (#2020)
- U6a — the exit readable and the guardianship handoff (#2021)
- U6b — the witness moves (#2022)
- U6c — the end-reason narrowing (#2023)
- U7 — the goal drop (#2024)
- P-B2 U2 — providers (#2055)
- P-B2 U3 — the setting vocabulary (#2056)
- P-B2 U4 — non-conventional rows (#2057)
- P-B2 U5 — kinship households (#2058)
- P-B2 U6 — the residence run (#2059)
- P-B3 U1 — arrangement facts (#2080)
- P-B3 U2 — removal facts (#2081)
- P-B3 U3 — trafficking (#2082)
- P-B3 U4 — the adoption / guardianship exit (#2083)
- P-B3 U5 — child facts (#2084)
- P-B3 U6 — the Tribe’s order of preference (#2085)
- AFCARS readiness rollout (#2127)
- AFCARS 2028 series rollout (#2148)
- IV-E determination inputs cutover (#1719)
- Re-verifying a signing receipt (#2201 / ADR-082)
- Container Deployment
- Transport security
- Database Setup
- RabbitMQ Configuration
- Keycloak Configuration
- Object Storage (S3)
- Retention & Archive
- Knobs (per archiving service: craig-security, craig-rules)
- craig-security’s
audit_log: retention by month (#3173) - craig-security’s
identity_issuance_log: retention by day (#3173) - Storage requirements (D9 — enforced or required)
- Enable order
- Reading an archive (D17)
- Purge posture & attribution
- Orphan objects
- Scaling
- Monitoring
- CI/CD Pipeline
Architecture
CRAIG consists of 9 API services, the craig-web BFF, 4 infrastructure services, and an optional CLI client:
| Service | Port | Database | Description |
|---|---|---|---|
craig-rules |
8001 |
craig_rules |
Rules engine (JDM evaluation) |
craig-cases |
8002 |
craig_cases |
Case management |
craig-placement |
8003 |
craig_placement |
Foster care & placement matching |
craig-exchange |
8004 |
craig_exchange |
Data exchange & ICPC |
craig-financial |
8005 |
craig_financial |
Payments, rate tables & claims |
craig-reporting |
8006 |
craig_reporting |
Reporting & data quality |
craig-security |
8007 |
craig_security |
Security & compliance |
craig-intake |
8008 |
— (stateless edge, ADR-017) |
Public intake (anonymous child abuse reporting; no DB/MQ — forwards to craig-cases over HTTP) |
craig-composition |
8009 |
craig_composition |
Composition layer engine (ADR-035) |
craig-web |
8080 |
— |
Web UI (BFF, no database) |
craig-portal |
8080 (devstack host 8081) |
— |
Caregiver self-service portal (BFF, no database; ADR-076 — a SEPARATE public host) |
Infrastructure:
-
PostgreSQL 18 — one database per service, native
uuidv7()for defaults -
RabbitMQ 4.2 — topic exchange
craig.events -
Keycloak 26.5 — OIDC provider with
craigrealm -
Garage v2 (or any S3-compatible store) — file attachments
Environment Variables
All services use the CRAIG_<SERVICE>__* prefix pattern (double underscore separates sections), loaded by the config crate.
Common Variables (All Services)
| Variable | Default | Description |
|---|---|---|
|
varies |
HTTP listen port |
|
— |
PostgreSQL connection string. Two principals share this variable NAME (#1310): the migration gate’s container carries the migration-owner DSN, the serving container the runtime DSN — see § Database Setup. |
|
— |
AMQP connection string |
|
— |
Public OIDC issuer URL for JWT |
|
— |
Internal URL for split-DNS deployments (Docker / k8s). When set, CRAIG fetches the discovery doc + JWKS via this URL and rewrites the discovery doc’s |
|
|
Comma-separated allowed CORS origins |
|
|
Maximum request body size in bytes — the GLOBAL cap on every route (#974: the attachment-accepting services no longer raise it; their upload routes carry the separate cap below). |
|
unset → derived: |
#974: whole-request cap for the ATTACHMENT-ACCEPTING routes only — craig-cases (contact / report / court-order attachments), craig-placement (home documents), craig-exchange (ICPC attachments); parsed by every service, consumed by those three. Applied per-route as an inner |
|
— (required) |
The configuration layers the service loads at boot (Configuration Reference § Deployment-Global Variables; § The configuration fetcher below). The jurisdiction layer’s manifest names the deployment’s jurisdiction (e.g. |
|
— (required) |
Display label for the administrative-unit concept ( |
craig-rules
| Variable | Default | Description |
|---|---|---|
|
|
Who owns the rule sets (ADR-087 § Amendment — #2956). |
|
|
Budget for one rules evaluation dispatch, ms (valid |
|
|
Per-NODE JS interrupt bound for JDM function nodes, ms (#1046). Explicit values must sit in |
|
|
Decision-cache sweep interval, s (valid |
Object Storage (craig-cases / craig-placement / craig-exchange / craig-reporting / craig-security / craig-rules)
Every service that touches the object store loads the same
CRAIG_STORE* family. CRAIG_STOREBACKEND is
explicit-required (#1362): a deployment that omits it refuses to
boot with the remedy in the message (craig-rules only loads the
family — and so only enforces the requirement — when its retention
archiver is enabled) — the backend is never silently defaulted,
because local writes blobs to a single container’s disk (dev/test
only; they vanish with the container). A deployment that intends S3
can therefore never silently get local.
| Variable | Default | Description |
|---|---|---|
|
— (required; boot refuses when unset) |
Storage backend ( |
|
— |
S3 bucket name |
|
— |
S3 endpoint URL |
|
— |
S3 access key |
|
— |
S3 secret key |
|
— |
S3 region |
craig-placement
| Variable | Default | Description |
|---|---|---|
|
craig-rules base URL — since #1641 the |
|
|
|
The license/training expiry notice sweep tick (#1641). 0 = no scheduler — the devstack posture ( |
|
|
Days ahead of an expiry the |
Sizing (#1641): every placement activation is one craig-rules evaluation and every matching search is one per DISTINCT eligibility facts tuple of its candidate set (≤ 64, 8 in flight, the whole fan-out under an 8 s budget); size craig-rules' per-IP CRAIG_RULES__RATE_LIMIT_RPM (default 600) for that volume from the placement pod(s). Rollout order for the consult: the subsection "Placement eligibility consults the ruleset (#1641)" under Upgrades below.
craig-financial
| Variable | Default | Description |
|---|---|---|
|
|
HTTP listen port |
|
— |
PostgreSQL connection string |
|
— |
AMQP connection string |
|
— |
Public Keycloak URL for JWT |
|
— |
Internal Keycloak URL for JWKS fetching |
|
|
Comma-separated allowed CORS origins |
|
|
Maximum request body size in bytes |
craig-reporting
| Variable | Default | Description |
|---|---|---|
|
|
HTTP listen port |
|
— |
PostgreSQL connection string |
|
— |
AMQP connection string |
|
— |
Public Keycloak URL for JWT |
|
— |
Internal Keycloak URL for JWKS fetching |
|
— (required in |
#2138: 32-byte base64 column key for craig-reporting only — never the cases key. Production: the orchestrator secret store; set it before rolling U1 (#2138), or a |
|
|
#2138: |
|
|
Comma-separated allowed CORS origins |
|
|
Maximum request body size in bytes |
Sizing (#2154, #2206): an AFCARS generate holds every sealed record row of its half, then the validation fold’s state, in
memory until its one commit, so a craig-reporting pod’s peak grows with the half’s in-population children N: the children
in care at the half’s start plus its entries, less the children the population rule drops. It drops only a child none of
whose episodes in the half ran longer than its threshold (24 hours in the shipped dictionary), each episode measured whole,
from removal to exit or to the half’s end; a dropped child holds no rows. An NCANDS generate likewise holds every child row
of its fiscal year until its one commit, where its peak lands, so it grows with the year’s child rows C.
-
Growth. An AFCARS generate grows the process by 27 MiB + 18.1 KiB ×
Nover its idle RSS, 336 MiB atN= 17 500. Measured on the hermetic generate: release build, 8 750 and 17 500 in-population children, 0.4% run to run. The method and figures are on #2154. -
NCANDS growth. An NCANDS generate grows it by 16 MiB + 0.42 KiB ×
C, 57 MiB atC= 100 000; readCfrom a prior submission’srecord_count. Measured the same way: release build, 50 000 and 100 000 child rows, 0.6% run to run. The method and figures are on #2206. -
Limit. Set the pod’s memory limit, and its request to the same value, at 1.5 × (idle RSS + the larger of the two growths) for the largest half and fiscal year you expect: a pod idling at 50 MiB with
N= 17 500 takes 580 MiB. NCANDS’s growth stays below that AFCARS 336 MiB until about 780 000 child rows. The margin covers what the measure could not: the image’s musl allocator (the measure ran glibc’s), real cells denser than the fixture’s mostly-null ones, and a sampled peak that is a lower bound. An NCANDS child row’s demographic fields are fixed-size, so its retained rows do not grow with data density; for NCANDS the margin covers the allocator and the sampled peak. -
Confirm. Read the idle RSS from the running pod, and check the figure on the first production generate against the container’s peak memory (cgroup v2
memory.peak). -
One federal-report generate per instance. Both kinds carry the
lease_keyreport_generate, a dispatch label (no engine lease), so a second generate of either kind waitsqueued, holding no permit, until the first ends. -
Replicas and OOM. Size every replica alike: a job runs on the replica that took its POST, and a crashed attempt re-queues on whichever replica’s scan finds it. An OOM kill ends every attempt on the pod. Each re-queues and runs again, up to 3 attempts; a pod that runs out every time fails them
exhaustedwith no submission.
craig-security
| Variable | Default | Description |
|---|---|---|
|
|
HTTP listen port |
|
— |
PostgreSQL connection string; the serving process must log in as |
|
— |
AMQP connection string |
|
— |
Public Keycloak URL for JWT |
|
— |
Internal Keycloak URL for JWKS fetching |
|
|
Comma-separated allowed CORS origins |
|
|
Maximum request body size in bytes |
craig-intake
craig-intake is a stateless edge (ADR-017): it has no
database and no message-queue connection — there are no DATABASE_URL/RABBITMQ_URL variables
for this service. The full variable set (standalone mode, SHINES backend, signed-path limits, TLS)
is in the Configuration Reference.
| Variable | Default | Description |
|---|---|---|
|
|
HTTP listen port |
|
— |
Public Keycloak URL for JWT |
|
— |
Internal Keycloak URL for JWKS fetching |
|
— |
Base URL of craig-cases (for forwarding authenticated reports) |
|
— |
Required (integrated mode). Base URL of craig-security (partner verification + signer-key lookup) |
|
— |
Required. OIDC |
|
— (required) |
Per-deployment HMAC secret for |
|
|
Max requests per hour from a single client IP against public (unauthenticated) endpoints. The devstack overrides this to |
|
|
#3083: max requests per hour from a single client IP against the partner API ( |
|
|
Comma-separated allowed CORS origins |
craig-web (BFF)
| Variable | Default | Description |
|---|---|---|
|
|
HTTP listen port |
|
— |
craig-rules base URL |
|
— |
craig-cases base URL |
|
— |
craig-placement base URL |
|
— |
craig-exchange base URL |
|
— |
craig-financial base URL |
|
— |
craig-security base URL |
|
— |
Keycloak realm URL (for OIDC) |
|
|
OIDC client ID |
|
required under |
craig-web’s confidential |
|
|
How the login access token is validated (#2686): |
|
— |
Public URL of the web UI (for OIDC redirect) |
|
— |
Required. AES-GCM master key for the stateless encrypted session cookie (ADR-013). Must be at least 64 bytes; the service refuses to start otherwise. Generate with |
|
|
Session cookie lifetime in seconds (default: 30 minutes). |
|
|
Emit the |
|
— (required) |
Theme directory name — since Plan U Step 8 (ADR-036) used only to resolve the agency logo ( |
|
— (required) |
Agency display name in the BFF chrome (e.g. "GEORGIA DEPARTMENT OF HUMAN SERVICES"). Plan A § Step 12: no fallback default. |
|
|
App display name in the BFF chrome. |
|
— |
Optional logo URL. |
|
|
Max multipart request-body size (bytes) for the two BFF upload routes (case-contact attachments, placement home documents), applied per-route so all other routes keep axum’s 2 MiB default (#970). Keep it ≤ each storing backend’s attachment cap ( |
|
empty (no proxies trusted) |
#1569: comma-separated CIDRs of the proxies in front of craig-web (ingress/LB). The BFF derives the browser client’s IP through the same trusted-proxy walk the backends use (#766) and relays it on every service-to-service call as an RFC 7239 |
Identity capacity
The internal token issuer’s replica count follows from one replica’s measured capacity (ADR-085 D17; plan
internal-token-issuer U7, #2744). cargo xtask perf --profile identity measures it on the devstack’s scaled
issuer, a port of Canopy’s capacity harness (Canopy ADR-049 P6). It signs client_credentials assertions with the
devstack client keys (devstack/devstack-client-keys.env, a public fixture) at W1’s rate: 600 requests a second at
design load and 1200 at peak. Until worker tokens arrive (plan U12), these grants stand in for the worker-token mix. The
harness adds the JWKS fan-in of 100 receivers, each fetching at most once per 30 s. It probes the issuance log’s append
and samples each replica’s memory, the issuer pool and the jti backlog. Key rotation happens inside the
rolling-restart cell, which keeps the load on past every restarted replica’s first rotation, 540 s after its boot.
The rolling-restart and kill cells restart or kill issuer replicas, dev start --replicas rescales
the stack, and --procedure wipes it at every start. Never run them while a battery or anyone else uses the
devstack. The requires devstack tests in the battery restart nothing.
|
The procedure
One command runs every step on release stacks it starts itself (#3166), from the primary checkout:
export CRAIG_IMAGE_TAG=$(git rev-parse --short=8 HEAD)
cargo xtask perf --profile identity --procedure
| Step | Replicas | Cell |
|---|---|---|
|
1 |
|
|
R |
|
|
R − 1 |
|
|
R |
|
|
R |
|
|
10 |
|
-
Starts. Before each step whose replica count differs from the running stack, the procedure runs
cargo xtask dev start --release --replicas craig-security-issuer=<N>. The run’s first start adds--bake, so every figure is this checkout’s release images. A release start wipes the stack, so each count begins on fresh databases and a fresh key registry.killandrollingshare one start. -
R. The capacity cell writes C and R to
test-results/identity/capacity.json, which the procedure deletes before that step and reads after it. No file after the capacity step ends the run, so no step runs at a guessed size. Without the capacity step, pass--r <R>(2 to 10); beside it,--ris refused. -
Choosing steps.
--steps kill,rolling --r 3runs a subset, always in the table’s order.--window-secs,--warmup-secs,--seedand--archive-ratepass through to every cell;--celland--replicasare refused. -
Failures. A start that fails ends the run. A cell that fails is recorded and the run goes on. The command exits non-zero when any step did.
-
Records. Under
test-results/identity/: each child’s output in<n>-<label>.log, andsummary.mdwith the commit,CRAIG_IMAGE_TAG, the arguments, and per step its replicas, exit code, start, end and the host before and after. The host reading is the CPU count,MemTotal, the three load averages and the 60 ssomeaverage of/proc/pressure/io, eachunknownwhen it cannot be read. -
Where it runs. On the host, not in craig-tools: each start replaces the project network. The cells it starts re-execute in craig-tools as every
perfrun does. -
In CI. The
issuer-capacityjob runs the procedure on its pipeline’s commit: by its play button on amainpipeline, or for a branch as a measurement pipeline of its own (MEASURE=issuer-capacity; Measurement pipelines has the command). It is on no merge-request pipeline, where a failed job would cancel it (#3178), and never on a train or a schedule. SetISSUER_CAPACITY_ARGS(for example--steps kill --r 3) to pass options: beside the play button onmain, or as a second variable of the measurement pipeline. It has a 4 h timeout, and keepstest-results/identity/for 90 days.
To iterate on one cell against a devstack build, start the stack and run the cell yourself. <R> is the R the first
step prints.
# 1. C and R: one replica, the offered rate stepped up until G3 breaks.
cargo xtask dev start --replicas craig-security-issuer=1
cargo xtask perf --profile identity --cell capacity --replicas craig-security-issuer=1
# 2. G1–G8 at R, and at R − 1 (the R − 1 replicas must carry the peak).
cargo xtask dev start --replicas craig-security-issuer=<R>
cargo xtask perf --profile identity --cell gates --replicas craig-security-issuer=<R>
cargo xtask dev start --replicas craig-security-issuer=<R-1>
cargo xtask perf --profile identity --cell gates --replicas craig-security-issuer=<R-1>
# 3. A killed replica and a rolling restart at R keep G3.
cargo xtask dev start --replicas craig-security-issuer=<R>
cargo xtask perf --profile identity --cell kill --replicas craig-security-issuer=<R>
cargo xtask perf --profile identity --cell rolling-restart --replicas craig-security-issuer=<R>
# 4. A rolling restart at R = 10 counts the published keys against the registry model.
cargo xtask dev start --replicas craig-security-issuer=10
cargo xtask perf --profile identity --cell rolling-restart --replicas craig-security-issuer=10
Each cell refuses to run when the running replica count differs from --replicas. --window-secs and
--warmup-secs (default 120 and 30, Canopy’s) set the gates cell’s windows. Each capacity step runs a 10 s warmup and
a 30 s window. --seed replays a run’s arrivals. G8 also needs --archive-rate <rows/s>: the ADR-058 archive engine’s
sustained rate, measured apart, because the engine archives only closed days past the hot window (#3173) and a run
cannot age its own rows. Without it, G8 reads UNJUDGED and the cell fails.
A cell exits non-zero when a gate does not pass. INVALID means G7 broke, so the harness or the host was the bound: generator lag p99 over 5 ms, host CPU over 80 %, the in-flight cap hit, a replica offered more than the limiters admit, a refused grant, or the wrong replica count. Rerun it on a quieter host. The capacity cell fails only when R > 10 or no step held. A failed gate stops plan U8 onward until ADR-085 is revised.
How it measures
-
Open loop. Arrivals are Poisson. Latency runs from each request’s scheduled start, so a slow answer does not slow the schedule.
-
Routing. Requests go round-robin to the replicas whose
/readyzanswers 200 (read every 500 ms), as a load balancer would. A refused connection is retried once on the next ready replica. A request that no replica answers, or that gets no answer within 10 s, counts as a failure. Each grant’s client is a hash of its turn, independent of the replica the round-robin picks (#3169): taking both from the turn’s position pinned each client to one replica whenever the ready count divided the nine clients. -
Limiters. The harness is one source address, where a deployment has many BFF pods, and D17 sizes the per-IP limit per pod.
docker-compose.scale.ymltherefore raises the issuer’sCRAIG_SECURITY__IDENTITY_TOKEN_RATE_LIMIT_RPMto 600 000 under--replicas. The per-client budgets keep their deployed default: nine clients at 6000 a minute. Offering a replica more than 90 % of those budgets (810 a second) makes the cell INVALID, so a C at that ceiling is a lower bound and the R it gives is conservative. -
G4. Ten times a second, the probe appends one row to
identity_issuance_logunder the issuer’s grants (the writer’s statement path), first with no load and then under the design load. Probe rows arerefusedrows with refusalcapacity_probeand replica id00000744-0000-7000-8000-000000000001. They name no client and record no credential. -
G5 and G6. Memory is read with
docker stats(the cgroup’s usage without page cache, a superset of RSS). Pool connections come frompg_stat_activityby replica address, counting only the request pool (application_namecraig-security-issuer); the log writer’s own connection is outside the 22. G6 judges the most connections a replica held open: the pool opens one only when none is idle, so a pool at its ceiling had every connection checked out at once. It also prints the most a replica had busy at a 1 s sample, running a statement or holding a transaction open (pool max 22 (busy 3)). That tells a pool that grew in a burst and sat idle from one under sustained load (#3151). Overdue jti rows are counted at the window’s end. -
G8’s storage figure. The log’s bytes a row are its partitions' total size (table, indexes and TOAST) over its rows. The log is partitioned by day (#3173) and its parent has no storage of its own, so a reading of the parent alone would be 0.
-
Diagnostics. Each step and window prints the mints' and the JWKS fetches' p50 and p99, and the issuer’s busy database sessions by wait event, averaged over the 1 s samples. The kill and rolling-restart cells also print each restart’s start and return to health as offsets from the load’s start, and a breakdown of the window’s failed requests on the same clock. It gives each one’s cause (no replica ready, refused twice, broken mid-request, a 5xx status, timed out, never sent) and the replica it went to, in 5 s buckets (#3152, #3169). The harness raises its soft
RLIMIT_NOFILEto 16 384 (craig-tools starts at 2048), so a full in-flight window never fails a connect locally. -
Build. The procedure’s figures are the release images', built as deployed (
dev start --release --bake). A cell run against a devstack measures itsdevstack-profile (unoptimized) build, so that C is conservative. ADR-085’s production run (plan U21) measures a release build.
Figures
2026-11-27: one commit per mint (#3151). The issuance-log writer now spends each mint’s jti in the transaction that
commits its log row, so a request no longer takes a pool connection to spend it. The issuer-capacity job re-ran the
gates on the release images of that change (#3151, note 4342857221). G7 judged every cell valid.
| Step | Replicas | Result |
|---|---|---|
gates |
3 |
Every judged gate passed: G1 p99 5.0 ms, G3 p99 5.6 ms with 0 of 144 775 failed, G4 p99 2.1 ms, G5 36 MiB, G6 pool maximum 2 (busy 0). G8 UNJUDGED (no archive rate) |
gates-below |
2 |
Every judged gate passed: G1 p99 5.5 ms, G3 p99 5.7 ms with 0 of 144 803 failed, G6 pool maximum 2 (busy 0), where the run before the change failed G6 at 22 (busy 4). G8 UNJUDGED |
In both cells' busy-connection samples at peak, no request-pool connection appears; the WAL waits sampled are all the log writer’s.
2026-11-27: the procedure in CI, on the release images. The issuer-capacity job ran every step on a quiet
dhs-aws-autoscaler-docker-4xlarge runner (16 CPUs; a 1-minute load average of at most 4.0 at every step), in 93 minutes
with the bake. G7 judged every cell valid (#2744, note 4336697782).
| Step | Replicas | Result |
|---|---|---|
capacity |
1 |
C ≥ 810/s, held at every step up to the limiter ceiling (p99 at most 7.7 ms), so C is a lower bound; R = 3 |
gates |
3 |
Every judged gate passed: G1 p99 7.5 ms, G3 p99 8.1 ms with 0 of 144 371 failed, G5 40 MiB, G6 pool 13. G8 UNJUDGED (no archive rate) |
gates-below |
2 |
G6 FAIL: pool maximum 22 (#3151); every other judged gate passed |
kill |
3 |
G3 FAIL: 111 of 145 866 failed (0.076 %), p99 8.7 ms (#3152) |
rolling |
3 |
G3 FAIL: 176 of 1 014 599 failed (0.017 %), 145 436 × 429, p99 8.0 ms (#3169). Keys 10, as modelled |
keys |
10 |
G3 FAIL: 187 of 1 525 925 failed (0.012 %), 82 224 × 429 (#3169). Keys 32, as modelled; peak 32 of D8’s 50 |
On the release build, one replica’s capacity is at least 810/s where the devstack build’s was 50/s, so R drops from 25 to 3. Latency holds everywhere. What fails is G6 one replica short of R, and requests lost when a replica dies or restarts. The two rolling cells' 429s were the harness’s, not the issuer’s (#3169). With three ready replicas, or nine while one of ten restarted, each client went to one replica and offered it 133/s against its 100/s budget, refused once the limiter’s 6000-request burst ran out. The gates cells' 150 s at peak ended before that, so they showed none.
2026-11-08: the devstack build, by hand. Measured on the primary checkout’s devstack (plan U7). The host was shared with other sessions, so
its load swung between about 5 and 125 on 32 CPUs. The images were the unoptimized devstack build. Every figure is
from a run G7 judged valid, unless the row says otherwise.
| Figure | Value | Verdict |
|---|---|---|
C (one replica’s G3 capacity) |
50/s, bounded by a knee: 50/s held at p99 33.9, 18.3 and 74.0 ms, and 63/s broke at p99 356.3, 360.8 and 504.0 ms (three runs). In four more runs, 50/s itself broke (p99 295 to 446 ms). |
— |
R = max(3, ⌈1200 ÷ C⌉ + 1) |
max(3, 24 + 1) = 25 |
FAIL (R > 10) |
Gates at R and R − 1 |
Not runnable: R = 25 is past the 10-replica cap. Run at the cap instead, 10 replicas: |
— |
G1 client-credentials p99 at design, 10 replicas |
393.2 ms (mints p50 4.5 ms) |
FAIL (≤ 50 ms) |
G2 at design, 10 replicas |
0 × 429, 22 failed, 72 988 of 73 010 answered |
FAIL (no 5xx) |
G3 at peak, 10 replicas |
p99 20.1 ms, 2 of 145 034 failed |
PASS |
G4 log-append p99, idle → design |
73.1 → 116.2 ms |
FAIL (≤ 87.7 ms) |
G5 peak memory a replica |
20 MiB |
PASS (≤ 192) |
G6 pool maximum, overdue jti rows |
22, at the ceiling; 42 295 overdue |
FAIL (pool < 22) |
G7 |
valid at design and at peak |
PASS |
G8 |
72 502 rows for 72 496 tokens; the archive rate was not measured |
UNJUDGED |
Hot window at design load |
51 840 000 rows a day, about 20 GiB a day at the measured bytes a row |
— |
G3 with a killed replica, 10 replicas |
p99 117.4 ms, 30 of 145 373 failed (0.021 %) |
FAIL |
G3 during a rolling restart, 10 replicas |
p99 743.8 ms, 1430 of 1 541 188 failed, 77 254 × 429; generator lag p99 7.62 ms |
INVALID (G7) |
Keys published after a rolling restart at R = 10 |
49, against a model of 49 (52 / 49 / 43 at the second before, at and after the reading); 10 new replicas, all rotated. The model’s peak was 52, over D8’s 50. |
Count matches. Peak FAIL: see below. |
Verdict. C = 50/s gives R = 25, past the cap of 10, and at the cap G1, G2, G4 and G6 fail at design load. Under ADR-085 D17 this sends the ADR back: plan U8 onward waits for the maintainer’s decision on ADR-085.
Where the knee comes from. The evidence points to the commits on the mint path, which wait on the WAL flush. Replica CPU is not the bound, and neither is a lock:
-
Not replica CPU. Each mint cost one replica about 2 to 3 CPU-ms (892 and 1305 clock ticks over about 4500 mints each). The container has no CPU quota.
-
Not the HTTP path or the harness. At the knee, JWKS fetches through the same harness, network and replica answered at p50 3.0 to 4.3 ms, while mints rose to p50 108 to 147 ms.
-
Not a lock or the pool. The only lock held across an await on the mint path is the 5 s client-status memo (one SELECT). On one replica, at most 3.5 of the 22 pool connections were busy on average.
-
The WAL flush. The issuer’s busy sessions waited on
LWLock:WALWriteandIO:WalSync: 1.8 and 0.8 pool connections plus the log writer on a broken 50/s step, and 6.2 onWALWriteat the 10-replica design load. Each mint commits twice in series: its jti INSERT, then its issuance-log batch. The writer barely batched, at 1.02 to 1.53 rows a transaction (about 38 commits a second at the knee). Both commits share one WAL with every devstack service, on a disk the host’s other sessions also used. -
C depends on the host. At 10 replicas the peak carried 120/s a replica at p99 20.1 ms during a quiet minute. One replica broke at 50/s during busy ones.
Not measured: how the delay splits between the jti commit and the log commit, which needs a span on each in the issuer. G7 judges host CPU only, never IO pressure.
Connections. Ten replicas hold up to 10 × (22 + the log writer) = 230 connections. That exhausted the devstack’s
max_connections = 250: Postgres logged remaining connection slots are reserved during the gates and after the
rolling restart. Size max_connections for R × 23 plus every other service.
The rolling restart’s peak. When the restart began, 40 keys from 31 replica processes were already published, left by this session’s earlier restarts at 1 and 10 replicas. The model replays them, so its peak of 52 is that history plus one rolling restart, not one rolling restart from steady state.
The registry model (xtask/src/cmd/perf/identity/keymodel.rs) replays restart patterns against D8’s cadence and
the 64-key cap. The model computes these counts; none is measured. Ten staggered replicas publish 10 to 20 keys in
steady state. A rolling restart of ten rotated replicas peaks at 30 keys. The worst alignment peaks at 40: every
replica rotates at once and restarts just after inserting its next key. D8’s allowance for a rolling restart is 50.
After the worst rolling restart, four more restarts of rotated replicas, or seven of unrotated ones, within 22 minutes
peak at 44, within allowances of 62 and 64. Past that, a crash loop fills the cap: the registry refuses the 65th key,
and the replica holds readiness.
Public report routing
The public report portal is served by craig-intake (the edge), not craig-web (epic &60 Phase 5; ADR-043). On a
single public hostname, the ingress path-routes the public report paths to craig-intake and everything else to
craig-web — there is no HTTP redirect and no compatibility route (constraint L6). craig-intake runs in
integrated mode and listens on container port 8008.
|
Required operator cutover step
This is a breaking change. After upgrading, you MUST add the ingress rule below. Without it, |
Route /report and /report/* → craig-intake (:8008); all other paths → craig-web (:8080).
# Public report portal → craig-intake (edge). No redirect (L6).
location /report { proxy_pass http://craig-intake:8008; }
location /report/ { proxy_pass http://craig-intake:8008; }
# Everything else → craig-web (BFF).
location / { proxy_pass http://craig-web:8080; }
# Attachment uploads: nginx's default client_max_body_size is 1 MiB, which
# would 413 uploads at the edge before they reach the BFF. Raise it to at
# least the largest upstream limit — craig-intake signed_body_limit (30 MiB)
# ≥ craig-web upload limit (11 MiB default) — see the upload-size tiers below.
client_max_body_size 30m;
apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
name: craig-public
annotations:
# ingress-nginx defaults to a 1 MiB body cap, which would 413 attachment
# uploads at the edge. Raise it to the largest upstream limit — craig-intake
# signed_body_limit (30 MiB) ≥ craig-web upload limit (11 MiB) — see the
# upload-size tiers below (#970).
nginx.ingress.kubernetes.io/proxy-body-size: "30m"
spec:
rules:
- host: report.example.gov
http:
paths:
- path: /report
pathType: Prefix
backend:
service:
name: craig-intake
port:
number: 8008
- path: /
pathType: Prefix
backend:
service:
name: craig-web
port:
number: 8080
Upload limits
The one place the attachment size policy is written down (#974). A file upload traverses up to four request-body caps (five on the public-portal path); the smallest one wins, so a large attachment 413s at whichever tier is under-sized. The shipped defaults satisfy the ordering invariant
BFF upload cap (11 MiB) ≤ backend attachment cap (51 MiB, derived) > object-store per-file cap (50 MiB)
out of the box: a fresh deployment uploads without configuring anything. Override any tier and keep the ordering.
-
Ingress / reverse proxy — nginx
client_max_body_size(default 1 MiB) or ingress-nginxproxy-body-size(default 1 MiB), shown in Public report routing. Operator infrastructure (the repo ships no gateway — ADR-043); size it to the largest upstream cap you expose (30 MiB covers the intake signed nest). -
Public edge (craig-intake, the portal path) —
CRAIG_INTAKEPUBLIC_MAX_FILE_BYTES(default 10 MiB, #1324) underCRAIG_INTAKEBODY_LIMIT(default 11 MiB); the signed nest carries its ownCRAIG_INTAKESIGNED_BODY_LIMIT(30 MiB, ADR-042 §D9 — the per-route precedent this section generalizes). MACHINE-checked: intake boot-validates its per-file cap against the declared downstream cap (CRAIG_INTAKECASES_MAX_UPLOAD_BYTES) and refuses to serve on inversion — set the declaration whenever you override cases' cap. -
BFF (craig-web) —
CRAIG_WEBUPLOAD_BODY_LIMIT(default 11 MiB), applied per-route to the two BFF upload routes (#970); every other BFF route keeps axum’s 2 MiB default. Keep it ≤ the backend attachment cap. The caregiver portal’s certificate upload is its own BFF tier of the same shape —CRAIG_PORTALUPLOAD_BODY_LIMIT(default 11 MiB; the effective cap a caregiver meets, the form names 10 MB) under placement’s home-document cap; an over-limit body there is the portal’s "too big, or the upload stopped" flash rather than a 413 (U10, #1853). -
Storing backend —
CRAIG_<SVC>ATTACHMENT_BODY_LIMITon craig-cases (contact / report / court-order attachments), craig-placement (home documents) and craig-exchange (ICPC attachments): the whole-request cap for EXACTLY their upload routes, layered as an innerDefaultBodyLimit(the sharedcraig_api::attachment_body_limithelper; axum’s body extractors read the innermost limit). Unset derivesCRAIG_STOREMAX_UPLOAD_BYTES+ 1 MiB of multipart-framing headroom. Every other route of those services — and every route of every other service — keeps the globalCRAIG_<SVC>__BODY_LIMIT(2 MiB default), so the larger cap never widens the request-body surface of the small-JSON endpoints. MACHINE-checked: an explicit value at or under the store’s per-file cap refuses the boot, because the whole-body 413 would then pre-empt the diagnostic per-file 400. -
Object store —
CRAIG_STORE__MAX_UPLOAD_BYTES(default 50 MiB), the per-FILE cap enforced while buffering thefilepart (a typed 400 naming the limit).
Rejection shapes at the backend: an over-cap FILE is the 400 upload too large: exceeds N byte limit;
a whole-request breach of the attachment cap (or of BODY_LIMIT on any other route) is the 413
payload-too-large / malformed-multipart RFC-9457 document; a part header the parser refuses (a CR, LF or
other control character, most often in the file name) is the 400 malformed-multipart whose fixed detail names the
part header and the file name and quotes none of the submitted bytes (#2532). Before #974 the devstack raised
CRAIG_<SVC>__BODY_LIMIT to 50 MiB on three whole services; those overrides are gone (pre-1.0
Changed) — a deployment that copied them can drop them too.
SHINES conversion cutover (#1071 / ADR-057)
One-time (per cohort batch) conversion of the GA closed-cohort subsidy recipients (RCS/ERCS, ERSG/ENRSG) out of SHINES — see ADR-057 for the full contract. The conversion runs as a bounded WINDOW, not a standing capability.
Deploy order (parser-first, then knob-off):
-
Deploy the substrate release (#1071 MR-A) EVERYWHERE first — it carries the craig-security audit-parser arms for
financial.subsidy_agreement_imported/financial.subsidy_import_batch_finalized, and the parser must be live before any producer can emit (no imported event may ever be audited through the unknown-type fallback). Let in-flight events drain. -
Deploy the surface release (#1071 MR-B) with
CRAIG_FINANCIALSUBSIDY_IMPORTENABLEDUNSET/false — it is knob-off inert (every import write refuses with a typed 403 naming the knob; GETs work).
The conversion window:
-
Enable — set
CRAIG_FINANCIALSUBSIDY_IMPORTENABLED=trueon craig-financial for the window. This gates ALL import writes including finalize; flipping it is the operator’s recorded consent (configuration reference). Since #1938 finalize is a background job and the knob is checked TWICE: the synchronous 403 at enqueue, and again at attempt start — a knob flipped OFF between the 202 and the attempt readsfailed(refused_at_start)naming it. -
Stage — run
craig --profile <deployment> subsidy import --manifest <json> --records <jsonl>(from thecraigCLI; an xtask verb until #3126). The operator signs in as the responsible STATE-OFFICE human (craig login --device) — there is deliberately NO service-principal mode (the finalize authority isApprovalAction::ImportHistory, whose floor the jurisdiction’s administrative-authority family declares — Georgia:state_office; a session below it is refused naming the floor). Staging runs the full validation battery per record and persists the outcome on the record row (staged / rejected + typed blockers + warnings) — nothing touches the live ledger. A dry run is stage + inspect + abort. -
Reconcile — the records ledger IS the reconciliation export: re-list the batch, review the rejection manifest and the warnings. Beyond-grace-overdue ACTIVE heads are BLOCKERS by design (refuse-beyond-grace, ADR-057 D6): complete or suspend the review in SHINES and re-export — CRAIG never auto-suspends at conversion. Expect and accept
overdue_renewal_anchor/overdue_paper_anchor(within-grace) andaged_suspensionwarnings: they are native-parity states; the post-finalize review sweep owns them — an aged suspension will surface on the sweep’s leg-2 backlog, and within-grace overdue anchors will suspend later only under YOUR sweep knobs. -
Finalize — the tool’s finalize step POSTs
{ client_request_id }ONCE (#1938, planbackground-jobsU6;--finalize-request-id <uuid>pins the id for wrapper scripts, else one is minted per invocation) and craig-financial answers 202 with animport_finalizejob the tool polls to terminal (2 s cadence, no overall deadline; a bearer expiry mid-poll re-runs the device-code grant ONCE and resumes the SAME job;--bearer-tokencannot be re-minted, so the tool exits naming the job andcraig job wait financial <id>). The consent act stays synchronous INSIDE the enqueue: the manifest gate (count + checksum + zero live rejections, else a 409 naming the four numbers) runs in the claim transaction BEFORE thequeuedrow and refuses with nothing enqueued. The job runs passes of the per-record engine until the batch leavesfinalizing:succeededwithresult.status = finalizedis the closeout;result.status = stagingmeans a pass rejected records (correct, restage, re-run). A job that endsfailedleaves the batchfinalizingexactly as the record ledger stands —crash(the process died mid-attempt),lost_proof(it died between the 202 and the attempt: the in-memory state-office proof is gone),interrupted(a rollout cut the attempt at a record boundary) orno_progress(three consecutive passes moved nothing;error.detailcarriesremaining_staged/passes— read the financial log for the record that cannot advance; a failed job carries noresult, the batch detail GET is the ledger). The tool prints the batch’s counts and the rule: re-run it against the same batch (--batch-id <id>,--yesskips the prompt) — a FRESH finalize id resumes per record exactly once (the SAME id would only replay the failure). Finalize is safe beside the subsidy generator and the case-assignment handlers (#2417) and beside a reinstatement of the same child’s agreement (#3075): each record’s transaction takes the child’s pay-exclusion lock, then the child’s family history locks, then (for a record that names a case) the per-case assignment lock, before it writes its first agreement row. Each agreement is born with itspayment_cutover_month, review slots materialized from the imported anchors (the conversion baseline — SHINES keeps pre-cutover review history). -
Disable — set the knob back to false and restart. VERIFY the closed posture: an import write (e.g. a batch create) must return 403 naming the knob; batch/record GETs must still work (the post-conversion audit surface). Materialized agreements are unaffected — their lifecycle never consults the knob.
The money boundary: SHINES pays every month strictly BEFORE cutover_month; CRAIG
pays every month from it onward. CRAIG enforces its side by machine — the generator’s
BeforeCutover rule bounds the scheduled, manual, and reconcile paths, and voids any
stray pre-cutover undisbursed row — but the SHINES side is inter-system agreement (⁂
#1073): confirm SHINES payment stop-dates against the batch’s cutover_month before
finalizing. Corrections after money moved are a designed 409: use native
amendments/transitions (+ #1028 adjustments), never a corrected re-export.
Below-floor subsidy backpay (#1115 / plan backpay-import-path)
The reconcile floor (current − 12) makes a month older than twelve months unreachable for the generator, so a late
activation’s earlier months need a separate act: the backpay ledger (#2223, #2224) behind the seven
/v1/financial/backpay/… routes (#2225; API reference, tag Subsidy Backpay). Unlike
the SHINES conversion window above, backpay is a STANDING capability (G-B ruling 2026-10-08 on #1115): the knob stays
on while the jurisdiction pays late activations, and OFF is the kill switch.
Deploy order (rulesets first, then knob-off):
-
Bootstrap the four authz files on craig-rules BEFORE the first image carrying #2225 — every engine-bearing service enumerates ALL resource types at boot, so
SubsidyBackpay/SubsidyBackpayBatchread as a coverage gap fleet-wide until the files are live (a boot bail whereverAUTHZ_REQUIRE_FULL_COVERAGE=true):craig rules bootstrap target/config/layers/<j>/<j>-authz-subsidy_backpay.jsonand…-authz-subsidy_backpay_batch.jsonper activated jurisdiction, as a humanadmin(theBackgroundJobprecedent in Background jobs rollout). Both ship admin-only. The devstack needs no bootstrap. No migration rides #2225. -
Roll the image with
CRAIG_FINANCIALSUBSIDY_BACKPAYENABLEDUNSET/false: every backpay write (batch create, stage, supersede, finalize, abort) refuses with a typed 403feature-disablednaming the knob; the batch list and detail GETs work.
The consent (G-B, Option B): enabling the knob is the jurisdiction’s recorded decision that months the reconcile
floor makes unreachable may be paid ONLY through the staged-and-finalized backpay act. The flip is made through the
deployment’s change-controlled configuration, authorized by the office that holds the jurisdiction’s backpay finalize
floor (Georgia: the state office), and that change record is the consent’s evidence; cite the G-B ruling in it. Each
finalize is the per-batch consent, bound by the configured BackpayFinalize floor (ADR-074), a finalizer who staged
none of the batch’s staged or materialized records, and the content_checksum of the prices the finalizer reviewed.
CRAIG keeps no separate consent record: the durable trace is each payment’s created_by (the finalizer) and each
record’s staged_by (the stager); the job row and its claim are pruned with the jobs window.
The operator flow runs through craig backpay (#2226; an xtask verb until #3127), which covers every backpay
act, so no step hands an operator a bearer token for a raw API call. The deployment’s craig profile names
craig-financial and the identity provider (--profile <deployment>), and the operator signs in as a human with
craig login --device before the act; the bearer is never printed. The global --bearer-token is for automation, and
a 401 cannot re-mint it. The stager and the finalizer are different people, so each signs in under their own
account (on a shared host, under their own profile name or OS user: the token cache is per profile). The full
reference is CLI (craig backpay).
-
Stage, as the stager:
craig backpay stage --file months.jsonl --request-id <uuid>, one{"agreement_id", "payment_month"}per line. The file is checked before any request: an empty file, more than 50,000 lines, a mid-month date or a repeated key is refused with nothing sent. The tool prints the key manifest checksum andcreate client_request_id <id>before the create (a re-run with the SAME--request-idreplays the one batch). The batch freezes the reconcile floor at creation. A line at or above thatfloor_monthis refused before any stage POST: abort the empty batch and re-run without it. Each line then stagesstaged(the priced row frozen),rejected(typed blockers) or a replay, at--throttle-rps(1 to 10, default 5).run-<batch>.jsonandrejections-<batch>.jsonlland in--out(defaultbackpay-run). A run that stops mid-file (a401, a batch-wide refusal, a transport failure) printscraig backpay stage --file <f> --batch-id <id>. That resume reads the ledger once and skips every key already live in the batch. -
Review:
craig backpay show --batch-id <id>posts nothing. It prints the batch header and every record, then, for astagingorfinalizingbatch, the review: every priced-row field of each live record, the gross total andcontent checksum: <hex>. A refusal a finalize would raise (rejected records, a count or key-manifest mismatch, a row-integrity failure, a ledger that moved mid-read) prints asa finalize would be refused: <reason>. The read-only web pages/financial/subsidy-backpay(the batch list, linked from the subsidy agreements page) and/financial/subsidy-backpay/<id>(counts, records and blockers) show the same ledger to an admin session. -
Finalize, by a DIFFERENT operator who holds the finalize floor and staged none of the batch’s staged or materialized records:
craig backpay finalize --batch-id <id>. The tool reads the ledger again and refuses locally when the session’s (unverified) subject staged a reviewed row; the service’s 409backpay-finalizer-stagedis the authoritative check. It prints the review and its checksum, then the operator types the checksum’s first 12 hex characters. A non-interactive run passes--expect-checksum <hex>(the checksumshowprinted) instead; there is no bare--yes. The tool posts only when the checksum it computed over the rows it just printed equals the confirmed one. It printsfinalize client_request_id <id>before the ONE POST (--finalize-request-idpins it), then the job id and the deep link/financial/subsidy-backpay/<id>?job=<job>, and polls the job; see thebackpay_finalizebullet in Background jobs rollout. -
Verify: the tool exits 0 and prints the post-finalize counts (every manifest key
materialized); the web detail page’s?job=<id>mount readssucceeded; the payments exist aspending. -
Pay: finalized payments are born
pendingand pass the ordinary approve → issue chain before money leaves. -
Disable only to stop every backpay write (the kill switch): a restart, after which queued finalize jobs end
lost_proof; running onesinterrupted(a graceful restart) orcrash(a killed process); the batch staysfinalizing, andcraig backpay finalize --batch-id <id>after re-enabling resumes it per record.
Exit codes (every subcommand):
| Exit | Meaning |
|---|---|
0 |
Done: staged clean, shown, finalized (or already finalized), aborted, or the dry |
1 |
An error the records cannot fix: transport, decode or I/O, a transient or internal service failure, an
unclassified answer, or a non-resumable job failure ( |
3 |
Operator action required: rejected or refused records, a pass that sent the batch back to |
4 |
Resumable: the job keeps running, or the batch stays |
Corrections (ruling 2): the refusals are distinct 409s, and supersede prints each one with its remedy.
-
An undisbursed month: void the payment (its web payment page,
/financial/payments/<id>), thencraig backpay supersede --record-id <id>, then stage the month again: into the same batch withstage --file <f> --batch-id <id>while it isstaging(ruling F-B), else into a new batch. Superseding before the void is 409backpay-supersede-void-first. -
A disbursed month: record a payment adjustment on the payment’s web page (or
craig adjustment create), then approve it through the CLI withcraig adjustment approve <id>(CLI); the record stays. Supersede is 409backpay-month-disbursed. -
A diverged record (a finalize pass sent the batch back to
staging;finalizelists each one with its key and blockers and exits 3):supersede --record-id <id>, thenstage --file <f> --batch-id <id>, thenfinalizeagain. -
A poisoned or unwanted
stagingbatch:craig backpay abort --batch-id <id>prints the batch and posts nothing; add the global--yesto abort it. Abort retires the batch, freeing the pairs its staged records hold. It never unpays: materialized records and their payments stay (void or adjust them individually), and each diverged record is superseded to free its month. Abort is refused (409batch-state) once the batch isfinalizing.
Runbook: a batch stuck finalizing
Symptom: the batch stays finalizing, and every fresh-id job ends failed(no_progress) (remaining_staged > 0,
passes = 3 in error.detail) or failed(engine_failed) with detail Store.
-
Case 1, a raw-corrupted
canonical_payloadthat no longer decodes. Each pass classifies it as an infrastructure error, so the record stays staged, and three barren passes givefailed(no_progress). The WARNbackpay finalize: infra error; the record stays stagednames therecord_idandvariant = Db. The web list (/financial/subsidy-backpay) still shows the batch status and counts. The detail page that fails (the service answers 500, which craig-web renders as its upstream-failure page) is the one holding the wedged record, and any tool read of the whole ledger fails the same way (showandfinalizeexit 1). -
Case 2, a canonicalization failure. It is pass-fatal (
failed(engine_failed), detailStore, the log namescanonicalization failed), and unreachable today underNUMERIC(10,2)money rounded to two places.
The operator cannot abort the batch (409 batch-state while finalizing) or supersede a staged record (409
batch-state). Money: no payment exists for the wedged record; records already materialized stay paid (pending
payments in the ordinary chain), and the subsidy_backpay_bounds invariant stays green.
Action: do not hand-edit backpay rows (the frozen payload and its hash are the evidence). Collect the batch id, the
job ids and the log lines, then escalate as a fix: issue. No API remedy exists today; #2229 tracks the operator
remedy for a wedged batch. Tell it apart from the cases that are NOT wedged:
-
crash/lost_proof/interrupted: wait until the old job readsfailed(a fresh id answers 409job-already-activeuntil the classifier stamps the dead job, stale after 30 s), then runcraig backpay finalize --batch-id <id>, the command the stopped run’s exit-4 line names. It mints a fresh id, reviews the ledger again and posts the confirmedcontent_checksum(the resume does not re-verify it); -
a long
waiting_for_lease: a peer holdssubsidy-backpay-finalize:<batch_id>; checkpg_locks.
Investigation response deadlines rollout (#895)
The #895 program (plan investigation-response-deadlines, archived; as-built in
ADR-072 § Amendment #895) made the referral’s
response priority and the investigation’s response deadline DERIVED through three per-jurisdiction
rulesets, retired direct referral creation and the caller-typed response_due_at pre-1.0, and added
an audited deadline override. Six releases carry it (the CHANGELOG Unreleased entries #1743–#1748);
ONE of them is a stop-the-world cases cutover. Order:
-
Promote the rulesets on craig-rules BEFORE any cases image that consults them — never demote first. All nine
{j}-response-priority/{j}-response-window/{j}-response-deadline-overridev1.0 files (georgia, texas, testonia — testonia is a fixture the seed never loads), the intake-screening OUTPUT-enum bumps (georgia-intake-screeningv1.4 /texas-intake-screeningv1.3) and thegeorgia-authz-investigation/texas-authz-investigation1.2.0 operation rows. A cases image consulting an ABSENT response ruleset refuses every report conversion and every investigation open with a typed 500 naming the ruleset (fail-closed by design — the ruleset is the image’s dependency, never the reverse); an intake-screening surface WITHOUT theresponse_priorityenum is NOT READY (response-priority-enum-missing), so the screening act and conversion answer the typed 503screening-surface-not-readyuntil the bump lands; the authz 1.2.0 rows are what confine the override operation to its operation-scoped rows (without them the operation reaches the old supervisor wildcard grant — the CLOSED arm still refuses, but the authz posture the release documents holds only with 1.2.0 live). -
The referral cutover (#1746, migration
20260910120000_referral_response_priority) is a STOP-THE-WORLD cases cutover. The migration DROPSreferrals.priorityand bumpsschema_compat_floorto its own version (ADR-063 D3). The floor is checked ONLY at boot: a running N−1 replica is not stopped by the migration — its referral reads simply start failing once the column is gone — and an N−1 replica that restarts refuses to boot ("roll forward"). Sequence: scale cases to zero → take the operator’s database backup / PITR mark under write quiescence → run the ADR-063 gate (<binary> migrate; its log carries aRAISE NOTICEcounting the referrals that have noauthorizing_decision_id— born by the retired direct-create route, they stayUNDERIVEDfor good and can never open an investigation; new referrals are born by conversion only) → start the new image → roll craig-web and the CLI in the SAME window, because the referral wire changed both ways:Referral.prioritybecameresponse_priority+ provenance on the read side,POST /v1/cases/reports/{id}/convertrefuses apriorityfield with a typed 422 on the write side, andPOST /v1/cases/referralsis gone (a routing 405 — the collection root is read-only). -
The other four releases are schema-additive and roll normally, ruleset first. #1745 (staff report entry;
20260909120000_report_receipt_attribution, no floor bump), #1744 (the arithmetic + the holiday seam; no migration), #1747 (the derived deadline;20260911120000_investigation_response_window— the provenance + override columns and thev_investigationsview, no floor bump) and #1748 (the override; no migration — it writes the columns #1747 shipped). Two wire notes for #1747: the investigation READ is safe in either order (craig-web’sresponse_timelinessview fields are serde-defaulted, so a web rolled ahead of cases still renders), but the investigation OPEN isdeny_unknown_fields— an N−1 craig-web form or an N−1 CLI still sendingresponse_due_atanswers a typed 422 until it rolls, so roll web + CLI promptly after the cases image. A devstack needscargo xtask dev reseedfor the seeded provenance to appear. -
Production rollback = redeploy the N−1 images AND restore the cases database from the pre-gate backup. Rows written after that backup are LOST — the release note must say so.
cargo xtask migrate rollbackis the devstack / CI snapshot restore only (a priormigrate snapshot;--forcefor a newer schema; every snapshotted database by default) — it is not a production procedure.
What the operator lives with afterwards:
-
craig-rules is on the request path of every report conversion and every investigation open. The consult runs as the acting worker inside the S2S hop budget; craig-rules unreachable / 5xx / 429 / a blown budget is a typed 503 (retry when rules recovers), a relayed 403 is
rules-consult-denied, an absent ruleset or an undecodable / drifted output is a named 500 — never a defaulted token or a guessed deadline. Budget craig-rules' per-IPCRAIG_RULES__RATE_LIMIT_RPMfor one evaluation per conversion and one per open from the cases pod(s) (plus one lazy roll-up for each pre-cutoverUNDERIVEDreferral that still has a decision, the first time it is opened). -
The Georgia and Texas override arms ship CLOSED.
POST /v1/cases/investigations/{id}/response-deadlineanswers 403response-deadline-override-refusedwith the arm’s policy basis verbatim for every actor that reaches the consult; a caseworker — an assigned one included — is refused 403 at authz before any consult, andadminor any realm role the intake-screening surface does not map is 403screening-actor-unmapped. Opening an arm is a ruleset promotion (role floor, reason requirement, extend-only and max hours are the arm’s outputs), never a code change or a knob; no web form ships while every arm is closed. -
Holiday calendars are StateBundle data.
StateBundle::holiday_calendar()defaults to EMPTY, and no Georgia or Texas window row setsskip_holidays(PAMMS 3.32 counts holidays as weekdays), so GA and TX deployments configure nothing. A jurisdiction whose window row DOES setskip_holidaysmust populate the calendar (entries plus acovered_from/covered_throughspan covering the whole window): an uncovered calendar is a named 500 at investigation open — an unlisted date is never silently a working day — and malformed calendar data refuses cases boot. -
A pre-cutover referral without a screening decision cannot open an investigation (409
response-priority-underivable); re-enter the intake throughPOST /v1/cases/reports(craig-web New Report, CLIcraig intake submit-report). A referral whose roll-up answeredNONEopens no investigation either (409response-window-undefinednaming the window basis): the token is snapshotted at conversion, and re-deriving it after a superseding decision is a filed follow-up.
Partner modules in the configuration layer (#3200 / ADR-090)
A jurisdiction’s configuration layer may hold partners/: its partner code as WebAssembly modules, with a manifest
(Partner modules). craig-exchange loads partners/partner-set.wasm from
the layers CRAIG_CONFIG_SOURCE names when it boots, and registers what it provides: that is the deployment’s
partner set, since no build compiles a partner in. No toolchain is needed where CRAIG is deployed: the committed
module is what is loaded.
What to look for at boot. One of two INFO lines from craig-exchange:
partner modules loaded from the configuration layer modules=<jurisdiction> version=<the modules' version> contract=1.0 partner_set_sha256=<64 hex digits>
no configuration layer holds partner modules
partner_set_sha256 is the SHA-256 of the loaded file. Compare it with sha256sum partners/partner-set.wasm in
the layer at the pinned commit to confirm which build of the partner code a service runs.
What refuses the boot. craig-exchange exits at startup, naming the cause, when the layer’s modules are not what
it can run: more than one layer holds partners/; the manifest is missing, unreadable or names another major
version of the contract; the module is missing, is not a module of the contract, or holds other interfaces than
its manifest lists. The remedy is in the layer: its
maintainers fix and rebuild the modules (Partner modules, § Building and
checking), and the deployment pins the new commit.
Georgia’s layer holds partners/, so a Georgia deployment sees the first line. A deployment whose layers hold
none sees the second, and its configuration may then list no adapter: a listed adapter nothing provides refuses
the boot.
Outbound partner authentication (#1813 / ADR-083)
craig-exchange presents a partner’s credential itself, on manual sends, trigger sends and the connectivity
probe. The partner row names a scheme and secret REFERENCES (auth_type, auth_config; see
the exchange data model); the deployment supplies each referenced value and the
hosts it may reach. A reference <ref> (lower case) names three variables, <REF> being it upper-cased:
| Variable | Meaning |
|---|---|
|
The value, inline. Wins over |
|
A path the value is read from on every send: at most 8 KiB, one trailing LF or CRLF stripped. |
|
The exact hosts the value may be sent to, comma-separated, each as the
endpoint URL’s canonical host: lower case, an international name in its |
|
Hosts a credential-bearing partner may reach over plain
|
A value holding a control byte (0x00-0x1F or 0x7F, TAB included) is refused; every other byte, non-ASCII
included, is accepted. The CRAIG_PARTNER_SECRET_* variables are never cached and are read at boot only for the
advisory warning below; CRAIG_EXCHANGE__PARTNER_AUTH_PLAIN_HTTP_HOSTS is read once at boot, so changing it takes a
restart. What follows from each choice:
-
Rotation. An inline value changes when the process restarts; a mounted
_FILEchanges on the next send. Either comes from the orchestrator’s secret store. ADR-064’s sops store holds devstack values only. -
Binding. Every partner row naming a reference may reach every host bound to it, so a broad binding grants every such row. The binding is host-only: a bound value may reach any port and any path on that host. A reference with a value and no
_HOSTS, or whose list omits the partner’s host, sends nothing (auth-misconfigured); one with no value sends nothing (auth-unavailable). -
Reference names through the probe. A reference’s value is read before its binding, so the probe answers
auth-unavailableorauth-misconfiguredfor any host a partner writer stores: that writer can learn which reference names are provisioned (names only, never a value). -
Plain http. Listing a host in
CRAIG_EXCHANGE__PARTNER_AUTH_PLAIN_HTTP_HOSTSsends credentials to it in clear. -
Failures. A credential problem holds or fails jobs under an
auth-*class (auth-unsupported,auth-misconfigured,auth-unavailable, andauth-refusedfor a trigger record the partner answered 401 or 403);auth-unavailableandauth-refusedretry on each job’s remaining attempts first, so the ladder rides out blips only that far. Nothing is lost: fix the secret or its binding, then release the interface’s record jobs of that class (craig-cli exchange trigger-release --interface <iface> --record-class <class>, repeated until it re-stages nothing) and, forauth-unsupported/auth-misconfiguredadmissions,--held-reason. A manual send the partner answered 401 or 403 rides the shared retry ladder toretries-exhausted; retry it after the fix. -
Deactivation. Deactivating a partner stops its queued manual jobs (
partner-inactive) and its trigger jobs (partner-changed). -
The boot warning. At start, exchange logs one
warn!per active partner whose credential would be refused now, naming the partner id, the class and the reference, never a value. It refuses nothing. -
Logs, events, stored responses. They carry a class and a reference name, never a value. A partner answer that echoes the credential is stored with each form exchange sent (the value, its header value, Basic’s encoded token, and their JSON spellings) replaced by
[credential]. The match is exact-form: a partner that echoes the secret transformed or escaped (a\uescape of a non-ASCII byte, a Go-style\u003cfor<or\u0026for&) defeats it and is stored unredacted, and a value short enough to occur by chance in an answer is redacted wherever it occurs there. -
The probe.
POST /v1/exchange/partners/{id}/testpresents the configured credential, so it needs partnerupdate, and reportsauth_applied(the scheme presented;/healthmay ignore it). A partner that answers it 401 or 403 is reported as the adapter’s error, with that status.
To activate a partner: provision its secret and _HOSTS, set auth_type / auth_config, run the probe, then,
for a trigger interface, its consent knob.
Upgrading through #2427 and #1813. #2427 is the fail-closed step: from it, every partner whose type is not
none holds or fails auth-unsupported, and its stored auth_config was emptied. Provision each secret and
binding before or with #1813, write each row’s reference config again (an emptied config on a credential-bearing
type is auth-misconfigured from #1813), then release the interface’s auth-unsupported admissions and record
jobs; they send once, authenticated. A deployment that relied on unauthenticated sends sets those rows to none.
Asking a person index (#3192)
A person index is the partner that answers who a person is across agencies
(Georgia’s is the EMPI). A deployment has one when its configuration layer’s
partner set provides one (A person
index). craig-exchange asks it on craig-cases' behalf through three routes,
POST /v1/exchange/person-index/matches, /registrations and
/participations, which only craig-cases may call, relaying a worker.
craig-cases calls them from the person-index conversation, three routes of
its own under /v1/cases/cases/{id}/persons/{person_id}/index-inquiries
(The person-index
conversation). A worker reaches them from a case’s Household tab, which
offers the ask only where the jurisdiction’s bundle names
person_index_identifier_kind.
The conversation needs, in the jurisdiction’s configuration layer:
-
person_index_identifier_kindinbundle/settings.toml, naming a declared identifier kind: the kind an index’s id is recorded under. Without it every act answers 409person-index-unconfigured. -
The ruleset
<jurisdiction>-person-index-choice, which readscountandtop_scoreand answersselection_open,selectable_from(present exactly when selection is open) andregistration_open. The jurisdiction’srule_evaluationauthorisation must admit the workers who may update a case, since the ruleset is consulted under the acting worker’s authority (403rules-consult-deniedotherwise).
and, in the deployment, a field-encryption key: a candidate is remembered
only by a keyed digest of its id, so a keyless deployment refuses the
conversation (409 person-index-unconfigured).
A call is made only when all of these hold; otherwise nothing is sent:
-
Consent:
CRAIG_EXCHANGEPERSON_INDEX<INTERFACE>__ENABLED=true(default off), naming the index’s interface. Asking releases a person’s names, sex and date of birth to the partner. Without it a call answers 403feature-disabled, naming the variable. A variable naming an interface the partner set has no person index for stops craig-exchange at boot. -
One partner row: exactly one active partner of that interface, with an endpoint and a usable credential (503 otherwise).
-
An agreement: that partner’s data-sharing agreement is active today (409
dsa-not-activeotherwise).
What a call leaves behind: nothing in craig-exchange’s database. A candidate
the index answers is another agency’s record of a person; craig-exchange
passes it to craig-cases and stores none of it, and its log and its
exchange_person_index_calls_total\{operation, outcome} counter carry the
product’s own ids and counts only.
A call that fails is not sent again: a registration that failed may have
created the person. The index has three seconds to answer, inside the five
craig-cases waits. A 409 person-index-refused means the index said no; a
503 means the call’s outcome is unknown, and its detail names the failure’s
class (partner-timeout, partner-status and the like).
Taking a partner’s calls (#3193 / ADR-091)
Some partners report back by calling CRAIG: the outcome of a referred application is the first. craig-exchange takes such a call on a listener of its own, apart from its API port, and only when the deployment says so (How the host runs a return). The jurisdiction’s partner set must hold a return leg for the interface; craig-exchange refuses to start on a consent it cannot serve.
A call is applied only when all of these hold; otherwise nothing is stored:
-
Consent:
CRAIG_EXCHANGERETURNS<INTERFACE>__ENABLED=true(default off, per interface). It is its own consent: agreeing to send a partner referrals does not agree to take its calls. With no interface consented no listener is bound. -
The listener:
CRAIG_EXCHANGERETURNSPORT, and three PEM files:CRAIG_EXCHANGERETURNSTLS_CERT_FILEand…TLS_KEY_FILE, the listener’s own certificate and key, andCRAIG_EXCHANGERETURNS__CLIENT_CA_FILE, the authorities whose client certificates may connect. Once an interface consents, a setting that is missing or a file that cannot be used stops craig-exchange at boot. The files are read once: renewing a certificate needs a restart. Expose the port to the partner only; it needs no ingress that ends TLS, since the service ends it and must see the client certificate itself. -
The partner’s certificate, registered: an administrator registers the partner’s client certificate against the partner in craig-security and approves it (
craig partner cert register,craig partner cert approve; the CLI). A certificate from a trusted authority that is not registered and approved is refused. Revoking it (craig partner cert revoke) refuses the partner’s next call, with no restart. -
The caller, bound to the interface: the interface’s partner row in craig-exchange names that craig-security partner as its caller (
PUT /v1/exchange/partners/{id}withcaller_partner_id). One caller has one active row per interface kind. -
An agreement: that partner row’s data-sharing agreement admits today.
-
craig-cases:
CRAIG_EXCHANGE__CASES_BASE_URLnames it; it stores each report on the application it is about.
What the partner is told: a refusal of the caller is a bare 403, whatever the reason, so the reason is not learned from outside; 503 means CRAIG could not decide or was applying another call, and the partner should call again. A call that was read is answered in the partner’s own wire, with what became of each report.
What a call leaves behind in craig-exchange: one exchange_transactions
row with origin return (the interface and leg, the counts, and
partner-certificate:<registration id> as initiated_by), and one
exchange.return_completed event. A call that was refused after the TLS
handshake leaves one exchange.return_refused event with the certificate’s
fingerprint and the class of the refusal; the audit log files both under
client-certificate:<fingerprint>. Nothing the partner reported is stored
in craig-exchange. A call refused at the handshake (no certificate, an
unknown authority, an expired certificate) leaves nothing: it never reached
the service’s code.
exchange_return_calls_total{outcome} counts every call that completed
the handshake by how it ended: completed or failed for a call that was
read and recorded, otherwise the class of its refusal (unknown-caller,
busy and the rest; the classes are listed with
the run). A rising
unknown-caller or not-callers-interface is a caller with a trusted
certificate that is not, or no longer, set up; lookup-unavailable,
store-unavailable and run-failed are CRAIG’s own failures.
/healthz lists the listener as the worker returns-listener: disabled
while no interface consents, and critical once one does, so a listener that
stops serving ends the process nonzero, naming the worker, for the
orchestrator to restart (Shutdown & fail-fast exit (#1186 / ADR-061)).
Outbound trigger rollout (#1828, #1835, #1829 / ADR-075)
An outbound TRIGGER turns a domain event into a partner send with no human
in the loop, so it is consented per interface and rolled out in a fixed
order. Nothing is sent until the last step, and nothing is lost before it:
every trigger that fires while the interface is unconsented records a
recoverable held(knob-off) row.
What a deployment can serve is fixed by the partner set its configuration
layer’s modules provide, and craig-exchange says so at start: one the
partner set of this deployment log line lists each interface with its dispatch class, its trigger
legs, its collections and its inquiry. A trigger row, a listed adapter or a
consent variable that the set cannot serve stops the service at boot,
naming it (What boot checks), so
compare the line with the configuration layer when a start is refused. The
SSA benefit screening has a source only when the configuration lists the
adapter of the interface that registers one; without it the staging route
answers 503 no SSA screening source is registered and jobs hold
contract-pending.
Per environment, in this order:
-
Deploy craig-cases first. The trigger legs assemble partner records from its outbound-principals projection (#1827); an exchange that cannot read it holds its records as
assembly-unavailableand retries. -
Apply the exchange migrations. All three bump
schema_compat_floorDELIBERATELY. A pre-#1828 exchange binary must refuse to start because it would claimresolve/recordjobs it cannot interpret; a pre-#1835 one because a catch-up admission carries no event id and its decode of that column would fail; a pre-#1829 one because the leg vocabulary is stage-qualified and it would find every admission unresolvable. Rollback is the newest release whose embedded max is at or above the floor (ADR-063 §D3). -
Roll every exchange replica, and verify through the orchestrator’s rollout status that no old replica remains. CRAIG exposes no build endpoint; the schema floor prevents an old replica from STARTING, not one already running from finishing its work.
-
Configure the partner. The interface must resolve to exactly ONE active
exchange_partnersrow of its adapter kind, carrying a data-sharing agreement that is owned by that partner,active, and inside both its effective and expiration dates. Anything else holds with a named reason (no-partner,partner-ambiguous,dsa-not-owned,dsa-expired, …). -
Catch up the stages that opened before the trigger existed.
cargo xtaskis not the tool here — this is a running-deployment act:craig-cli exchange trigger-catch-up --interface cprs --kind caseRun it once per stage KIND the interface serves — `--kind case` for the ongoing stage, `--kind investigation` for the `INV` one. It walks the cases open-stages projection and admits every open stage the admission ledger does not already cover, under a deployment-wide lease, recording a run row with its counts. It is IDEMPOTENT — a stage an event already admitted is counted, not re-admitted — so running it twice is indistinguishable from running it once, and re-running is also how you finish a walk that hit its page cap. This step serves two purposes at once: the catalogue's own initial pre-population of open stages at release, and the repair for any event an older binary consumed during step 3. . *Consent.* `CRAIG_EXCHANGE__TRIGGERS__<INTERFACE>__ENABLED=true` (default off, per interface). From here the interface sends. The variable must name an interface the deployment's partner set has a trigger leg for: craig-exchange refuses to start on one it cannot serve (a misspelling, or a partner the configuration layer's modules do not hold), set either way, naming the variable. The same holds for `CRAIG_EXCHANGE__COLLECTIONS__<INTERFACE>__ENABLED` and collections, and for `CRAIG_EXCHANGE__PERSON_INDEX__<INTERFACE>__ENABLED` and the partner set's person index. . *Drain the backlog raised before consent.* Everything held while the knob was off is still recorded:
craig-cli exchange trigger-release --interface cprsThe act re-runs the consent chain over each held row: whatever now admits becomes a staged resolve, whatever still refuses is re-held with the reason AS IT STANDS TODAY. One pass addresses at most 500 admissions, oldest first — the response counts say whether there is more, and the act is idempotent, so "run it again" is the whole continuation protocol. An interface this deployment declares no leg for is refused rather than answered with a pass that touched nothing. An occurrence that will never be sent is retired instead, terminally and with a reason:
craig-cli exchange trigger-dismiss --interface cprs --id <admission-id> \ --reason "stage predates the partner agreement"
DOE-SLDS custody list (#1821, plan custody-episodes-doe-slds D7)
The DOE-SLDS legs follow the procedure above with these values and these differences. They send a child to DOE when the child is in DFCS custody AND holds a live GTID, whichever fact is recorded second (INC); leaving custody or a corrected close sends OUC; the GTID’s end or retraction, or the episode’s retraction, sends RMV.
-
craig-cases first: every replica on #2343 or later (the custody projection). An exchange that reads an older cases image gets 404 on every custody read and settles the record
assembly-refused(not retried). -
The exchange migration adds
exchange_outbound_recipients.subject_identifier_id(the GTID row a recipient was listed under, an id, never the GTID) and BUMPSschema_compat_floor: an exchange binary older than #1821 refuses to start on this schema, and exchange cannot roll back below #1821 once it has run. Roll every replica and confirm none older remains: an older replica still running settles a DOE job naming a leg it lacks as terminalunresolvable-dispatch. -
The partner: exactly one active
exchange_partnersrow withadapter_kind = doe_slds, carrying an admitting agreement. Its credential, if it needs one, is provisioned as Outbound partner authentication (#1813 / ADR-083) describes. -
Catch up the episodes opened before admissions were recorded, once:
craig-cli exchange trigger-catch-up --interface doe_slds --kind custody_episodeIt walks the open episodes whose child holds a live GTID; a GTID recorded later admits through its own event. . *Consent:* `CRAIG_EXCHANGE__TRIGGERS__DOE_SLDS__ENABLED=true` (default off; one knob gates all six legs). Then release what was held:
craig-cli exchange trigger-release --interface doe_slds
Two DOE-only outcomes appear in the ledgers. An INC that finds the
child’s previous episode not yet removed at DOE waits (retryable class
predecessor-unsettled); if it runs out of attempts it is held as
predecessor-unsettled, and the transaction that stages that removal
releases it. If you DISMISS that removal instead, release the INC
yourself:
craig-cli exchange trigger-release --interface doe_slds \
--held-reason predecessor-unsettled
An INC, an episode retraction or a corrected close for an episode older
than the one DOE now lists is dismissed superseded-by-reentry and sends
nothing (a GTID end is never skipped). The brake for staged DOE jobs is
to deactivate the DOE partner row or its agreement (each later record
settles partner-changed); no pause exists (#2348). The knob off holds
new admissions only. The stored DOE acknowledgement keeps
transaction_id, status and received_at, never the GTID.
Collecting DOE’s weekly student data (#3188)
DOE reports each listed child’s school in its weekly student file. Reading it is a separate consent from the sends above, and a separate act:
-
Consent:
CRAIG_EXCHANGECOLLECTIONSDOE_SLDS__ENABLED=true(default off). Until it is set a run is refused 409collection-disabledand nothing is enqueued or fetched. -
The owner:
CRAIG_EXCHANGE__PLACEMENT_BASE_URLnames craig-placement, which stores each reported record. craig-exchange stores none of them. -
Run it, as a human admin on their own bearer (a service identity and a worker relayed through craig-web are refused):
craig-cli exchange collection-run --interface doe_slds --leg weekly_records
A run fetches the partner’s file from the DOE partner row’s endpoint with
that row’s credential, and admits a record only for a child this deployment
currently lists with DOE. The run’s counts say what became of the file’s
records: applied, stale (craig-placement already held this report or a
later one), not_listed (dropped: no open listing, or one that ended while
the report was on its way), unattributable (the record named no CRAIG
person) and failed.
A run is a background job (#3190). POST /v1/exchange/collections/run
takes \{ client_request_id, interface, leg }, enqueues a collection_run
job and answers 202 with the job and Location: /v1/exchange/jobs/{id}.
craig-exchange’s job executor runs it, and the caller polls the job; the CLI
does both. A file of any size is collected: the run posts one report at a
time and no request waits for it. What the job’s end means:
| The job | What happened |
|---|---|
|
A run was recorded. The job’s |
|
The run did not start: DOE was not called and nothing is recorded.
|
|
Three attempts in a row were interrupted by a shutdown or lost their replica. Each interrupted attempt recorded its own failed run. Run again. |
|
A database or event-staging error; the detail names which, and the log holds the error. |
One run at a time per deployment: a second enqueue while a run is queued or
running is refused 409 job-already-active, and a job that finds another
replica’s run holding the collection lease waits for it (progress.phase is
waiting_for_lease) rather than fail. While a run posts, the job’s
progress counts the reports posted (done of total).
Shutdown. A run told to stop (a rollout, a scale-down) stops between two
reports, or leaves the fetch or the post it is waiting on, and is recorded as
a failed run with the class interrupted and the counts by then. The job is
queued again and the next attempt posts every report again: craig-placement
answers stale for those it already holds. Nothing is lost and nothing is
applied twice.
On a schedule. CRAIG_EXCHANGECOLLECTION_SCHEDULEINTERVAL_SECONDS
(default 0: no schedule) makes craig-exchange collect by itself: for a
weekly file, 604800. The collection-schedule worker looks once a minute,
or once an interval when that is shorter, at every collection the deployment
has consented to, and runs each that is due:
-
A collection is due when it has never been run, or when its newest counted run started at least the interval ago. An operator’s run counts, so a collection run by hand is not run again until an interval later, and a restarted service or a second replica does not fetch a file that was just collected.
-
A failed run counts too: a partner that is down is asked once an interval, not once a minute. Run the collection by hand once the cause is fixed.
-
A run a shutdown interrupted does not count. It is recorded as a failed run (
interrupted), and the first look after the restart runs the collection again. -
A run refused before the partner was called (no usable partner, an agreement that does not admit) leaves no record and is tried again at every look; the worker logs the refusal when it starts, not at every look.
A scheduled run is the system’s: its transaction’s initiated_by is
system, its exchange.collection_completed event carries no user_id, and
its audit record names the system as the actor. It takes turns with an
operator’s job on the collection lease: a job waits for a scheduled run, and
a look that finds a job running leaves the collection to it.
The worker’s heartbeat (worker_last_success_timestamp_seconds{worker="collection-schedule"})
is recorded on a look only when every consented collection is in good
standing: a run the look made completed, and a collection it left alone has
no failed run as its newest counted one (a collection never run yet is in
good standing). A run that failed, was refused or was interrupted withholds
it. A failed run therefore withholds it until a run of that collection
succeeds, the next scheduled one or an operator’s, and the staleness alert of
Worker functional-health alerting fires meanwhile.
With no interval set the worker is listed disabled on /readyz.
Rolling this release. The run route’s body and answer changed with the
release that carries #3190: a script that posts the old body \{ interface,
leg } is refused 422, and a 202 must be polled. craig-exchange’s migration
(the two job tables and two indexes) is additive, so replicas of both
versions can serve the schema during the roll; a run enqueued on a new
replica is executed by a new replica.
Order per environment, for the release that carries craig-placement’s partner-report route:
-
Bootstrap the authz family first.
craig rules bootstrap target/config/layers/georgia/georgia-authz-education_partner_report.json --profile <env>(and each other active jurisdiction’s file) as a humanadmin, before the first image. Every engine-bearing service enumerates all resource types at boot, soEducationPartnerReportreads as a coverage gap fleet-wide until the file is live: a boot bail whereverAUTHZ_REQUIRE_FULL_COVERAGE=true, and elsewhere every read of a partner report is refused. The devstack needs no bootstrap. -
Roll craig-placement and craig-exchange together. The report body changed (it names its listing, and carries no idempotency key). Across a mixed pair every admitted report counts
faileduntil both are new; a rerun then applies them. craig-placement’s migration is additive.
craig-placement keeps one report per child, readable by an admin and by the
caseworker and supervisor of the child’s case (the jurisdiction’s
education_partner_report ruleset), and by nobody else. It drops the report
when craig-exchange stops listing the child with DOE: custody closed, or the
child’s GTID ended. That reaches craig-placement as the event
exchange.listing_ended on its events queue. A dead letter of that key from
craig-placement.events means a report is still readable for a child who
has left DOE’s list, so it is one to act on
(DLQ alerting recommendations).
Each run that called DOE leaves one transaction (origin collection,
direction inbound, no payload) and one exchange.collection_completed
event. A run whose status is failed posted some reports and not others;
run it again, since a report already stored is answered stale or replaced
by the same facts. A run stops posting once three posts in a row say
craig-placement is not taking reports (no answer, a server error, a refused
identity) and counts the rest failed, so a craig-placement that is down
ends the run, recorded, in seconds, and does not hold the collection lease
for the length of the file. A collection transaction cannot be retried from
the transactions list: run the collection again.
Caregiver ledger + portal enrollment rollout (#1848 / ADR-076)
Order per environment: craig rules bootstrap the two new families for EVERY active jurisdiction
({j}-authz-foster_home_caregiver, {j}-authz-foster_portal) BEFORE the post-U6 craig-placement image
(until then every service boots with a coverage warning for the two resource types and the ledger routes
answer 403); then the placement image (the migration is additive — no floor bump); then the two knobs on
craig-placement — CRAIG_PLACEMENTSUBJECT_CLIENTS=craig-portal-ui and
CRAIG_PLACEMENTPORTAL_PATHS=/v1/placement/portal/ (empty = the enrollment act answers 401/403 to every
portal request). CRAIG_PLACEMENTENROLLMENT_RATE_LIMIT_RPM defaults to 5 per client IP AND per subject per
minute; the per-IP bucket sees the caregiver’s browser only when the portal BFF’s CIDR is in
CRAIG_PLACEMENTTRUSTED_PROXIES — otherwise every portal caregiver shares the BFF’s ONE address bucket, which
trips at 5 enrollments a minute for the whole fleet (the per-subject bucket never gets to bound anything). List
the BFF’s CIDR before the first invitations go out. The #1847 {j}-authz-person 1.2.0 fixtures must be live on
craig-cases first: a caregiver create verifies the person through the display-name arm and answers a named
500 (not the retryable 503) when cases refuses the read. Likewise the #1850 {j}-authz-worker_identity 1.2.0
fixtures must be live on craig-security (rules promote — an existing family) before the post-U8 placement
image: until then the portal unit projection answers names_unavailable for caseworker names. Superseded: since #1857
the portal reads caseworker names through the worker_identity contact row, and #2525 retired the 1.2.0
display-name row with its route, so a new environment promotes the current {j}-authz-worker_identity fixture
(georgia 1.5.0, texas 1.6.0); the 1.2.0 steps in this section are history.
U8 (#1851) additions. Promote BOTH {j}-authz-foster_home_caregiver 1.1.0 (craig-financial’s scoped
caregiver_bindings service row) and {j}-authz-worker_identity 1.2.0 BEFORE the post-U8 placement image —
existing families, rules promote. Set CRAIG_PLACEMENTSECURITY_BASE_URL (default http://localhost:8007; the
devstack compose sets http://craig-security:8007; since #1903 the leaf is the shared security_base_url every
engine-bearing service reads for the admin-units snapshot — § Admin-unit scoping rollout, step 6 — with the env name
unchanged): the worker name read (the #1857 contact read today) runs on placement’s OWN principal
under a 4 s budget and DEGRADES (caseworker_name: null, names_unavailable: true) rather than refusing, so a wrong
URL costs caseworker names on the portal, never the portal itself; a 403 logs the missing-row remedy
(today it names the #1857 revision). The
portal projections (GET /v1/placement/portal/units… and the training-certificate upload) need the post-U8 image
plus the two U6 knobs above — CRAIG_PLACEMENTPORTAL_PATHS=/v1/placement/portal/ and
CRAIG_PLACEMENT__SUBJECT_CLIENTS=craig-portal-ui (the issue text’s craig-portal value is stale: that is the channel
ROLE, not the public client). The internal read GET /v1/placement/internal/caregiver-bindings sits OUTSIDE
PORTAL_PATHS by design; its consumer is U9 (#1852).
U9 (#1852) additions. Financial is the second service on the channel: set
CRAIG_FINANCIALSUBJECT_CLIENTS=craig-portal-ui and CRAIG_FINANCIALPORTAL_PATHS=/v1/financial/portal/ (empty =
every portal request answers 401/403, the no-portal posture) and make sure CRAIG_FINANCIAL__PLACEMENT_BASE_URL
reaches craig-placement — the portal payments projection (GET /v1/financial/portal/units/{unit}/payments) resolves
the caregiver’s units against GET /v1/placement/internal/caregiver-bindings?sub= on financial’s OWN principal on
EVERY request (no projection, no cache; 4 s budget) and, unlike the U8 name arms above, FAILS CLOSED: placement not
answering is the typed 503 portal-bindings-unavailable, never a degraded page; a placement 403 is the missing
{j}-authz-foster_home_caregiver 1.1.0 row (promote it per the U8 paragraph BEFORE the post-U9 financial image) and
answers a named 500 carrying that remedy. The financial migration (idx_subsidy_agreement_parties_person) is
additive — no floor bump. Then the caregiver hard check, in THIS order per environment (plan portals decision 11):
-
Enter the caregivers (U7, the staff caregivers panel) for every active home and kinship placement.
-
Measure the gap —
craig-manage caregiver-coverage [--as-of YYYY-MM-DD] [--jurisdiction <j>]counts the ACTIVE placements whose unit has NO current caregiver binding, per jurisdiction / county / unit kind (bucket counts, not placement ids) (--strictexits non-zero on any gap). Name the placement database with--database-urlorCRAIG_PLACEMENTDATABASE_URL(there is no default) and the cases database with--cases-database-urlorCRAIG_CASESDATABASE_URL. Repeat until the residual gaps are understood — every gap is an enrollment the check will refuse. -
Issue invitations (the U6 enrollment act) — the portal payments route serves a caregiver only once a binding exists.
-
Enable — set
CRAIG_FINANCIALSUBSIDY_CAREGIVER_CHECKENABLED=trueon craig-financial and restart. Until then the knob is REPORT-ONLY, not inert: both boundaries (ERR create-active on the ENROLLMENT date; SG/NRSG activation on the TRANSFER date) already evaluate every party and logcaregiver_check_would_refuse+ countsubsidy_caregiver_check_total{boundary,outcome="would_refuse"}— watch that series reach zero on real traffic before flipping; after the flip the same misses areoutcome="refused": typed 400subsidy-party-not-caregivernamingparties[i], the person and the date, zero rows written. Anoutcome="facts_unavailable"series means a craig-placement that predates #1851 (roll placement first — knob ON, that read is a 503 at both boundaries). -
Disable — set the knob back to false and restart; writes resume unchanged and the counter keeps reporting
would_refuse. VERIFY the report-only posture: an enrollment naming a non-caregiver party must succeed with the warn line, not the 400. Nothing else consults the knob either way — create-pending SG/NRSG, theguardianship_finalizedwitness and every existing-agreement lifecycle path are unaffected.
U11 (#634) additions. Placement becomes the first ADR-037 §4–§7 tenant (surface foster_home_portal) AND a state-bundle
consumer, so the order per environment matters: (1) ship the jurisdiction layer’s field_ownership.toml for EVERY
active jurisdiction — georgia and texas ship identical maps; until U4 (#2955) the file rode the placement image under
/app/rulesets/ (a custom CRAIG_PLACEMENTRULESETS_DIR had to point at a root holding
<jurisdiction>/field_ownership.toml), and since U4 placement reads it from the layer CRAIG_CONFIG_SOURCE names — and
rules promote the eight field-permission families for BOTH jurisdictions, {j}-authz-placement (georgia 1.4.0, texas
1.5.0) and {j}-authz-education_record / health_record / foster_home (1.2.0), existing families, BEFORE the post-U11
placement image: the new image evaluates resolve_field_permission on every staff write of a governed field, and an
un-promoted family answers none — a 403 field-permission-denied on every governed PUT and create. (2) Set
CRAIG_CONFIG_SOURCE on craig-placement (the devstack compose supplies the georgia layers):
placement REFUSES boot without it and on any field-owner-map
fault (the message names file, surface and field); the migrate container does not need it, so the gate still runs first.
(3) Roll the placement image (the pending_edits_foster_home_portal migration is additive — no floor bump), then craig-web
(the Studio queue) and craig-portal (CRAIG_PORTALPROPOSAL_RATE_LIMIT_RPM, default 30, the third HTML-shaped limiter).
Approver note: acceptance is Action::Approve on the TARGET row’s own type under the SHIPPED rows — Georgia admin
supervisor; Texas admin + an IN-UNIT regional_director (#1904 — the fused foster_home CHECK row is action-wildcard on
i_unit_match, so the home’s attrs.admin_unit decides), while a Texas plain supervisor (whose approve row is
i_supervises-gated and inert on these refs) is denied accept and sees an empty pending list — today’s Texas update
posture, no new approve rows. The Studio "Pending changes" view (/studio/pending-changes) and its nav-pending-changes
item are gated on the realm roles admin / supervisor (FIELD_APPROVER_ROLES), and the array stays
{admin, supervisor} (ruled 2026-10-06, #1927; ADR-037): the in-unit regional_director the Texas ruleset admits at
the placement API accepts through POST /v1/placement/field-proposals/{id}/accept, the API-only path, not the view.
craig-portal (caregiver portal BFF)
The portal is its own public host (plan portals U5, ADR-076 D6): it serves caregivers, never staff, and
reaches only craig-placement and craig-financial — with the caregiver’s own IdP token relayed in
X-Craig-Subject under the portal’s service bearer. Publish it on a hostname distinct from craig-web’s
(cookies are portal_*, the CSP is the strict BFF policy, and the fleet guard refuses any portal-role
bearer that bypasses it). The confidential craig-portal client’s secret must equal the realm’s; the
portal ships NO actor signing key by design (CRAIG_PORTAL__SIGNING_JWK does not exist).
| Variable | Default | Description |
|---|---|---|
|
required ( |
HTTP listen port |
|
required |
The OIDC issuer as the browser reaches it |
|
unset |
In-network issuer URL for discovery / token calls (split DNS) |
|
required ( |
The PUBLIC code + PKCE client the caregiver’s browser authenticates against |
|
required |
This host’s |
|
required |
The two backends the portal reads (dedicated |
|
required (≥ 64 bytes) |
Private / signed cookie key material |
|
required |
The confidential |
|
|
How the login access token is validated (#2686): |
|
|
|
|
|
Session cookie |
|
|
Locale when neither the session tier nor the request negotiates one ( |
|
|
Per-client-IP |
|
|
Per-client-IP |
|
|
Per-client-IP certificate-upload POSTs per minute (U10); a refusal is a flash + 303 back to the documents page;
|
|
|
Whole-body cap on the certificate upload route only (U10) — the EFFECTIVE cap a caregiver meets (placement’s per-file 50 MiB sits above); the form says 10 MB; an over-limit body is the "too big, or the upload stopped" flash, never a 413. See Upload limits |
|
unset |
Comma-separated CIDRs whose |
|
required / |
Header branding |
U10 (#1853) additions — the pages. Every protected response and the signed-in /welcome (the connect page)
carry Cache-Control: no-store. The session cookie’s Max-Age (1800 s) is the 30-minute idle limit, and the
realm SSO session outlives it (the committed realm: SSO idle 3600 s against the craig-portal-ui client’s
1800 s), so after 30 idle minutes the next request is routed through /login and is usually a silent SSO
re-entry — the sign-in form appears only once the IdP session has lapsed too; any refresh failure drops the
session. A backend 403 (no current binding, a revoked identity) does NOT end the session — /units renders the
not-connected state with the enrol form and every other page redirects there with a neutral flash (ADR-076 U10
note). Rate limiting: the portal’s three per-IP limiters and placement’s enrollment quota key on the caregiver’s
IP only when each service’s trusted-proxy list names the hop in front of it — list the ingress CIDR in
CRAIG_PORTALTRUSTED_PROXIES and the portal’s CIDR in CRAIG_PLACEMENTTRUSTED_PROXIES before the first
invitations go out (the rule the rollout section above states for placement). The certificate upload’s
effective cap is CRAIG_PORTAL__UPLOAD_BODY_LIMIT (see Upload limits). The caregiver-facing walkthrough is
the Caregiver Portal Guide.
Watching it
exchange_trigger_admissions_total{interface,leg,status} counts every
occurrence the matrix admitted; exchange_trigger_held_total{interface,reason}
is the recoverable backlog and should drain to zero once the reason above is
fixed; exchange_trigger_dispatch_total{interface,kind,outcome} is the
worker’s verdict per job. A held row is not an error — it is work waiting
for a decision, and the release act is how the decision is applied.
exchange_trigger_catchup_runs is the durable record of each walk: who ran
it, what it scanned, what it created, and whether it completed. A run left
running is one whose process died mid-walk; its admissions are real and
the next run picks up what it missed.
A stage closing sends one record per recipient the OUTBOUND ledger still carries, with no age re-filter — a child who turned 18 in care is still told the stage closed. The opening record and the closure record are two separate sends, in that order (they share the stage’s FIFO key), and which of the two a job is was decided when it was staged, not when it dispatches.
An investigation principal who is UNLINKED from the report is retired and
the partner is not called: the catalogue’s rule is that a removed entry
receives no further updates, not that it receives a final one. The ongoing
stage has no removal event to bind, so its recipients are only retired when
a closure finds them gone from the household. A recipient the projection no longer carries at closure is
retired (exchange_outbound_recipients.removed_at) and receives nothing:
CRAIG has no household-removal event for the ongoing stage, so absence at
closure is the only evidence there is.
What a failure looks like
Failures are CATEGORICAL by design: exchange_send_jobs.last_error and the
exchange.failed event carry class[:code] digest=…, never the partner’s
response body (which can echo a child’s name). Correlate two occurrences by
their digest; read the partner’s own logs for the text.
Before production
Sending to a real partner additionally needs the protocol agreed and
outbound authentication implemented. The catalogued CPRS interface is a
SOAP/XML pull against a SHINES-side table, while the shipped adapter pushes
JSON; exchange_partners.auth_config is written but never read. Both are
tracked, and the devstack mock proves only the CRAIG side of the exchange.
Administrative-authority bootstrap (#1786 / ADR-074)
The administrative-authority program (plan administrative-authority, epic &86;
ADR-074) moves the subsidy office hierarchy and every
per-action approval floor out of Rust and into ONE ruleset family per jurisdiction,
{j}-administrative-authority (Rule Set Patterns and Domain Knowledge § metadata.authority). U1 (#1786) ships the CONTENT and
the tooling only — no service consults it yet; U2 (#1787) ships the craig-financial image that resolves every
human approval act through it and answers 503 SUBSIDY_AUTHORITY_NOT_READY until the family is live in
craig-rules. The order per environment is therefore fixed:
-
Bootstrap the family on craig-rules BEFORE any financial image that consults it.
rules promotetargets an EXISTING set, so the first load is the one-timecraig rules bootstrap target/config/layers/georgia/georgia-administrative-authority.json --profile <env> [--bearer-token …]as a humanadmin(signed in withcraig login --deviceotherwise; service principals are deniedrule_set: create). Repeat for every jurisdiction the deployment activates. The command is idempotent: an existing row is reported with its revision and nothing is created. The devstack needs no bootstrap —seed.shloads every top-level.jsonof each config layer (rulesets/<j>/.jsonuntil U4). -
Verify by name.
GET /v1/rules/sets/by-name/georgia-administrative-authorityanswers the row (by-name resolves ACTIVE rows only; a soft-deleted same-name row makes the bootstrap’s create a 409 — restore it, never recreate). -
Later versions ride the two-step promote. Run
cargo xtask authority-evidence <candidate.json> target/config/layers/<j>/evidence/administrative-authority.tomlfirst: it replays every evidence key through the engine against the candidate and printsauthority-evidence:<sha256>. The in-process family never populatesrule_evaluations, so its canary is thin by construction;craig rules promote … --acknowledged-thin-corpusrefuses the family unless--reasonquotes that digest (ADR-074 decision 13). The command knows the family by the document’sname, whatever the candidate file is called, and recomputes the digest from the candidate and theevidence/administrative-authority.tomlin the candidate’s own directory, so keep the two together. -
Then deploy the consuming financial image (U2 onward) and watch its
authority_surface_verified{jurisdiction}gauge read1(theauthority-surface-verifierCritical worker re-verifies every 60 s; a stuck0after boot is the alert). Until it does, every human approval act answers 503 and writes nothing; consentedsystemautomation keeps running.
What the operator lives with afterwards:
-
A hierarchy or floor change is a ruleset PROMOTION (with the evidence digest), never a source change or a configuration flag; the approval row persists the
rule_set_id+revisionthat authorized it (U2). -
A jurisdiction with two tiers declares two entries; a session holding only an undeclared office role holds no office there and is refused with the existing office message. A fourth tier is a fleet contract change (#1791), not a declaration.
Admin-unit scoping rollout (#1086 / ADR-077)
The admin-unit scoping program (plan admin-unit-scoping, epic &95;
ADR-077 D8) landed in ordered units, every one merged; the seven
steps below stay the per-environment ORDER — each names the image and the ruleset act it needs, and the gate
between them is a manifest DERIVED from the tree, never a literal file count. Steps 1–3 landed with U1a / U1b
(#1899 / #1900), step 4 with U3a (#1901), step 5 with U3b (#1902), step 6 with U2 (#1903) and step 7 — the promote
of every Texas file rules drift reports behind, over the verified snapshot — with U4 (#1904). Nothing
product-side ships with step 7: the rows are data.
-
Deploy the craig-security image carrying U1a, then bootstrap the NEW family.
{j}-authz-worker_admin_unitis a family no environment has —rules promotebails on its by-name 404, so the first load is the one-timecraig rules bootstrap target/config/layers/georgia/georgia-authz-worker_admin_unit.json --profile <env> [--bearer-token …]and the same fortarget/config/layers/texas/texas-authz-worker_admin_unit.json(×2: every jurisdiction the deployment activates), as a humanadmin(signed in withcraig login --deviceorcraig loginon that profile otherwise). Until the family is live, the registry routes answer 403 (the engine is fail-closed on an absent policy) and every service that boots an authz engine reports a coverage warning naming theworker_admin_unitruleset. -
Deploy the image carrying U1b, then PROMOTE
{j}-authz-worker_identityto 1.3.0. The family exists in every environment (1.2.0 since #1850), so this is the two-step promote —craig rules promote target/config/layers/georgia/georgia-authz-worker_identity.json --reason '…', read the canary report, re-run with--confirm-preview <id>; the same fortarget/config/layers/texas/texas-authz-worker_identity.json(×2). The 1.3.0 row admits ANY service principal — and only a service principal — to the U1b snapshot projection (GET /v1/security/worker-identities/admin-units?jurisdiction=;claims.is_service && resource.attrs.projection == 'admin_units', service id wildcarded): until the row is live that route answers 403 to a service caller. It is the read every engine-bearing service performs from U2 on; nothing consumes it before then, and the #1850 display-name row is untouched. -
Gate:
craig rules drift --rulesets target/config/layers --strict --profile <env> [--bearer-token …]green. The command walks exactly the file setcargo xtask rules checkcompiles and classifies each against the live service:absent(no active row by that name →rules bootstrap),behind(the live version differs and is not newer than the file’s: older, the same number spelled differently, or unorderable; OR the same version with drifted canonical content —serde_json::Valueequality of the whole document, key order and whitespace irrelevant →rules promote),ahead(#1920 — the live version is strictly newer than the file’s: an environment promoted from a later branch, or a hot-fix promoted ahead of the commit → bring the tree up to the live row, by rebasing onto the commit that carries it or committing the live content to the file; never a promote, which would regress it) orcurrent. Versions order numerically, component by component, over semver1.3.0and the seed’sv1.0default (a missing component reads as 0); a pair with a side of any other shape (a pre-release suffix, say) is never ordered and readsbehind. It prints one line per file with the remedy and a summary whose every count is derived from the walk.--strictexits non-zero after the table when any file is absent, behind or ahead;testoniafiles print asfixture(the #1621 marker — never seeded, outside the verdict), and a lookup transport error aborts naming the file rather than reading it as absent. After steps 1–2 the two newworker_admin_unitfiles and the two 1.3.0worker_identityfiles readcurrent; anything else the command reports behind or ahead is pre-existing drift in that environment, and the remedy on its line is the act. -
(U3a, #1901) Deploy the craig-cases image FIRST, then placement and financial with their migrations, then the backfill. The cases image adds the OPTIONAL
admin_unitkey tocase.assignment_changed(ADR-077 D6); the placement and financial images read it when present and apply a retained six-key envelope unchanged, so cases-first is safe whichever side drains first. Then run the two20260916140000_admin_unit_stampmigrations through the ADR-063 gate (additive — nullableadmin_unitcolumns with partial indexes, noschema_compat_floorbump) and roll every placement / financial replica; the cases20260916140000_investigation_admin_unitmigration backfillsinvestigations.admin_unitfromreferralsby itself (total). Finallycraig-manage backfill-assignments --yesonce per environment, with the four service databases named (CLI § craig-manage; without--yesit prints its targets and stops): after the revision-guarded pair legs it runs a revision-independent unit-fill pass (bothcase_assignmentsprojections, then placements, kinship_options, subsidy_agreements, payments, payment_adjustments via the payments JOIN) and printsunits filledper table; an ordinary re-run fills the units that retained pre-upgrade envelopes left NULL — there is no flag. Nothing consults the stamps for authorization until the U4 rows land over a verified snapshot; a NULL stamp is outside every unit scope by construction. The backfill is safe beside the running services, the subsidy generator included (#2417): every statement autocommits and touches one table, except the twosubsidy_agreementsstatements, which run in one craig-financial transaction per case that first takes the pay-exclusion lock of every child with an agreement on the case (child id ascending), then the per-case assignment lock, and only then the agreement rows — craig-financial’s own order for a writer of several children’s agreements, so the tool waits for a generator pass on one of those children instead of deadlocking with it. If a child’s first agreement on a case commits while the tool waits for that case’s lock, the run stops withagreement child … appeared behind the backfill’s child locks, that case’s agreements unwritten; run it again. -
(U3b, #1902) Roll the craig-cases, craig-placement and craig-financial images carrying the check census — images only, no migration, any order. Every
authz.checkon the ten unit-bearing types now carriesattrs.admin_unitfrom the row through the type’s one builder fetched BEFORE the check (ADR-077 D5); no shipped ruleset row reads the attribute, so authorization is unchanged until the U4 rows land. The one observable change is the existence-first order on the reordered routes: a missing row answers 404 BEFORE any 403 for an unauthorized caller (theget_paymentshape) on the thirteen handler paths the CHANGELOG lists, and a field proposal whose foster-home row is gone answers 404foster homeon accept and reject. -
(U2, #1903) Set
CRAIG_<SVC>SECURITY_BASE_URLon the seven HTTP consumers (craig-security reads its own table), roll the eight engine images (any order), then GATE on the gauge. Every service that boots the shared authz engine — all eight — now installs craig-security’s admin-units snapshot: the seven HTTP consumers, craig-rules included (its first outbound inter-service HTTP edge), on their OWN principal, craig-security from its own table (ADR-077 D4):craig_bootstrap::admin_units::SecurityUnitsSourcereadsGET /v1/security/worker-identities/admin-units ?jurisdiction=under one 4 s budget at boot, every 60 s once verified (2 s doubling to 60 s after a failed pass) and on everysecurity.worker_admin_unit.*event (a per-instance exclusive queue<svc>.authz-cache.units.{uuid}— inside every service’s existingauthz-cachebroker ACL, so no credential changes), and installs a snapshot only when itsregistry_generationexceeds the held one (equal re-confirms, lower is refused with a warning). The leaf is the sharedsecurity_base_url— lifted from the placement extension by #1903, env names unchanged (CRAIG_PLACEMENTSECURITY_BASE_URLincluded); the devstack compose setshttp://craig-security:8007on the seven, and a container left on thehttp://localhost:8007default readsunreachable. Two Critical workers per service join the manifest,admin-units-verifier
admin-units-invalidation(a dead LOOP fails/readyz; a failed VERIFY never exits — readiness is NOT gated on the verdict). The gate:admin_units_snapshot_verified{jurisdiction} = 1on every engine-bearing service (theauthority_surface_verifiedshape) BEFORE any ruleset that consultsclaims.admin_unitsis promoted —/readyzis deliberately not the signal. A0with an error-level log namingrules promoteis step 2 undone in that environment (the 1.3.0 row is missing → 403 →forbidden); a0withunreachableis the URL or the network. Until the gauge reads 1 a consulting ruleset answers 503ADMIN_UNITS_UNAVAILABLEwith the closed reason asdetail(pending/stale/unreachable/forbidden/malformed/unconfigured) — never an empty unit list; no ruleset consults units until step 7 promotes the #1904 Texas rows, so this step changes nothing observable but the workers, the gauge and the leaf — and the gauge reading1is step 7’s precondition.CRAIG_<SVC>ADMIN_UNITSMAX_AGE_SECS(default 300, at least 1) bounds a snapshot’s age: older answersstaleuntil the next verified pass. -
(U4, #1904) Promote every Texas file
rules driftreports behind — the unit-scopedregional_directorrows (ADR-077 D7) — file by file, over the verified gauge. Precondition:admin_units_snapshot_verified{jurisdiction="texas"} = 1on EVERY engine-bearing service of the environment (step 6). Promoting a consulting file before the gauge reads 1 makes EVERY human evaluation of that resource type answer 503ADMIN_UNITS_UNAVAILABLE— admin included; only bare service principals short-circuit the consult. A Georgia-only deployment promotes nothing here: its files readcurrent, and no Georgia row consults units. Then: (i)craig rules drift --rulesets target/config/layers --strict --profile <env> [--bearer-token …]lists every re-authored Texas file asbehind(a version bump AND drifted canonical content on each — every edited file bumped one minor because craig-rules refuses a LIVE version string with different content); that manifest IS the promotion list, never a literal count. Two of them are RE-promotes of rows already live —texas-authz-worker_identity(the step-2 #1900 projection row,currentat the step-3 gate) andtexas-authz-rule_evaluation(the #1624 director rows), each 1.3.0 → 1.4.0 with the retired input dropped and those rows unchanged — soworker_identityreadingbehindagain after the step-3 gate is expected, not a regression. A file readingahead(#1920) is never on that list — the loop’s$1 == "behind"skips it — and is reconciled in the tree, not promoted. (ii) Per file, the two-step promote —rules promotetakes ONE positional file (a manifest-driven multi-file form is #1930):craig rules promote <path> --reason '#1904 unit-scoped regional_director rows' --profile … [--bearer-token …]renders the canary report and prints the execute line (since #1935 the preview is a 202 background job — the command pollsGET /v1/rules/jobs/{id}every 2 s until the report is ready; a 401 mid-poll re-runs the device-code grant once and resumes the SAME job, while under--bearer-tokenit exits non-zero printing the job id andcraig job wait rules <id>); read the report, then run the printed line, which carries--confirm-preview <id>AND--acknowledged-thin-corpus— every-authz-promote is thin-corpus by construction (the canary corpus isrule_evaluations, and in-process authz evaluations never write one, so the count sits under the evidence floor); the drift table’s remedy line omits that flag (#1930 as well) — state it once and expect it on every execute. Engines refresh onruleset.changed.<name>— no restart. A loop over the manifest, the execute still a read-then-run per file:# the drift table prints each path as ./target/config/layers/texas/… (./rulesets/texas/… until U4) craig rules drift --rulesets target/config/layers --profile "$CRAIG_PROFILE" --bearer-token "$TOKEN" \ | awk '$1 == "behind" && $2 ~ /(^|\/)layers\/texas\/texas-authz-/ { print $2 }' \ | while read -r f; do craig rules promote "$f" --reason '#1904 unit-scoped regional_director rows' \ --profile "$CRAIG_PROFILE" --bearer-token "$TOKEN" # read the canary report, then run the printed execute line for THIS file: # craig rules promote "$f" --reason '…' --confirm-preview <id> --acknowledged-thin-corpus \ # --profile "$CRAIG_PROFILE" --bearer-token "$TOKEN" done(iii)
craig rules drift --rulesets target/config/layers --strict …green. The devstack needs no promote:cargo xtask dev reseed—seed.shconverges every fixture to its(name, version)(aPUTunderIf-Matchon the bump). Observable flips to record: aregional_directorbound to units gains in-unit reads on the ten unit-bearing types (and the in-unit writes the supervisor shape admits — foster_home field writes and proposal accept); on the four types whose Texas supervisor row isi_supervises-dead (report, referral, investigation, foster_home) that is a read a Texas supervisor never had; a supervisor + regional_director dual holder’s LIST becomes the unit scope (rita: supervised rows → Harris + Travis rows) while both CHECK reads stay; an unbound regional gets empty pages and 403 by id; NULL stamps (case-less agreements / payments, imports) stay outside every regional read; a session carrying the retiredi_regionalrole token loses the dead rows and gains nothing (no realm role ever carried it). Rollback = re-promote the prior file versions from git through the same two-step (a different version string is never the live-reuse refusal), or the lifecycle rollback (POST /v1/rules/sets/{id}/rollback, rulesets § Lifecycle: history, promote, rollback, pinning) — rows are data; no image rolls back, andrules driftthen reports the treebehinduntil the next promote.
Background jobs rollout (#1933 / ADR-068 § Amendment — #1571)
The background-jobs program (plan background-jobs, epic &96;
ADR-068 § Amendment — #1571, Accepted 2026-09-18 —
the Batch class itself is deleted at the close-out, #1940) moved the engines that
rode the 600 s Batch ceiling behind a per-service durable job resource: the enqueue IS the ADR-062 claim
transaction and answers 202 + Location: /v1/<svc>/jobs/{id} + the job; a Criticality::Critical
executor per service runs the attempts; ONE generic read-only poll, GET /v1/<svc>/jobs/{id}, is authorized on
the new BackgroundJob resource type. U1 (#1933) lands the substrate on craig-placement with the expiry sweep as
the pilot; U2 (#1934) adds craig-security’s archive_run, U3 (#1935) craig-rules' promote_preview, U5 (#1937)
craig-financial’s subsidy_generate, U4 (#1936) craig-reporting’s ncands_generate, U6 (#1938) craig-financial’s
import_finalize (the first CONSENT kind — a second kind on financial’s existing executor, no new worker or
migration) and U7 (#1939) craig-financial’s sweep_preview + sweep_execute (the last two kinds on that same
executor; the single-use execute token became an explicit issuance POST) — the same authz pair (step 1 below is
already done for them) and the same executor shape per service. The program’s eight kinds as landed, plus P-D2’s
afcars_generate (#2143; its route since #2144), #2225’s backpay_finalize (the third CONSENT kind, on
financial’s same executor) and #3190’s collection_run (craig-exchange’s first kind, with the substrate mounted
there for it), eleven kinds in all (each KIND / CONSENT / dedup_key / lease_key
from the owning service’s jobs.rs; every enqueue takes a REQUIRED client_request_id and answers 202
Location: /v1/<svc>/jobs/{id}):
| Kind | Enqueue route (POST) | Service | Consent | dedup_key |
lease_key |
Re-POST rule |
|---|---|---|---|---|---|---|
|
|
placement |
proof-less |
|
|
convergent: the system re-queues |
|
|
security |
proof-less |
|
|
convergent as above; |
|
|
rules |
proof-less |
|
|
convergent as above; |
|
|
reporting |
proof-less |
|
|
convergent as above; |
|
|
reporting |
proof-less |
|
|
convergent as above (the recovery read first: an attempt whose submission already committed completes over it);
|
|
|
financial |
proof-less |
|
|
convergent as above (the |
|
|
financial |
CONSENT |
|
|
never re-queued, never adopted: |
|
|
financial |
CONSENT |
|
|
never re-queued, never adopted: |
|
|
financial |
proof-less |
|
|
convergent as above (a cut attempt
wrote nothing: the |
|
|
financial |
CONSENT |
|
|
never re-queued, never adopted: |
|
|
exchange |
proof-less |
|
|
convergent as above, and an |
Per environment, in this order:
-
Bootstrap the authz family on craig-rules BEFORE the first image carrying U1 — every engine-bearing service enumerates ALL resource types at boot, so
BackgroundJobreads as a coverage gap fleet-wide until the two files are live (a boot bail whereverAUTHZ_REQUIRE_FULL_COVERAGE=true):craig rules bootstrap target/config/layers/georgia/georgia-authz-background_job.json --profile <env> [--bearer-token …](and thetexas-twin where activated) as a humanadmin; idempotent — an existing row is reported, nothing recreated. The devstack needs no bootstrap (seed.shloads every top-level*.jsonof each config layer). The read policy: admin realm-flat; the CREATOR (a human or a service principal, byassigned_worker_sub); everyone else the fleet’s typed 403; an unknown id is 404. -
Roll craig-cases BEFORE craig-reporting (#1936). The reporting → cases NCANDS hop is a pre-1.0 S2S wire change:
GET /v1/cases/ncands-exportis PAGED (as_ofREQUIRED,after/limit, theNcandsExportPagebody) and the one-shot whole-FFY response is gone. The mixed window is NOT fail-safe in one direction: the old cases query DTO never denied unknown parameters, so an older cases IGNORESas_of/after/limit, answers the whole FFY in one shot, and a #1936 reporting decodes that as a single last page — a small FFY would land as a submission over a NON-fixed cohort (thecreated_at ⇐ as_ofexclusion never applied); a large one trips the 8 s per-page budget, the attempt endsengine_failedwith zero rows written — a TERMINALfailedjob (an engine failure never re-queues), re-POSTed with a fresh id once cases has rolled. Roll cases first and neither happens. The other direction is safe: an older reporting against a #1936 cases reads the extractor’s 400 (as_ofREQUIRED) and its synchronous generate answers the upstream error — nothing is written. -
Roll the image. The
background_jobs+background_job_attemptsmigrations are ADDITIVE (noschema_compat_floorbump) and ship with the executor in the same image through the ADR-063 gate./readyzgains the Criticalbackground-jobsworker on every adopting service — placement (#1933), security (#1934), rules (#1935), financial (#1937), reporting (#1936), exchange (#3190) — (the executor; itsbackground-jobs-retentionpruner is implicit, Observed,disabledat window 0). Every caller of a flipped route mints the now-REQUIREDclient_request_idin the SAME release (the CLIcraig home expiry-sweep/craig archive run/craig reporting generate-ncands,craig rules promote,craig subsidy import(#1938 — its finalize step is ONE POST + the poll),craig backpay(#2226 — it mints and prints the create and finalize ids), the test-lib, the web poll fragment (#1936 — the NCANDS generate action lands on/reporting/ncands?job=<id>; #1939 — craig-web’s sweep pages poll the preview job, issue the token through the BFF’s ownPOST /financial/subsidy-reviews/sweep/runs/{run_id}/tokenand poll the execute job); financial’s generate, preview and execute have NO CLI command — a caller mints its own id and polls withcraig job wait financial <id>). Reporting’s executor needsCRAIG_REPORTING__CASES_BASE_URLto resolve from the WORKER plane (the cases client is built before the workers spawn; the request path only enqueues). -
Set the retention knob if the default does not suit.
CRAIGBACKGROUND_JOBSWINDOW_DAYS(deployment-global, default31= the claims window + 1,0disables): the pruner deletes only TERMINAL jobs older than the window whose claim row no longer exists — claim-joined, so a claim kept forever keeps its job forever and a pruner backlog can never orphan an ADR-062 replay. Keep it at leastCRAIGREQUEST_CLAIMSWINDOW_DAYS + 1.
The re-POST rule per kind, what an operator lives with:
-
The SAME
client_request_idreplays the SAME job (202 again, whatever its state — afailedjob replays asfailed); a FRESH id is a new job, admitted by the arbiter only when no job of that(jurisdiction, dedup_key)isqueued/running(else 409job-already-active— poll the active one). -
Convergent kinds (
expiry_sweepU1,archive_runU2,promote_previewU3,subsidy_generateU5,ncands_generateU4,sweep_previewU7): an attempt cut by a rollout (interruptedat the engine’s boundary inside the 5 s worker drain) or by a process death (crash— a heartbeat older than 30 s, classified by any replica’s scan) is RE-QUEUED by the system asattempt + 1, up tomax_attempts(3), thenfailed(exhausted); aqueuedrow whose owner died before handoff is ADOPTED by any replica. No operator act is needed untilexhausted; then re-POST with a fresh id. -
Consent kinds (
import_finalize#1938,sweep_execute#1939,backpay_finalize#2225): their in-memory ADR-074 proof cannot be re-minted, so acrash/lost_proof/interruptedattempt ends the jobfailedand is NEVER adopted or re-queued; the operator re-POSTs with a fresh id (either finalize resumes per record; a sweep run readsfailedwith its counters preserved and its preview burned — a fresh PREVIEW is the sweep’s remedy, never a second execute of the same run). -
archive_run(security, #1934): ONE active archive job per jurisdiction (dedup_key = archive_run); it holds theretention-archivelease for its LIFE, so the hourly scheduled archiver SKIPS its tick (an info log, no heartbeat onretention-archive) while the job runs. The D11 knob is checked twice — the synchronous 403 at enqueue, andfailed(refused_at_start)namingRETENTION_ARCHIVE__ENABLEDif it was flipped OFF before the attempt.succeededatmore = falsewith a D13-isolated table’sper_table[].errorvisible inresult(read the quarantine log — the job does not fail for it);failed(no_progress)when a pass moved nothing (neither archived nor quarantined a row) whilemorestayed true (read the log for the row that cannot advance, resolve it, then re-POST with a fresh id).archive/purgeis unchanged: synchronous, Standard. -
promote_preview(rules, #1935): one active preview per rule set (dedup_key = promote_preview:<rule_set_id>,lease_key = promote:<rule_set_id>— previews of different sets run concurrently); a live head that moved between enqueue and the attempt endsfailed(engine_failed)(detaillive-revision-moved) — a fresh preview is the remedy; thepreviewsrow and--confirm-preview <preview_id>are unchanged; the execute stays synchronous (Standard). -
subsidy_generate(financial, #1937):POST /v1/financial/subsidy-payments/generatewith the body{ "client_request_id": <uuid>, "month": "YYYY-MM" }(monthoptional; it resolves at enqueue to[current − 12, current]on the Eastern business clock; the nil-idSubsidyAgreement/Approvecheck and the subsidy-writes gate stay synchronous — 403 / 400 — BEFORE the claim); one active job per MONTH (dedup_key = subsidy_generate:<YYYY-MM>) but EVERY month shareslease_key = subsidy-gen— the engine’s own lease — so an instance runs one month at a time and keeps the othersqueued(no permit held). The hourly scheduled tick keeps taking that lease directly: while a job holds it the tick SKIPS (an info log, nosubsidy-generatorheartbeat) and converges next hour; while the tick holds it a job attempt readswaiting_for_lease. Proof-less and convergent: acrash/interruptedattempt re-queues (the checkpoint sits BEFORE each child’s transaction and thepayment_monthidentity makes the re-run free — no second payment), so re-POST only afterexhausted, with a fresh id; the SAME id resumes polling. An attempt whose month fell below the 12-month floor while the job waited (a month boundary between enqueue and run) failsengine_failed(below_reconcile_floor, #2228) with nothing written and is never retried — re-POST for a month inside the bound.succeededwitherrors > 0is the unchanged partial-success posture (WARN logs keyed byresult.run_id). Every run from EITHER initiator writes onesubsidy_generation_runsrow (initiatorscheduled|manual,job_id/attempton the job’s,outcome, the report, a categoricalerror) — the operator’s ledger of what ran for a month; a lease-busy tick writes none.claims/generateis unchanged: synchronous, Standard. -
import_finalize(financial, #1938 — the first CONSENT kind):POST /v1/financial/subsidy-imports/{id}/finalizewith the body{ "client_request_id": <uuid> }(the import knob, authz, the subsidy-writes gate and the state-floorImportHistoryproof stay synchronous BEFORE the claim — 403 / 403 / 400 / the proof’s 400 / 403 / 503; the manifest gate and the batch-state refusal run INSIDE the claim transaction and abort it — 409 with the four numbers, 404, nothing enqueued); one active finalize per batch (dedup_key = import_finalize:<batch_id>),lease_key = import:<batch_id>— finalizes of DIFFERENT batches run in parallel;resource= the batch (/v1/financial/subsidy-imports/{id}). The proof rides process memory to the attempt and is NEVER re-minted: acrash/lost_proof/interruptedattempt ends the jobfailed— never re-queued, never adopted — and the batch staysfinalizingexactly as the record ledger left it; re-POST with a FRESH id (the tool’s re-run) and the new job resumes per record exactly once (per-record transactions + the live-reference unique). The attempt re-checks the knob first (failed(refused_at_start)namingSUBSIDY_IMPORT__ENABLED), declaresprogress.total = expected_countand counts onedoneper record, and runs passes of the per-record engine until the batch leavesfinalizing:succeededwithresult.status = finalized, orstaging(live rejections — the operator corrects, restages, re-POSTs with a fresh id); three consecutive passes that moved nothing (a swallowed per-record infrastructure error is what a pass retries) end itfailed(no_progress)withremaining_staged/passesinerror.detail— a failed job carries noresult; the batch detail GET is the ledger. A peer replica holding the engine’ssubsidy-import-finalize:<batch_id>session lock readswaiting_for_lease(never the old 409); a second job for the SAME batch while one is queued / running is 409job-already-active; a POST after the batch isfinalizedis a new job whose single pass is the deterministic replay. The operator surface iscraig subsidy import(one POST, then the shared poll; afailedjob prints the batch counts and the re-run rule) or any caller minting its own id +craig job wait financial <id>. -
backpay_finalize(financial, #2225 — the third CONSENT kind):POST /v1/financial/backpay/batches/{id}/finalizewith the body{ "client_request_id": <uuid>, "content_checksum": <64 lowercase hex> }(the backpay knob, authz onsubsidy_backpay_batchfinalize, the subsidy-writes gate and the state-floorBackpayFinalizeproof stay synchronous BEFORE the claim — 403 / 403 / 400 / the proof’s 400 / 403 / 503; the consent gate runs INSIDE the claim transaction and aborts it — 409backpay-finalizer-staged, 409manifest-mismatchwith the leg named, 409batch-stateon anabortedbatch, 404, nothing enqueued); one active finalize per batch (dedup_key = backpay_finalize:<batch_id>),lease_key = backpay:<batch_id>— finalizes of DIFFERENT batches run in parallel;resource= the batch (/v1/financial/backpay/batches/{id}). The proof rides process memory to the attempt and is NEVER re-minted: queued jobs endlost_proof; running onesinterrupted(a graceful restart) orcrash(a killed process); the batch staysfinalizingexactly as the record ledger left it. Once the old job readsfailed, re-POST with a FRESH id and the same reviewedcontent_checksum(the resume does not re-verify it) and the new job resumes per record exactly once. The attempt re-checks the knob first (failed(refused_at_start)namingSUBSIDY_BACKPAY__ENABLED), declaresprogress.total = expected_count, and runs passes of the per-record engine until the batch leavesfinalizing:succeededwithresult.status = finalized, orstaging(a record diverged or a manifest key is not materialized — supersede, re-stage, finalize again); three consecutive passes that moved nothing end itfailed(no_progress)withremaining_staged/passesinerror.detail→ the stuck-finalizing runbook. A peer replica holding the engine’ssubsidy-backpay-finalize:<batch_id>session lock readswaiting_for_lease; a second job for the SAME batch while one is queued / running is 409job-already-active; a POST after the batch isfinalizedis a new job whose single pass is the deterministic replay. The operator surface iscraig backpay finalize(#2226: the review, the confirmed checksum, one POST, then the shared poll; a resumablefailedjob prints the batch counts and the fresh-id re-run rule) or any caller minting its own id +craig job wait financial <id>. -
sweep_preview+sweep_execute(financial, #1939 — the last two kinds; the token an explicit POST): the manual review-sweep runbook is preview → poll → token → execute → poll.POST /v1/financial/subsidy-reviews/sweep/previewwith the body{ "client_request_id": <uuid> }(the supervisorreview_sweepauthz row and the subsidy-writes gate stay synchronous BEFORE the claim — 403 / 400) enqueues ONE preview per jurisdiction (dedup_key = sweep_preview:<jurisdiction>;lease_key = sweepis the executor’s dispatch label — a preview takes NO engine lease). Proof-less and convergent: acrash/interruptedattempt re-queues and a stalequeuedrow is adopted — safe because the previous attempt wrote nothing (thepreviewedrun row and the job’ssucceededcommit in ONE transaction). Poll it:resultis the pinned sets withtoken_state: availableandresourcelinks the run (/v1/financial/subsidy-reviews/sweep/runs/{id}) — NO token rides the job. ThenPOST /v1/financial/subsidy-reviews/sweep/runs/{run_id}/token(no body; the previewer or an admin; the subsidy-writes gate): the ONE issuance, inside 15 minutes of the run’sstarted_at— 200{ run_id, execute_token, expires_at }underCache-Control: no-store, shown once and never retrievable again; a second POST is 409sweep-token-issued, a closed window 409sweep-preview-expiredwith the run stampedexpired(preview again), any other state 409sweep-run-state. ThenPOST /v1/financial/subsidy-reviews/sweep/{run_id}/executewith{ "client_request_id": <uuid>, "execute_token": "…", "acknowledged_suspend": n, "acknowledged_terminate": n, "acknowledged_handoff": n }— the regionalSweepExecuteoffice proof is minted synchronously BEFORE the claim (its 400 / 403 / 503 set unchanged) and an aged preview is stampedexpiredin its own statement (409sweep-preview-expired); INSIDE the claim transaction the token digest (400), the acknowledged counts (409sweep-preview-stale) and thepreviewed → consentedflip (409sweep-run-stateon a replay or a second execute) — a refusal enqueues nothing and the run stayspreviewed, so the SAME id may retry; one active execute per run (dedup_key = sweep_execute:<run_id>,lease_key = sweep),resource= the run. The attempt takes the engine’ssubsidy-sweeplease (a scheduled pass holding it iswaiting_for_lease; a job holding it makes the scheduled tick SKIP — an info log, noreview-sweepheartbeat), re-checks the office proof under it, moves the runconsented → executingand commits the counters after EVERY agreement — the run detail GET shows them climbing.succeeded= the runcompletedwith theSweepReportasresult(partial success is still success). A CONSENT kind: acrash/lost_proof/interruptedattempt ends the jobfailed— never re-queued, never adopted — with the run stampedfailed, the counters as committed (NULL when the attempt never started) and the preview burned; the remedy is a FRESH preview, never a second execute of the same run. craig-web drives the whole flow (its sweep page polls the preview job, issues the token through the BFF’s ownPOST /financial/subsidy-reviews/sweep/runs/{run_id}/token, renders the execute form once, then polls the execute job); there is no CLI verb — a scripted caller mints its own ids and polls withcraig job wait financial <id>. -
ncands_generate(reporting, #1936):POST /v1/reporting/ncands/generatewith the body{ "client_request_id": <uuid>, "reporting_year": <ffy> }(the admin authz check stays synchronous BEFORE the claim); one active generation per fiscal year per jurisdiction (dedup_key = ncands_generate:<ffy>); NO engine lease (lease_key = report_generatesince #2206, the dispatch label it shares withafcars_generate: an instance runs one federal-report generate at a time, so a second waitsqueued, holding no permit, behind a running AFCARS or NCANDS generate; nothing ever readswaiting_for_leasehere). Proof-less and convergent: the job’sinput.as_ofis the enqueue instant, so EVERY attempt walks the SAME FIXED cohort (received_at ∈ [ffy) AND created_at ⇐ as_of) page by page from cases — a referral converted after enqueue is excluded deterministically, whatever its reportreceived_at; a page that hangs past the 8 s hop budget, 5xxs or decodes malformed fails the attemptengine_failedwith ZERO rows written (nothing rests before the final transaction) — TERMINALfailedon that attempt (an engine failure never re-queues; only acrash/interruptedattempt re-queues, up to 3, thenfailed(exhausted)) — re-POST with a fresh id once cases answers (a cases outage is the usual cause; the SAME id replays the failed job, never a new one). Completion is one transaction: the submission (id== the job id), its rows AND the job’ssucceededcommit together, so a crash between them cannot exist; a re-queued attempt that finds the submission already present completes without regenerating.resultis the finalized submission (the pre-#1936 200 body) — review / approve / transmit it as before;resourceis empty (no submission GET exists — the id is in the result). The CLI iscraig reporting generate-ncands --reporting-year <ffy> [--client-request-id <uuid>] [--no-wait]; the web action lands on the list page with?job=<id>, which polls the fragment every 2 s until terminal.afcars/generateis unchanged in shape (the #949 stub) and now rides Standard; the two export POSTs (ncands|afcars/{id}/export) are synchronous Extended (5 min request ceiling; the BFF’spost_extended310 s caller budget); the export DOWNLOAD GETs are Standard; NCANDS’s streams, AFCARS’s is buffered since P-D4 U2 (#2177) (§ Streaming downloads rollout below). -
The engine lease is never probed at enqueue: a scheduled pass holding it (the hourly generator, the retention worker — or a peer’s
archive_runjob holding it for its life) shows asprogress.phase = waiting_for_lease— a 5 s re-dispatch, never a failure or a timeout.
What the close-out (#1940) leaves as the request-ceiling contract. The Batch class is gone: every route answers its
response HEAD inside the Standard 20 s or the Extended 300 s ceiling — no head arrives past 300 s — and an external
caller sets its client budget above its class (first-party callers pair only the Extended budget, 310 s); a streamed
download BODY is outside the ceiling by design (§ Streaming downloads rollout below — set an idle budget ≥ 120 s on
downloads, never a total). POST
/v1/admin/events/replay is Standard-classed (20 s) on the #1941 bound: one call re-stages at most 20 × 5 000 =
100 000 rows in per-batch 10 s-budgeted transactions — a full 100 k-row call measured ≈ 0.63 s on the test plane (the
slowest batch ≈ 33 ms, ≈ 0.3 % of the budget; the (created_at, id) index built in ≈ 22 ms) — and a larger window is
walked by passing resume_from back with the SAME from / to / event_type until more = false; the index build’s
SHARE lock on event_outbox is the § Migration gates note below. The web BFF is unpaired by design: it pairs only the
Extended budget (post_extended on the two export POSTs, post_multipart on the upload proxies; its download proxies
ride the streaming client — #1947) and never carried a Batch leg — its proxies of the once-Batch routes rode the shared
30 s client, which is why those routes are jobs.
Streaming downloads rollout (#1946 / #1947 / ADR-068 § Amendment — #1572)
Every object-store download — the eight backend GETs (reporting ncands|afcars/{id}/export/download (AFCARS since
P-D4 U2 (#2177) excepted: its body is buffered and opened before the head is sent — see
P-D4 U2 — the sealed export (#2177)), cases contact /
court-order / report attachments, placement home + portal documents, exchange ICPC attachments) and the six edge
proxies in front of them (craig-web ×4, craig-portal, intake’s partner attachment download) — is Standard-classed
and streams: the response head (status, Content-Length, Content-Type, Content-Disposition, Cache-Control:
no-store) arrives inside the 20 s ceiling after ONE object head(), and the body follows as lazy 8 MiB ranged reads
whose frames are forwarded as they arrive — no service or edge holds the blob in memory, and the 300 s Extended
ceiling covers only the upload nests and the two export POSTs. For operators:
-
Two bounds, neither a total. Upstream, each 8 MiB chunk runs under the store’s per-request timeout and fixed retry policy: the chunk deadline is
3 × CRAIG_STOREREQUEST_TIMEOUT_SECS + 10 s(100 s at the default 30 s). At every first-party edge the body runs on a dedicated streaming client whose idle budget isDOWNLOAD_IDLE_BUDGET= 120 s PER READ (it resets on every frame; there is no total, so a body that keeps flowing is never cut), while the head is awaited under the BFF’s 30 sDEFAULT_TIMEOUT(intake: its own 20 s Standard ceiling). The two are ordered by construction for the default only: keepCRAIG_STOREREQUEST_TIMEOUT_SECS ≤ 36(3 × 36 + 10 = 118 ≤ 120). Past that a chunk still retrying upstream can be cut by the edge; any service that builds aStorelogs ONE warning at boot naming both numbers and this constraint (the store’s chunk deadline exceeds the edge download idle budget) — lower the timeout, or raise the edge budget (a code constant,craig_common::ceiling::DOWNLOAD_IDLE_BUDGET, in a release). -
A stalled chunk is a TRUNCATED download, never a 504. Once the head is on the wire no status can change: a chunk that exhausts its retry budget, a foreign overwrite’s 412, or a blob deleted mid-download ENDS the body short of
Content-Length, and the browser or client sees an incomplete transfer. It is visible asdownload_stream_outcome_total{outcome="failed"}on the serving backend plus ONE correlatederrorline inside the request span (method / route andrequest_id, theX-Request-Idthe response echoed);failedalso counts a stored object shorter or longer than its head’sContent-Length.abandonedcounts a peer that went away first,completeda full body (the declared length served). Alert onfailed, not on 5xx — the head-scoped HTTP metrics never see a body failure. -
A digest mismatch is an integrity alarm, not a transfer error (#1949). A streamed download whose row stores the stored bytes' digest — today the NCANDS export (
ncands_submissions.export_sha256; attachment rows store none) — is hashed as it streams. A body that serves its fullContent-Lengthwith a different sha256 adds onedownload_digest_mismatch_total{service}sample and logs ONEerrorline (streamed download digest mismatch) inside the request span, with the correlation id (request_id), the object key and both digests. The client has already received those bytes: the head committed the response. A failed or abandoned body is never compared. Alert on any increase. The remedy is to treat the stored object as corrupted: regenerate the export (POST /v1/reporting/ncands/{id}/exportwith a freshclient_request_id, or none — a retry under the same id replays the same stored artifact), or restore the object’s prior version where the bucket keeps versions (§ Object Storage (S3); versioning or object lock is required once the archiver is enabled, § Storage requirements); and have the recipient discard the file it downloaded. -
External download callers set an idle (read) budget ≥ 120 s and no total; a total budget on a download re-creates the retired class on the caller side. The four craig-web download routes forward the backend’s Content-Type (a PDF attachment is
application/pdf, no longerapplication/octet-stream; the two text exports are reporting’s baretext/plain, no longertext/plain; charset=utf-8) under the edge-widenosniff+Content-Disposition: attachment; text exports are no longer gzip-compressed (attachment responses are exempt from the compression layer soContent-Lengthsurvives). -
Downloads are resumable (#1948). Every download response carries
Accept-Ranges: bytesand, when the object has a strong one, itsETag(the AFCARS export’s is the sha256 of the opened file). A singleRange: bytes=a-b(ora-, or the suffix-n) answers206withContent-Range: bytes a-b/<length>and the slice’sContent-Length, and the body streams over that slice alone: the same 8 MiB ranged reads, tiled froma, never the whole object. A range that starts at or past the end answers416(therange-not-satisfiableproblem document) withContent-Range: bytes */<length>. A malformedRange, another unit, or a multi-range request is ignored and answers the full200: multipart/byteranges is never produced.If-Rangelets the range through only when it is a strong entity-tag equal to the object’sETag; a weak tag, an HTTP-date (noLast-Modifiedis sent) or a changed object answers the full200, so a resumed download of a changed object restarts rather than splicing two versions. A HEAD is never ranged. The six edge routes forwardRange/If-Rangeupstream and relay the206/416status withAccept-Ranges,Content-RangeandETagunchanged. A206is not digest-audited (the stored digest is the whole object’s). Each resumed request is a separate request: the portal certificate download writes one read audit per request, a416included. Nothing to configure. An ingress or reverse proxy in front of the edges must pass those request and response headers and the206/416statuses through for resumption to work; one that dropsRangeonly costs resumability (every download answers the full200), and one that weakens theETag(for example by compressing) makes every resume restart from byte 0. -
Downstream stalls are bounded (#1951). Every CRAIG HTTP server ends a connection whose response writes make no progress for 120 s (
craig_common::ceiling::RESPONSE_WRITE_IDLE_BUDGET, a code constant): a reader that stops consuming is cut and its body dropped — a streamed download countsabandoned, notfailed, so thefailedalert stays a store signal — with onewarnline (response write made no progress within the write-idle budget; closing the connection). It is an idle bound, not a total: a reader that keeps draining is not cut while each write completes within the budget, and reads and idle keep-alive connections never arm it. Not covered: an HTTP/2 peer (intake’s TLS ALPN, or h2c prior-knowledge where hyper-utilhttp2is compiled in) that withholds flow-control credit. -
Order. No migration, ruleset or S2S change. Backends (#1946) BEFORE the edges (#1947): a buffering BFF in front of a streaming backend merely keeps its old 310 s whole-download budget, while a streaming edge in front of a buffering backend awaits a head that a large export may not produce inside the edge’s head bound (30 s at the BFF, the 20 s ceiling at intake).
AFCARS federal ruleset bootstrap (#1972 / plan afcars-federal-ruleset)
The AFCARS program’s first child plan (plan afcars-federal-ruleset, epic &99, P-A of #949;
Plan: AFCARS Federal Ruleset Class, Dictionary Tooling, the Crosswalk Verifier and the Verified Surface (#1962, P-A of #949)) gives craig-reporting a VERIFIED SURFACE over two craig-rules
documents it reads by name — the jurisdiction-invariant dictionary federal-afcars-2020 (the federal layer’s
class, Rule Set Patterns and Domain Knowledge § The federal ruleset class) and the deployment’s {j}-afcars-crosswalk — parsed,
structurally verified and RETAINED, never compiled (nothing evaluates a dictionary before P-D). U4 (#1972) ships the
reporting image that reads them; the documents ship as data. The order per environment is therefore fixed:
-
Bootstrap both documents on craig-rules BEFORE the U4 reporting image. A family that does not yet exist cannot be promoted (
rules promotetargets an EXISTING set), so the first load is the one-timecraig rules bootstrap target/config/layers/federal/federal-afcars-2020.json --profile <env> [--bearer-token …]followed bycraig rules bootstrap target/config/layers/georgia/georgia-afcars-crosswalk.json …(the crosswalk of every jurisdiction the deployment activates), as a humanadmin(the device-code grant otherwise; service principals are deniedrule_set: create). The command is idempotent: an existing row is reported with its revision and nothing is created. The devstack needs no bootstrap — the seed’s/config//current/glob (/seed/rulesets//until U4) loads the federal layer like every jurisdiction layer. -
Verify by name.
GET /v1/rules/sets/by-name/federal-afcars-2020and…/by-name/georgia-afcars-crosswalkanswer the rows (by-name resolves ACTIVE rows only). Later versions ride the two-step promote;cargo xtask rules checkis the local gate — the dictionary’s citation manifest is BLOCKING for the federal directory, and the crosswalk arm verifies every crosswalk against the committed dictionary and the fleet vocabularies. -
Then deploy the reporting image. Its Critical worker
afcars-surface-verifierre-reads both documents on the 2 s → 60 s ladder (both reads sequential inside ONE 4 s budget, each under its own timeout) and walks the closed check order; the gaugeafcars_surface_verified{jurisdiction}is its verdict.
First install vs upgrade of the two documents (#1986)
The three steps above are an environment’s FIRST INSTALL. Once a family exists rules bootstrap is a reported no-op
(EXISTS: <name> (<id>) at revision <n> (version <v>) — nothing created; later versions go through `craig rules
promote`), and every later version of a committed document — the P-A2 record-layout pins (U5b), a dictionary
re-cut, a crosswalk gaining a table — is an UPGRADE through the same two-step promote every ruleset rides
(Rule Set Patterns and Domain Knowledge § Lifecycle: history, promote, rollback, pinning). The order per environment is fixed by what
the reporting binary can read (#2168). craig-reporting parses the WHOLE active dictionary against a closed vocabulary
— its table set and its predicate tokens — and one failed pass makes the snapshot gate refuse every half, 2022 ones
included. So a dictionary version that ADDS vocabulary is promoted only AFTER the craig-reporting image that reads
both it and the version it replaces is on every replica: (1) roll that image; (2) promote the dictionary ONCE (each
promotion stales the uncertified exports made under the previous identity: afcars-artifact-stale until the half is
regenerated); (3) promote every activated jurisdiction’s crosswalk (the crosswalk arm verifies against the dictionary
the environment HOLDS, so a crosswalk that maps onto a new element series promotes AFTER the dictionary carrying it).
An image that RETIRES vocabulary rolls only once the newer dictionary is live in every deployment. Rollback is the
newer side first — craig-rules does not check what the binary reads: before the retiring image, the dictionary back to
its previous version (the both-vocabulary image reads it), then the image if needed; after it, the image back first,
then the dictionary. Each dictionary version’s CHANGELOG entry names the image it needs. Both documents are data no
evaluation consults before P-D, so their corpora are thin by construction:
--acknowledged-thin-corpus is the named consent on every execute, not a bypass.
# FIRST INSTALL — idempotent: an existing family is reported, never re-created
craig rules bootstrap target/config/layers/federal/federal-afcars-2020.json \
--profile <env> [--bearer-token …]
craig rules bootstrap target/config/layers/georgia/georgia-afcars-crosswalk.json \
--profile <env> [--bearer-token …]
# UPGRADE of an existing family — AFTER the reporting image that reads the new version (above); the dictionary, then each crosswalk
cargo xtask rules afcars-manifest --print-document-hash (1)
craig rules promote target/config/layers/federal/federal-afcars-2020.json \
--reason "federal-afcars-2020 <sha256 from <1>> — <what changed>" \
--profile <env> [--bearer-token …] (2)
craig rules promote target/config/layers/federal/federal-afcars-2020.json \
--reason "federal-afcars-2020 <sha256 from <1>> — <what changed>" \
--confirm-preview <preview-id> --acknowledged-thin-corpus \
--profile <env> [--bearer-token …] (3)
craig rules promote target/config/layers/georgia/georgia-afcars-crosswalk.json \
--reason "georgia-afcars-crosswalk <sha256 from <1>> — <what changed>" \
--profile <env> [--bearer-token …]
craig rules promote target/config/layers/georgia/georgia-afcars-crosswalk.json \
--reason "georgia-afcars-crosswalk <sha256 from <1>> — <what changed>" \
--confirm-preview <preview-id> --acknowledged-thin-corpus \
--profile <env> [--bearer-token …]
| 1 | Prints the canonical content hash (craig_rules_contracts::identity, the body craig-rules records on the
promotion snapshot) of the committed dictionary and of every committed {j}-afcars-crosswalk.json — the value
the verification below compares against. Quote it in --reason so the promotion record names WHICH bytes were
promoted; the digest is not recomputed from the reason (that check is the administrative-authority family’s). |
| 2 | The preview: the promote-preview job’s result names the preview id and the command prints the confirm line
verbatim; nothing is activated. |
| 3 | The execute: the same reason, the preview id, the thin-corpus consent. A promote-preview-stale answer means the
row moved under the preview — re-run <2> without --confirm-preview to re-preview. |
Verify every act by identity, not by the gauge. GET /v1/reporting/afcars/metadata (the probe below) projects the
dictionary and crosswalk identity triples (rule_set_id, revision, content_sha256) of the candidate the
reporting service retained on its last verifier pass (the 2 s → 60 s ladder, so at most a minute after the promote).
After each act the document’s content_sha256 MUST equal the hash <1> printed for that file and its revision the row
the promote (or bootstrap) answered with: the two hashes are ONE canonical body computed on both sides, so a mismatch is
never a formatting artefact — it means the service reads a different row (a stale replica; a by-name ACTIVE row that is
not the one just promoted). A first install is checked the same way against the bootstrapped rows. surface.state
stays not_ready / layout-unpinned until the committed dictionary carries the pins — the identity check is the
operator’s proof that the act landed, independent of the verified verdict.
What the operator lives with afterwards:
-
The gauge reads
0BY DESIGN on a P-A image. The check order endslayout-unpinned→dictionary-unsupported-by-binary→jurisdiction-unregistered→verified, and two of those arms cannot pass yet: the committed dictionary carries no record-layout pins until P-A2 (#1973) pins the layout, and the binary’sAFCARS_RECORD_CONTRACTcovers every oohc element (P-D2 U2, #2139) but no record layout until P-D5’s renderer, so a pinned dictionary still answersdictionary-unsupported-by-binaryon its layout alone. A0after bootstrap is therefore not the alert — the reason token is. Nothing consumes the verified snapshot before P-D, so a0refuses nothing today. -
The metadata GET is the operator’s probe.
GET /v1/reporting/afcars/metadata(the sameAfcarsSubmissionnil-idreadrows the detail GET consults;Cache-Control: no-store) projects the retained CANDIDATE, never the verified-only path:surface.state(verified|not_ready) with the closedreasontoken, thedictionary/crosswalkidentities (rule_set_id,revision,content_sha256— the ONE canonical hash incraig_rules_contracts::identity, the same body craig-rules records on the promotion snapshot, so the two agree by construction),current_periodon the jurisdiction clock (the completed half stays CURRENT through its due date, a weekend due date rolled to Monday) and the crosswalk’ssupported_from. Read it after bootstrap:not_ready/layout-unpinnedwith BOTH identities populated is the expected P-A state;dictionary-absent/crosswalk-absentmeans step 1 has not happened for that document;read-timeoutnames the rules hop; a structural token names the document that fails to parse or verify;jurisdiction-unregisteredmeans the deployment’s bundle declares nobusiness_timezone(bundle/settings.toml). Every field but the state is null while no candidate is retained. -
What a new jurisdiction registers. The
BLOCKING_JURISDICTIONSentry and the federal lock line are the FEDERAL directory’s, registered once (#1969) — a jurisdiction adds nothing there for AFCARS. It registers: a compiled StateBundle whose jurisdiction equals the configured one and that declares itsbusiness_timezone()(the zoneBusinessClock::try_for_jurisdictionresolves — that lookup IS thejurisdiction-unregisteredcheck, #2207), its{j}-afcars-crosswalk.json— TOTAL by equality over everyfleet_vocabularies()entry, so a vocabulary the registry does not yet carry is a registry entry first — with the manifest rows in itscitations.toml(Rule Set Patterns and Domain Knowledge § Crosswalks, "Adding an element"), and the two authz files the routes consult —{j}-authz-afcars_submission.json(the nil-idreadrow) and{j}-authz-background_job.json(the job-first generate’s poll).
AFCARS cases capture rollout (#1964)
The AFCARS cases capture plan (plan afcars-cases-capture, P-C of #949, ADR-078 D4;
Plan: AFCARS Cases Capture — Demographics, the Effective-Dated Child Facts, ICWA, Parents and Parental Rights, the Permanency Ledgers and the Plan Projection (#1964, P-C of #949) D7) moves the guardianship activation’s reunification refusal from the
placement’s permanency_goal to the child’s CURRENT plan in the craig-cases permanency ledger
(data-model-cases.adoc#permanency-ledgers). U6a (#1996) ships both halves: craig-cases serves the ONE service
read of P-C data, GET /v1/cases/cases/{case_id}/children/{child_id}/permanency-plans/current?as_of= (craig-financial
only; 200 the plan in force at as_of, 204 when none), and craig-financial’s activation calls it with the derived
transfer date. U6b (#1997) then removes the now-unread PlacementSubsidyEligibility.permanency_goal from craig-placement.
The reunification refusal is never dark during the roll. Per environment, in this order:
-
Roll craig-cases (U5 + U6a) BEFORE craig-financial (U6a) (#1996). A U6a financial against a pre-U6a cases gets
404from the unrouted path, which it treats as a failure, never as "no plan": every guardianship activation answers the plan leg’s fail-closed503("craig-cases is unreachable — the child’s permanency plan cannot be verified …") until cases rolls. Roll cases first and nothing refuses. The other direction is safe: a pre-U6a financial against a U6a cases still readsPlacementSubsidyEligibility.permanency_goal, which craig-placement keeps serving until step 3. There is no migration, no knob, noschema_compat_floorbump and no seed re-bless. After the roll the refusal is the cases plan in force at the transfer date: a child whose plan isreunificationis refused with the unchanged400, a child with no plan row passes as before, and a placement goal alone no longer refuses — no placement goal is migrated into the ledger (pre-1.0, refuse-on-data at U5). A hung cases lookup is bounded byPLAN_S2S_BUDGET(4 s) and answers its own503naming the leg, inside the 20 s Standard ceiling. -
DRAIN every pre-U6a craig-financial instance (#1997). Before craig-placement rolls, no financial instance older than U6a may still serve traffic: a pre-U6a financial refuses
reunificationonly from the placement field, which it deserializes as absent (None) from a U6b placement — its refusal would go DARK and let a reunification transfer through. Confirm every financial replica runs the U6a image (or later) and no old replica drains in-flight activations. -
Roll craig-placement (U6b) (#1997). The eligibility read stops serving
permanency_goal; theplacements.permanency_goalcolumn, the placement create / update wire and the caregiver portal label are untouched here (P-B1 U7, #2024, retires them: § AFCARS placement capture rollout, U7). A U6a financial still declares the field but reads it nowhere, and a financial built after U6b ignores an older placement’s leftover key (the contract rejects no unknown field), so the order between placement replicas does not matter once step 3 begins.
Rollback. Name images by unit, and reverse the steps. Roll craig-placement back to its U6a image FIRST (it re-serves the unread field — harmless to a U6a financial). Only then may craig-financial roll back past U6a (a pre-U6a financial re-reads the field that placement serves again), and craig-cases last (the plan route has no other caller). NEVER run a pre-U6a craig-financial against a U6b craig-placement: its reunification refusal goes dark. Rolling only craig-placement back is always safe.
AFCARS placement capture rollout (#1963)
The AFCARS placement capture plans (P-B1, Plan: AFCARS Placement Capture I — Removal Episodes, Living-Arrangement Lifecycle, the Shared Ledger Core (#1963, P-B1 of #949) § Rollout + risks, ADR-079, P-B2, Plan: AFCARS Placement Capture II — The Arrangement Vocabulary, Setting Identity, the Element Map (#2026, P-B2 of #949) § Rollout + risks, #2026, and P-B3, Plan: AFCARS Placement Capture III — The Element Capture: Arrangement, Removal, Exit and Child Facts (#2052, P-B3 of #949) § Rollout + risks, #2052; all of #949) roll unit by unit, each in the order its § Rollout + risks row names. This section carries the units whose roll needs an operator step.
U3 — removal episodes and episode-bound arrangements (#2018)
U3 makes a removal episode the unit of care, and every placement a living arrangement inside one: the create names an
episode_id and derives the case and child from it, and a planned row is cancelled
(POST /v1/placement/placements/{id}/cancel), never ended. Its one migration,
20260925130000_removal_episodes_recut, is DESTRUCTIVE (it drops removal_date, removal_reason, the CTW and
reasonable-efforts columns and sibling_placements), refuses on data, and makes craig_placement’s first
schema_compat_floor bump. Per environment, in this order:
-
Roll craig-security first. Its parse arms record
placement.cancelledas (update,placement) andplacement.episode_facts_changedas (update,removal_episode), and theplacement.episode_andplacement.cancelledfamilies resolve their resource ids. A pre-U3 craig-security has no arm for either key, so it must be live before the first U3 placement publishes. -
Roll craig-placement: refuse-on-data, the floor bump, every replica replaced before traffic. The migration’s guard runs FIRST and refuses on ANY
placementsrow: no recorded fact says which removal an existing placement belongs to, or when that removal happened, so no episode is synthesized. sqlx applies the file in one transaction, so a refusal leaves nothing of it applied. Before any production data the table is empty. A database that holds placements stops the roll: the message namescargo xtask dev reseedfor a disposable environment, and anything else needs a planned data migration first. The migration installs the trustedbtree_gistextension as the owner role (the per-child exclusion constraints; see § Per-service DB roles). The floor bump to20260925130000is its LAST statement. An N−1 craig-placement reads and writes the dropped columns and inserts placements without an episode. The floor is checked only at boot, so a restarting N−1 replica refuses to start, but a running one is not stopped. Replace EVERY replica before the service takes traffic: no mixed-version window. -
Devstack. The migration’s
-- devstack: wipe-before-applymarker makes the devstack wipe craig_placement and reseed it automatically. The seed derives one removal episode per placed child. -
Roll craig-web, then craig-cli. In the window after placement rolls, an old craig-web cannot create a placement: its create body carries no
episode_id. It meets nocancelledrow unless the CLI cancels one in the window (accepted: devstack-only before any production data). craig-financial and craig-reporting deploy nothing for U3 (their changes are tests only).
Rollback. N−1 images AND a database restore. The floor refuses an N−1 craig-placement against the U3 schema, and the dropped columns cannot come back with their values. Take the operator’s craig_placement backup / PITR mark before step 2. To roll back, restore that backup, then roll craig-placement to its N−1 image, then craig-web and craig-cli.
U4 — exits, re-entry and the historical episode (#2019)
U4 records how a removal episode ends. It adds the exit_responses ledger, the exit acts
(POST /v1/placement/episodes/{id}/exit, …/exit/{row_id}/corrections, …/exit/{row_id}/retract) and the historical
episode (POST /v1/placement/episodes/historical). It adds re-entry, which is a new episode opened after the exit, and the
arrangement end reason left_care. Its one migration, 20260925150000_exit_responses, is ADDITIVE: a new table, a
replaced check_episode_current_instants body and a superset chk_placements_end_reason. There is no refuse-on-data guard,
no schema_compat_floor bump and no devstack wipe marker. Per environment, in this order:
-
craig-security deploys nothing. The plan’s row names it first, and that order is kept, but nothing needs to roll: the
placement.episode_facts_changedarm and theplacement.episode_family are ledger-blind. The exit acts and the historical episode publish the event keys U3 already maps, and U4 changes craig-security’s tests only. -
Roll craig-web FIRST. Its strict decoders (the placement view’s and the end form’s
PlacementEndReason) must knowleft_carebefore placement can store one. Its episode view is lenient, so a U4 craig-web reads a U3 placement: a missingexitis read as none. Accepted window, until placement rolls: Record exit posts to a route a U3 placement lacks, so the worker sees the generic "failed" flash (a 404/405 without a problem body), and a U3 placement refuses aleft_careend (a 400 flash). -
Roll craig-placement. The migration applies on boot through the migration gates, and a rolling replacement is acceptable. An N−1 replica neither writes an exit nor decodes
end_reasonstrictly. Window hazard: the replacedck_episode_current_instantsalso refuses, at COMMIT, a retired episode that still holds a live removal or exit response (a retracted episode is inert, ADR-079 D2). A U3 replica’s retract of an exited episode with no arrangement retires the episode but not its exit. That retract therefore fails closed: the act answers a redacted 500 and writes nothing. Retry it on a U4 replica. -
craig-cli ships with the workspace. Its new
craig placement episode exit record/correct/retractandcraig placement episode historicalcommands need the U4 routes. -
craig-financial and craig-reporting deploy nothing (craig-reporting’s change is a test only; craig-financial has none). An arrangement ended
left_carewhile a guardianship agreement is pending raises craig-financial’s existing WARN "pending guardianship agreement anchored to a placement that ended WITHOUT a guardianship transfer". The WARN is truthful: a guardianship transfer is ended asguardianship, notleft_care. -
Devstack. A new migration without a marker takes the cached-rebuild path, the migration gates apply it on
compose up, and the seed change triggers a reseed on its own (the seed now emits exits and re-entry episodes). No wipe.
Rollback. N−1 images, placement first, no database restore (the migration is additive and the floor is unchanged).
craig-web may go back past U4 only while no left_care row exists: an N−1 craig-web cannot decode one.
U5 — retract, historical record and replacement (#2020)
U5 corrects an arrangement entered in error. An active or ended placement is retracted
(POST /v1/placement/placements/{id}/retract): the row stays as the record, marked retracted. A past arrangement is
recorded born ended (POST /v1/placement/placements/historical). A replacement names the retracted arrangement in
replaces_placement_id, on the create or on the historical record, and craig-financial re-anchors the retracted
arrangement’s subsidy agreements onto it. The new events are placement.retracted, placement.recorded and
financial.subsidy_anchor_replaced; placement.activated gains the optional replaces_placement_id. Its one migration,
20260925170000_retracted_arrangements, WIDENS the schema, so it has no refuse-on-data guard and no devstack wipe marker.
Its LAST statement is a voluntary schema_compat_floor bump. Per environment, in this order:
-
Roll craig-security first. It gains the parse arms and resource families for
placement.retracted(update,placement) andplacement.recorded(create,placement), and the arm forfinancial.subsidy_anchor_replaced(update,subsidy_agreement). A pre-U5 craig-security drops none of them: it records the two placement keys by the raw split, with the CASE uuid as the resource id. -
Roll craig-web. Its strict
PlacementStatusdecoder must knowretractedbefore placement can write one: an N−1 craig-web’s placement list and detail pages error on a retracted row. Accepted window, until placement rolls: the Retract and historical-record forms post to routes a U4 placement lacks, so the worker sees the generic "failed" flash (the U4 precedent). -
Roll craig-financial, EVERY replica. It binds
placement.retractedandplacement.recordedand carries the re-anchor. Thecraig-financial.eventsqueue is shared and bind-only: the first U5 replica binds the new keys for the whole fleet, and an N−1 replica still running consumes them with no arm and stamps them processed. The void or the re-anchor is then lost, and an N−1 replica also dropsreplaces_placement_idfromplacement.activatedsilently (the payload is lenient). No N−1 craig-financial replica may be alive when placement rolls. craig-financial has no migration and no floor bump, and it is inert against a U4 placement, which publishes none of the new keys. -
Roll craig-placement: the cutover, every replica replaced before traffic. The migration applies on boot through the migration gates, and its floor bump to
20260925170000is its LAST statement. An N−1 craig-placement decodes status through the strictPlacementStatusenum and cannot read a retracted row. The floor is checked only at boot, so a restarting N−1 replica refuses to start, but a running one is not stopped (the U3 text). Replace EVERY replica before the service takes traffic: no mixed-version window. -
craig-cli ships with the workspace. Its
craig placement retract,craig placement historicalandcraig placement create --replacesneed the U5 routes. In the window before placement rolls,--replacesagainst a U4 placement is silently dropped (the create body is lenient): do not use it until step 4 completes. -
craig-reporting deploys nothing (its change is a test only).
-
Devstack. A new migration without a marker takes the cached-rebuild path, and the migration gates apply it on
compose up. The seed is unchanged, so there is no reseed and no wipe.
Rollback. N−1 images AND a database restore. The floor refuses an N−1 craig-placement against the U5 schema. Take the
operator’s craig_placement backup / PITR mark before step 4. To roll back, restore that backup, then roll
craig-placement to its N−1 image, then craig-web. Roll craig-financial back only AFTER craig-placement is at N−1: an N−1
craig-financial facing a U5 placement loses voids and re-anchors. A lost one is findable from placement’s retracted
rows and their replacements' replaces_placement_id, and is repaired by hand. craig-security may stay at U5.
Limitation, and its report (#2041). The retract voids only the undisbursed (pending or approved) per-diems of the
retracted arrangement. Issued and cleared payments stay, and a replacement’s activation can bill a first period again
under the replacement’s id. Since #2041 the report-only invariant perdiem_disbursed_on_retracted_placement
(craig-manage invariants) names both. Correct each row with a payment adjustment (#1078), never a void. When a
submitted or accepted claim covers the row, the adjustment’s approval is refused (409 claimed-payment-frozen, #1357):
that post-claim correction is the amendment vehicle, a DFCS decision (#1073).
Money disbursed for days after a placement’s end (#3199). When a placement ends, craig-financial settles only its
undisbursed per-diems to the last paid day. A per-diem already issued or cleared stays as it is, including the days it
paid after the end. The report-only invariant perdiem_disbursed_past_placement_end (craig-manage invariants) names
each one, with the placement’s last paid day and how many of the row’s own days come after it; correct the row with a
payment adjustment, as above. It judges only endings consumed since the migration 20261202140000_termination_last_paid_day (ADDITIVE, no
floor bump, rollback by N-1 images alone): an earlier ending has no recorded last paid day.
#2041’s craig-financial migration 20261015140000_retracted_perdiem_reconciliation is ADDITIVE with no floor bump:
roll every craig-financial replica as usual, and roll back with N−1 images alone. It backfills retracted_at from
event_inbox for each tombstone a retraction wrote. It cannot recover an ending-then-retraction consumed before it, an
inbox row already pruned, a retraction or replacement an N−1 replica consumes during the roll, or any replacement link.
Once no N−1 replica is alive, repair those by hand from craig-placement:
-
On
craig_placement:SELECT id FROM placements WHERE status = 'retracted'andSELECT id, replaces_placement_id FROM placements WHERE replaces_placement_id IS NOT NULL. -
On
craig_financial:UPDATE placement_terminations SET retracted_at = now() WHERE placement_id = ANY(<retracted ids>) AND retracted_at IS NULL, then oneINSERT INTO placement_replacements (placement_id, replaces_placement_id) VALUES (…) ON CONFLICT (placement_id) DO NOTHINGper replacement.
A retracted id with no tombstone in craig-financial was never consumed: that is the U5 rollback case above, not this repair.
U6a — the exit readable and the guardianship handoff (#2021)
U6a makes a removal episode’s exit readable by the fleet. craig-placement publishes placement.episode_exited on every
exit record, correction and retraction and on the historical episode (an episode retract publishes none). The
subsidy-eligibility read gains the additive episode_exit { exit_on, exit_reason } | null. The report-only invariant
guardianship_ending_without_exit lists every episode whose latest effective arrangement ended guardianship without a
matching guardianship exit. craig-financial’s #1070 guardianship WARN arms move from placement.ended to the new event
(ADR-056’s 2026-09-25 #2021 amendment), and craig-web’s one-step handoff records the guardianship exit. There is no
migration and no floor bump. Per environment, in this order:
-
Roll craig-security first. It gains the
placement.episode_exitedarm (update,removal_episode). A pre-U6a craig-security drops nothing: it records the key by the raw split, withepisode_idalready resolved by theplacement.episode_resource family. -
Roll craig-financial, EVERY replica. It binds
placement.episode_exited. Thecraig-financial.eventsqueue is shared and bind-only: the first U6a replica binds the key for the whole fleet, and an N−1 replica still running consumes it with no arm and drops it. No U5 craig-financial replica may be alive when placement rolls. Itsplacement.endedarms stop warning forguardianshipandleft_careendings. It decodesepisode_exitleniently (absent from a U5 placement = null) and does not read it yet (U6b does). Window: from this step until placement rolls, NO guardianship WARN fires, because a U5 placement publishes noplacement.episode_exited. The arms are log-only and no money moves, so the window is accepted. -
Roll craig-placement. It serves
episode_exit, publishes the event and carries the invariant. No migration and no floor bump, so replicas roll in place. -
Roll craig-web. Its one-step handoff records the
guardianshipexit. An older craig-web’s handoff records none, and the invariant flags each such row until a worker records the exit. -
craig-reporting deploys nothing (its change is a test only); craig-cli is unchanged.
-
U6b gate. Run
craig-manage invariants --service craig-placementagainst the environment. U6b rolls only whenguardianship_ending_without_exitis EMPTY. Repair is truthful: record the guardianship exit at the arrangement’s end instant, or correct the live exit to it. From U6a, aplacement.endedcarryingleft_careraises no WARN (the U4 section’sleft_caresentence holds for U4 and U5 fleets only); the exit’s arm raises the withdraw WARN on a non-guardianship exit.
Rollback. Images only. craig-web and craig-placement go back to U5 in either order. craig-financial goes back only
AFTER craig-placement: a U5 craig-financial drops placement.episode_exited and restores the guardianship arms on
placement.ended. craig-security may stay at U6a.
Limitation. A guardianship ending with no exit raises no craig-financial WARN. The invariant is its detector: every plain guardianship end (only the one-step handoff records the exit) and every handoff whose exit act was refused after the end leaves such a row until a worker records the exit.
U6b — the witness moves (#2022)
U6b moves craig-financial’s guardianship witness — the SG/NRSG activation and the ERR guardianship_finalized
termination — from the placement’s end_reason to the removal episode’s exit (ADR-056’s #2022 amendment). The anchoring
placement must be ended, its subsidy-eligibility read must serve episode_exit with exit_reason = guardianship, and
its ended_on must equal exit_on, which becomes the transfer date. craig-placement’s subsidy-eligibility read, with
as_of absent, dates its caregivers at exit_on whenever it serves episode_exit. There is no migration and no floor
bump. Per environment, in this order:
-
Gate — every craig-web at U6a. An older craig-web’s one-step handoff ends the arrangement without recording the exit, and U6b’s termination witness then refuses its ERR step after the irreversible end.
-
Gate —
guardianship_ending_without_exitis EMPTY. Runcraig-manage invariants --service craig-placementagainst- the environment and STOP while its `craig-placement
-
guardianship_ending_without_exit` line reads
FAIL. The command exits non-zero when ANY craig-placement invariant is violated, so read the named line, not the exit code. Repair each row truthfully and re-run until that line readsOK: record theguardianshipexit at the arrangement’sended_at, or correct the live exit to it. The web exit form is date-only and lands on noon UTC of its date (clamped to now while that noon is still ahead). An arrangement whoseended_atis another instant — a same-morning one-step handoff whose exit act was refused, or a historical record entered the same morning on the web or at any instant through the CLI — is repaired withcraig placement episode exit record <episode-id> --exit-at <ended_at> --exit-reason guardianship, or withcraig placement episode exit correct <episode-id> --row-id <exit_row_id>and the same two flags. Run this gate from the U6b release’s tree: #2023 (U6c) retired the invariant, so a later checkout does not carry it.
-
Roll craig-financial, EVERY replica (the witness). Every row the gate cleared passes both the U6a and the U6b witness, at the same transfer date, so mixed replicas agree on it.
-
Roll craig-placement (the evidence date). Replicas roll in place. On every row the U6b witness admits,
exit_on == ended_on, so the caregivers it reads are the same on either side of this step. -
craig-web’s reworded guidance texts are true under U6a and U6b, so craig-web rolls in any order. craig-security, craig-reporting and craig-cli are unchanged.
The gate cannot see a pending SG/NRSG anchored on an arrangement that is NOT its episode’s latest one. U6b refuses that activation truthfully (the child did not leave care from it): correct the episode’s arrangements, or withdraw the agreement.
Rollback. Images only: craig-placement FIRST, then craig-financial. A U6a craig-financial derives the transfer from
ended_on and must not meet a U6b craig-placement that dates caregivers at a different exit_on. Every agreement U6b
activated stores guardianship_transfer_on = exit_on = ended_on, the same date a U6a witness derives from ended_on.
Devstack. A fresh seed writes no guardianship ending, so the gate is EMPTY by construction; a devstack that ran
U6a-era suites holds flagged rows — cargo xtask dev reseed.
U6c — the end-reason narrowing (#2023)
U6c removes the six exit tokens (reunification, adoption, aging_out, guardianship, emancipation, death)
from the placement end reason; the reason a child left care lives only on the episode’s exit. craig-placement’s
migration 20260926120000_end_reason_narrowing.sql rewrites, audited, each exit-token end reason on an episode’s latest
effective arrangement under a live exit to left_care, refuses on every other exit-token row (retracted rows included),
narrows the CHECK and bumps the floor. craig-web’s end form states a guardianship transfer as Left care with the
guardianship box. Per environment, in this order:
-
Gate — every craig-financial at U6b, drained. A U6a financial still witnesses
end_reason = guardianship: after the rewrite it would refuse every guardianship activation andguardianship_finalizedtermination. -
Pre-flight (recommended) — what the guard will refuse. Run, read-only, against craig_placement:
WITH latest AS ( SELECT DISTINCT ON (p.episode_id) p.id FROM placements p WHERE p.activated_at IS NOT NULL AND p.status <> 'retracted' ORDER BY p.episode_id, p.started_at DESC, p.id DESC) SELECT p.id, p.episode_id, p.status, p.end_reason FROM placements p WHERE p.end_reason IN ('reunification', 'adoption', 'aging_out', 'guardianship', 'emancipation', 'death') AND NOT (p.status = 'ended' AND p.id IN (SELECT id FROM latest) AND EXISTS (SELECT 1 FROM removal_episodes e JOIN exit_responses x ON x.episode_id = e.id AND x.retired_at IS NULL WHERE e.id = p.episode_id AND e.retired_at IS NULL));Each row listed stops the migration. A latest arrangement whose episode holds no live exit is repaired by recording the exit truthfully (the web exit form; or
craig placement episode exit record <episode-id> --exit-at <ended_at> --exit-reason <reason>for a non-noon instant). A non-latest or a retracted exit-token row has NO API repair, since a retract keepsend_reason: a disposable environment reseeds (cargo xtask dev reseed); anything else needs a planned data migration first. The migration itself is the authority: it runs in one transaction, refuses naming the count, and applies nothing on a refusal. -
Take the craig_placement backup / PITR mark.
-
Roll craig-placement, EVERY replica replaced before traffic. The migration takes a SHARE lock on the three tables for its run (bounded by a 10 s lock wait; a timeout aborts it cleanly, then rerun). Its floor bump is LAST: an N−1 craig-placement must not serve, because it admits the six tokens and would meet the narrowed CHECK as a 500. On success every rewritten arrangement has a
placement_end_reason_rewritesrow. -
Roll craig-web. Until it rolls, an older craig-web’s end form and one-step handoff cannot write an exit token (placement answers 400, flashed verbatim), and its historical form’s exit token is refused 422. Its Left care end runs no guardianship check and offers no one-step handoff: keep the window short, or hold guardianship endings until craig-web rolls.
-
Roll craig-financial (any time after craig-placement). Only log text changes: A and D are reworded, keeping their leading clauses
active ERR agreement anchored to/pending guardianship agreement ready to ACTIVATE(re-point any alert keyed on the rest); a replayed pre-U6cplacement.endedcarryingguardianshipraises the reason-blind B/E WARNs. -
craig-cli and craig-reporting ship with the workspace; craig-security is unchanged.
Rollback. N−1 images AND a restore. Roll craig-web back FIRST (a U6b web decodes every row a U6c DB holds), then restore craig_placement and roll craig-placement to its U6b image; craig-financial in any order (log-only). NEVER serve a U6c craig-web against a restored pre-U6c craig_placement: its placement list and detail pages fail on the first exit-token row.
Devstack. The -- devstack: wipe-before-apply marker wipes craig_placement and reseeds it. The seed writes no exit
token.
U7 — the goal drop (#2024)
U7 retires the placement permanency goal: a child’s plan lives on craig-cases' permanency_plans (ADR-078 D4).
craig-placement’s migration 20260926180000_placement_goal_drop.sql drops placements.permanency_goal, whose CHECK
goes with it, without moving a value. It has no refuse-on-data guard, and it bumps the floor as its last statement
(mandatory: the drop is destructive, ADR-063 D3). The governed token placements.permanency_goal leaves the
foster_home_portal surface, which keeps six tokens. Per environment, in this order:
-
Roll craig-web and craig-portal. craig-web’s placement list, detail and create form lose the goal. Roll it first: the placement create and update ignore fields they do not know, so after craig-placement rolls, an older craig-web’s goal would be silently dropped. The portal never rendered the goal label; its position is not load-bearing.
-
Pre-flight (optional) — what the drop discards. Run, read-only, against craig_placement:
SELECT count(*) FROM placements WHERE permanency_goal IS NOT NULL;The restore below is the only way back to those values. -
Take the craig_placement backup / PITR mark.
-
Roll craig-placement, EVERY replica replaced before traffic. The migration waits at most 10 s for its lock (a timeout aborts it cleanly; rerun it). Its floor bump is LAST: an N−1 craig-placement selects and writes the dropped column, so every placement read it serves fails once the column is gone. The floor stops a restarting N−1 replica, not a running one. The jurisdiction layer’s
field_ownership.tomlloses the goal line and changes together with the image (until U4, #2955, it rode the image, and a customCRAIG_PLACEMENT__RULESETS_DIRwas replaced with it): craig-placement refuses to boot on a roster mismatch in either direction. A create first sent before this step and retried after it with the sameclient_request_idanswers409 idempotency-conflict(the create intent changed). -
craig-cli and craig-reporting ship with the workspace; an older craig-cli’s
--permanency-goalis ignored by the new craig-placement. craig-security and craig-financial are unchanged, and no ruleset is promoted.
Rollback. N−1 images AND a restore. Restore craig_placement, then roll craig-placement to its U6c image. Restore
the seven-token field_ownership.toml along with that image: since U4 (#2955) by pinning the jurisdiction layer back
to the commit that carries it, and until U4 in a custom rulesets directory. craig-web and
craig-portal may stay at U7: they send and read no goal.
Devstack. The migration carries no wipe marker and the seed writes no goal: no reseed, no bless.
P-B2 U2 — providers (#2055)
U2 makes a foster-home row either a family home or a congregate facility. foster_homes.provider_kind
(family_home | congregate_facility, NOT NULL, no default, immutable by trigger; every existing row family_home) is
required on the create, and license_type is nullable: present iff family_home. The create refuses a missing or
unknown kind (422, the body extractor’s data error) and a mismatched license type (400 required-field-missing for a
family home without one / structural-mismatch for a congregate provider with one); the update refuses a kind change and a
license_type on a congregate provider (400 structural-mismatch). A congregate provider takes no caregiver binding and
records no training (both 422). Matching requires the provider_kind it searches (400 structural-mismatch when
absent). Its one migration, 20260927100000_foster_home_provider_kind, WIDENS the schema and ends with a voluntary
schema_compat_floor bump. Per environment, in this order:
-
Roll craig-placement, every replica replaced before traffic. The migration applies on boot through the migration gates. An N−1 craig-placement cannot insert a home (it omits the NOT NULL column) or decode a NULL
license_type, so no mixed-version window: the floor stops a restarting N−1 replica, not a running one. -
Roll craig-web, then craig-cli. Accepted window until both roll: N−1 craig-web and craig-cli home creates refuse with 422 (missing
provider_kind; the web shows the generic failed flash), and their matching searches refuse with 400structural-mismatch(the web shows its problem detail on the form). NO congregate provider may be created in the window — an N−1 craig-web fails to decode a NULLlicense_typeon the home list, matching and the placement picker. -
craig-financial, craig-portal and craig-security deploy nothing.
Devstack. The migration has no wipe marker, so it takes the cached-rebuild path. The seed changes (it derives one
congregate provider twin per home a residential arrangement names, and those arrangements name the twin), so reseed:
a merely migrated devstack has every home family_home and no twins.
Rollback. N−1 images AND a database restore. Take the craig_placement backup / PITR mark before step 1. To roll back, restore that backup, then roll craig-placement to its N−1 image, then craig-web and craig-cli.
P-B2 U3 — the setting vocabulary (#2056)
U3 re-cuts placements.placement_type to foster_family_home plus the 14 federal (e)(4) tokens verbatim
(trial_home_visit becomes placed_at_home; foster_care, kinship, therapeutic, group_home, residential and
pre_adoptive remain rate classes only), adds the six (e)(3) ffh_type_* flags to a family row and the generated
(e)(2) foster_family_home, and enforces the setting identity (a congregate row names a congregate_facility, a
non-caregiving row names no home). placement.activated types placement_type and gains ffh_types;
the strict placement.recorded gains placement_type and ffh_types. Its one migration,
20260927120000_placement_setting_vocabulary, has no crosswalk: its guard refuses ANY existing placements row, and
it bumps schema_compat_floor to 20260927120000. Per environment, in this order:
-
Roll craig-web (and craig-cli beside it).
-
Roll craig-financial. It has no migration —
payment_typekeeps its tokens, the D5 rate class maps onto them — but it must decode the strictplacement.recordedwith its new keys before placement emits one. -
Roll craig-placement, every replica replaced before traffic. The migration applies on boot through the migration gates; the floor stops a restarting N−1 replica, not a running one.
-
craig-security deploys nothing: it stores placement payloads verbatim and maps both events by type, and U3 adds no routing key.
Neither web / placement order has a working window: a new craig-web sends settings and ffh_types an N−1
craig-placement refuses, and an N−1 craig-web cannot decode a new row. It is accepted because U3 is a devstack wipe and
the guard refuses any placements row elsewhere.
Devstack. The guard refuses the existing seeded rows, so wipe and reseed: cargo xtask dev reseed.
Rollback. N−1 images AND a database restore. Take the craig_placement backup / PITR mark before step 1 (financial has no migration). To roll back, restore that backup, then roll craig-placement to its N−1 image, then craig-financial, then craig-web and craig-cli.
P-B2 U4 — non-conventional rows (#2057)
U4 lets the six non-caregiving settings activate without the craig-cases placement-facts read and without a craig-rules
consult (their #1724 provenance pair stays null), and stops craig-financial staging financial.payment_generation_skipped
(missing_foster_home) for them. No migration, no schema_compat_floor bump, no wire or payload change. Per
environment:
-
Roll craig-financial first (a rolling replacement is fine). Until every replica is replaced, an N−1 replica still stages
missing_foster_homefor a non-caregiving activation and craig-reporting queues ano_payment_activationwarning (fieldfoster_home_id) for it — a false positive; resolve it (PUT /v1/reporting/quality/issues/{id}/resolve). The same holds for any such warning queued between the U3 and U4 financial rolls. -
Roll craig-placement. Until it rolls, a non-caregiving activation still runs the hop and the child-only consult (and is refused while craig-rules or craig-cases is down); afterwards it runs neither.
craig-web, craig-cli, craig-reporting, craig-security and craig-portal deploy nothing.
Devstack. No reseed.
Rollback. The N−1 images in reverse order (placement, then financial); no data to restore — a row U4 activated keeps its null pair, as a planned or historical row does.
P-B2 U5 — kinship households (#2058)
U5 gives every home-less family arrangement a kinship household (kinship_households, the case-less setting identity;
Data Model: Placement § Kinship households) and re-keys caregiver
bindings from placement_id to kinship_household_id. Its one migration, 20260928120000_kinship_households, runs in
place (no wipe): it mints one household per existing home-less foster_family_home row, of any status (the household’s
id is the row’s), points the row and its bindings at it, rewrites the portal queue’s unit_kind placement to
kinship_household, adds the binding overlap EXCLUDE, re-cuts chk_placements_setting_identity, and bumps
schema_compat_floor to 20260928120000. Its guard runs first and refuses the migration, naming each count, when any
of these holds:
-
a caregiver binding keys a placement that is not a home-less
foster_family_homerow; -
a home-less
foster_family_homerow has a NULLadmin_unit— heal it withcraig-manage backfill-assignments, then restart craig-placement; -
a home-less
foster_family_homerow’screated_byis not a UUID; -
two bindings of one person on one unit overlap (bindings are never deleted, so this has no in-place repair).
For the first, third and fourth, on a disposable environment, reseed: cargo xtask dev reseed.
Per environment, in this order:
-
Roll craig-portal and craig-financial (either order; rolling replacement is fine). financial reads the new required
child_arrangement_ids/payment_arrangement_idsof the authoritative bindings read; craig-portal reads thekinship_householdunit kind. -
Roll craig-placement, every replica replaced before traffic. The guard and the migration apply on boot through the migration gates; the floor stops a restarting N−1 replica, not a running one.
-
Roll craig-web (and craig-cli beside it).
-
Promote
{j}-authz-foster_home_caregiver(georgia 1.2.0, texas 1.3.0), any time. Description only, rows unchanged, so authorization does not move and the step is order-free; without itcraig rules drift --rulesets target/config/layers --strictreports both filesbehind. The two-step promote per file (×2):craig rules promote target/config/layers/georgia/georgia-authz-foster_home_caregiver.json --reason '#2058 description only' --profile … [--bearer-token …], read the canary report, then run the printed execute line with--confirm-preview <id>AND--acknowledged-thin-corpus(every-authz-promote is thin-corpus); the same fortarget/config/layers/texas/texas-authz-foster_home_caregiver.json.
The windows: between the financial and placement rolls every portal payments read answers 503
portal-bindings-unavailable; between the craig-portal and placement rolls a caregiver bound to a kinship household sees
the portal’s shape error; between the placement and craig-web rolls the caregivers panel on a kinship placement refuses
(422 / 400). All clear when the last service rolls.
craig-security deploys nothing: its generic split resolves no resource id for a placement.caregiver_bound /
caregiver_ended event, which no longer names a placement_id (#1877).
Devstack. The migration applies in place, but the seed’s identity changes, so reseed: cargo xtask dev reseed.
Rollback. N−1 images AND a database restore: an N−1 craig-placement writes caregiver_bindings.placement_id and
inserts a home-less family row with no household, and the floor refuses it against the U5 schema. Take the
craig_placement backup / PITR mark before step 2. To roll back, restore that backup, then roll craig-placement to its
N−1 image, then craig-financial and craig-portal, then craig-web and craig-cli.
P-B2 U6 — the residence run (#2059)
U6 derives each caregiving arrangement’s residence run at read time and serves it on the subsidy-eligibility read as
residence; episode_exit is also served for an earlier arrangement of the same run. craig-financial’s guardianship witness
then requires the run’s end to equal the guardianship exit day, its residence floor measures from the run’s first day, and an
SG / NRSG create refuses a non-caregiving anchor (422 subsidy-anchor-not-caregiving). No migration, no floor, no event. Per
environment, in this order:
-
Roll craig-placement (rolling). An N−1 craig-financial ignores
residence(its decode is lenient) and applies the old anchor-end rule to the widenedepisode_exit. An anchor that newly sees an exit is refused "guardianship exit is dated" unless it ended on the exit day, and the new financial admits that case too, so the widened exit admits nothing the new financial refuses. The N−1 financial still has no caregiving refusal: it can activate an SG / NRSG (or accept an ERRguardianship_finalizedtermination) anchored on a non-caregiving arrangement that is its episode’s latest, which the new financial refuses (400 "no residence run"); for SG / NRSG see Agreements on a non-caregiving anchor below. -
Roll craig-financial (rolling).
Wrong order. A new craig-financial reading an N−1 craig-placement decodes no residence and refuses EVERY SG / NRSG
activation and ERR guardianship_finalized termination (400 "no residence run") until placement rolls.
Agreements on a non-caregiving anchor. From the U3 roll (the vocabulary lets a non-caregiving arrangement activate) until craig-financial rolls here, an SG / NRSG create could anchor on one, and an N−1 craig-financial could activate it when that arrangement was its episode’s latest and ended on the guardianship exit day. Once craig-financial rolls, a pending one cannot activate (the projection serves it no residence run): withdraw or decline it and enroll again on the child’s caregiving arrangement. One an N−1 craig-financial already activated stays active — review it.
Invariants. The report-only sg_residence_floor is gone; drop it from any external invariant schedule.
Rollback. The reverse: craig-financial first (an N−1 financial reads the new body), then craig-placement. No data to restore.
P-B3 U1 — arrangement facts (#2080)
U1 adds the arrangement’s own AFCARS facts, (e)(5)–(e)(8) and (i)(5)–(i)(8), as sixteen nullable placements columns
(Arrangement facts). The create and the historical record REQUIRE every
fact key (present, null = unanswered); the placements PUT takes an optional arrangement_facts.
Migration. 20260929100000_arrangement_facts.sql is additive: every new column is NULL on every existing row, and NULL
satisfies every new CHECK, so it has no refuse-on-data guard and no floor bump. It applies in place.
Per environment, in this order:
-
Roll craig-placement (rolling is fine).
-
Roll craig-web and craig-cli.
The window. Until craig-web and craig-cli roll, their create and historical bodies lack the fact keys and are refused
422 validation-failed; nothing is erased.
Idempotency. A claim minted before U1 and replayed with a post-U1 body is 409 idempotency-conflict (the intents are
PlacementIntent, then named PlacementIntentV7, and HistoricalPlacementIntentV4). A pre-U1 retry body is 422 before the claim is read.
Rollback. craig-web and craig-cli FIRST, then craig-placement. An N−1 craig-placement refuses a U1 historical body
(its HistoricalPlacementRequest is deny_unknown_fields) and silently drops the facts of a U1 create
(CreatePlacementRequest is not strict). No restore: the columns stay, unread.
Devstack. cargo xtask dev reseed for the seeded facts.
P-B3 U2 — removal facts (#2081)
U2 adds the removal’s own AFCARS facts, (d)(3), (d)(4), (i)(1) and (i)(4), as forty-three nullable removal_responses
columns (Removal facts). The episode open, the historical episode and the
removal correction REQUIRE every answer key (present, null = unanswered); a correction is the complete state.
Migration. 20260929110000_removal_facts.sql is additive: every new column is NULL on every existing row, and NULL
satisfies every new CHECK, so it has no refuse-on-data guard, and it ends with a voluntary schema_compat_floor bump to
20260929110000: an N−1 craig-placement’s removal correction would write NULL over every answer.
Per environment, in this order:
-
Roll craig-placement, replacing EVERY replica before traffic (the floor is read only at boot; an N−1 replica refuses to start against it).
-
Roll craig-web and craig-cli.
The window. Until craig-web and craig-cli roll, their episode open and removal correction bodies (and the CLI’s
historical episode) lack the answer keys and are refused 422 validation-failed; nothing is erased.
Idempotency. A claim minted before U2 and replayed with a post-U2 body is 409 idempotency-conflict (the intents are
OpenEpisodeIntentV2, CorrectRemovalIntentV2 and HistoricalEpisodeIntentV2). A pre-U2 retry body is 422 before the
claim is read.
Rollback. craig-web and craig-cli FIRST, then N−1 craig-placement images AND a database restore. The floor refuses an N−1 craig-placement against the U2 schema. Take the operator’s craig_placement backup / PITR mark before step 1. To roll back, roll craig-web and craig-cli to N−1, restore that backup, then roll craig-placement to its N−1 image.
Devstack. cargo xtask dev reseed for the seeded (d)(3) / (d)(4).
P-B3 U3 — trafficking (#2082)
U3 adds the episode’s AFCARS trafficking facts, (d)(5)–(d)(6)(ii), as two event ledgers:
episode_trafficking_statements (a statement dated stated_on holds five nullable answers) and
trafficking_law_enforcement_reports (one row per report) (Trafficking). The
acts are new routes: POST|GET /v1/placement/episodes/{id}/trafficking and …/trafficking-reports, each with
…/{row_id}/corrections and …/{row_id}/retract. An episode retract also retires the episode’s live trafficking rows.
Migration. 20260930100000_trafficking_ledgers.sql is additive: two new tables, the replaced
check_episode_current_instants() body, and its constraint trigger on both new tables. No existing row changes, so it has
no refuse-on-data guard. It ends with a voluntary schema_compat_floor bump to 20260930100000: an N−1 craig-placement’s
episode retract does not retire the trafficking rows, so on an episode holding one it is REFUSED at COMMIT by the
replaced trigger (a redacted 500).
Per environment, in this order:
-
Roll craig-placement, replacing EVERY replica before traffic (the floor is read only at boot; an N−1 replica refuses to start against it).
-
Roll craig-web and craig-cli.
craig-security and craig-reporting deploy nothing. The placement.episode_facts_changed arm is ledger-blind: the two
new ledger tokens ride the existing routing key, and no consumer acts on the ledger.
The window. No existing body changes, so there is no 422 window: an N−1 craig-web shows no trafficking panel, and an N−1
craig-cli has no trafficking subcommand.
Idempotency. The acts claim new scopes only; U3 replaces no intent, so no pre-U3 claim can conflict.
Rollback. craig-web and craig-cli FIRST, then N−1 craig-placement images AND a database restore. The floor refuses an N−1 craig-placement against the U3 schema. Take the operator’s craig_placement backup / PITR mark before step 1. To roll back, roll craig-web and craig-cli to N−1, restore that backup, then roll craig-placement to its N−1 image.
Devstack. No reseed: U3 changes no seed.
P-B3 U4 — the adoption / guardianship exit (#2083)
U4 adds the adoption / guardianship exit’s own AFCARS facts, (h) less (h)(14) and (i)(10)–(i)(13), as twenty-one
nullable exit_responses columns, two of them adoptive-parent slots naming craig-cases persons
(The adoption / guardianship exit). The exit, the exit correction and the
historical episode REQUIRE every exit-answer key (present, null = unanswered; transfer_agency_type stays optional); a
correction is the complete state.
Migration. 20260930120000_adoption_exit_facts.sql is additive: every new column is NULL on every existing row, and
NULL satisfies every new CHECK, so it has no refuse-on-data guard, and it ends with a voluntary schema_compat_floor bump
to 20260930120000: an N−1 craig-placement’s exit correction would write NULL over every answer.
Per environment, in this order:
-
Roll craig-placement, replacing EVERY replica before traffic (the floor is read only at boot; an N−1 replica refuses to start against it).
-
Roll craig-web and craig-cli.
The window. Until craig-web and craig-cli roll, their exit and exit-correction bodies (and the CLI’s historical
episode) lack the exit-answer keys and are refused 422 validation-failed; nothing is erased. The guardianship subsidy’s
one-step chain (craig-web) fails its exit leg the same way in the window.
Idempotency. A claim minted before U4 and replayed with a post-U4 body is 409 idempotency-conflict (the intents are
ExitIntentV2 — the exit and its correction — and HistoricalEpisodeIntentV3). A pre-U4 retry body is 422 before the
claim is read.
craig-cases. A fresh exit, correction or historical episode naming an adoptive parent reads craig-cases' person
projection; while craig-cases is down it is refused 503 person-lookup-unavailable (retry), and a replay still answers.
Rollback. craig-web and craig-cli FIRST, then N−1 craig-placement images AND a database restore. The floor refuses an N−1 craig-placement against the U4 schema. Take the operator’s craig_placement backup / PITR mark before step 1. To roll back, roll craig-web and craig-cli to N−1, restore that backup, then roll craig-placement to its N−1 image.
Devstack. cargo xtask dev reseed for the seeded adoptive parents.
craig-financial, craig-security and craig-reporting deploy nothing.
P-B3 U5 — child facts (#2084)
U5 adds the child’s health and education AFCARS facts
(Child facts: health and education): (b)(9) as the health_assessment visit
flag on health_records, and (b)(10)–(b)(12), (b)(14) on two new per-child window ledgers, child_health_facts and
child_education_facts, with their own routes under /v1/placement/children/{child_id}/health-facts and
…/education-facts. The health create REQUIRES health_assessment (a bool); the health PUT takes it optional (absent =
unchanged).
Migration. 20260930140000_child_facts.sql is additive: two new tables, a new function, and a column whose constant
default (false) satisfies every existing row, so it has no refuse-on-data guard and no floor bump. It applies in place.
Per environment, in this order:
-
Roll craig-placement (rolling is fine).
-
Roll craig-web and craig-cli.
The window. Until craig-cli rolls, an N−1 craig-cli health create lacks health_assessment and is refused 422
validation-failed; nothing is erased. The ledgers are new routes: no N−1 client calls them.
Idempotency. The health create’s intent gained health_assessment (then as HealthIntentV2): a claim minted before U5 and replayed with a post-U5 body
is 409 idempotency-conflict. A pre-U5 retry body is 422 before the claim is read.
Rollback. craig-web and craig-cli FIRST, then craig-placement; no restore. An N−1 craig-placement replica ignores a
current writer’s health_assessment (its CreateHealthRequest is not strict), so a create it serves records false.
The tables and the column stay, unread.
Devstack. cargo xtask dev reseed for the seeded windows and (b)(9) flags.
With U5, placement capture is COMPLETE (AFCARS_CAPTURE_STAGE = LAST_UNIT).
P-B3 U6 — the Tribe’s order of preference (#2085)
U6 adds two nullable child_icwa_facts columns, tribe_order_foster_care i)(5)(v and tribe_order_adoptive
i)(10)(iv (The ICWA ledger). Every icwa-facts record and correction body
REQUIRES both keys (present, null = unanswered). U6 maps no AFCARS key; the stage stays LAST_UNIT.
Migration. craig-cases 20260930150000_tribe_order_of_preference.sql is additive: both columns are NULL on every
existing row, and NULL satisfies both gate CHECKs, so it has no refuse-on-data guard, and it ends with a voluntary
schema_compat_floor bump to 20260930150000: an N−1 craig-cases correction or change would write both answers NULL.
Per environment, in this order:
-
Roll craig-cases, replacing EVERY replica before traffic (the floor is read only at boot; an N−1 replica refuses to start against it).
-
Roll craig-web and craig-cli.
The window. Until craig-web and craig-cli roll, their icwa-facts record and correction bodies lack the two keys and
are refused 422 validation-failed; nothing is erased. A post-U6 craig-web refuses an ICWA form an N−1 replica rendered
(no facts_rev) with the reload flash. Rolled out of order, a post-U6 craig-web in front of an N−1 craig-cases shows the
ICWA panel as "could not load" (it cannot decode a row without the keys); nothing is lost — roll craig-cases.
Idempotency. The child_icwa_facts record and correct claims hash the facts whole: a claim minted before U6 and replayed
with a post-U6 body is 409 idempotency-conflict. A pre-U6 retry body is 422 before the claim is read.
Rollback. craig-web and craig-cli FIRST, then N−1 craig-cases images AND a database restore. The floor refuses an N−1 craig-cases against the U6 schema. Take the operator’s craig_cases backup / PITR mark before step 1. To roll back, roll craig-web and craig-cli to N−1, restore that backup, then roll craig-cases to its N−1 image.
Devstack. None: no seed change; the migration applies on the next cargo xtask dev up.
AFCARS readiness rollout (#2127)
P-D4 U2 — the sealed export (#2177)
U2 seals every AFCARS export at rest under CRAIG_REPORTING_FIELD_ENCRYPTION_KEY (AES-256-GCM-SIV, bound to the
submission, the export attempt and its generated_on); the download opens it and serves the decrypted flat file, and
refuses (a redacted 500, the detail logged) an object that does not open. export_sha256 (column, event, response) stays
the digest of the delivered file. Only a keyless optional deployment stores and serves plaintext. The first keyed
export writes craig_reporting’s crypto_key_lineage row if no generate has; a mismatched key is refused before anything
is claimed. The AFCARS download is buffered, not streamed (the file is one half’s TSV).
Migration. 20261004120000_afcars_export_sealed.sql marks every pending / stored AFCARS export attempt
superseded (a replay of one is refused, nothing written: 409 export-source-changed keyed, 422 keyless) and bumps
schema_compat_floor to 20261004120000: no pre-U2 craig-reporting boots against it.
Per environment, in this order:
-
Stop EVERY craig-reporting replica. Each runs the export-attempt reconciler in process, and the floor is read only at boot — a pre-U2 replica left running would keep claiming plaintext attempts.
-
Run the migration gate (
craig-reporting migrate, § Migration gates). -
Start the U2 image.
-
Re-export each pre-U2 artifact. A pre-U2 export is a plaintext object the U2 download refuses. For every AFCARS submission with an export (
SELECT id FROM afcars_submissions WHERE export_object_key IS NOT NULL), run a fresh export —POST /v1/reporting/afcars/{id}/exportwith no body (every bare POST is a new operation) or, for anapprovedrow, the web Export action (admin; any other status uses the POST): the pointer moves to a sealed artifact; the old object stays on disk (federal evidence). A pointer whose attempt was pruned re-exports too (#2172).
Rollback. Refused below U2 by the floor; recovery is a forward fix (pre-1.0, no production deployment).
Devstack. None required (the devstack is keyed); a pre-U2 export left in a long-lived devstack answers 500 on download
until re-exported, or cargo xtask dev reseed.
craig-cases, craig-placement, craig-financial, craig-security, craig-web and craig-cli deploy nothing.
P-D4 U3 — the readiness record (#2178)
U3’s export finalizer writes one afcars_export_readiness row per winning export: the record the U4 act certifies.
Migration. 20261004130000_afcars_retained_policy_immutable.sql (#2174) and
20261004140000_afcars_export_readiness.sql are additive with no floor bump; apply in place.
P-D4 U4 — the ready_for_transmission act (#2179)
U4 adds the act PUT /v1/reporting/afcars/{id}/ready-for-transmission (authz Approve): it moves an approved AFCARS
submission to the new status ready_for_transmission after re-verifying its current export against the verified AFCARS
surface, stamps who certified which export generation, and stages one audited
reporting.afcars_ready_for_transmission event. The status has no outgoing edge until the delivery program (#1967).
Afterwards the submission’s artifact is frozen: every export of it is refused before anything is built (409
afcars-artifact-frozen), and an in-flight export attempt that lands on it supersedes itself.
Migration. 20261004150000_afcars_ready_for_transmission.sql adds the three nullable columns ready_by, ready_at
and ready_export_generation to afcars_submissions and bumps schema_compat_floor to 20261004150000: no pre-U4
craig-reporting boots against it.
Per environment, in this order:
-
Stop EVERY craig-reporting replica. A pre-U4 replica cannot decode the
ready_for_transmissionstatus and ignores the freeze, and the floor is read only at boot. -
Run the migration gate (
craig-reporting migrate, § Migration gates). -
Start the U4 image.
An export finalized by a pre-U3 craig-reporting has no readiness record: re-export it before the act, or the act answers
409 afcars-export-missing.
Rollback. Refused below U4 by the floor; recovery is a forward fix (pre-1.0, no production deployment).
Devstack. None. No AFCARS surface verifies before #1987, so the act answers 503 afcars-surface-not-ready there.
craig-cases, craig-placement, craig-financial, craig-security (one audit arm, no deploy order), craig-web and craig-cli deploy nothing in a fixed order.
P-D4 U5 — the transmit route retired (#2180)
POST /v1/reporting/afcars/{id}/transmit (a 404 now) and the CLI’s transmit-afcars are removed; an approved AFCARS
submission leaves approved only through the U4 act. No migration and no floor bump. Roll craig-web and craig-cli with
or before craig-reporting: a pre-U5 craig-web’s Transmit button gets 404 from a U5 craig-reporting.
AFCARS 2028 series rollout (#2148)
U2 — the qualified notices, the parent action dates, the Tribe’s order dates (#2004)
U2 adds four nullable child_icwa_facts columns — tribe_notified_before_first_proceeding (2028 (b)(5)(i)),
parent_or_indian_custodian_notified_before_first_proceeding (2028 (b)(5)(iii)), tribe_order_foster_care_on,
tribe_order_adoptive_on (The ICWA ledger) — and retires the unqualified
parent_or_indian_custodian_notified from every wire (the column stays, unread). Every icwa-facts record and correction
body REQUIRES the four keys; an order of preference yes needs its date on every new write. The persons export adds the
four keys to icwa_window and terminated_on / petition_filed_on to each parent_set entry.
Migration. craig-cases 20261011120000_icwa_qualified_notices_and_order_dates.sql is additive: the columns are NULL on
every existing row and NULL satisfies every CHECK (the date gates are one-way, so a stored dateless yes order stays
valid), so it has no refuse-on-data guard and no backfill; it ends with a voluntary schema_compat_floor bump to
20261011120000: an N−1 craig-cases correction or change would write the four answers NULL.
Per environment, in this order:
-
Roll craig-cases, replacing EVERY replica before traffic (the floor is read only at boot).
-
Roll craig-web, craig-cli and craig-reporting.
The window. Until craig-web and craig-cli roll, their icwa-facts bodies lack the four keys and are refused 422
validation-failed; nothing is erased. A post-U2 craig-web refuses an ICWA form an older replica rendered (facts_rev
b3u6) with the reload flash. A post-U2 craig-web in front of an N−1 craig-cases shows the ICWA panel as "could not load"
(it cannot decode a row without the required keys); roll craig-cases. craig-reporting decodes either side’s export rows
(no export row type is strict); the craig-reporting that reads the new fields is #2272’s and later.
Legacy answers. Nothing is backfilled: a child whose notice answers predate U2 reports 2028 (b)(5)(i) and (b)(5)(iii)
blank (counted missing) until a worker re-answers them, and a yes order without its date reports as unknown (#2273),
leaving every (i)(5) / (i)(10) category owed. Re-answer before the first 2029A generate (2029-04-01); a child entering
on or after 2028-10-01 owes (b)(5)(i).
Idempotency. The child_icwa_facts record and correct claims hash the facts whole: a claim minted before U2 and replayed
with a post-U2 body is 409 idempotency-conflict. A pre-U2 retry body is 422 before the claim is read.
Rollback. craig-web, craig-cli and craig-reporting FIRST, then N−1 craig-cases images AND a database restore. Take the operator’s craig_cases backup / PITR mark before step 1.
Devstack. None: no seed change; the migration applies on the next cargo xtask dev up.
IV-E determination inputs cutover (#1719)
#1719 (plan ive-determination-inputs U2) moves the IV-E determination’s inputs into the rulesets. Georgia
georgia-ive-eligibility v3.6 and Texas texas-ive-eligibility v1.8 declare them in metadata.ive, behind a CLOSED
input schema (Rule Set Patterns § metadata.ive). craig-cases serves the surface at
GET /v1/cases/ive-surface. Its act refuses:
-
an act without the rendered
surfaceidentity (400); -
a stale
surfaceidentity (409ive-policy-moved); -
an undeclared, misscoped or ill-typed answer (400
ive-input-not-declared).
craig-web renders the served surface. Both sides break across versions. A closed schema refuses what a pre-#1719 craig-cases or craig-web sends (zen refuses the undeclared key, which surfaces as a 500). A #1719 craig-cases cannot serve a ruleset that lacks the block. So this is a cutover: the images first, then the rulesets.
Prerequisite. craig-rules at #2325 or later (the expect evaluate) on every replica. #1719 itself rolls no
craig-rules image.
Migration. craig-cases 20261012140000_ive_determinations_rule_set_id.sql is additive. It adds a nullable
rule_set_id to ive_determinations, NULL on every existing row. There is no backfill and no schema_compat_floor
bump: an N−1 craig-cases writes the column NULL, as every historic row has it.
Per environment, in this order:
-
Roll craig-cases, then craig-web right after it.
-
Each new craig-cases replica boots the Critical
ive-surface-verifier. -
Until the configured
{j}-ive-eligibilitycarriesmetadata.ive, the surface read and the act answer 503ive-surface-not-ready, detailmetadata-absent. The verifier’s warning log names the defect./readyzis untouched. -
The IV-E tab shows its notice with submit disabled. A form an N−1 craig-web rendered earlier posts without
surface; craig-cases answers 400 before its readiness check, and nothing is recorded.
-
-
Promote the IV-E rulesets once no N−1 craig-cases or craig-web replica remains.
-
Promote each
*-ive-eligibilityfile the environment holds;craig rules drift --rulesets target/config/layers --strictlists them asbehind. The configured jurisdiction’s file is the one that ends the window. -
Use the two-step promote (Rule Set Patterns and Domain Knowledge § Lifecycle: history, promote, rollback, pinning).
-
Within the verifier’s next pass (at most 60 s), the act is accepted and the tab renders the declared inputs.
-
The canary. The preview replays the last 100 IV-E evaluations. Their inputs predate the closed schema: Georgia’s carry
child_in_secondary_school, and Texas’s carry thevpa_*keys andssa_deprivation_evidence. Expect them as candidate errors (✗ evaluation …lines). No rule row moves, so a≠divergence line is NOT expected: if one appears, stop and review it before confirming. A candidate error does not block the promote. A thin-corpus refusal needs--acknowledged-thin-corpus, as for any family.
-
-
Nothing else rolls. craig-rules runs no #1719 code, and the CLI has no IV-E command.
craig rules promote target/config/layers/georgia/georgia-ive-eligibility.json \
--reason '#1719 the declared IV-E surface (v3.6)' --profile <env> [--bearer-token …]
craig rules promote target/config/layers/georgia/georgia-ive-eligibility.json \
--reason '#1719 the declared IV-E surface (v3.6)' --confirm-preview <preview-id> \
--profile <env> [--bearer-token …]
# Texas: the same two invocations with target/config/layers/texas/texas-ive-eligibility.json and '(v1.8)'
The window. Between steps 1 and 2 no IV-E determination can be made (503 ive-surface-not-ready), so keep it short.
-
An N−1 craig-web in front of a #1719 craig-cases posts without
surfaceand gets a 400. That is why craig-web rolls right after craig-cases. -
A #1719 craig-web in front of an N−1 craig-cases finds no surface route and shows the notice.
After the cutover. Every later promotion of an IV-E ruleset makes forms rendered before it stale. Their submit shows
the reload message (409 ive-policy-moved) and records nothing. A lost response is retried from the retry page under
the same request id, so the retry replays the committed act.
Answers change meaning. Booleans are tri-state, and a blank answer is now an absent key. Under Georgia v3.6 a blank
vpa_best_interest_order past day 180 pends instead of failing, and a blank ctw_in_first_order no longer takes its
== false row. Citizenship, Georgia’s countable resources and every removal / judicial finding are answered per child.
Historic acts keep their recorded inputs. A replay of a committed act returns the original, whatever the surface state.
Rollback, the newer side first (the #1986 order above):
-
Return each IV-E ruleset to its pre-#1719 version (Georgia v3.5, Texas v1.7) in one of two ways:
-
re-promote the prior file version from git through the same two-step; or
-
use the lifecycle rollback,
POST /v1/rules/sets/{id}/rollback, with a freshclient_request_id,target_revisionset to the revision the promotion moved FROM,expected_revisionset to the live one, and areason(rulesets § Lifecycle: history, promote, rollback, pinning).The #1719 images then answer
ive-surface-not-ready, never a zen 500. A form rendered before the rollback gets the reload message (409ive-policy-moved) or, once the cached surface is gone, the retry page (503); nothing is recorded.
-
-
Then roll craig-web and craig-cases back to N−1.
Restoring the images first, while a closed schema is live, 500s every act. The migration stays: it is additive, and N−1 ignores the column.
Devstack. cargo xtask dev refresh rebuilds the craig-cases and craig-web images, applies the migration and converges
both rulesets in place (#1118). Historic devstack acts keep their inputs.
Re-verifying a signing receipt (#2201 / ADR-082)
Every signed report leaves a signing receipt in the keyring’s database: the evidence that a registered key signed
that payload. craig-intake-keyring verify-receipt checks that evidence again, for a dispute or an audit. It is a
mode of the keyring binary, so run it from the keyring image at the deployed version:
docker run --rm -e CRAIG_INTAKE_KEYRING__DATABASE_URL -v "$PWD/report.json:/report.json:ro" \
<registry>/craig-intake-keyring:<tag> verify-receipt --jti <uuid> --payload /report.json
-
Inputs.
--jtiis the submission’s single-use id.--payloadis the report JSON as submitted; the keyring never holds it, so it comes from wherever the deployment keeps delivered reports. The database URL is the only setting read. The session is read-only, and the command neither serves nor migrates. -
Output. One line per stored receipt, ending
VALIDorINVALID:with the check that failed. The lines name the signer, so handle the output as you would the key list. -
Exit codes. 0 when every receipt is valid, 1 when any is not, 2 when no receipt is stored for the
jtior the payload cannot be read as JSON. -
Limit. The origin recorded in a passkey’s signed client data is not compared with the WebAuthn policy, which this command does not load.
What each check covers is listed in the keyring page.
Container Deployment
Docker images are built from the multi-stage Dockerfile in the repository root:
# Build all service images
docker build --target craig-rules -t craig-rules:latest .
docker build --target craig-cases -t craig-cases:latest .
docker build --target craig-placement -t craig-placement:latest .
docker build --target craig-exchange -t craig-exchange:latest .
docker build --target craig-financial -t craig-financial:latest .
docker build --target craig-reporting -t craig-reporting:latest .
docker build --target craig-security -t craig-security:latest .
docker build --target craig-intake -t craig-intake:latest .
docker build --target craig-composition -t craig-composition:latest .
docker build --target craig-web -t craig-web:latest .
# Standalone-SHINES profile only (ADR-042 §D8):
docker build --target craig-intake-keyring -t craig-intake-keyring:latest .
Images use Alpine 3.23 as the runtime base for minimal footprint.
A jurisdiction is configuration, not a build (#2956)
No image carries a jurisdiction’s reference data. Each service loads its
jurisdiction and that jurisdiction’s bundle (rates, codes, calendars, theme,
terminology, the outbound trigger matrix) at boot from the layers
CRAIG_CONFIG_SOURCE names
(Configuration Reference § Deployment-Global Variables;
the bundle/ file map), and refuses to
start when the variable is unset, a layer is missing or a bundle file is refused
(ADR-072 § Amendment — #2956).
CRAIGACTIVE_STATE_BUNDLES and CRAIG_<SVC>JURISDICTION are not read; one
left set in a deployment is ignored.
Partner adapters are a jurisdiction’s too: they are the partner modules of its
configuration layer (Partner modules in the configuration
layer). craig-exchange registers the ones the jurisdiction’s
bundle/adapters.toml lists; a name the layer’s modules do not provide refuses
boot. One build of craig-exchange serves every jurisdiction.
Every service container therefore mounts the fetcher’s published tree read-only and starts after the fetcher has published (§ The configuration fetcher). A changed bundle file applies by publishing the layer and restarting the services.
Inbox-conversion deploys are stop-then-start (epic &77, ADR-062)
Each Track A unit (A2–A6) converts one service’s event consumers from
the legacy at-least-once inbox path to the
ADR-062
single-transaction attempt machine. The two implementations must never
run concurrently against one event_inbox table: the legacy path’s
autocommitted claim bypasses the row lock the transactional path
serializes on, reopening the double-execution window mid-rollout.
Deploy those releases with a stop-then-start barrier — compose
recreates the container (the devstack’s single-replica shape already
does this); on Kubernetes set the workload’s update strategy to
Recreate for the conversion release (and back to rolling afterwards
if desired). Pre-1.0 the platform ships single-replica, so this is a
release-note discipline rather than an orchestration change.
The configuration fetcher (#2953 / ADR-087)
ADR-087 moves a deployment’s configuration into signed git
config repositories. craig-config-fetch (tools/craig-config-fetch) is the one component that talks to them: it
fetches each source, verifies the commit against a trust root the deployment holds, and publishes it for the services
to read. Every service that loads configuration reads the tree it publishes.
The rules bootstrap, rules promote and authority-evidence steps in the rollout sections above name a layer’s file
through the view cargo xtask config fetch builds in a CRAIG checkout, target/config/layers/<j>/<file> (a checkout
of the layer’s craig-config-<j> repository serves as well); until U4 (#2955) they named rulesets/<j>/<file> in
CRAIG’s source.
Commands.
-
craig-config-fetch resolvepins each git source’s branch or tag to the commit it names now (git ls-remote; a tag to the commit it peels to) and prints the pinned list on stdout as one line. A rollout runs it once and hands every replica the same list, so the replicas move together. -
craig-config-fetch syncpublishes each git source, pinned or not, and exits 0 when every source is published and 1 when any was refused (after trying every source; 2 for a usage or setup error). It logs to stderr.
Settings (each also a flag: --source, --root, --trust-dir):
| Variable | Meaning |
|---|---|
|
The ordered source list, lowest precedence first, in the one grammar the services read too
(Configuration Reference):
|
|
Where the trees are published ( |
|
The trust roots, mounted from the deployment, never from a config repo. |
What a sync writes. Under CRAIG_CONFIG_ROOT/<name>/: repo.git (the bare fetch cache), one directory per
published commit (<sha>/, a git worktree), current (a relative symlink to the published <sha>),
status.json and sync.lock. Several fetchers may share one root, as replicas' init containers do on a shared
volume: a sync holds an exclusive advisory lock on the source’s sync.lock from its first step until its status is
written, so a second sync of the same source waits, then finds the tree published and reuses it (#3058). The lock
ends with the process that holds it, so the file is never stale; leave it in place. Per source a sync fetches the tracked ref, checks the commit out with git worktree add at
<sha>.tmp, verifies it, renames it to <sha>, writes current.tmp and renames it over current (rename(2), so
a reader sees the old tree or the new one, never a mix). Replaying a sync changes nothing: an existing <sha> tree is
reused once it is checked to be that commit with no change, and it is verified again against today’s trust root.
Old trees are kept, because a service reads through the <sha> path it resolved at boot; the fetcher does not prune
them.
Verification modes (after Flux’s; the default is head for a branch and tag for a tag):
| Mode | What must carry a trusted signature |
|---|---|
|
The commit ( |
|
The annotated tag object ( |
|
Both the tag object and the commit it points at. |
Trust roots. For each source, in CRAIG_CONFIG_TRUST_DIR:
| File | Holds |
|---|---|
|
SSH signers, the |
|
OpenPGP signers, one fingerprint per line ( |
|
The public keys of the fingerprints in |
SSH, OpenPGP or both may be present. The fetcher reads the signer from git’s raw status output and requires it on the
list: the SSH principal ssh-keygen matched, or the VALIDSIG signing-key or primary-key fingerprint. An absent or
empty trust file trusts nobody, and a file with a line the fetcher cannot read is refused whole; the refusal names
the file. For OpenPGP, each sync of a source imports <name>.openpgp.asc into a fresh GNUPGHOME of its own (a
mode-0700 directory under /tmp, removed when the source’s verification ends, after gpgconf --kill all stops
the gpg-agent it started), so the deployment provides no keyring and the image needs no writable one, only a
writable /tmp. The home is under /tmp whatever TMPDIR says: gpg-agent binds its sockets there when the
container has no /run/user/<uid>, and a socket path must fit 108 bytes. Importing a key trusts nothing: a key in the file whose fingerprint is not listed verifies no
commit, and keyring trust levels are never consulted. A <name>.openpgp without its <name>.openpgp.asc refuses
every OpenPGP signer, naming the key file, and so does a key file gpg cannot import. A listed fingerprint whose key
is not in the file refuses the list whole, naming the fingerprint.
Refusal. A refused source keeps its current on the last good tree, the run exits 1 and logs the reason, and
status.json records it:
{
"ok": false,
"sha": "<the commit the sync resolved, or null>",
"reason": "commit <sha>: unsigned: it carries no signature"
}
A successful sync writes "ok": true with the published sha and a null reason. Services read the status at boot
(U1, U4) and refuse a source whose last sync failed and which has no previous good tree.
Credentials. A source URL carrying userinfo (user@, user:token@) is refused, for SSH as well as HTTPS.
Private repositories authenticate through the standard git credential environment: a deploy token through
GIT_ASKPASS or a credential helper in the fetcher’s git config, a mounted deploy key through GIT_SSH_COMMAND or
ssh config. Prompting is off (GIT_TERMINAL_PROMPT=0), so a missing credential fails the sync instead of waiting.
Every git child runs with git’s repository-local variables removed (git rev-parse --local-env-vars; #2964).
The image and the compose one-shot. tools/craig-config-fetch/Dockerfile builds an Alpine image (non-root, uid
10001) carrying git, ssh-keygen and gpg; its bases are digest-pinned and come through BASE_REGISTRY like the root
Dockerfile’s. Build it from the repository root with
`docker build -f tools/craig-config-fetch/Dockerfile -t craig-config-fetch .. The devstack’s docker-compose.yml
declares the craig-config-fetch one-shot: it runs sync over the layers config-sources.lock pins, publishes into
the craig-config named volume at /config and mounts CRAIG_CONFIG_TRUST_HOST_DIR (default ci/config-trust/)
read-only at /trust. Every service that loads configuration (craig-rules, craig-cases and its migration gate,
craig-placement, craig-exchange, craig-financial, craig-reporting, craig-security, craig-composition, craig-intake,
craig-web) and the seed depend on it
(condition: service_completed_successfully), mount the volume read-only and name their layers in
CRAIG_CONFIG_SOURCE with CRAIG_CONFIG_ROOT=/config. In Kubernetes the same image runs as an init container
writing to a volume the service containers mount read-only.
Running the compose stack without xtask
The config-source lists need no xtask and nothing set: each is a committed file under devstack/config-sources/,
and the fetcher and every service that loads configuration read theirs through a service-level env_file: as its
CRAIG_CONFIG_SOURCE (#3143). The key files below are not committed, so a deployment still provides them:
| File | Read by | List |
|---|---|---|
|
|
Every layer |
|
craig-rules, craig-cases (with |
The federal entry, then the georgia entry. |
|
|
The federal entry, then the texas entry. |
The files are generated from config-sources.lock in the source repository, and the merge request that bumps a pin
regenerates them (cargo xtask config env; CI refuses a lock and files that disagree). A deployment of a checkout
therefore fetches exactly the commits that checkout’s lock pins, with no list to derive or copy. Do not edit them; an
environment: entry or a -e for CRAIG_CONFIG_SOURCE on a service overrides its file. A
CRAIG_DEVSTACK_CONFIG_SOURCE or CRAIG_DEVSTACK_CONFIG_SOURCE_<NAME> set by hand for an earlier release is no
longer read; remove it. The files are Compose v2 env_file syntax, which strips the single quotes around each list;
Compose v1, docker run --env-file and kubectl create configmap --from-env-file keep the quotes as part of the
value, so do not reuse the files verbatim with those tools.
The operator inputs that remain are the fetcher’s trust root and the two field-encryption key files. A key file is
gitignored, so a fresh checkout holds neither, and compose refuses to load the project, for every service and
profile, while either env_file: is missing. cargo xtask dev start writes both on a developer machine (ADR-048
§ D5);
a deployment writes them from its own secret store before its first docker compose call:
| Input | Read by | Value |
|---|---|---|
|
|
The host directory holding the trust roots (Trust roots above). Default |
|
craig-cases, |
One line, |
|
craig-reporting |
One line, |
Generate each key once. Write a key file once for a database and keep it: data written under one key does not
decrypt under another, and craig-cases and craig-reporting refuse to boot on the mismatch (the crypto_key_lineage
check), so a re-keyed file strands the encrypted data. xtask keeps the same rule: it reuses an existing valid file and
never re-keys it.
Network and credentials. craig-config-fetch clones each repository named in the lists, so its container needs
outbound HTTPS to them (gitlab.com for the three locked today, which are fetchable anonymously). A deployment that
points a layer at a private repository supplies a git credential environment to the fetcher as Credentials in
The configuration fetcher (#2953 / ADR-087) describes; a URL carrying userinfo is refused.
Health Checks
All services expose three health endpoints (no auth required), aligned with the Kubernetes liveness/readiness convention (Step 6 of platform-stabilization):
| Endpoint | Status | Purpose |
|---|---|---|
|
200 (always, while the process is responsive) |
Kubernetes liveness probe. Failure → restart. Never checks downstream deps — restarting on a transient DB blip is the wrong reaction. |
|
200 when no Critical worker is dead/missing AND DB + MQ report healthy; 503 with
|
Kubernetes readiness probe and load-balancer signal. Failure → remove from
service rotation without restart. Compose |
|
200 with detailed JSON: |
Human/dashboard view. Always 200; the body’s |
Kubernetes probe example
livenessProbe:
httpGet:
path: /livez
port: 8002
initialDelaySeconds: 5
periodSeconds: 10
readinessProbe:
httpGet:
path: /readyz
port: 8002
initialDelaySeconds: 2
periodSeconds: 5
failureThreshold: 3
The identity issuer (craig-security issuer, ADR-085 D2) binds its listener only once its first signing key can sign,
60 s after it publishes the key (#3152). Until then every probe and every request is refused at connect, which an
ingress retries on another replica. A replica that listened during that minute would answer each token request 503
while a load balancer’s readiness view still routed to it. So give the issuer a startup probe that allows a slow first
bind, and keep the liveness probe off until it succeeds:
startupProbe:
httpGet:
path: /livez
port: 8011
periodSeconds: 5
failureThreshold: 30 # 150 s: the 60 s staged lead, boot and a margin
A replica whose first key the registry refused (its 64-key cap, ADR-085 D8) binds at once and stays unready while it retries, as before.
Readiness
Services report ready (/readyz → 200) when:
-
Database migrations have completed
-
JWKS has been fetched from Keycloak
-
The RabbitMQ parent connection AND the confirm-selected publisher channel are open (services with MQ; craig-web omits). The MQ arm reads both (#1235); each subscription owns its own connection, reconnects on loss (#1127) and never gates through this arm
-
The HTTP listener is bound
-
No Critical background worker is dead or missing (#1186 / ADR-061 — Observed workers never gate). The Critical set includes
mq-publisher-channel(#2826), the monitor over the same parent connection and publisher channel, so a dead publisher link fails both the MQ arm and the worker gate, then exits the process
Shutdown & fail-fast exit (#1186 / ADR-061)
A Critical worker death fail-fasts the process: the registry records the death, the
supervisor cancels the process shutdown token, HTTP gets a bounded 20s drain
(HTTP_DRAIN_DEADLINE), workers get a bounded 5s drain (WORKER_DRAIN_DEADLINE —
20s + 5s stays inside k8s’s default 30s termination grace), and the process exits
NONZERO naming the dead worker so the orchestrator restarts it. SIGTERM/SIGINT takes
the same drain path and exits zero. From orchestration’s view the pod leaves rotation
by 503-or-refusal-then-exit: after the cancel, new connections may be refused while
open ones can still see the 503 — a refused probe fails readiness exactly as a 503
does, so no fresh-network-probe-sees-503 guarantee is claimed.
Since #2826 a dead publisher link is one of these deaths. lapin channels close for good,
so a publisher channel or parent connection that leaves the open state would fail every
publish until a restart. The Critical mq-publisher-channel monitor reads both
statuses every 100 ms and dies when either goes down, so the process exits nonzero
naming mq-publisher-channel. A broker restart or failover therefore restarts every
connected service: its subscriptions alone would have reconnected (#1127), but the
publisher channel would not. While the broker is still down, a restarted process fails
its boot-time RabbitMQ connect and exits, and the orchestrator retries it. Events the
dead channel could not publish stay in the outbox: their claims are released, or expire
if the exit outruns the release, and the restarted instance publishes them
(at-least-once, ADR-022).
Ops requirement: run every service under a restart policy that restarts a nonzero
exit. Kubernetes: restartPolicy: Always (the only value a Deployment accepts; a bare
Pod may use OnFailure). Compose: restart: on-failure, unless-stopped or
always. systemd: Restart=on-failure or always. Without one, a fail-fast leaves
the service down until someone starts it.
The devstack compose files are the deliberate exception: they keep the default
restart: "no" so a crashed service stays down loud instead of silently flapping, and
cargo xtask dev start is the remedy.
Worker functional-health alerting (#1231 / ADR-061)
Supervision is HANDLE-liveness: a hung worker, a reconnect-forever supervisor, or a
persistently warn-and-continue loop stays running in /healthz. The
worker_last_success_timestamp_seconds{worker=…} gauge family (meter
craig-worker-health, exported on /metrics like every other instrument) closes
that gap: each instrumented loop records the unix time of its last SUCCESSFUL pass
— failure paths stay silent, so the gauge stales honestly. Metrics-only by
design: nothing here gates /readyz. Like every CRAIG instrument, the family
exports through the OTel → Prometheus bridge on /metrics, which initializes only
when OTEL_EXPORTER_OTLP_ENDPOINT is set (telemetry::init) — stock devstack does
not set it, so the end-to-end export proof lives in craig-common’s
Prometheus-bridge unit test (the #1160 precedent).
Since ADR-068 the pool-saturation hysteresis exports its own alerting gauge —
db_pool_degraded is 1 after 2 consecutive slow acquire probes (>2.5s, half the
5s cliff) and clears after 4 consecutive healthy ones. It deliberately never gates
/readyz (a saturated-but-alive database must not trigger restart flapping); the
alert IS the operator surface:
db_pool_degraded > 0
Alert on staleness relative to the worker’s cadence — 3×cadence is the
recommended floor (it tolerates one missed tick plus jitter without paging):
time() - worker_last_success_timestamp_seconds{worker="outbox"} > 60
worker label |
Cadence | Suggested alert threshold |
|---|---|---|
|
~1 s poll |
> 60 s |
|
hourly sweep ( |
> 3 h |
|
1 h refresh |
> 3 h |
|
configured discovery interval |
> 3× the interval |
|
|
> 6× the sweep period |
|
30 s consumer-liveness tick while a consume session is live (#1321; silent during reconnect backoff) |
> 120 s |
|
configured refresh interval (devstack 15 s; default 300 s) |
> 3× the interval |
|
hourly |
> 3 h |
|
5 min pass (deletes person-index inquiries past their fifteen-minute expiry); beats only on a pass that completed |
> 30 min |
|
5 min pass; beats only on a clean pass |
> 30 min |
|
5 min pass (#1274: heals entity-delete blob halves that never landed — soft-deleted rows still |
> 30 min |
|
configured |
> 3× the interval alerting on max() across replicas (a replica that keeps losing the lease stays silent — the |
|
a look every 60 s, or every |
> 3 min (three looks), alerting on max() across replicas; a firing alert means a collection’s last run failed, or was refused before its partner was called: read the worker’s log line and the collection’s newest transaction |
|
every executor scan — a |
> 60 s |
|
~1 s poll |
> 60 s |
|
configured scan interval (60 s default; absent when Disabled) |
> 3× the interval |
|
configured schedule; EXECUTED runs only — a replica behind a peer-held lease stays silent; since #1937 the generator tick also SKIPS (an info log, no beat) while a |
> 3× the interval, alerting on max() across replicas |
|
at boot, then hourly; beats on every successful pass, whether or not it made a partition |
> 3 h |
|
hourly + jitter; absent when the archive knob is off; on security the tick SKIPS (an info log, no beat) while an |
> 3 h |
|
~1 s poll (knob-gated; absent when |
> 60 s |
|
hourly; EXECUTED passes only (a lock-skip stays silent); absent when
|
> 3 h |
The series is ABSENT until a worker’s first successful pass (an hourly loop exports
nothing for its first interval) — pair the staleness rule with an
absent_over_time(…[3×cadence])-style guard rather than treating boot-time
absence as failure. The retention archiver’s sibling gauge
(archive_last_success_timestamp, ADR-058) predates this family and keeps its own
name (0-at-boot, unlabeled — different semantics, deliberately not aliased). The
engine-level subsidy_sweep_last_success_timestamp_seconds is the second named
exception: it fires for manual AND scheduled runs (lease-winner scoped), a different
signal from the review-sweep scheduler heartbeat that now exists alongside it.
Since #1321 every registered worker beats: subscribers via the 30 s consumer-liveness
tick (beats while a consume session is live — a quiet queue is healthy and keeps
beating; reconnect backoff is silent, so broker-loss staleness alerts honestly), and
the per-service loops at their genuine-success points (lease-skipped scheduler ticks
deliberately do not beat — alert on max() across replicas).
Rules engine counters (#1219)
Beyond the decision-refresh heartbeat above, craig-rules exports (meter
craig-rules-engine):
-
rules_decision_refresh_outcomes_total{outcome=refreshed|removed|evicted|failed}— per-pass reconcile outcomes (the #1188 sweep’s four sets; zero-count outcomes export no series). A nonzeroevictedrate means stored ruleset content stopped compiling (direct-SQL writes — the API pre-validates); sustainedfailedmeans per-name re-probe/fetch/compile failures that never starve the rest of the pass. -
rules_decision_refresh_probe_failures_total— passes whose bulk probe failed outright (nothing reconciled that tick; pairs with the heartbeat staleness alert). -
rules_evaluations_total{outcome=completed|timeout|runtime_error}— zen dispatches by terminal outcome, reusing therule_evaluationsdisposition words. It counts at the DISPATCH boundary, so it approximately tracks the table: a redelivered inbox attempt re-counts, a post-success audit-commit failure counts with no row, and a converged timeout staystimeouthere while its row becomeslate_completed. Infra-class errors (Db/staging/compile/not-found) count nothing. Alert on thetimeout/runtime_errorrate relative tocompleted.
DLQ alerting recommendations (#1205)
The security.dlq.threshold_exceeded event (ADR-022 §D3) is the per-event_type
AUDIT record of a dead-letter burst — it lands in audit_log and pages nobody.
The operator-visible mechanism is THIS rule set over the #1199 dlq_* family
(meter craig-mq-dlq; the same OTEL_EXPORTER_OTLP_ENDPOINT-gated /metrics
export as every other instrument). Scrape scope: the depth gauges and
capture/outcome counters export from craig-security only (the fleet’s one DLQ
consumer, port 8007) — but dlq_handler_panics_total{path="events"|"inbox"}
fires in EVERY craig-mq-consuming service’s handler paths, so the panic rule
needs fleet-wide scrape, not just 8007. The choice — shipped rules, not an event
consumer routing to a paging channel — is recorded in ADR-022 §Amendment #1205.
# Any quarantined capture requires an operator drain (ADR-059 §D7 — the
# tier has NO consumer by design; every publish also logs at error!).
dlq_queue_depth{queue="craig-security.dlq.quarantine"} > 0
# Parking is self-draining at the 10-minute TTL: a nonzero FLOOR across
# 3x the TTL means the replayer is not returning captures (or they
# re-park every cycle — the ~2 h park cap will quarantine them).
min_over_time(dlq_queue_depth{queue="craig-security.dlq.parking"}[30m]) > 0
# The DLQ itself should drain promptly; a sustained floor means the
# consumer is down or its DB writes are refusing.
min_over_time(dlq_queue_depth{queue="craig-security.dlq"}[15m]) > 0
# The metrics ANALOGUE (approximate, not equivalent) of the ADR-022
# section-D3 threshold event. The counter has no event_type label, so
# this is the AGGREGATE 1-hour rate: usually more sensitive (it sums
# across types), but it CAN stay silent when the event fires — the
# event's per-type window also counts divergent-quarantine rows this
# outcome excludes, and the counter undercounts across a
# craig-security restart or a crash between the DB commit and the
# increment. The event's audit_log row is the authoritative
# per-event_type record; this rule is the pager, not the ledger.
increase(dlq_outcomes_total{outcome="recorded"}[1h]) > 10
# Same-token-different-content collisions: investigate immediately.
increase(dlq_outcomes_total{outcome="divergent_quarantined"}[1h]) > 0
# Any handler panic is a code defect, not an outage (#1203).
increase(dlq_handler_panics_total[1h]) > 0
# Staleness guard — check BEFORE trusting a depth value: a stale sample
# timestamp means the sampler is down and dlq_queue_depth is frozen, not
# current (3x the 30 s default sampling cadence).
time() - dlq_depth_last_sample_timestamp > 90
Pair the staleness rule with an absent_over_time(…[3m])-style guard, same as
the worker-health family above: every series is absent until its first sample, so
a never-sampled queue alerts through absence, not staleness. Two outage regimes,
two different rules: during a BROKER outage nothing can publish to parking and
the sampler itself fails (depth frozen) — the staleness/absence guards are what
fire. During a craig-security DB/handler outage longer than the 1-hour window,
the threshold event can stay silent while parking fills — the depth-floor rules
fire there (the gauges are the compensating control, ADR-059 §D9).
Transport security
CRAIG is transport-neutral by design: services do not validate that their DATABASE_URL or RABBITMQ_URL declares TLS at the URL layer. Operators are free to put TLS at whichever layer matches their deployment architecture. Common patterns:
| Pattern | What the operator does |
|---|---|
Direct TLS in URL (self-hosted with TLS-direct) |
Set |
Sidecar mTLS (Kubernetes service mesh — Istio, Linkerd) |
Services connect to |
Managed DB/MQ inside private VPC (AWS RDS + AWS MQ; GCP Cloud SQL; Azure Database) |
Operator chooses: enable per-URL TLS (recommended) with the cloud provider’s CA bundle, OR rely on VPC-perimeter network policies. Both are valid postures. |
Devstack / docker-compose |
No TLS. Containers communicate over the docker bridge network only; never exposed to the outside. Production deploys should never run this pattern. |
What CRAIG does protect (independent of transport):
-
Secrets in process memory zeroize on drop (
FieldEncryptor.key_bytes,WebSession.{access,refresh,id}_token) — see Plan B § F-004 -
Field-level PII encryption (
cases.persons.ssn_last_four,cases.reports.{reporter_*, narrative, children, adults, raw_submission}) — see Plan B § F-001, F-002 -
IP hash salting via per-deployment HMAC secret — see Plan B § F-003
Process-memory + at-rest protection does not require transport TLS; transport TLS is recommended for production but is an operator-environment choice, not a CRAIG enforcement gate.
The certificate authorities an outbound call trusts (#3194)
When a service calls an https:// origin (the identity provider, a partner’s endpoint, the bot-protection verifier),
it verifies the server’s certificate against the trust store of the container it runs in. No root set is compiled
into the binaries. The released images carry Alpine’s ca-certificates-bundle, the public certificate authorities, at
/etc/ssl/certs/ca-certificates.crt, and their build fails if that file is missing or empty.
A deployment whose identity provider or partner gateway presents a certificate from a private certificate authority adds that authority in one of two ways:
-
Set
SSL_CERT_FILEon the service to a PEM file that holds every authority the service must trust. The file replaces the image’s bundle; it does not add to it. A service that also calls public origins needs the public authorities in the same file: the image’s bundle with the private authority appended is such a file.SSL_CERT_DIR, a colon-separated list of directories of certificate files, is read the same way, and the image’s bundle is not read when either variable is set. -
Or derive an image whose
/etc/ssl/certs/ca-certificates.crthas the authority appended.
The store is read when a service builds an HTTP client, which for most calls is once, at boot: restart a service after
changing the file. A store with no certificate authority in it is refused. The service exits at boot, and the error
it prints names the cause (No CA certificates were loaded from the system).
Releases before this one verified against a root set compiled into each binary and did not need the image’s certificates. A deployment that runs CRAIG’s binaries in an image of its own must make sure that image has them.
Database Setup
Each stateful service requires its own PostgreSQL database (craig_intake is optional —
the intake edge is stateless per ADR-017 and never populates it):
CREATE DATABASE craig_cases;
CREATE DATABASE craig_composition;
CREATE DATABASE craig_exchange;
CREATE DATABASE craig_financial;
CREATE DATABASE craig_placement;
CREATE DATABASE craig_reporting;
CREATE DATABASE craig_rules;
CREATE DATABASE craig_security;
Per-service DB roles — migration-owner vs runtime (#1310, ADR-063)
The migration gate is process-mode separation; the privilege boundary behind it is TWO Postgres principals per stateful service (the per-service least-privilege shape the RabbitMQ credentials already follow, #1202):
-
a migration-owner role — owns the database (so migrations, including the trusted
pg_trgmandbtree_gistextensions, apply without superuser; craig_placement’s owner installsbtree_gist, #2018). Used ONLY by the migration gate; every migration-created object, including sqlx’s_sqlx_migrationsledger, is owned by it. -
a runtime role —
CONNECT+USAGEon schemapublic+ table DML through the owner’s default privileges. Used by the serving boot: the verify-only path needsSELECTon_sqlx_migrations+schema_compat_floor(covered by the same grants), and DDL under this role fails with SQLSTATE42501— a compromised serving process can no longer alter the schema.
Per service (names are yours to choose — no privilege the gate enforces depends on them,
#2337 — except craig-security’s, below; devstack uses craig_<svc>_owner /
craig_<svc>_app with password == role name as a PUBLIC dev fixture):
CREATE ROLE cases_owner LOGIN PASSWORD '<from your secret manager>';
CREATE ROLE cases_app LOGIN PASSWORD '<from your secret manager>';
ALTER DATABASE craig_cases OWNER TO cases_owner;
GRANT CONNECT ON DATABASE craig_cases TO cases_app;
-- then, connected to craig_cases:
GRANT USAGE ON SCHEMA public TO cases_app;
ALTER DEFAULT PRIVILEGES FOR ROLE cases_owner IN SCHEMA public
GRANT SELECT, INSERT, UPDATE, DELETE ON TABLES TO cases_app;
Set the default privileges BEFORE the first gate run and every future migration-created
table is DML-accessible to the runtime role with zero per-release grant churn (CRAIG has
no sequences — UUIDv7 keys fleet-wide — so no sequence grants are needed). The gate’s
CRAIG_<SVC>__DATABASE_URL carries the owner DSN; the serving container’s carries the
runtime DSN — same variable NAME, two per-container values (the split is provisioning,
not code).
craig-security’s required names (#2739, ADR-085
§ Amendment — #2739): the one exception to the name-free rule above. ADR-085 D2 grants
distinct, partly column-level privileges and function EXECUTE on craig-security’s identity_
objects to distinct principals, which default privileges and the gate’s ACL-reading hardening
cannot express, so its migrations name the roles in unconditional statements and FAIL when a
named role is absent. Each role is required from the release that introduces it:
-
from #2739 (plan Internal Token Issuer U2):
craig_security_owner, the migrate gate’s login and owner of everyidentity_object, andcraig_security_app, the serving login; -
from U4:
craig_security_issuer(the issuer process) andcraig_security_provisioner.
The names supplement privilege checks: craig-security refuses to boot unless its serving login is
craig_security_app and holds no privilege on an identity_ table, no EXECUTE on
identity_retire_legacy_issuer and no grant option on an identity_ object, directly, through
PUBLIC or through a role membership, and owns (directly or through a membership) neither the
database, the public schema nor an identity_ object. Its
EXECUTE on identity_record_legacy_issuer is granted by the migration and may be revoked (the
switch does, ADR-085 D7); without it craig-security logs a WARN and boots. Roles are
cluster-wide, so two independently credentialed CRAIG installations cannot share one PostgreSQL
cluster under these names.
A deployment whose craig-security roles have other names (here security_owner /
security_app) moves to the canonical ones BEFORE it deploys #2739, on the release it runs:
CREATE ROLE craig_security_owner LOGIN PASSWORD '<from your secret manager>';
CREATE ROLE craig_security_app LOGIN PASSWORD '<from your secret manager>';
ALTER DATABASE craig_security OWNER TO craig_security_owner;
GRANT CONNECT ON DATABASE craig_security TO craig_security_app;
-- then, connected to craig_security:
REASSIGN OWNED BY security_owner TO craig_security_owner;
GRANT USAGE ON SCHEMA public TO craig_security_app;
ALTER DEFAULT PRIVILEGES FOR ROLE craig_security_owner IN SCHEMA public
GRANT SELECT, INSERT, UPDATE, DELETE ON TABLES TO craig_security_app;
GRANT SELECT, INSERT, UPDATE, DELETE ON ALL TABLES IN SCHEMA public TO craig_security_app;
-- only when the identity_ tables already exist (the grant above must not reach them):
REVOKE ALL ON identity_legacy_issuers, identity_legacy_issuer_retirements FROM craig_security_app;
Then point the gate’s CRAIG_SECURITY__DATABASE_URL at craig_security_owner and the serving
one at craig_security_app, redeploy and verify boot.
Rollback keeps the canonical credentials. Once REASSIGN OWNED has run, security_owner owns
nothing in craig_security and holds no grant there (as a non-superuser it cannot even read
_sqlx_migrations), so pointing the DSNs back at the old roles is NOT a rollback: the gate fails.
Roll back by redeploying the prior image with the canonical DSNs, which serve every release. To
restore the old names instead, on a release before #2739 only, reverse the ownership first:
ALTER DATABASE craig_security OWNER TO security_owner;, then, connected to craig_security,
REASSIGN OWNED BY craig_security_owner TO security_owner; and the runtime grants for
security_app (GRANT USAGE ON SCHEMA public …, ALTER DEFAULT PRIVILEGES FOR ROLE
security_owner …, GRANT … ON ALL TABLES …, as above with the old names); only then restore the
old DSNs. From #2739 on, pointing craig-security’s serving DSN at any role but
craig_security_app is not a rollback at all: the service refuses to boot.
Retire the old roles once the canonical ones serve. DROP OWNED BY is destructive: in the
database it runs in, it DROPS every object the role still owns, tables and their rows included,
and revokes the role’s grants and default privileges there; it moves nothing. So in EACH database
where the old roles own or hold anything (craig_security, and any other), connected to it, first
REASSIGN OWNED BY security_owner, security_app TO <that database’s owner role>;
(craig_security_owner in craig_security; the REASSIGN OWNED sharp edge below applies), and
only then DROP OWNED BY security_owner, security_app; there. DROP ROLE security_owner,
security_app; comes last; it fails while either role still owns or holds anything in any
database, which tells you a database was missed.
Runtime-DML hardening (automatic; #1550, #2337): default privileges cannot exclude
individual tables, so the runtime role would otherwise hold DML (not just SELECT) on
tables only the owner may write: the two schema meta-tables (_sqlx_migrations,
schema_compat_floor) and each service’s attestation tables — craig-cases
crypto_field_lineage (the boot-verify marker), crypto_field_rewrites (the
field-scheme rewrite ledger) and crypto_key_lineage (the field-key anchor),
craig-placement placement_end_reason_rewrites (the #2023 end-reason audit). On every
successful verdict, apply and no-op alike, the gate revokes INSERT, UPDATE, DELETE,
TRUNCATE on each from every grantee but the table’s owner, PUBLIC included. It reads
the grantees from the table ACL and the column ACLs themselves, so it works whatever you
named the runtime role, removes a column-level grant along with a table-level one,
re-revokes a grant issued after the migration that created the table, and catches grants
your session could not see through information_schema. SELECT stays: the verify-only
boot reads the meta-tables, the marker and the key anchor, and the rewrite fence’s
trigger reads the ledger as the caller. No manual step remains. The statement it issues
per table and grantee is, for example:
REVOKE INSERT, UPDATE, DELETE, TRUNCATE ON crypto_field_lineage FROM cases_app;
The attestation migrations' own REVOKE … FROM craig_<svc>_app names the devstack role;
under any other name it does nothing, and the gate pass is what protects these tables.
Two consequences of how the pass works:
-
A grant issued between gate runs (an ad-hoc
GRANT, aGRANT … ON ALL TABLES) stands until the next successful gate run (any deploy) revokes it. -
A REVOKE removes grants only. The protection holds while the runtime role is not a superuser, the table owner, a member of the owner role, or a member of
pg_write_all_data: privileges held that way are not grants, and no gate can revoke them. In a shared-credential deployment (the pre-#1310 posture, one role for the gate and serving) the service runs as the table owner, so no REVOKE can protect these tables and the serving process can write them. A serving-boot check that detects a runtime role holding DML on these tables is tracked as #2338.
Rotation: the two principals rotate independently. The owner credential is needed only
during deploys — scope it to the deploy pipeline’s secret store and rotate per release if
desired (ALTER ROLE cases_owner PASSWORD '…' between deploys is invisible to serving).
The runtime credential rotates like any service secret: ALTER ROLE, then roll the
serving pods. Neither rotation touches grants — privileges attach to the role, not the
password.
Cutover from a shared credential (the pre-#1310 posture), per service and rollback-safe:
provision both roles + ALTER DATABASE … OWNER + default privileges as above, then
REASSIGN OWNED BY <old_shared_role> TO <svc>_owner; in each database (existing tables
become owner-owned; grant the runtime role on them once — GRANT SELECT, INSERT, UPDATE,
DELETE ON ALL TABLES IN SCHEMA public TO <svc>_app; — since default privileges only cover
FUTURE objects), flip the gate DSN, verify a deploy, flip the serving DSN, verify boot,
then retire the shared credential. That GRANT … ON ALL TABLES also hands the runtime
role DML on the meta-tables and the attestation tables; the gate run in the verify a
deploy step revokes it again (runtime-DML hardening, above), so until that gate run
succeeds the runtime role can write them, and the order above (verify a deploy before
flipping the serving DSN) is what closes that window. For craig-security the grant must not
reach the identity_ objects (#2739): the gate’s hardening leaves SELECT in place and these
tables allow the runtime role nothing, so once they exist follow the grant with
REVOKE ALL ON identity_legacy_issuers, identity_legacy_issuer_retirements FROM
craig_security_app;, and its runtime role is craig_security_app (required names, above).
Rollback: until REASSIGN OWNED runs, point the DSNs back. After it the shared role owns
nothing in that database (as a non-superuser it cannot even read _sqlx_migrations), so
pointing the DSNs back is not a rollback: keep the new credentials and redeploy the prior image,
or first reverse the ownership (ALTER DATABASE … OWNER TO <old_shared_role>; and, connected to
the database, REASSIGN OWNED BY <svc>_owner TO <old_shared_role>;). craig-security’s serving
DSN can never point back at the shared role or any role but craig_security_app from #2739 on:
the service refuses to boot on it. One
sharp edge: REASSIGN OWNED also reassigns SHARED objects (databases, tablespaces) the
old role owns, cluster-wide — run the per-database ALTER DATABASE … OWNER steps for
ALL services FIRST so no database can transiently land on the wrong service’s owner.
Devstack: devstack/postgres/init.sql provisions all 16 roles (drift-pinned against
the xtask service registry); the craig superuser remains the devstack ADMIN principal
(seed, test-plane scratch/template databases, xtask tooling, pg_isready). Because
init.sql runs only on a fresh data directory, upgrading an existing devstack across
#1310 requires cargo xtask dev reseed. One operational upside: the serving roles are no
longer superuser, so superuser_reserved_connections (3) now genuinely reserves admin
access under connection-pool saturation.
Migration gates (ADR-063, since M3a/#1276)
Schema application is a DEPLOY phase, not a serving-startup side effect. Every service
image doubles as its own migration gate: <binary> migrate (exact argv — nothing else)
connects with ONE env var (CRAIG_<SVC>__DATABASE_URL — the MIGRATION-OWNER DSN since
#1310; serving containers carry the runtime DSN under the same variable name), classifies
the schema against its embedded migration set, and acts by verdict:
-
Exact/Ahead— no-op, exit 0. TheAheadno-op is what makes ROLLBACK safe: an older gate against a newer database does nothing instead of refusing. -
Behind— applies the missing migrations (safe by construction —Behindis reachable only when the applied set is a strict subset of the embedded set). -
Diverged/Dirty/ checksum-mismatch — refuses with a typed message that names the remedy; exit ≠ 0.
The reference compose graph carries the gates automatically: one craig-<svc>-migrate
one-shot per stateful service, sharing the app’s image: + build: via a merged fragment
(a gate can never run a stale :local image the app wasn’t built from), with the app
gating on service_completed_successfully. Locally, cargo xtask migrate apply
[--service <name>] builds + runs the gates and reports per service (partial success is
retry-safe — applied migrations re-verdict as no-ops).
Kubernetes deployments run the gate as a parallelism-1 Job or deploy hook per service before rolling the serving image. A per-pod init container is NOT equivalent — per-pod means N concurrent appliers, which recreates the boot convoy the gate removes. Production uses immutable image tags/digests so gate and app provably run the same binary.
Since M3b, serving boot is VERIFY-ONLY (a pre-1.0 breaking change, CHANGELOG’d): the
gate step is mandatory and serving binaries never issue DDL. Boot verifies BEFORE any
JWKS/RabbitMQ init (craig_api::bootstrap_verified — data plane → schema verdict →
control plane), so an identity-provider or broker outage can never mask a schema refusal.
A Behind database refuses serving startup with the gate named as the remedy; Ahead
(rollback) boots. Rollback support is explicit: back to the newest release whose embedded
migrations reach the schema’s schema_compat_floor (destructive contract migrations bump
it; the verifier refuses binaries older than the floor with "roll forward").
The #648 pair of craig-cases cutovers and the #2375 one each bump the floor and are REFUSE-ON-DATA (the #648 pair: no rewrite without a policy guess — ADR-040’s leave-unpopulated class; #2375: a V3 digest can be neither re-keyed, the field key living outside the database, nor re-derived, the actor not being stored), so they run as stop-the-world windows (scale cases to zero → backup / PITR mark → gate → new image; rollback = N−1 images AND a DB restore):
-
20260912120000_disposition_recut— floor20260912120000; refuses while any allegation or investigation still carries the retiredinconclusivetoken. -
20260913120000_report_source— floor20260913120000; refuses while ANYreports/referralsrow exists (the newNOT NULL report_sourcehas no backfill — the NCANDS source is a captured intake fact the reporter status does not determine). -
20261019120000_report_digest_keyed— floor20261019120000; refuses while anyreportsrow carries areceived_request_hash(#2375: the V3 digest hashed the encrypted report columns as plaintext, and the field key that would re-key it is outside the database; seeded rows carry none). Stop every N−1 replica first: a running one keeps writing V3 digests. Backups taken before the cutover keep the V3 digests, so age them out.
All three files carry the -- devstack: wipe-before-apply — <reason> header annotation
(Local Development): on a disposable stack dev start / dev refresh wipe the volumes and
reseed BEFORE the gate runs (dev status names the reason; cargo xtask dev reseed is the explicit
remedy the guard text names). A real deployment with recorded rows needs an operator-supplied
per-row capture plan before the gate can pass — the guard says so and stops.
The #1941 20260918150000_event_outbox_created_at_id_idx migration ×8 (every outbox-bearing service) is
additive (no floor bump) but builds event_outbox_created_at_id_idx as a plain CREATE INDEX inside the
gate’s transaction: the build holds a SHARE lock on event_outbox for its duration (seconds on a 30-day
table), so every domain write on that service — each stages an outbox row — waits; run the gate in the release
window, not alongside peak traffic (pre-1.0 posture; post-1.0 = CONCURRENTLY outside a transaction).
Field-scheme rewrite fence (#1399 U1): roll the fence release on EVERY craig-cases replica first; never roll below the #1399 U1 fence while a crypto_field_rewrites row is live.
The 20260920120000_crypto_field_rewrites migration is additive (no floor bump, no wipe-before-apply) but
the fence it belongs to is a one-way door — an N−1 (pre-U1) image has none of these guards and would read a
half-rewritten table under the old marker. The fence has four machine-enforced layers, none timing-based:
every craig-db pool connection takes a shared SESSION advisory lock (hashtext('craig:scheme-rewrite')) at
connect, so a booting replica or a migrate gate refuses BY NAME (DbConnectError::RewriteFenceHeld, naming
each holder’s pid / role / application_name) while a craig-cases rewrite-scheme run holds the exclusive
lock (U2b — takeable only when NO participant connection exists), and a reconnect during the run is never
handed out (the acquire times out — fail-closed); a per-statement BEFORE INSERT OR UPDATE trigger on
persons refuses every writer whose role is not the live ledger row’s db_user (SQLSTATE 55000; the
message names persons and #1399 — a writer on the OWNER role shares the row’s db_user and is NOT fenced by
it, and a superuser can disable the trigger: both are fenced by this runbook, not by the statement); the serving boot verify and the gate’s pre_apply step refuse on a live ledger row BEFORE any migration
applies (FieldLineageError::RewriteInProgress, naming table, column, status and started_at). DSN class:
session advisory locks need a DIRECT connection — a transaction-pooling pgbouncer between any service (or the
tool) and Postgres defeats the fence; the DSN must be a direct connection (or session pooling). Privileges: the
runtime role must keep SELECT on crypto_field_rewrites — the trigger is SECURITY INVOKER and reads the ledger
as the caller on EVERY persons INSERT / UPDATE, so a role without it is refused (42501) live row or not; the
gate’s runtime-DML hardening (#2337) revokes only INSERT / UPDATE / DELETE / TRUNCATE. The tool, its quiesce →
--dry-run → run → gate → roll sequence and its key handling: § Field-scheme rewrite, next.
Field-scheme rewrite (#1399)
<craig-cases binary> rewrite-scheme [--dry-run | --abort] is the craig-cases image’s SECOND process mode
(ADR-063 § Amendment — #1399; the marker’s second
owner-role writer, ADR-049 § Amendment — #1399): a
key-bearing, owner-DSN, OFFLINE tool — NOT a deploy phase. It rewrites persons.ssn_last_four between
BlindIndex and Opaque (the allowlist of ONE, craig_cases_fields::resolve::ALLOWLIST; since #1007 a scheme
flip is a per-row re-encryption because the v2 AAD of a BlindIndex base binds its ssn_hmac sibling) and
replaces the crypto_field_lineage marker LAST, by ONE compare-and-swap UPDATE in the completion transaction.
There is no --to: the TARGET is the registry the deployment’s bundle resolves (from CRAIG_CONFIG_SOURCE,
exactly as boot and the gate resolve it), the SOURCE is the marker row — the tool
can only rewrite toward what the next gate / boot verifies. Skipping it is the existing case-2 refusal
(RecordedMismatch), which now names the command.
Argv and environment. argv is exactly rewrite-scheme, rewrite-scheme --dry-run or rewrite-scheme --abort;
anything else is refused BEFORE any environment variable is read ("invoke the tool as exactly <binary>
rewrite-scheme [--dry-run | --abort]`"), and the verb beside `migrate / --print-openapi is a conflicting-modes
refusal (dispatch order: rewrite-scheme → migrate → --print-openapi). The environment is the cases gate’s
plus the key — every variable is read and checked before the first connection:
-
CRAIG_CASES__DATABASE_URL— the migrate gate’s deploy-scoped MIGRATION-OWNER DSN (the one thecraig-cases-migrateone-shot carries; #1310), never the runtime DSN: the runtime role has no INSERT / UPDATE / DELETE oncrypto_field_rewritesorcrypto_field_lineage(the gate revokes them on every successful verdict, whatever the role is named, in a split-role deployment; § Per-service DB roles states the condition). A DIRECT connection (or session pooling) — the fence is session advisory locks; the DSN-class note in § Migration gates applies to the tool exactly as to every participant. -
CRAIG_FIELD_ENCRYPTION_KEY— the SAME secret the serving pod mounts, loaded through the serving loader (FieldEncryptor::from_env); absent / malformed / wrong-length refuses naming the variable, and a well-formed WRONG key is refused by the KCV + canary preflight againstcrypto_key_lineagebefore any row is read. -
CRAIG_CONFIG_SOURCE(required; withCRAIG_CONFIG_ROOTand the published tree forgit+layers) — the layers whosebundle/search_schemes.tomldeclares the target scheme; an unset or refused source refuses as boot does. -
CRAIG_CASES__ENCRYPTION_MODE=required— unset meansrequired;optional(or any other value) refuses (ModeNotRequired): the tool never performs a keyless plaintext walk. -
RUST_LOG— the gate’s logging-only telemetry, unchanged.
The sequence, per environment (the same immutable image tag / digest serves as the tool, the gate and the serving binary):
-
Roll the #1399 U1 fence release on EVERY craig-cases replica first (§ Migration gates) and ship the image whose bundle declares the new scheme.
-
Scale craig-cases to ZERO. The tool’s exclusive lock is takeable only when NO participant connection exists in the database — a straggler replica or a concurrent gate is refused BY NAME (
LockHeld, each holder’s pid / role /application_name), and a replica that tries to reconnect while the tool holds the lock fails closed at connect (RewriteFenceHeld), never on timing. End every other client ofcraig_casestoo (psql, a pooler, the seed): the census refuses any other client backend by pid / role /application_name(OtherBackends) — those are not fenced by the lock. -
Take a PITR mark / backup.
-
<binary> rewrite-scheme --dry-run— pass 1 alone: classifies every row and prints the counts; writes NOTHING (no ledger row); exit ≠ 0 on any refusal, still with nothing written. -
<binary> rewrite-scheme— the run (below). Exit 0 prints the report; exit ≠ 0 prints the refusal, which leads with the remedy. -
<binary> migrate— the gate; the marker now equals the resolved registry (reconcile case 1) and it no-ops. -
Roll serving; the boot verify accepts under the new marker.
Kubernetes: a parallelism-1 Job (or a one-off exec of the image) carrying the serving pod’s key secret and
the gate’s owner DSN, run while the Deployment is scaled to zero. The reference compose one-shot service
(craig-cases-rewrite, profile rewrite) and the cargo xtask rewrite-scheme CLONE rehearsal landed with U3
(#1959; CLI guide); a devstack scheme flip is a jurisdiction flip and
would strand the seed identity, so the devstack guard keeps wipe + reseed and the wrapper rehearses on a clone it
creates and drops.
What a run does, in order (every step’s refusal is a typed arm whose message leads with the remedy): the
exclusive lease (pg_try_advisory_lock(hashtext('craig:scheme-rewrite')) on a raw connection,
application_name = craig-cases-rewrite-scheme) → the census → a one-connection tool pool
(RewriteFence::Rewriter, the gate’s 30 s statement timeout) → the schema verdict, which must be Exact —
Ahead or any refusal is "run <binary> migrate first; nothing was written" (a rolled-back or half-deployed
image cannot rewrite) → the key preflight → SOURCE (marker) and TARGET (config) resolution → the ledger first
(a live crypto_field_rewrites row is adopted or refused; otherwise a running row is inserted with the key’s
KCV, the tool version and db_user = current_user) → pass 1 CLASSIFY (read-only keyset over persons) →
pass 2 REWRITE (one transaction per 1 000-row batch: the rows FOR NO KEY UPDATE, each rewritten through the
production encrypt / decrypt walk and written by a compare-and-swap UPDATE on both cells, the ledger’s cursor
/ rows_seen / rows_mutated / rows_healed advanced in the SAME transaction; the lease session is re-checked
before every batch) → running → verifying → pass 3 VERIFY (every row re-read under the TARGET spec only: the
base decrypts; BlindIndex ⇒ ssn_hmac equals the recomputed digest; Opaque ⇒ ssn_hmac IS NULL) → the swap
transaction (the marker CAS + verifying → completed) → an in-process reconcile self-check (case 1). updated_at
is untouched, no event is published and no audit_log row is written — the ledger row is the record. A populated
plaintext cell, an undecryptable cell or a sibling digest that authenticates but does not match the plaintext
REFUSES the whole run in either direction (never a provenance guess); the three derived-data heals (a stale
sibling cleared, a missing sibling re-derived, an orphan sibling cleared) are counted writes.
The printout (stdout on exit 0): per pass seen / skip / already_target / rewrite / mutated / healed{kind: n}
and the duration, lineage before / lineage after (the canonical spec strings), key kcv and ledger (the row
id). Never a plaintext, the key, a last_error payload or more than ONE row id (a refusal names exactly one).
A second run after completion prints "already recorded under <canonical> — nothing to do" and exits 0.
The ledger states (crypto_field_rewrites, Data Model: Case Management; one live row per field by partial
UNIQUE index):
-
running— pass 1 / 2 in flight, or interrupted (a crash,LeaseLost, a refusal after the first committed batch —last_errorsays which). Serving boot, the gate’spre_applyand every non-ownerpersonswriter refuse while a row isrunningorverifying. -
verifying— pass 2 is fully committed; pass 3 or the swap is pending or failed (last_error). The marker is UNCHANGED — the table is entirely under the target scheme but still recorded as the source. -
completed— the marker was swapped in the same transaction; terminal. -
aborted— terminal, and legal ONLY atrows_mutated = 0(a pass-1 refusal on a fresh run, or--abort). -
There is NO
failedstate: any refusal after the first committed batch leaves the rowrunning/verifyingwithlast_error— never a terminal state a boot would ignore.
Resume and rollback. A plain re-run ADOPTS the live row when its from_spec, to_spec, key_kcv and db_user
match this run’s, and repeats from pass 1 — converged rows classify AlreadyTarget, so correctness never depends
on the cursor. Mid-run rollback is therefore FORWARD (resume) or a PITR restore to the mark: a half-rewritten
table under the old marker is unreadable by ANY binary, the live row refuses every U1+ boot / gate / non-owner
write until the run completes, and an N−1 (pre-U1) image has none of these guards — never roll below the U1 fence
while a row is live. --abort closes the live row aborted iff rows_mutated = 0 — the COUNTER decides, never a
read pass (in BlindIndex → Opaque a rewritten row is byte-indistinguishable from a NULL-sibling source row, so
no read pass can prove "nothing was rewritten"); otherwise AbortRefused names the count and the remedy is to
resume forward.
What each refusal means (exit ≠ 0; stderr):
| Refusal | Meaning | Remedy |
|---|---|---|
argv shape / missing |
Refused before the first connection; nothing was read or written. |
Fix the invocation / the environment (above). |
|
A participant connection lives — a serving replica, a gate, another tool run — named by pid / role /
|
Scale craig-cases to zero, end the named sessions, retry. |
|
A non-participant client (psql, a pooler, the seed) is attached; the lock does not fence it. |
End it, retry. |
|
The schema is ahead of / diverged from this binary’s embedded migrations; nothing was written. |
Run |
|
The mounted key is not the one |
Mount the serving key; nothing was read. |
|
The gate never stamped the marker / the marker names a field this binary does not allowlist / the recorded spec cannot be reconstructed. |
Run |
|
A row is live and the configuration now names the run’s ORIGIN scheme. |
Set |
|
The live row was started under another key / another role / another |
Mount the original key / resume as that role (the |
|
ONE row holds plaintext, an undecryptable cell or a mismatched sibling digest. Fresh run ⇒ the ledger row is
closed |
Repair or restore that row, re-run. |
|
An UNFENCED writer (the owner role itself, a superuser) changed a row mid-batch / the lease session died; the batch rolled back, nothing further was written. |
End the writer; re-run (adopts the row). |
|
Another operator acted on the ledger / the marker moved underneath the swap / a row failed the target-scheme
verify. The marker is untouched; the row stays |
Inspect, then re-run. |
|
The swap IS committed; the in-process gate self-check refused afterwards. |
Investigate before rolling serving — boot would refuse the same way. |
|
|
Nothing to do / resume forward. |
Independent oracles after a run: the devstack’s cargo xtask verify-seed --expect keyed reconstructs the
registry FROM the replaced marker but inspects siblings for BlindIndex bases only, so after BlindIndex → Opaque
also assert SELECT count(*) FROM persons WHERE ssn_hmac IS NOT NULL = 0 by raw SQL. Cost: three AEAD passes per
row in 1 000-row transactions — minutes per million rows; after BlindIndex → Opaque the partial
idx_persons_ssn_hmac index empties (no DDL) and equality search on the field is refused by the planner until
the reverse run restores the siblings.
Connection Pool Defaults
-
Max connections: 10 (
CRAIG_<SVC>__DB_MAX_CONNECTIONS) -
Idle timeout: 600 seconds (
CRAIG_<SVC>__DB_IDLE_TIMEOUT_SECS) -
Statement timeout: 30,000 ms (
CRAIG_<SVC>__DB_STATEMENT_TIMEOUT_MS) — batch jobs extend per-transaction viaSET LOCAL -
Acquire timeout (serving pools): 5 seconds — fixed, deliberately not a knob (#1160). Under session exhaustion every acquire queues up to the full bound and fails as
PoolTimedOut, quantizing overload into 5 s latency cliffs; that fail-fast cliff is the intended trade. Raising the bound would deepen the queue without adding capacity — size the budget below instead, and watch thedb_pool_*instruments (Monitoring → Metrics below). The constant lives incrates/craig-db. ONE recorded exception (#1340): the ADR-063 migration gate dials with its own 60 s bound — a one-shot deploy phase should wait out a busy server (rolling deploys keep old replicas serving while the gate runs), not fail the deployment on the serving cliff. -
application_name(#1600): every pool tags its sessionscraig-<svc>-<role>—craig-cases-servingfor the serving pool,craig-cases-events/craig-exchange-send/-reconcilerfor the dedicated worker pools,craig-<svc>-migrate-gatefor the ADR-063 gate,craig-managefor the read-only operator reports (craig-manage invariants,reconcile,caregiver-coverage), andcraig-xtaskforverify-seed. Filterpg_stat_activity,pg_stat_statements, andpg_locksjoins on this column to attribute a slow query or a held lock to a specific service and pool. Not a knob — derived from the service identity.
Database connection budget (#1160)
Postgres refuses sessions beyond its server-wide max_connections, and a CRAIG deployment
holds more sessions than its pool arithmetic suggests. Budget every class:
| Session class | Worst case | Notes |
|---|---|---|
Service pools |
Σ |
craig-web and craig-intake (edge mode) hold no database; craig-intake-keyring joined the
stateful set with its own small Postgres store (epic &84 / ADR-042 §D8 amendment), pool
tagged |
Dedicated worker pools (ADR-062 §Amendments #1304/#1034/#1326) |
+3 (craig-cases) +3 (craig-security) +8 (craig-exchange) = 14 |
The cases auto-link consumer (nested acquisitions), security’s fleet-wide audit + DLQ
subscribers (volume), and exchange’s three domain workers (aggregate starvation:
events 3 + send 3 + reconciler 2) ride dedicated pools tagged via |
Detached advisory-lease sessions |
+14 fleet-wide |
|
Migration gates + verdict boot |
+2 per service, transient |
ADR-063: each gate one-shot holds 1 session (its minimal pool) +1 detached apply session when Behind (#1153); the serving boot’s verdict re-check adds a transient pooled read. Worst case during a rolling deploy: gates ×9 + the OLD replicas' full pools + the surge replica’s pool all coexist — budget the deploy window, not just steady state. |
Concurrent list requests |
2 pooled connections per request |
#1138: list endpoints run page + count concurrently. This consumes POOL headroom, not extra server sessions — about 5 concurrent lists saturate a default-10 pool — but it shapes per-service pool sizing. |
Operator tooling |
a few |
|
Superuser reserve |
3 |
|
Rule of thumb: max_connections ≥ Σ pools + 14 + (1 × services) + tooling + 3, then margin.
The devstack pins 250, with its instance arithmetic (including the pre-push battery’s
scratch-DB test pools) recorded next to the knob in docker-compose.yml and floor-pinned by
crates/craig-db/tests/connection_budget.rs; production deployments substitute their own
pool sizes and replica counts.
Per-service pool sizes were reviewed for #1160 and stay at the uniform default 10:
differentiated devstack pools would re-introduce per-service acquire cliffs under bursty e2e
load for roughly 20 sessions of headroom the right-sized ceiling already provides.
Production deployments size pools per service from observed db_pool_* saturation, not from
this default.
RabbitMQ Configuration
Exchanges (operator-owned topology, #1202)
Two durable topic exchanges. Since #1202 they are operator-owned — services
no longer declare them at runtime (granting a service configure on a shared
exchange would include DELETE, letting a compromised service delete/redeclare
craig.dlx and silently suppress forensic delivery). Devstack pre-declares both in
devstack/rabbitmq/definitions.json; production operators MUST provision them before
first boot (a missing exchange fails the first bind/publish loudly rather than being
silently recreated).
| Name | Type | Durable | Purpose |
|---|---|---|---|
|
topic |
true |
Domain-event fan-out — every service’s outbox publishes here; consumers bind their |
|
topic |
true |
Dead-letter exchange (ADR-022) — nack-without-requeue and capture publishes route here under |
Queues
Each service declares its own queues on startup (the exchanges are operator-owned — see above). The queue names here are what the #1202 per-service credentials are scoped to (User Configuration, below).
| Queue | Type | Bindings |
|---|---|---|
|
exclusive |
|
|
competing |
|
|
competing |
|
|
competing |
|
|
competing |
the wildcards |
|
competing |
|
|
competing |
|
|
exclusive |
|
|
exclusive |
|
|
exclusive |
|
|
competing |
|
|
— |
No bindings (published via the default exchange; ADR-059 §D4) — the bounded-retry and terminal-capture companions |
craig-intake is a stateless edge
(ADR-017): it holds NO broker connection and forwards reports to craig-cases over HTTP.
craig-web (BFF) also holds no broker connection.
|
Competing consumers (shared queue): use for DB-mutating handlers — ensures each event is processed by exactly one instance.
Exclusive consumers (per-instance queue): use for cache invalidation — every instance must receive the event.
Queue type and delivery limits (#1198)
The "Type" column above is the consumer pattern (competing vs exclusive). This section is about the RabbitMQ queue type property (classic vs quorum vs stream) — a different axis.
Every CRAIG queue is declared x-queue-type=classic
(ADR-003 §Amendment #1198): the fleet’s redelivery
semantics assume classic-no-delivery-limit, and a quorum queue’s default delivery-limit = 20
would silently drop or re-route deliveries — on the DLX audit queue that means destroying
forensic records. The explicit argument makes CRAIG immune to a default_queue_type at fresh
declare and turns any conflict into a loud boot failure.
Operator MUST-NOTs:
-
Do not set a vhost-level
default_queue_typeother thanclassicon a CRAIG vhost (the management-UI vhost dropdown is the one-click hazard). This is defense-in-depth — CRAIG’s explicit declarations are immune at fresh declare regardless — but a non-classic DQT will still catch any type-omitting declarer and confuse drift diagnosis. -
Do not apply
delivery-limit(or any queue-type-affecting) policies or operator policies tocraig*queues. Classic queues ignore delivery limits today; the prohibition keeps the posture honest rather than accidental. -
Do not enable
quorum_queue.property_equivalence.relaxed_checks_on_redeclaration— with it on, the broker ignoresx-queue-typeon redeclaration and a CRAIG subscriber would silently consume from a quorum queue where classic is pinned. -
(#1197) Do not apply
message-ttl,max-length,max-length-bytes,expires, or a destructiveoverflowpolicy tocraig*queues: a TTL/length policy on the no-DLX DLQ or the parking/quarantine queues silently DESTROYS forensic captures, andexpiresdeletes the consumer-less quarantine queue outright. These remain operator conventions — services hold AMQP credentials only and cannot enforce them at runtime (ADR-059 §D1 names this failure domain).
Parking and quarantine queues (#1197)
Each DLQ subscription (production: craig-security.dlq) declares two durable classic
companions at boot (ADR-059):
-
{queue}.parking— the bounded-retry holding queue. Self-draining: a client-side replayer (prefetch 1) sleeps each capture toparked_at + parking_ttl(default 10 min) and returns it tocraig.dlxwith a confirmed + mandatory republish. No TTL/DLX arguments — nothing to configure, no redeclare hazard. -
{queue}.quarantine— terminal captures (permanent failures, park-cap exhaustion after ~2 h of cycles, malformed bodies with their raw bytes base64-embedded, non-canonical routes). NO consumer: operators drain it. Every quarantine publish logs aterror!alongside the #1199dlq_*metrics (triage flows: DLQ Triage Runbook); broker disk alarms are the backstop. Duplicate copies can exist by design (an ack lost after a confirmed publish); correlate on the capture’scapture_id+occurrence_token— tokenless/malformed captures have NO reliable automatic dedup.
Automated drain (#1206): craig-manage quarantine-drain <queue> --yes [--out <dir>] [--limit <n>], with
the broker URL exported as CRAIG_QUARANTINE_DRAIN_AMQP_URL, implements the procedure below exactly — returnable captures
republish bytes-unchanged and ack only on a clean confirm; malformed captures file to a
timestamped NDJSON (fsynced before their ack); any unclean confirm stops the drain with
the capture left in place. The URL is required and has no default (#2647): without it the
command refuses, naming the variable, and never falls back to a test identity. It never
travels on the command line (#2692: argv is readable by any local user and lands in shell
history) — export it from the secret store, or read -rs CRAIG_QUARANTINE_DRAIN_AMQP_URL &&
export CRAIG_QUARANTINE_DRAIN_AMQP_URL, and the drain never prints its userinfo. A devstack
run exports .ports.env’s `CRAIG_TEST__RABBITMQ_URL; production exports an operator-scoped
account — the service identities deliberately
cannot consume quarantine (#1202), and the recommended production shape is a
purpose-scoped account holding exactly read on {queue}.quarantine + write on
craig.dlx. The manual procedure below remains the fallback.
Replaying quarantined captures (manual-ack AMQP procedure — never a destructive management
get; a management-UI peek must use requeue mode):
-
Consume from
{queue}.quarantinewith MANUAL acknowledgements. -
Validate the capture (
payload._park): readoriginal_routing_key(dlq.…) and inspectreason/last_error. Malformed captures (reason: "malformed") are excluded — they have no replayable route; export them to file. -
Republish the message bytes UNCHANGED to the
craig.dlxexchange underoriginal_routing_key, with publisher confirms +mandatory, and wait for the clean confirm. -
ONLY THEN ack the quarantine delivery. A nack/close before the confirm leaves the capture safely in place.
Verify the contract on a live broker (the first command shows the stored client arguments, which distinguish an explicit pin from a resolved default):
rabbitmqctl list_queues name type arguments
rabbitmqctl list_vhosts name default_queue_type
rabbitmqctl list_policies && rabbitmqctl list_operator_policies
rabbitmq-diagnostics environment | grep relaxed_checks
Failure signature and remedies:
-
Boot failure
PRECONDITION_FAILED - inequivalent arg 'x-queue-type' … received 'classic' but current is 'quorum'— a queue pre-exists with the wrong type. With a backlog you care about, shovel/drain the queue first, then delete it and let the service redeclare (a bare delete destroys a durable backlog). The same signature at runtime (service up, not consuming, ERROR-level "operator action required" logs) means a mid-life type flip — same remedy. -
Queues first declared on pre-3.13 brokers and upgraded in place may lack a stored type argument and 406 on the explicit redeclare — same shovel/drain-then-delete remedy. Queues born on 4.x brokers are unaffected (the resolved type is stored at first declare).
-
A drifted vhost DQT:
rabbitmqctl update_vhost_metadata / --default-queue-type classic. Notedefinitions.jsonimports apply at first boot only — they never overwrite existing broker state, so fixing definitions alone does not repair a live vhost.
User Configuration — per-service least privilege (#1202)
Each service connects as its OWN broker account, scoped to exactly the queues it
declares plus the shared exchanges it uses. A single shared account is a
pre-1.0-retired anti-pattern: it let any service read every other service’s dead-letter
records and (via configure on a shared exchange, which includes DELETE) delete
craig.dlx and suppress forensic delivery. RabbitMQ permission patterns are a
substring match, so every pattern below is anchored (^(…)$).
An administrator-tagged operator account (here craig) is still needed for the
management plane (vhost/policy administration). It is NOT a service identity — no
service connects as it.
The per-op derivation: write carries craig.events (the outbox publish) and
craig.dlx (every events-role queue is declared with an x-dead-letter-exchange
argument, which RabbitMQ authorizes as a write on the DLX); read carries
craig.events (bind reads) plus the service’s own queues; configure is the
service’s own queues ONLY. craig-security additionally holds the dead-letter plane:
amq.default write (the parking/quarantine capture publishes go via the default
exchange), craig.dlx read (the dlq.# bind), and configure/read on its
dlq/dlq.parking/dlq.quarantine (quarantine is configure-only — no consumer).
|
Production passwords
Devstack uses |
The canonical spec is devstack/rabbitmq/definitions.json (imported at first boot,
/ vhost). Provision the same via the management API or rabbitmqctl; the
set_permissions argument order is configure write read. Example for two
representative accounts (a plain service and the audit service):
# A plain service account (craig-rules shown; the five event services follow the
# same shape with their own <svc> prefix — craig-rules itself has carried NO
# `.events` queue since #1670 retired its only domain-event binding):
rabbitmqctl add_user craig-rules "$CRAIG_RULES_BROKER_PASSWORD"
rabbitmqctl set_permissions -p / craig-rules \
'^(craig-rules\.cache\..*|craig-rules\.authz-cache\..*)$' \
'^(craig\.events|craig\.dlx|craig-rules\.cache\..*|craig-rules\.authz-cache\..*)$' \
'^(craig\.events|craig-rules\.cache\..*|craig-rules\.authz-cache\..*)$'
# The audit service (craig-security) — the only account on the dead-letter plane:
rabbitmqctl add_user craig-security "$CRAIG_SECURITY_BROKER_PASSWORD"
rabbitmqctl set_permissions -p / craig-security \
'^(craig-security\.events|craig-security\.authz-cache\..*|craig-security\.dlq|craig-security\.dlq\.parking|craig-security\.dlq\.quarantine)$' \
'^(amq\.default|craig\.events|craig\.dlx|craig-security\.events|craig-security\.authz-cache\..*|craig-security\.dlq)$' \
'^(craig\.events|craig\.dlx|craig-security\.events|craig-security\.authz-cache\..*|craig-security\.dlq|craig-security\.dlq\.parking)$'
# The operator account (management plane only — not a service identity):
rabbitmqctl add_user craig "$CRAIG_BROKER_ADMIN_PASSWORD"
rabbitmqctl set_user_tags craig administrator
rabbitmqctl set_permissions -p / craig '.*' '.*' '.*'
The other services follow the same three-column shape scoped to their own queue
names, with these differences from the craig-rules exemplar (which is the only
account carrying a .cache family, and since #1670 the only event service WITHOUT an
.events queue): craig-placement, craig-exchange, craig-financial, and
craig-reporting have .events + .authz-cache only (no .cache); craig-cases carries .events + .authz-cache (its
craig-cases.events queue arrived with the ADR-062 §G4 auto-link consumer, #1269); craig-composition also omits .events and carries
.composition-cache + .authz-cache. Copy the exact triples from definitions.json
— it is the executable source of truth.
Re-running the import or set_permissions is idempotent (a permission set replaces,
never appends). Verify:
rabbitmqctl list_permissions -p / # one row per account, triples as above
rabbitmqctl list_users # only craig carries [administrator]
# Per-service connect smoke (should succeed as its own identity, fail cross-namespace):
rabbitmq-diagnostics check_port_connectivity
Retiring craig-rules.events (#1670) — ordered cutover with rollback
#1670 retired craig-rules' only domain-event binding (case.intake_created →
craig-rules.events): its payload carried no screening facts, and the intake-screening
consult moved to the cases service’s screening-decision act over HTTP (plan v2.3,
epic &88). The definitions.json grant above already omits the queue; an EXISTING broker
keeps its durable queue, binding and grant until you retire them. Forward order, no
downtime:
-
Roll the #1670 rules image and let every old replica drain (
rabbitmqctl list_consumers -p /shows no consumer oncraig-rules.events;/healthzlists noevents-subscriberworker). -
Promote the strict rulesets —
georgia-intake-screeningv1.3 andtexas-intake-screeningv1.2 (craig rules promote …; the seed does it on a devstack). Order matters: their input schemas are closed, and a pre-#1670 consumer feeding{investigation_id, referral_id}would turn every delivery into an engine error. -
Clean the broker through the management API or
rabbitmqctl: unbindcase.intake_createdfromcraig-rules.events, delete the queue, thenset_permissionsthe new craig-rules triple (above). -
Deploy the cases act (U2, #1672) — the next section; the rulesets stay callable via
POST /v1/rules/evaluatethroughout.
Rollback (ruleset revision, cases image and rules image TOGETHER; the {j}-screening-policy
row is never part of it — it stays live until the release is final, next section):
-
Roll the N−1 cases image (it does not verify the screening surface).
-
Re-promote
georgia-intake-screeningv1.2 /texas-intake-screeningv1.1 from the previous tag’s checkout — the strict schema would otherwise fail every event the restored consumer feeds. -
Restore the grant, then the queue, then the binding (the reverse of step 3 above).
-
Roll the N−1 rules image.
Superseding a screening decision recorded BEFORE the U2 cutover (rows carrying the
legacy cicc / county_supervisor / caseworker role tokens) was refused
(screening-override-not-authorized, the token named) until the contract migration
#1697 rewrote those values; see the #1697 section below.
The screening act consults the ruleset (#1672) — ordered rollout with rollback
#1672 made POST /v1/cases/reports/{id}/screening-decisions consult the jurisdiction’s
{j}-intake-screening ruleset with the real facts (plan v2.3, epic &88 — U2). The wire is
pre-1.0 BREAKING (actor_role removed, rationale required, attested added), so the
release is ordered:
-
Steps 1–3 of the #1670 cutover above (the rules image, the strict rulesets, the broker cleanup) must have run.
-
Roll the #1672 cases image. The migration is ADDITIVE (seven nullable provenance columns under an all-or-none CHECK, the
screening_decision_evaluationstable, the recreatedv_effective_disposition; NOschema_compat_floorbump), so N−1 cases replicas keep inserting their eight-column rows during the roll. Each new replica boots the Criticalscreening-surface-verifierworker, which reads the ruleset with the service principal every minute once verified (a failed pass retries after 2 s, doubling to the 60 s ceiling — #1727); until its first successful pass the screening routes (the act, conversion, follow-ups, the two reads) answer the typed 503screening-surface-not-readywith a closed reason token —/readyzis untouched. Thescreening_surface_verified{jurisdiction}gauge is the operator alert:0after boot means the ruleset shape or the rules reachability needs repair (the verifier log names the specific defect). -
Roll craig-web and the CLI. An N−1 web or CLI against a #1672 cases answers a typed 422 (the removed
actor_roleis an unknown field) — the N−1 web shows its generic flash until this step; the window is symmetric, so start it once no N−1 cases replica remains. -
Do NOT retire the
{j}-screening-policyruleset row yet. Nothing reads it after step 2, butDELETE /v1/rules/sets/{id}is a SOFT delete with no restore route (by-name resolution requiresactive = true, promotion and rollback act on the live row, and the name is unique), so the row is the N−1 rollback’s dependency. Retire it only once the release is declared final and an N−1 cases image is no longer a rollback target:DELETE /v1/rules/sets/{id}?reason=…as an admin (audited on the snapshot).
Rollback while the row is live (the order is the #1670 rollback above, minus its step 0,
which no longer exists): roll the N−1 cases image — it reads the still-live
{j}-screening-policy row and records decisions with the pre-cutover role tokens against
the expanded table (NULL provenance, which the #1695 contract migration below refuses);
superseding such a row after
rolling forward again stays refused (screening-override-not-authorized, the token named)
until the contract migration #1697 (next section) rewrites it.
Screening role-token contract migration (#1697) — after the #1672 roll
20261104120000_screening_actor_role_contract rewrites the legacy
screening_decisions.actor_role tokens to the mapping tokens: cicc → cicc_intake,
county_supervisor → county_director, caseworker → cicc_intake. Once it has run,
superseding a pre-cutover decision works like superseding any other. It is idempotent
(a re-run rewrites nothing) and bumps schema_compat_floor to its own version (ADR-063
§D3), so rolling craig-cases back past it is refused at boot (FloorAboveBinary): roll
forward instead.
-
Ship it in a release AFTER #1672 has fully rolled: no N−1 cases replica may still be running. An N−1 replica writes the legacy tokens, so a row it writes after the rewrite escapes it. The floor stops an N−1 replica from starting, but it does not stop one that is already running.
-
Roll the cases image. The migration gate applies the rewrite. Afterwards, nothing holds a legacy token:
SELECT count(*) FROM screening_decisions WHERE actor_role IN ('cicc', 'county_supervisor', 'caseworker')answers0.
The rewrite targets Georgia’s mapping tokens. On a deployment whose ruleset maps other
tokens (Texas: swi_intake, swi_supervisor, county_director, regional), a legacy
cicc or caseworker row becomes cicc_intake, which its mapping does not name, so
superseding that row stays refused, the token named. A legacy county_supervisor row
becomes county_director, which the Texas mapping does name.
Screening provenance contract migration (#1695) — after the #1672 roll
20261106120000_screening_decision_provenance_contract makes the seven
screening_decisions provenance columns NOT NULL and drops the all-or-none CHECK
screening_decision_provenance_all_or_none. It bumps schema_compat_floor to its own
version (ADR-063 §D3), so rolling craig-cases back past it is refused at boot
(FloorAboveBinary): roll forward instead.
A database still holding a decision recorded without the consult (before #1672, or by an
N−1 replica) REFUSES the migration, and nothing is applied. The error names the first
NULL column and the count, for example #1695 screening provenance contract: 3
screening_decisions row(s) carry NULL rule_set_name. The file does not invent a consult or
delete a decision, because referrals, follow-ups and superseding decisions hold their ids.
Before 1.0 only dev and test databases hold such rows. The migration carries the
wipe-before-apply marker, so cargo xtask dev start and cargo xtask dev refresh wipe
the devstack before applying it. cargo xtask dev reseed is the explicit remedy the error
names. Any other database: stop, because there is no data migration for these rows.
-
Ship it in a release AFTER #1672 has fully rolled: no N−1 cases replica may still be running. An N−1 replica’s eight-column INSERT fails against the
NOT NULL(23502). The floor stops an N−1 replica from starting, but it does not stop one that is already running. -
Check first:
SELECT count(*) FROM screening_decisions WHERE rule_set_name IS NULLmust answer0. -
Roll the cases image. The migration gate applies the contract.
Legal-status chain sequence (#2353)
20261106140000_legal_status_chain_seq adds legal_status_facts.chain_seq, which orders a
day’s legal-status rows, and back-fills it in the existing chain_root_id order, so no row
changes place. It bumps schema_compat_floor to its own version (ADR-063 §D3): rolling
craig-cases back past it is refused at boot (FloorAboveBinary), so roll forward instead.
-
Stop every N−1 craig-cases replica first. An N−1 replica’s legal-status INSERT names no
chain_seqand fails against theNOT NULL(23502). The floor stops an N−1 replica from starting, but not one that is already running. -
Roll the cases image. The migration gate applies the back-fill under an exclusive lock on
legal_status_facts. -
Roll craig-web after cases. A legal-status row’s
factsnow carry a requiredchain_seq; an N−1 web ignores it.
Placement eligibility consults the ruleset (#1641) — ordered rollout with rollback
#1641 made both placement-activation sites and GET /v1/placement/matching consult the
jurisdiction’s {j}-placement-eligibility ruleset, and made craig-web’s foster-home views
REQUIRE the derived effective_license_status. Order:
-
Promote
{j}-placement-eligibilityv1.0 (Georgia AND Texas) on craig-rules BEFORE the #1641 placement image. A placement that consults an absent ruleset answers a typed 500 naming the deployment defect on every activation and every matching call (fail-closed by design) — the ruleset is the image’s dependency, never the reverse. -
Roll the #1641 placement image. Its migration is ADDITIVE (two partial indexes, the
foster_home_expiry_noticesledger, the training-write lock trigger; noschema_compat_floorbump), applied by the ADR-063 gate. SetCRAIG_PLACEMENTRULES_ENGINE_URL; leaveEXPIRY_SWEEPINTERVAL_SECONDSat0until the alert row is wired. -
Roll craig-web (and the CLI) AFTER placement. An N−1 web against a #1641 placement is fine (extra keys are ignored); a #1641 web against an N−1 placement answers 502 on every page that decodes a foster home (the homes list, matching, the new-placement form —
effective_license_statusis required) and renders the detail’sPendingsentinel.
Rollback ORDER: web first (if it was rolled), then the placement image to N−1 — the derived
column and the consult go with it; the migration stays (additive; the ledger and the trigger are
inert to N−1). Never demote the ruleset first: an N image consulting a missing ruleset refuses
every activation. The #1642 training machine’s v1.1 ruleset follows the same rule (promote v1.1
BEFORE the U2 image; roll the U2 image back BEFORE re-promoting v1.0 — the U2 parser requires the
training keys). The #1721 matching-scope v1.2 ruleset follows the same rule (promote v1.2 — both
jurisdictions — BEFORE the #1721 placement image: its matching parser requires matching_scope_statuses,
and a v1.1 answer is a typed 500 on every search with per_page > 0; roll the image back BEFORE re-promoting v1.1).
The #972 child_criteria v1.3 ruleset (plan identity-based-matching MR-2, #1775) follows the same rule
(promote v1.3 — both jurisdictions — BEFORE the #972 MR-3 placement image, whose merged matching consult requires
the four child keys age_band / icwa / sibling / child_refusal_reason — a v1.2 answer is a typed 500 on
every search; roll the image back BEFORE re-promoting v1.2). v1.3 is DORMANT under the #1721 image, which reads
only matching_scope_statuses, so promoting it early changes nothing.
Retiring the shared credential — ordered cutover with rollback
If you are upgrading from the pre-#1202 shared craig service credential, cut over
WITHOUT downtime and keep a rollback until every service is confirmed healthy:
-
Provision all per-service accounts + the two exchanges (above). The old shared
craigcredential stays valid throughout — additive, no service is touched yet. -
Deploy the per-service
CRAIG_<SVC>__RABBITMQ_URLsecrets and roll the fleet. Each service reconnects as its own identity. -
Verify consumption:
rabbitmqctl list_consumers -p /shows each service’s queue attached under its own connection;readyzis green fleet-wide; noACCESS_REFUSEDin service logs. -
Retire the shared credential’s SERVICE use: confirm no connection remains authenticated as
craigon the AMQP plane (rabbitmqctl list_connections user), then repurposecraigto the operator/management plane only. -
Scrub the old shared password from every config store.
Rollback (any step before 5): re-point the affected CRAIG_<SVC>__RABBITMQ_URL back
at a still-provisioned fallback credential and redeploy — always BEFORE revoking
anything, never after. Do not delete the old credential until step 5.
If using a custom rabbitmq.conf, the RABBITMQ_DEFAULT_USER environment variable will not work.
Configure users via definitions.json or the management API instead.
|
Keycloak Configuration
Realm
CRAIG requires a craig realm with:
-
Roles (9): the six operational roles
admin,supervisor,caseworker,eligibility_worker,icpc_coordinator,readonly, plus the three office-authority rolescounty_director,regional_director,state_office(the ADR-054 subsidy approval matrix axis). Plan E additionally requires the per-serviceservice:<svc>realm roles — see IdP Integration -
Clients:
-
craig-api: public, Direct Access Grant (ROPC) for the CLI and integration tests. Service-to-service auth uses per-serviceclient_credentialsprincipals since Plan E — see IdP Integration -
craig-ui: public, Authorization Code + PKCE for the web UI
-
Token Configuration
-
Access token lifetime: 30 minutes (recommended)
-
Refresh token: enabled for
craig-ui
Dual URL Pattern
In containerized deployments, Keycloak is typically accessible at different URLs from the host and from service containers:
# JWT 'iss' claim uses the public URL (what the browser/CLI sees)
OIDC_ISSUER=https://auth.example.com/realms/craig
# JWKS is fetched via the internal network
OIDC_INTERNAL_URL=http://keycloak:8080/realms/craig
Both must point to the same Keycloak realm. The iss claim in JWTs is validated against OIDC_ISSUER.
Boot-time discovery retry (#1335)
The boot-time JWKS/discovery fetch tolerates a saturated bring-up: connect/timeout-class
failures retry up to 3 attempts with a 2 s pause (a starved GET on a cold host — 14
containers + a cold JVM — must not brick a service into exited (1) for everything
downstream of its compose edge). Fail-loud is preserved for genuine misconfiguration:
HTTP status errors, JSON-decode failures, and refused connects still surface within
seconds (a refused connect fails each attempt instantly, so the whole window is ~4 s);
only a fetch that is genuinely WAITING burns its per-attempt HTTP budget, giving real
saturation 30-60 s of patience (one vs both GETs timing out per attempt) before the
same loud failure.
Boot-time database connect retry (#1353)
The data-plane’s eager DB dial gets the same treatment: PoolTimedOut — the ONLY
retried class — means the first connect starved past the serving pools' fixed 5 s
acquire cliff (#1160; sqlx retries refused connects internally until that deadline,
so a busy or not-yet-accepting server surfaces the same way). Three attempts with a
2 s pause bound the window at ~19 s before the loud failure. Every other error class
(bad URL, DNS, TLS, auth) fails on the FIRST attempt, and the pool’s acquire policy
is untouched — once serving, overload still cliffs visibly at 5 s (#1340’s migration
gate remains the one acquire-bound exception).
Object Storage (S3)
Services that handle file uploads (craig-cases, craig-placement, craig-exchange) require S3-compatible object storage.
Supported Providers
-
Garage (devstack default) — Rust-based, AGPL-3.0, lightweight
-
AWS S3 — production
-
MinIO, Ceph — self-hosted alternatives
Retention & Archive
#1129 / ADR-058. Two classes: transport tables
prune themselves (30/31-day windows, always on — see the retention knobs in
Configuration Reference); audit-class tables
(audit_log, dead_letter_audit, rule_evaluations) are ARCHIVED to the object store and only
then pruned, behind an explicit consent knob.
A third self-pruning class since B2 (#1194, ADR-062 §B):
every service’s request_claims table, swept hourly by the request-claims-retention worker
on the deployment-global CRAIGREQUEST_CLAIMSWINDOW_DAYS horizon (platform CRAIG__
prefix — one fleet-wide replay boundary, never per-service; default 30; 0 disables with an
explicit Disabled registration in /healthz; an unparseable value also disables, with an
error log — the pruner never guesses a horizon). The request_claims_retention_overrun
invariant is the beyond-grace watchdog.
Knobs (per archiving service: craig-security, craig-rules)
| Env (CRAIG_<SVC>__…) | Default | Meaning |
|---|---|---|
|
|
THE consent act (D11): enables the scheduled archiver
AND the security |
|
|
Rows older than this are archive-eligible. craig-exchange refuses boot below |
|
|
Scheduled-pass cadence; |
|
|
Rows per batch (1..=10000); one batch = one object |
|
|
Byte cap per archive object; a single row exceeding it alone is quarantined loudly and left in place (D13). |
craig-security’s audit_log: retention by month (#3173)
audit_log is range-partitioned by UTC calendar month
(data model), and the archiver retains it a whole month at a time: once a
month’s last instant (the next month’s 1st, 00:00 UTC) has left RETENTION_ARCHIVEHOT_WINDOW_DAYS, its rows are
written page by page (RETENTION_ARCHIVEBATCH_SIZE rows an object) under
retention-archives/craig-security/audit_log/<month’s first day>/<attempt>/ with a partition manifest, and the
partition is dropped in the transaction that writes their ledger rows, only when its row count still equals the rows
archived. No row is deleted. A row therefore stays up to about 31 days past the hot window, which the
audit_log_hot_window_overrun watchdog allows (90 + 31 + 7 days at the default window). dead_letter_audit and the
other archived tables keep row batches.
-
A row larger than
RETENTION_ARCHIVE__MAX_BATCH_BYTESholds its whole month: nothing is dropped, the pass warns per row, counts it onretention_quarantined_total, and the job’s report carries the partition-held error foraudit_log. Raise the cap above the row and run another pass. -
The drop waits at most 2 s for the table’s lock behind in-flight audit inserts, then gives up until the next pass; inserts are never refused because of it.
The partition horizon. There is no default partition, so an audit insert whose month has no partition is refused
and the audit consumer redelivers it until one exists. craig-security’s partition-maintenance worker (Critical)
makes every partition from the current month through the month holding the date 30 days ahead at start and then
hourly, whether or not archiving is enabled; a failed start refuses boot, a failed hourly pass logs a WARN and
retries on the next tick. The audit_log_partition_horizon invariant (high) fires when no partition holds the instant
7 days from now. When it fires:
-
Read craig-security’s log for the worker’s WARN (
could not make audit_log’s and identity_issuance_log’s partitions) and itsworker_last_success_timestamp_seconds{worker="partition-maintenance"}gauge; fix the cause (database reachable, the owner’s functions present, no lock held onaudit_logfor long). -
To restore the horizon by hand, as
craig_security_appor the owner:SELECT audit_log_ensure_partitions(current_date, current_date + 30);then re-run the invariant.
`audit_log’s own migration bumps no schema floor, but the issuance log’s, which follows it, does (below): once both have run, no craig-security built before them boots, and a rollback is a roll forward.
craig-security’s identity_issuance_log: retention by day (#3173)
identity_issuance_log, the token issuer’s record of every mint and refusal, is range-partitioned by UTC day
(data model), and the archiver retains it a whole day at a
time: once a day’s last instant (the next day’s 00:00 UTC) has left RETENTION_ARCHIVEHOT_WINDOW_DAYS, its rows
are written page by page (RETENTION_ARCHIVEBATCH_SIZE rows an object) under
retention-archives/craig-security/identity_issuance_log/<day>/<attempt>/ with a partition manifest, and the
partition is dropped in the transaction that writes their ledger rows, only when its row count still equals the rows
archived. No row is deleted. A row therefore stays up to a day past the hot window, which the
identity_issuance_log_hot_window_overrun watchdog allows (90 + 1 + 7 days at the default window). At the design
load a day is about 52 million rows (§ Identity capacity, G8), so one closed day is one archive attempt of many
objects.
-
A row larger than
RETENTION_ARCHIVE__MAX_BATCH_BYTESholds its whole day, as it holds anaudit_logmonth: raise the cap above the row and run another pass. -
The drop waits at most 2 s for the log’s lock behind in-flight issuer inserts, then gives up until the next pass. While it waits, the issuer’s log inserts queue behind it, inside the mint’s 2 s budget; a mint whose row has not committed within that budget answers 503 and releases nothing.
The partition horizon. There is no default partition, so with no partition for the current day every mint
answers 503. craig-security’s partition-maintenance worker, in the ordinary process (the issuer process never
makes a partition: its login stays insert-only), makes every day from yesterday through 30 days ahead at start and
then hourly, beside audit_log’s months, whether or not archiving is enabled. The
`identity_issuance_log_partition_horizon invariant (high) fires when no partition holds the instant 7 days from
now. When it fires, read the worker’s WARN and gauge as for audit_log above, then restore the horizon by hand, as
craig_security_app or the owner:
SELECT identity_issuance_log_ensure_partitions(current_date - 1, current_date + 30); and re-run the invariant.
The schema floor. The migration (20261128010000_identity_issuance_log_day_partitions) drops
identity_prune_issuance_log, which an earlier craig-security’s archiver calls, so it bumps schema_compat_floor:
stop every earlier craig-security replica, the issuer’s included, before it runs; afterwards no earlier build boots.
It copies the log into the partitioned table under an exclusive lock, so the issuer’s log inserts wait for the copy
to finish.
G8’s size reading. cargo xtask perf --profile identity reads the log’s bytes a row as its partitions' total size
over its rows; the partitioned parent alone reads 0 (§ Identity capacity, How it measures).
Storage requirements (D9 — enforced or required)
Boot REFUSES (D10 probe, hard startup failure) when the archiver is enabled and:
-
the store backend is
local(a single container’s disk is not durable archive storage), or -
a scoped write → read-back → delete probe under
retention-archives/{service}/fails.
Required by policy (not machine-checkable — verify before enabling):
-
S3-compatible storage with versioning or object lock enabled on the bucket — the recovery path for any operator error, and what makes `put_create’s no-overwrite meaningful against a misbehaving client.
-
Least-privilege credentials: the archiver needs put/get/delete/list under
retention-archives/only. The devstack’s single shared Garage credential is DEV-ONLY. -
An encrypted bucket (SSE) — archives carry the audit trail’s PII.
-
No lifecycle rule may expire objects under
retention-archives/— deletion happens only through the D14 purge path.
Enable order
The craig-security release carrying the rules.evaluations_archived parser arms must be deployed
FLEET-WIDE before CRAIG_RULESRETENTION_ARCHIVEENABLED=true — parser-first, so rules'
fleet-bookkeeping events never land in a security instance that would audit-log them as unknown
without ledger bookkeeping (a pre-parser instance acks the event, so its fleet copy is
permanently absent — bookkeeping-only, never data loss: rules' own archive_ledger is the
authority).
Reading an archive (D17)
An evaluation_id (or any archived row id) stays resolvable forever — hot via the service, cold
via the owning service’s ledger id-ranges:
# One row by id (verifies the batch sha256 against the ledger first)
craig-manage archive-fetch craig-rules rule_evaluations --id <uuid>
# Every line of every batch overlapping a time range
craig-manage archive-fetch craig-security audit_log \
--from 2026-01-01T00:00:00Z --to 2026-02-01T00:00:00Z
The tool (an xtask verb until #3128) reads the ledger named by --database-url, else by the owning service’s own
CRAIG_<SERVICE>DATABASE_URL, and refuses to start when neither is set; it reads the store via
the services' own CRAIG_STORE* contract, and emits the archived NDJSON lines VERBATIM — the
manifest’s ColumnSpec schema (stored beside every object) says how to interpret five-year-old
lines without the live schema.
Purge posture & attribution
Purge refuses EVERYTHING until DFCS names a records-retention schedule: every destructive
statement independently requires retention_until IS NOT NULL AND retention_until ⇐ CURRENT_DATE
AND NOT legal_hold (D14), and the engine writes every ledger row with retention_until = NULL.
When a schedule exists, an operator sets retention_until (and legal_hold where litigation
requires), then drains in bounded slices: craig archive purge --limit 100 until more is
false. Every run/purge is attributed — the manual operator’s claims.sub (or
system:retention for scheduled passes) lands in archived_by/purged_by and in the staged
security.archive_completed / security.archive_purged events (the purge event names it user_id, #2211).
Orphan objects
A crash between the object puts and the prune commit leaves data+manifest objects with NO ledger
row — harmless (the next pass re-archives under a fresh id). Garbage-collect ONLY against the
owning service’s LOCAL ledger (D8): list retention-archives/{service}/{table}/, delete objects
whose archive_id has no ledger row older than a day. Never GC from the security fleet-copies of
rules' rows — archive_ledger in craig_rules is the authority for rules objects.
Scaling
Horizontal Scaling
All services are stateless and can be scaled horizontally:
-
Database connections are pooled per instance — every replica adds its full pool plus its detached-lease sessions to the server budget; re-run the arithmetic in Database Setup → Database connection budget before scaling out
-
RabbitMQ competing consumers distribute events across instances
-
Services with in-memory caches (craig-rules) use exclusive subscriber queues for cache invalidation — every instance receives the invalidation event
Considerations
-
craig-rules caches compiled rule sets in memory. After mutations, a
rules.cache_invalidatedevent triggers every OTHER instance to run an identity-aware reconcile pass against the database (#1188: a conditional per-name apply on the trigger-enforced(id, revision)token — never a wholesale reload, so a pass can’t clobber a concurrent local mutation). Since #1216 the event staging is transactional with the rule-set write (a staging failure rolls the mutation back), and each instance ALSO runs a periodic reconcile sweep (CRAIG_RULES__DECISION_REFRESH_SECONDS, default 300) that bounds lost-event staleness to ≤ ~2×interval + pass duration under a healthy DB (with the DB unreachable the sweep warns and retries next tick); replica sweeps de-phase via a deterministic per-instance start offset. -
craig-reporting holds a federal-report generate’s rows (AFCARS records, NCANDS child rows) in memory until its one commit and runs one such generate per instance; size its memory per the Sizing (#2154, #2206) note under Environment Variables → craig-reporting.
-
Object storage is shared — all instances read/write to the same S3 bucket.
-
Keycloak JWKS is fetched at startup and auto-refreshed periodically. No inter-instance coordination needed.
Monitoring
Health Checks
All services: GET /livez (k8s liveness, always 200), GET /readyz (k8s readiness, 200/503), GET /healthz (JSON detail). See Health Checks above for the full table.
Metrics
Every service serves Prometheus text at GET /metrics. Instruments export only when
OTEL_EXPORTER_OTLP_ENDPOINT is set (otherwise the endpoint returns an empty 200 —
the devstack default).
Database session exhaustion is directly observable via the db_pool_* family (#1160),
wired to every service’s pool by the shared bootstrap:
-
db_pool_connections_max/db_pool_connections_size/db_pool_connections_idle— scrape-time pool facts (in_use = size - idle).size == maxwithidle == 0is pool saturation;size < maxalongside rising acquire waits means the SERVER ceiling — the pool cannot grow because Postgres is refusing new sessions (see Database Setup → Database connection budget). -
db_pool_acquire_wait_seconds— wait of the most recent acquire probe (a timedacquire()every 15 s). -
db_pool_acquire_probe_timeouts_total— probes that failed to obtain a connection at all: the 5 s acquire-timeout cliff, observed rather than inferred.
sqlx additionally logs any single acquire slower than 2 s at WARN on target
sqlx::pool::acquire (its built-in acquire_slow default) — a free per-request signal
that complements the sampled probe.
craig-cases also exports the person-matching latency pair (#1157):
person_match_candidates_per_entry and person_match_entry_eval_duration_seconds —
per ranked report entry, how many candidates were seeded and how long the (bounded, 8
in flight) rules-evaluation phase took.
Outbound calls made through craig_common::telemetry::send_with_metrics (every BFF
Transport call, and the service clients built on it) record the pair
http_client_requests_total / http_client_request_duration_seconds, labelled caller
(the emitting service), target, method, status (status="0" = no response). The two
BFF hosts label their own calls: craig-web caller="craig-web", craig-portal
caller="craig-portal". Before #1954, craig-portal’s samples carried caller="craig-web",
so a panel or alert that watched the portal through that label must select
caller="craig-portal".
Logging
Structured JSON logging via tracing + tracing-subscriber:
{"timestamp":"2025-01-01T00:00:00Z","level":"INFO","target":"craig_rules","message":"server listening","addr":"0.0.0.0:8001"}
OpenAPI / Swagger UI
Each API service serves Swagger UI at /swagger-ui:
-
craig-rules: http://localhost:8001/swagger-ui
-
craig-cases: http://localhost:8002/swagger-ui
-
craig-placement: http://localhost:8003/swagger-ui
-
craig-exchange: http://localhost:8004/swagger-ui
-
craig-financial: http://localhost:8005/swagger-ui
-
craig-reporting: http://localhost:8006/swagger-ui
-
craig-security: http://localhost:8007/swagger-ui
-
craig-intake: http://localhost:8008/swagger-ui
CI/CD Pipeline
A merge train is the merge gate (ADR-086): each car runs the whole battery (the gates, the one compile, the unit, integration, E2E, SDK, security and perf-smoke lanes) in one car job, described below. The pre-push hook runs the fast subset (cargo xtask validate --profile fast).
Beside the car, three CI stages execute in this order:
-
scan: SAST (GitLab template), secret detection, dependency scanning, and the
cargo deny checkadvisory-DB, licence and source check. -
promote:
release-build, the one job that pushes images (planci-dev-loopD3, #3045); see Release images. On tagsrelease-notesrenders the tag’sCHANGELOG.adocsection as Markdown, followed by a Container images list of every promoted service’s$CI_REGISTRY_IMAGE/<service>:<tag>(xtask changelog notes --version <tag> --images "$CI_REGISTRY_IMAGE" --out release-notes.md, #3012), andreleasecreates the GitLab Release with that file as its description (release-cli v0.24.0 reads--descriptionas a file when the value is a whitespace-free path inside the working directory) andrelease-build’s SBOM as an asset link. The link names `release-buildby the id it hands over in itssbom.envdotenv report (/-/jobs/$SBOM_JOB_ID/artifacts/raw/…), not the ref: GitLab resolvesjobs/artifacts/<ref>only through the ref’s latest successful pipeline, so any unrelated failed job would 404 it (#3016). A tag with no== <tag>section inCHANGELOG.adocfailsrelease-notes, soreleasedoes not run (#2974). -
deploy:
pagesbuilds the Antora docs site on main. On an MR thedocsjob builds it instead and exposes the merge-request-scoped review environment.
Workflow rules restrict pipeline creation to four contexts: merge-request pipelines (gating merges), main-branch pipelines (post-merge, driving pages; release-build by hand), tag pipelines (releases), and scheduled pipelines (pentest/perf/cluster/triage).
On a merge-request or merge-train pipeline a failed job cancels the pipeline’s other jobs (auto_cancel: on_job_failure: all on that workflow rule, plan ci-battery-ahead D3; a job allowed to fail cancels nothing); the main, tag and schedule rule has no such setting, so a red job there never cancels release-build or a scheduled stack.
The scheduled policy-drift job (POLICY_DRIFT=true, allow_failure by doctrine) runs cargo xtask policy drift --jurisdiction georgia --jurisdiction federal --jurisdiction texas and publishes ONE policy-drift-report.txt; what it does and does NOT detect (the pinned artefact only — never a new annual CFR edition, an amendment published elsewhere or a new bulletin version, #1975) is stated in quality-gates § Citation audit gate (#1970; texas joined for its pinned url-class rows, #1974).
Feature-branch pushes without an open MR deliberately produce no pipeline: the MR’s car runs the battery, and suppressing branch-ref pipelines avoids duplicate CI runs on the same SHA.
Every Rust job runs in one image, craig-ci (ci/Dockerfile.ci, plan ci-compile-once D1, #2983):
rust:1.97.0-bookworm by digest with rustfmt and clippy, cargo-nextest, cargo-machete, cargo-deny and cargo-cyclonedx
(the one pin site for each), sops, age, git-lfs, the Docker CLI with its buildx and compose plugins from Docker’s
signed apt repository, and the cargo registry pre-fetched for the Cargo.lock it was built from. Every tool is a
pinned release binary verified by its checksum; no job installs anything at run time beyond a short allow-list the
pipeline contract test holds (ci-image itself, the one entry); the Antora jobs run craig-docs
(ci/Dockerfile.docs, Quality Gates § CI: the car). The image’s tag is the SHA-256 of ci/Dockerfile.ci and rust-toolchain.toml, never of
Cargo.lock (a lock change costs a delta fetch, not a rebuild), pinned in CRAIG_CI_IMAGE_TAG. The ci-image job
runs first in every pipeline (cargo xtask ci-image --ensure) and builds and pushes
$CI_REGISTRY_IMAGE/ci/craig-ci:<tag> only when the registry lacks it; every other job waits on it through needs:.
To change the image or the toolchain: edit ci/Dockerfile.ci (or rust-toolchain.toml), run cargo xtask ci-image
--bump and commit both; a stale pin fails the pipeline contract test. The first pipeline after the bump builds the
image (about ten minutes); later ones find it. Git LFS objects are fetched only where read: the clone skips them
(GIT_LFS_SKIP_SMUDGE: "1"), xtask e2e pulls its visual baselines (git lfs pull --include on the host side, after
the battery has judged the tree, #3046), and the Antora jobs smudge the docs screenshots.
The car’s shape is described in Quality Gates § CI: the car (plan ci-dev-loop D2,
#3046): ci-image → xtask → car ∥ docs, the car one job on one VM running the developer’s commands (the gates,
dev clean --any-project and dev start, then the lanes), blocking on a merge train (ADR-086 D2) and on a plain MR
that changes code or a stack input (#3028); it pushes nothing. xtask compiles xtask once and ships the binary to
every job that runs it (#2982). On a train the car leaves the unit tests to the battery (--leave-to-battery, #2995).
docs is the one Antora build: --log-failure-level=warn (the xref gate), the review environment’s site, and the
external-link verdict, which exits 42 on a dead link; the job allows exactly that exit, also on a train, and advises
on a plain MR; a docs-only MR runs it alone. feature-matrix runs on main and the schedule, never on a car (a bundle that stops building alone is a
post-merge fix). pages stays its own job on main, as GitLab Pages publishes only a job of that name.
A push to main repeats nothing its merge train proved (plan ci-compile-once D4, #2985): the train ran the car on the
merged tree, so main runs no car and builds no image. A merge pushes no release image: release-build is manual on
main (plan ci-dev-loop D3, #3045). The advisory stacks leave the merge path:
| Job | On a push to main | On a schedule | Notes |
|---|---|---|---|
|
runs |
runs |
|
|
manual |
runs |
also on tags; see Release images |
|
no |
runs |
also on tags; |
|
runs (the first two when their inputs changed) |
runs |
|
|
no |
|
the train ran them on the same tree |
|
manual |
runs, every schedule |
brings up its own stack ( |
|
manual |
runs, every schedule |
each bakes its commit’s release images and measures
them ( |
|
manual |
no |
the issuer capacity procedure on the pipeline’s own release images (Identity capacity, #3166); never on a train or a merge-request pipeline |
|
manual |
the |
builds its own rig images (their build args differ) |
|
no |
every schedule; |
|
pentest and perf-load results are therefore weekly (the one schedule, #2651), not per merge; run them by hand on a main pipeline to check one
merge. To measure a branch before it merges, perf-load, perf-stress and issuer-capacity each run alone in a
measurement pipeline started on that branch with MEASURE=<job>
(Measurement pipelines, #3178).
See the .gitlab-ci.yml file at the repository root for job definitions and runner tags.
The operator image
craig-operator carries the two operator tools at the services' version (ADR-088): craig, which speaks to the
services' APIs, and craig-manage, which acts directly on a deployment’s databases, broker and object store
(CLI). It has no entrypoint: name the tool.
# craig reads its profiles from ~/.config/craig; mount the operator's.
docker run --rm -it -v "$HOME/.config/craig:/home/craig/.config/craig" \
<registry>/craig-operator:<tag> craig --profile <deployment> login --device
# craig-manage takes each target from a flag or the service's own variable; it has no default.
docker run --rm -e CRAIG_PLACEMENT__DATABASE_URL \
<registry>/craig-operator:<tag> craig-manage invariants --service craig-placement
The container runs as the non-root craig user (uid 10001), so a mounted profile directory must be readable and, for
craig login, writable by that uid. A tool that writes a report (reconcile, backfill-assignments,
quarantine-drain) writes it inside the container unless a directory is mounted for it. The image serves nothing and
has no health check. It was first built for the release after v0.4.0; no tag before that carries it.
Release images
docker-bake.hcl at the repository root names the release images (plan ci-dev-loop D3,
#3045). Its release group is the twelve deployable
services, built from the Dockerfile’s `builder chef stage under CARGO_PROFILE=release, and craig-operator
(The operator image), built from its own operator-builder stage. Its one feature build
argument switches on the services' declared release-features that a default build leaves off
(plugin-ssa-screening, in craig-web and craig-composition), and nothing else: cargo xtask release-artifact-gate
reads the bake file and fails on an undeclared or test-only feature, and walks the release graph under exactly those
features. Its release-stack group is the three devstack-only side images the smoke’s stack needs (craig-seed,
craig-mock-server and the self-signed TLS intake), built locally and never pushed.
The protected release-build job (stage: promote, resource_group: release) is the only job that pushes images. It
never runs on a merge request or a merge train; it runs:
-
on every tag pipeline;
-
on every scheduled pipeline of
main: the weekly baseline. The schedule lives in GitLab (Build → Pipeline schedules), owned by a maintainer, who creates it if it is missing; today it is "Weekly main", Mondays 06:00 UTC; -
by hand from any
mainpipeline (a manual job).
Its lines are developer commands, in this order: docker login to the registry and the Dependency Proxy; docker
buildx bake --file docker-bake.hcl release --load and docker buildx bake --file docker-bake.hcl release-stack, into
the VM’s daemon; xtask dev start --release (the stack on those images, compiling nothing), xtask perf --profile
smoke and xtask security --phase public-api against the shipped bytes; and last docker buildx bake --file
docker-bake.hcl release --push, which the same builder
serves from its cache, so the registry receives the bytes the smoke ran. Each of the job’s three bake lines also
carries --allow=fs.read=$CARGO_HOME/registry: the bake file passes craig-ci’s pre-fetched cargo registry as a build
context, a directory outside the checkout, and buildx refuses that read unless the command line grants it (#3059). A
hand run leaves CARGO_HOME unset for bake, so it passes no such context and needs no grant. The push is fail-closed: a red line before it
ends the job, so a failed smoke pushes nothing, and release publishes nothing.
When the smoke fails, the job keeps its containers' logs (#3167).
release-build is a stack job like the car: before xtask dev clean removes the stack, its after_script runs xtask
dev logs --to test-results/container-logs --skip-on-success, and the job uploads test-results/container-logs/, one
<container>.log per container, as its artifact (Build → Jobs → the job → Browse). The artifact is kept 30 days and
is developer-only: the repository is public and the logs carry the smoke’s data. A run that succeeds uploads none.
The SBOM is its own job, release-sbom. A release’s asset link points at the SBOM, so that artifact is public, and
a job’s artifacts have one access level, so it cannot share a job with the logs. release-sbom runs xtask sbom --out
craig-sbom-<name>.cdx.json --job-env sbom.env on a tag and on the schedule; the file is named after the tag on a tag
pipeline and the commit’s short SHA otherwise, and is kept with expire_in: never. release-build waits for it, so
nothing is pushed without an SBOM, and release reads the link from it. A hand run on main has no release-sbom
job and makes no SBOM: its images are a build to try, and a release is cut from a tag.
Every successful run pushes $CI_REGISTRY_IMAGE/<service>:<sha8>, the commit’s short SHA. Only a tag pipeline also
pushes :vX.Y.Z and moves :latest, so :latest tracks releases, never a weekly or manual build. A merge to main
pushes nothing. A deployer pulls a release by its tag; the Release page’s Container images list names every one.
To build and smoke the release images by hand:
export CRAIG_IMAGE_TAG=$(git rev-parse --short=8 HEAD)
docker buildx bake --file docker-bake.hcl release --load # --push only from release-build, after the smoke
docker buildx bake --file docker-bake.hcl release-stack
cargo xtask dev start --release # refuses a side image it cannot find
cargo xtask perf --profile smoke
cargo xtask security --phase public-api
Release tags survive the project’s container cleanup policy only if the policy’s name_regex_keep protects them.
Today it protects nothing (keep_n: 5, older_than: 7d, name_regex: ., name_regex_keep: null), so a release’s
images are deleted about a week after the cut, once five newer tags exist in each repository
(#3012). Setting the policy is a maintainer decision
(*Settings → Packages and registries → Cleanup policies). Set:
name_regex_keep: '^(v\d+\.\d+\.\d+.*|latest)$'
To check that a release’s images are present, inspect each tag. A missing one fails with "not found":
for service in craig-rules craig-cases craig-placement craig-exchange craig-financial craig-reporting \
craig-security craig-intake craig-intake-keyring craig-composition craig-web craig-portal; do
docker buildx imagetools inspect "registry.gitlab.com/gadhs/application/ccwis/craig/$service:vX.Y.Z" >/dev/null \
&& echo "ok $service" || echo "MISSING $service"
done