Plan: AFCARS Source History — the Class-3 Columns Read As Of (#2131)
Archive record
Merge requests: !1814 (U0 plan page + the ADR-078 / ADR-079 amendments + the unit and follow-up issues, Relates #2131) + !1815 (U1, Closes #2186) + !1816 (U2, Closes #2187) + !1817 (U3, Closes #2188) + !1818 (U4, Closes #2189); the close-out (U5, Closes #2190 and #2131)
2026-10-05 — approved in plan mode 2026-10-05 (rulings R-H1–R-H9 as recommended) after a contextless round 1 (no-ship, 2
blockers fixed, 17 findings folded), the maintainer’s round 2 (no-ship, 5 findings folded), a three-pass fold check and a
closure check. What landed, column by column (P-D1 D3’s class 3):
six columns reclassified with no code (D1: cases.admin_unit, placement started_at, placement_type, ffh_type_* and the
setting, payments.status);
the (b)(18) share as of as_of (U1, D3: PAID_CHILD_IDS_SQL subtracts the adjustments approved after as_of from the stored
net, keeping the generated column’s rounding; no schema);
write-once end stamps (U2, D4: placements.ended_recorded_at and caregiver_bindings.ended_recorded_at, stamped
statement_timestamp() by the end and binding writers and now() by the born-ended insert, under four named CHECKs; the backfill
takes activated_at / created_at; an end or cancel recorded after as_of reads open; a required floor bump);
prior-value revisions (U3 and U4, D5: placement_fact_revisions, health_record_revisions and contact_revisions, insert-only
under refuse_revision_mutation(), written in the UPDATE’s own statement through Postgres 18’s RETURNING old and stamped
clock_timestamp() after the row lock; the export reads the earliest revision superseded after as_of, never COALESCE`d; the
histories start with their migrations; voluntary floor bumps);
the household fence (U4, D2: `case_household.added_at ⇐ as_of; the fixtures backdated and the seed’s added_at its case’s
opened_at);
persons current-state (D6, ⁂ on #1073: a correction, never a dated change).
Reads at one as_of now agree on every former class-3 column but persons (and D3’s unbacked fixture row, which production
never writes); a fresh generate still answers edits made after its predecessor’s as_of. One erratum: U2’s migration header
says Plaintext but not SCHEME-FROZEN. Follow-up: #2185 (structurally refuse an issued payment’s void and an edit to an approved
adjustment’s four D3 columns).
Status
Done (2026-10-05) — !1818
| Anchor | What binds here |
|---|---|
#2131; AFCARS 2020 Program (#949) |
every class-3 column gets an outcome: an as-of history the
export reads, or a current-state ruling (⁂ on #1073); a |
P-D1 (#1965) D3 ( |
the three as-of classes;
|
P-D2 (#2125) D8 |
a replay (a re-export of stored records) never differs;
a fresh generate mints a new |
ADR-078 D1; ADR-079 D3 and § Amendment #2052 D1 |
identity facts are corrected in place (the persons ruling); |
ADR-041, ADR-051; ADR-063 D3 |
DOB is ciphertext (no revision column is encrypted); the compatibility floor (R-H9) |
Context (census 2026-10-05, on main)
-
The class-3 text lives in the three route docs (
craig-placement/src/api/afcars_export.rs:64,craig-cases/src/api/afcars_export.rs:69,craig-financial/src/api/afcars_facts.rs:48) and the data-model pages (data-model-placement.adoc:1138,:1397;data-model-cases.adoc:1317;data-model-financial.adoc:385). -
Not edited in place.
cases.admin_unitis insert-only (craig-cases/src/store/cases.rs:35-44);case_householdhas one writer, an INSERT withadded_at DEFAULT now()(:330). NoUPDATE placementssite (craig-placement/src/store/placements.rs:374,:410,:464,:493) setsplacement_type,ffh_type_*or the setting;started_atrides only the activating request (api/placements.rs:407-425). Every void writer filtersstatus IN ('pending', 'approved')(craig-financial/src/store/ payments.rs:293-300,:338;subsidy/generator.rs:294), so an issued payment can only becomecleared. -
Write-once ends.
placements.ended_atcomes only from the ending transition (store/placements.rs:376;transitions.rs:115-140) and the born-ended insert (:214-250);caregiver_bindings.ended_ononly fromend_binding(store/caregivers.rs:442-458; a cancel isended_on = effective_from). Neither records when the end was written. -
Multi-edit sets. The sixteen arrangement facts are a full-state PUT (
placements.rs:410-426);update_health_recordrewritesvisit_date/health_assessmentbehind an IS-DISTINCT gate (store/health.rs:218-244);update_contactrewrites the three visit columns under theversionCAS (craig-cases/src/store/contacts.rs:178-188). -
The export reads. Placement: kind 7’s key SQL (
store/afcars_export.rs:95-100),ARRANGEMENTS_SQL(:123-136),CAREGIVER_SLOTS_SQL(store/afcars_export_facts.rs:37-45) andVISITS_SQL(:48). Cases:VISITS_SQL(store/afcars_ledgers.rs:287-292) and the unfencedchild_memberships(store/afcars_export.rs:26-42). Financial:PAID_CHILD_IDS_SQLtestsffp_amount > 0(store/afcars_facts.rs:29-38). -
net_amountis derivable. The approval transaction recomputesnet_amount = gross + Σ approved(api/adjustments_resolution.rs: 300-343); approval is terminal and stampsapproved_at(transitions.rs:39-49,store/adjustments.rs:94-99);ffp_amountis generated (migrations/20260703130000_financial_domain_constraints.sql:29-34) from inputs frozen before issue (payments.rs:406-416);idx_payment_adjustments_payment_approvedexists (migrations/20260726050000_hot_path_indexes.sql:6-7). -
No house revision table. The ledgers'
refuse_event_row_mutationadmits an UPDATE as a RETIRE, which never fits here. The fully append-only shape isrefuse_end_reason_rewrite_mutation(craig-placement/migrations/20260926120000_end_reason_narrowing.sql:66-76) plus #2174’s truncate trigger (craig-reporting/migrations/20261004130000_afcars_retained_policy_immutable.sql:21-30). Postgres 18 (devstack/postgres/Dockerfile:1;implementation-guide.adoc:132) hasUPDATE … RETURNING old.<col>.
Scope
In: D1–D6; the class-3 text of the three routes, their module docs and the three data-model pages; the ADR-078 and ADR-079 amendments; CHANGELOG entries; the seed and the test fixtures that a new CHECK (U2) or the fence (U4) touches.
Out: a persons history (R-H4); prior values for edits made before a migration (none exist); reporting (no wire shape changes);
a structural refusal of issued | cleared → voided and of edits to an approved adjustment’s payment_id, amount, status or
approved_at (its admin_unit and assignment stay writable, craig-financial/src/inbox/case_assignment.rs:391-476; U0 files one
follow-up issue).
Design
D1 — Reclassified, no code (R-H1)
cases.admin_unit (fixed at insert), placement started_at (fixed at activation, so the class-2 fence covers it), placement_type,
ffh_type_* and the setting (foster_family_home, foster_home_id, kinship_household_id, fixed at insert), and payments.status.
Status needs care: given issued_at ⇐ as_of, the row was issued at as_of and can now only be issued or cleared, and the
predicate counts both. Each service’s MR moves its columns out of the class-3 sentence, with the reason in one clause. After U4 the
cases route’s class 3 is persons alone (D6), and the placement and financial routes have none.
D2 — The case_household fence (R-H7)
child_memberships gains an as_of parameter (read_keys passes window.as_of, api/afcars_export_page.rs:81) and
AND h.added_at ⇐ $4. It becomes class 2: a membership added after as_of gives that key’s not_found row, so reads at one
as_of agree. No schema. The cases-export fixtures are wrong under the fence: they add memberships at now(), after every random_as_of()
(tests/api/afcars_export_seed.rs:111-115). Fx::member, and so child_case, writes added_at = now() - interval '2 hours'
(:336-353); dev_case_with_child (:80-107) backdates its membership the same way by SQL after the API add; the commit message
says why. The seed renders case_household.added_at as its case’s opened_at, not load time (which hides seeded memberships from a
generate for 5 min), and the cases hashes in tools/craig-seed/tests/sql_byte_identity.rs are re-blessed.
D3 — The (b)(18) share as of as_of (R-H8)
PAID_CHILD_IDS_SQL replaces p.ffp_amount > 0 with the share as it stood at as_of. It subtracts the approvals recorded after
as_of from the stored net and keeps the generated column’s rounding:
CASE WHEN p.ive_eligible THEN round((p.net_amount - COALESCE((SELECT sum(a.amount) FROM payment_adjustments a WHERE a.payment_id = p.id AND a.status = 'approved' AND a.approved_at > $3), 0)) * p.ffp_rate, 2) ELSE 0 END > 0
With no approval after as_of, this equals ffp_amount, so older periods do not move. It assumes two things: each approval moved
net_amount by its own amount in its own transaction, and an approved row’s payment_id, amount, status and approved_at
never change (its admin_unit and assignment do, which D3 never reads). It does not assume adjustments = Σ
approved, so a row whose adjustments has no rows behind it (the zero_net fixture) reads right unless it is also adjusted after
as_of, when the recompute drops the unbacked part. Production writes no such row (create_payment leaves adjustments at 0).
approved_at is the handler’s clock, as issued_at is (P-D1 accepted that stamp). The existing index serves the subquery. No schema.
D4 — Write-once record stamps (R-H5)
-
Columns.
placements.ended_recorded_atandcaregiver_bindings.ended_recorded_at, bothTIMESTAMPTZ, hold the DB instant of the statement that wrote the end. Neither reaches a response body (no wire change). -
CHECKs, named to sort after the names tests pin on rows that also break a pairing, since Postgres tests CHECKs in name order (
caregiver_bindings_interval,tests/api/caregivers.rs:831;placements_ended_has_ended_at,tests/api/placements.rs:914). Pairing,(<end> IS NULL) = (ended_recorded_at IS NULL):placements_ended_recorded_pairing,caregiver_bindings_recorded_pairing;placements_ended_recorded_after_activation(>= activated_at) andcaregiver_bindings_recorded_after_creation(>= created_at). -
Writers.
update_placementaddsended_recorded_at = COALESCE(ended_recorded_at, CASE WHEN $3 IS NOT NULL THEN statement_timestamp() END)andend_bindingstampsstatement_timestamp(): notnow()(asstore/removal_episodes.rs:722), since an end begun before a racing activation would stamp beforeactivated_atand fail the bound, while its UPDATE runs after the locked read.insert_historical_placementstampsnow(), its ownactivated_at(no race; no torn read inside the insert). A stamp at or beforeas_ofstill means a transaction begun by then (P-D1). -
Backfill (same migration, before the CHECKs). Every placement with
ended_at IS NOT NULL(ended, or retracted from ended,api/arrangement_acts/status_acts.rs:299-304) takesactivated_at, and every binding withended_on IS NOT NULL(an end or a cancel)created_at: the proven lower bound, since an end is never recorded before the activation or creation (a later request, or the born-ended insert itself;placements_activated_pairing,20260925170000_retracted_arrangements.sql:38). A legacy end therefore reads as known from activation, which is today’s answer, so no past period moves.ended_atis not a bound, because nothing refuses a future-dated end. The UPDATE touches only the new column, so the occupancy trigger’s WHEN guard andck_arrangement_in_episodestay silent. -
Fixtures. "Head schema" means a database built by the full
MIGRATOR(scratch()or the devstack). There a raw test write of an end stamps what the statement givesactivated_at(an UPDATE’sCOALESCE(activated_at, now()), asconstraints/occupancy_recompute_race.rs:139), else the row’sactivated_at/created_at, ornow()whencreated_atdefaults, asCASE WHEN <end> IS NULL THEN NULL ELSE … END, where<end>is the value the statement writes (its bind, literal or expression), never the column, asupdate_placementtests$3. Only a leg testing a late stamp differs. So replay legs keep their ends and evil legs their pinned names. A pool fromchain_db(v)(constraints/removal_episodes_migration.rs:285) withvat or below this migration’s version keeps its shape (a chain above it stamps as the head does):legacy_arrangementcallers (end_reason_narrowing_migration.rs:193), the raw INSERT atremoval_episodes_migration.rs:410, andkinship_households_migration.rs’s bindings (:145-160`, ended at:394, on a post-#2056 chain that also uses the head builders).ended_by()(removal_episodes_ddl.rs:319) splits:ended()stamps,legacy_ended()does not. The backfill leg writes its ends unstamped witharrangement()and explicit columns. -
Read.
CASE WHEN ended_recorded_at ⇐ $as_of THEN ended_at ENDinARRANGEMENTS_SQL(which gains anas_ofbind), and the same forb.ended_onin both ofCAREGIVER_SLOTS_SQL’s predicates. An end or cancel recorded after `as_ofreads open.
D5 — Prior-value revisions for the multi-edit sets (R-H2, R-H3)
-
Tables. Three tables, each narrow (the export columns only; the parent’s types and nullability, so
visit_date,health_assessmentandoccurred_atare NOT NULL and the rest nullable; no copied domain CHECKs), plaintext-only and insert-only:-
placement_fact_revisions:placement_idand the sixteen facts; -
health_record_revisions:health_record_id,visit_date,health_assessment; -
contact_revisions:contact_id, the supersededversion(UNIQUE (contact_id, version)),occurred_at,visited_child_id(REFERENCES persons(id) ON DELETE RESTRICT, as oncontacts),location.
-
-
Columns and keys. Each has
id UUID PRIMARY KEY DEFAULT uuidv7(),superseded_at TIMESTAMPTZ NOT NULL(no default), the parent FKON DELETE RESTRICTand an index on(<parent>_id, superseded_at, id). A row holds the values that stood untilsuperseded_at. -
The instant is read after the row lock. The writer inserts
superseded_at = clock_timestamp(), nevernow().now()is the transaction’s start; the placement and health handlers lock inside the transaction (craig-placement/src/api/health.rs:324-334,api/placements.rs:1606-1660) and a contact’s UPDATE takes its own lock, so two edits whose transactions began in the opposite order to their locks would sort backwards. An earlieras_ofwould then answer the second prior value. The INSERT consumes the UPDATE’s output, so its clock is read after the lock is held: a later edit waited for the earlier one’s commit and always sorts after it.superseded_at ⇐ as_ofstill means committed before page 1 (P-D1). -
Guard. One function per service,
refuse_revision_mutation(), raisesintegrity_constraint_violationnaming the table andTG_OP, attachedBEFORE UPDATE OR DELETE … FOR EACH ROWandBEFORE TRUNCATE … FOR EACH STATEMENT. The guard makes each table SCHEME-FROZEN, so no column may joinresolve::ALLOWLIST. Revision columns are not element-map sources (noFieldSpec). No REVOKE: the guard refuses every role; the house revokes only where the serving role never writes (end_reason_narrowing.sql:78-84). -
Writer: the same statement as the UPDATE. Each store writer (
update_arrangement_facts,update_health_record,update_contact) moves its UPDATE into a CTE. The CTE’sRETURNINGadds the prior export columns through Postgres 18’soldalias. A second CTE inserts the revision from that outputWHERE (old cols) IS DISTINCT FROM (new cols), and the outerSELECTreturns the row, which sqlx maps by name. A revision exists exactly when the UPDATE landed and changed an export column: a CAS or IS-DISTINCT miss, a notes-only health edit and a narrative-only contact edit write none; no trigger writes data (the house’s triggers are guards). First use ofRETURNING old: read the PG 18 docs first. -
As-of read, one shape for all three. Never
COALESCEa value: a prior NULL (an unanswered fact, a cleared visit) is an answer:LEFT JOIN LATERAL (SELECT r.id, r.<cols> FROM <t>_revisions r WHERE r.<parent>_id = x.id AND r.superseded_at > $as_of ORDER BY r.superseded_at, r.id LIMIT 1) r ON true -- each column: CASE WHEN r.id IS NULL THEN x.<col> ELSE r.<col> END
-
Where it applies.
-
Placement:
ARRANGEMENTS_SQL’s facts, kind 7’s key predicate, and `VISITS_SQL, which gains anas_ofbind. -
Cases:
VISITS_SQLresolves the as-of trio for each contact of the key’s case, then filters on the as-ofvisited_child_idandoccurred_at < to, so a re-pointed visit answers under its as-of child.
-
-
No backfill. A row with no revision has stood unchanged since the migration. An edit made before the migration kept no prior value, so each route’s text says its history starts with this release.
D6 — persons stays current-state (R-H4, ⁂ on #1073)
-
Corrections.
UPDATE_PERSON_SQLrewritessex, the encrypted DOB,birth_year,dob_estimated_abandonedandyear_of_birth_declared(craig-cases/src/store/persons.rs:212-221). ADR-078 D1 calls such a write "a correction of an identity, never a dated change", so no prior value is worth keeping; parents'birth_yearis the same. -
Cost and effect. Demographics that change are class-1 ledgers already (
person_demographic_facts); a history would copy DOB ciphertext into the crypto registry, the scheme rewrite and key rotation (an ADR-041/051 amendment). A replay never differs (P-D2 D8) and a fresh generate reads at a newas_of, so it carries a correction either way. Current-state means only that a correction landing mid-walk answers on the pages read after it:personsis the one table where reads at oneas_ofcan disagree (beside D3’s unbacked row, which production never writes).
Units
Each MR Relates to #2131, #1965 and #949 and closes its own unit issue; U5 closes #2131.
| MR | Scope | W |
|---|---|---|
U0 |
this page (Active nav); the unit issues under &99 ( |
1 |
U1 |
FINANCIAL: D1 ( |
2 |
U2 |
PLACEMENT STAMPS: D4’s migration (lock, backfill, CHECKs, floor bump LAST), the three writers, the two reads; D4’s head-schema
fixtures (not the |
3 |
U3 |
PLACEMENT REVISIONS: D5’s two tables, guard and floor bump; the two writers and the three reads; D1’s placement columns; the
route text, module docs (with the test module doc, |
5 |
U4 |
CASES: |
3 |
U5 |
CLOSE-OUT: the amendments Accepted; Status |
1 |
-
Migrations. Each file sorts after its service’s latest (
20260930140000placement,20260930150000cases). Its header takes the class (ADDITIVE) and "Plaintext … SCHEME-FROZEN" from placement’s20260930140000_child_facts.sql:30-50, the floor and rollback sentences from20260925170000_retracted_arrangements.sql:17-22(with R-H9’s reason). ThenSET LOCAL statement_timeoutandlock_timeout; U2 addsLOCK TABLE placements, caregiver_bindings IN ACCESS EXCLUSIVE MODE(explicit hold and lock order, as…_placement_setting_vocabulary.sql:33-36). Last,UPDATE schema_compat_floor SET min_required_version = <own timestamp>;. Erratum (2026-10-05): U2’s migration header says Plaintext but not SCHEME-FROZEN: its stamp columns sit on placements and caregiver_bindings, which carry no row guard (#2187). -
Order and weight. Weight 15. U0 first; then U1, U2 → U3 (placement’s migration order) and U4 in any order, since no unit reads another’s change. Each MR is green alone with its CHANGELOG entry (
Changed: the answers move;Added: the schema, with the deploy note); every new test carries// @axis:. -
Test placement. Devstack legs live in each service’s
tests/api/afcars_*.rsand migration legs intests/constraints/. The race legs call crate-private writers, so they are scratch-DB#[path]siblings undersrc/store/: craig-placement’splacements_tests.rs(U2’s end race, U3’s facts race) andhealth_tests.rs(U3’s health race), and craig-cases'contacts_tests.rs(U4’s). No test fn added to asrc/**/*tests.rsfile may contain_and: the fn-name-and lint walks those files (xtask/src/cmd/lints.rs:2445-2460). Replay legs followrows_recorded_retired_or_closed_after_as_of_read_as_at_as_of(craig-placement/tests/api/afcars_export.rs:461): aWindowwithas_of= now − 1 h,recorded= now − 2 h,late= now − 30 min (afcars_export_seed.rs:19-70); financial’sWindowgainslate= now − 30 min (U1); cases stamps withWindow::after(). An API edit made now is afteras_of. Legs seed random far-past windows, leave residue and never delete an edited row (the RESTRICT FK and guard refuse it).
Test matrix (by risk)
| Test | Axis | Unit | Asserts |
|---|---|---|---|
|
replay |
U1 |
an adjustment row approved at |
|
sad |
U1 |
its API recovery leg
( |
|
conc |
U1 |
full API recoveries mid-walk: every page equals the baseline |
|
replay |
U2 |
stamped |
|
replay |
U2 |
both stamped at |
|
happy |
U2 |
an API placement end, an API binding end and an API cancel each
stamp a DB instant between |
|
conc |
U2 |
transaction A begins; B activates the row and commits; A locks it and
calls |
|
evil |
U2 |
the four named CHECKs each refuse a raw write, by name |
|
happy |
U2 |
ended and retracted-from-ended rows take |
|
replay |
U3 |
a facts PUT through the API after |
|
replay |
U3 |
two PUTs: the first revision answers |
|
conc |
U3 |
|
|
conc |
U3 |
|
|
replay |
U3 |
|
|
happy |
U3 |
an identical facts PUT, health’s IS-DISTINCT miss and a notes-only health edit insert nothing |
|
evil |
U3 |
UPDATE, DELETE and TRUNCATE refused on both tables, owner role included |
|
conc |
U3 |
PUTs during a walk: every page answers the pre-edit facts |
|
replay |
U4 |
A and B are active child members of one case; after |
|
replay |
U4 |
|
|
happy |
U4 |
version bumps, no revision row, the export unchanged |
|
evil |
U4 |
UPDATE, DELETE, TRUNCATE and a duplicate |
|
conc |
U4 |
the same opposite-start race on a contact: the revisions sort by |
|
conc |
U4 |
contact PUTs during a walk: every page equals the baseline |
Verification
-
Per MR: fmt, clippy, the budgets,
validate-migration-constraints(U2–U4),api-docs --check(each route text change),coverage-matrix-mapping --check,check-docs,plan-lint; the constraint legs locally; then the battery (baregit push). -
Close-out:
cargo xtask plan-lint --done docs/modules/ROOT/pages/plans/archive/afcars-source-history.adoc --allow-open 949,1073,1965,2131, plus U5’s own unit issue and the follow-up issue U0 files.
Rollout and risks
-
Rollout. U1 has no migration. U2–U4 each bump the floor LAST and replace every replica of that service before traffic (R-H9); rollback is N-1 images and a database restore; the CHANGELOG ops note names each migration as the start of its history.
-
Risks. An
as_ofbefore a migration can still read an earlier edit’s value (the route text says so). Legacy ends read as known from activation (D4). An approved adjustment’s four D3 columns and the void writers' status sets rest on the writers (the follow-up issue). A request spanningas_ofcan read partly applied for at most its own duration (activation isnow(), a revisionclock_timestamp()); reads at oneas_ofstill agree, since the request ended before page 1 (P-D1).
Rulings (approved 2026-10-05 as recommended; D1–D6 are binding)
| # | Recommendation | Alternative |
|---|---|---|
R-H1 |
Treatments per D1–D6: six reclassified, one fence, one derivation, two stamps, three revision sets, persons current |
a revision table for every column D3 lists |
R-H2 |
Arrangement facts keep prior-value revisions |
a P-B1-style response ledger ( |
R-H3 |
A CTE in the store writer ( |
an |
R-H4 |
|
a persons revision table holding DOB ciphertext (registry, ALLOWLIST; ≈ +5–8) |
R-H5 |
Backfill stamps at the proven lower bound ( |
|
R-H6 |
Amend ADR-079 (facts, health, stamps) and ADR-078 (contacts; D1 reaffirmed for persons) |
a new cross-service ADR |
R-H7 |
Fence |
rule it current-state |
R-H8 |
Subtract the approvals after |
rebuild from gross plus approvals at or before |
R-H9 |
A floor bump on each schema MR: U2’s required (an N-1 end breaks the pairing CHECK); U3’s and U4’s voluntary under ADR-063
D3 and taken ( |
no bump on U3 / U4 (N-1 edits unrevised) |
Review log
| Round | Vendor | Resolved model | Verdict |
|---|---|---|---|
1 |
Anthropic — one fresh contextless reviewer (the page, the rules, the four questions; 56 citations checked) |
Claude Opus 5.5 |
no-ship — 2 blockers fixed (the household fence’s fixtures backdated; the stamp fixture sweep widened and the CHECKs named); 17 of 17 findings folded |
2 |
OpenAI — maintainer-run (2026-10-05) |
GPT Astra |
no-ship — 5 findings folded: revisions
stamped |