fix(807): remove the collision class instead of asserting it away

Round 7 reviewed the assertion added two commits ago and found it covered 1 of
the 5 nodes where the collision fires — the four it missed being the ones that
matter, since they are where the walk actually qualifies a name. I had already
widened it to walk the whole tree, but the reviewer's recommendation is better
than either version and is taken here: restructure so there is nothing to assert.

A nested inline object lives in its OWN namespace. The defect was qualifying its
members as `parent.child` BEFORE subtracting `required`, which merges the two
namespaces and lets a literal `a.b` member mask a nested `a` -> `b` one. Now
`_optional_of` subtracts inside each namespace and qualifies only the survivors,
so the sets are never mixed. No separator to defend, no assumption to assert, and
`NESTED_SEPARATOR` and its whole-tree checker are gone.

Verified at all five sites — top level of a named schema, one level down, inside
an `allOf` arm, under `items`, and inside an inline request body — every one now
surfaces (`a.b`, `outer.a.b`, `a.b`, `a.b`, `a.b`); four were masked before.

The reviewer flagged a trap in this fix and it is real: keeping a 2-tuple
compatibility shim (`return properties | nested, required`) re-creates the mask
at the merge boundary while the suite stays green. So `_resolve` returns three
sets and every caller changed. There is now a case that reddens exactly that
shim.

Residual, stated rather than hidden: a literal `a.b` and a nested `a` -> `b` that
are BOTH optional conflate into one reported string. That is a diagnostic
ambiguity, not a miss — the schema still enters the population and still forces a
disposition.

Also from round 7: `prefixItems` was the one keyword whose `required` handling no
case pinned (its only case carried none), so discarding it stayed green; it has a
case now. And the assumptions docstring is back to describing two assertions
rather than three, which the separator removal resolved on its own.

REBASED onto ad31a0285 (#825). That change edits the same guard-inventory summary
line this branch does, and the merged truth is neither side's number: 38 guards /
20 proof files / 16 with a mutation proof. Resolved by reading it off
`test_the_summary_counts_match_the_table` rather than by picking a side.

One local trap worth recording: a stale `scripts/**/__pycache__` made pytest
report this commit's new case failing while the source could not produce that
result — `_optional_of` returned the right value when called directly. Clearing
the cache resolved it. I nearly "fixed" correct code on the strength of a red.

946 passed 2 skipped on the new base, ruff check 0, ruff format 0, typecheck 0,
eslint 0, 1200/1200 web, build 0, catalog clean, doc-narrative 0 new.
This commit is contained in:
2026-08-23 01:36:32 +02:00
parent 161c788a70
commit 424ffb573b
2 changed files with 75 additions and 92 deletions
+74 -91
View File
@@ -26,7 +26,7 @@ write — is DERIVED here, every run, from `ErsatzTV/wwwroot/openapi/v1.json`. T
are the SCOPE: a reviewed policy choice per schema, legitimately hand-written, and each one is
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`
down what should happen about it — that is the reach, bounded by what `_resolve`
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
@@ -50,13 +50,6 @@ import pytest
REPO_ROOT = Path(__file__).resolve().parents[2]
# Separator for a nested inline object's members (`logo.contentType`). A JSON property name may
# legally contain any character, so a literal member called `logo.contentType` would COLLIDE with
# the nested one — and the collision is silent in the miss direction: if the literal is `required`,
# the nested optional member is masked and disappears from the population (measured 2026-08-23).
# `test_the_walks_ASSUMPTIONS_about_the_document_still_hold` asserts no property name contains this,
# so the day one does the guard fails loudly instead of quietly shrinking.
NESTED_SEPARATOR = "."
OPENAPI = REPO_ROOT / "ErsatzTV" / "wwwroot" / "openapi" / "v1.json"
# --- the closed disposition vocabulary -------------------------------------------------------
@@ -200,36 +193,37 @@ def _request_reachable(doc: dict) -> set[str]:
return seen
def _property_names_containing_the_separator(node: object, trail: str = "") -> set[str]:
"""Every property name anywhere in the document that contains `NESTED_SEPARATOR`.
def _optional_of(schema: object) -> set[str]:
"""The members of `schema` a client may omit, nested inline objects included.
Walks the WHOLE parsed tree rather than the top-level `properties` of each named schema. The
first version of this check did the latter and missed the cases that matter most: a dotted name
on a NESTED inline object, or inside an INLINE request body — neither of which is a top-level
member of a component schema, and both of which the resolver does qualify. A check that does
not walk the same tree as the thing it is checking is the recurring shape on this issue, and it
recurred here inside the fix for it (verified 2026-08-23 by planting each shape).
This is the function to call. `_resolve` below is its recursive half and returns three sets;
the split matters and is the fix for a real defect, so it is stated here rather than in a
comment further down.
A nested inline object lives in its OWN namespace. Qualifying its members as `parent.child`
BEFORE subtracting `required` merges the two namespaces, and a literal member named
`parent.child` then collides with the nested one — masking it entirely when the literal is
required, so a droppable member vanishes from the population with nothing failing (measured
2026-08-23). Subtracting inside each namespace first and qualifying only the survivors means
the two sets are never mixed, so the collision cannot arise and there is no separator to
defend. An earlier version instead ASSERTED that no property name contains a dot, which is a
guard where a restructure was available.
Residual, stated because it is real: if a literal `a.b` and a nested `a` -> `b` are BOTH
optional they conflate into one reported string. That is a diagnostic ambiguity, not a miss —
the schema still enters the population and still forces a disposition.
"""
found: set[str] = set()
if isinstance(node, dict):
for member, value in (node.get("properties") or {}).items():
if NESTED_SEPARATOR in member:
found.add(f"{trail}{member}" if trail else member)
found |= _property_names_containing_the_separator(value, f"{trail}{member}.")
for key, value in node.items():
if key != "properties":
found |= _property_names_containing_the_separator(value, trail)
elif isinstance(node, list):
for value in node:
found |= _property_names_containing_the_separator(value, trail)
return found
properties, required, nested_optional = _resolve(schema)
return (properties - required) | nested_optional
def _properties_and_required(schema: object) -> tuple[set[str], set[str]]:
"""Resolve one schema node to (properties, required), following composition RECURSIVELY.
def _resolve(schema: object) -> tuple[set[str], set[str], set[str]]:
"""(properties, required, already-resolved nested optional members) for one schema node.
Two things here are easy to get wrong and both were, in the first version of the inline walk
(measured 2026-08-22 by probing constructed schemas rather than by reading):
The third set is carried through every composition site rather than merged into the first two,
for the namespace reason in `_optional_of`. Do NOT collapse this back to a 2-tuple to spare the
callers: folding `nested_optional` into `properties` re-creates the mask at the merge boundary
and the whole suite stays green while it does.
NESTING. Handling `allOf` one level deep misses an `allOf` inside an `allOf` — a property there
reported as no properties at all. Composition nests, so the resolution has to recurse.
@@ -246,50 +240,46 @@ def _properties_and_required(schema: object) -> tuple[set[str], set[str]]:
requires it — the `required` sets INTERSECT. Unioning them instead (the first version) marks a
member required because one arm requires it, hiding the arm that lets a client omit it. That is
the drop this whole guard exists to catch, so getting it backwards is not a detail.
No cycle guard, deliberately. This resolver never follows `$ref`, so the only way to recurse
forever is a schema that contains ITSELF by object identity — which `json.load` cannot produce,
since JSON has no back-references. Verified 2026-08-23: a hand-built self-referential dict does
raise `RecursionError`, a LOUD red rather than a silent wrong answer. The `$ref` cycle a real
document CAN express is handled by `_request_reachable`'s `seen` set, also verified.
"""
if not isinstance(schema, dict):
return set(), set()
# No cycle guard, deliberately. This resolver never follows `$ref` (see below), so the only way
# to recurse forever is a schema that contains ITSELF by object identity — which `json.load`
# cannot produce, since JSON has no back-references. Verified 2026-08-23: a hand-built
# self-referential dict does raise `RecursionError`, and that is a LOUD red rather than a silent
# wrong answer, so it needs no defence. The `$ref` cycle that a real document CAN express is
# handled by `_request_reachable`'s `seen` set, also verified: a mutual A->B->A cycle resolves
# to {A, B} and terminates.
return set(), set(), set()
properties = set(schema.get("properties") or {})
required = set(schema.get("required") or [])
nested_optional: set[str] = set()
# 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.
# `required` really does emit `?:` and really is droppable. Resolved in its own namespace and
# qualified afterwards — see `_optional_of`.
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}{NESTED_SEPARATOR}{child}" for child in nested_properties}
required |= {f"{name}{NESTED_SEPARATOR}{child}" for child in nested_required}
nested_optional |= {f"{name}.{child}" for child in _optional_of(value)}
# CONJUNCTIVE: every `allOf` arm applies, so both sets union.
for branch in schema.get("allOf") or []:
branch_properties, branch_required = _properties_and_required(branch)
branch_properties, branch_required, branch_nested = _resolve(branch)
properties |= branch_properties
required |= branch_required
nested_optional |= branch_nested
# 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
# That is the polarity error this function warns about above, 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] = []
@@ -298,20 +288,21 @@ def _properties_and_required(schema: object) -> tuple[set[str], set[str]]:
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)
branch_properties, _, branch_nested = _resolve(branch)
properties |= branch_properties
nested_optional |= branch_nested
# 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
# correct required set is the intersection within each keyword, unioned across them. Merging
# the two lists first intersects across keywords and under-reports required — safe-direction
# (it over-reports droppable) but wrong, and untested until it was written down here.
# the two lists first intersects across keywords and under-reports required.
for keyword in ("oneOf", "anyOf"):
alternatives = schema.get(keyword) or []
shared_required: set[str] | None = None
for branch in alternatives:
branch_properties, branch_required = _properties_and_required(branch)
branch_properties, branch_required, branch_nested = _resolve(branch)
properties |= branch_properties
nested_optional |= branch_nested
shared_required = branch_required if shared_required is None else (shared_required & branch_required)
if shared_required:
required |= shared_required
@@ -319,28 +310,24 @@ def _properties_and_required(schema: object) -> tuple[set[str], set[str]]:
# 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`
# is the 2020-12 spelling of that tuple. Handling only the dict shape skipped the other two
# silently, which is the same "it does not appear in today's document" reasoning that has been
# wrong repeatedly on this issue.
# is the 2020-12 spelling of that tuple.
for keyword in ("items", "prefixItems"):
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)
branch_properties, branch_required, branch_nested = _resolve(branch)
properties |= branch_properties
required |= branch_required
nested_optional |= branch_nested
return properties, required
return properties, required, nested_optional
def _optional_members(doc: dict) -> dict[str, list[str]]:
"""Schema -> its properties that sit OUTSIDE `required`, i.e. the ones that emit `?:`."""
out: dict[str, list[str]] = {}
for name, schema in doc["components"]["schemas"].items():
properties, required = _properties_and_required(schema)
if not properties:
continue
optional = sorted(properties - required)
optional = sorted(_optional_of(schema))
if optional:
out[name] = optional
return out
@@ -358,7 +345,7 @@ def _inline_body_members(doc: dict) -> dict[str, list[str]]:
Keyed by `"<VERB> <path> (<media type> inline body)"` rather than by a schema name, because there is no name
to use — which is exactly why the component-schema walk cannot see it.
Composition is resolved by `_properties_and_required`, which recurses and treats `allOf` as
Composition is resolved by `_optional_of`/`_resolve`, which recurse and treat `allOf` as
conjunction and `oneOf`/`anyOf` as alternatives — this body splits its properties across `allOf`
arms and would otherwise report none.
"""
@@ -370,14 +357,13 @@ 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
# Belt-and-braces, not load-bearing: `_optional_of` returns an 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)
optional = sorted(_optional_of(schema))
if optional:
# Keyed by MEDIA TYPE as well as verb and path. An operation may declare more
# than one inline body (a second `[Consumes]` is all it takes), and keying on
@@ -434,13 +420,6 @@ def test_the_walks_ASSUMPTIONS_about_the_document_still_hold() -> None:
2. Every `$ref` in the document points into `#/components/schemas/`. `_schema_refs` matches on
that prefix, so a ref into any other bucket is invisible to it.
3. No property name ANYWHERE in the document contains `NESTED_SEPARATOR`. The walk qualifies a
nested inline object's members as `parent.child`, so a literal member of that name would
collide — and the collision is silent in the MISS direction, masking the nested member when
the literal is required. "Anywhere" is load-bearing: the first version of this clause checked
only the top-level members of named schemas, so it could not see a dotted name on a nested
inline object or inside an inline body, which are exactly the places the resolver qualifies.
Both are cheap to assert and neither is asserted anywhere else, so a change in the emitter
would otherwise shrink this guard's population without failing anything.
@@ -458,14 +437,6 @@ def test_the_walks_ASSUMPTIONS_about_the_document_still_hold() -> None:
"so schemas behind a shared request body are now INVISIBLE to this guard. Teach the walk "
"to resolve that bucket before deleting this assertion."
)
offenders = sorted(_property_names_containing_the_separator(doc))
assert not offenders, (
f"these property names contain {NESTED_SEPARATOR!r}, which this guard uses to qualify a "
f"nested inline object's members: {offenders}. A literal member and a nested one would "
"collide, and the collision MASKS the nested member when the literal is required. Change "
"NESTED_SEPARATOR to something the document does not use before deleting this assertion."
)
ref_buckets = set(re.findall(r'"#/components/([^/"]+)/', json.dumps(doc)))
assert ref_buckets <= {"schemas"}, (
f"$refs now point into {sorted(ref_buckets - {'schemas'})} as well as schemas; "
@@ -629,6 +600,19 @@ def test_every_droppable_request_schema_has_a_stated_disposition() -> None:
},
["nested.b"],
),
(
"a REQUIRED literal `a.b` cannot mask a nested `a` -> `b` — the namespaces never merge",
{"properties": {"a.b": {}, "a": {"properties": {"b": {}}}}, "required": ["a.b", "a"]},
["a.b"],
),
(
"`prefixItems` positions are conjunctive, so a `required` there really does bind",
{
"type": "array",
"prefixItems": [{"properties": {"pReq": {}, "pOpt": {}}, "required": ["pReq"]}],
},
["pOpt"],
),
(
"a dotted nested member cannot be confused with a top-level member of the same name",
{
@@ -670,7 +654,7 @@ def test_every_droppable_request_schema_has_a_stated_disposition() -> None:
],
)
def test_composition_is_resolved_the_way_JSON_Schema_means_it(case: str, schema: dict, expected: list[str]) -> None:
"""Pin `_properties_and_required` against constructed schemas, not against today's document.
"""Pin `_optional_of`/`_resolve` against constructed schemas, not against today's document.
The document exercises exactly one shape (a two-arm `allOf` in the artwork upload body), so
every other branch of this resolver would otherwise be unexercised prose. Both of the first
@@ -678,14 +662,13 @@ def test_composition_is_resolved_the_way_JSON_Schema_means_it(case: str, schema:
whose `required` it unioned instead of intersecting — which marked a member required because
ONE arm required it, hiding the arm that lets a client drop it.
"""
properties, required = _properties_and_required(schema)
assert sorted(properties - required) == expected, case
assert sorted(_optional_of(schema)) == expected, case
def test_a_ref_ARM_is_covered_by_the_component_walk_not_by_this_one() -> None:
"""The two walks COMPOSE; neither alone covers an inline body with a `$ref` arm.
`_properties_and_required` does not resolve `$ref`, so an `allOf` arm that is a `$ref`
`_resolve` does not resolve `$ref`, so an `allOf` arm that is a `$ref`
contributes nothing to the inline key. That looks like a gap and is not: the referenced schema
is a named component, so it is seeded by `_request_reachable` and walked by `_optional_members`,
and its optional members surface under their own key. Pinned here because the obvious "fix" —