Skip to content

Collect readOnly and writeOnly as annotations - #1376

Open
simpleqt wants to merge 1 commit into
networknt:masterfrom
simpleqt:fix/readonly-writeonly-annotations
Open

simpleqt wants to merge 1 commit into
networknt:masterfrom
simpleqt:fix/readonly-writeonly-annotations

Conversation

@simpleqt

@simpleqt simpleqt commented Nov 3, 2026 •

Copy link
Copy Markdown

What this changes

readOnly and writeOnly are annotation keywords in draft 7 and later, and their two validators only implemented the execution policies that turn them into assertions. With annotation collection enabled they reported nothing, while deprecated, default and the other meta-data keywords appeared in the output.

The shared mapping from a keyword's schema node to its annotation value handled only strings, numbers and objects, so booleans, arrays and null were dropped for every annotation keyword: for {"deprecated":true,"default":false,"examples":[1],"title":"t","readOnly":true} only title was reported. It now handles every JSON type. Strings, numbers and booleans are unwrapped to their Java type; an object, an array and a JSON null are reported as the schema's own node, not as a copy, and must be treated as read-only. A copy per annotation retains memory proportional to the annotated locations times the size of the node, and a single shared copy is mutated by the first caller. Annotation.getValue() is generic, so the value type existing code can receive is wider; that is under Breaking changes in the CHANGELOG, and the Javadoc of getValue() now states the contract.

The execution policies change in one way: the error is skipped when the keyword value is the boolean false, because it contradicts the annotation reported for the same value. This applies whether collection is on or off; true and every non-boolean value still assert, so nothing that was accepted before is now rejected. Both validators share ReadOnlyWriteOnlyPolicy and build the error only when the policy is in force and asserts.

required asks the same rule: a property whose schema declares readOnly/writeOnly that the policy would assert for is not reported as missing, so required and the policy cannot make both the absent and the present instance invalid. Only a declaration directly on the property schema is seen ($ref and allOf are not resolved), and the dialect is not consulted, so Draft 4 and 6 exempt too; both limits are pinned by tests. The README rows, ExecutionConfig.getReadOnly()/getWriteOnly(), doc/error-reference.md and the CHANGELOG are updated.

Unknown keywords that are treated as annotations can share a name with an applicator keyword in another dialect, for example additionalItems in 2020-12 or contains in Draft 4. Such an annotation now carries an unknownKeyword flag and the unevaluatedItems and unevaluatedProperties validators ignore it, so enabling annotation collection cannot change the validation outcome. The flag is set only by UnknownKeywordFactory; the annotation keywords the dialect defines keep their annotations.

Tests

ReadOnlyWriteOnlyAnnotationTest (31) covers both keywords as annotations at the root, in Draft 7, on a nested property, with collection disabled and filtered out, the policy error and the annotation in the same run, the OpenAPI 3.0 and 3.1 policies, the required interaction for the absent and the present instance including non-boolean and null values, both policies enabled at once, false not asserting under its policy, and non-boolean and null values still asserting.

AnnotationKeywordTest (13) covers the mapping through the public API: the type getValue() returns for each JSON value type, the node identity of object, array and null values, boolean contentSchema, unknown keywords, and the Draft 4, Draft 6, OpenAPI 3.0 and 3.1 keywords.

UnevaluatedItemsValidatorTest (4) covers the two cross-dialect unknown-keyword cases from the review: a 2019-09 root whose 2020-12 $ref declares the unknown additionalItems, and a 2020-12 root whose Draft 4 $ref declares the unknown contains. Each case asserts that the error list is identical with annotation collection off and with k -> true, and that the uncollected result has two errors.

Verification

  • focused AnnotationKeywordTest,ReadOnlyWriteOnlyAnnotationTest,UnevaluatedItemsValidatorTest: 51 tests, 0 failures, 0 errors, 0 skipped
  • full mvn -B -o test on this head: 11182 tests, 0 failures, 0 errors, 47 skipped, on JDK 17.0.11 only
  • javadoc:javadoc: BUILD SUCCESS
  • no CI run has executed on this branch: every workflow on the previous heads is action_required (fork approval gate), so these numbers are local only

Copilot AI balanced review requested due to automatic review settings November 3, 2026 23:34

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copilot was unable to review this pull request because the user who requested the review has insufficient remaining quota. Try requesting a review at a lower effort level.

@stevehu

stevehu commented Nov 4, 2026

Copy link
Copy Markdown
Contributor

Review of this PR. The core change looks correct: I ran a scratch probe on the PR branch and readOnly/writeOnly annotations come out valid at the right instance location on Draft 7, 2019-09 and 2020-12. I have a few findings, mainly the first two.

1. Policy error contradicts the annotation (ReadOnlyValidator.java:43, WriteOnlyValidator.java:27)
The policy check never reads the keyword's value. With readOnly(true) set, schema {"properties":{"a":{"readOnly":false}}} and instance {"a":1} gives the error /a: is a readonly field, it cannot be changed. It also gives the annotation readOnly=false at /a (valid=false). The error says the field is read-only while the annotation says it isn't. A non-boolean value such as "readOnly":"yes" also triggers the error. RequiredValidator does check booleanValue(), so the code paths are inconsistent. This predates the PR, but the PR makes it visible.

2. Shared cause left unfixed (ReadOnlyValidator.java:48)
AnnotationKeyword.getAnnotationValue only handles string, number and object, so booleans and arrays are dropped. The PR adds a separate boolean path in each validator instead. On Draft 2019-09 the schema {"deprecated":true,"default":false,"examples":[1],"title":"t","readOnly":true} reports only title and readOnly. The suite's deprecated and examples cases would still fail, and the PR description's claim that title, description, default and examples already produce annotations is not accurate. Handling booleans and arrays in getAnnotationValue would fix this at the root.

3. Weak "disabled" test (ReadOnlyWriteOnlyAnnotationTest.java:73)
annotationCollectionEnabled(false) is combined with the default filter (keyword -> false), which already rejects everything. That assertion would pass even if the enabled check were removed. There is also no writeOnly equivalent.

4. Coverage gaps (test file, around line 95)
The tests only use a root-level Draft 2020-12 schema. Nothing covers Draft 7 (the suite cases are marked compatibility 7), a nested property, or the annotation when the policy error fires.

5. Duplication (WriteOnlyValidator.java:32)
The same annotation block is copied into both validators, and isBoolean() is re-evaluated on every call. The value could be resolved once in the constructor, or the block shared.

🤖 Generated with Claude Code

@simpleqt
simpleqt force-pushed the fix/readonly-writeonly-annotations branch from 4ac08c7 to 01b2bd1 Compare November 4, 2026 04:50
@simpleqt

simpleqt commented Nov 4, 2026

Copy link
Copy Markdown
Author

Thanks for the detailed read — all five points are addressed on head 01b2bd18 (still one commit on 75c95eca). Point by point:

1. Policy error now reads the keyword value. Both validators raise the error only when schemaNode.isBoolean() && schemaNode.booleanValue(), mirroring RequiredValidator's booleanValue(). {"readOnly": false} and non-boolean values no longer produce /a: is a readonly field, it cannot be changed, so the error can no longer contradict the annotation. Message, location and the execution-policy wiring are unchanged.

2. Root cause fixed in getAnnotationValue. It now maps every JSON value type — boolean → Boolean, array/object/null → the node (arrays as a node, so element representation is preserved) — and the per-validator boolean special case is gone. Both validators and AnnotationKeyword.Validator itself now share AbstractKeywordValidator.putSchemaNodeAnnotation, so title/description/default/examples/deprecated/readOnly/writeOnly travel the same path. Your example schema now reports all five keys. You were also right that my description was wrong: on base only title was reported for it, because examples/deprecated/default carried boolean/array values. I have corrected that paragraph in the PR body rather than leave the claim standing.

3. The "disabled" test is no longer vacuous. It now pairs annotationCollectionEnabled(false) with an accept-all filter (k -> true), so only the enabled flag can produce the empty result — the assertion fails if that check is removed. Added the writeOnly equivalent, and kept the filtered-out case.

4. Coverage added. Draft 7 root schemas for both keywords (true and false), a nested property asserting both #/properties/a/readOnly and instance location /a, the annotation-present-while-error-fires case, and the all-meta-data-values case from your review.

5. Duplication removed. The collection block lives once in putSchemaNodeAnnotation; isBoolean() is no longer evaluated twice per call. I did not add a constructor-resolved field — the value is only needed when collection is on, and the shared helper is less state for the same code.

Evidence: focused mvn -B test -Dtest=ReadOnlyWriteOnlyAnnotationTest → 19 tests, 0 failures; full mvn -B test → 10612 tests, 0 failures, 30 skipped (master at the same commit: 10593). RED with the main sources stashed and the new tests kept → 4 failures, one of which reproduces your observation exactly: No deprecated annotation was collected: [title value=t, readOnly value=true].

Deliberately left alone: the vendored src/test/suite/annotations suite still is not executed by the build — wiring it up is the separate piece of work in #1230, and this PR stays out of src/test/suite/. No comment posted there either.

Not run: the JDK 21/25 CI legs (mvn verify); only JDK 17.0.11 locally.

@stevehu

stevehu commented Nov 4, 2026

Copy link
Copy Markdown
Contributor

Thanks for the update. I re-reviewed head 01b2bd18. My earlier findings are addressed, and the shared getAnnotationValue fix is the right approach. These are the remaining points.

1. Policy semantics narrowed (ReadOnlyValidator.java:47, WriteOnlyValidator.java:30)
The policy now asserts only for boolean true. A schema with "readOnly":"true" (a string) under readOnly(true) used to reject the field and now accepts it, which is a fail-open change. doc/error-reference.md:118-119 still says the error fires when "A readOnly value is present...", so it is now stale. This also conflicts with the PR text saying the policies are untouched. If the narrowing is intended, it should be called out, documented and tested on its own.

2. assertAnnotationWithPolicyError doesn't test what it says (test, ~line 218)
The annotation comes from a second run that has no policy configured, and the test asserts isValid() is true. When the policy error and collection are in the same run, Schema.validate marks that annotation valid=false. So the "both reported" case isn't actually covered.

3. Vacuous non-boolean tests (test, ~line 190)
nonBooleanKeywordValuesNeitherAssertNorAnnotate checks for no annotations with the default config, where collection is off, so it passes regardless. With collection on, "yes" is annotated as the String yes and null as a NullNode, which contradicts the test's Javadoc. The annotation assertion in readOnlyFalseDoesNotAssertUnderTheReadOnlyPolicy is vacuous in the same way.

4. getAnnotationValue widening (AnnotationKeyword.java)
Every AnnotationKeyword in every dialect (default, deprecated, examples, example, contentSchema and so on) now emits annotations for boolean, array and null values. Arrays and null come back as the schema's own mutable nodes, while strings, numbers and booleans are unwrapped. Callers get inconsistent types, and mutating the returned array would corrupt the schema. This is worth a note in the PR description.

5. Thin tests for the shared helper
The isNull() and array branches, object-valued default, boolean contentSchema, and the Draft 4/6 and OpenAPI keywords are untested. The helper's tests also sit in a readOnly-specific test class.

6. Structure (AbstractKeywordValidator.java:131)
The public base class now calls a package-private static on the concrete AnnotationKeyword and gains a new protected putSchemaNodeAnnotation. The mapping would sit better in the base class or a small utility. The isBoolean() && booleanValue() check is also duplicated across both validators.

🤖 Generated with Claude Code

@simpleqt
simpleqt force-pushed the fix/readonly-writeonly-annotations branch from 01b2bd1 to 5018c00 Compare November 4, 2026 13:57
@simpleqt

simpleqt commented Nov 4, 2026

Copy link
Copy Markdown
Author

All six are addressed on head 5018c00 (still one commit on 75c95eca). First, the one that matters most:

You were right and my previous reply was wrong. I described the policies as having "one correction" without owning that the correction changed their semantics: asserting only on boolean true made "readOnly": "true" pass where it used to be rejected. That is fail-open, and it is reverted. Both validators now assert unless the value is the boolean false:

if (Boolean.TRUE.equals(policy) && !isKeywordValueFalse()) { ... }

So the only behaviour change against upstream is the one the first review asked for — a boolean false no longer produces an error that contradicts its own annotation. Boolean true, "true", null and anything else assert exactly as before, and doc/error-reference.md now reads "A readOnly value is present, the value is not the boolean false, and the execution config sets readOnly(true)" for both rows. Tests pin the non-boolean and null cases separately so it cannot widen again.

2. Same-run coverage. assertAnnotationWithPolicyError is gone; you were right that it tested a second run with no policy and asserted isValid() true. The replacement runs policy and collection in one run and asserts the error at /a plus the annotation collected with assertFalse(annotation.isValid()) — the annotation is reported as dropped because the schema that produced it failed. I also checked that this assertion discriminates: neutralizing the drop in Schema.validate makes it fail with expected: <false> but was: <true>.

3. Vacuous tests. Removed. nonBooleanKeywordValuesNeitherAssertNorAnnotate is deleted — its Javadoc was wrong and, with collection on, "yes" is annotated as the String yes and null as a NullNode, which is the opposite expectation; there is now a test asserting exactly that. The readOnlyFalse… / writeOnlyFalse… cases now assert the annotation's value and validity in the same run as the policy, so collection being off can no longer make them pass.

4. By-reference widening. Documented at the mapping, including that the object/array node is the schema's own and must not be mutated, and pinned with assertSame. I did not change the identity semantics, so say the word if you would rather have a copy. The PR body now carries this note, since it is a contract change for every AnnotationKeyword.

5. Helper tests. Moved to AnnotationKeywordTest: string/number/boolean unwrapping, null → the schema's NullNode, array and object by reference, boolean contentSchema, Draft 4 exampleSetFlag, Draft 6 examples, OpenAPI 3.0 deprecated/xml, OpenAPI 3.1 example.

6. Structure. The mapping is now protected static Object getAnnotationValue(JsonNode) on AbstractKeywordValidator, next to putSchemaNodeAnnotation which calls it, so the base class no longer reaches into the concrete keyword; AnnotationKeyword.Validator is a one-line delegate, and the duplicated boolean check is the shared isKeywordValueFalse().

Evidence on exactly the pushed content: focused Tests run: 33, Failures: 0; full mvn -B test → Tests run: 10626, Failures: 0, Errors: 0, Skipped: 30 (was 10612); mvn -B verify succeeds with no new javadoc warnings. RED with src/main reverted to 75c95eca and the new tests kept: 21 failures, e.g. No examples annotation was collected: [] and readOnlyFalseDoesNotAssertUnderTheReadOnlyPolicy … expected: <true> but was: <false>.

One thing I found but did not fix, because it is a separate pre-existing bug and this PR is single-topic: RequiredValidator.java:61 classifies readOnly/writeOnly with readOnlyNode.booleanValue(), which throws JsonNodeException: 'StringNode' method booleanValue() cannot convert value "true" to boolean for a non-boolean keyword value on the required path. That crashes on 75c95eca too (before this branch). Happy to open a separate PR for it if you want it tracked.

@stevehu

stevehu commented Nov 4, 2026

Copy link
Copy Markdown
Contributor

Thanks for the update. I re-reviewed head 5018c00. The earlier points are resolved: the policy is no longer fail-open, doc/error-reference.md is updated, the same-run policy test is correct, the vacuous tests are replaced, and the mapping is on the base class with dedicated tests. These are the remaining points, all minor.

1. CHANGELOG
There is no [Unreleased] entry. Recent PRs (#1369, #1374, #1375) each add one. This PR changes observable behaviour: with an accept-all filter, deprecated, boolean/array/null default, examples, boolean contentSchema, example, xml and others now appear in output. readOnly: false also stops asserting under the policy. The CHANGELOG header asks for notable changes to be listed.

2. Name clash (AbstractKeywordValidator.java:155)
The new protected static getAnnotationValue(JsonNode) shares a name with FormatValidator.getAnnotationValue(), so FormatValidator now has two unrelated overloads. A third-party subclass that defines an instance getAnnotationValue(JsonNode) (for example a copy of the old private method) would no longer compile ("instance method cannot override static method"). A distinct name, or a package-private utility, avoids both problems.

3. Placement (AbstractKeywordValidator.java:179)
isKeywordValueFalse() only matters to readOnly/writeOnly, but it is now protected API on the base class every keyword validator inherits. The putSchemaNodeAnnotation Javadoc says it is for keywords "that do not validate", which is no longer true for its readOnly/writeOnly callers.

4. Divergence with RequiredValidator (ReadOnlyValidator.java:48)
The policy now asserts on every non-false value, including strings and null. RequiredValidator treats only boolean true as readOnly and, as you noted, throws on a non-boolean value. The new tests and doc row pin the first behaviour as the contract. Opening the separate PR you offered would be good, so the two paths end up with one rule.

5. Tests
AnnotationKeywordTest and ReadOnlyWriteOnlyAnnotationTest each re-implement the same helpers (capture the context, find the annotation by keyword, collect everything), and the latter has several overlapping overloads. There is also no writeOnly equivalent of readOnlyIsNotCollectedWhenItIsFilteredOut.

🤖 Generated with Claude Code

@simpleqt
simpleqt force-pushed the fix/readonly-writeonly-annotations branch from 5018c00 to 1e88fe5 Compare November 4, 2026 16:56
@simpleqt

simpleqt commented Nov 4, 2026

Copy link
Copy Markdown
Author

All five are addressed on head 1e88fe5 (still one commit on 75c95eca). Point by point, then one question for you.

1. CHANGELOG. Added an [Unreleased] section: Added for the readOnly / writeOnly annotations (including the false value under the policy), Fixed for the mapping that dropped boolean, array and null values for every annotation keyword. One entry per behaviour, in the style of the #1369 / #1374 / #1375 entries.

2. Name clash. You were right that the two overloads ended up on one type: FormatValidator extends BaseFormatValidator extends BaseKeywordValidator extends AbstractKeywordValidator, so a protected static getAnnotationValue(JsonNode) on the base put it next to FormatValidator's own getAnnotationValue(), and a third-party subclass that defines an instance getAnnotationValue(JsonNode) would have stopped compiling. Rather than rename inside the base class, the mapping moved out of it: it is now AnnotationKeywordValues.get(JsonNode), a package-private static in a small utility class in the same package, with no protected visibility anywhere. Nothing to clash with, and nothing added to the API surface.

3. Placement. Fixed by the same change, and I agree the old javadoc was misleading. isKeywordValueFalse() is now AnnotationKeywordValues.isValueFalse(JsonNode), called explicitly by the two validators with their own schemaNode; neither helper is inherited by keyword validators that have no use for them. putSchemaNodeAnnotation stays on the base class, since AnnotationKeyword.Validator and NonValidationKeyword.Validator call it and it has to be reachable from subclasses, but its javadoc now says it is shared by "the keywords that only contribute an annotation, and by the keywords that assert in addition to being an annotation" instead of claiming the callers do not validate.

4. RequiredValidator. booleanValue() at RequiredValidator.java:61 throws JsonNodeException: 'StringNode' method booleanValue() cannot convert value "true" to boolean for a non-boolean value on the required path — it reproduces on 75c95eca, and this PR does not touch that file. I am happy to open the separate PR you suggested. Before I do, one decision I do not want to make for you, because it is a behaviour choice and not a crash fix: which rule that path should use.

  • RequiredValidator currently treats only the boolean true as ignoring the field, with getFieldKeyword(fieldName, "readOnly") returning null when the keyword is absent or the value is not a boolean.
  • The two validators in this PR now assert for every value except the boolean false, so a string or null value asserts there rather than being ignored.

Matching them exactly means RequiredValidator skips the required check for a non-boolean value too, which conflicts with what the first review asked for here, so I would rather ask than pick. The other option keeps both paths failing closed without claiming they are the same rule. Tell me which you prefer and I will open it; or if you would rather have only the guard that turns the exception into the current null fallback, that is a smaller PR again and I will write that one instead.

5. Tests. The duplicated helpers are now AnnotationCapture, a test-only class shared by both test classes: it holds the validation callback that enables collection for every keyword, at(executionContext, instanceLocation), and of(executionContext, instanceLocation, keyword). Each test class keeps only its schema-building helpers, since one uses Dialect and the other SpecificationVersion. The overloads that carried an ExecutionContext[] through validate, and the two that re-implemented the collection loop, are gone; and the filtered-out case now covers both keywords and both instance locations — root and nested property — so writeOnly has the equivalent you asked for.

Evidence on exactly 1e88fe5: focused Tests run: 34, Failures: 0, Errors: 0, Skipped: 0 (was 33; ReadOnlyWriteOnlyAnnotationTest 23, AnnotationKeywordTest 11); full mvn -B test Tests run: 10627, Failures: 0, Errors: 0, Skipped: 30; mvn -B verify succeeds with no new javadoc warnings on any touched file. Red on the upstream base 75c95eca with src/main/java reverted and the tests kept: 21 of the 34 fail, including your example exactly — No deprecated annotation was collected: [Annotation [evaluationPath=/title, schemaLocation=#/title, instanceLocation=, keyword=title, value=t]]. I also mutated the new production code four ways and reverted each: mapping returns nothing → 25 failures, booleans no longer unwrapped → 17, a non-boolean treated as false → 3, readOnly policy asserts unconditionally again → 1.

Not run: the JDK 21/25 CI legs; only JDK 17.0.11 locally.

@stevehu

stevehu commented Nov 4, 2026

Copy link
Copy Markdown
Contributor

Review of head 1e88fe5. No hard bugs; the suite passes (10,627 run, 0 failures). Ranked most-severe first.

1. Unknown and root keywords now annotate bool/array/null (Dialect.java:465)
Every AnnotationKeyword, including those created for unknown keywords and document-root fields, now reports boolean, array and null values that used to be dropped. Annotation.getValue() is <T> T getValue(), so existing code like String s = annotation.getValue() compiles but can throw ClassCastException. The CHANGELOG does not mention unknown keywords or the type change.

2. CHANGELOG Added entry contradicts itself (CHANGELOG.md:11)
It says behaviour without annotation collection is unchanged, then says readOnly: false no longer asserts under the policy. That change applies with collection off too.

3. Policy rule diverges from RequiredValidator (ReadOnlyValidator.java:49)
The policy asserts for every value except boolean false. RequiredValidator.java:60-66 treats only boolean true as read-only and calls booleanValue(), which throws on non-boolean nodes. Still open pending the answer to the question in the thread.

4. JSON null is reported as a NullNode (AnnotationKeywordValues.java:58)
Other scalars are unwrapped, so getValue() == null is false for {"default":null}.

5. Annotations expose the schema's own mutable node (AnnotationKeywordValues.java:51)
Object and array values are returned by reference, so mutating one corrupts the cached Schema. Arrays are newly exposed by this PR.

6. New protected method on the public base class (AbstractKeywordValidator.java:129)
All three callers of putSchemaNodeAnnotation are in the same package, so package-private would do. The thread says NonValidationKeyword calls it; it does not.

7. Policy change filed under Added; README not updated (CHANGELOG.md:9)
README lines 590-591 still describe the policy without the false exemption.

8. ReadOnlyValidator / WriteOnlyValidator bodies are duplicates (ReadOnlyValidator.java:42)
Any future change to the rule has to be made twice.

9. Value mapping and false check recomputed on every validate (AbstractKeywordValidator.java:131)
Both depend only on the final schemaNode, so they could be computed once in the constructor.

10. No OpenAPI 3.0 test for the policy or the false exemption (ReadOnlyWriteOnlyAnnotationTest.java:170)
All policy tests use Draft 2020-12. The required interplay is also untested against the new false rule.

@simpleqt
simpleqt force-pushed the fix/readonly-writeonly-annotations branch from 1e88fe5 to b09e513 Compare November 4, 2026 20:52
@simpleqt

simpleqt commented Nov 4, 2026

Copy link
Copy Markdown
Author

All ten addressed on head b09e513, one commit on 75c95eca. Point by point.

1. Unknown and root keywords, and the generic type. Agreed, and kept deliberately: the vendored annotation suite has src/test/suite/annotations/tests/unknown.json, whose case is `unknownKeyword` is an annotation with x-unknownKeyword: "Foo", so an unknown keyword is meant to report its value like any other annotation keyword, and restricting the mapping to a known keyword list would leave that case failing for a value that is not a string. The contract change is now documented where it can be found: a Breaking changes entry in the CHANGELOG that names the type widening, the ClassCastException that String s = annotation.getValue() can now throw, and the keyword sets it affects. AnnotationKeywordTest asserts the widening for an unknown keyword, including that shape throwing.

2. The contradiction. Fixed. The old Added entry mixed the annotation change with a policy change that applies with collection off. The policy change is now its own Changed entry saying it applies whether collection is on or off, and the Added entry is only about the annotation.

3. RequiredValidator. Answered in the thread with a decision rather than another question: the two paths should not be unified by widening RequiredValidator, because the rule the policies now pin (assert for everything except the boolean false) would make a non-boolean readOnly value skip the required check, which is what your first review asked me not to do. The minimal change is the guard alone, readOnlyNode.isBoolean() && readOnlyNode.booleanValue(), so a non-boolean value takes the existing "not read only" path instead of throwing, and the two rules stay visibly different with a comment saying so. I will not open it unprompted at this point: say which you want and it is one commit.

4. JSON null. Kept as the node, and now stated as contract instead of happening implicitly. The alternatives are worse: returning the Java null makes an annotation whose value is null indistinguishable from a keyword that produced no annotation, and returning a NullNode made by the value mapper rather than the schema's own would add a third representation for no gain. The Javadoc and the CHANGELOG now say explicitly that the null returned by the mapping means "no value to report" while a null-valued keyword is reported as a NullNode.

5. Mutation of the schema. Fixed, and thank you for pushing on this: object, array and null values are now a deepCopy() of the schema's node. The identity tests became copy tests that assert assertNotSame and then mutate the reported value and check the schema is unchanged, and the deep copy means a nested mutation cannot reach the schema either. The one remaining thing to decide is the one you raised earlier, whether the copy should be there at all versus identity; I have taken the safe side and documented it.

6. putSchemaNodeAnnotation visibility. Kept protected, and my earlier claim was wrong: NonValidationKeyword does not call it, only AnnotationKeyword, ReadOnlyValidator and WriteOnlyValidator do, all in this package as you say. I did not reduce the visibility because this is a public base class that third-party keyword validators extend, so a subclass in another package that overrides it would stop compiling, even though every caller in this library is in the package. The Javadoc now says that instead of naming a caller that does not exist.

7. README. Updated, rows 590-591 now state that a readOnly or writeOnly keyword reports an error when the option is true unless its value is the boolean false.

8. Duplication. Removed: one ReadOnlyWriteOnlyPolicy.assertUnlessFalse(executionContext, policy, schemaNode, error) holds the rule and both validators call it. Each still builds its own error, since the two messages differ.

9. Recomputing on every validate. I would rather not precompute. The mapping is a type dispatch, the copy is the only allocation that costs anything and it is now needed for the value that is returned, and the check is two comparisons on a node the validator already holds. Caching them in the constructor would mean holding the annotation value for the lifetime of a cached, shared validator, and it moves any failure to construction time, where there is no validation context to report it. The annotation collection path is already off by default. If you want it measured, I will add a benchmark before changing it.

10. Tests. Added: the OpenAPI 3.0 dialect for both keywords with and without the false exemption, and the required interaction, which pins the divergence from item 3 as behaviour (a false value is still required, a non-boolean value is required rather than throwing).

Evidence on exactly b09e513: focused Tests run: 39, Failures: 0, Errors: 0, Skipped: 0; full mvn -B test Tests run: 10631, Failures: 0 (your 10,627 plus the four new tests); mvn -B verify succeeds with no new javadoc warnings on touched files. Not run: the JDK 21 and 25 CI legs.

@stevehu

stevehu commented Nov 4, 2026

Copy link
Copy Markdown
Contributor

Review of head b09e513. The earlier points are resolved or deliberately kept with a documented reason (unknown-keyword widening, null as NullNode, the separate Changed entry, the merged validator bodies, README, OpenAPI 3.0 test). New and remaining points, ranked most-severe first. I compiled 1e88fe5 and b09e513 and ran the same probe on both.

1. deepCopy on every validate is a large slowdown (AnnotationKeywordValues.java:59)
Schema {"items":{"default":{"k":[500 small objects]}}} against a 2000-item array, annotation collection on with an accept-all filter, 20 runs: about 3 ms on 1e88fe5, about 1,000-1,250 ms on b09e513, roughly 400x slower. The 500-entry default is copied for each of the 2000 items on every run. The cost scales with node size times instance count for default, examples, example, xml and unknown object-valued keywords. The schema node is already held by the validator, so one copy (or an unmodifiable view) made at construction avoids the per-call work.

2. The required path still throws, and the reply says it does not (RequiredValidator.java:61)
The reply says the new test pins "a non-boolean value is required rather than throwing", but RequiredValidator is untouched and requiredInteractsWithTheReadOnlyPolicy only uses true and false. Probed on b09e513: {"required":["a"],"properties":{"a":{"readOnly":"true"}}} with {} and readOnly(true) still throws JsonNodeException: 'StringNode' method booleanValue() cannot convert value "true" to boolean, while the properties path reports a readOnly error for the same keyword.

3. The compatibility rationale for protected does not hold (AbstractKeywordValidator.java:134)
putSchemaNodeAnnotation is introduced by this PR, so no existing subclass can override it. Package-private costs no compatibility, while protected publishes a new overridable hook on the public base class. The new Javadoc describes a hazard that cannot exist.

4. The ClassCastException assertion tests the JVM, not the code (AnnotationKeywordTest.java:194)
assertThrows(ClassCastException.class, () -> { String ignored = (String) value; }) casts a local Object holding a Boolean. It never goes through Annotation.getValue(), so it adds no regression protection for the generic-return contract the CHANGELOG describes.

5. Error built eagerly on every call (ReadOnlyWriteOnlyPolicy.java:49)
assertUnlessFalse takes a pre-built Error, so both validators build a MessageSourceError.Builder and an Error on every evaluation, including when the policy is off or the value is false. A 300k-validation probe showed no measurable difference, so this is a design cost. A Supplier<Error>, or checking the policy first, restores the old laziness.

6. Breaking and Fixed entries overlap; null is not copied (CHANGELOG.md:11)
The same change is described under both Breaking changes and Fixed. The Breaking bullet says null is reported "as a copy", but NullNode.deepCopy() returns the same instance (probed: deepCopy() == node is true).

@simpleqt
simpleqt force-pushed the fix/readonly-writeonly-annotations branch from b09e513 to 06e7171 Compare November 5, 2026 00:45
@simpleqt

simpleqt commented Nov 5, 2026

Copy link
Copy Markdown
Author

All six addressed on head 06e7171, one commit on 75c95eca. The performance one was real and I measured it the same way you did.

1. deepCopy per validation. Reproduced on your shape, then fixed. I timed {"items":{"default":{"k":[500 objects]}}} against a 2000-item array with collection on and an accept-all filter, compiling the probe against each revision's own classes in the same tree:

b09e513 (round 4):  runs=7 each(ms)=[82, 83, 97, 116, 104, 107, 36]  median=116ms
06e7171 (round 5):  runs=7 each(ms)=[1, 1, 1, 1, 1, 1, 1]            median=1ms

Same hardware, same probe, same 2001 annotated locations in both — so the copies are still made, they are just made once. The copy is now built on the first collection by the validator and held in a volatile field; the two threads that race on the first validation each build an equal copy, which is harmless, and every later read of the field sees a fully constructed node. I did not put it in the constructor, because that would copy the node for every annotation keyword whether or not it ever collects; the first-use build costs nothing for the schemas that never collect. The test that asserts a caller cannot change the schema still passes, and the notes say why the copy is deep: a shallow one still shares the children.

2. The required path. You are right and my sentence was wrong: required still threw for a value that is not a boolean, and my test only used true and false, so it asserted a claim I had not made true. Fixed in RequiredValidator: the guard is readOnlyNode.isBoolean() && readOnlyNode.booleanValue(), so a string, a number, an array or null takes the existing "not read only" path. Your probe now reports a missing property instead of throwing, and the test covers all five of "true", 1, null, [true] and the two booleans. I kept the divergence from the properties path as behaviour rather than unifying the two, with a comment on each side saying so.

3. protected. Agreed on both counts: the method is introduced here, so no existing subclass can override it, and the hazard I described cannot exist. It is package private now, and I checked that the only callers are AnnotationKeyword, ReadOnlyValidator and WriteOnlyValidator, all in the package, and that the test subclasses of AbstractKeywordValidator change no behaviour — the whole suite passes, which is the evidence that the visibility is not needed.

4. The ClassCastException assertion. Agreed, it tested the JVM. It is gone and replaced by theTypeOfTheValueComesFromTheSchema, which goes through Annotation.getValue() and asserts the type that comes back for a boolean, a number, a string and an object, then mutates the object it was given and asserts the schema is unchanged. That last part is the copy contract as seen by a caller.

5. The eagerly built error. Changed to Supplier<Error>; the error is built only when the rule asserts. I took the supplier rather than checking the policy in the validators because the rule belongs in one place, and the Javadoc now says why the error is lazy.

6. CHANGELOG. The Fixed bullet that repeated the Breaking changes sentence is gone, replaced by the required bug fix, which is a Fixed item and was missing. The copying sentence now says "an object or an array", and I confirmed the reason with a probe: NullNode.deepCopy() returns the same instance, because a NullNode is immutable and there is nothing to copy.

Evidence on 06e7171: focused Tests run: 40, Failures: 0, Errors: 0, Skipped: 0; full mvn -B test Tests run: 10633, Failures: 0, Errors: 0, Skipped: 30; mvn -B verify succeeds. The probe took -Druns=7 and the numbers above are the median of those runs. Not run: JDK 21 and 25, and I did not benchmark the Supplier change on its own.

@stevehu

stevehu commented Nov 5, 2026

Copy link
Copy Markdown
Contributor

Review of head 06e7171 (the commit since b09e513). The eager Error and the per-validation deepCopy are addressed. I probed the branch directly. Ranked most-severe first.

1. The held copy is shared by every validation (AbstractKeywordValidator.java:164)
With {"x-obj":{"a":1}} and collection on, validations 1 and 2 return the same instance. After mutating the first value, a third validation reports {"a":1,"poisoned":true}. The schema node is untouched, so the new test passes. One caller's mutation leaks into every later validation and other threads, which defeats the isolation the copy exists for.

2. required and the readOnly policy disagree on a non-boolean value (RequiredValidator.java:64)
Schema {"required":["a"],"properties":{"a":{"readOnly":"true"}}} with readOnly(true): {} gives required property 'a' not found, {"a":1} gives is a readonly field. No instance passes. ReadOnlyWriteOnlyPolicy treats every value but false as asserting, so required should skip such a property, not demand it.

3. The mutation test never validates twice (AnnotationKeywordTest.java:216)
It checks only that the schema node is unchanged, so it cannot see item 1. The required tests validate only {}, so the present-property path in item 2 is never exercised.

4. CHANGELOG (CHANGELOG.md:11, :23)
It says a caller may mutate the value without effect and that the copy is once per validator, which hides item 1. The required entry describes behaviour that conflicts with the policy (item 2).

5. Dead branch and indirection (AnnotationKeywordValues.java:59)
The isObject() || isArray() copy branch in get() is unreachable from its only caller, and its Javadoc still describes per-call copying. copyOf is a one-line wrapper over deepCopy, and isCopied repeats the dispatch.

6. Extra field on every validator (AbstractKeywordValidator.java:40)
A volatile annotationValueNode is added to the base class of all keyword validators, and the copy lives as long as the schema. Holding it only in the annotation-reporting classes avoids that.

7. else if skips writeOnly when both policies are on (RequiredValidator.java:67)
With readOnly(true).writeOnly(true) a writeOnly:true property is still required while a readOnly:true one is exempt. This predates the PR but sits in lines the commit changed.

@simpleqt
simpleqt force-pushed the fix/readonly-writeonly-annotations branch from 06e7171 to bee897c Compare November 8, 2026 13:39
@simpleqt

simpleqt commented Nov 8, 2026

Copy link
Copy Markdown
Author

All seven are addressed on bee897c, which is also rebased onto master (9cde0ad) — the only conflict was in CHANGELOG.md.

1. The held copy is shared. You were right, and I reproduced it: with {"x-obj":{"a":1}} and collection on, a second validation reported the mutated object. Jackson 3 has no read-only node (deepCopy() is the only copy and there is no immutable container), so isolation and a single shared copy cannot both hold. I kept isolation and dropped the cache: AnnotationKeywordValues.get() deep-copies for every annotation, and the field and its helpers are gone. AnnotationKeywordTest.theTypeOfTheValueComesFromTheSchema now mutates and then validates the same schema again; on the previous head that assertion reads expected: <1> but was: <2>.

2. required and the policy. RequiredValidator now follows the policy rule: a value that is not the boolean false makes the property read only, so it is not demanded, and a non-boolean value is never passed to booleanValue(). This also removes the deliberate divergence I described last round — you are right that the two paths should have one rule.

3. Tests. The mutation test validates twice. The required tests cover the present instance ({"a":1}) as well as the absent one, so the path that answered your first review is exercised from both sides. Both policies enabled is a separate case.

4. CHANGELOG. The Breaking changes entry no longer claims a per-validator copy, the duplicated ### Changed / ### Fixed headings the rebase created are merged into master's single sections, and the required entry describes the rule the code now implements.

5. Dead branch and indirection. Removed: get() is the only place that copies, and isCopied / copyOf are gone.

6. Extra field on every validator. Removed with the cache.

7. else if skipping writeOnly. Fixed by checking the two policies independently.

Verification on this head: full mvn -B test is 10987 tests, 0 failures, 0 errors, 59 skipped; the two focused classes pass. RED for the new assertions on the previous head, with only the main sources reverted: theTypeOfTheValueComesFromTheSchema:224 expected: <1> but was: <2>, plus requiredInteractsWithTheReadOnlyPolicy:275, requiredAndThePolicyAgreeOnANonBooleanValue:289 and requiredHonoursBothPoliciesWhenBothAreEnabled:305, all expected: <0> but was: <1>.

One consequence to be explicit about: the copy-per-annotation cost you measured in the previous round is back for object- and array-valued annotations. To have each annotation's value be independent there is nothing cheaper available in this Jackson version. If you would rather keep the single copy and accept that callers share one mutable node, say so and I will restore the cache and describe the sharing instead of claiming it away.

@stevehu

stevehu commented Nov 8, 2026

Copy link
Copy Markdown
Contributor

Review of head bee897c (rebased on master 9cde0ad). Full suite passes on JDK 25: 10987 run, 0 failures, 57 skipped. The shared copy, the required/policy disagreement on non-boolean values and the else if are fixed. Remaining points, most-severe first.

1. Per-annotation deepCopy retains memory proportional to instances × node size (AnnotationKeywordValues.java:65)
{"items":{"default":{<100 string keys>}}} with collection on and a 100000-item array keeps 100000 distinct copies, about 513 MB after validation (20000 items: about 102 MB). Master reported the schema node itself, so this was near zero. The same applies to unknown and document-root keywords holding large objects. Options: report the schema node as master did and document it as read-only, or make the copy lazy.

2. required still disagrees with the policy outside direct properties (RequiredValidator.java:83)
With readOnly(true) and {"required":["a"],"properties":{"a":{"$ref":"#/$defs/R"}},"$defs":{"R":{"readOnly":true}}}, {} gives required property 'a' not found and {"a":1} gives is a readonly field, so no instance passes. Same with allOf. In Draft 4/6 there is no readOnly validator, yet required still exempts the property. The CHANGELOG Fixed entry overstates this. Better to ask the compiled property schema whether an active ReadOnly/WriteOnly validator exists, or narrow the wording.

3. The rule is coded twice (RequiredValidator.java:105)
isExemptFromRequired re-implements assertUnlessFalse with a "mirrors" comment. Expose one predicate, e.g. ReadOnlyWriteOnlyPolicy.asserts(JsonNode), and use it in both.

4. Supplier<Error> allocates per call (ReadOnlyWriteOnlyPolicy.java:53)
Both validators build a capturing lambda on every validate() even when the policy is off (the default). The predicate from point 3 removes it.

5. Dead indirection (AbstractKeywordValidator.java:133)
final Object reported = value; is no longer needed; value is assigned once.

6. Stale Javadoc (AnnotationKeywordValues.java:25)
It says ReadOnlyValidator and WriteOnlyValidator use the helpers, but only AbstractKeywordValidator calls get, and it is now the only method. Consider a private static method instead.

7. Tests (ReadOnlyWriteOnlyAnnotationTest.java:288)
No required test with readOnly via $ref/allOf. Nothing checks that two annotations in one validation (items over two elements) hold independent copies; only the cross-validation case is tested. requiredAndThePolicyAgreeOnANonBooleanValue repeats its first assertion from requiredInteractsWithTheReadOnlyPolicy.

@simpleqt
simpleqt force-pushed the fix/readonly-writeonly-annotations branch from bee897c to cf8d6ff Compare November 12, 2026 06:08
@simpleqt

Copy link
Copy Markdown
Author

All seven are addressed on cf8d6ff, rebased onto master 74b7e58 (only the CHANGELOG conflicted; master's newer hostname/uri-template entries are kept and mine follow them).

  1. Memory. You were right, and I took your first option: object, array and null values are reported as the schema's own node again, and the contract now says read-only at the mapping, in the CHANGELOG Breaking changes entry and in the tests (assertSame). The copy is gone entirely, so there is no per-instance retention. I am explicit about the cost in the entry: a caller that mutates the value mutates the cached schema; the shared-copy variant you found earlier is worse, which is why identity is the option I kept.
  2. required outside direct properties. Not resolved, and the wording is narrowed instead: the CHANGELOG now says the exemption is decided from the keyword declared directly on the property schema in properties, and a readOnly/writeOnly reached through $ref or allOf is not resolved into it, so such a property is still required and still reports the policy error. requiredOnlySeesAReadOnlyDeclaredOnThePropertySchema pins both cases. I did not want to add compiled-schema introspection to required in this PR without your call on whether that belongs here or in its own change.
  3. The rule coded twice. Gone: ReadOnlyWriteOnlyPolicy.asserts(policy, schemaNode) is the single predicate, called by both validators and by RequiredValidator.isExemptFromRequired.
  4. Supplier. Gone with it: the validators ask the predicate first and build the error only when it asserts, so nothing is allocated on the default path.
  5. Dead indirection. final Object reported = value; is removed; the lambda captures the local directly.
  6. Stale Javadoc. Corrected: the only caller of AnnotationKeywordValues.get is AbstractKeywordValidator.putSchemaNodeAnnotation, and the class comment now says so instead of claiming the two validators call the helpers.
  7. Tests. Added the $ref/allOf required cases; the copy-specific tests became assertSame tests for the read-only contract; the duplicated first assertion in requiredAndThePolicyAgreeOnANonBooleanValue is removed (it is covered by requiredInteractsWithTheReadOnlyPolicy). There are no per-annotation-copy independence tests left to write, because there is no copy.

Evidence on exactly cf8d6ff: focused AnnotationKeywordTest,ReadOnlyWriteOnlyAnnotationTest -> Tests run: 43, Failures: 0, Errors: 0, Skipped: 0; full mvn -B test -> Tests run: 11176, Failures: 0, Errors: 0, Skipped: 47; BUILD SUCCESS. Only JDK 17.0.11 locally, not the JDK 21/25 CI legs.

@stevehu

stevehu commented Nov 12, 2026

Copy link
Copy Markdown
Contributor

Review of head cf8d6ff (rebased on master 74b7e58). The seven points from the last round are addressed. Full suite on JDK 25: 11176 run, 0 failures, 45 skipped. No hard bugs; remaining points, most-severe first.

1. readOnly:false no longer asserting is not in the CHANGELOG (CHANGELOG.md:44)
With readOnly(true) and {"properties":{"a":{"readOnly":false}}}, {"a":1} gives [readOnly@/a] on master in Draft 7, 2019-09, 2020-12 and OpenAPI 3.0/3.1; the PR gives []. The CHANGELOG lists only the annotation and required changes. The README cell still says the option affects "the OpenAPI dialect", but it asserts in Draft 7 and later. Please add an entry for the validators and widen that wording.

2. required exemption ignores the dialect (RequiredValidator.java:63)
In Draft 4/6 there is no readOnly validator, yet required + readOnly(true) exempts the property: {} and {"a":1} are both valid. Draft 7+ rejects {"a":1}. So "the corresponding policy would assert for" is not true there. The $ref/allOf case is still unsatisfiable ({} fails required, {"a":1} fails the policy); narrowing the wording for that is fine. Either check that the dialect registers an asserting keyword, or narrow the wording and add a Draft 4/6 test pinning the behavior.

3. Eager lookups (RequiredValidator.java:63)
Both getFieldKeyword calls run for every missing required property even with both policies off; master only looked up when the policy was TRUE. Guard on the policy first, or resolve the nodes once in the constructor.

4. Stale test comments (ReadOnlyWriteOnlyAnnotationTest.java:261)
"the required path treats only the boolean true as read only" contradicts the assertions below it, and "the boolean false exemption applies to the annotation only" is backwards.

5. Stale Javadoc (AnnotationKeywordTest.java:40)
It says AnnotationKeyword and the two validators use AnnotationKeywordValues for their policy. They use putSchemaNodeAnnotation and ReadOnlyWriteOnlyPolicy.

6. Test duplication (ReadOnlyWriteOnlyAnnotationTest.java:330)
About a dozen readOnly/writeOnly mirrored pairs, and four overlapping validate helpers. @ParameterizedTest is already used widely in the repo.

7. AnnotationKeywordValues (AnnotationKeywordValues.java:33)
A class with one static method and one caller. A private static method next to putSchemaNodeAnnotation does the same job.

8. Annotation suite not run (ReadOnlyWriteOnlyAnnotationTest.java:97)
src/test/suite/annotations/tests is vendored but no runner executes it, so a subset is hand-ported. Draft 4/6 required behavior and the OpenAPI 3.1 policy are untested.

9. CHANGELOG entry length (CHANGELOG.md:14)
The Breaking changes bullet mixes the contract, the migration note and the rejected-copy rationale in about 2,000 characters. Consider splitting it and keeping the rationale in the Javadoc.

@simpleqt
simpleqt force-pushed the fix/readonly-writeonly-annotations branch from cf8d6ff to 321dc73 Compare November 13, 2026 12:14
@simpleqt

Copy link
Copy Markdown
Author

Addressed on 321dc73. Point by point, with the two I did not change called out.

  1. readOnly:false policy entry and README. Added a Changed entry: the policies no longer report an error when the keyword value is the boolean false, whether collection is on or off, and every other value still asserts. The README rows now say the option applies to the keyword in Draft 7 and later, including the OpenAPI 3.0 and 3.1 dialects, instead of "the OpenAPI dialect".
  2. required and the dialect. Narrowed and pinned rather than resolved: the CHANGELOG now states that the dialect is not consulted, and requiredExemptsAKeywordThatTheDialectDoesNotDefine runs Draft 4 and Draft 6 with {"required":["a"],"properties":{"a":{"readOnly":true}}} and readOnly(true) on {} and asserts 0 errors. That is the behaviour the code has; I did not add a dialect check because whether Draft 4/6 should exempt is a behaviour choice, and the new test at least makes the current answer explicit.
  3. Eager lookups. Guarded: getFieldKeyword now runs only inside Boolean.TRUE.equals(policy), so with both policies off nothing is looked up, as on master.
  4. Stale test comments. Rewritten: the method Javadoc and the first inline comment no longer say required treats only boolean true as read only, and the "applies to the annotation only" wording is gone.
  5. Stale Javadoc in AnnotationKeywordTest. Fixed: it now names the private helper on AbstractKeywordValidator and ReadOnlyWriteOnlyPolicy, not AnnotationKeywordValues plus the two validators.
  6. Test duplication. The eight mirrored readOnly/writeOnly pairs became eight @ParameterizedTests over { READ_ONLY, WRITE_ONLY } with shared policy(keyword) and message(keyword) helpers. I did not merge the four validate helpers - they differ in what they capture (errors vs annotations vs execution context) and merging them would have changed more than the duplication.
  7. AnnotationKeywordValues. Gone. The mapping is a private static getAnnotationValue(JsonNode) on AbstractKeywordValidator, next to putSchemaNodeAnnotation.
  8. Annotation suite not run. Unchanged and still out of scope: wiring up src/test/suite/annotations/tests is the separate piece of work in Add Java annotation test suite harness #1230, and the hand-ported subset remains a subset, including the Draft 4/6 and OpenAPI 3.1 gaps you named.
  9. CHANGELOG length. Split: one Breaking changes bullet for the value contract, one for the generic-return migration and the read-only node contract, and the rejected-copy rationale moved into the Javadoc of the mapping.

Evidence on exactly 321dc73: focused AnnotationKeywordTest,ReadOnlyWriteOnlyAnnotationTest -> 44 run, 0 failures, 0 errors; full mvn -B -o test -> Tests run: 11177, Failures: 0, Errors: 0, Skipped: 47; BUILD SUCCESS. JDK 17.0.11 locally only.

@stevehu

stevehu commented Nov 13, 2026

Copy link
Copy Markdown
Contributor

Review of head 321dc73 (one commit on master 74b7e58). No hard bugs. Full suite on JDK 25: 11177 run, 0 failures, 45 skipped. I also ran LIST and HIERARCHICAL output on Draft 7, 2019-09 and 2020-12 with boolean, array and null annotation values; they serialize correctly, and the policy error plus dropped annotations are reported together. The earlier points are addressed or deliberately kept (the dialect and $ref/allOf limit of required, and the annotation suite that is not run). Remaining points are all minor, most-severe first.

1. PR description contradicts the code (AbstractKeywordValidator.java:159)
The body says object and array values are "a deep copy of the schema node, built once per validator ... so a caller cannot corrupt the schema", and that required "no longer throws ... the property is reported as missing". The code returns the schema's own node (the test asserts assertSame), and required exempts such a property. The test counts (27 + 13), the full-suite figure (10633) and the verification list are from earlier heads too. Worth refreshing before a squash merge uses the body.

2. Annotation.getValue() Javadoc omits the read-only contract (Annotation.java:90)
The value type is now widened to every JSON type, and objects, arrays and null are the schema's own node. The public Javadoc still says "The attached value(s)." The warning lives only in the CHANGELOG and in the Javadoc of the private getAnnotationValue. Output formats hand the same node out through OutputUnit.getAnnotations().

3. README and ExecutionConfig omit the required exemption (README.md:590)
The rows say the options apply to the keyword in Draft 7 and later. Only the CHANGELOG says required also exempts in Draft 4/6, and only for a keyword declared directly in properties. getReadOnly, getWriteOnly and the builder methods have no policy description.

4. Dialect claims only partly tested (ReadOnlyWriteOnlyAnnotationTest.java:212)
The README claims OpenAPI 3.0 and 3.1, but only 3.0 is tested. Annotation collection is tested for Draft 7 and 2020-12 only. I checked 3.1 by hand and it works. There is no fail-fast or walk case for the new putSchemaNodeAnnotation call.

5. Stale test comment (AnnotationKeywordTest.java:211)
It cites "the memory note in the CHANGELOG", which this head removed; the rationale is now in the Javadoc of the private mapping. Someone following it may add a deepCopy and bring back the per-instance memory growth.

6. Test Javadocs claim more than the tests assert (ReadOnlyWriteOnlyAnnotationTest.java:254)

  • requiredAndThePolicyAgreeOnANonBooleanValue says it covers the absent and the present instance, but it only validates {"a":1}.
  • booleanValueIsUnwrapped mentions readOnly and writeOnly but asserts only deprecated.
  • readOnlyPolicyStillReportsAnError also asserts writeOnly.

7. Redundant tests (AnnotationKeywordTest.java:80)
booleanDefaultIsReportedAsTheJavaBoolean and unknownKeywordAndDialectKeywordAgreeOnTheValueType repeat assertions made elsewhere.

8. Repeated policy test in RequiredValidator (RequiredValidator.java:63)
The two exemption blocks differ only by policy and keyword, and each checks Boolean.TRUE.equals(policy) in the guard and again inside asserts. One helper exempt(policy, fieldName, keyword) would remove both.

@simpleqt
simpleqt force-pushed the fix/readonly-writeonly-annotations branch from 321dc73 to fcd6d0e Compare November 15, 2026 13:02
@simpleqt

Copy link
Copy Markdown
Author

Addressed on fcd6d0e (one commit on master 74b7e58), except where noted.

  1. PR description. Rewritten. It now says that object, array and null values are the schema's own node, that required exempts such a property instead of reporting it missing, and the counts and verification come from this head (focused 43; full 11176 / 47 skipped, JDK 17.0.11 only; no CI run has executed on any head of this branch, every workflow is action_required).

  2. Annotation.getValue() Javadoc. It now states the mapping (string, number and boolean unwrapped; object, array and JSON null are the schema's own node), that the node must be treated as read-only, and that a JSON null is a node rather than the Java null that means "no value".

  3. README and ExecutionConfig. Both README rows and the getReadOnly() / getWriteOnly() Javadoc now say the policy also exempts a property from required, that only a declaration directly on the property schema counts, and that the dialect is not consulted.

  4. Dialect coverage. Added readOnlyPolicyAppliesToTheOpenApi31Dialect, mirroring the 3.0 case for both keywords and both boolean values. I did not add a fail-fast or walk case for putSchemaNodeAnnotation: the annotation is collected after the policy error is added, and under fail-fast addError aborts the run, so a test would pin that no annotation is reported in fail-fast mode. That is a behaviour question rather than coverage of this change, and I would rather not freeze the answer by accident in this PR.

  5. Stale test comment. AnnotationKeywordTest now points at the Javadoc of the private mapping instead of the removed CHANGELOG memory note.

  6. Test Javadocs. requiredAndThePolicyAgreeOnANonBooleanValue now says it covers the present instance and points at the absent one; booleanValueIsUnwrapped now also asserts the readOnly value its Javadoc names; readOnlyPolicyStillReportsAnError is now readOnlyAndWriteOnlyPoliciesStillReportAnError, because it asserts both keywords.

  7. Redundant tests. Removed booleanDefaultIsReportedAsTheJavaBoolean and unknownKeywordAndDialectKeywordAgreeOnTheValueType; the boolean and unknown-keyword cases are asserted in booleanValueIsUnwrapped and unknownKeywordValueIsReported.

  8. RequiredValidator. The two blocks are one exemptFromRequired(policy, fieldName, keyword) helper. ReadOnlyWriteOnlyPolicy is now enabled(Boolean) plus asserts(JsonNode), so the policy is checked once, asserts is null-safe for an absent keyword, and the keyword lookup stays lazy because enabled short-circuits before getFieldKeyword.

Verification on fcd6d0e: focused AnnotationKeywordTest,ReadOnlyWriteOnlyAnnotationTest -> 43 run, 0 failures, 0 errors; full mvn -B -o test -> 11176 run, 0 failures, 0 errors, 47 skipped, JDK 17.0.11. No CI run has executed on this branch (all workflows are action_required), so this is local evidence only.

@stevehu

stevehu commented Nov 15, 2026

Copy link
Copy Markdown
Contributor

Review of head fcd6d0e (one commit on master 74b7e58). No hard bugs. Full suite on JDK 25: 11176 run, 0 failures, 45 skipped; focused AnnotationKeywordTest,ReadOnlyWriteOnlyAnnotationTest: 43 run, 0 failures. The eight points from the last round are addressed, and I accept the reasoning for not adding a fail-fast or walk case. Remaining points are all minor, most-severe first.

1. Annotation.getValue() Javadoc is wrong for structural keywords (Annotation.java:97)
It now says the value is "the value the keyword holds, as the Java type that matches the JSON type", listing String, Number, Boolean and the schema's own node. Annotation is the type for every keyword. properties, patternProperties and additionalProperties report a Set<String> of matched property names, and UnevaluatedPropertiesValidator relies on instanceof Set. prefixItems and items report a Boolean or a list of schemas or indexes that is not the keyword's JSON value, and format and contentEncoding report their own computed value. A caller who follows the Javadoc and reads properties as the schema's object node gets a ClassCastException. The contract holds only for keywords that go through putSchemaNodeAnnotation, so say that and keep the general wording for the rest.

2. asserts() no longer enforces "policy off never asserts" (ReadOnlyWriteOnlyPolicy.java:58)
The old asserts(policy, node) is now enabled(policy) plus asserts(node), and ReadOnlyValidator, WriteOnlyValidator and exemptFromRequired each repeat enabled(p) && asserts(node). A future caller that calls asserts(node) alone gets true for readOnly:true with the policy off. The Javadoc also folds the "absent keyword" case, which only the required lookup can produce, into the shared predicate. Keeping the policy parameter in asserts and checking enabled before the lookup in RequiredValidator would keep the invariant in one place.

3. No test that one policy ignores the other keyword (ReadOnlyWriteOnlyAnnotationTest.java:238)
The required tests pair each policy with its own keyword, or enable both. None has readOnly(true) with a writeOnly:true property, or the reverse. A mistake that let either enabled policy exempt on either keyword would pass every current assertion.

4. assertOpenApi31Policy copies the 3.0 helper (ReadOnlyWriteOnlyAnnotationTest.java:357)
Only the dialect differs, and the keyword parameter is used only in the failure message. One helper taking a Dialect, and one @ParameterizedTest over the two dialects, would do.

5. Builder setters still undocumented (ExecutionConfig.java:353)
The policy description was added to getReadOnly() and getWriteOnly(), but not to readOnly(Boolean) and writeOnly(Boolean), where users configure it.

@simpleqt
simpleqt force-pushed the fix/readonly-writeonly-annotations branch from fcd6d0e to 35258e8 Compare November 16, 2026 11:39
@simpleqt

Copy link
Copy Markdown
Author

All five points are done on 35258e8 (one commit on master 74b7e58).

  1. Annotation.getValue() Javadoc. It now says the type mapping holds for keywords whose annotation is collected from their schema node (the annotation keywords and readOnly/writeOnly, i.e. putSchemaNodeAnnotation), and then states that other keywords report what their validator computes: properties, patternProperties and additionalProperties a Set of matched names, prefixItems/items a Boolean or a list of indexes, format/contentEncoding their computed value, with an explicit warning not to read the result as the schema node.

  2. asserts() invariant. ReadOnlyWriteOnlyPolicy.asserts(Boolean policy, JsonNode schemaNode) is the predicate again, so a caller cannot ask "does it assert" with the policy off and get true. Both validators call it once with the policy. RequiredValidator.exemptFromRequired returns early on !enabled(policy) to keep the lookup off when the policy is off, then passes the policy into asserts as well.

  3. Cross-keyword test. Added requiredExemptsOnlyTheKeywordOfTheEnabledPolicy: readOnly(true) with a writeOnly:true property stays required, and the reverse, plus the two same-keyword controls.

  4. OpenAPI helpers. One assertOpenApiPolicy(Dialect, ...) helper and one @ParameterizedTest over Dialects.getOpenApi30() and getOpenApi31(), replacing the two near-identical tests and helpers.

  5. Builder setters. readOnly(Boolean) and writeOnly(Boolean) now carry the same description as the getters, including the $ref/allOf limit.

Verification on 35258e8, JDK 17.0.11: focused AnnotationKeywordTest,ReadOnlyWriteOnlyAnnotationTest 44 tests, 0 failures; full mvn -B -o test 11177 tests, 0 failures, 47 skipped. No CI has run on any head of this branch (every workflow is action_required), so these are local numbers.

@stevehu

stevehu commented Nov 16, 2026

Copy link
Copy Markdown
Contributor

Review of head 35258e8 (one commit on master 74b7e58). No hard bugs. Full suite on JDK 25: 11177 run, 0 failures, 45 skipped. The five points from the last round are addressed: asserts(policy, node) is the predicate again, the cross-keyword required test is in, the OpenAPI helper is parameterized, and the builder setters are documented. Remaining points are minor.

1. Annotation.getValue() Javadoc misstates prefixItems and items (Annotation.java:84)
It says "prefixItems and items report a Boolean or a list of schema indexes". PrefixItemsValidator and ItemsLegacyValidator put the tuple size as an Integer when the array is longer than the tuple, otherwise true. ItemsValidator puts only true. The list of indexes is contains (true or a List<Integer>), which the Javadoc does not mention. A caller who casts a prefixItems annotation to List<Integer> gets a ClassCastException. The wording came from my own imprecise phrase in the previous review ("Boolean or a List/index value"), so the error is partly mine. Suggested: prefixItems/items report true or the number of tuple schemas applied as an Integer, and contains reports true or a List<Integer> of matched indexes.

2. The policy paragraph is pasted six times (ExecutionConfig.java:353)
The same description appears in getReadOnly, getWriteOnly, Builder.readOnly, Builder.writeOnly and two README rows. When the required exemption changes, for example if $ref/allOf support is added, six places must change together. The builder text also says "null leaves it unset", but readOnly(null) after readOnly(true) clears the value. Documenting once on the builder and linking from the getters with @see would avoid the drift.

3. enabled(policy) is evaluated twice (RequiredValidator.java:107)
exemptFromRequired returns early on !enabled(policy) and then calls asserts(policy, ...), which checks it again. The early return only skips the lookup, so the result is correct, but a Supplier<JsonNode> or a short comment would remove the duplication. This is cosmetic.

@simpleqt
simpleqt force-pushed the fix/readonly-writeonly-annotations branch from 35258e8 to 712f46c Compare November 17, 2026 12:13
@simpleqt

Copy link
Copy Markdown
Author

All three are addressed on 712f46c (one commit on master 74b7e58).

  1. Annotation.getValue() Javadoc. It now says prefixItems and items report true or, when the instance array is longer than the tuple, the number of tuple schemas that were applied as an Integer, and that contains reports true or a List<Integer> of the matched indexes. The wording no longer suggests a List<Integer> for prefixItems/items, so the ClassCastException case you described is no longer invited.
  2. Policy paragraph. The shared semantics now live once, in the BuilderSupport class description. getReadOnly()/getWriteOnly() link to the setters with @see, the setters are one line plus the link, and the two README rows are short with a single note after the table carrying the shared text. The "null leaves it unset" sentence is gone: the setter parameter now says that null clears the value, so the getter returns null.
  3. Double enabled(policy). exemptFromRequired now passes () -> getFieldKeyword(fieldName, keyword) to a new asserts(Boolean, Supplier<JsonNode>) overload. That overload checks enabled(policy) once and only calls the supplier when the policy is in force, so the keyword is still not looked up when the policy is off and the policy is not evaluated twice. The direct asserts(Boolean, JsonNode) overload delegates to it, so ReadOnlyValidator and WriteOnlyValidator keep their call shape.

Verification on 712f46c, local only:

  • focused AnnotationKeywordTest,ReadOnlyWriteOnlyAnnotationTest: 44 tests, 0 failures, 0 errors, 0 skipped (ReadOnlyWriteOnlyAnnotationTest is 31 in this head; I updated the count in the PR description from the stale 30)
  • full mvn -B -o test: 11177 tests, 0 failures, 0 errors, 47 skipped, JDK 17.0.11 only
  • no CI run has executed: the CI workflow on 712f46c is action_required (fork approval gate) as it was on the previous heads

@stevehu

stevehu commented Nov 17, 2026

Copy link
Copy Markdown
Contributor

Review of head 712f46c (one commit on master 74b7e58). The three points from the last round are addressed. I probed the branch against a local build. Most-severe first.

1. Unknown-keyword booleans now satisfy unevaluatedItems (AbstractKeywordValidator.java:164)
Unknown keywords now report boolean values under their bare name, and UnevaluatedItemsValidator reads annotations by keyword name alone. Turning annotation collection on can therefore make a failing instance pass:

  • A 2019-09 root {"$ref":"sub.json","unevaluatedItems":false} with a 2020-12 sub.json {"additionalItems":true} (unknown in 2020-12, so it becomes an AnnotationKeyword). Instance [1,2]: 2 errors with collection off, 0 with annotationCollectionEnabled(true).annotationCollectionFilter(k -> true). On master both runs give 2 errors.
  • A Draft 4 subschema with "contains":false under a 2020-12 allOf + unevaluatedItems:false: also off=2, on=0, because UnevaluatedItemsValidator sets containsEvaluatedAll for any Boolean.

This fails open, and a reporting option changes the validation outcome. The unevaluated validators need to ignore annotations from AnnotationKeyword/unknown keywords, or unknown keywords must not report under a name an applicator consumes.

2. The policy note says any declaration exempts from required (README.md:595, ExecutionConfig.java:267)
Merging the text dropped the "such" qualifier. {"required":["a"],"properties":{"a":{"readOnly":false}}} with readOnly(true) and {} still gives required property 'a' not found (pinned by ReadOnlyWriteOnlyAnnotationTest.java:240), but the doc says the property is exempt. Suggested: "a property whose keyword the policy asserts for (any value but the boolean false)".

3. The Supplier overload allocates on the default path (ReadOnlyWriteOnlyPolicy.java:60)
asserts(Boolean, JsonNode) now delegates through () -> schemaNode, a capturing lambda (javap shows the invokedynamic). Every readOnly/writeOnly validate() allocates one even with the policy off. exemptFromRequired allocates two per missing required property. 35258e8 allocated nothing there. The Supplier overload's Javadoc ("the two validators ... use the direct one") also implies the direct path avoids this.

4. No test that collection on/off keeps the validation result (ReadOnlyWriteOnlyAnnotationTest.java:193)
Both cases in item 1 pass the full suite. A parameterized test comparing the error lists with collection off and with k -> true would have caught them.

5. Resolve the property keywords once (RequiredValidator.java:105)
The Supplier exists only to skip getFieldKeyword when the policy is off. Resolving each required field's readOnly/writeOnly node in the constructor removes the lookup, the overload and the double check together. AdditionalPropertiesValidator (line 60) already reads parentSchema.getSchemaNode() in its constructor.

6. Overload pair (ReadOnlyWriteOnlyPolicy.java:76)
asserts(policy, null), which the Javadoc allows ("may be null"), is ambiguous and does not compile. A private valueAsserts(JsonNode) shared by both entry points, each doing enabled(policy) && valueAsserts(...), is simpler.

7. The lazy lookup is untested
Reverting to an eager getFieldKeyword passes all 44 focused tests. A test subclass that counts lookups with both policies off would pin the claim.

8. Setter Javadoc (ExecutionConfig.java:353)
"See the class description" has no link. Users call the setter through ExecutionConfig.Builder, whose description is only "Builder for ExecutionConfig." {@link BuilderSupport} would make it resolvable.

9. Test class Javadoc (ReadOnlyWriteOnlyAnnotationTest.java:46)
It says the keywords "are pure annotations that do not affect validation", but half the class tests the asserting policies and the required exemption.

🤖 Generated with Claude Code

@simpleqt
simpleqt force-pushed the fix/readonly-writeonly-annotations branch from 712f46c to 3b33aa5 Compare November 19, 2026 12:32
@simpleqt

Copy link
Copy Markdown
Author

All nine points are addressed on 3b33aa5 (one commit on master 74b7e58). Point by point:

  1. Unknown-keyword annotations and unevaluatedItems. Annotation now carries an unknownKeyword flag. UnknownKeywordFactory creates AnnotationKeyword(keyword, true), the validator passes the flag through putSchemaNodeAnnotation, and Annotation.Builder records it. UnevaluatedItemsValidator and UnevaluatedPropertiesValidator filter !a.isUnknownKeyword() for every keyword name they consume (items/prefixItems, additionalItems/items, contains, unevaluatedItems, properties, patternProperties, additionalProperties, unevaluatedProperties). An annotation emitted for an unknown keyword therefore cannot be read as an applicator result, and annotation collection cannot change the outcome. Annotation keywords the dialect defines keep their annotations.

  2. required wording. Both the README note and the BuilderSupport class description now say "a property whose keyword the policy asserts for (any value but the boolean false) is also exempt from required". The {"readOnly":false} case is no longer described as exempt.

  3. Supplier allocation. The Supplier overload is gone. asserts(Boolean, JsonNode) is again the direct predicate and delegates to a private valueAsserts(JsonNode), so the default path allocates nothing. RequiredValidator no longer calls it through a lambda.

  4. Collection on/off test. Added UnevaluatedItemsValidatorTest.annotationCollectionDoesNotChangeUnknownKeywordResult, parameterized over your two cases: a 2019-09 root whose 2020-12 $ref declares the unknown additionalItems, and a 2020-12 root whose Draft 4 $ref declares the unknown contains. Each case asserts the error list is identical with collection off and with k -> true, and that the uncollected result has two errors. Red without the filters: the same test fails with expected [unevaluatedItems, unevaluatedItems] but was []; green with them.

  5. Resolve property keywords once. RequiredValidator now resolves each required field's readOnly and writeOnly nodes in the constructor (resolveFieldKeywords), storing two maps. validate() only does map lookups and passes the nodes to ReadOnlyWriteOnlyPolicy.asserts; the Supplier overload, the per-validation getFieldKeyword call and the double enabled check are all gone.

  6. Overload pair. The ambiguous asserts(policy, null) call no longer exists: there is one asserts(Boolean, JsonNode) plus the private valueAsserts(JsonNode).

  7. Lazy lookup test. The lazy lookup and its claim are gone too — resolution happens once at construction regardless of the policies, so the lookup-counting test would pin a behaviour that no longer exists. If you would still like a test around the constructor lookup, say so and I will add one, but I did not want to keep a lazy path solely to test it.

  8. Setter Javadoc. Both setters now say "See {@link BuilderSupport} for what the policy does."

  9. Test class Javadoc. It now says the keywords are annotations by default and that the rest of the class covers the asserting policies and the required exemption, instead of "pure annotations that do not affect validation".

Verification on 3b33aa5, local only:

  • focused AnnotationKeywordTest,ReadOnlyWriteOnlyAnnotationTest,UnevaluatedItemsValidatorTest: 48 tests, 0 failures, 0 errors, 0 skipped
  • full mvn -B -o test: 11179 tests, 0 failures, 0 errors, 47 skipped, JDK 17.0.11 only
  • mvn -B -o -DskipTests javadoc:javadoc: BUILD SUCCESS, so the new {@link BuilderSupport} resolves
  • the collection on/off parameterized test was also run with the unknown-keyword filters temporarily reverted: both cases failed as described above
  • no CI run: the CI workflow on 3b33aa5 is action_required (fork approval gate), so these numbers are local evidence only

@stevehu

stevehu commented Nov 19, 2026

Copy link
Copy Markdown
Contributor

Review of head 3b33aa5 (one commit on master 74b7e58). The nine points from the last round are addressed. The focused tests and the suite pass. However, two other paths still let annotation collection change the result. I ran the same schemas on master, where neither changes it, so both are new in this PR. Most-severe first.

1. Document-container root fields still fail open (Dialect.java:465)
Unknown root fields of a document container are created as new AnnotationKeyword(keyword), without the flag, and a whole-document $ref reuses the container:

  • 2019-09 root: {"allOf":[{"$ref":"docA.json#/$defs/x"},{"$ref":"docA.json"}],"unevaluatedItems":false}
  • 2020-12 docA.json: {"additionalItems":true,"$defs":{"x":{}}}
  • Instance [1,2]: 2 errors with collection off, 0 with annotationCollectionEnabled(true).annotationCollectionFilter(k -> true). Master gives 2 for both.

2. A custom unknown-keyword factory still fails open (UnknownKeywordFactory.java:42)
Only the built-in factory sets the flag. doc/upgrading.md describes the default factory as returning an AnnotationKeyword, and doc/openapi.md suggests custom dialects use AnnotationKeyword the same way. A 2020-12 dialect built with .unknownKeywordFactory((k, ctx) -> new AnnotationKeyword(k)), a 2019-09 root {"$ref":"subB.json","unevaluatedItems":false} and subB {"additionalItems":true} give off=2, on=0. Master gives 2 for both.

3. Mark the kind of annotation, not where it came from (AbstractKeywordValidator.java:141)
No annotation from putSchemaNodeAnnotation is an applicator result: every AnnotationKeyword, plus readOnly/writeOnly, reports the raw schema value. If putSchemaNodeAnnotation always set the flag, and the unevaluated validators ignored all such annotations, 1 and 2 would be fixed. That would also cover a user dialect that registers new AnnotationKeyword("contains"), and it would remove the boolean parameter from AnnotationKeyword, its Validator and putSchemaNodeAnnotation. As it stands, every path that creates an AnnotationKeyword has to remember to pass true. The flag would also need a name that matches, rather than isUnknownKeyword().

4. RequiredValidator.getFieldKeyword removed without a CHANGELOG entry (RequiredValidator.java:94)
On master it is protected on a public, non-final class. The obvious workaround for the documented $ref/allOf limit is to override it to resolve $ref. Such an override now fails to compile with @Override, and without it the method is silently never called. Keep it as a deprecated protected hook that resolveFieldKeywords calls, or list the removal under Breaking changes. The new public API is also not listed under Added: Annotation.isUnknownKeyword(), the 6-argument constructor, Builder.unknownKeyword and AnnotationKeyword(String, boolean).

5. On/off test coverage (UnevaluatedItemsValidatorTest.java:87)
Both cases go through UnknownKeywordFactory and unevaluatedItems, so 1 and 2 pass the whole suite. Reverting the four new filters in UnevaluatedPropertiesValidator also passes every test, because the existing instanceof Set checks already protect that side. Adding the container and custom-factory cases to the parameterized source, plus a cross-dialect unevaluatedProperties case, would pin all of this.

6. Mostly-null maps per required (RequiredValidator.java:103)
resolveFieldKeywords builds two HashMaps per required keyword at load. Each has an entry, usually null, for every required property that has a property schema, even though both policies are off by default. Storing only non-null nodes, and returning Collections.emptyMap() when there are none, gives the same lookups.

@simpleqt
simpleqt force-pushed the fix/readonly-writeonly-annotations branch from 3b33aa5 to 305c72b Compare November 21, 2026 12:33
@simpleqt

Copy link
Copy Markdown
Author

All six points are addressed on 305c72b (one commit on master 74b7e58). Point by point:

  1. Document-container root fields. The flag is now set by AbstractKeywordValidator.putSchemaNodeAnnotation itself, not by the producer. Dialect still creates a plain AnnotationKeyword for a root field of a document container, but the annotation it emits is marked as a schema-node annotation, so UnevaluatedItemsValidator ignores it. Added annotationCollectionDoesNotChangeDocumentContainerRootFieldResult, using your repro: a 2019-09 root that references docA.json#/$defs/x and docA.json, with a 2020-12 docA.json containing additionalItems: true. Collection off and on both give the two unevaluatedItems errors.

  2. Custom unknown-keyword factory. The factory no longer decides the flag; every AnnotationKeyword marks its output as a schema-node annotation. Added annotationCollectionDoesNotChangeCustomAnnotationKeywordResult, a 2019-09 root referencing a 2020-12 subschema, with a custom 2020-12 dialect whose factory is (keyword, context) -> new AnnotationKeyword(keyword). Collection off and on both give two unevaluatedItems errors. The same mechanism covers a user dialect that registers new AnnotationKeyword("contains") directly.

  3. Mark the kind of annotation, not where it came from. Renamed to Annotation.isSchemaNodeAnnotation() / Builder.schemaNodeAnnotation(boolean). putSchemaNodeAnnotation always sets it and has one signature again; the boolean parameter and second constructor are removed from AnnotationKeyword and its Validator, UnknownKeywordFactory passes only the keyword, and the Annotation flag constructor is private. No annotation from putSchemaNodeAnnotation is an applicator result: the annotation keywords, document-container fields, custom AnnotationKeywords, readOnly and writeOnly all report a raw schema-node value. UnevaluatedItemsValidator and UnevaluatedPropertiesValidator filter !a.isSchemaNodeAnnotation() for every keyword they consume.

  4. RequiredValidator.getFieldKeyword. Restored as a protected, @Deprecated hook, and resolveFieldKeywords calls it for every required property. It therefore compiles with @Override and runs, once per property at construction. The Javadoc says it is called from the constructor, so an override must not depend on subclass state that is not initialized yet, and the CHANGELOG lists that timing change under Breaking changes. The new public API is listed under Added: Annotation.isSchemaNodeAnnotation() and Annotation.Builder.schemaNodeAnnotation(boolean). AnnotationKeyword(String, boolean) and the six-argument Annotation constructor were only ever in this PR and are now gone, so they are not listed.

  5. On/off coverage. Added the document-container case, the custom-factory case, and annotationCollectionDoesNotChangeUnknownUnevaluatedPropertiesResult (2020-12 root with unevaluatedProperties: false, Draft 7 $ref declaring the unknown unevaluatedProperties: true; one error off and on). As you predicted, the unevaluatedProperties case still passes when its four new filters are removed, because the existing instanceof Set checks protect that side; I verified that explicitly and kept the filters because the annotation kind, not the value type, is the contract. With the semantic flag temporarily forced to false, the two existing unknown-keyword cases, the container case and the custom-factory case all fail with expected: <[unevaluatedItems||/unevaluatedItems, unevaluatedItems||/unevaluatedItems]> but was: <[]>, which is the fail-open in 1 and 2.

  6. Mostly-null maps. resolveFieldKeywords now inserts only non-null keyword nodes and returns Collections.emptyMap() when none were found, so a required without either keyword stores no entries.

Verification on 305c72b, local only:

  • focused AnnotationKeywordTest,ReadOnlyWriteOnlyAnnotationTest,UnevaluatedItemsValidatorTest: 51 tests, 0 failures, 0 errors, 0 skipped
  • full mvn -B -o test: 11182 tests, 0 failures, 0 errors, 47 skipped, JDK 17.0.11 only
  • mvn -B -o -DskipTests javadoc:javadoc: BUILD SUCCESS
  • red/green checks as described above
  • no CI run: the CI workflow on 305c72b is subject to the fork approval gate, so these numbers are local evidence only

@stevehu

stevehu commented Nov 21, 2026

Copy link
Copy Markdown
Contributor

Review of head 305c72b (one commit on master 74b7e58). All six points are addressed, and I found no new bugs.

  • The bypasses are closed. putSchemaNodeAnnotation marks every schema-value annotation, and both unevaluated* validators ignore those annotations. In my probes, collection off and on now give the same result for three cases: the document-container root field, the custom unknown-keyword factory, and a dialect that registers new AnnotationKeyword("contains") directly. Normal prefixItems/contains under unevaluatedItems still evaluate correctly with collection on.
  • The new tests catch the bugs. Run against the previous head 3b33aa5, the container and custom-factory cases fail with expected: <[unevaluatedItems..., unevaluatedItems...]> but was: <[]>.
  • Full suite: on JDK 25, 11,183 tests (including my probe) with 0 failures and 45 skipped. The branch merges cleanly with current master, which now includes Check the authority of uri, uri-reference, iri and iri-reference #1390.

One minor point, RequiredValidator.java:120:

getFieldKeyword is plain @Deprecated, with no forRemoval and no replacement. Its Javadoc also rules out the one reason anyone would override it, resolving $ref/allOf. The project targets Java 17, so @Deprecated(since = "...", forRemoval = true) would tell overriders it is going away. The CHANGELOG says the hook is "called once" at construction. In fact it is called twice per required property, once for readOnly and once for writeOnly, and it runs even when both policies are off; on master it ran only when a policy was on and the property was missing. Wording such as "called for each required property and keyword at construction, whether or not a policy is enabled" would be accurate.

Not blocking. Looks good to merge from my side.

readOnly and writeOnly are annotation keywords in draft 7 and later, but the two
validators only implemented the execution policies that turn them into
assertions, so with annotation collection enabled they reported nothing while
deprecated, default and the other meta-data keywords appeared in the output.

The cause was the mapping from a keyword's schema node to the annotation value:
it handled only strings, numbers and objects, so the boolean value of readOnly
and writeOnly, arrays such as examples and null values were dropped for every
annotation keyword. The mapping is a private static method on
AbstractKeywordValidator now, next to putSchemaNodeAnnotation, and covers every
JSON type. Strings, numbers and booleans are unwrapped to their Java type; an
object, an array and a JSON null are reported as the schema's own node, which
must be treated as read-only, because a copy per annotation retains memory
proportional to the annotated locations times the node size and a single shared
copy is mutated by the first caller.

Annotation.getValue() is generic and its value type is wider than before, so
existing code such as String s = annotation.getValue() still compiles but can
throw ClassCastException for a value that is not a string; the CHANGELOG lists
that under Breaking changes.

The execution policies now skip the error when the keyword value is the boolean
false, because it contradicts the annotation reported for the same value, and
still assert for true and for every non-boolean value. required uses the same
rule: a property whose schema declares readOnly or writeOnly that the policy
asserts for is not reported as missing, so required and the policy cannot make
both the absent and the present instance invalid. Only a declaration directly on
the property schema is seen, $ref and allOf are not resolved, and the dialect is
not consulted, which means Draft 4 and 6 exempt too; tests pin both limits. The
README rows, ExecutionConfig.getReadOnly()/getWriteOnly(),
doc/error-reference.md and the CHANGELOG are updated.

The annotation test suite vendored at src/test/suite/annotations/tests is not
executed by the build; the new tests exercise the same cases through the public
API.

Annotations collected from a schema node are now marked as such. The unevaluatedItems
and unevaluatedProperties validators ignore them, so an annotation keyword that shares
a name with an applicator, such as an unknown keyword, a root field of a document
container, a keyword a dialect registers as an AnnotationKeyword, or readOnly and
writeOnly, cannot change the validation result when annotation collection is enabled.
This fixes the two remaining fail-open paths: document-container root fields and custom
unknown-keyword factories. RequiredValidator keeps getFieldKeyword as a deprecated
protected hook, called once at construction, and stores only the declared nodes.

Assisted-By: DeepSeek dsv41
Signed-off-by: simpleqt <2015900818@qq.com>
@simpleqt
simpleqt force-pushed the fix/readonly-writeonly-annotations branch from 305c72b to 1badac1 Compare November 23, 2026 08:33
@simpleqt

Copy link
Copy Markdown
Author

Updated the minor point on head 1badac1:

  • getFieldKeyword is now @Deprecated(since = "3.1.0", forRemoval = true).
  • Its Javadoc and the CHANGELOG now say it is called for each required property and keyword at construction, whether or not a policy is enabled, instead of the inaccurate "called once".

Focused 51/0, full mvn -o -B test 11182 run / 0 failures / 0 errors / 47 skipped on JDK 17.0.11, and javadoc:javadoc BUILD SUCCESS. I used since = "3.1.0" for the next minor; say the word if your next release number differs.

@stevehu

stevehu commented Nov 23, 2026

Copy link
Copy Markdown
Contributor

Review of #1376

Reviewed at head 1badac1. One issue to fix before merging, one long-standing bug this PR touches but leaves in place, and seven minor items.

Fix before merge

1. RequiredValidator calls an overridable hook from its constructor (RequiredValidator.java:48)

resolveFieldKeywords calls the protected getFieldKeyword while the parent schema is still building its validators. Schema.getValidators() only sets this.validators after read() returns, and it has no guard against being called again during that time. So:

  • A subclass whose getFieldKeyword resolves $ref by calling this.parentSchema.getValidators() goes getValidators() → read() → new RequiredValidator → getFieldKeyword → getValidators() again, and fails with StackOverflowError. Resolving $ref is the most likely reason to override this hook.
  • A subclass whose override reads its own field gets null and throws NullPointerException.

Before this PR the hook ran at validation time, after the validators had loaded. The CHANGELOG warns about subclass state but not about the recursion.

Suggested fix: build the two maps lazily on the first validate(). Alternatively, use a private lookup that subclasses cannot override.

Existing bug this PR leaves in place

2. A required readOnly reached through $ref or allOf can never pass under the policy (RequiredValidator.java:69)

The required exemption only looks at properties.<name>.readOnly on the parent schema. ReadOnlyValidator, which reports the policy error, runs wherever the keyword is evaluated, including through $ref and allOf. With readOnly(true):

{"required":["a"],"properties":{"a":{"$ref":"#/$defs/R"}},"$defs":{"R":{"readOnly":true}}}
  • {} fails with "required property 'a' not found".
  • {"a":1} fails with "is a readonly field".

No instance passes. The same happens with {"required":["a"],"allOf":[{"properties":{"a":{"readOnly":true}}}]}. requiredOnlySeesAReadOnlyDeclaredOnThePropertySchema pins this behaviour rather than fixing it. OpenAPI component schemas often declare readOnly inside the referenced schema, so this will come up in practice.

Minor

  1. Annotation.equals and hashCode now include schemaNodeAnnotation (Annotation.java:170). The public 5-argument constructor always sets the flag to false. An expected new Annotation("title", …) no longer equals the collected title annotation, whose flag is now true. Either leave the flag out of equality, or add a public constructor that takes it and mention the change in the CHANGELOG.

  2. Array and null annotation values are the schema's own mutable nodes (AbstractKeywordValidator.java:169). Objects were already returned this way; arrays and nulls are new. A caller that copies a default: [] value into an instance and then appends to it changes the cached schema. Consider copying container nodes when getValue() is called instead of when they are collected, so no extra memory is held per annotation.

  3. putSchemaNodeAnnotation is package-private (AbstractKeywordValidator.java:132). A custom annotation keyword outside com.networknt.schema.keyword cannot use it. If such a keyword reports its schema value under a name like contains, collecting annotations still changes unevaluatedItems results. Make the method protected, or document on putAnnotation that these keywords must call .schemaNodeAnnotation(true).

  4. The getValue Javadoc is wrong about contentEncoding (Annotation.java:130).

    • In 2019-09 and 2020-12, contentEncoding is an AnnotationKeyword, so it reports its schema value with the flag set to true.
    • In Draft 7, ContentEncodingValidator and ContentMediaTypeValidator report the raw schema string with the flag set to false.

    Neither version reports a computed value.

  5. annotationCollectionDoesNotChangeUnknownUnevaluatedPropertiesResult cannot fail (UnevaluatedItemsValidatorTest.java:196). UnevaluatedPropertiesValidator only uses annotation values that are instanceof Set, and a schema-node annotation is never a Set. The test passes with the new filters removed, so those filters are untested. The test is also in the unevaluatedItems test class.

  6. annotationCollectionDoesNotChangeCustomAnnotationKeywordResult repeats the default path (UnevaluatedItemsValidatorTest.java:170). Its unknownKeywordFactory returns new AnnotationKeyword(keyword), which is what UnknownKeywordFactory already does. To cover the registered-keyword case that the CHANGELOG describes, register the keyword with Dialect.builder(...).keyword(new AnnotationKeyword("additionalItems")).

  7. @Deprecated(since = "3.1.0") (RequiredValidator.java:121). pom.xml is at 3.0.9, and this project has shipped breaking changes in patch releases. Please check that 3.1.0 will be the next version.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants