ADR-R2-2. The coaching-input contract crate
Source:
docs/decisions/ADR-R2-2-coaching-input-contract.md. Generated at build time; edit the source file.
Date: 2026-11-21 Status: Accepted. Placeholder number; the controller renumbers R2 ADRs before merging. Builds on ADR-R2-1.
Context
Section titled “Context”R2 (the Rust profile engine) produces a CoachingInput for the AI coach (R3) and the web. M3 defines that contract as the zod schema CoachingInput in packages/ai/src/input/schema.ts (m3 worktree). It is strict: unknown keys are rejected, every key is present (nullable fields are null, never absent), and every string, array and number is bounded. Several rules are zod refinements, which do not appear in a JSON Schema. The Rust side needs the same contract in a form that R2 can build, R3 can read, and a test can compare with the TS source.
Decision
Section titled “Decision”One crate, shared by R2 and R3
Section titled “One crate, shared by R2 and R3”backend/crates/coaching-input holds the contract and nothing else. It has no sqlx and no engine code, so R3 depends on it without pulling in the profile engine. It contains:
types.rs: serde + schemars structs that mirror the zod objects field for field;limits.rs:INPUT_VERSION,LIMITSand the other zod bounds and patterns;validate.rs:CoachingInput::validate() -> Result<(), Vec<Issue>>;schema.rs:json_schema(), the draft 2020-12 schema generated by schemars;enums.rs(ADR-R2-1):AreaId,BandId,WeaknessState.
The schemars attributes and validate read the same constants in limits.rs, so they cannot drift apart.
Field-for-field mapping
Section titled “Field-for-field mapping”Every struct is #[serde(rename_all = "camelCase", deny_unknown_fields)]. Every Option serialises as null.
| zod | Rust |
|---|---|
z.strictObject({...}) |
struct with deny_unknown_fields |
X.nullable() |
Option<X> with #[serde(deserialize_with = "nullable")]: null is None, a missing key is an error (serde alone would read it as None) |
inputVersion: z.literal("coaching-input-v1") |
InputVersion::V1; the schema is {"const": "coaching-input-v1"} |
accountId: z.uuid() |
uuid::Uuid; the schema has zod’s pattern; validate checks it (version 1-8 or nil/max) |
platform, timeClass, color, side, verdict, kind, unit, example side |
Platform, TimeClass (From<chess_core::TimeClass>), PlayerColor (From<chess_core::Color>), LineSide, Verdict, CauseKind, MetricUnit, ExampleSide. All are built with Task 1’s wire_enum!, so like AreaId they have ALL, as_str, Display and FromStr. |
IsoDatetime (generatedAt, playedAt) |
OffsetDateTime with common::js_time::iso (YYYY-MM-DDTHH:mm:ss.sssZ) |
IsoDate (windowStart, windowEnd, onsetDate, onsetFrom, onsetTo) |
time::Date as YYYY-MM-DD. No chrono (ADR-R2-1), so not NaiveDate. |
Count, ply, rank, deviationPly, baseSeconds, incrementSeconds |
u32; rating is u16 |
Score union {cp} / {mate} |
enum Score { Cp(i32), Mate(i32) }, serde’s externally tagged form with lowercase names, so Score::Cp(-30) is {"cp": -30}. That is exactly the zod shape, and a value with both keys is rejected. #[serde(untagged)] would put a bare number on the wire. |
before/after: `string |
number` |
ChangeExample (...exemplarFields, side) |
ChangeExample { #[serde(flatten)] position: ExemplarPosition, side }; unknown keys are still rejected |
UNIT_MAX |
MetricUnit::max(): 1, 1000, 100, 100 000, 4000 |
parseCoachingInput issues |
Issue { path, message }, path joined with . (weaknesses.0.exemplars.0.fen) |
Schema generation
Section titled “Schema generation”json_schema() uses SchemaSettings::draft2020_12() plus one recursive transform, contract_transform:
- schemars 1.2.3 leaves a plain
Optionfield out ofrequired, and#[schemars(required)]would drop itsnull. So the transform setsrequiredon every object to all its property names (sorted, so the output does not depend on serde_json’s map order).Option<T>staysT | null.rust_schema_requires_every_property_and_keeps_nulltests this. - It drops schemars’ Rust-only number formats (
uint32,int32,doubleand so on). zod does not emit them, and a strict validator such as Ajv rejects unknown formats.
Timestamps, dates and the UUID use schema_with functions that emit zod’s exact format, pattern and maxLength. Unit-only enums carry no per-variant doc comments, because those would turn enum into a oneOf of consts.
The output is committed as backend/crates/coaching-input/schema/coaching-input.schema.json (renamed with v2, ADR 0085). committed_schema_is_current fails when it is stale. To regenerate it, run COACHING_SCHEMA_WRITE=1 cargo test -p coaching-input --test parity committed_schema_is_current in rust-dev.
Parity with the TS schema
Section titled “Parity with the TS schema”backend/fixtures/coaching-input/ts-schema.json is z.toJSONSchema(CoachingInput, {target: "draft-2020-12", unrepresentable: "any"}), exported once from the m3 worktree. SOURCE records the commit, the command, the date and the sha256. To refresh it, rerun that command against a newer m3 commit, update SOURCE, and run cargo test -p coaching-input. If the TS contract changed shape, the parity test fails until the Rust types follow. valid-sample.json is a byte-for-byte copy of M3’s own coaching-input.b2-rapid.json fixture, which M3’s tests assert is valid.
tests/parity.rs checks the following:
sample_validates_against_ts_schemaandsample_validates_against_rust_schemarun jsonschema 0.61.2 with format validation on. The inputs are the sample andto_json()of an input built in Rust with everyOptionSome, and again with everyOptionNone.ts_schema_rejects_what_rust_rejects: an unknown key, a missing nullable key, a score with two keys or with none, and another input version are rejected by the TS schema, the Rust schema and serde alike. Both schemas must report the error at the expected instance path.schemars_schema_matches_ts_schema_shapewalks both schemas from the root by property path. It resolves$refs, ignores$defsnames, and treats{"type": [T, "null"]}andanyOf [T, null]as the same, andoneOfandanyOfas the same.- For every object it asserts the same property names,
requiredequal to all properties, andadditionalProperties: false. - It asserts the same value set for every enum or const, and the same type everywhere.
- For
minLength,maxLength,minItems,maxItems,minimum,maximum,exclusiveMinimum,exclusiveMaximum,patternandformat, the check runs both ways: a bound present on one side must be present and equal on the other. - Keywords beside a
$refcount as part of its target, and a value that conflicts with the target is a difference. Keywords beside a union are compared too, including those beside a single nullable member. - Every keyword on either side must be one the walker compares or a known annotation (
$schema,$defs,title,description). A new keyword such asuniqueItems,allOf,not,prefixItemsordefaultfails the test. - A guard asserts that the walk reached at least the 41 object sites and 17 enum sites of the contract.
walker_reports_unknown_keywords_and_sibling_differenceschecks these rules on small hand-made schemas.
- For every object it asserts the same property names,
Refinements and bounds in validate()
Section titled “Refinements and bounds in validate()”JSON Schema cannot express the zod refinements. validate() checks them with zod’s paths and messages:
- the FEN is valid, and its side to move agrees with the ply parity (odd =
w; the second FEN field is read as zod reads it). Validity takes two checks. The first is a structural check: six fields and eight ranks of pieces and digits 1-8 that fill eight squares with no two digits in a row, as chess.js requires (Position::from_fenalone accepts44). Its whitespace rule is deliberately stricter than chess.js/zod (which accept runs of whitespace): fields must be separated by single spaces, with no leading, trailing or other whitespace. That is the safe direction, and the builder never emits such FENs. The second ischess_core::board::Position::from_fen; - the metric
value,low,highandbandMedianlie within the unit range, andlow <= high; intervalLow <= posteriorRate <= intervalHigh, andevents <= opportunities;- ranks are unique (the issue is at the second occurrence);
areaScoreshas each area exactly once;onsetFrom <= onsetDate <= onsetTo,analysedGames <= importedGames, andwindowStart <= windowEnd.
validate() also re-checks every schema bound, so a Rust value that passes it also passes zod:
- string lengths count Unicode code points (
chars().count()). zod 4.6.7 measuresmin/maxwithutil.codePointLength, which counts a surrogate pair once, and JSON Schema’smaxLengthcounts code points too. So 120 emoji fit a 120-character label; - array sizes, number ranges, the UCI and weakness-id patterns and the UUID pattern;
- dates and datetimes must have a four-digit year;
- every
f64must be finite, because serde_json would write NaN asnull.
It walks the whole value and returns every issue, not only the first. Two gaps remain, both bounded. First, the structural pre-check plus Position::from_fen (which reproduces chess.js 1.4.0, ADR 0037) stand in for chess.js’s validateFen; they are not that function itself. Second, serde reads JSON 48.0 into an integer field as an error, where zod accepts it. R2 only writes integers there, so this matters only for hand-made input.
What the gate covers: to_json() output, not foreign bytes
Section titled “What the gate covers: to_json() output, not foreign bytes”serde plus validate() equals zod only for what to_json() writes. Deserialisation is more lenient than zod in places that to_json() never produces:
common::js_time::isoparses any RFC 3339 timestamp, including other offsets (+02:00), where zod requiresZ;uuid::Uuidparses the simple, braced and URN forms, where zod requires the hyphenated form.
The typed value forgets which form was read, and validate() checks the typed value, so it cannot see these differences. to_json() always writes the canonical forms. So R3, or anything else that passes a CoachingInput on to zod, must forward to_json() output of a validated value. It must never forward raw bytes it received from elsewhere.
Rulings carried by this contract (global constraints R-1 to R-8)
Section titled “Rulings carried by this contract (global constraints R-1 to R-8)”- R-1
Strengthis exactly{area, label, metricKey, exemplars}. TS M2’s extra fields stay in the internalStrengthCandidate. - R-2 Contract metrics are catalogue rows with an area and a
contract_unit. Signed or unit-less rows stay internal.value,lowandhighare clamped to the unit range, and rows with no value are omitted.validate_rejects_value_outside_unit_rangepins the range rule. - R-3
weaknessescontains only estimates withreason = ok, becausebandMedianandbandPercentileare non-null in the contract. - R-4 The band comes from the latest rating, else from the mean opponent rating of the last 20 games, else
B2.bandis never null. - R-5 An empty window has
windowStart = windowEnd, whichvalidateaccepts. - R-6 The builder (Task 34) truncates every list to
LIMITSby its own order and runsvalidate()before returning. A failure is a bug (BuildError::Contract(Vec<Issue>)). - R-7
gameIdis the platform id (at most 64 chars).lineKeyis"{color}:{slug}", cut to fit 64 chars with a hash suffix. - R-8 Scores are White-POV
{cp}/{mate}.avgEvalAtOpeningEndis the rounded mean White-POV cp, with mate counted as ±1000.
Consequences
Section titled “Consequences”- R3 and R2 share one Rust definition of the contract. Shape drift between Rust and the TS source fails a test, as long as the TS export is refreshed when M3 changes the schema.
- serde_json writes an
f64such as48as48.0. That is the same JSON number to zod and JSON Schema, but not byte-identical to JS output. - The committed schema is for consumers outside Rust (and for review). It is generated, never hand-edited.