# Nutrition reference contract and profile audit

Use this reference when designing or reviewing a read-only backend/data contract that compares documented nutrient intake with age/sex/factor-specific public-health reference values.

## Source-first inventory

1. Record the exact revision and clean/dirty state; make no writes during a source-only design review.
2. Inspect the canonical nutrient contract, unit conversions, read API aggregation, reference-context helper, canonical DB schema, synthetic fixtures, and focused nutrition/profile tests.
3. Verify what “profile” means in this repository. A build/render profile or action schema is not a demographic nutrition-reference profile.
4. State explicitly whether structured birth date, sex classification, pregnancy/lactation or other required factors exist. Never infer them from document text, names, OCR, or unrelated health observations.
5. Run the narrow existing tests and report pre-existing failures separately; recheck that the tree stayed unchanged.

## Minimal robust architecture

Prefer four narrowly separated pieces:

1. **Local immutable reference dataset** — versioned JSON or Python data containing exact canonical nutrient key, unit, source organisation/title/edition/publication and retrieval dates, group selector, required factors, target kind, range/point values, and basis. Runtime loading must not access the network.
2. **Strict loader/validator** — reject unknown nutrient keys or units, duplicate/overlapping selectors, unknown factor names, non-finite values, invalid ranges and checksum/version drift.
3. **Explicit versioned profile store** — structured birth date, source-defined sex class, valid-from/to interval and strictly validated factor object. Multiple active rows, missing fields or invalid factors fail closed.
4. **Resolver/comparison layer** — resolve exactly one group as of an explicit date; return no numeric target when the profile is missing, incomplete, ambiguous or unsupported.

Do not silently repurpose a generic presentation-only reference helper into a numeric medical contract. Keep laboratory observation-specific ranges, personal baselines and nutrition orientation as separate reference types.

## Profile and selector rules

- Compute age from birth date on the explicit comparison date; test the birthday boundary.
- Preserve the terminology used by the source (`sex_class`, if applicable) rather than conflating it with identity/gender fields.
- Model pregnancy, lactation, body weight, activity level or dietary-composition factors only when a released reference entry requires them.
- Missing, `unknown` and `not_applicable` are distinct.
- Never fall back to “general adult”, nearest age group, or either sex.
- Detect overlapping profile validity intervals and overlapping reference selectors at runtime even if schema constraints cover common cases.
- If a reporting period crosses a selector/profile boundary, either segment it explicitly or fail closed; do not mix targets invisibly.

## Period and missingness semantics

For day/7-day/30-day views, use an explicit calendar period but calculate each nutrient over its own documented days:

- `calendar_days`: requested span;
- `documented_days`: days with at least one valid documented or estimated value for that nutrient;
- `complete_documented_days`: days where every relevant food observation is known under the declared completeness rule;
- `mean_per_documented_day`: denominator is `documented_days`, never `calendar_days`;
- explicit documented zero counts as documented;
- absent, not-reported or unknown days are not zero-filled;
- expose `coverage_status` and missingness counts alongside every comparison.

Keep food, enrichment and supplements separately attributable. For per-food evidence, enumerate the item × released-nutrient relationship so an absent nutrient row becomes `not_reported` rather than disappearing from coverage. Bound output; if showing top contributions, report omitted counts and define the denominator as documented food value only.

## Percentage and range contract

- Never clamp percentages at 100; values above 100 are valid arithmetic results.
- Point target: `percent_of_target`.
- Range target: separately emit `percent_of_lower` and `percent_of_upper`; do not invent a midpoint.
- Upper-only/lower-only guidance must retain its target kind and direction.
- Return source version, resolved group ID and profile/reference `as_of` with the numeric target.
- Use neutral comparison language. A documented intake/reference comparison is not a deficiency, toxicity, diagnosis or dosing recommendation.

## API integration strategy

Before adding an endpoint, check whether an existing bounded range endpoint already owns the data. An additive, version-bumped `reference_comparisons` section is usually smaller than a new route. Preserve existing query parsing, future-date policy, read-only DB connection and row limits.

Use shared evidence normalization rather than independently reimplementing unit and missingness logic in daily detail, period summary and series paths. If legacy and current nutrient storage paths coexist, test both.

## Required deterministic tests

1. Local dataset version/checksum and no-runtime-network behavior.
2. Unknown key/unit, non-finite target, duplicate and overlap rejection.
3. Exact age/birthday, sex and required-factor resolution.
4. Missing or ambiguous profile returns no numeric reference.
5. Day, 7-day and 30-day per-nutrient denominators with no zero-fill.
6. Explicit zero versus missing/unknown.
7. Percentages above 100 remain above 100.
8. Point, range and one-sided target calculations.
9. Per-food documented/estimated/not-reported/unknown evidence.
10. Food, enrichment and supplements remain separate.
11. Source, group, source version and as-of fields are present.
12. Neutral-language and forbidden-field scans.
13. Future dates, duplicate/unknown query parameters and row limits remain fail closed.
14. Migration idempotency, overlap detection, integrity and real restore proof for a new profile table.

## Adversarial medical/nutrition correctness probes

For final read-only review, do not rely only on happy-path fixtures. Run small deterministic probes against the resolver/parser and inspect the exact returned target, unit, percentage, and wording:

1. **Every selector boundary:** test the day before, day of, and day after each birthday boundary against the source table's literal labels. Do not derive boundaries from filenames (`65years` can still contain “66 years and older”).
2. **Locale-formatted numbers:** probe decimal commas, decimal points, ranges, slash-separated alternatives, leading `+`, inequalities, footnotes, and parenthetical numbers. A generic regex that recognizes only `.` can turn `9,1` into `9` and `1`.
3. **Additive versus absolute values:** pregnancy, lactation, trimester, age-phase, and activity adjustments marked `+` are increments, not standalone daily targets. If the baseline and required phase factor cannot be combined unambiguously, return no numeric comparison.
4. **Compound formulae:** preserve every term in values such as `g/kg + trimester addition`; never take only the first number. Range-valued weight factors must remain ranges after multiplication.
5. **Semantic units:** dimensional equality is insufficient. Treat `µg`, `µg-RE`, DFE, NE, alpha-TE and similar biological-equivalence units as distinct unless the intake contract explicitly proves equivalence and conversion.
6. **Life-stage states:** missing, unknown, explicitly not applicable, pregnant, and lactating must remain distinct. Absence must not silently mean “not pregnant/lactating” when that factor is required to select the source group.
7. **Period boundary crossing:** a 7/30-day period crossing a birthday, profile-validity, pregnancy/lactation, or other selector boundary must be segmented or rejected, not assigned wholly to the end-date group.
8. **Denominator consistency:** compare the denominator used for the nutrient mean, completeness, percentages, and displayed top-food contributions. A contribution labelled “per documented day” must use that nutrient's documented-day denominator, not all nutrition days.
9. **Above-100 behavior:** verify the numeric text remains unclamped and neutral. For ranges, expose percent-of-lower and percent-of-upper explicitly; a generic percent range can obscure which boundary was used. Visual clipping may not hide the exact textual result.
10. **Rendered source text:** inspect raw source labels passed into the UI for phrases such as “supplement/addition.” Source quotations must be clearly attributed and must not appear as an application-generated supplement recommendation.

When practical, execute the parser directly with adversarial profile/input dictionaries and report concrete counterexamples (for example, the exact erroneous target and percentage), not only source inspection.

## Provenance review

- Preserve snapshot-level provenance: source organisation, official landing/table URL, retrieval date, immutable local version, and checksum.
- Preserve row-level provenance with each numeric target: exact source row/group ID, underlying citation or URL when supplied, source version, and comparison/profile `as_of` date.
- A README containing URLs is not sufficient if the API/UI emits numeric targets without the corresponding row-level provenance.
- Verify checksums against the manifest, but also verify that the runtime loader checks or pins the expected version/checksum rather than trusting any file at the path.

## Medical-language review

- Scan both generated copy and raw source text rendered by the UI.
- Neutral terms include “documented intake,” “below/within/above the reference value,” and “not assessable because data are incomplete.”
- Avoid converting arithmetic into deficiency, excess/toxicity, diagnosis, individualized need, dosing, or supplementation advice.
- For lower-only guidance, values above 100% mean only that the lower reference was reached; for upper-only guidance, wording must retain the upper-limit direction.
- A general disclaimer does not repair a false numeric target, a unit mismatch, or visible prescriptive supplement wording.

## Common pitfalls

- Treating a dashboard generation profile test as evidence that a demographic profile schema exists.
- Publishing numerical references while the current helper explicitly says the profile is incomplete.
- Trusting age-group filenames instead of the literal source selector boundaries.
- Parsing localized decimal commas or additive/compound formulae with a generic number regex.
- Treating biological-equivalence units as interchangeable because their metric prefixes match.
- Treating missing life stage as ordinary/non-pregnant rather than an explicit state.
- Averaging over calendar days and thereby converting missing days to zero.
- Counting a day as complete because one food has a nutrient while other foods omit it.
- Computing contribution shares against an inferred total when coverage is partial.
- Dividing contribution amounts by all period days while the nutrient mean uses nutrient-specific documented days.
- Mixing supplement intake into food contribution labels or rendering source supplement wording as application advice.
- Hiding a profile/reference group change inside a multi-day average.
- Exposing only snapshot-level provenance while dropping the exact row citation used for a numeric target.
- Adding an endpoint when an existing range endpoint can carry a versioned additive section.
