Skip to content

feat(java): apply JSON SKIP null handling to codec-decoded nulls - #4234

Open
pavel-ptashyts wants to merge 4 commits into
apache:mainfrom
pavel-ptashyts:json-codec-null-skip
Open

pavel-ptashyts wants to merge 4 commits into
apache:mainfrom
pavel-ptashyts:json-codec-null-skip

Conversation

@pavel-ptashyts

@pavel-ptashyts pavel-ptashyts commented Nov 17, 2026 •

Copy link
Copy Markdown
Contributor

Why?

onNullRead(SKIP) and onContentNullRead(SKIP) act only on an explicit JSON null token. A null that the selected codec returns for a non-null JSON value is still assigned or inserted. Normalizing codecs (a trimming codec that maps " " to null) therefore cannot rely on SKIP: {"id":"1","id":" "} clears id, and ["a"," "] with a trimming elementCodec reads ["a", null]. Dropping such elements today takes a complete custom collection codec per field type. Jackson's Nulls.SKIP treats a deserializer-returned null like a JSON null for both properties and collection contents. Details in #4233.

What does this PR do?

  • Semantics. Under SKIP, a Java null decoded by the selected codec from a non-null JSON value is handled like an explicit JSON null:
    • property (field, setter): not assigned, setter not called;
    • creator argument: stays absent, so the existing missing-argument default and failOnMissingRequiredProperties apply;
    • JsonUnwrapped child property or creator argument: decoded before its group is created, so a decoded null does not publish an otherwise absent group (same as an explicit JSON null);
    • element of a Collection, object array or AtomicReferenceArray, map value, and Any value (Any map and Any setter, which follow the global content setting): not inserted / setter not called.
      SET and FAIL are unchanged; FAIL still rejects only an explicit JSON null. No new API.
  • Interpreted path. JsonFieldInfo assigns a decoded value through one small helper that returns early on null under SKIP. JsonCreatorFieldInfo.read* now store into the argument array (read*(reader, arguments)), so a skipped value leaves the MISSING marker in place; the 12 ObjectCodec call sites use it. AnyInfo.skipDecodedNull guards the 15 Any read sites. Unwrapped routes decode first only under SKIP; SET keeps the group-then-read order. Unboxed carriers (value classes) are stored as decoded, as before, in every path.
  • Generated path. JsonReaderCodegen emits the null test only for SKIP properties, SKIP creator arguments that go through a codec (readResolvedField, assignCreatorValue), unwrapped SKIP routes, and Any values under content SKIP. Generated code for SET/FAIL is unchanged (checked with FORY_CODE_DIR).
  • Containers. GenericCollectionCodec/ObjectCollectionCodec and GenericMapCodec skip the insertion; the SET ArrayList fast path and the scalar-specialized collection and map codecs are untouched (their built-in element codecs never decode null from a non-null token). Object arrays and AtomicReferenceArray drop decoded nulls in one pass after the read loop, only under SKIP, so each graph-memory batch is still reserved before the batch's final element is read; the reservation covers every decoded element.
  • Docs. JsonProperty, NullHandling.SKIP and ForyJsonBuilder Javadoc; docs/json/annotations.md and docs/json/custom-codecs.md (the sentence "A codec returning Java null after consuming a non-null token is not filtered" is replaced).
  • Tests (JsonNullHandlingTest, both codegen modes, Latin1/UTF-16/UTF-8/stream inputs):
    • decodedNullProperties: public field and setter keep their value under SKIP and are cleared under SET; a creator argument decoded to null counts as missing (failOnMissingRequiredProperties throws) and an earlier duplicate is kept.
    • customChildAndInvalidTargets: List, Set, String[], AtomicReferenceArray with an elementCodec and Map with a valueCodec drop decoded nulls; the default SET keeps them.
    • registeredElementCodec: a codec registered with registerCodec for an element type, as a property and as a root List.
    • decodedNullUnwrappedAndAny: unwrapped mutable and creator children stay absent, an earlier unwrapped value is kept; Any setter, Any map and creator Any map skip decoded nulls.
    • decodedNullOutsideSkip: under SET and FAIL, decoded nulls are still assigned or inserted for every path above.
    • propertyAssignments: the assertion that pinned the old behavior now checks that a decoded null does not overwrite an earlier value.

Not covered, by design: primitive arrays with a custom element codec (a decoded null still fails, as before), Optional/AtomicReference content, and unboxed carriers. Their built-in or carrier codecs define their own null representation.

Related issues

AI Contribution Checklist

  • Substantial AI assistance was used in this PR: yes
  • If yes, I included a completed AI Contribution Checklist in this PR description and the required AI Usage Disclosure.
  • If yes, my PR description includes the required ai_review summary and screenshot evidence or equivalent persisted links of the final clean AI review results from both fresh reviewers described in AI_POLICY.md, the Fory-guided reviewer and the independent general reviewer, on the current PR diff or current HEAD after the latest code changes.

Completed checklist from AI_POLICY.md section 9:

  • Substantial AI assistance was used in this PR: yes
  • I included the standardized AI Usage Disclosure block below.
  • I can explain and defend all important changes without AI help.
  • I reviewed AI-assisted code changes line by line before submission.
  • I completed line-by-line self-review first and fixed issues before requesting AI review.
  • I ran two fresh AI review agents on the current PR diff or current HEAD after the latest code changes: one Fory-guided reviewer using AGENTS.md and .agents/ci-and-pr.md, and one independent general reviewer in a separate clean-context review session that was not pointed to .agents/ci-and-pr.md or any copied Fory-specific review checklist.
  • I addressed all AI review comments and repeated the review loop until both ai reviewers reported no further actionable comments.
  • I attached equivalent persisted links of the final clean AI review results from both fresh reviewers on the current PR head in this PR body.
  • I ran adequate human verification and recorded evidence (checks run locally, pass/fail summary, and confirmation I reviewed results).
  • I added/updated tests and specs where required.
  • I validated protocol/performance impacts with evidence when applicable.
  • I verified licensing and provenance compliance.
AI Usage Disclosure
- substantial_ai_assistance: yes
- scope: design drafting, code drafting, tests, docs, PR text
- affected_files_or_subsystems: java/fory-json (JsonFieldInfo, JsonCreatorFieldInfo, ObjectCodec, JsonReaderCodegen, CollectionCodec, MapCodec, ArrayCodec, ScalarCodecs.AtomicReferenceArrayCodec, JsonProperty/ForyJsonBuilder Javadoc), docs/json
- ai_review: line-by-line self-review by the contributor is pending (see unchecked items above). Two-reviewer loop on fresh sessions every round, four rounds. Fixed from review: unwrapped groups were created before a decoded null was skipped; Any map and Any setter values were not filtered; the guide still said codec nulls are never filtered; SET/FAIL keeping decoded nulls was not pinned by tests; the interpreted creator path filtered null unboxed carriers while generated code did not. Final round on the current head: both reviewers report no further actionable comments.
- ai_review_artifacts: Fory-guided reviewer: https://github.com/apache/fory/pull/4234#issuecomment-6953140699 ; independent general reviewer: https://github.com/apache/fory/pull/4234#issuecomment-6953141734 (both on head commit 193d2b84, final round, no further actionable comments)
- human_verification: see "Verification" below
- performance_verification: SET generated code unchanged; JMH JsonSerializationSuite on a shared host shows no difference beyond host drift (see "Benchmark")
- provenance_license_confirmation: all code written for this PR against the Apache Fory sources; no third-party code introduced

Verification

JDK 21.0.2, Windows 11 x86_64, base apache/main c8bb610:

  • java/ at 193d2b8: mvn -pl fory-json spotless:check checkstyle:check test: 1341 tests, 0 failures; spotless and checkstyle clean.
  • JsonNullHandlingTest from this branch run against apache/main sources: 8 failures (the new SKIP assertions, both codegen modes). decodedNullUnwrappedAndAny also fails on the first commit of this branch, before the Any/unwrapped fix.
  • Generated reader sources (FORY_CODE_DIR) inspected: the decoded-null test and the deferred unwrapped group creation appear only in readers of SKIP models.
  • docs/json: prettier clean for the changed files.

Does this PR introduce any user-facing change?

  • Does this PR introduce any public API change?
  • Does this PR introduce any binary protocol compatibility change?

Behavior change: under SKIP, a null returned by a codec for a non-null JSON value is now skipped instead of assigned or inserted. SET (the default) and FAIL are unchanged.

Benchmark

The JsonSerializationSuite model (eishay MediaContent, default SET, codegen on) does not reach any changed line: with SET the generated readers are textually identical to apache/main (the 1186 generated classes of JsonCreatorTest, JsonCollectionTest, JsonAnyPropertyTest and JsonUnwrappedTest, dumped with FORY_CODE_DIR and compared after normalizing class-number suffixes, show no difference), ArrayList fields keep their SET fast path, and List<String> uses the scalar collection codec. The changed interpreted loops (GenericCollectionCodec/ObjectCollectionCodec for non-ArrayList collections, GenericMapCodec, JsonFieldInfo object branch) gain one null comparison per value before an existing codec call.

JMH, JsonSerializationSuite.fory(To|From)Json(Bytes|String), JDK 21.0.2, Windows 11, 10 logical CPUs, -f 2 -wi 5 -w 2s -i 8 -r 2s, runs alternating base/patched, ops/ms:

Run Build FromJsonBytes FromJsonString ToJsonBytes ToJsonString
1 base 1543 ± 249 1529 ± 188 5389 ± 635 3783 ± 521
2 patched 1454 ± 214 1427 ± 241 4847 ± 846 3762 ± 632
3 base 1493 ± 227 1251 ± 385 4482 ± 494 3010 ± 298
4 patched 1046 ± 271 962 ± 67 3484 ± 511 2845 ± 413

The host was shared with other workloads during these runs: the write benchmarks, which this PR does not touch, drift down by the same proportion as the read benchmarks, and the error bars overlap across runs 1-3. I read this as no measurable difference, and would rerun on a quiet host if maintainers want numbers for the record.

🤖 Generated with Claude Code

pavel-ptashyts and others added 4 commits November 17, 2026 15:42
With onNullRead(SKIP) or onContentNullRead(SKIP), a Java null returned by
the selected codec for a non-null JSON token is now treated like an
explicit JSON null: the property keeps its current value (creator
arguments stay absent), and the collection element, reference-array
element, AtomicReferenceArray element, or map value is omitted. SET and
FAIL are unchanged.

Generated readers emit the null test only for SKIP properties, so
default SET code is unchanged. Reference arrays compact decoded nulls
after the read loop so graph-memory batch reservation stays ahead of each
batch's final element.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Under content SKIP, a null decoded by an Any value codec is no longer put
into the Any map or passed to the Any setter. Under property SKIP, an
unwrapped child property (field or creator argument) is decoded before
its group is created, so a decoded null does not publish an otherwise
absent group. SET keeps the original group-then-read order.

Also fix the read-side null handling guide, which still stated that codec
nulls are never filtered.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Interpreted creator reads filtered a null unboxed carrier under SKIP,
while generated readers and property paths store carriers as decoded.
Keep the decoded-null skip to the selected codec value only.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@pavel-ptashyts

Copy link
Copy Markdown
Contributor Author

AI review artifact: Fory-guided reviewer (final round)

  • Reviewer: Codex CLI gpt-6-astra, reasoning effort medium, fresh read-only session, prompted to follow AGENTS.md, .agents/ci-and-pr.md and .agents/languages/java.md
  • Reviewed: git diff c8bb6101..193d2b84 (branch head 193d2b8)
  • Result:
No further actionable comments.

Residual risks for `c8bb6101..193d2b84`:

- Review was static; no builds, tests, benchmarks, or linters were run.
- Default SET performance needs benchmark confirmation for the added interpreted-path branches.
- Tests cover both codegen modes, but the final unboxed creator-carrier adjustment lacks a dedicated regression test.

Review rounds

  1. 1109882: Fory-guided: unwrapped group materialized on decoded null; Any map/setter not filtered; guide contradiction. Independent: guide contradiction, AtomicReferenceArray missing in guide. Fixed in 1850d9a.
  2. 1850d9a: Fory-guided: no further actionable comments. Independent: SET/FAIL keep-decoded-null not pinned by tests. Fixed in 80b42ed.
  3. 80b42ed: Fory-guided: no further actionable comments. Independent: interpreted creator filtered null unboxed carriers, generated did not. Fixed in 193d2b8.
  4. 193d2b8: both: no further actionable comments.

@pavel-ptashyts

Copy link
Copy Markdown
Contributor Author

AI review artifact: independent general reviewer (final round)

  • Reviewer: Claude Code claude -p --model claude-opus-5-5 --effort medium, fresh read-only session, not pointed to .agents/ci-and-pr.md
  • Reviewed: git diff c8bb6101..193d2b84 (branch head 193d2b8)
  • Result:
No further actionable comments.

I read the whole `c8bb6101..HEAD` diff (code, docs and tests) and checked the read paths around it. I only read files; nothing was built or run.

- **Property paths:** the interpreted `JsonFieldInfo` default and custom-primitive branches now skip a codec null under SKIP. In generated code, `readResolvedField` covers ARRAY, MAP and non-canonical OBJECT properties, which is where every property with a custom codec ends up. The other generated cases (STRING, ENUM, COLLECTION, canonical object codecs) only use built-in codecs, which never return null for a non-null token.
- **Unwrapped groups:** an explicit JSON null is still consumed by `skipNullRead` before the new decode-first branch runs. The interpreted and generated readers make the same decisions, so a null from the codec does not create an otherwise absent group.
- **Creators:** `JsonCreatorFieldInfo` changed its methods from returning a value to taking the argument array. Nothing outside `ObjectCodec` calls them; the Kotlin module only uses the static checked helpers. Unboxed carriers are stored as decoded in the interpreted creator, generated creator and property readers alike.
- **Any values:** every `anyReader.read*` call in `ObjectCodec` is followed by `skipDecodedNull`. The generated reader uses the same global `onContentNullRead` setting as the interpreted one.
- **Containers:** the untouched read paths are only fed by built-in codecs that can't return null for a non-null token: `StringKeyMapCodec` and its subclasses, the typed-key map path, the untyped readers, and the direct collection and primitive array codecs. The non-null array and map variants only reject an explicit JSON null, so they behave the same as collections.
- **SET and FAIL:** the default path is unchanged. Every new branch is guarded by `onContentNullRead`/`onNullRead == SKIP`. The generated code for SET and FAIL is the same as before (the `Invoke` constructor defaults are equivalent), and the interpreted code only gains a cheap null check per value.
- **Tests:** `JsonNullHandlingTest` runs with codegen both on and off, across four input forms (Latin-1, UTF-16, UTF-8 bytes, stream). Before this change it asserted that a `"decode-null"` value was assigned under SKIP, and it now asserts the opposite, so the new tests would fail without the fix. The `reader == 1` special cases come from the extra `ignoredUnicode` member that form adds, not from different behavior.
- **Docs:** they match what the code does, including that FAIL rejects only a literal JSON null and that Any values follow the global content setting.

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.

[Java][JSON] SKIP null handling ignores a null returned by a property or element codec

1 participant