State Machines
CRAIG uses explicit state machines with validated transitions for all stateful entities.
Invalid transitions return HTTP 400 with a descriptive error message.
Each diagram below is derived directly from the transitions.rs source code in the corresponding service.
Case Management (craig-cases)
Investigation Status
Investigations track the lifecycle from intake through disposition.
The closed transition carries a disposition — the outcome determination, not a status. Since #648 its
vocabulary is the seven NCANDS Child File outcomes (codebook rev 2025-09-12, one token per RptDisp code):
substantiated (1), indicated (2), alternative_response_victim (3), alternative_response_nonvictim (4),
unsubstantiated (5), unsubstantiated_false_report (6), closed_no_finding (7). The same vocabulary is the
per-allegation disposition (Mal*Lev). closed_no_finding is a VALUE ("the assessment could not be completed"),
never a default: closing requires a recorded disposition (this request’s or the row’s), refused 400
investigation-disposition-required and backed by the CHECK investigations_closed_has_disposition (#1764).
The status machine is untouched by #895; two DERIVED values ride beside it on every read, and one audited act may move the deadline.
Response deadline (response_due_at, #1747) — derived ONCE at open, never typed: the referral’s
response_priority token (rolled up at conversion by {j}-response-priority) is consulted against
{j}-response-window, and craig_common::deadline::derive_deadline turns the row’s spec into an
instant on the jurisdiction clock, anchored on the report’s receipt. HOURS is a checked interval from
the receipt instant; WEEKDAYS / CALENDAR_DAYS walk from the receipt’s business date counting the
dates the flags admit (receipt_day_is_day_one, skip_weekends, skip_holidays — the bundle’s
holiday_calendar() must cover the window or the open is a named 500), ending at local
23:59:59.999999 of the target (end_of_day) or at the receipt’s wall time. Georgia (PAMMS 3.32):
IMMEDIATE and PRIORITY_24HR = 24 hours; STANDARD = five weekdays counting the receipt day as day
one, weekends skipped, holidays included, to 23:59:59.999999 Eastern; a NONE token opens nothing
(409 response-window-undefined). The window’s provenance (token, basis, ruleset, revision, evaluation
id) is stored beside the deadline.
Timeliness band (response_timeliness, on every row v_investigations serves) — a READ-TIME value
computed from first_contact_at against response_due_at and now(), never written back:
| Band | Meaning |
|---|---|
|
no first contact yet; the deadline is ahead |
|
no first contact yet; the deadline has passed |
|
first contact recorded at or before the deadline |
|
first contact recorded after the deadline |
Audited override (POST /v1/cases/investigations/{id}/response-deadline, #1748) — the ONE
sanctioned way response_due_at moves after open: authz admits the OPERATION
(attrs.operation = override_response_deadline, operation-scoped rows plus admin’s standing wildcard row — a caseworker is refused
at authz, an assigned one included), the jurisdiction’s {j}-response-deadline-override arm judges
the service-derived facts (actor role, status, first contact recorded, extension or not, whole hours
from the ORIGINAL deadline, reason present), the write keeps response_due_original and stamps who /
when / why / which evaluation under the row lock with every consulted fact re-derived, and
case.investigation_response_deadline_overridden is staged in the same claimed transaction. Georgia
and Texas ship the arm CLOSED (403 with the policy basis verbatim, ⁂ #1073) — opening it is a ruleset
promotion, never a code change.
Placement (craig-placement)
Placement Status
Placements track a child’s physical location in care. Since
#2018 each placement is a living
arrangement inside one removal episode (see Removal Episode).
Creating an active placement increments the foster home’s occupancy counter; ending it decrements; a
cancel never occupied a bed, so it leaves the counter unchanged. Since #2020 a retract of an active
placement frees its bed (decrements), a retract of an ended one leaves the counter unchanged, and a
historical record is born ended, so it never occupies.
The PUT moves only planned → active and active → ended; planned → ended is refused (400
invalid-state-transition). A planned placement that never happens is cancelled instead
(POST /v1/placement/placements/{id}/cancel, a note required): it stamps cancelled_at /
cancelled_by / cancel_note and emits placement.cancelled, never placement.ended. cancelled is
terminal. Both activations stamp activated_at write-once (the database transaction’s instant) and
refuse a start outside [removal_at, now()] of the episode (400 activation-start-out-of-range); the
PUT accepts started_at only on the activation. A status change on a retracted episode is the 409
episode-retracted. An arrangement that ends because the agency’s placement and care responsibility
ended takes the end reason left_care (#2019); since #2023 the end reasons are transfer, disruption,
runaway and left_care, and the reason a child left care lives only on the exit. The episode’s exit is
refused while any arrangement is still planned or active (see Removal Episode).
An activated placement entered in error is retracted
(POST /v1/placement/placements/{id}/retract, #2020, a note required): active → retracted or
ended → retracted. It stamps retracted_at / retracted_by / retract_note, keeps activated_at,
ended_at and end_reason as the record, and emits placement.retracted (never placement.ended). A
caregiver binding keys the kinship household, not the arrangement, so it never blocks a retract (P-B2 U5, #2058).
retracted is terminal, and a retracted row leaves the effective set (the overlap exclusion and the in-episode check).
A missed past arrangement is recorded (POST /v1/placement/placements/historical, #2020): born ended
with started_at, ended_at and end_reason set at birth, ended_at after started_at and not after
the transaction instant; its one lifecycle event is placement.recorded (the #634
placement.field_written audit of its status is staged beside it), and it never activates, never
occupies and never bills. Either re-record, the live create or the historical record, may name the retracted arrangement it
replaces (replaces_placement_id, 409 invalid-replacement unless that row is a retracted, not yet
replaced arrangement of the same episode).
Terminal facts are immutable (#1112). The create endpoint births a placement planned or active only; it refuses ended (and, since #2018, cancelled: cancel is the act on a planned row; since #2020, retracted: retract is the act on an activated row) outright, since a create-born ended row would freeze NULL terminal facts forever and never emit placement.ended, and this closes the previously-unvalidated status vocabulary. Since #2020 a past arrangement is born ended only by the historical record, which sets its facts (ended_at, end_reason) at birth, so no NULL-terminal-facts row can arise (placements_ended_has_ended_at). ended_at and end_reason are writable only in the request that transitions the placement to ended, and that transition must carry ended_at: an end recorded without its instant could never be repaired under immutability. end_reason stays optional there, since whether a reason is mandatory is jurisdiction policy, not structure. A request that tries to decouple either fact from the ending transition is refused with the typed terminal-facts-end-transition problem, and because ended admits no further PUT transition, not even to itself, and its one exit, the retract (#2020), keeps ended_at and end_reason in place, the facts recorded at the end are permanent. The one sanctioned exception is #2023’s narrowing (ADR-079 D4, pre-1.0): its migration rewrote each exit-token end_reason to left_care on an arrangement that was its episode’s latest effective arrangement under a live exit — the exit already carries the reason — and recorded each rewrite as a placement_end_reason_rewrites row. It published no event, so a placement.ended a consumer already processed keeps the earlier token. Consumers that snapshot the terminal facts, such as the #1070 SG activation’s witness (the end date must equal the guardianship exit date, #2022) and the financial placement.ended void handler, can no longer be desynchronized through the API. Since #2024 dropped permanency_goal, the last non-terminal record-keeping column (#2018 dropped the CTW and reasonable-efforts ones), an ended row has no field a PUT may still write: a fact-free PUT (one stating none of status, started_at, ended_at and end_reason) is still admitted and changes nothing but updated_at. Terminal facts stay immutable in place: since #2020 an activated arrangement is corrected by retract + re-record, never by an edit. The retract keeps the row as the record and emits placement.retracted (financial voids its undisbursed payments); the re-record, the live create or the historical record naming replaces_placement_id, emits placement.activated or placement.recorded with that field (financial re-anchors the retracted arrangement’s subsidy agreements to it). Since #1583 a CHECK makes a stripped end instant unrepresentable at write time (since #2020 placements_ended_has_ended_at, which replaced #1583’s placements_ended_pairing) (the placement_ended_missing_ended_at blocking invariant stays in the battery gate as belt), but a raw rewrite of the fact values falls outside any constraint’s reach, since the columns carry no history to compare against (the #2023 migration is the one audited exception). The store remains the single legitimate writer. Since #2018 placements_ended_after_started is strict (ended_at > started_at): the PUT refuses a zero-length arrangement with a generic 400 bad request before it reaches the CHECK.
Removal Episode
A removal episode (#2018,
ADR-079 D2 + D4) is one removal of a child under a case;
its current removal_at is its live removal response’s and its exit_at its live exit response’s (NULL
while the child is in care). The open records the episode and its root removal response together. A
removal correction supersedes the live removal response and moves removal_at, leaving the episode in
its state; a removal correction onto or past a live exit is the 400 exit-before-removal.
Recording the exit (#2019) records the
root exit response and sets exit_at, moving the episode to exited. It is refused with the 409
episode-already-exited when the episode already has a live exit, episode-has-open-arrangement
while a planned or active arrangement references it (end or cancel it first; an arrangement ending
because the agency’s responsibility ended takes the end reason left_care), and
arrangement-outside-episode when an ended arrangement runs past the exit; an exit at or before the
removal is the 400 exit-before-removal. An exit correction supersedes the live exit response and
moves exit_at (400 response-after-recording past the chain’s first recording; 409 episode-overlap
into the child’s later episode). An exit retraction retires the live exit response and clears
exit_at, re-opening the episode; it is refused with the 409 later-episode-exists when the child has a
later live episode the re-opened window would overlap. The retraction ends that exit chain: an exit recorded after it is a new
response with its own first-recording stamp (R-B18). Re-entry is a new episode opened after the exit;
an exit and a re-entry on one instant are adjacent, not overlapping. A historical episode
(POST /v1/placement/episodes/historical) is born exited: the episode, its root removal response
and its root exit response are recorded together.
A retraction retires the episode as retracted (entered in error) together with its live removal
response, on an exited episode its live exit response, and (#2082) every live row of both trafficking
ledgers. It is refused with the 409
episode-has-arrangements while a planned, active or ended arrangement references it, so only an
episode with no arrangement but cancelled or (#2020) retracted ones can be retracted. A retracted episode takes no further
act (409 episode-retracted). Every act emits placement.episode_facts_changed (the historical episode
emits two). Full model: Data Model: Placement.
Foster Home License Status
License status controls whether a home can receive new placements: since
#1635 both activation
sites — a placement born active and the planned → active transition — refuse with the
typed 409 foster-home-license-not-active unless the license is active, decided under the
home row lock before the placement write (occupancy is trigger-derived, so a refusal changes
nothing). Planning is deliberately ungated for every license state (mid-licensing is the common
case; the activation gate is what protects the bed); matching presents only the STORED statuses the
jurisdiction’s {j}-placement-eligibility matching-scope table names (Georgia: active only — #1721).
Since #1641 expired is ALSO
a DERIVED state: every FosterHome read answers effective_license_status = expired when the
stored status is active and license_expires is strictly before the jurisdiction business
date (never written back — the active → expired edge below is both a stored transition and
this derivation). Activation and matching consult the jurisdiction’s
{j}-placement-eligibility ruleset (license_gate) on the DERIVED status: a derived expiry
refuses activation 409 foster-home-license-expired (naming the date, the days and the ruleset
revision) and excludes the home from matching; stored pending / suspended / revoked and
a stored terminal expired keep the #1635 problem type. The consult runs before the
transaction and its facts are re-derived under the home row lock (a change ⇒ 409
concurrent-modification, never a stale admit); every training write serializes behind that
same lock (a DB trigger). The expiry sweep raises foster_home.license_expiring /
license_expired once per (home, kind, expires_on); the list filter and sort on
license_status read the EFFECTIVE column.
Foster Home Training Records
foster_home_training has no state machine: a record is created, updated in place, or
soft-deleted (active = false, deleted_at); no training write stages an event, though since
#1641 every training write serializes behind the parent home’s row lock (a DB trigger — the
activation gate re-derives its facts under that lock). Since #1642 its expires_at is READ:
per (home, training_type) currency is DERIVED on the jurisdiction clock, never stored — over
the type’s active rows with completed_at ⇐ today, dated rows decide by max(expires_at)
(current through the expiry date, expired strictly after), only undated rows ⇒ undated,
none ⇒ absent (a household proxy: the table carries no caregiver identity, #1722; a future
completed_at is refused at the API, typed 400). The {j}-placement-eligibility consult’s
training_gate (v1.1) reads all six types — Georgia refuses matching AND activation for an
expired or undated cpr_first_aid (409 foster-home-training-expired /
foster-home-training-unverifiable, grace 0); every other type and an absent type admit (the
"missing required training" arm is #1723) — and the expiry sweep’s training leg raises
foster_home.training_expiring / training_expired once per
(home, kind, expires_on, training_type), independent of the license window. The home detail
page marks each row from the backend’s evidence (expired / undated / current), never from
a web-side clock. The home’s license_expires is no longer inert (#1641,
ruled on #1639): every FosterHome
read DERIVES effective_license_status (expired when stored active and license_expires <
today on the jurisdiction clock — never written back), the {j}-placement-eligibility consult
gates activation and matching on it, and the expiry sweep raises foster_home.license_expiring /
license_expired once per (home, kind, expires_on).
Data Exchange (craig-exchange)
Data Sharing Agreement Status
Agreements govern the legal basis for exchanging data with external partners.
Exchange Transaction Status
Transactions represent individual data exchange operations with partners. A failed
transaction can be retried: retry_failed_transaction is a guarded
UPDATE … SET status = 'pending' WHERE status = 'failed' that mints a fresh
correlation_id and restages a send job. There is NO intermediate retry state: a DB
CHECK pins the vocabulary to pending | success | failed
(#1638 — the never-written
TransactionStatus::Retry variant was retired with it) and the terminal guard in
update_transaction_status keeps success / failed from being overwritten. Corrected by
the #1609 reader pass — the earlier diagram showed a retry state the code never had.
Exchange Send Job Status
Every transaction send rides an exchange_send_jobs row (DB CHECK vocabulary
pending | in_flight | sent | failed). The send worker claims pending rows under
FOR UPDATE SKIP LOCKED with a 90 s lease and a fencing claim_generation; every
terminal stamp and retry re-admission carries status = 'in_flight' AND claim_generation =
<mine>, so a crashed claimant’s stale stamp applies nothing. Lease reclaim is NOT a
transition: an expired lease is re-claimed within in_flight with a new generation and a
counted attempt. Terminal rows age out of the transport window; pending / in_flight
rows are never age-deleted (an aged pending row is the only evidence of an undelivered
send).
ICPC Request Status
ICPC (Interstate Compact on the Placement of Children) requests follow a multi-step workflow
driven ONLY by PUT /v1/exchange/icpc/{id}: the handler matrix plus a status-pinned CAS
UPDATE drive every edge, and a DB CHECK pins the nine-token vocabulary (#1638).
Withdrawal is legal from draft or submitted only; once received, it is refused (the
earlier "not after a home study is in progress" wording was wrong — #1609). The received
edge stamps deadline_at (CRAIG_EXCHANGE__ICPC_DEADLINE_DAYS, default 60 calendar days —
42 U.S.C. § 671(a)(26)(A)(i), #1734); completed and withdrawn stamp completed_at.
Overdue is not a status: the list’s overdue=true filter matches a request whose
deadline_at has passed while its status is none of approved, denied, conditional,
completed or withdrawn, so each of the three home-study decisions takes a request off the
overdue list (#2287; the definition). Home
studies and attachments are child records that never advance the request and carry no
parent-status precondition.
SSA Screening Run / Member / Job Status
The SSA screening graph (ADR-065) is three
CHECK-constrained machines. A run is pending | completed with an orthogonal one-way
invalidated_at (cohort_changed | operator_cancelled | freshness_expired); at most one
pending non-invalidated run exists per case (partial unique — completion or invalidation
releases the slot). A member moves from pending to exactly one terminal token —
screened | no_gateway_record | identifier_stale | failed | cancelled — and never again. A
job is the send-job machine plus the H16 paused class (pending | in_flight | paused |
sent | failed): in_flight → paused when a dispatch precondition lapses (gate off,
partner unavailable, DSA lapse, egress config, contract pending), paused → pending only
through the explicit resume endpoint; every job stamp and the member outcome stamp are
generation-fenced. Every member-terminal writer completes the run once no member is
pending. A case.screening_cohort_changed envelope raises the per-case watermark
(GREATEST) and invalidates only runs with a strictly lower cohort_revision, sweeping
their graph (paused/unclaimed jobs failed run-invalidated, pending members cancelled,
in-flight jobs spared) in the same transaction as the invalidation stamp.
Inbound Event Envelope (event_inbox)
Every service’s inbound consumer runs the craig-mq single-transaction attempt machine
(ADR-062): a claimed envelope’s handler
effects and its processed_at stamp commit together; a redelivery of a processed envelope
dedups without re-running the handler; a same-identity different-payload delivery never
runs the handler and is ledgered in event_inbox_collisions; after INBOX_MAX_RETRIES
counted attempts the row is stamped failed_at and re-surfaced byte-identical to the DLX.
Rows age out after the inbox retention window. craig-exchange has ONE such consumer
(queue craig-exchange.events), subscribed to case.created and placement.created (no
effect — log only), case.assignment_changed (the ICPC denorm under the strict-greater
revision guard) and case.screening_cohort_changed (SSA invalidation, above). There is
no partner-inbound message machine — the #1609 reader pass looked for one. A partner that
calls CRAIG (#3193) arrives on craig-exchange’s return listener, not on a queue, and its
call has no stored states: a run writes its one exchange_transactions row terminal
(How the host runs a return).
Reporting (craig-reporting)
AFCARS Submission Status
AFCARS (Adoption and Foster Care Analysis and Reporting System) submissions follow a review and approval workflow before transmission to the federal Administration for Children and Families (ACF). A generate finalizes inside its own transaction (#2162), so draft is never visible after one: validated when the file has records and no failed standard, else the terminal validated_with_errors (always, until P-D5 evaluates the two A8 steps). An approved submission becomes ready_for_transmission only through the act (PUT /v1/reporting/afcars/{id}/ready-for-transmission, #2179), which re-verifies its current export against the verified surface; the state has no outgoing edge until the delivery program (#1967). AFCARS has no approved → transmitted edge: the marking-only transmit route was retired in P-D4 U5 (#2180), so only delivery (#1967) will reach transmitted; the seed’s 2024B row is pre-#1967 history. NCANDS keeps approved → transmitted and has no ready edge.
NCANDS Submission Status
NCANDS (National Child Abuse and Neglect Data System) submissions follow the same review workflow as AFCARS. The generate finalizes a draft to validated only when the file has records and no validation errors; otherwise it writes the terminal validated_with_errors, which no transition leaves (#782). approved is the last state: NCANDS has no approved → transmitted edge since its marking-only transmit route was retired (#2130), and nothing delivers the Child File to ACF yet, so no submission is marked transmitted.
Financial (craig-financial)
Payment Status
Foster care maintenance and assistance payments track the forward chain pending → approved → issued → cleared. Each step has been a supervisor-gated REST transition since #978 (PUT …/approve, /issue, /clear), implemented as one atomic UPDATE … WHERE status = <expected> that stages its lifecycle event (financial.payment_approved / payment_issued / payment_cleared) in the same transaction. voided is permitted from every state by the transition predicate, but the production writers only ever void undisbursed (pending/approved) rows: the placement.ended consumer’s placement-scoped void (#776; since #3189 only of the rows no day of which was in care, or of every undisbursed row when the end carries no end date) and, since #2020, the placement.retracted consumer’s void of every undisbursed row (payments_voided cause placement_retracted), and, since #1068, the subsidy generator’s reconcile pass, which voids an agreement-month whose derivation went stale (backdated status/terms) and regenerates it under the voided-exclusive unique key (ADR-053). Disbursed rows are frozen instead, and surface through the subsidy_disbursed_derivation_mismatch invariant. A deliberate manual-void path is a tracked follow-up (#1028).
One edge runs backwards, and only the system takes it (#3189): when a placement ends, an approved per-diem that runs past the last paid day is shortened to it and returned to pending with its approval stamps cleared, for a person to approve what is now owed (financial.payment_period_shortened, returned_to_pending). The transition predicate behind the approve, issue and clear routes still refuses approved → pending; Data Model: Financial & Claims has the settling rule.
Adjustment Status
Payment adjustments (recoupment, underpayment correction, allocation change) require the same supervisor approval as the originating payment.
Claiming Record Status
Title IV-E claiming records are aggregated into quarterly federal financial participation (FFP) claims (CB-496 / CB-250) for submission to ACF.
Subsidy Agreement Status
Kinship-subsidy agreements (ADR-052, #1067) are governed by the Georgia DFCS Policy Manual’s chapter 22.8, covering the ERR and SG/NRSG programs, and chapter 22.9, the review workflow (ADR-054, #1081). SG (Subsidized Guardianship) pays a relative caregiver after a permanent-guardianship transfer; NRSG is its non-relative counterpart. The statuses below label business-effective intervals (subsidy_agreement_status_intervals), not a mutable row state: subsidy_agreements.current_status is a projection of the interval head, maintained single-writer by craig_financial::subsidy::store under a parent FOR UPDATE and verified by blocking invariants. pending exists because SG/NRSG agreements are signed before the guardianship transfer. Since #1070 (ADR-056) the witnessed activation (POST …/subsidy-agreements/{id}/activate) is the only native pending → active mint: it runs at the derived transfer date, the date of the child’s guardianship exit from the agreement’s anchoring placement (the specific placement record whose ACTIVE state justifies the agreement; since #2022 it must be the removal episode’s latest arrangement and must have ended on the exit’s date), confirmed by a service-to-service read from craig-placement rather than operator-entered, and under a county-floor proof. The generic transition endpoint refuses that same transition for native SG/NRSG agreements, naming this path instead. Imported agreements never enter native activation, and since #1071/ADR-057 an open-pending import is unrepresentable, so the refusal is belt-only. suspended is distinct from termination: a missed review causes suspension, and three suspended months cause termination, automated by the #1081 knob-consented review-enforcement sweep. terminated → active is reinstatement under chapter 22.8, on the same identity, with cause-specific approval enforced by #1081; a post-closure re-application is instead a new agreement row with a predecessor_agreement_id link. withdrawn and declined are pending-terminal paths.
Security & Compliance (craig-security)
Security Review Status
Biennial security reviews (45 CFR § 95.621(f)) are scheduled and tracked on the security_reviews table with the three-state workflow below.
NIST Control Implementation Status
NIST SP 800-53 controls tracked on nist_controls follow a three-state implementation lifecycle. Each control records last_assessed_at, assessed_by, and free-text implementation notes.
Security Alert Acknowledgement
Detection rules create alerts on security_alerts. An alert begins unacknowledged; an admin (or the system on webhook response) acknowledges with a note.
Invariant (#1156, DB-enforced since #1172): at most one unacknowledged alert exists per rule. The partial unique index uq_security_alerts_standing_rule is the arbiter, so overlapping scans, from the scheduler and on-demand alike, insert exactly one. The standing alert is the operator’s signal for a sustained breach; acknowledging it re-arms the rule, and a still-breached condition fires a fresh alert on the next scan.
Public Intake (craig-intake)
Public Report Status
Public abuse/neglect reports submitted via /report move through screening to either a formal referral (converted) or a screen-out decision.
Signer Key Status (Partner JWS)
Partners registering signer keys for JWS-signed intake submissions go through an admin approval step. Keys can be revoked at any time after approval; revoked keys are permanent (submissions fail JWS verification).
Client Certificate Status (Partner Return)
A partner that calls CRAIG is known by a client certificate an administrator registered against it (ADR-091). Registration and approval are separate acts. Only an approved certificate admits a caller, and a revocation is one-way: the same certificate is registered afresh to be used again.
-
Each move is one conditional update, so of several made at once exactly one takes effect and the others are answered 404 (
concurrent_approvals_and_revocations_each_take_effect_once). -
A fingerprint is live (pending or approved) at most once, against one partner (
concurrent_registrations_of_one_certificate_register_it_once). -
Each move stages
security.partner.client_certificate_registered,…_approvedor…_revokedin its transaction.