Plan: Placement Expiry Machines — License + Training (#1641, #1642)

Archive record

Merge requests: !1584 (U1, Closes #1641) + !1585 (U2, Closes #1642)

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

  1. GA training_gate (⁂ #1073): an EXPIRED cpr_first_aid refuses activation and excludes from matching (PAMMS 14.9 "maintain current certification in CPR and First Aid throughout the approval period"); an UNDATED cpr_first_aid record 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.

  2. GA license_gate: DERIVED expired (stored active, 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 terminal expired and pending | suspended | revoked keep today’s foster-home-license-not-active at activation (the #1635 pins are untouched).

  3. 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 expired arms apply only where a CPA records an end date.

  4. Matching candidate scope: the SQL generator keeps stored active + capacity — pre-existing tier-1 residue outside this ruling, kept for result precision; license_admits_matching is therefore reachable only for stored-active candidates (stated in the ruleset, the citations and the ADR-072 amendment; migrating the scope into a matching-scope table is a follow-up issue).

  5. Household proxy: foster_home_training carries 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-eligibility v1.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). Clearing license_expires through update_foster_home (#1725).

Design

A. Derivations (store)

  • effective_license_status_sql(p) builds CASE 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). FosterHome gains effective_license_status: LicenseStatus; every FosterHome query binds today (get, get_for_update, list_paged, count, create/update via RETURNING *, <expr>, search_matching_homes); the license_status filter AND sort use the effective column (pre-1.0 Changed). days_past_license_expiry(home, today) is 0 unless derived-expired.

  • U2 training_evidence(exec, home_ids, today): per type of the six-token craig_reference::TrainingType vocabulary, TypeEvidence { state: Current | Expired | Undated | Absent, effective_expires_on, days_past_expiry, days_until_expiry, evidence_row } from ACTIVE rows with completed_at ⇐ today (future completions are not evidence): dated rows decide by max(expires_at); only undated rows ⇒ Undated; no rows ⇒ Absent. ONE representation feeds the gate input, the 409 detail, the sweep and FosterHomeDetail.training_evidence. The API refuses a future completed_at at record/update (typed 400, jurisdiction clock).

  • Migration 20260908120000_foster_home_expiry.sql (additive; SET LOCAL statement_timeout = '60s'): a partial index on foster_homes (license_expires) WHERE license_status = 'active'; an index on foster_home_training (foster_home_id, training_type, expires_at) WHERE active; the notices ledger (§F); the trigger trg_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 in tests/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; inputs i_status, i_days; outputs license_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 over training.<type>.state, i_ptype field placement_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; absent admits). 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 ⇒ facts days_past_license_expiry > 0; training_expired / training_unverifiable ⇒ some type in the facts is expired / undated; an unknown token or a missing required key ⇒ 500. Required outputs: v1.0 the three license_* keys; v1.1 adds the three training_* keys.

  • Citations: the #description row and one row per rule (value = _description verbatim; pamms rows carry source_ref, section, manual_transmittal, effective_date, verified_date, verified_by, quoted evidence, derivation where transformed, source_sha256 pinned by cargo xtask policy sync-cache --pin); Texas rows manual authority with the HHSC PDF as source_ref; the plumbing row excepted. Tests: services/craig-rules/tests/{georgia,texas}_ruleset_evaluation.rs pin every row and the all-defaults fall-through; rules check, ruleset_discovery, the tether tests and committed_corpus_audits_finding_free gate 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

  1. Create born-active: validate → authz → ClaimSpec → request_claims::precheck — a Replay returns 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 409 CONCURRENT_MODIFICATION → capacity → write. The §A trigger makes every training writer wait on that lock, so the equality is DB-enforced across mixed versions.

  2. planned → active (no claim; a repeated active is an invalid transition): the same pre-tx consult, then the in-tx equality in guard_home_for_transition.

  3. check_home_admits_activation(&home, &facts_locked, &consulted, &verdict) replaces the #1635 stored-status branch, which is now the LicenseNotActive arm.

E. Matching — evaluate before paging

  1. SELECT id, <facts columns> for ALL candidates in order (scope unchanged; MATCHING_CANDIDATE_CAP = 5000, truncated beyond) → U2 training_evidence batch → facts per candidate → grouped by tuple → memoized consults, buffer_unordered(8), the WHOLE fan-out under MATCHING_CONSULT_BUDGET = 8 s and MAX_DISTINCT_TUPLES = 64 (either exceeded ⇒ typed 503 "narrow the search"); a const assertion keeps 8 s + MARGIN_MS under STANDARD_REQUEST_CEILING; per_page = 0 ⇒ an empty page, no consult.

  2. Admitted ids → the page query WHERE id = ANY($ids) with the same ORDER BY + LIMIT/OFFSET, so pages are full and total is the admitted count. Response, defined in the bin (FosterHome is pub(crate)): MatchingResponse { #[serde(flatten)] page: PageResponse<FosterHome>, excluded_by_policy, truncated }; the matching.rs row leaves UNTYPED_ENVELOPE_ALLOWLIST. Owned consequence: readonly gets 403 RULES_CONSULT_DENIED on matching (fail-closed).

  3. craig-web: BOTH matching paths call /v1/placement/matching (the no-child_id fallback drops the raw homes list); refusals render rejection_detail verbatim.

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: raw sqlx (the bin’s store/events are not importable), the four domain_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") (AlreadyRunning when held; released on every exit) → select_candidates — two INDEPENDENT selections: license (stored active, license_expires ⇐ today
    lead_days
    ) and, U2, training (stored-active homes with any or NULL license date whose per-type effective_expires_on ⇐ today + lead_days) → per candidate notice_one: one tx that locks the home row, RE-DERIVES the fact (skips if it no longer holds), then INSERT … ON CONFLICT DO NOTHING RETURNING id and 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_one are pub for the deterministic tests.

  • Health: record_success("expiry-sweep") ONLY when failures == 0; failures logged at error with a counter placement_expiry_notice_failures_total; alert on a stale heartbeat OR a rising counter. Worker expiry-sweep (Observed, watch_optional, census id worker.craig-placement.main.watch_optional, health pin disabled on the devstack); a drain test; spawn_workers gains &settings; nextest placement-expiry-lease = { max-threads = 1 } with the override in all three profiles.

  • Admin run POST /v1/placement/expiry-sweep/run (body-less; Action::Approve on a nil-id FosterHome ref — GA admin + supervisor, TX admin + regional_supervisor; caseworker/readonly 403) → Json< ExpirySweepReport> (contracts); lease held → 409 SWEEP_ALREADY_RUNNING; ceiling class Batch; test-lib PlacementClient::run_expiry_sweep() typed.

  • Events (contracts, deny_unknown_fields): FosterHomeLicenseNoticePayload { notice_id, foster_home_id, expires_on, days, created_by }, FosterHomeTrainingNoticePayload { …, training_type } under foster_home.license_expiring|license_expired|training_expiring|training_expired; created_by feeds craig-security’s actor chain, whose extract_resource_id gains the foster_home. family (foster_home_id) and whose parse_event_type gains the three missing arms; a devstack test asserts the persisted audit_log actor 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 on ServiceSettings; env CRAIG_PLACEMENTRULES_ENGINE_URL, CRAIG_PLACEMENTEXPIRY_SWEEPINTERVAL_SECONDS (devstack 0), 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_evidence marks expired/undated rows; create_placement flashes rejection_detail verbatim.

  • Seed: anchor without new RNG draws — license_expires = as_of_month + 12 months + (licensed_at ordinal % 300) days, licensed_at = license_expires − 24 months; CPR completed_at = as_of_month − (ordinal % 700) days, expires_at = completed_at + 730 days; regenerate tests/e2e/lib/seed.ts (no id churn) and update the placement byte pins in tools/craig-seed/tests/sql_byte_identity.rs.

  • Corpus: U1 re-classes license_expires_drives_status → store-only with blocked_by = ["#1642"]; U2 re-classes training_expiry_observed → store-only, unblocks and retitles the row; cargo xtask scenarios audit --bless per 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.adoc Added/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_gate admit row answers the sentinel token none (the closed vocabulary is none | 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_expiry and 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 beside api/store), not under api/ — it defines no routes and the route-module LOC budget counts api/*.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_total is recorded inside the pass body (the lib’s run_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.

Edit this page · latest