Plan: the intake section save builds each section’s contract payload (#3593)
Status: Done (2026-12-01) — the routed contract check, the typed builder and the typed completion delivered in three units
Closes: #3593 (by U3)
Issues: #3593 (parent) · U1 #3594 (w3) · U2 #3595 (w5) · U3 #3596 (w1) · relates to #3408, #3591, #3592, #3597, #3598
Branches: test/intake-section-mock-decodes (U1), fix/intake-section-payload-typed (U2), refactor/complete-data-collection-typed (U3)
This is a Design + Scope plan: GitLab owns tracking, the unit issues carry the implementer brief, and the plan freezes when U1 starts.
Problem
A worker saves an intake section from a small form on the intake page. canopy-web turns the posted form into the JSON body of canopy-applications' PUT /v1/applications/{id}/sections/{program}/{section}. One generic converter does this for all twelve sections: form_to_section_payload in services/canopy-web/src/api/applications.rs.
-
It guesses a value’s type from its text.
trueandfalsebecome booleans, two named fields become numbers,verified_at=nowbecomes the server time, and everything else is a string. -
It forwards every posted key except
_csrf. -
It adds eight booleans (
OPTIONAL_BOOLS) to every non-empty body, whatever the section. -
Two more functions patch the object afterwards:
SectionTarget::bind_householdwrites the household id, andsynthesize_household_membersadds the roster.
No type says which fields a section’s body carries. Four things follow.
-
Fields outside the section are stored. canopy-applications checks a body against the section’s payload and then stores the body as received (
services/canopy-applications/src/api/sections.rs,typed; #3592). An identity save is stored withrelationships_confirmed: false,agreement_signed: falseand six more. A household-composition or Personal Responsibility save is stored with averified_atits payload does not have. A crafted form can add keys of its own. -
No test shows that a section’s form produces a body its contract decodes. The routed mock for the section write (
services/canopy-web/src/api/mock_upstream/intake.rs,section_put) checks only that the program is active. One unit test covers household composition and one routed test covers special circumstances. -
A value a section cannot take is sent upstream. It comes back as canopy-applications' 422, which the worker sees as the redacted upstream error.
-
A note that reads
trueorfalseis refused. The converter sends it as a boolean, which the note’s field does not decode. The SAVE case number has the same defect.
These are the last sites budget B3a counts in canopy-web (#3408): fifteen serde_json::Value mentions in the section-save code and two in the Complete Data Collection handler.
Decisions (maintainer, approved 2026-11-30)
-
canopy-web refuses a value a section cannot take, before the write. The answer is the save’s existing banner in the row’s status slot (HTTP 200, "Could not save: …"), naming the field. Today the value reaches canopy-applications and is refused there. A person field is the exception:
admitruns first, and it still refuses any value that is not a roster member’s id with its audit record, as today. -
A save sends only the fields of its section’s contract payload. New saves stop storing the eight booleans on sections that do not have them. Rows stored earlier keep what they hold. No code in the workspace reads inside a stored section’s payload: the intake page takes a stored row’s program, section name and two stamps (
build_intake_section_rows), theapplication_section.updatedevent carries no payload, and no SQL or e2e spec reads it. The doc comment onApplicationSection.payloadsays the intake template re-deserialises it; that comment is out of date.
The body’s shape changes in one more way. It becomes the contract payload’s own serialization, and the payload structs do not skip unset fields. A field the save leaves unset is sent asnull, and an emptyverificationslist as[], where today those keys are absent. canopy-applications decodes an absent key and anullto the same value, and stores what it receives. -
A field the section’s form does not offer is not sent, even where the contract has it:
document_evidence_id,abawd_applicable,exemption_reason,good_cause_claim,ivd_referral_id,state_months_used,signed_atand theverificationslists. A crafted request that posts one is no longer forwarded.admitdoes not change: it still checks every postedhousehold_idand every posted person field (person_id,…_person_id), whatever the section, and refuses and records as today. -
verified_atis the server’s time, to the second as today. A posted timestamp is not read. Today a crafted request can post any timestamp and it is forwarded. The time stays the wall clock (chrono::Utc::now()), where the converter reads it today. One consequence: a request that posts noverified_atnow saves, where today the origin refuses it for the missing field. The page’s own form has always posted it. -
signed_atstays unset on the Personal Responsibility section, as today. What it should hold is #3591. -
The write’s answer is still not read. The handlers do not use it. Any JSON answer counts as saved, as today.
-
canopy-web refuses an unknown section slug, with the same banner and no write. The gates keep their order, so the two binding reads and
admit(with its audit record for another household or an off-roster person) still run first, as today. Today the slug is forwarded and refused upstream. The page links only the twelve sections. -
Text is stored as text. A note or a SAVE case number whose whole text is
trueorfalsesaves as that text.
Design
The payload type
A new child module, services/canopy-web/src/api/applications/section_payload.rs, holds the type and its builder. It is a child of api/applications.rs, so no route module grows (api/mod.rs is at 496 of the 500 lines budget B1 allows).
/// One intake section's body: the contract payload of the section it saves.
#[derive(Debug, PartialEq, Serialize)]
#[serde(untagged)]
pub(super) enum SectionPayload {
Identity(IdentityPayload),
HouseholdComposition(HouseholdCompositionPayload),
Citizenship(CitizenshipPayload),
Residency(ResidencyPayload),
IncomeEmployment(IncomeEmploymentPayload),
Resources(ResourcesPayload),
ExpensesShelter(ExpensesShelterPayload),
WorkRegistration(WorkRegistrationPayload),
SpecialCircumstances(SpecialCircumstancesPayload),
TanfChildSupport(TanfChildSupportPayload),
TanfPersonalResponsibility(TanfPersonalResponsibilityPayload),
TanfTimeLimits(TanfTimeLimitsPayload),
}
impl SectionPayload {
pub(super) fn from_form(
section: SectionName,
form: &HashMap<String, String>,
household_id: HouseholdId,
members: &[HouseholdMemberRef],
now: DateTime<Utc>,
) -> Result<Self, FieldRefusal>;
/// The special-circumstances answer, for the homelessness follow-up.
pub(super) fn special_circumstances(&self) -> Option<&SpecialCircumstancesPayload>;
}
The variants are the twelve structs of canopy_contracts_applications::sections::payloads. untagged makes the enum serialize as the struct it holds, which is the body canopy-applications decodes. The builder takes the household’s id and members as plain values, not the SectionTarget whose fields are private to section_binding, so its tests build them directly.
The builder
from_form is one exhaustive match on SectionName that calls one small function per section. Each function reads the fields in the middle column and sets the rest as the right column says.
| Section | Read from the form | Set by the builder |
|---|---|---|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
the six flags, |
|
|
|
|
|
|
|
|
|
|
The field readers are private functions of the module.
-
text(form, name)is the trimmed value, absent when it is blank, as the converter treats a value today. Every other reader goes through it. -
id::<T: FromStr>(form, name, what)reads a required id (PersonId). -
choice::<T: DeserializeOwned>(form, name, what)andoptional_choiceread a closed set. They parse with the contract enum’s own serde names (T::deserialize(text.into_deserializer())), so the values accepted are the contract’s. -
checked(form, name, what)reads a checkbox. Absent or blank isfalse,trueandfalseare themselves, and any other text is refused. -
number::<i32>(form, name, what)readsfederal_months_usedwithi32::from_str, so it takes the numbers the origin’s decode takes today. The form’sminandmaxare the browser’s check; the contract sets no range. -
optional_text(form, name)readsworker_notesandsave_case_number: absent when blank, the trimmed text otherwise (decision 8).
FieldRefusal is Missing(&'static str) or Invalid(&'static str), and displays as "missing <what>" or "invalid <what>". "invalid <what>" is the fact editors' wording (api/fact_editor/form_values.rs); "missing <what>" is new, in the same form. It holds the field’s label and nothing from the request, so the banner and the log line carry the label and not the value. The labels: person_id "person"; head_of_household_person_id "head of household"; address_person_id "address holder"; verification_method "verification method"; categorical_eligibility_basis "categorical eligibility basis"; sua_election "utility allowance election"; registration_status "registration status"; cooperation_status "cooperation status"; federal_months_used "federal months used"; a checkbox is its field name with spaces for underscores. The refusal is not an audited one: it names no other household or person, and the upstream 422 it replaces was not audited either.
SectionTarget::members returns one HouseholdMemberRef per roster member where it returned string pairs: relationship_to_head is the membership’s relationship, and purchases_and_prepares_meals_with_head is none. The head-only fallback of synthesize_household_members goes. admit refuses a head who is not on the roster, so an empty roster does not reach the builder with a head (an_empty_roster_admits_no_person), and a save with no head is refused as "missing head of household".
now is read once by the handler, as chrono::Utc::now().trunc_subsecs(0) (chrono::SubsecRound), and passed in, so the builder is a pure function. Whole seconds is the precision the converter writes today, and the homelessness follow-up keys its claim on this value (claim_key), so two saves in the same second share a key (the_claim_key_is_shared_by_twins_only). The truncation is the handler’s, so a routed test pins it: a_saved_sections_time_is_whole_seconds.
Considered and not taken: one serde form struct per section, decoded from the posted map. A checkbox’s "absent is false" and a refusal that names its field would each need a custom deserializer per field, which is more code than the readers above.
The handler
put_section_proxy keeps its gates in their order. Only steps 4 and 5 change.
-
The path program’s scope gate (
authorize_path_program). -
The binding reads (
section_binding::section_target). -
SectionTarget::admiton the raw form, with its audited refusals. A person off the roster is still refused here, so the builder sees only roster members (the_section_save_binds_its_household_and_people). -
New:
SectionName::from_slugresolves the slug andSectionPayload::from_formbuilds the body fromtarget.household_id()andtarget.members(). An unknown slug ("unknown section") or aFieldRefusalreturns through a newsection_payload_refused(application_id, program, section, message)besidesection_save_refused: it logs a warning with those four values and rendersSectionSaveOutcome::Refused. No write is made. -
The write:
save_section_upstream::<SectionPayload, serde::de::IgnoredAny>.
homelessness_claim::follow takes Option<&SpecialCircumstancesPayload>, from SectionPayload::special_circumstances. SyncError::Section, its arm for a body that did not decode, is removed: the payload is already the type. The failure case of the_follow_up_banner_names_what_was_written is rewritten onto SyncError::Key ("the claim could not be keyed"), so the banner’s failure branch keeps its unit test.
complete_data_collection_proxy posts crate::api::snap_action_ladder::EmptyBody, the typed empty body canopy-web already has. It serializes as {}, the bytes the handler sends today. The answer is read as serde::de::IgnoredAny.
Removed: form_to_section_payload, synthesize_household_members, SectionTarget::bind_household, SPECIAL_CIRCUMSTANCES_BOOLS, OPTIONAL_BOOLS, and their tests. The doc comments of put_section_proxy and SectionTarget::household_id that describe them are rewritten.
Function size. Every function this plan adds is 40 lines or fewer. put_section_proxy is 97 lines today and about 70 after U2; complete_data_collection_proxy is 50 and stays 50. Both are existing debt over the 40-line rule and under budget B2’s 100. Neither grows, and this plan does not split them: the standards make burning down grandfathered debt its own issue (standards:coding-conventions, the transition-allowed lints).
The form
services/canopy-web/templates/applications/_intake_section_form.html loses its hidden verified_at input, which carried only the placeholder now. The comment above it says canopy-applications fills a missing verified_at. It does not (the field is required), so the comment goes with the input, and the file’s header comment stops naming the hidden field. No other markup changes.
What does not change
-
The fields each form offers, and the values a valid save stores for them. Decision 2 covers the keys stored around them.
-
The scope gate, the binding reads,
admitand its audited refusals. -
canopy-applications. It still validates what canopy-web sends (the note’s and the case number’s length, at least one member) and still answers 422 for a program not on the application or a section that does not apply. What it stores for other writers is #3592.
-
The retrying
put_idempotentwrite (#1270) and the 200-with-banner answer (#2082). -
The special-circumstances homelessness follow-up (#3147).
-
The e2e helpers in
tests/e2e/lib/given/, which save sections straight to canopy-applications.
Units — U1 → U2 → U3
Weights: 1 trivial · 2 small · 3 medium · 5 large. One unit is one MR and one child issue. Paths below are under services/canopy-web/src/api/ unless they say otherwise.
U1 (w3) — the routed mock decodes a section body as the origin does (tests only)
Files: mock_upstream/intake.rs; one line changed in place in mock_upstream.rs; new applications/section_forms.rs and applications/section_contract_tests.rs (both #[cfg(test)], declared in applications.rs); applications.rs (its tests module); write_authz_route_tests.rs; bound_route_tests.rs; applications/homelessness_claim/route_tests.rs.
The mock. mock_upstream.rs passes the request body to mock_intake_surface (line 344; the file is within two lines of budget B1’s 500, so the call changes in place and adds no line). section_put then answers a PUT in the origin’s order (upsert_section): an unknown section slug is the 422 "unknown section name"; a body that does not decode as that section’s payload is the 422 "payload does not match section schema"; a program not on the application is today’s 422; anything else falls through to the mock’s {} answer, as today. The decode is one exhaustive match on SectionName over serde_json::from_str::<TheSectionsPayload>. The mock does not run the origin’s Validate step: canopy-web does not depend on validator, and this plan does not add it. A unit test beside it, the_section_write_refuses_a_body_its_section_cannot_decode, calls section_put with {} for each section and with each section’s valid body.
The form table. section_forms.rs holds, for each of the twelve sections, the program whose page shows it (snap, or tanf for the three TANF sections) and its fields as (name, value). The values are valid, with TEST_PERSON and TEST_HH of route_test_harness for people and the household. It also holds rendered_form(section), which renders the intake page for that program and returns the section’s form: tests::intake_tmpl and tests::section_form in applications.rs become pub(super), and section_form takes the program (the TANF render sets sections and program_slug as the test at applications.rs:7096 does).
The test. every_sections_form_saves_a_body_its_contract_decodes, twelve cases. Each asserts the table’s field names equal the name="…" attributes of the rendered form, then sends the table’s form through the route (worker scoped to the program, the mock’s application on that program through CaseSpec::upstream) and asserts one write and the banner Saved — {section} ({program}).. A section whose body does not decode is a defect of today’s code: it gets its own fix: issue and MR before U2.
Existing tests. Three routed tests expect a save and post a body the contract does not decode. They pass today only because the mock counts the write before it answers. U1 gives each a body that decodes, and has each assert the saved banner: put_section_write_authz_matrix (an empty body) takes the table’s identity form for its in-scope writers; the_section_save_binds_its_household_and_people and a_save_with_nothing_to_change_writes_no_fact gain the verified_at=now the form posts.
U2 (w5) — the typed builder
Files: applications.rs; under applications/: section_payload.rs and section_payload/tests.rs (new), section_binding.rs, section_forms.rs, section_contract_tests.rs, homelessness_claim.rs with its tests.rs and route_tests.rs, special_circumstances_route_tests.rs; bound_route_tests.rs; services/canopy-web/templates/applications/_intake_section_form.html; tests/e2e/specs/intake.spec.ts and intake-partial-demo.spec.ts (one comment each names the hidden input); docs/modules/ROOT/pages/api/canopy-web.adoc; CHANGELOG.adoc; xtask/quality-budgets.lock.
Everything in the Design except Complete Data Collection. The form table gains a second valid value per field and loses verified_at, and every test body that posts verified_at=now drops it, as the form does. only_the_household_sections_carry_the_proven_household moves to the builder’s tests. B3a falls by 15: fourteen mentions in applications.rs and section_binding.rs:143.
Tests
The workspace has no HTML parser. The tests that read a rendered form find its name="…" and <option value="…"> attributes with a string scan, as test_support::form_keys does. A test that needs a body’s keys decodes it into BTreeMap<String, serde::de::IgnoredAny>, so no test adds a counted serde_json::Value.
| Category | Tests |
|---|---|
Contract (wire) |
U1: |
Unit (builder) |
One table test per section: the form table’s fields give exactly the expected payload struct at a fixed |
Property |
|
Agreement |
|
Routed |
|
Regression |
|
Mutation |
A hand mutant in each section’s builder (a field read under another name, a flag inverted, a default changed) fails that section’s table test. |
Not run locally unless a devstack is up (the merge train runs them): the Playwright intake journeys, which save sections through the page.
Risks
| Risk | Mode | Mitigation |
|---|---|---|
A builder reads a field under the wrong name, and a value the worker entered is dropped. |
silent |
The per-section table tests assert the exact payload, and |
The form gains an input and no builder reads it. |
silent |
U1’s test holds the form table’s names to the rendered template’s, and the agreement test needs every name in the table to change the payload. |
The form offers a choice the contract does not have. |
fail-closed |
The save is refused naming the field. |
The builder refuses a value canopy-applications would accept. |
fail-closed |
The readers use the contract types' own parsers (serde names, |
A test that expects a save posts a body the builder refuses, as the write-authorization matrix’s empty body would be. |
fail-closed |
The test fails. U1 gives each such test a body its section decodes before the builder exists. |
A crafted request posts a contract field the form does not offer, or its own timestamp. |
fail-closed |
Neither is read or sent (decisions 3 and 4): |
The builder is given an empty roster with a head, and sends a composition with no members. |
fail-closed |
|
The save’s time loses its whole-second precision, and a double-submitted homeless save claims twice. |
silent |
The handler truncates to seconds as the converter does: |
A save lands and its answer is not the contract’s shape. |
fail-open |
The answer is not read (decision 6), so the banner says saved, as today: |
A new save stores |
silent |
canopy-applications' payload structs decode both to the same value, and U1’s mock decodes every typed body with those structs. No code in the workspace reads inside a stored payload (decision 2). |
Rows stored before the change keep fields of other sections. |
silent |
No code in the workspace reads inside a stored section’s payload (decision 2 lists what was checked). #3592 decides whether the origin should refuse or strip such fields. |
A page rendered before the deploy still posts |
fail-closed |
The builder does not read it. The save lands with the server’s time. |
A signed Personal Responsibility agreement still has no |
silent |
Unchanged from today and out of scope (#3591). |
Scope
In scope: canopy-web’s section save and Complete Data Collection handlers, the section form’s hidden input, the routed mock’s section write, and their tests and docs.
Out of scope:
-
What canopy-applications stores or refuses (#3592).
-
The Personal Responsibility section’s signing time (#3591).
-
Offering the contract fields the form does not have (documents, exemptions, the verifications lists).
-
A range for
federal_months_used. The contract takes anyi32, and only the browser holds it to 0-60 (#3597). -
Splitting
put_section_proxyandcomplete_data_collection_proxyto 40 lines (Design, Function size). -
The cancel write in
api/actions_verification.rs, which carries a marker and is not a counted site. -
Correcting the out-of-date doc comment on
ApplicationSection.payload, which is in the contract crate. It is recorded on #3592. -
The clock
verified_atis read from. canopy-applications stamps the same save from the decision clock, so under an advanced test clock the two differ, as they do today. canopy-web holds no decision-clock handle, and budget B8 admits no new ambientclock::now()(#3598).
Verification
-
Each unit:
cargo xtask test --unit(fmt, clippy and the unit lane) is green, with the tests this plan names among those run. -
cargo xtask quality-budgetsreports B3a down by 15 after U2 and by 2 more after U3, and no other budget up. -
U1 on today’s code: all twelve cases pass, or the failing section has its
fix:issue first. -
U2: each hand mutant of the Tests table fails its table test, and is reverted.
-
The merge train’s pipeline is green. It is the first run of the Playwright intake journeys against the typed bodies.
Delivery
-
Plan: this page is committed as
docs/modules/ROOT/pages/plans/intake-section-save-typed.adoc, with its entry indocs/modules/ROOT/nav.adoc, before U1 starts. -
Docs: in
docs/modules/ROOT/pages/api/canopy-web.adoc, the row forPUT /applications/{id}/sections/{program}/{section}says what the save builds, what it refuses and that it sends only the section’s fields (U2). The row for the completion route says what it posts and that the answer is not read (U3). -
Changelog: one entry per unit under
== UnreleasedinCHANGELOG.adoc. U2’s says a save now refuses a value the section cannot take, no longer sends other sections' fields, and stores a note that readstrueas text. -
Budget:
xtask/quality-budgets.lockfalls with U2 and U3, each with its note. -
Close: U3’s MR closes #3593. The merge SHAs go on #3593 and #3408.
Review log
| round | vendor | resolved model | verdict |
|---|---|---|---|
1 |
Anthropic |
claude-fable-5-2 |
CLEAN on the first draft. On the draft revised after the adversarial review: FLAGS — the whole-second truncation had no test that fails without it. |
2 |
gemini-4-carbon |
CLEAN on the first draft, and CLEAN on the revised draft. |
|
adversarial, asked for by the maintainer |
gemini-4-hydrogen |
FLAGS — two blockers and six majors, each checked against the code and answered in this text. Blockers: the write-authorization matrix posts an empty identity form, which the builder refuses (U1 now gives it a valid body); decision 7 promised no upstream call where the binding reads still run (now "no write"). Majors: unstated changes for a request without |