Skip to content

Fix discriminator state leaking between alternative branches - #1379

Merged
stevehu merged 1 commit into
masterfrom
fix/issue-1378-discriminator-scope
Nov 7, 2026
Merged

stevehu merged 1 commit into
masterfrom
fix/issue-1378-discriminator-scope

Conversation

@stevehu

@stevehu stevehu commented Nov 7, 2026

Copy link
Copy Markdown
Contributor

Fixes #1378. Nested OpenAPI 3.0 discriminators in sibling alternatives could throw SchemaException when the same value mapped to different schemas. Snapshot discriminator locations before each oneOf/anyOf branch and discard newly recorded descendant state afterward, in both validation and walk loops. Preserve same-location and pre-existing state; allOf and DiscriminatorValidator remain unchanged.

Regression coverage uses the issue document and all four instances with outer oneOf and anyOf. Both variants reproduced the exception before the fix. Full offline suite passed: 10,595 tests, 0 failures/errors, 30 skipped (mvn -o -q test -Dversion.maven-surefire=3.6.0; pinned 3.6.1 is unavailable offline). Existing Issue1270 and same-location discriminator guards pass. GitNexus impact and compare-to-master detection reported LOW risk.

Known limitation: alternative branches defining discriminators at the outer validator's own instance location can still throw; this remains undefined behavior.

@stevehu

stevehu commented Nov 7, 2026

Copy link
Copy Markdown
Contributor Author

Review of head d6a3bc8. The fix matches the approach in the issue discussion, but it introduces a performance regression, so I would not merge it as is. I built the branch and measured it. Ranked most-severe first.

1. Quadratic cost on arrays of discriminated items (OneOfValidator.java:91, AnyOfValidator.java:79)
Every branch copies the whole discriminator map's key set (new HashSet<>(keySet())) and then removeIf scans the whole map. Entries at each element's own location are retained, so an array of N items does O(N) work per element. With OpenAPI 3.0, items.oneOf [A,B] plus discriminator, alternating items, warmed:

N master this PR
1,000 3 ms 20 ms
4,000 5 ms 212 ms
16,000 18 ms 2.9 s
64,000 70 ms 54.5 s

A payload of a few thousand polymorphic items becomes about 70x slower. Suggestion: keep an append-only creation log in ExecutionContext, take mark = log.size() before a branch, and afterwards inspect only log[mark..], removing the descendants of the validator's location from the map and the log. The cost is then proportional to what the branch recorded.

2. The non-validating walk loops do nothing (OneOfValidator.java:266, AnyOfValidator.java:205)
Validator.walk calls validate only when shouldValidateSchema is true, so these loops never record discriminator state. The snapshot and discard there cannot discard anything, and no test covers them. Leave those two loops as they were.

3. API shape (ExecutionContext.java:206)
discardDiscriminatorsBelow is a new public method that only works with a matching snapshot, and the snapshot/discard pair is copied eight times across four loops. A package-private scope (beginAlternative / endAlternative) would hide the representation and fix item 1 in one place.

4. Test gaps (Issue1378Test.java:38)
There is no scale test, no differing-propertyName case (the "redefining the discriminator property" throw), no same-location guard, and no walk case. The invalid instance asserts only that the error list is non-empty. replaceFirst("oneOf", keyword) depends on Container being the first oneOf in the file.

5. CHANGELOG (CHANGELOG.md:9)
The entry is a bare bullet under ## [Unreleased]. Put it in a ### Fixed subsection.

The same points apply to #1380, which has identical code.

@stevehu

stevehu commented Nov 7, 2026

Copy link
Copy Markdown
Contributor Author

Review of the uncommitted follow-up on fix/issue-1378-discriminator-scope (the branch head is still d6a3bc8; I reviewed a copy of the author's working tree, so line numbers may shift once it is pushed). The five earlier findings are addressed. The branch insertion journal fixes the performance regression: with arrays of 64,000 discriminated items nested inside an outer oneOf, the previous head took 117 s, this tree takes 73 ms, and master takes 76 ms. The discriminator tests (Issue1378Test, DiscriminatorValidatorTest, OneOf/AnyOfValidatorTest, OpenApi31Test, OpenAPI30JsonSchemaTest, Issue1270Test, Issue1325Test, JsonWalkTest) and the JSON Schema Test Suite pass; I did not run the full Maven suite. Four minor points remain.

1. The journal hooks only HashMap.put (ExecutionContext.java:165)
In a probe, inside evaluateDiscriminatorBranch, put leaves 0 entries after the branch, but putIfAbsent, computeIfAbsent, putAll and merge each leave 1. DiscriminatorValidator uses put today, but the map is public API, and a refactor to computeIfAbsent would bring #1378 back without a failing test. An explicit ExecutionContext.putDiscriminator(path, state) that journals, with getDiscriminatorMapping() returning an unmodifiable view, makes it structural. The anonymous HashMap subclass also needs the journal fields declared above it.

2. OpenAPI 3.1 is affected too (CHANGELOG.md:11)
With Dialects.getOpenApi31() and "openapi":"3.1.0", master throws for the same instances and this tree fixes them. The CHANGELOG says "OpenAPI 3.0" and the tests cover only 3.0. Reword it and add the 3.1 dialect to Issue1378Test.

3. Duplicated validate/walk dispatch (OneOfValidator.java:89, AnyOfValidator.java:77)
The dispatch is written twice per loop (inside the lambda and in the else if chain), and the lambda is allocated for every branch. Build one Runnable and run it with or without evaluateDiscriminatorBranch.

4. Scale test does not exercise the journal path (Issue1378Test.java:118)
It uses a top-level array, where the discriminator is recorded at depth 0 and nothing is journaled. Put the discriminated array inside an outer oneOf/anyOf branch, and add the non-put mutator case from item 1.

@stevehu

stevehu commented Nov 7, 2026

Copy link
Copy Markdown
Contributor Author

Second follow-up on the uncommitted working tree for fix/issue-1378-discriminator-scope (the branch head is still d6a3bc8; I reviewed a copy of the author's working tree, so line numbers may shift once it is pushed). The four earlier findings are addressed.

Checked: put, putIfAbsent, computeIfAbsent, putAll and merge now all leave 0 entries after a branch. The discriminator tests, Issue1378Test (19 cases, including OpenAPI 3.1) and the JSON Schema Test Suite pass; I did not run the full Maven suite. Arrays of 64,000 discriminated items nested in an outer oneOf take 91 ms, against about 76 ms on master. Three minor points remain.

1. The scale test cannot see scans inside ExecutionContext (Issue1378Test.java:112)
It traps entrySet() on the wrapper returned by the overridden getDiscriminatorMapping(), but the fix works on the private map field directly. I added for (NodePath p : new ArrayList<>(discriminatorMapping.keySet())) {...} to endDiscriminatorBranch in a scratch copy: all 19 cases stayed green while the 64,000-item benchmark went from 91 ms to 61 s. Count the work instead: a package-private counter of journal entries visited, or a linear-growth assertion between 1,000 and 16,000 items.

2. Two public evaluateDiscriminatorBranch overloads (ExecutionContext.java:257)
The Runnable one is used only by tests. The Schema one moves validate-or-walk dispatch and a Jackson JsonNode import into the state class. Package-private begin/end methods, or a helper owned by OneOfValidator/AnyOfValidator, keep the surface smaller.

3. Seven-method anonymous map, and changed gating (ExecutionContext.java:168)
A named package-private class owning the map, journal and depth would be testable on its own. Also, enablement is now decided with schema.getSchemaContext() of each branch instead of the validator's own schemaContext. They match when branches share the context; I did not verify a branch that switches dialect, and no test covers it.

@stevehu

stevehu commented Nov 7, 2026

Copy link
Copy Markdown
Contributor Author

Third and fourth follow-ups on the uncommitted working tree for fix/issue-1378-discriminator-scope (the branch head is still d6a3bc8; I reviewed a copy of the author's working tree, so line numbers may shift once it is pushed).

The earlier findings are addressed: the scale tests now count operations on the actual backing map and assert linear growth, the callback/dispatch overloads are replaced by a scope API with a shared no-op scope, DiscriminatorMapping is a named class, gating is back on each validator's own schemaContext, and the test-only constructor is gone.

Checked: the discriminator tests, Issue1378Test (20 cases) and the JSON Schema Test Suite pass; I did not run the full Maven suite. A full-map scan added to DiscriminatorMapping.end in a scratch copy makes 4 of the 20 cases fail, so the ratio assertion does catch the regression. Arrays of 64,000 discriminated items nested in an outer oneOf take about 73 ms, in line with master.

One minor point remains.

The scale test mutates a final field by reflection (Issue1378Test.java:239)
countBackingEntries overwrites private final Map entries (DiscriminatorMapping.java:35) with Field.set. JEP 500 deprecates mutating final fields this way (a warning by default from JDK 26, an error later), so the four scale cases would start warning and later fail on newer JDKs. Dropping final on that package-private field, or giving DiscriminatorMapping a package-private instrumentation method, avoids it.

@stevehu
stevehu merged commit 2861c69 into master Nov 7, 2026
4 checks passed
@stevehu
stevehu deleted the fix/issue-1378-discriminator-scope branch November 7, 2026 03:18
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

1 participant