Plan: Placement Expiry Machines — License + Training (#1641, #1642)
- Archive record
- Status
- Context
- Scope
- Design
- A. Derivations (store)
- B. The ruleset —
rulesets/{georgia,texas}/{j}-placement-eligibility.json - C. The consult —
services/craig-placement/src/eligibility.rs - D. Activation
- E. Matching — evaluate before paging
- F. The notice sweep —
services/craig-placement/src/expiry_sweep.rs(lib target) - G. Settings, web, seed, corpus
- Steps
- Verification
- Documentation Updates
- Review log
- Errata
Status
Done (2026-09-08) — !1585
- Anchors
-
#1641 (license machine + the ruleset, weight 5), #1642 (training machine, weight 5, depends on #1641), the ruling #1639 (closed 2026-09-03; ADR-072 "Applications"), #1635 (the activation license gate this extends), ADR-053 (BusinessClock), ADR-062 (replay contract), ADR-070 (citations), ADR-071 (corpus), epic &90, follow-ups #1721–#1725, #1701 (
plan-lint --doneis promised by the rule and not yet implemented — completion follows the checklist by hand), ⁂ readings on #1073.
Context
The 2026-09-02 ruling on #1639 (option (a)): CRAIG owns foster-home license AND training expiry
monitoring, and expiry GATES matching and activation. The derivations (effective_license_status from
foster_homes.license_expires; training currency from foster_home_training.expires_at) and the
expiring/expired producers are tier 3; WHICH expiry blocks matching vs activation, grace windows and
per-type exemptions are tier 1 — decision arms in a new {j}-placement-eligibility ruleset, cited in
citations.toml.
Today nothing reads either date against a clock. The #1635 gate
(services/craig-placement/src/api/placements.rs:862-883) compares the STORED license_status;
search_matching_homes (store/foster_homes.rs:434-462) filters stored active + capacity in SQL;
craig-placement has no rules client, no settings extension, no sweep and no foster_home.* producer;
the corpus row core.placement.training-expiry-inert is blocked with both oracles none; the docs
annotate the machine as unbuilt (implementation-guide.adoc:1629/1651, state-machines.adoc:112-121).
Rulings recorded at the gate (2026-09-07, maintainer).
-
GA
training_gate(⁂ #1073): an EXPIREDcpr_first_aidrefuses activation and excludes from matching (PAMMS 14.9 "maintain current certification in CPR and First Aid throughout the approval period"); an UNDATEDcpr_first_aidrecord is UNVERIFIABLE and refuses the same way (14.9 "check the expiration date of the current certifications"; 26 TAC §749.831(e) "certificates for pediatric first aid and pediatric CPR must have an expiration date"); every other type’s lapse or missing date admits (14.9 frames CPD as annual oversight); a type never recorded admits (completeness model is a follow-up). Grace 0. -
GA
license_gate: DERIVEDexpired(storedactive,license_expires < today) refuses both, grace 0 (14.13 SAFE Update lapse; 14.15 "no new placements in a pending or closed home"); the STORED terminalexpiredandpending | suspended | revokedkeep today’sfoster-home-license-not-activeat activation (the #1635 pins are untouched). -
The Texas twin ships in the same units, cited to the HHSC Minimum Standards for Child-Placing Agencies (August 2026): §749.805, §749.831(e), §749.925(d)-(e), kinship §749.4421–§749.4425; Texas verifications are non-expiring, so the
expiredarms apply only where a CPA records an end date. -
Matching candidate scope: the SQL generator keeps stored
active+ capacity — pre-existing tier-1 residue outside this ruling, kept for result precision;license_admits_matchingis therefore reachable only for stored-active candidates (stated in the ruleset, the citations and the ADR-072 amendment; migrating the scope into amatching-scopetable is a follow-up issue). -
Household proxy:
foster_home_trainingcarries no caregiver identity while 14.9 requires EACH caregiver’s certification valid; currency is derived per (home, type) from the latest DATED, COMPLETED row and documented as a household proxy; per-caregiver identity is a follow-up on the provider model.
Scope
In scope
-
One SQL derivation of the effective license status bound to the jurisdiction’s business date, consumed by every foster-home read, the list filter/sort, matching and both activation sites; a shared per-type training evidence representation (U2).
-
{j}-placement-eligibilityv1.0 (license_gate) and v1.1 (training_gate) for Georgia and Texas, every row cited; a closed refusal-token vocabulary with cross-field validation; typed 409s. -
The activation consult with the ADR-062 precheck first, the verdict bound to facts re-derived under the home row lock, and DB-enforced serialization of training writers behind that lock.
-
Matching evaluated BEFORE paging (memoized per distinct facts tuple, bounded fan-out), a typed response with
total, and both craig-web matching paths routed through it. -
The notice sweep (scheduled worker + admin run endpoint), a per-key ledger, four events staged exactly once per key inside the notice transaction, audit attribution, failure-aware health.
-
Settings, craig-web surfaces, seed anchoring, the corpus re-class, docs, the ADR-072 amendment.
Out of scope (each with its issue)
-
Migrating the matching candidate scope into the ruleset (#1721); per-caregiver training identity (#1722); a "missing required training" arm (#1723); a placement-side evaluation pointer (#1724).
-
plan-lint --done(#1701). Clearinglicense_expiresthroughupdate_foster_home(#1725).
Design
A. Derivations (store)
-
effective_license_status_sql(p)buildsCASE WHEN license_status = 'active' AND license_expires < {p} THEN 'expired' ELSE license_status END AS effective_license_status(strict<: the expiry date itself is still licensed).FosterHomegainseffective_license_status: LicenseStatus; every FosterHome query bindstoday(get,get_for_update,list_paged,count,create/updateviaRETURNING *, <expr>,search_matching_homes); thelicense_statusfilter AND sort use the effective column (pre-1.0Changed).days_past_license_expiry(home, today)is 0 unless derived-expired. -
U2
training_evidence(exec, home_ids, today): per type of the six-tokencraig_reference::TrainingTypevocabulary,TypeEvidence { state: Current | Expired | Undated | Absent, effective_expires_on, days_past_expiry, days_until_expiry, evidence_row }from ACTIVE rows withcompleted_at ⇐ today(future completions are not evidence): dated rows decide bymax(expires_at); only undated rows ⇒Undated; no rows ⇒Absent. ONE representation feeds the gate input, the 409 detail, the sweep andFosterHomeDetail.training_evidence. The API refuses a futurecompleted_atat record/update (typed 400, jurisdiction clock). -
Migration
20260908120000_foster_home_expiry.sql(additive;SET LOCAL statement_timeout = '60s'): a partial index onfoster_homes (license_expires) WHERE license_status = 'active'; an index onfoster_home_training (foster_home_id, training_type, expires_at) WHERE active; the notices ledger (§F); the triggertrg_foster_home_training_lock_home(BEFORE INSERT/UPDATE/DELETE →PERFORM 1 FROM foster_homes WHERE id = COALESCE(NEW.foster_home_id, OLD.foster_home_id) FOR NO KEY UPDATE, the #1117 lock-first shape) so every training writer, old binaries included, serializes behind the home row. Constraint names pinned intests/constraints/foster_home_expiry_constraints.rs.
B. The ruleset — rulesets/{georgia,texas}/{j}-placement-eligibility.json
Schema-less JDM (the georgia-subsidy-eligibility.json shape); every key of the version is always
present (zen: a missing key never matches):
{ "license_status_effective": "active|pending|suspended|revoked|expired",
"days_past_license_expiry": 0,
"placement_type": "foster_care", // null at matching
"training": { "cpr_first_aid": { "state": "current|expired|undated|absent", "days_past_expiry": 0 },
"…all six types…": {} } } // v1.1
-
license_gate(first-hit; inputsi_status,i_days; outputslicense_admits_matching,license_admits_activation,license_refusal_reason; every row carries every input and output id; admit rows write the literal"null"). Georgia: [0]"expired"/> 0→ false/false/"license_expired"(14.13, 14.15) · [1]"expired"/""→ false/false/"license_not_active"(the stored terminal state) · [2]"active"→ true/true/null (14.15 Full Approval) · [3]"pending"· [4]"suspended"· [5]"revoked"→ false/false/"license_not_active"(14.15 / 14.23;derivation: activation-only, ruling 4) · [6] catch-all → false/false/"license_not_active"([plumbing]exception, the fail-closed default). -
training_gate(v1.1; field-less input cells overtraining.<type>.state,i_ptypefieldplacement_type). Georgia: [0]training.cpr_first_aid.state == 'expired'→ false/false/"training_expired"(14.9) · [1]training.cpr_first_aid.state == 'undated'→ false/false/"training_unverifiable"(14.9; TX §749.831(e)) · [2] catch-all → true/true/null (derivation: 14.9 oversight;absentadmits). Default-ADMIT is deliberate and stated in the#description. -
Refusal tokens are CLOSED:
license_not_active | license_expired | training_expired | training_unverifiable. Cross-field validation, each a named deterministic 500:admits == false⇒ a non-null reason;admits == true⇒ a null reason;license_expired⇒ factsdays_past_license_expiry > 0;training_expired/training_unverifiable⇒ some type in the facts isexpired/undated; an unknown token or a missing required key ⇒ 500. Required outputs: v1.0 the threelicense_*keys; v1.1 adds the threetraining_*keys. -
Citations: the
#descriptionrow and one row per rule (value=_descriptionverbatim; pamms rows carrysource_ref,section,manual_transmittal,effective_date,verified_date,verified_by, quoted evidence,derivationwhere transformed,source_sha256pinned bycargo xtask policy sync-cache --pin); Texas rowsmanualauthority with the HHSC PDF assource_ref; the plumbing row excepted. Tests:services/craig-rules/tests/{georgia,texas}_ruleset_evaluation.rspin every row and the all-defaults fall-through;rules check,ruleset_discovery, the tether tests andcommitted_corpus_audits_finding_freegate the manifests. -
Rollout: promote v1.0 (both jurisdictions) before the U1 image and v1.1 before the U2 image. Rollback ORDER: roll the placement image back FIRST, then re-promote v1.0 — never the ruleset first (the U2 parser requires the training keys). The devstack reseed converges the branch’s ruleset files.
C. The consult — services/craig-placement/src/eligibility.rs
RulesClient from settings.placement.rules_engine_url (with_metrics_caller("craig-placement")) as
Extension<RulesClient>. EligibilityFacts (U1: license_status_effective, days_past_license_expiry,
placement_type; U2 adds training) is Eq + Hash + Serialize and IS the input document.
consult(rules, relay, jurisdiction, context, &facts) posts EvaluateRequest { rule_set:
"{j}-placement-eligibility", context_type, context_id } — activation ("placement-eligibility",
Some(home_id)), matching ("placement-matching", None) — under RULES_CONSULT_BUDGET = 4 s;
GateVerdict parsing applies §B’s validation. map_consult_error: timeout / unreachable / 429 / 5xx →
503; Forbidden → 403 RULES_CONSULT_DENIED; RulesetMissing → 500 naming the ruleset as a deployment
defect; other 4xx / malformed → 500. The relay is the caller’s own headers (authorization
X-Craig-Actor); a bare service never consults. Typed 409s in craig_common::error::problem_types:
FOSTER_HOME_LICENSE_EXPIRED ("license expired on {date} ({n} days; {ruleset} r{rev})"),
LicenseNotActive → the existing FOSTER_HOME_LICENSE_NOT_ACTIVE, U2 FOSTER_HOME_TRAINING_EXPIRED
("the home’s most recent {type} certificate expired on {date}") and FOSTER_HOME_TRAINING_UNVERIFIABLE
("… carries no expiration date"). Order: license, training, then the untyped capacity 400.
D. Activation
-
Create born-
active: validate → authz →ClaimSpec→request_claims::precheck— aReplayreturns the stored placement BEFORE any consult (ADR-062: eligibility is a volatile business prerequisite, not current authorization) → read the home →derive_facts→consult→ refuse here (nothing persisted, the claim never taken) → the claim tx:claim_first→get_foster_home_for_update→ re-derive the facts UNDER the lock and require equality with the consulted facts, else 409CONCURRENT_MODIFICATION→ capacity → write. The §A trigger makes every training writer wait on that lock, so the equality is DB-enforced across mixed versions. -
planned → active(no claim; a repeatedactiveis an invalid transition): the same pre-tx consult, then the in-tx equality inguard_home_for_transition. -
check_home_admits_activation(&home, &facts_locked, &consulted, &verdict)replaces the #1635 stored-status branch, which is now theLicenseNotActivearm.
E. Matching — evaluate before paging
-
SELECT id, <facts columns>for ALL candidates in order (scope unchanged;MATCHING_CANDIDATE_CAP = 5000,truncatedbeyond) → U2training_evidencebatch → facts per candidate → grouped by tuple → memoized consults,buffer_unordered(8), the WHOLE fan-out underMATCHING_CONSULT_BUDGET = 8 sandMAX_DISTINCT_TUPLES = 64(either exceeded ⇒ typed 503 "narrow the search"); aconstassertion keeps8 s + MARGIN_MSunderSTANDARD_REQUEST_CEILING;per_page = 0⇒ an empty page, no consult. -
Admitted ids → the page query
WHERE id = ANY($ids)with the same ORDER BY + LIMIT/OFFSET, so pages are full andtotalis the admitted count. Response, defined in the bin (FosterHomeispub(crate)):MatchingResponse { #[serde(flatten)] page: PageResponse<FosterHome>, excluded_by_policy, truncated }; thematching.rsrow leavesUNTYPED_ENVELOPE_ALLOWLIST. Owned consequence:readonlygets 403RULES_CONSULT_DENIEDon matching (fail-closed). -
craig-web: BOTH matching paths call
/v1/placement/matching(the no-child_idfallback drops the raw homes list); refusals renderrejection_detailverbatim.
F. The notice sweep — services/craig-placement/src/expiry_sweep.rs (lib target)
-
Ledger
foster_home_expiry_notices (id, foster_home_id FK ON DELETE CASCADE, kind CHECK IN ('license_expiring','license_expired','training_expiring','training_expired'), training_type NULL for license kinds, expires_on, days_delta, initiated_by, noticed_at; CHECK (kind LIKE 'training%') = (training_type IS NOT NULL); UNIQUE INDEX (foster_home_id, kind, expires_on, COALESCE(training_type, ''))). The module is self-contained: rawsqlx(the bin’sstore/eventsare not importable), the fourdomain_event!wrappers defined here over the contracts payloads,Initiator { Scheduled, Manual { sub } }→created_by="system"/ the sub. -
run_pass(pool, today, SweepConfig { lead_days }, &Initiator):craig_retention::AdvisoryLease:: try_acquire(pool, "placement-expiry-sweep")(AlreadyRunningwhen held; released on every exit) →select_candidates— two INDEPENDENT selections: license (storedactive,license_expires ⇐ today) and, U2, training (stored-active homes with any or NULL license date whose per-type
lead_dayseffective_expires_on ⇐ today + lead_days) → per candidatenotice_one: one tx that locks the home row, RE-DERIVES the fact (skips if it no longer holds), thenINSERT … ON CONFLICT DO NOTHING RETURNING idand stages the event in the SAME tx only when the row landed.expiring:0 ⇐ expires_on − today ⇐ lead_days;expired:expires_on < today; keys(home, kind, expires_on[, type])— a renewal is a new key.select_candidates/notice_onearepubfor the deterministic tests. -
Health:
record_success("expiry-sweep")ONLY whenfailures == 0; failures logged at error with a counterplacement_expiry_notice_failures_total; alert on a stale heartbeat OR a rising counter. Workerexpiry-sweep(Observed,watch_optional, census idworker.craig-placement.main.watch_optional, health pindisabledon the devstack); a drain test;spawn_workersgains&settings; nextestplacement-expiry-lease = { max-threads = 1 }with the override in all three profiles. -
Admin run
POST /v1/placement/expiry-sweep/run(body-less;Action::Approveon a nil-id FosterHome ref — GA admin + supervisor, TX admin + regional_supervisor; caseworker/readonly 403) →Json< ExpirySweepReport>(contracts); lease held → 409SWEEP_ALREADY_RUNNING; ceiling classBatch; test-libPlacementClient::run_expiry_sweep()typed. -
Events (contracts,
deny_unknown_fields):FosterHomeLicenseNoticePayload { notice_id, foster_home_id, expires_on, days, created_by },FosterHomeTrainingNoticePayload { …, training_type }underfoster_home.license_expiring|license_expired|training_expiring|training_expired;created_byfeeds craig-security’s actor chain, whoseextract_resource_idgains thefoster_home.family (foster_home_id) and whoseparse_event_typegains the three missing arms; a devstack test asserts the persistedaudit_logactor and resource columns.
G. Settings, web, seed, corpus
-
PlacementSettings { rules_engine_url, expiry_sweep: { interval_seconds (0 = no scheduler), lead_days (30, `1..=365) } }` flattened onServiceSettings; envCRAIG_PLACEMENTRULES_ENGINE_URL,CRAIG_PLACEMENTEXPIRY_SWEEPINTERVAL_SECONDS(devstack0),CRAIG_PLACEMENTEXPIRY_SWEEP__LEAD_DAYS. -
craig-web:
FosterHomeView.effective_license_status(required; backend deploys first); effective badges on list/detail/matching; "expired on {date}";training_evidencemarks expired/undated rows;create_placementflashesrejection_detailverbatim. -
Seed: anchor without new RNG draws —
license_expires = as_of_month + 12 months + (licensed_at ordinal % 300) days,licensed_at = license_expires − 24 months; CPRcompleted_at = as_of_month − (ordinal % 700) days,expires_at = completed_at + 730 days; regeneratetests/e2e/lib/seed.ts(no id churn) and update the placement byte pins intools/craig-seed/tests/sql_byte_identity.rs. -
Corpus: U1 re-classes
license_expires_drives_status→store-onlywithblocked_by = ["#1642"]; U2 re-classestraining_expiry_observed→store-only, unblocks and retitles the row;cargo xtask scenarios audit --blessper unit.
Steps
U1 — the license machine + the ruleset (#1641, weight 5; Closes #1641)
§A (license half, the ledger, the trigger), §B v1.0, §C, §D, §E, §F (license notices), §G — one MR on
feat/1641-license-expiry, five commits: derive effective license status + settings; add the ruleset
v1.0 (GA + TX, citations); consult license_gate at activation and matching; sweep license notices
the run endpoint; web + e2e + seed + corpus + docs. Green alone: the v1.0 output set is the U1 parser’s
required set.
U2 — the training machine (#1642, weight 5; Closes #1642)
§A training evidence, §B v1.1, §C/§D/§E training half, §F training notices, §G — one MR on
feat/1642-training-expiry, four commits: derive training evidence + v1.1 training_gate; gate
activation and matching on training; sweep training notices; web + e2e + corpus + as-built docs
the ADR-072 amendment + .claude/CLAUDE.md. Completion: push (battery) → open the MR → commit Status
Done (YYYY-MM-DD) — !N + nav Active → Archive → push → merge.
Verification
Before every push: the bare validate stages (fmt, clippy -D warnings, quality-budgets, plan-lint,
every lints, axis-coverage, check-docs, machete, rustdoc, api-docs --check, validate-authz-coverage,
rules check, policy audit, scenarios audit, contested-census, coverage-matrix-mapping); cargo
nextest run for craig-common, placement-contracts, test-lib, web, rules, policy, craig-seed and xtask;
the devstack and the FULL cargo nextest run -p craig-placement --run-ignored all; the rehearsal (the
run endpoint as supervisor; an expired-by-date given home absent from both matching paths and the
new-placement form, its activation 409 flashed verbatim; /readyz lists expiry-sweep disabled; the
caseworker e2e project green); then the pre-push battery, one at a time, reseeded first.
Test classes (property-named, // @axis: tagged): proptests for the derivations, the training state
classification and every new contract’s serde round-trip; unit tests for the consult error map, each
cross-field 500 and the budget assertions; devstack HTTP tests for filter/sort semantics, full matching
pages with total, one consult per distinct tuple, the readonly 403, the typed refusals, replay after
expiry, the unchanged #1635 pins and the endpoint role matrix; real-path concurrency tests with
wait_for_blocked_behind; sweep tests (once per key, lead-window edges, renewal between selection and
notice, event-iff-row, partial failure withholds the heartbeat); render tests; the e2e spec.
Documentation Updates
-
implementation-guide.adoc(REST row, events rows, rules bullet),data-model-placement.adoc,state-machines.adoc,adr-003-rabbitmq-topology.adoc(catalog),rulesets.adoc(7 domains, differences row, files),configuration-reference.adoc,deployment-guide.adoc(knobs, rollout and rollback order, alert row, rate-limit sizing),api/craig-placement.adoc(regenerated), ADR-072== Amendment — #1641/#1642,CHANGELOG.adocAdded/Changed,.claude/CLAUDE.md(U2).
Review log
| Round | Vendor | Resolved model | Verdict |
|---|---|---|---|
1 |
Anthropic — three fresh contextless lenses (engineering, security/policy, implementability), the four plan-lifecycle questions |
Claude Fable 5.1 |
engineering ship; security/policy no-ship; implementability no-ship → folded |
2 |
the maintainer (human gate review) |
— |
no-ship (15 findings + 4 ambiguities) → folded → approved 2026-09-07 |
Errata
-
Erratum (2026-09-07): zen-engine 0.54 omits a null-valued output from the evaluation result, so the
license_gateadmit row answers the sentinel tokennone(the closed vocabulary isnone | license_expired | license_not_active) rather than the literal null §B assumed; the consult treats an absent required key as contract drift (500) unchanged. -
Erratum (2026-09-07): the day-count helper
days_past_license_expiryand its properties land with their consumer in the consult commit, not the derivation commit (an unused fn is dead code under-D warnings). -
Erratum (2026-09-07): the consult module lives at
services/craig-placement/src/eligibility.rs(a bin module besideapi/store), not underapi/— it defines no routes and the route-module LOC budget countsapi/*.rs; §C’s design is unchanged. §C’s heading now cites this as-built path (citation corrected 2026-10-15). -
Erratum (2026-09-07):
placement_expiry_notice_failures_totalis recorded inside the pass body (the lib’srun_pass_held, so scheduled and manual passes alike), not by the scheduler loop — one emission site; the heartbeat rule (failures == 0) stays in the scheduler as §F says.