Deployment Guide

Table of Contents

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 craig realm

  • 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

CRAIG_<SVC>__PORT

varies

HTTP listen port

CRAIG_<SVC>__DATABASE_URL

—

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.

CRAIG_<SVC>__RABBITMQ_URL

—

AMQP connection string

OIDC_ISSUER

—

Public OIDC issuer URL for JWT iss validation (e.g. https://auth.example.com/realms/craig). Any OIDC-compliant issuer that supports the client_credentials grant works (Keycloak, authentik, Okta, Azure AD/Entra, ForgeRock, PingFederate, Auth0). Dex 2.45.1 does not qualify. CRAIG resolves the actual endpoints via OIDC discovery (<issuer>/.well-known/openid-configuration) at boot per Plan E § Step 2. See IdP integration guide.

OIDC_INTERNAL_URL

—

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 jwks_uri + token_endpoint host portions to match. Browser-facing endpoints (authorization_endpoint, end_session_endpoint) keep the public OIDC_ISSUER URL since those land in HTTP redirects.

CORS_ORIGINS

*

Comma-separated allowed CORS origins

BODY_LIMIT

2097152

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).

CRAIG_<SVC>__ATTACHMENT_BODY_LIMIT

unset → derived: CRAIG_STORE__MAX_UPLOAD_BYTES + 1 MiB (51 MiB under the defaults)

#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 DefaultBodyLimit, so uploads work out of the box while every other route keeps BODY_LIMIT. An explicit value MUST exceed the store’s per-file cap — the service refuses to boot otherwise (no headroom for multipart framing would let the whole-body 413 pre-empt the typed per-file 400). See Upload limits.

CRAIG_CONFIG_SOURCE (no service prefix)

— (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. georgia, texas) and its bundle/ directory carries the jurisdiction’s reference data; no service-prefixed variable names the jurisdiction. Required by craig-rules, craig-cases (its migration gate too), craig-placement, craig-exchange, craig-financial, craig-reporting, craig-security, craig-composition, craig-intake and craig-web: unset refuses start. A git+ layer also needs CRAIG_CONFIG_ROOT and the fetcher’s published volume mounted read-only.

CRAIG_<SVC>__ADMIN_UNIT_LABEL

— (required)

Display label for the administrative-unit concept (County, Region, Chapter, …​). Plan A § Step 12: no fallback default; service bails at boot if unset.

craig-rules

Variable Default Description

CRAIG_RULES__RULE_SET_AUTHORITY

config

Who owns the rule sets (ADR-087 § Amendment — #2956). config: the configuration layers own them, boot reconciles the database to the layers' rule-set files and the write routes answer 409 config-managed. api: the rule-set write API stays open and boot reconciles nothing. Any other value refuses boot. The jurisdiction that prefixes rule set names is the one CRAIG_CONFIG_SOURCE names, under both values.

CRAIG_RULES__EVAL_TIMEOUT_MS

5000

Budget for one rules evaluation dispatch, ms (valid 1..=25000; boot-validated). Elapsing returns 503 on evaluate and fails the domain-event handler (#784). Keep well below HTTP callers' shared 30s client budget.

CRAIG_RULES__FUNCTION_TIMEOUT_MS

min(5000, eval budget)

Per-NODE JS interrupt bound for JDM function nodes, ms (#1046). Explicit values must sit in 1..=EVAL_TIMEOUT_MS (boot-validated); the default derives, so lowering only the eval budget needs no coordination. See configuration-reference for the per-node vs per-dispatch semantics.

CRAIG_RULES__DECISION_REFRESH_SECONDS

300

Decision-cache sweep interval, s (valid 10..=86400; boot-validated; #1188 / the ADR-006 #1188 amendment). Each instance periodically reconciles its compiled-decision cache against the DB via the identity-aware (id, revision) CAS, bounding staleness after a LOST rules.cache_invalidated event to ≤ ~2×interval + pass duration under a healthy DB (≈10 min at the default). Replicas de-phase via a deterministic per-instance start offset. Devstack compose pins 15.

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

CRAIG_STORE__BACKEND

— (required; boot refuses when unset)

Storage backend (s3 or local; local is single-container disk, dev/test only)

CRAIG_STORE__BUCKET

—

S3 bucket name

CRAIG_STORE__S3_ENDPOINT

—

S3 endpoint URL

CRAIG_STORE__S3_ACCESS_KEY

—

S3 access key

CRAIG_STORE__S3_SECRET_KEY

—

S3 secret key

CRAIG_STORE__S3_REGION

—

S3 region

craig-placement

Variable Default Description

CRAIG_PLACEMENT__RULES_ENGINE_URL

http://localhost:8001

craig-rules base URL — since #1641 the {j}-placement-eligibility consult at placement activation and matching (relay-authenticated as the acting worker; a PlacementSettings field) as well as the authz RulesetSource. The compose sets the service host.

CRAIG_PLACEMENTEXPIRY_SWEEPINTERVAL_SECONDS

0

The license/training expiry notice sweep tick (#1641). 0 = no scheduler — the devstack posture (/readyz lists expiry-sweep as disabled); the operator run works regardless: since #1933 POST /v1/placement/expiry-sweep/run takes the body { "client_request_id": <uuid> } and answers 202 + Location: /v1/placement/jobs/{id} + the job — poll the Location (or craig home expiry-sweep) until succeeded; the pass report is the job’s result. One pass per tick under the deployment-wide placement-expiry-sweep lease; a replica behind a peer-held lease skips the tick, an enqueued job WAITS for it (waiting_for_lease).

CRAIG_PLACEMENTEXPIRY_SWEEPLEAD_DAYS

30

Days ahead of an expiry the expiring notice is raised (1..=365, boot-validated). WHEN to warn only — whether an expiry gates activation or matching is the eligibility ruleset’s arm, never this knob.

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

CRAIG_FINANCIAL__PORT

8005

HTTP listen port

CRAIG_FINANCIAL__DATABASE_URL

—

PostgreSQL connection string

CRAIG_FINANCIAL__RABBITMQ_URL

—

AMQP connection string

OIDC_ISSUER

—

Public Keycloak URL for JWT iss validation

OIDC_INTERNAL_URL

—

Internal Keycloak URL for JWKS fetching

CORS_ORIGINS

*

Comma-separated allowed CORS origins

BODY_LIMIT

2097152

Maximum request body size in bytes

craig-reporting

Variable Default Description

CRAIG_REPORTING__PORT

8006

HTTP listen port

CRAIG_REPORTING__DATABASE_URL

—

PostgreSQL connection string

CRAIG_REPORTING__RABBITMQ_URL

—

AMQP connection string

OIDC_ISSUER

—

Public Keycloak URL for JWT iss validation

OIDC_INTERNAL_URL

—

Internal Keycloak URL for JWKS fetching

CRAIG_REPORTING_FIELD_ENCRYPTION_KEY

— (required in required mode)

#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 required-mode boot refuses, naming the variable. Boot verifies it against craig_reporting’s crypto_key_lineage (verify-only). Since P-D4 U2 (#2177) it also seals every stored AFCARS export; no sealed export opens without it. See Configuration Reference

CRAIG_REPORTING__ENCRYPTION_MODE

required

#2138: required refuses boot without a valid CRAIG_REPORTING_FIELD_ENCRYPTION_KEY; optional permits a keyless boot (unit-test / non-PII deployments only). Any other value fails boot

CORS_ORIGINS

*

Comma-separated allowed CORS origins

BODY_LIMIT

2097152

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 × N over its idle RSS, 336 MiB at N = 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 at C = 100 000; read C from a prior submission’s record_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_key report_generate, a dispatch label (no engine lease), so a second generate of either kind waits queued, 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 exhausted with no submission.

craig-security

Variable Default Description

CRAIG_SECURITY__PORT

8007

HTTP listen port

CRAIG_SECURITY__DATABASE_URL

—

PostgreSQL connection string; the serving process must log in as craig_security_app and the migrate gate as craig_security_owner (§ Per-service DB roles, #2739)

CRAIG_SECURITY__RABBITMQ_URL

—

AMQP connection string

OIDC_ISSUER

—

Public Keycloak URL for JWT iss validation

OIDC_INTERNAL_URL

—

Internal Keycloak URL for JWKS fetching

CORS_ORIGINS

*

Comma-separated allowed CORS origins

BODY_LIMIT

2097152

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

CRAIG_INTAKE__PORT

8008

HTTP listen port

OIDC_ISSUER

—

Public Keycloak URL for JWT iss validation

OIDC_INTERNAL_URL

—

Internal Keycloak URL for JWKS fetching

CRAIG_INTAKE__CASES_URL

—

Base URL of craig-cases (for forwarding authenticated reports)

CRAIG_INTAKE__SECURITY_URL

—

Required (integrated mode). Base URL of craig-security (partner verification + signer-key lookup)

CRAIG_INTAKECLIENT_ID / CRAIG_INTAKECLIENT_SECRET

—

Required. OIDC client_credentials principal for intake’s outbound S2S calls

CRAIG_INTAKE__IP_HASH_SECRET

— (required)

Per-deployment HMAC secret for received_ip_hash — set to a random value per deployment

CRAIG_INTAKE__PUBLIC_RATE_LIMIT

5

Max requests per hour from a single client IP against public (unauthenticated) endpoints. The devstack overrides this to 100000 to keep concurrent E2E submits from hitting the gate; production should leave the conservative default. All intake rate limits (this one and the partner-scoped rate_limit_rpm) are per-instance by design (ADR-017 §Amendment #269): each replica’s bucket fills independently, so the effective cluster-wide limit is the configured value × replica count — size limits accordingly, and front intake with an edge/gateway limiter if a deployment needs precise global quotas.

CRAIG_INTAKE__PARTNER_RATE_LIMIT

36000

#3083: max requests per hour from a single client IP against the partner API (/partner/v1), counted before the API key is checked. 36000 an hour is 600 a minute, the other services' per-IP RATE_LIMIT_RPM default. Partners that share one egress address (several systems behind one NAT) share this budget: raise it where their combined traffic from that address exceeds 600 a minute, and set CRAIG_INTAKE__TRUSTED_PROXIES when intake sits behind a load balancer, or every partner shares the balancer’s bucket. A burst is capped at one minute’s worth (the ceiling / 60), so a partner batch larger than that sent at once sees 429s. 0 refuses the boot. The devstack sets 6000000 (a burst of 100000). Per-instance, like the limit above.

CRAIG_INTAKE__CORS_ORIGINS

*

Comma-separated allowed CORS origins

craig-web (BFF)

Variable Default Description

CRAIG_WEB__PORT

8080

HTTP listen port

CRAIG_WEB__RULES_URL

—

craig-rules base URL

CRAIG_WEB__CASES_URL

—

craig-cases base URL

CRAIG_WEB__PLACEMENT_URL

—

craig-placement base URL

CRAIG_WEB__EXCHANGE_URL

—

craig-exchange base URL

CRAIG_WEB__FINANCIAL_URL

—

craig-financial base URL

CRAIG_WEB__SECURITY_URL

—

craig-security base URL

CRAIG_WEB__OIDC_INTERNAL_URL

—

Keycloak realm URL (for OIDC)

CRAIG_WEB__KEYCLOAK_CLIENT_ID

craig-ui

OIDC client ID

CRAIG_WEBCLIENT_ID / CRAIG_WEBCLIENT_SECRET

required under auto / introspect

craig-web’s confidential client_credentials principal for outbound service calls, and the principal it introspects an opaque / JWE login access token as (#2686). Boot refuses to start without both unless CRAIG_WEB__TOKEN_VALIDATION_MODE=jws

CRAIG_WEB__TOKEN_VALIDATION_MODE

auto

How the login access token is validated (#2686): jws (JWKS only), introspect (RFC 7662 only) or auto (a JWS through JWKS, an opaque / JWE token through introspection). See IdP Integration § BFF login

WEB_EXTERNAL_URL

—

Public URL of the web UI (for OIDC redirect)

CRAIG_WEB__SESSION_SECRET

—

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 openssl rand -hex 32 and store via your orchestrator’s secret store.

CRAIG_WEB__SESSION_MAX_AGE_SECS

1800

Session cookie lifetime in seconds (default: 30 minutes).

SESSION_SECURE

true

Emit the Secure flag on the session cookie. Set to false only for non-HTTPS dev loops.

CRAIG_WEB__THEME

— (required)

Theme directory name — since Plan U Step 8 (ADR-036) used only to resolve the agency logo (static/themes/{name}/logo.svg); the per-jurisdiction color palette comes from the jurisdiction layer’s bundle/theme.toml, served as /assets/theme.css, not an override.css. Plan A § Step 12: no fallback default.

CRAIG_WEB__BRANDING_AGENCY

— (required)

Agency display name in the BFF chrome (e.g. "GEORGIA DEPARTMENT OF HUMAN SERVICES"). Plan A § Step 12: no fallback default.

CRAIG_WEB__BRANDING_APP_NAME

CRAIG

App display name in the BFF chrome.

CRAIG_WEB__BRANDING_LOGO_URL

—

Optional logo URL.

CRAIG_WEB__UPLOAD_BODY_LIMIT

11534336 (11 MiB)

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 (CRAIG_<SVC>__ATTACHMENT_BODY_LIMIT, derived 51 MiB by default — #974) and ≤ the ingress body-size cap, or uploads 413 at whichever tier is smallest. See Upload limits.

CRAIG_WEB__TRUSTED_PROXIES

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 Forwarded: for= header — so backend per-IP rate limits key on the browser, not the BFF. Two knobs must pair: list your ingress CIDR here, and list craig-web’s CIDR in each backend’s CRAIG_<SVC>__TRUSTED_PROXIES (or the relayed header is ignored as spoofable). An invalid CIDR fails startup. Empty is correct when browsers reach craig-web directly (no fronting proxy): the TCP peer is the client.

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

capacity

1

capacity: C, stepped up until G3 breaks, and R from it

gates

R

gates: G1–G8

gates-below

R − 1

gates: the R − 1 replicas must carry the peak

kill

R

kill: G3 with a killed replica

rolling

R

rolling-restart: G3 through a rolling restart

keys

10

rolling-restart: the published keys against the registry model

  • 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. kill and rolling share 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, --r is refused.

  • Choosing steps. --steps kill,rolling --r 3 runs a subset, always in the table’s order. --window-secs, --warmup-secs, --seed and --archive-rate pass through to every cell; --cell and --replicas are 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, and summary.md with 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 s some average of /proc/pressure/io, each unknown when 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 perf run does.

  • In CI. The issuer-capacity job runs the procedure on its pipeline’s commit: by its play button on a main pipeline, 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. Set ISSUER_CAPACITY_ARGS (for example --steps kill --r 3) to pass options: beside the play button on main, or as a second variable of the measurement pipeline. It has a 4 h timeout, and keeps test-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 /readyz answers 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.yml therefore raises the issuer’s CRAIG_SECURITY__IDENTITY_TOKEN_RATE_LIMIT_RPM to 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_log under the issuer’s grants (the writer’s statement path), first with no load and then under the design load. Probe rows are refused rows with refusal capacity_probe and replica id 00000744-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 from pg_stat_activity by replica address, counting only the request pool (application_name craig-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_NOFILE to 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 its devstack-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:WALWrite and IO:WalSync: 1.8 and 0.8 pool connections plus the log writer on a broken 50/s step, and 6.2 on WALWrite at 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, /report returns 404 — craig-web no longer serves it. (The repo ships no in-repo gateway; ingress is operator infrastructure per ADR-017.)

Route /report and /report/* → craig-intake (:8008); all other paths → craig-web (:8080).

nginx
# 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;
Kubernetes Ingress (path-based; longest-prefix wins)
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.

  1. Ingress / reverse proxy — nginx client_max_body_size (default 1 MiB) or ingress-nginx proxy-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).

  2. Public edge (craig-intake, the portal path) — CRAIG_INTAKEPUBLIC_MAX_FILE_BYTES (default 10 MiB, #1324) under CRAIG_INTAKEBODY_LIMIT (default 11 MiB); the signed nest carries its own CRAIG_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.

  3. 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).

  4. Storing backend — CRAIG_<SVC>ATTACHMENT_BODY_LIMIT on 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 inner DefaultBodyLimit (the shared craig_api::attachment_body_limit helper; axum’s body extractors read the innermost limit). Unset derives CRAIG_STOREMAX_UPLOAD_BYTES + 1 MiB of multipart-framing headroom. Every other route of those services — and every route of every other service — keeps the global CRAIG_<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.

  5. Object store — CRAIG_STORE__MAX_UPLOAD_BYTES (default 50 MiB), the per-FILE cap enforced while buffering the file part (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):

  1. 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.

  2. Deploy the surface release (#1071 MR-B) with CRAIG_FINANCIALSUBSIDY_IMPORTENABLED UNSET/false — it is knob-off inert (every import write refuses with a typed 403 naming the knob; GETs work).

The conversion window:

  1. Enable — set CRAIG_FINANCIALSUBSIDY_IMPORTENABLED=true on 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 reads failed(refused_at_start) naming it.

  2. Stage — run craig --profile <deployment> subsidy import --manifest <json> --records <jsonl> (from the craig CLI; 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 is ApprovalAction::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.

  3. 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) and aged_suspension warnings: 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.

  4. Finalize — the tool’s finalize step POSTs { client_request_id } ONCE (#1938, plan background-jobs U6; --finalize-request-id <uuid> pins the id for wrapper scripts, else one is minted per invocation) and craig-financial answers 202 with an import_finalize job 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-token cannot be re-minted, so the tool exits naming the job and craig 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 the queued row and refuses with nothing enqueued. The job runs passes of the per-record engine until the batch leaves finalizing: succeeded with result.status = finalized is the closeout; result.status = staging means a pass rejected records (correct, restage, re-run). A job that ends failed leaves the batch finalizing exactly 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) or no_progress (three consecutive passes moved nothing; error.detail carries remaining_staged / passes — read the financial log for the record that cannot advance; a failed job carries no result, 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>, --yes skips 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 its payment_cutover_month, review slots materialized from the imported anchors (the conversion baseline — SHINES keeps pre-cutover review history).

  5. 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):

  1. 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 / SubsidyBackpayBatch read as a coverage gap fleet-wide until the files are live (a boot bail wherever AUTHZ_REQUIRE_FULL_COVERAGE=true): craig rules bootstrap target/config/layers/<j>/<j>-authz-subsidy_backpay.json and …-authz-subsidy_backpay_batch.json per activated jurisdiction, as a human admin (the BackgroundJob precedent in Background jobs rollout). Both ship admin-only. The devstack needs no bootstrap. No migration rides #2225.

  2. Roll the image with CRAIG_FINANCIALSUBSIDY_BACKPAYENABLED UNSET/false: every backpay write (batch create, stage, supersede, finalize, abort) refuses with a typed 403 feature-disabled naming 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).

  1. 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 and create client_request_id <id> before the create (a re-run with the SAME --request-id replays the one batch). The batch freezes the reconcile floor at creation. A line at or above that floor_month is refused before any stage POST: abort the empty batch and re-run without it. Each line then stages staged (the priced row frozen), rejected (typed blockers) or a replay, at --throttle-rps (1 to 10, default 5). run-<batch>.json and rejections-<batch>.jsonl land in --out (default backpay-run). A run that stops mid-file (a 401, a batch-wide refusal, a transport failure) prints craig backpay stage --file <f> --batch-id <id>. That resume reads the ledger once and skips every key already live in the batch.

  2. Review: craig backpay show --batch-id <id> posts nothing. It prints the batch header and every record, then, for a staging or finalizing batch, the review: every priced-row field of each live record, the gross total and content 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 as a 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.

  3. 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 409 backpay-finalizer-staged is 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 checksum show printed) 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 prints finalize client_request_id <id> before the ONE POST (--finalize-request-id pins it), then the job id and the deep link /financial/subsidy-backpay/<id>?job=<job>, and polls the job; see the backpay_finalize bullet in Background jobs rollout.

  4. Verify: the tool exits 0 and prints the post-finalize counts (every manifest key materialized); the web detail page’s ?job=<id> mount reads succeeded; the payments exist as pending.

  5. Pay: finalized payments are born pending and pass the ordinary approve → issue chain before money leaves.

  6. Disable only to stop every backpay write (the kill switch): a restart, after which queued finalize jobs end lost_proof; running ones interrupted (a graceful restart) or crash (a killed process); the batch stays finalizing, and craig 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 abort read.

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 (refused_at_start names the knob, engine_failed points to the runbook below, exhausted says escalate).

3

Operator action required: rejected or refused records, a pass that sent the batch back to staging, a classified service refusal, or a local refusal (the file checks, the floor pre-check, the review gate, a wrong confirmation). The printed lines name each record and its remedy. A rejected row or a record-scoped refusal (a 404, batch-conflict, backpay-judgment-moved, backpay-record-diverged, subsidy-approval-context-stale) is reported on its line while staging continues with the next line; only a batch-stopping refusal or a local refusal stops the run, and nothing past it was posted.

4

Resumable: the job keeps running, or the batch stays finalizing. The printed line names the resume command.

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>), then craig backpay supersede --record-id <id>, then stage the month again: into the same batch with stage --file <f> --batch-id <id> while it is staging (ruling F-B), else into a new batch. Superseding before the void is 409 backpay-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 with craig adjustment approve <id> (CLI); the record stays. Supersede is 409 backpay-month-disbursed.

  • A diverged record (a finalize pass sent the batch back to staging; finalize lists each one with its key and blockers and exits 3): supersede --record-id <id>, then stage --file <f> --batch-id <id>, then finalize again.

  • A poisoned or unwanted staging batch: craig backpay abort --batch-id <id> prints the batch and posts nothing; add the global --yes to 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 (409 batch-state) once the batch is finalizing.

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_payload that no longer decodes. Each pass classifies it as an infrastructure error, so the record stays staged, and three barren passes give failed(no_progress). The WARN backpay finalize: infra error; the record stays staged names the record_id and variant = 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 (show and finalize exit 1).

  • Case 2, a canonicalization failure. It is pass-fatal (failed(engine_failed), detail Store, the log names canonicalization failed), and unreachable today under NUMERIC(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 reads failed (a fresh id answers 409 job-already-active until the classifier stamps the dead job, stale after 30 s), then run craig 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 confirmed content_checksum (the resume does not re-verify it);

  • a long waiting_for_lease: a peer holds subsidy-backpay-finalize:<batch_id>; check pg_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:

  1. 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-override v1.0 files (georgia, texas, testonia — testonia is a fixture the seed never loads), the intake-screening OUTPUT-enum bumps (georgia-intake-screening v1.4 / texas-intake-screening v1.3) and the georgia-authz-investigation / texas-authz-investigation 1.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 the response_priority enum is NOT READY (response-priority-enum-missing), so the screening act and conversion answer the typed 503 screening-surface-not-ready until 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).

  2. The referral cutover (#1746, migration 20260910120000_referral_response_priority) is a STOP-THE-WORLD cases cutover. The migration DROPS referrals.priority and bumps schema_compat_floor to 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 a RAISE NOTICE counting the referrals that have no authorizing_decision_id — born by the retired direct-create route, they stay UNDERIVED for 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.priority became response_priority + provenance on the read side, POST /v1/cases/reports/{id}/convert refuses a priority field with a typed 422 on the write side, and POST /v1/cases/referrals is gone (a routing 405 — the collection root is read-only).

  3. 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 the v_investigations view, 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’s response_timeliness view fields are serde-defaulted, so a web rolled ahead of cases still renders), but the investigation OPEN is deny_unknown_fields — an N−1 craig-web form or an N−1 CLI still sending response_due_at answers a typed 422 until it rolls, so roll web + CLI promptly after the cases image. A devstack needs cargo xtask dev reseed for the seeded provenance to appear.

  4. 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 rollback is the devstack / CI snapshot restore only (a prior migrate snapshot; --force for 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-IP CRAIG_RULES__RATE_LIMIT_RPM for one evaluation per conversion and one per open from the cases pod(s) (plus one lazy roll-up for each pre-cutover UNDERIVED referral 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-deadline answers 403 response-deadline-override-refused with 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, and admin or any realm role the intake-screening surface does not map is 403 screening-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 sets skip_holidays (PAMMS 3.32 counts holidays as weekdays), so GA and TX deployments configure nothing. A jurisdiction whose window row DOES set skip_holidays must populate the calendar (entries plus a covered_from / covered_through span 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 through POST /v1/cases/reports (craig-web New Report, CLI craig intake submit-report). A referral whose roll-up answered NONE opens no investigation either (409 response-window-undefined naming 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

CRAIG_PARTNER_SECRET_<REF>

The value, inline. Wins over _FILE; empty counts as unset.

CRAIG_PARTNER_SECRET_<REF>_FILE

A path the value is read from on every send: at most 8 KiB, one trailing LF or CRLF stripped.

CRAIG_PARTNER_SECRET_<REF>_HOSTS

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 xn-- form, a normalized IPv4, an IPv6 host bracketed; no port, no wildcard.

CRAIG_EXCHANGE__PARTNER_AUTH_PLAIN_HTTP_HOSTS

Hosts a credential-bearing partner may reach over plain http:// (default empty: https:// only).

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 _FILE changes 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-unavailable or auth-misconfigured for 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_HOSTS sends credentials to it in clear.

  • Failures. A credential problem holds or fails jobs under an auth-* class (auth-unsupported, auth-misconfigured, auth-unavailable, and auth-refused for a trigger record the partner answered 401 or 403); auth-unavailable and auth-refused retry 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, for auth-unsupported / auth-misconfigured admissions, --held-reason. A manual send the partner answered 401 or 403 rides the shared retry ladder to retries-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 \u escape of a non-ASCII byte, a Go-style \u003c for < or \u0026 for &) 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}/test presents the configured credential, so it needs partner update, and reports auth_applied (the scheme presented; /health may 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:

  1. person_index_identifier_kind in bundle/settings.toml, naming a declared identifier kind: the kind an index’s id is recorded under. Without it every act answers 409 person-index-unconfigured.

  2. The ruleset <jurisdiction>-person-index-choice, which reads count and top_score and answers selection_open, selectable_from (present exactly when selection is open) and registration_open. The jurisdiction’s rule_evaluation authorisation must admit the workers who may update a case, since the ruleset is consulted under the acting worker’s authority (403 rules-consult-denied otherwise).

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:

  1. 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 403 feature-disabled, naming the variable. A variable naming an interface the partner set has no person index for stops craig-exchange at boot.

  2. One partner row: exactly one active partner of that interface, with an endpoint and a usable credential (503 otherwise).

  3. An agreement: that partner’s data-sharing agreement is active today (409 dsa-not-active otherwise).

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:

  1. 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.

  2. The listener: CRAIG_EXCHANGERETURNSPORT, and three PEM files: CRAIG_EXCHANGERETURNSTLS_CERT_FILE and …TLS_KEY_FILE, the listener’s own certificate and key, and CRAIG_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.

  3. 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.

  4. 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} with caller_partner_id). One caller has one active row per interface kind.

  5. An agreement: that partner row’s data-sharing agreement admits today.

  6. craig-cases: CRAIG_EXCHANGE__CASES_BASE_URL names 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:

  1. 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-unavailable and retries.

  2. Apply the exchange migrations. All three bump schema_compat_floor DELIBERATELY. A pre-#1828 exchange binary must refuse to start because it would claim resolve / record jobs 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).

  3. 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.

  4. Configure the partner. The interface must resolve to exactly ONE active exchange_partners row 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, …).

  5. Catch up the stages that opened before the trigger existed. cargo xtask is not the tool here — this is a running-deployment act:

    craig-cli exchange trigger-catch-up --interface cprs --kind case
      Run 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 cprs
    The 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.

  1. 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).

  2. The exchange migration adds exchange_outbound_recipients.subject_identifier_id (the GTID row a recipient was listed under, an id, never the GTID) and BUMPS schema_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 terminal unresolvable-dispatch.

  3. The partner: exactly one active exchange_partners row with adapter_kind = doe_slds, carrying an admitting agreement. Its credential, if it needs one, is provisioned as Outbound partner authentication (#1813 / ADR-083) describes.

  4. Catch up the episodes opened before admissions were recorded, once:

    craig-cli exchange trigger-catch-up --interface doe_slds --kind custody_episode
      It 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:

  1. Consent: CRAIG_EXCHANGECOLLECTIONSDOE_SLDS__ENABLED=true (default off). Until it is set a run is refused 409 collection-disabled and nothing is enqueued or fetched.

  2. The owner: CRAIG_EXCHANGE__PLACEMENT_BASE_URL names craig-placement, which stores each reported record. craig-exchange stores none of them.

  3. 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

succeeded

A run was recorded. The job’s result is that run: its transaction_id, its status, its failure class and the counts. status completed means craig-placement took every admitted report. status failed means DOE’s file could not be read (failure is the partner failure’s class, and nothing was applied) or craig-placement did not take every report (failure is apply-failed:<n>). Run a failed run again.

failed, refused_at_start

The run did not start: DOE was not called and nothing is recorded. error.detail says what did not hold: collection-disabled (the consent was turned off after the enqueue), collection-undeclared, partner-unresolved:<class> (no single active DOE partner row with an endpoint and a usable credential) or agreement-does-not-admit (the partner’s data-sharing agreement does not admit today). Fix it and run again.

failed, exhausted

Three attempts in a row were interrupted by a shutdown or lost their replica. Each interrupted attempt recorded its own failed run. Run again.

failed, engine_failed

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:

  1. 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 human admin, before the first image. Every engine-bearing service enumerates all resource types at boot, so EducationPartnerReport reads as a coverage gap fleet-wide until the file is live: a boot bail wherever AUTHZ_REQUIRE_FULL_COVERAGE=true, and elsewhere every read of a partner report is refused. The devstack needs no bootstrap.

  2. 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 failed until 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):

  1. Enter the caregivers (U7, the staff caregivers panel) for every active home and kinship placement.

  2. 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) (--strict exits non-zero on any gap). Name the placement database with --database-url or CRAIG_PLACEMENTDATABASE_URL (there is no default) and the cases database with --cases-database-url or CRAIG_CASESDATABASE_URL. Repeat until the residual gaps are understood — every gap is an enrollment the check will refuse.

  3. Issue invitations (the U6 enrollment act) — the portal payments route serves a caregiver only once a binding exists.

  4. Enable — set CRAIG_FINANCIALSUBSIDY_CAREGIVER_CHECKENABLED=true on 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 log caregiver_check_would_refuse + count subsidy_caregiver_check_total{boundary,outcome="would_refuse"} — watch that series reach zero on real traffic before flipping; after the flip the same misses are outcome="refused": typed 400 subsidy-party-not-caregiver naming parties[i], the person and the date, zero rows written. An outcome="facts_unavailable" series means a craig-placement that predates #1851 (roll placement first — knob ON, that read is a 503 at both boundaries).

  5. 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, the guardianship_finalized witness 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

CRAIG_PORTAL__PORT

required (8080 in compose)

HTTP listen port

CRAIG_PORTAL__OIDC_ISSUER

required

The OIDC issuer as the browser reaches it

CRAIG_PORTAL__OIDC_INTERNAL_URL

unset

In-network issuer URL for discovery / token calls (split DNS)

CRAIG_PORTAL__KEYCLOAK_CLIENT_ID

required (craig-portal-ui)

The PUBLIC code + PKCE client the caregiver’s browser authenticates against

CRAIG_PORTAL__REDIRECT_URI

required

This host’s /callback URL (must end with /callback; /welcome is derived from it for post-logout)

CRAIG_PORTALPLACEMENT_URL / CRAIG_PORTALFINANCIAL_URL

required

The two backends the portal reads (dedicated /v1/<svc>/portal/ projections, U8 / U9)

CRAIG_PORTAL__SESSION_SECRET

required (≥ 64 bytes)

Private / signed cookie key material

CRAIG_PORTALCLIENT_ID / CRAIG_PORTALCLIENT_SECRET

required

The confidential craig-portal service client — the outbound channel; there is no bearer fallback. Also the principal the portal introspects an opaque / JWE login access token as (#2686)

CRAIG_PORTAL__TOKEN_VALIDATION_MODE

auto

How the login access token is validated (#2686): jws (JWKS only), introspect (RFC 7662 only) or auto (a JWS through JWKS, an opaque / JWE token through introspection). See IdP Integration § BFF login

CRAIG_PORTAL__SESSION_SECURE

true

Secure on every cookie (false only on the plain-http devstack)

CRAIG_PORTAL__SESSION_MAX_AGE_SECS

1800

Session cookie Max-Age (the client idle timeout)

CRAIG_PORTAL__DEFAULT_LOCALE

en

Locale when neither the session tier nor the request negotiates one (en / es ship)

CRAIG_PORTAL__LOGIN_RATE_LIMIT_RPM

30

Per-client-IP /login requests per minute (problem+json on refusal); 0 disables

CRAIG_PORTAL__ENROLLMENT_RATE_LIMIT_RPM

10

Per-client-IP POST /enrol requests per minute (U10, #1853); a refusal is the "too many tries" flash + 303, not problem+json; 0 disables. Placement’s own CRAIG_PLACEMENT__ENROLLMENT_RATE_LIMIT_RPM (5, per IP AND per subject) sits behind it and answers the same flash

CRAIG_PORTAL__UPLOAD_RATE_LIMIT_RPM

30

Per-client-IP certificate-upload POSTs per minute (U10); a refusal is a flash + 303 back to the documents page; 0 disables

CRAIG_PORTAL__UPLOAD_BODY_LIMIT

11534336 (11 MiB)

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

CRAIG_PORTAL__TRUSTED_PROXIES

unset

Comma-separated CIDRs whose Forwarded / X-Forwarded-For the client-IP walk trusts — the ingress in front of the portal. Every per-IP limiter here (login / enrol / upload) keys on the caregiver’s browser only when this names that hop; pair it with the portal’s CIDR in CRAIG_PLACEMENT__TRUSTED_PROXIES so placement’s enrollment quota does too

CRAIG_PORTAL__BRANDING_AGENCY / _BRANDING_APP_NAME / _BRANDING_LOGO_URL

required / CRAIG Family Portal / shipped mark

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:

  1. Bootstrap the family on craig-rules BEFORE any financial image that consults it. rules promote targets an EXISTING set, so the first load is the one-time craig rules bootstrap target/config/layers/georgia/georgia-administrative-authority.json --profile <env> [--bearer-token …] as a human admin (signed in with craig login --device otherwise; service principals are denied rule_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.sh loads every top-level .json of each config layer (rulesets/<j>/.json until U4).

  2. Verify by name. GET /v1/rules/sets/by-name/georgia-administrative-authority answers 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).

  3. Later versions ride the two-step promote. Run cargo xtask authority-evidence <candidate.json> target/config/layers/<j>/evidence/administrative-authority.toml first: it replays every evidence key through the engine against the candidate and prints authority-evidence:<sha256>. The in-process family never populates rule_evaluations, so its canary is thin by construction; craig rules promote … --acknowledged-thin-corpus refuses the family unless --reason quotes that digest (ADR-074 decision 13). The command knows the family by the document’s name, whatever the candidate file is called, and recomputes the digest from the candidate and the evidence/administrative-authority.toml in the candidate’s own directory, so keep the two together.

  4. Then deploy the consuming financial image (U2 onward) and watch its authority_surface_verified{jurisdiction} gauge read 1 (the authority-surface-verifier Critical worker re-verifies every 60 s; a stuck 0 after boot is the alert). Until it does, every human approval act answers 503 and writes nothing; consented system automation 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 + revision that 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.

  1. Deploy the craig-security image carrying U1a, then bootstrap the NEW family. {j}-authz-worker_admin_unit is a family no environment has — rules promote bails on its by-name 404, so the first load is the one-time craig rules bootstrap target/config/layers/georgia/georgia-authz-worker_admin_unit.json --profile <env> [--bearer-token …] and the same for target/config/layers/texas/texas-authz-worker_admin_unit.json (×2: every jurisdiction the deployment activates), as a human admin (signed in with craig login --device or craig login on 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 the worker_admin_unit ruleset.

  2. Deploy the image carrying U1b, then PROMOTE {j}-authz-worker_identity to 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 for target/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.

  3. Gate: craig rules drift --rulesets target/config/layers --strict --profile <env> [--bearer-token …] green. The command walks exactly the file set cargo xtask rules check compiles 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::Value equality 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) or current. Versions order numerically, component by component, over semver 1.3.0 and the seed’s v1.0 default (a missing component reads as 0); a pair with a side of any other shape (a pre-release suffix, say) is never ordered and reads behind. It prints one line per file with the remedy and a summary whose every count is derived from the walk. --strict exits non-zero after the table when any file is absent, behind or ahead; testonia files print as fixture (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 new worker_admin_unit files and the two 1.3.0 worker_identity files read current; anything else the command reports behind or ahead is pre-existing drift in that environment, and the remedy on its line is the act.

  4. (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_unit key to case.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 two 20260916140000_admin_unit_stamp migrations through the ADR-063 gate (additive — nullable admin_unit columns with partial indexes, no schema_compat_floor bump) and roll every placement / financial replica; the cases 20260916140000_investigation_admin_unit migration backfills investigations.admin_unit from referrals by itself (total). Finally craig-manage backfill-assignments --yes once per environment, with the four service databases named (CLI § craig-manage; without --yes it prints its targets and stops): after the revision-guarded pair legs it runs a revision-independent unit-fill pass (both case_assignments projections, then placements, kinship_options, subsidy_agreements, payments, payment_adjustments via the payments JOIN) and prints units filled per 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 two subsidy_agreements statements, 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 with agreement child … appeared behind the backfill’s child locks, that case’s agreements unwritten; run it again.

  5. (U3b, #1902) Roll the craig-cases, craig-placement and craig-financial images carrying the check census — images only, no migration, any order. Every authz.check on the ten unit-bearing types now carries attrs.admin_unit from 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 (the get_payment shape) on the thirteen handler paths the CHANGELOG lists, and a field proposal whose foster-home row is gone answers 404 foster home on accept and reject.

  6. (U2, #1903) Set CRAIG_<SVC>SECURITY_BASE_URL on 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::SecurityUnitsSource reads GET /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 every security.worker_admin_unit.* event (a per-instance exclusive queue <svc>.authz-cache.units.{uuid} — inside every service’s existing authz-cache broker ACL, so no credential changes), and installs a snapshot only when its registry_generation exceeds the held one (equal re-confirms, lower is refused with a warning). The leaf is the shared security_base_url — lifted from the placement extension by #1903, env names unchanged (CRAIG_PLACEMENTSECURITY_BASE_URL included); the devstack compose sets http://craig-security:8007 on the seven, and a container left on the http://localhost:8007 default reads unreachable. 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} = 1 on every engine-bearing service (the authority_surface_verified shape) BEFORE any ruleset that consults claims.admin_units is promoted — /readyz is deliberately not the signal. A 0 with an error-level log naming rules promote is step 2 undone in that environment (the 1.3.0 row is missing → 403 → forbidden); a 0 with unreachable is the URL or the network. Until the gauge reads 1 a consulting ruleset answers 503 ADMIN_UNITS_UNAVAILABLE with the closed reason as detail (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 reading 1 is step 7’s precondition. CRAIG_<SVC>ADMIN_UNITSMAX_AGE_SECS (default 300, at least 1) bounds a snapshot’s age: older answers stale until the next verified pass.

  7. (U4, #1904) Promote every Texas file rules drift reports behind — the unit-scoped regional_director rows (ADR-077 D7) — file by file, over the verified gauge. Precondition: admin_units_snapshot_verified{jurisdiction="texas"} = 1 on 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 503 ADMIN_UNITS_UNAVAILABLE — admin included; only bare service principals short-circuit the consult. A Georgia-only deployment promotes nothing here: its files read current, 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 as behind (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, current at the step-3 gate) and texas-authz-rule_evaluation (the #1624 director rows), each 1.3.0 → 1.4.0 with the retired input dropped and those rows unchanged — so worker_identity reading behind again after the step-3 gate is expected, not a regression. A file reading ahead (#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 promote takes 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 polls GET /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-token it exits non-zero printing the job id and craig 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 is rule_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 on ruleset.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.sh converges every fixture to its (name, version) (a PUT under If-Match on the bump). Observable flips to record: a regional_director bound 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 is i_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 retired i_regional role 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, and rules drift then reports the tree behind until 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

expiry_sweep

/v1/placement/expiry-sweep/run

placement

proof-less

expiry_sweep (one per jurisdiction)

expiry

convergent: the system re-queues interrupted / crash up to 3 attempts and any replica adopts a stale queued row; re-POST a FRESH id only after failed(exhausted)

archive_run

/v1/security/archive/run

security

proof-less

archive_run (one per jurisdiction)

retention-archive

convergent as above; failed(refused_at_start) (knob OFF) or failed(no_progress) (a barren pass) → resolve the cause, re-POST a fresh id

promote_preview

/v1/rules/sets/{id}/promote/preview

rules

proof-less

promote_preview:<rule_set_id>

promote:<rule_set_id>

convergent as above; failed(engine_failed) live-revision-moved → a fresh preview

ncands_generate

/v1/reporting/ncands/generate

reporting

proof-less

ncands_generate:<ffy>

report_generate (a dispatch label shared with afcars_generate, #2206 — no engine lease)

convergent as above; failed(engine_failed) (a cases page hung / 5xx’d / decoded malformed — zero rows written) is TERMINAL → re-POST a fresh id once cases answers

afcars_generate

/v1/reporting/afcars/generate

reporting

proof-less

afcars_generate:<label>

report_generate (a dispatch label shared by every half, #2154, and with ncands_generate, #2206 — no engine lease)

convergent as above (the recovery read first: an attempt whose submission already committed completes over it); failed(engine_failed) (detail one of the closed tokens surface_not_ready, jurisdiction_unmapped, not_generable, view_unavailable, financial_unavailable, placement_unavailable, placement_out_of_order, cases_batch, cases_unavailable, cases_key_index, derive, assembly, count, encrypt, chain_forked, lineage_mismatch, db, exemption_row_missing, exemption_excluded, assist_record, predicate_unbound, arms_exhausted, applicability_cycle, tardy_rows_missing, cited_aggregation, finalize_conflict — zero rows written) is TERMINAL → re-POST a fresh id once the cause clears

subsidy_generate

/v1/financial/subsidy-payments/generate

financial

proof-less

subsidy_generate:<YYYY-MM>

subsidy-gen (shared by every month)

convergent as above (the payment_month identity makes a re-run free); succeeded with errors > 0 is the unchanged partial-success posture; failed(engine_failed) below_reconcile_floor (the month fell below the 12-month floor while queued, #2228) is TERMINAL → re-POST only for a month inside the bound

import_finalize

/v1/financial/subsidy-imports/{id}/finalize

financial

CONSENT

import_finalize:<batch_id>

import:<batch_id>

never re-queued, never adopted: crash / lost_proof / interrupted → failed, the batch stays finalizing; re-POST a FRESH id and the new job resumes per record exactly once; failed(no_progress) → correct, restage, fresh id

backpay_finalize

/v1/financial/backpay/batches/{id}/finalize

financial

CONSENT

backpay_finalize:<batch_id>

backpay:<batch_id>

never re-queued, never adopted: crash / lost_proof / interrupted → failed and the batch stays finalizing; once the old job reads failed, re-POST a FRESH id with the same reviewed content_checksum (not re-verified on resume) and the new job resumes per record exactly once; failed(no_progress) → the stuck-finalizing runbook

sweep_preview

/v1/financial/subsidy-reviews/sweep/preview

financial

proof-less

sweep_preview:<jurisdiction>

sweep (a dispatch label — no engine lease)

convergent as above (a cut attempt wrote nothing: the previewed run and succeeded commit in ONE tx); the token is a separate POST …/sweep/runs/{run_id}/token inside 15 min

sweep_execute

/v1/financial/subsidy-reviews/sweep/{run_id}/execute

financial

CONSENT

sweep_execute:<run_id>

sweep

never re-queued, never adopted: failed with the run stamped failed, counters as committed, the preview burned — the remedy is a FRESH PREVIEW, never a second execute of the same run

collection_run

/v1/exchange/collections/run

exchange

proof-less

collection_run (one per jurisdiction, whichever interface and leg)

collection

convergent as above, and an interrupted attempt records its own failed run; succeeded with status failed in the result is a recorded run that failed (the partner’s document unread, or reports the owner did not take) → re-POST a fresh id; failed(refused_at_start) (consent off, no usable partner, an agreement that does not admit) → resolve the cause, re-POST a fresh id (Collecting DOE’s weekly student data)

Per environment, in this order:

  1. Bootstrap the authz family on craig-rules BEFORE the first image carrying U1 — every engine-bearing service enumerates ALL resource types at boot, so BackgroundJob reads as a coverage gap fleet-wide until the two files are live (a boot bail wherever AUTHZ_REQUIRE_FULL_COVERAGE=true): craig rules bootstrap target/config/layers/georgia/georgia-authz-background_job.json --profile <env> [--bearer-token …] (and the texas- twin where activated) as a human admin; idempotent — an existing row is reported, nothing recreated. The devstack needs no bootstrap (seed.sh loads every top-level *.json of each config layer). The read policy: admin realm-flat; the CREATOR (a human or a service principal, by assigned_worker_sub); everyone else the fleet’s typed 403; an unknown id is 404.

  2. Roll craig-cases BEFORE craig-reporting (#1936). The reporting → cases NCANDS hop is a pre-1.0 S2S wire change: GET /v1/cases/ncands-export is PAGED (as_of REQUIRED, after / limit, the NcandsExportPage body) 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 IGNORES as_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 (the created_at ⇐ as_of exclusion never applied); a large one trips the 8 s per-page budget, the attempt ends engine_failed with zero rows written — a TERMINAL failed job (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_of REQUIRED) and its synchronous generate answers the upstream error — nothing is written.

  3. Roll the image. The background_jobs + background_job_attempts migrations are ADDITIVE (no schema_compat_floor bump) and ship with the executor in the same image through the ADR-063 gate. /readyz gains the Critical background-jobs worker on every adopting service — placement (#1933), security (#1934), rules (#1935), financial (#1937), reporting (#1936), exchange (#3190) — (the executor; its background-jobs-retention pruner is implicit, Observed, disabled at window 0). Every caller of a flipped route mints the now-REQUIRED client_request_id in the SAME release (the CLI craig 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 own POST /financial/subsidy-reviews/sweep/runs/{run_id}/token and poll the execute job); financial’s generate, preview and execute have NO CLI command — a caller mints its own id and polls with craig job wait financial <id>). Reporting’s executor needs CRAIG_REPORTING__CASES_BASE_URL to resolve from the WORKER plane (the cases client is built before the workers spawn; the request path only enqueues).

  4. Set the retention knob if the default does not suit. CRAIGBACKGROUND_JOBSWINDOW_DAYS (deployment-global, default 31 = the claims window + 1, 0 disables): 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 least CRAIGREQUEST_CLAIMSWINDOW_DAYS + 1.

The re-POST rule per kind, what an operator lives with:

  • The SAME client_request_id replays the SAME job (202 again, whatever its state — a failed job replays as failed); a FRESH id is a new job, admitted by the arbiter only when no job of that (jurisdiction, dedup_key) is queued / running (else 409 job-already-active — poll the active one).

  • Convergent kinds (expiry_sweep U1, archive_run U2, promote_preview U3, subsidy_generate U5, ncands_generate U4, sweep_preview U7): an attempt cut by a rollout (interrupted at 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 as attempt + 1, up to max_attempts (3), then failed(exhausted); a queued row whose owner died before handoff is ADOPTED by any replica. No operator act is needed until exhausted; 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 a crash / lost_proof / interrupted attempt ends the job failed and is NEVER adopted or re-queued; the operator re-POSTs with a fresh id (either finalize resumes per record; a sweep run reads failed with 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 the retention-archive lease for its LIFE, so the hourly scheduled archiver SKIPS its tick (an info log, no heartbeat on retention-archive) while the job runs. The D11 knob is checked twice — the synchronous 403 at enqueue, and failed(refused_at_start) naming RETENTION_ARCHIVE__ENABLED if it was flipped OFF before the attempt. succeeded at more = false with a D13-isolated table’s per_table[].error visible in result (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) while more stayed true (read the log for the row that cannot advance, resolve it, then re-POST with a fresh id). archive/purge is 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 ends failed(engine_failed) (detail live-revision-moved) — a fresh preview is the remedy; the previews row and --confirm-preview <preview_id> are unchanged; the execute stays synchronous (Standard).

  • subsidy_generate (financial, #1937): POST /v1/financial/subsidy-payments/generate with the body { "client_request_id": <uuid>, "month": "YYYY-MM" } (month optional; it resolves at enqueue to [current − 12, current] on the Eastern business clock; the nil-id SubsidyAgreement / Approve check 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 shares lease_key = subsidy-gen — the engine’s own lease — so an instance runs one month at a time and keeps the others queued (no permit held). The hourly scheduled tick keeps taking that lease directly: while a job holds it the tick SKIPS (an info log, no subsidy-generator heartbeat) and converges next hour; while the tick holds it a job attempt reads waiting_for_lease. Proof-less and convergent: a crash / interrupted attempt re-queues (the checkpoint sits BEFORE each child’s transaction and the payment_month identity makes the re-run free — no second payment), so re-POST only after exhausted, 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) fails engine_failed (below_reconcile_floor, #2228) with nothing written and is never retried — re-POST for a month inside the bound. succeeded with errors > 0 is the unchanged partial-success posture (WARN logs keyed by result.run_id). Every run from EITHER initiator writes one subsidy_generation_runs row (initiator scheduled | manual, job_id / attempt on the job’s, outcome, the report, a categorical error) — the operator’s ledger of what ran for a month; a lease-busy tick writes none. claims/generate is unchanged: synchronous, Standard.

  • import_finalize (financial, #1938 — the first CONSENT kind): POST /v1/financial/subsidy-imports/{id}/finalize with the body { "client_request_id": <uuid> } (the import knob, authz, the subsidy-writes gate and the state-floor ImportHistory proof 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: a crash / lost_proof / interrupted attempt ends the job failed — never re-queued, never adopted — and the batch stays finalizing exactly 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) naming SUBSIDY_IMPORT__ENABLED), declares progress.total = expected_count and counts one done per record, and runs passes of the per-record engine until the batch leaves finalizing: succeeded with result.status = finalized, or staging (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 it failed(no_progress) with remaining_staged / passes in error.detail — a failed job carries no result; the batch detail GET is the ledger. A peer replica holding the engine’s subsidy-import-finalize:<batch_id> session lock reads waiting_for_lease (never the old 409); a second job for the SAME batch while one is queued / running is 409 job-already-active; a POST after the batch is finalized is a new job whose single pass is the deterministic replay. The operator surface is craig subsidy import (one POST, then the shared poll; a failed job 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}/finalize with the body { "client_request_id": <uuid>, "content_checksum": <64 lowercase hex> } (the backpay knob, authz on subsidy_backpay_batch finalize, the subsidy-writes gate and the state-floor BackpayFinalize proof 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 — 409 backpay-finalizer-staged, 409 manifest-mismatch with the leg named, 409 batch-state on an aborted batch, 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 end lost_proof; running ones interrupted (a graceful restart) or crash (a killed process); the batch stays finalizing exactly as the record ledger left it. Once the old job reads failed, re-POST with a FRESH id and the same reviewed content_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) naming SUBSIDY_BACKPAY__ENABLED), declares progress.total = expected_count, and runs passes of the per-record engine until the batch leaves finalizing: succeeded with result.status = finalized, or staging (a record diverged or a manifest key is not materialized — supersede, re-stage, finalize again); three consecutive passes that moved nothing end it failed(no_progress) with remaining_staged / passes in error.detail → the stuck-finalizing runbook. A peer replica holding the engine’s subsidy-backpay-finalize:<batch_id> session lock reads waiting_for_lease; a second job for the SAME batch while one is queued / running is 409 job-already-active; a POST after the batch is finalized is a new job whose single pass is the deterministic replay. The operator surface is craig backpay finalize (#2226: the review, the confirmed checksum, one POST, then the shared poll; a resumable failed job 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/preview with the body { "client_request_id": <uuid> } (the supervisor review_sweep authz 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 = sweep is the executor’s dispatch label — a preview takes NO engine lease). Proof-less and convergent: a crash / interrupted attempt re-queues and a stale queued row is adopted — safe because the previous attempt wrote nothing (the previewed run row and the job’s succeeded commit in ONE transaction). Poll it: result is the pinned sets with token_state: available and resource links the run (/v1/financial/subsidy-reviews/sweep/runs/{id}) — NO token rides the job. Then POST /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’s started_at — 200 { run_id, execute_token, expires_at } under Cache-Control: no-store, shown once and never retrievable again; a second POST is 409 sweep-token-issued, a closed window 409 sweep-preview-expired with the run stamped expired (preview again), any other state 409 sweep-run-state. Then POST /v1/financial/subsidy-reviews/sweep/{run_id}/execute with { "client_request_id": <uuid>, "execute_token": "…", "acknowledged_suspend": n, "acknowledged_terminate": n, "acknowledged_handoff": n } — the regional SweepExecute office proof is minted synchronously BEFORE the claim (its 400 / 403 / 503 set unchanged) and an aged preview is stamped expired in its own statement (409 sweep-preview-expired); INSIDE the claim transaction the token digest (400), the acknowledged counts (409 sweep-preview-stale) and the previewed → consented flip (409 sweep-run-state on a replay or a second execute) — a refusal enqueues nothing and the run stays previewed, 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’s subsidy-sweep lease (a scheduled pass holding it is waiting_for_lease; a job holding it makes the scheduled tick SKIP — an info log, no review-sweep heartbeat), re-checks the office proof under it, moves the run consented → executing and commits the counters after EVERY agreement — the run detail GET shows them climbing. succeeded = the run completed with the SweepReport as result (partial success is still success). A CONSENT kind: a crash / lost_proof / interrupted attempt ends the job failed — never re-queued, never adopted — with the run stamped failed, 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 own POST /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 with craig job wait financial <id>.

  • ncands_generate (reporting, #1936): POST /v1/reporting/ncands/generate with 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_generate since #2206, the dispatch label it shares with afcars_generate: an instance runs one federal-report generate at a time, so a second waits queued, holding no permit, behind a running AFCARS or NCANDS generate; nothing ever reads waiting_for_lease here). Proof-less and convergent: the job’s input.as_of is 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 report received_at; a page that hangs past the 8 s hop budget, 5xxs or decodes malformed fails the attempt engine_failed with ZERO rows written (nothing rests before the final transaction) — TERMINAL failed on that attempt (an engine failure never re-queues; only a crash / interrupted attempt re-queues, up to 3, then failed(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’s succeeded commit together, so a crash between them cannot exist; a re-queued attempt that finds the submission already present completes without regenerating. result is the finalized submission (the pre-#1936 200 body) — review / approve / transmit it as before; resource is empty (no submission GET exists — the id is in the result). The CLI is craig 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/generate is 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’s post_extended 310 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_run job holding it for its life) shows as progress.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 is DOWNLOAD_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 s DEFAULT_TIMEOUT (intake: its own 20 s Standard ceiling). The two are ordered by construction for the default only: keep CRAIG_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 a Store logs 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 as download_stream_outcome_total{outcome="failed"} on the serving backend plus ONE correlated error line inside the request span (method / route and request_id, the X-Request-Id the response echoed); failed also counts a stored object shorter or longer than its head’s Content-Length. abandoned counts a peer that went away first, completed a full body (the declared length served). Alert on failed, 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 full Content-Length with a different sha256 adds one download_digest_mismatch_total{service} sample and logs ONE error line (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}/export with a fresh client_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 longer application/octet-stream; the two text exports are reporting’s bare text/plain, no longer text/plain; charset=utf-8) under the edge-wide nosniff + Content-Disposition: attachment; text exports are no longer gzip-compressed (attachment responses are exempt from the compression layer so Content-Length survives).

  • Downloads are resumable (#1948). Every download response carries Accept-Ranges: bytes and, when the object has a strong one, its ETag (the AFCARS export’s is the sha256 of the opened file). A single Range: bytes=a-b (or a-, or the suffix -n) answers 206 with Content-Range: bytes a-b/<length> and the slice’s Content-Length, and the body streams over that slice alone: the same 8 MiB ranged reads, tiled from a, never the whole object. A range that starts at or past the end answers 416 (the range-not-satisfiable problem document) with Content-Range: bytes */<length>. A malformed Range, another unit, or a multi-range request is ignored and answers the full 200: multipart/byteranges is never produced. If-Range lets the range through only when it is a strong entity-tag equal to the object’s ETag; a weak tag, an HTTP-date (no Last-Modified is sent) or a changed object answers the full 200, so a resumed download of a changed object restarts rather than splicing two versions. A HEAD is never ranged. The six edge routes forward Range / If-Range upstream and relay the 206 / 416 status with Accept-Ranges, Content-Range and ETag unchanged. A 206 is 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, a 416 included. Nothing to configure. An ingress or reverse proxy in front of the edges must pass those request and response headers and the 206 / 416 statuses through for resumption to work; one that drops Range only costs resumability (every download answers the full 200), and one that weakens the ETag (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 counts abandoned, not failed, so the failed alert stays a store signal — with one warn line (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-util http2 is 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:

  1. Bootstrap both documents on craig-rules BEFORE the U4 reporting image. A family that does not yet exist cannot be promoted (rules promote targets an EXISTING set), so the first load is the one-time craig rules bootstrap target/config/layers/federal/federal-afcars-2020.json --profile <env> [--bearer-token …] followed by craig rules bootstrap target/config/layers/georgia/georgia-afcars-crosswalk.json … (the crosswalk of every jurisdiction the deployment activates), as a human admin (the device-code grant otherwise; service principals are denied rule_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.

  2. Verify by name. GET /v1/rules/sets/by-name/federal-afcars-2020 and …/by-name/georgia-afcars-crosswalk answer the rows (by-name resolves ACTIVE rows only). Later versions ride the two-step promote; cargo xtask rules check is 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.

  3. Then deploy the reporting image. Its Critical worker afcars-surface-verifier re-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 gauge afcars_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 0 BY DESIGN on a P-A image. The check order ends layout-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’s AFCARS_RECORD_CONTRACT covers every oohc element (P-D2 U2, #2139) but no record layout until P-D5’s renderer, so a pinned dictionary still answers dictionary-unsupported-by-binary on its layout alone. A 0 after bootstrap is therefore not the alert — the reason token is. Nothing consumes the verified snapshot before P-D, so a 0 refuses nothing today.

  • The metadata GET is the operator’s probe. GET /v1/reporting/afcars/metadata (the same AfcarsSubmission nil-id read rows the detail GET consults; Cache-Control: no-store) projects the retained CANDIDATE, never the verified-only path: surface.state (verified | not_ready) with the closed reason token, the dictionary / crosswalk identities (rule_set_id, revision, content_sha256 — the ONE canonical hash in craig_rules_contracts::identity, the same body craig-rules records on the promotion snapshot, so the two agree by construction), current_period on the jurisdiction clock (the completed half stays CURRENT through its due date, a weekend due date rolled to Monday) and the crosswalk’s supported_from. Read it after bootstrap: not_ready / layout-unpinned with BOTH identities populated is the expected P-A state; dictionary-absent / crosswalk-absent means step 1 has not happened for that document; read-timeout names the rules hop; a structural token names the document that fails to parse or verify; jurisdiction-unregistered means the deployment’s bundle declares no business_timezone (bundle/settings.toml). Every field but the state is null while no candidate is retained.

  • What a new jurisdiction registers. The BLOCKING_JURISDICTIONS entry 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 its business_timezone() (the zone BusinessClock::try_for_jurisdiction resolves — that lookup IS the jurisdiction-unregistered check, #2207), its {j}-afcars-crosswalk.json — TOTAL by equality over every fleet_vocabularies() entry, so a vocabulary the registry does not yet carry is a registry entry first — with the manifest rows in its citations.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-id read row) 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:

  1. Roll craig-cases (U5 + U6a) BEFORE craig-financial (U6a) (#1996). A U6a financial against a pre-U6a cases gets 404 from the unrouted path, which it treats as a failure, never as "no plan": every guardianship activation answers the plan leg’s fail-closed 503 ("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 reads PlacementSubsidyEligibility.permanency_goal, which craig-placement keeps serving until step 3. There is no migration, no knob, no schema_compat_floor bump and no seed re-bless. After the roll the refusal is the cases plan in force at the transfer date: a child whose plan is reunification is refused with the unchanged 400, 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 by PLAN_S2S_BUDGET (4 s) and answers its own 503 naming the leg, inside the 20 s Standard ceiling.

  2. 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 reunification only 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.

  3. Roll craig-placement (U6b) (#1997). The eligibility read stops serving permanency_goal; the placements.permanency_goal column, 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:

  1. Roll craig-security first. Its parse arms record placement.cancelled as (update, placement) and placement.episode_facts_changed as (update, removal_episode), and the placement.episode_ and placement.cancelled families 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.

  2. Roll craig-placement: refuse-on-data, the floor bump, every replica replaced before traffic. The migration’s guard runs FIRST and refuses on ANY placements row: 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 names cargo xtask dev reseed for a disposable environment, and anything else needs a planned data migration first. The migration installs the trusted btree_gist extension as the owner role (the per-child exclusion constraints; see § Per-service DB roles). The floor bump to 20260925130000 is 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.

  3. Devstack. The migration’s -- devstack: wipe-before-apply marker makes the devstack wipe craig_placement and reseed it automatically. The seed derives one removal episode per placed child.

  4. 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 no cancelled row 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:

  1. 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_changed arm and the placement.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.

  2. Roll craig-web FIRST. Its strict decoders (the placement view’s and the end form’s PlacementEndReason) must know left_care before placement can store one. Its episode view is lenient, so a U4 craig-web reads a U3 placement: a missing exit is 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 a left_care end (a 400 flash).

  3. 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_reason strictly. Window hazard: the replaced ck_episode_current_instants also 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.

  4. craig-cli ships with the workspace. Its new craig placement episode exit record / correct / retract and craig placement episode historical commands need the U4 routes.

  5. craig-financial and craig-reporting deploy nothing (craig-reporting’s change is a test only; craig-financial has none). An arrangement ended left_care while 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 as guardianship, not left_care.

  6. 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:

  1. Roll craig-security first. It gains the parse arms and resource families for placement.retracted (update, placement) and placement.recorded (create, placement), and the arm for financial.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.

  2. Roll craig-web. Its strict PlacementStatus decoder must know retracted before 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).

  3. Roll craig-financial, EVERY replica. It binds placement.retracted and placement.recorded and carries the re-anchor. The craig-financial.events queue 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 drops replaces_placement_id from placement.activated silently (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.

  4. Roll craig-placement: the cutover, every replica replaced before traffic. The migration applies on boot through the migration gates, and its floor bump to 20260925170000 is its LAST statement. An N−1 craig-placement decodes status through the strict PlacementStatus enum 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.

  5. craig-cli ships with the workspace. Its craig placement retract, craig placement historical and craig placement create --replaces need the U5 routes. In the window before placement rolls, --replaces against a U4 placement is silently dropped (the create body is lenient): do not use it until step 4 completes.

  6. craig-reporting deploys nothing (its change is a test only).

  7. 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:

  1. On craig_placement: SELECT id FROM placements WHERE status = 'retracted' and SELECT id, replaces_placement_id FROM placements WHERE replaces_placement_id IS NOT NULL.

  2. On craig_financial: UPDATE placement_terminations SET retracted_at = now() WHERE placement_id = ANY(<retracted ids>) AND retracted_at IS NULL, then one INSERT INTO placement_replacements (placement_id, replaces_placement_id) VALUES (…) ON CONFLICT (placement_id) DO NOTHING per 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:

  1. Roll craig-security first. It gains the placement.episode_exited arm (update, removal_episode). A pre-U6a craig-security drops nothing: it records the key by the raw split, with episode_id already resolved by the placement.episode_ resource family.

  2. Roll craig-financial, EVERY replica. It binds placement.episode_exited. The craig-financial.events queue 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. Its placement.ended arms stop warning for guardianship and left_care endings. It decodes episode_exit leniently (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 no placement.episode_exited. The arms are log-only and no money moves, so the window is accepted.

  3. 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.

  4. Roll craig-web. Its one-step handoff records the guardianship exit. An older craig-web’s handoff records none, and the invariant flags each such row until a worker records the exit.

  5. craig-reporting deploys nothing (its change is a test only); craig-cli is unchanged.

  6. U6b gate. Run craig-manage invariants --service craig-placement against the environment. U6b rolls only when guardianship_ending_without_exit is EMPTY. Repair is truthful: record the guardianship exit at the arrangement’s end instant, or correct the live exit to it. From U6a, a placement.ended carrying left_care raises no WARN (the U4 section’s left_care sentence 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:

  1. 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.

  2. Gate — guardianship_ending_without_exit is EMPTY. Run craig-manage invariants --service craig-placement against

    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 reads OK: record the guardianship exit at the arrangement’s ended_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 whose ended_at is 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 with craig placement episode exit record <episode-id> --exit-at <ended_at> --exit-reason guardianship, or with craig 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.

  3. 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.

  4. 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.

  5. 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:

  1. Gate — every craig-financial at U6b, drained. A U6a financial still witnesses end_reason = guardianship: after the rewrite it would refuse every guardianship activation and guardianship_finalized termination.

  2. 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 keeps end_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.

  3. Take the craig_placement backup / PITR mark.

  4. 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_rewrites row.

  5. 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.

  6. 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-U6c placement.ended carrying guardianship raises the reason-blind B/E WARNs.

  7. 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:

  1. 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.

  2. 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.

  3. Take the craig_placement backup / PITR mark.

  4. 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.toml loses the goal line and changes together with the image (until U4, #2955, it rode the image, and a custom CRAIG_PLACEMENT__RULESETS_DIR was 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 same client_request_id answers 409 idempotency-conflict (the create intent changed).

  5. craig-cli and craig-reporting ship with the workspace; an older craig-cli’s --permanency-goal is 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:

  1. 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.

  2. 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 400 structural-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 NULL license_type on the home list, matching and the placement picker.

  3. 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:

  1. Roll craig-web (and craig-cli beside it).

  2. Roll craig-financial. It has no migration — payment_type keeps its tokens, the D5 rate class maps onto them — but it must decode the strict placement.recorded with its new keys before placement emits one.

  3. 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.

  4. 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:

  1. Roll craig-financial first (a rolling replacement is fine). Until every replica is replaced, an N−1 replica still stages missing_foster_home for a non-caregiving activation and craig-reporting queues a no_payment_activation warning (field foster_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.

  2. 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:

  1. a caregiver binding keys a placement that is not a home-less foster_family_home row;

  2. a home-less foster_family_home row has a NULL admin_unit — heal it with craig-manage backfill-assignments, then restart craig-placement;

  3. a home-less foster_family_home row’s created_by is not a UUID;

  4. 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:

  1. Roll craig-portal and craig-financial (either order; rolling replacement is fine). financial reads the new required child_arrangement_ids / payment_arrangement_ids of the authoritative bindings read; craig-portal reads the kinship_household unit kind.

  2. 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.

  3. Roll craig-web (and craig-cli beside it).

  4. 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 it craig rules drift --rulesets target/config/layers --strict reports both files behind. 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 for target/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:

  1. Roll craig-placement (rolling). An N−1 craig-financial ignores residence (its decode is lenient) and applies the old anchor-end rule to the widened episode_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 ERR guardianship_finalized termination) 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.

  2. 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:

  1. Roll craig-placement (rolling is fine).

  2. 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:

  1. Roll craig-placement, replacing EVERY replica before traffic (the floor is read only at boot; an N−1 replica refuses to start against it).

  2. 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:

  1. Roll craig-placement, replacing EVERY replica before traffic (the floor is read only at boot; an N−1 replica refuses to start against it).

  2. 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:

  1. Roll craig-placement, replacing EVERY replica before traffic (the floor is read only at boot; an N−1 replica refuses to start against it).

  2. 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:

  1. Roll craig-placement (rolling is fine).

  2. 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:

  1. Roll craig-cases, replacing EVERY replica before traffic (the floor is read only at boot; an N−1 replica refuses to start against it).

  2. 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:

  1. 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.

  2. Run the migration gate (craig-reporting migrate, § Migration gates).

  3. Start the U2 image.

  4. 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}/export with no body (every bare POST is a new operation) or, for an approved row, 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:

  1. Stop EVERY craig-reporting replica. A pre-U4 replica cannot decode the ready_for_transmission status and ignores the freeze, and the floor is read only at boot.

  2. Run the migration gate (craig-reporting migrate, § Migration gates).

  3. 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:

  1. Roll craig-cases, replacing EVERY replica before traffic (the floor is read only at boot).

  2. 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 surface identity (400);

  • a stale surface identity (409 ive-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:

  1. 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-eligibility carries metadata.ive, the surface read and the act answer 503 ive-surface-not-ready, detail metadata-absent. The verifier’s warning log names the defect. /readyz is 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.

  2. Promote the IV-E rulesets once no N−1 craig-cases or craig-web replica remains.

    • Promote each *-ive-eligibility file the environment holds; craig rules drift --rulesets target/config/layers --strict lists them as behind. 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 the vpa_* keys and ssa_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.

  3. 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 surface and 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):

  1. 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 fresh client_request_id, target_revision set to the revision the promotion moved FROM, expected_revision set to the live one, and a reason (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 (409 ive-policy-moved) or, once the cached surface is gone, the retry page (503); nothing is recorded.

  2. 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. --jti is the submission’s single-use id. --payload is 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 VALID or INVALID: 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 jti or 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 resolve pins 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 sync publishes 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

CRAIG_CONFIG_SOURCE

The ordered source list, lowest precedence first, in the one grammar the services read too (Configuration Reference): <name>=git+https://<host>/<repo>#branch=<b> or #tag=<t>, git+ssh://… the same, comma-separated. The fragment may add &verify= (head, tag or tag-and-head) and &sha=<commit> (the pin resolve writes). A path: source passes through unfetched. A name is lowercase letters, digits, - and _.

CRAIG_CONFIG_ROOT

Where the trees are published (/config in the image).

CRAIG_CONFIG_TRUST_DIR

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

head

The commit (git verify-commit --raw).

tag

The annotated tag object (git verify-tag --raw); a lightweight tag is refused.

tag-and-head

Both the tag object and the commit it points at.

Trust roots. For each source, in CRAIG_CONFIG_TRUST_DIR:

File Holds

<name>.allowed_signers

SSH signers, the ssh-keygen(1) allowed-signers format with namespaces="git".

<name>.openpgp

OpenPGP signers, one fingerprint per line (# starts a comment).

<name>.openpgp.asc

The public keys of the fingerprints in <name>.openpgp, ASCII-armored, one or more keys (gpg --armor --export <fingerprint>…, blocks may be concatenated). Required beside <name>.openpgp.

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

fetch.env

craig-config-fetch

Every layer config-sources.lock locks, in the lock’s order.

georgia.env

craig-rules, craig-cases (with craig-cases-migrate and craig-cases-rewrite), craig-placement, craig-exchange, craig-financial, craig-reporting, craig-security, craig-composition, craig-web, craig-intake, the three craig-intake-standalone* services and craig-seed

The federal entry, then the georgia entry.

texas.env

craig-intake-tx

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

CRAIG_CONFIG_TRUST_HOST_DIR (optional variable)

craig-config-fetch, mounted read-only at /trust

The host directory holding the trust roots (Trust roots above). Default ./ci/config-trust, relative to docker-compose.yml: the checkout’s own, which lists the signers of the three locked repositories.

devstack/field-key.env (required file)

craig-cases, craig-cases-rewrite and craig-seed

One line, CRAIG_FIELD_ENCRYPTION_KEY=<key>: the cases field key, shared with the seed (Configuration Reference § Deployment-Global Variables).

devstack/reporting-field-key.env (required file)

craig-reporting

One line, CRAIG_REPORTING_FIELD_ENCRYPTION_KEY=<key>: craig-reporting’s own key, never the cases key (the same section; its production channel is ADR-048 § Amendment — #949).

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

GET /livez

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.

GET /readyz

200 when no Critical worker is dead/missing AND DB + MQ report healthy; 503 with Retry-After: 5 and the discriminating body not ready: <check[, check]> (checks named in the fixed order workers, database, rabbitmq) otherwise

Kubernetes readiness probe and load-balancer signal. Failure → remove from service rotation without restart. Compose depends_on: condition: service_healthy also points here. Since #1186 (ADR-061) the gate covers the worker registry and genuinely covers the RabbitMQ parent connection (the pre-#1186 probe was silently DB-only); since #1235 it also covers the publisher CHANNEL (a dead confirm channel on a live connection fails readiness — healthz distinguishes disconnected from publisher channel closed). Since #2826 a dead publisher channel or connection also exits the process (see Shutdown & fail-fast exit).

GET /healthz

200 with detailed JSON: status + uptime_seconds + per-dep checks incl. a checks.workers array of {name, criticality, state, panicked?} entries (structured state only — raw panic/error text stays in logs)

Human/dashboard view. Always 200; the body’s status field carries the ok/degraded signal (an Observed worker death degrades here without failing /readyz). Use for ops dashboards, not probes.

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:

  1. Database migrations have completed

  2. JWKS has been fetched from Keycloak

  3. 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

  4. The HTTP listener is bound

  5. 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

outbox (all 8 backend services)

~1 s poll

> 60 s

request-claims-retention / background-jobs-retention (placement #1933, security #1934, rules #1935, financial #1937, reporting #1936, exchange #3190; every service that adopts a job kind) / reconcile-sweep (financial) / send-jobs-sweep (exchange)

hourly sweep (background-jobs-retention registers disabled when CRAIGBACKGROUND_JOBSWINDOW_DAYS is 0)

> 3 h

jwks-refresh (backends AND craig-web — #962 collapsed craig-web’s two per-policy tasks into one task over a shared key cache)

1 h refresh

> 3 h

oidc-discovery-refresh (craig-web)

configured discovery interval

> 3× the interval

authz-ttl-refresh (all authz-booting services)

policy_ttl/10, floor 30 s, ±25% jitter

> 6× the sweep period

events-subscriber (5 services — craig-rules' was retired by #1670) / audit-subscriber / dlq-subscriber (security) / cache-invalidation (rules) / composition-invalidation / authz-invalidation (all authz-booting services)

30 s consumer-liveness tick while a consume session is live (#1321; silent during reconnect backoff)

> 120 s

decision-refresh (rules)

configured refresh interval (devstack 15 s; default 300 s)

> 3× the interval

jws-cleanup (cases)

hourly

> 3 h

person-index-sweep (cases, #3192)

5 min pass (deletes person-index inquiries past their fifteen-minute expiry); beats only on a pass that completed

> 30 min

upload-attempt-reconciler (cases, exchange, placement, reporting — one shared label)

5 min pass; beats only on a clean pass

> 30 min

blob-janitor (cases, placement — one shared label)

5 min pass (#1274: heals entity-delete blob halves that never landed — soft-deleted rows still object_status = 'present' past a 1 h grace)

> 30 min

expiry-sweep (placement, #1641)

configured EXPIRY_SWEEP__INTERVAL_SECONDS; beats ONLY on a failure-free pass (a pass with failed notice transactions logs at error and bumps placement_expiry_notice_failures_total instead); absent when the interval is 0 (devstack)

> 3× the interval alerting on max() across replicas (a replica that keeps losing the lease stays silent — the review-sweep posture), OR increase(placement_expiry_notice_failures_total[<interval>]) > 0

collection-schedule (exchange, #3190)

a look every 60 s, or every COLLECTION_SCHEDULE__INTERVAL_SECONDS when that is shorter; beats ONLY when no consented collection’s newest counted run failed and no run of this look failed, was refused or was interrupted, so a failed collection run silences it until a run of that collection succeeds; absent when the interval is 0 (devstack)

> 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

background-jobs (placement #1933, security #1934, rules #1935, financial #1937, reporting #1936, exchange #3190 — Criticality::Critical: a dead executor fails /readyz; every service that adopts a job kind registers the same label)

every executor scan — a Notify wake or the 15 s tick, boot included; a running attempt additionally stamps its row’s heartbeat_at every 5 s (the 30 s stale classification reads THAT, not this label)

> 60 s

send-worker (exchange)

~1 s poll

> 60 s

detection-scheduler (security)

configured scan interval (60 s default; absent when Disabled)

> 3× the interval

subsidy-generator / review-sweep (financial)

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 subsidy_generate job holds subsidy-gen — a long manual month reads as staleness on this label, not a fault; since #1939 the review-sweep tick likewise SKIPS (an info log, no beat) while a sweep_execute job holds subsidy-sweep — a manual execute in flight reads as staleness here, not a fault

> 3× the interval, alerting on max() across replicas

partition-maintenance (security, #3173)

at boot, then hourly; beats on every successful pass, whether or not it made a partition

> 3 h

retention-archive (rules, security, exchange — #1566)

hourly + jitter; absent when the archive knob is off; on security the tick SKIPS (an info log, no beat) while an archive_run job holds the lease (#1934) — a long manual run reads as staleness on this label, not a fault

> 3 h

ssa-worker (exchange)

~1 s poll (knob-gated; absent when WORKER_POLL_SECONDS=0)

> 60 s

ssa-transport-sweep (exchange, #1566)

hourly; EXECUTED passes only (a lock-skip stays silent); absent when TRANSPORT_RETENTION_DAYS=0

> 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 nonzero evicted rate means stored ruleset content stopped compiling (direct-SQL writes — the API pre-validates); sustained failed means 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 the rule_evaluations disposition 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 stays timeout here while its row becomes late_completed. Infra-class errors (Db/staging/compile/not-found) count nothing. Alert on the timeout/runtime_error rate relative to completed.

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 DATABASE_URL=postgres://…​?sslmode=verify-full&sslrootcert=/etc/ssl/…​/ca.crt and RABBITMQ_URL=amqps://…​. Standard sqlx + lapin handle the verification.

Sidecar mTLS (Kubernetes service mesh — Istio, Linkerd)

Services connect to localhost in cleartext (or to the sidecar’s local listener). The sidecar handles mTLS to the actual DB / MQ. CRAIG sees the cleartext URL because the sidecar terminates TLS inside the pod.

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_FILE on 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.crt has 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_trgm and btree_gist extensions, apply without superuser; craig_placement’s owner installs btree_gist, #2018). Used ONLY by the migration gate; every migration-created object, including sqlx’s _sqlx_migrations ledger, is owned by it.

  • a runtime role — CONNECT + USAGE on schema public + table DML through the owner’s default privileges. Used by the serving boot: the verify-only path needs SELECT on _sqlx_migrations + schema_compat_floor (covered by the same grants), and DDL under this role fails with SQLSTATE 42501 — 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 every identity_ object, and craig_security_app, the serving login;

  • from U4: craig_security_issuer (the issuer process) and craig_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, a GRANT … 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. The Ahead no-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 — Behind is 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 — floor 20260912120000; refuses while any allegation or investigation still carries the retired inconclusive token.

  • 20260913120000_report_source — floor 20260913120000; refuses while ANY reports / referrals row exists (the new NOT NULL report_source has no backfill — the NCANDS source is a captured intake fact the reporter status does not determine).

  • 20261019120000_report_digest_keyed — floor 20261019120000; refuses while any reports row carries a received_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 the craig-cases-migrate one-shot carries; #1310), never the runtime DSN: the runtime role has no INSERT / UPDATE / DELETE on crypto_field_rewrites or crypto_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 against crypto_key_lineage before any row is read.

  • CRAIG_CONFIG_SOURCE (required; with CRAIG_CONFIG_ROOT and the published tree for git+ layers) — the layers whose bundle/search_schemes.toml declares the target scheme; an unset or refused source refuses as boot does.

  • CRAIG_CASES__ENCRYPTION_MODE=required — unset means required; 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):

  1. Roll the #1399 U1 fence release on EVERY craig-cases replica first (§ Migration gates) and ship the image whose bundle declares the new scheme.

  2. 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 of craig_cases too (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.

  3. Take a PITR mark / backup.

  4. <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.

  5. <binary> rewrite-scheme — the run (below). Exit 0 prints the report; exit ≠ 0 prints the refusal, which leads with the remedy.

  6. <binary> migrate — the gate; the marker now equals the resolved registry (reconcile case 1) and it no-ops.

  7. 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_error says which). Serving boot, the gate’s pre_apply and every non-owner persons writer refuse while a row is running or verifying.

  • 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 at rows_mutated = 0 (a pass-1 refusal on a fresh run, or --abort).

  • There is NO failed state: any refusal after the first committed batch leaves the row running / verifying with last_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 CRAIG_CASES__DATABASE_URL / MissingJurisdiction / ModeNotRequired / KeyLoad

Refused before the first connection; nothing was read or written.

Fix the invocation / the environment (above).

LockHeld { holders }

A participant connection lives — a serving replica, a gate, another tool run — named by pid / role / application_name.

Scale craig-cases to zero, end the named sessions, retry.

OtherBackends { backends }

A non-participant client (psql, a pooler, the seed) is attached; the lock does not fence it.

End it, retry.

SchemaNotExact { extra } / SchemaRefused

The schema is ahead of / diverged from this binary’s embedded migrations; nothing was written.

Run <binary> migrate with the binary whose migrations match, then retry with that binary.

KeyPreflight

The mounted key is not the one crypto_key_lineage records (KCV / canary), or the database is keyless.

Mount the serving key; nothing was read.

MarkerAbsent / MarkerExtraRow / MarkerUninterpretable

The gate never stamped the marker / the marker names a field this binary does not allowlist / the recorded spec cannot be reconstructed.

Run <binary> migrate first / restore the matching binary or reseed.

ConfigReverted { forward_target }

A row is live and the configuration now names the run’s ORIGIN scheme.

Set CRAIG_CONFIG_SOURCE back to the layers declaring the forward target and resume, or --abort while nothing was mutated.

ResumeKeyMismatch / NotOwnerOfLiveRow { db_user } / ResumeMismatch

The live row was started under another key / another role / another (from, to, table, column).

Mount the original key / resume as that role (the persons trigger admits only it) / resume with the original configuration.

Refused { row_id, refusal }

ONE row holds plaintext, an undecryptable cell or a mismatched sibling digest. Fresh run ⇒ the ledger row is closed aborted; resume ⇒ it stays running.

Repair or restore that row, re-run.

ConcurrentModification { row_id } / LeaseLost

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).

LedgerMoved / MarkerMoved / VerifyFailed { row_id, kind }

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 verifying.

Inspect, then re-run.

PostSwapReconcile

The swap IS committed; the in-process gate self-check refused afterwards.

Investigate before rolling serving — boot would refuse the same way.

NoLiveRowToAbort / AbortRefused { rows_mutated }

--abort with no live row / after a committed mutating batch.

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 via SET 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 the db_pool_* instruments (Monitoring → Metrics below). The constant lives in crates/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 sessions craig-<svc>-<role> — craig-cases-serving for the serving pool, craig-cases-events / craig-exchange-send / -reconciler for the dedicated worker pools, craig-<svc>-migrate-gate for the ADR-063 gate, craig-manage for the read-only operator reports (craig-manage invariants, reconcile, caregiver-coverage), and craig-xtask for verify-seed. Filter pg_stat_activity, pg_stat_statements, and pg_locks joins 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

Σ DB_MAX_CONNECTIONS (default 10 × 9 stateful services = 90)

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 craig-intake-keyring-serving and fixed at the default size (no DB_MAX_CONNECTIONS knob). Horizontal replicas multiply each service’s term.

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 application_name. Replicas multiply each term.

Detached advisory-lease sessions

+14 fleet-wide

PoolConnection::detach() releases the pool permit, so these sessions sit OUTSIDE pool accounting: craig-financial +4 (generator, review sweep, transport prune, reconcile sweep; +N more with the import knob on), craig-exchange +2 (transport prune, send-jobs sweep), craig-rules / craig-security +2 each (transport prune, retention-archive lease when enabled), +1 transport prune for each other stateful service. Exception: craig-intake-keyring carries no transport tables and no prune worker (its only advisory lock is transaction-scoped), so it adds no detached-lease term — the fleet total stays +14.

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

cargo xtask database commands cap their pools at 2; each psql session is one.

Superuser reserve

3

superuser_reserved_connections — unavailable to non-superuser service roles.

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

craig.events

topic

true

Domain-event fan-out — every service’s outbox publishes here; consumers bind their <svc>.events queues.

craig.dlx

topic

true

Dead-letter exchange (ADR-022) — nack-without-requeue and capture publishes route here under dlq.<queue>; only craig-security binds/consumes it.

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

craig-rules.cache.{uuid}

exclusive

rules.cache_invalidated

craig-placement.events

competing

case.created, case.assignment_changed, exchange.listing_ended (#3188: withdraws a partner’s report when craig-exchange stops listing the child)

craig-exchange.events

competing

case.created, placement.created, case.assignment_changed, case.screening_cohort_changed, plus every event key the active outbound-trigger matrix declares (#1828, #1829, #2343; inbox_routing_keys in craig-exchange’s main.rs). (#1313: eligibility.evaluated was retired from this binding set — platform-stabilization Step 5; financial pushes eligibility to exchange explicitly. craig-cases has produced the event since #1313 U6, for its financial and reporting consumers.)

craig-financial.events

competing

placement.activated, placement.ended, placement.retracted, placement.recorded (#2020), placement.episode_exited, eligibility.evaluated, case.ive_determination_invalidated, rules.evaluated, case.assignment_changed, case.created (#1632)

craig-reporting.events

competing

the wildcards case., placement., eligibility., financial.

craig-security.events

competing

# (wildcard — subscribes to all events for audit logging)

craig-cases.events

competing

case.report_converted (ADR-062 §G4 — the auto-link consumer, #1269)

craig-composition.composition-cache.{uuid}

exclusive

composition.invalidated.{jurisdiction}

<svc>.authz-cache.{uuid}

exclusive

authz.policy_changed — every service that runs the shared authz engine (all eight) declares one

<svc>.authz-cache.units.{uuid}

exclusive

security.worker_admin_unit.* — every service that runs the shared authz engine (all eight) declares one (#1903, ADR-077 D4); the handler only re-reads the admin-units snapshot. The authz-cache prefix keeps it inside each service’s existing broker ACL

craig-security.dlq

competing

dlq.# (bound to craig.dlx — the fleet-wide dead-letter audit consumer)

craig-security.dlq.parking + craig-security.dlq.quarantine

—

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_type other than classic on 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 to craig* 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 ignores x-queue-type on 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 destructive overflow policy to craig* queues: a TTL/length policy on the no-DLX DLQ or the parking/quarantine queues silently DESTROYS forensic captures, and expires deletes 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 to parked_at + parking_ttl (default 10 min) and returns it to craig.dlx with 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 at error! alongside the #1199 dlq_* 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’s capture_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):

  1. Consume from {queue}.quarantine with MANUAL acknowledgements.

  2. Validate the capture (payload._park): read original_routing_key (dlq.…) and inspect reason/last_error. Malformed captures (reason: "malformed") are excluded — they have no replayable route; export them to file.

  3. Republish the message bytes UNCHANGED to the craig.dlx exchange under original_routing_key, with publisher confirms + mandatory, and wait for the clean confirm.

  4. 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. Note definitions.json imports 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 password == account-name — a PUBLIC ACL fixture for local dev, never a containment boundary (the broker port binds the host, the hashes are in the public tree). Production MUST use a unique high-entropy secret per account (openssl rand -base64 24), stored in your secret manager (Vault / k8s Secret / AWS Secrets Manager) and injected as CRAIG_<SVC>__RABBITMQ_URL. Percent-encode any reserved characters (@ : / ?) in the password before placing it in the URL.

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:

  1. Roll the #1670 rules image and let every old replica drain (rabbitmqctl list_consumers -p / shows no consumer on craig-rules.events; /healthz lists no events-subscriber worker).

  2. Promote the strict rulesets — georgia-intake-screening v1.3 and texas-intake-screening v1.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.

  3. Clean the broker through the management API or rabbitmqctl: unbind case.intake_created from craig-rules.events, delete the queue, then set_permissions the new craig-rules triple (above).

  4. Deploy the cases act (U2, #1672) — the next section; the rulesets stay callable via POST /v1/rules/evaluate throughout.

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):

  1. Roll the N−1 cases image (it does not verify the screening surface).

  2. Re-promote georgia-intake-screening v1.2 / texas-intake-screening v1.1 from the previous tag’s checkout — the strict schema would otherwise fail every event the restored consumer feeds.

  3. Restore the grant, then the queue, then the binding (the reverse of step 3 above).

  4. 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:

  1. Steps 1–3 of the #1670 cutover above (the rules image, the strict rulesets, the broker cleanup) must have run.

  2. Roll the #1672 cases image. The migration is ADDITIVE (seven nullable provenance columns under an all-or-none CHECK, the screening_decision_evaluations table, the recreated v_effective_disposition; NO schema_compat_floor bump), so N−1 cases replicas keep inserting their eight-column rows during the roll. Each new replica boots the Critical screening-surface-verifier worker, 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 503 screening-surface-not-ready with a closed reason token — /readyz is untouched. The screening_surface_verified{jurisdiction} gauge is the operator alert: 0 after boot means the ruleset shape or the rules reachability needs repair (the verifier log names the specific defect).

  3. Roll craig-web and the CLI. An N−1 web or CLI against a #1672 cases answers a typed 422 (the removed actor_role is 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.

  4. Do NOT retire the {j}-screening-policy ruleset row yet. Nothing reads it after step 2, but DELETE /v1/rules/sets/{id} is a SOFT delete with no restore route (by-name resolution requires active = 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.

  1. 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.

  2. 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') answers 0.

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.

  1. 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.

  2. Check first: SELECT count(*) FROM screening_decisions WHERE rule_set_name IS NULL must answer 0.

  3. Roll the cases image. The migration gate applies the contract.

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.

  1. Stop every N−1 craig-cases replica first. An N−1 replica’s legal-status INSERT names no chain_seq and fails against the NOT NULL (23502). The floor stops an N−1 replica from starting, but not one that is already running.

  2. Roll the cases image. The migration gate applies the back-fill under an exclusive lock on legal_status_facts.

  3. Roll craig-web after cases. A legal-status row’s facts now carry a required chain_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:

  1. Promote {j}-placement-eligibility v1.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.

  2. Roll the #1641 placement image. Its migration is ADDITIVE (two partial indexes, the foster_home_expiry_notices ledger, the training-write lock trigger; no schema_compat_floor bump), applied by the ADR-063 gate. Set CRAIG_PLACEMENTRULES_ENGINE_URL; leave EXPIRY_SWEEPINTERVAL_SECONDS at 0 until the alert row is wired.

  3. 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_status is required) and renders the detail’s Pending sentinel.

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:

  1. Provision all per-service accounts + the two exchanges (above). The old shared craig credential stays valid throughout — additive, no service is touched yet.

  2. Deploy the per-service CRAIG_<SVC>__RABBITMQ_URL secrets and roll the fleet. Each service reconnects as its own identity.

  3. Verify consumption: rabbitmqctl list_consumers -p / shows each service’s queue attached under its own connection; readyz is green fleet-wide; no ACCESS_REFUSED in service logs.

  4. Retire the shared credential’s SERVICE use: confirm no connection remains authenticated as craig on the AMQP plane (rabbitmqctl list_connections user), then repurpose craig to the operator/management plane only.

  5. 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 roles county_director, regional_director, state_office (the ADR-054 subsidy approval matrix axis). Plan E additionally requires the per-service service:<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-service client_credentials principals 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

Bucket Setup

Create a single bucket for the deployment:

# Using AWS CLI
aws s3 mb s3://craig-prod --endpoint-url https://s3.example.com

# Using Garage CLI
garage bucket create craig-prod
garage bucket allow --read --write --owner craig-prod --key craig-prod-key

Object Key Format

Files are stored with the key pattern:

{service}/{entity_type}/{parent_id}/{object_uuid}/{filename}

Example: cases/contact_attachments/abc123/def456/report.pdf

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

RETENTION_ARCHIVE__ENABLED

false

THE consent act (D11): enables the scheduled archiver AND the security /archive/run + /archive/purge endpoints (/archive/run is a 202 background job since #1934 — the typed 403 stays synchronous at enqueue and the job re-checks this knob at attempt start, failed(refused_at_start) naming it). Archiving deletes hot rows after copying them; leave OFF until the storage requirements below are met. The no-overwrite guarantee is backend-independent since #1293 (digest-verified creates — a foreign occupant at an archive key fails the batch before any prune); backends honoring If-None-Match: * (AWS S3, MinIO, R2) additionally get the native conditional-put refusal, while Garage permanently ignores it (ADR-058 §Amendment #1293).

RETENTION_ARCHIVE__HOT_WINDOW_DAYS

90

Rows older than this are archive-eligible. craig-exchange refuses boot below 365 (#1466 B5 — the SSA screening quiescence horizon); set it explicitly for exchange. Operational knob — NOT the DFCS records-retention schedule (⁂ #1073); archives are held indefinitely regardless.

RETENTION_ARCHIVE__INTERVAL_SECONDS

3600

Scheduled-pass cadence; 0 = no worker (the manual endpoints still work when enabled).

RETENTION_ARCHIVE__BATCH_SIZE

1000

Rows per batch (1..=10000); one batch = one object
one crash-atomic prune transaction.

RETENTION_ARCHIVE__MAX_BATCH_BYTES

33554432

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_BYTES holds its whole month: nothing is dropped, the pass warns per row, counts it on retention_quarantined_total, and the job’s report carries the partition-held error for audit_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:

  1. Read craig-security’s log for the worker’s WARN (could not make audit_log’s and identity_issuance_log’s partitions) and its worker_last_success_timestamp_seconds{worker="partition-maintenance"} gauge; fix the cause (database reachable, the owner’s functions present, no lock held on audit_log for long).

  2. To restore the horizon by hand, as craig_security_app or 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_BYTES holds its whole day, as it holds an audit_log month: 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_invalidated event 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 == max with idle == 0 is pool saturation; size < max alongside 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 timed acquire() 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:

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:

  1. scan: SAST (GitLab template), secret detection, dependency scanning, and the cargo deny check advisory-DB, licence and source check.

  2. promote: release-build, the one job that pushes images (plan ci-dev-loop D3, #3045); see Release images. On tags release-notes renders the tag’s CHANGELOG.adoc section 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), and release creates the GitLab Release with that file as its description (release-cli v0.24.0 reads --description as a file when the value is a whitespace-free path inside the working directory) and release-build’s SBOM as an asset link. The link names `release-build by the id it hands over in its sbom.env dotenv report (/-/jobs/$SBOM_JOB_ID/artifacts/raw/…), not the ref: GitLab resolves jobs/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 in CHANGELOG.adoc fails release-notes, so release does not run (#2974).

  3. deploy: pages builds the Antora docs site on main. On an MR the docs job 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

ci-image, xtask, secrets-policy, pages

runs

runs

release-build

manual

runs

also on tags; see Release images

release-sbom

no

runs

also on tags; release-build waits for it

feature-matrix, cargo-deny, the GitLab scans

runs (the first two when their inputs changed)

runs

car, docs

no

docs runs (the link check)

the train ran them on the same tree

pentest

manual

runs, every schedule

brings up its own stack (xtask dev start)

perf-load, perf-stress

manual

runs, every schedule

each bakes its commit’s release images and measures them (xtask dev start --release --bake, #3157)

issuer-capacity

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

cluster-tests

manual

the CLUSTER_TESTS=true schedule

builds its own rig images (their build args differ)

policy-drift, coverage-floor

no

every schedule; policy-drift the POLICY_DRIFT=true one

coverage-floor is advisory (the line-coverage floor, #2672)

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 main pipeline (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
Edit this page · latest