fix(807): then/else are ALTERNATIVES — stop unioning their required

Round 6 returned BLOCKED on a polarity error I committed in the block that fixed
the previous polarity error.

`then` and `else` were in the conjunctive list with `allOf`, so their `required`
unioned. They are MUTUALLY EXCLUSIVE: a member required only under `then` is
omittable whenever `if` does not match. The guard reported it as required — the
silent-miss direction, which is the one this file exists to catch. Twelve lines
below the defect the same function warns, about `oneOf`, that getting exactly
this backwards "is not a detail".

The comment made it worse, not better: it asserted the semantics had been
considered, which is what stops the next reader checking. Its reasoning was right
for properties (union them — a client may send them) and silently inverted for
`required`.

`if`, `then`, `else` and `dependentSchemas` now share one loop with one rule:
collect properties, discard `required`. They discard for three different reasons
— a branch selector, a branch that may not be taken, a trigger key that may be
absent — but the rule is identical, so one loop beats three arguments.

Why fix a keyword the emitter has never produced: this head added `prefixItems`
and `dependentSchemas` handling on the stated grounds that "it does not appear in
today's document" has been wrong repeatedly here. That standard cannot apply to
three keywords and not the fourth — and a wrongly-handled keyword is worse than
an unhandled one, because it ships a comment claiming it was thought about.

The real lesson is narrower than "handle more keywords": for EVERY keyword whose
`required` is unioned or discarded, ship a case that puts a `required` under it.
None of the 27 cases did, which is why both this and the unpinned `if` discard
were invisible. Three such cases added.

Also closes the last blind spot with a mechanism behind it: an inline object
under `properties`. The generator recurses into it and emits `"b"?:`, so it is
genuinely droppable; the resolver returned nothing. Now reported with a DOTTED
path, so `logo.contentType` cannot be mistaken for a top-level `contentType` in a
MISSING diagnostic. `patternProperties` is correctly unhandled (no fixed members,
like `additionalProperties`) and now has a case saying so rather than being
silently absent.

The docstring now names the resolver's exact reach instead of gesturing at it,
and the `$ref` skip in the inline walk is marked as belt-and-braces rather than
reading as protective — deleting it changes no result.

Population unchanged at 9, set equality holds. 33 resolver cases, 908 passed 2
skipped, ruff 0/0, typecheck 0, eslint 0, 1200/1200 web, build 0, catalog clean.
This commit is contained in:
2026-08-23 01:36:32 +02:00
parent 4ce590662a
commit 4d7fd26a3e
3 changed files with 102 additions and 30 deletions
@@ -164,9 +164,13 @@ That is the rule, not a claim about how much of the tree currently follows it. N
second half — #820 — so any sentence here asserting present coverage would be falsifiable by one
`tsc` run and would go stale on the next screen anyone adds. Two wrappers annotated under #807
initially shipped with unannotated construction sites for exactly that reason. To find out what is
actually annotated, read the code; do not read a count here. That direction fires only on a fresh literal in a contextually typed position,
and a literal returned from a generic `.map` callback is not one, because `map<U>` infers `U` from
the callback rather than from the target element type. Measured on the pre-#807 tree by injecting a
actually annotated, read the code; do not read a count here.
**Why the second half of the rule is the one that gets skipped.** The wrapper annotation catches a
MISSING member anywhere. The PHANTOM direction — a field the schema does not accept — relies on
TypeScript's excess-property check, and that fires only on a fresh object literal in a contextually
typed position. A literal returned from a generic `.map` callback is not one, because `map<U>`
infers `U` from the callback rather than from the target element type. Measured on the pre-#807 tree by injecting a
phantom property at each construction site then present: some rejected it and some accepted it,
and among those that accepted, three contained neither a spread nor an inferred local — so "it has
no spread" is not a reason to think a site is checked. No denominator is given: what counts as a
+1 -1
View File
@@ -216,8 +216,8 @@ recorded as unexamined rather than as cleared.
| `scripts/tests/test_prepush_unsets_git_env.py` | the `script-tests` job | PROOF | NONE | — |
| `scripts/tests/test_pr_changed_files.py` | the `script-tests` job | PROOF | NONE | — |
| `scripts/tests/test_prepush_rebase_check_tag_exemption.py` | the `script-tests` job | PROOF | NONE | — |
| `scripts/tests/test_prove_fix.py` | the `script-tests` job | PROOF | NONE | — |
| `scripts/tests/test_optional_request_members.py` | the `script-tests` job, on an OpenAPI request schema that can silently drop a member with no stated disposition | GUARD | MUTATION | `test_optional_request_members.py::test_every_droppable_request_schema_has_a_stated_disposition` |
| `scripts/tests/test_prove_fix.py` | the `script-tests` job | PROOF | NONE | — |
| `scripts/tests/test_remote_state_inventory.py` | the `script-tests` job, on an executable that talks to a remote service with no row in `docs/remote-state-inventory.md` | GUARD | MUTATION | `test_remote_state_inventory.py::test_every_in_scope_file_has_a_row_and_every_row_names_a_real_file` |
| `scripts/tests/test_worktree_ownership_guard.py` | the `script-tests` job | PROOF | NONE | — |
+94 -26
View File
@@ -27,7 +27,11 @@ are the SCOPE: a reviewed policy choice per schema, legitimately hand-written, a
FORCED to exist by the set-equality assertion. A new optional member in a named component schema
reachable from a request body, or in an inline request body, fails this test until someone writes
down what should happen about it — that is the reach, bounded by what `_properties_and_required`
resolves. An earlier draft said "anywhere in the request graph"; inline bodies were invisible at
resolves. That resolver walks `allOf`, `oneOf`, `anyOf`, `if`/`then`/`else`, `dependentSchemas`,
`items`/`prefixItems` and inline objects under `properties`, and deliberately contributes nothing
for `additionalProperties`/`patternProperties` (which name no fixed members) — each pinned by a
case in `test_composition_is_resolved_the_way_JSON_Schema_means_it`. It does NOT follow `$ref`;
that is the component walk's job. An earlier draft said "anywhere in the request graph"; inline bodies were invisible at
the time, so the universal was false the day it was written.
Set equality is asserted in BOTH directions and reported separately, because they are opposite
@@ -224,16 +228,45 @@ def _properties_and_required(schema: object) -> tuple[set[str], set[str]]:
properties = set(schema.get("properties") or {})
required = set(schema.get("required") or [])
# CONJUNCTIVE keywords: every arm applies, so both sets union. `then`/`else` are conjunctive
# with whatever else the node says because a member declared there is reachable on some branch,
# and this walk asks "can a client omit it", not "which branch is taken".
for keyword in ("allOf", "then", "else"):
# A property may itself be an INLINE OBJECT rather than a `$ref`, and the generator recurses
# into it (`objectTypeFromSchema` -> `typeFromSchema`), so a member outside that nested
# `required` really does emit `?:` and really is droppable. Reported with a DOTTED path so it
# cannot be confused with a top-level member of the same name — `logo.contentType` is a
# different member from `contentType`, and a MISSING diagnostic naming the wrong one would send
# the reader to the wrong place.
for name, value in (schema.get("properties") or {}).items():
if not isinstance(value, dict) or "$ref" in value:
continue
nested_properties, nested_required = _properties_and_required(value)
properties |= {f"{name}.{child}" for child in nested_properties}
required |= {f"{name}.{child}" for child in nested_required}
# CONJUNCTIVE: every `allOf` arm applies, so both sets union.
for branch in schema.get("allOf") or []:
branch_properties, branch_required = _properties_and_required(branch)
properties |= branch_properties
required |= branch_required
# CONDITIONAL keywords — `if`, `then`, `else`, `dependentSchemas`. All four are treated the same
# way: collect their properties (a client may send them) and DISCARD their `required` (it binds
# only on a branch that may not be taken, so the member is omittable).
#
# An earlier version put `then`/`else` in the conjunctive list above, unioning their `required`.
# That is the polarity error this function warns about twelve lines below, committed in the same
# block: `then` and `else` are MUTUALLY EXCLUSIVE, so a member required only under `then` is
# omittable whenever `if` does not match, and the guard reported it as required — the
# silent-miss direction, which is the one this whole file exists to catch. `if`'s `required` is
# discarded for a different reason (it selects a branch rather than obliging anyone), and
# `dependentSchemas` for a third (it binds only when its trigger key is present), but the
# resulting rule is identical, so they share one loop rather than three arguments.
conditional: list[object] = []
for keyword in ("if", "then", "else"):
value = schema.get(keyword)
branches = value if isinstance(value, list) else ([value] if isinstance(value, dict) else [])
for branch in branches:
branch_properties, branch_required = _properties_and_required(branch)
properties |= branch_properties
required |= branch_required
conditional.extend(value if isinstance(value, list) else ([value] if isinstance(value, dict) else []))
conditional.extend((schema.get("dependentSchemas") or {}).values())
for branch in conditional:
branch_properties, _ = _properties_and_required(branch)
properties |= branch_properties
# DISJUNCTIVE keywords, handled SEPARATELY rather than concatenated: `oneOf` and `anyOf` are
# conjunctive WITH EACH OTHER (a body satisfying both must satisfy one arm of each), so the
@@ -250,22 +283,6 @@ def _properties_and_required(schema: object) -> tuple[set[str], set[str]]:
if shared_required:
required |= shared_required
# `if` is a CONDITION, not a constraint: its `required` decides which branch applies rather
# than obliging the client to send anything, so its properties are collected (a client may send
# them) and its `required` is deliberately discarded. Treating that `required` as required
# would mark a member non-droppable on the strength of a branch selector.
condition = schema.get("if")
if isinstance(condition, dict):
condition_properties, _ = _properties_and_required(condition)
properties |= condition_properties
# `dependentSchemas` applies only when its trigger key is present, so its properties are
# members a client MAY send while its `required` is conditional — collected and discarded
# respectively, same treatment as `if`.
for branch in (schema.get("dependentSchemas") or {}).values():
branch_properties, _ = _properties_and_required(branch)
properties |= branch_properties
# An inline body may be an ARRAY of inline objects; the members live on `items`, and a member
# droppable there is droppable in the request. `items` is a SCHEMA in OpenAPI 3.1 / JSON Schema
# 2020-12 and may be a LIST in the 3.0 tuple form, so both shapes are walked — and `prefixItems`
@@ -320,6 +337,11 @@ def _inline_body_members(doc: dict) -> dict[str, list[str]]:
for content_type, media in (operation["requestBody"].get("content") or {}).items():
schema = media.get("schema") or {}
if "$ref" in schema:
# Belt-and-braces, not load-bearing: `_properties_and_required` returns empty
# sets for a bare `$ref` node anyway, so deleting this line changes no result
# today. It stays because a body that names a component schema is that schema's
# business — `_optional_members` already covers it — and skipping it here keeps
# that division explicit rather than accidental.
continue
properties, required = _properties_and_required(schema)
optional = sorted(properties - required)
@@ -526,6 +548,52 @@ def test_every_droppable_request_schema_has_a_stated_disposition() -> None:
{"dependentSchemas": {"trigger": {"properties": {"depOpt": {}}, "required": ["depOpt"]}}},
["depOpt"],
),
(
"a `required` under `then` does NOT make a member required — the branch may not be taken",
{
"if": {"properties": {"k": {}}, "required": ["k"]},
"then": {"properties": {"m": {}}, "required": ["m"]},
},
["k", "m"],
),
(
"a `required` under `else` does not either, and `then`/`else` are mutually exclusive",
{
"if": {"properties": {"k": {}}},
"then": {"properties": {"m": {}}, "required": ["m"]},
"else": {"properties": {"m": {}}},
},
["k", "m"],
),
(
"a `required` under `if` selects a branch, it does not oblige the client",
{"if": {"properties": {"k": {}}, "required": ["k"]}, "then": {"properties": {"m": {}}}},
["k", "m"],
),
(
"an INLINE OBJECT under `properties` is recursed into, reported with a dotted path",
{
"properties": {
"top": {},
"nested": {"properties": {"a": {}, "b": {}}, "required": ["a"]},
},
"required": ["top", "nested"],
},
["nested.b"],
),
(
"a dotted nested member cannot be confused with a top-level member of the same name",
{
"properties": {"b": {}, "nested": {"properties": {"b": {}}}},
"required": ["b", "nested"],
},
["nested.b"],
),
(
"`patternProperties` names no FIXED members, so it contributes none — same as additionalProperties",
{"properties": {"named": {}}, "patternProperties": {"^x-": {"properties": {"notAMember": {}}}}},
["named"],
),
(
"`additionalProperties` names no members, so it contributes none",
{"properties": {"named": {}}, "additionalProperties": {"properties": {"notAMember": {}}}},