Skip to content

Fix fastjson2 concurrent ref deserialization - #16369

Open
goutamadwant wants to merge 2 commits into
apache:3.3from
goutamadwant:fix/dubbo-16368-fastjson2-concurrent-ref
Open

Fix fastjson2 concurrent ref deserialization#16369
goutamadwant wants to merge 2 commits into
apache:3.3from
goutamadwant:fix/dubbo-16368-fastjson2-concurrent-ref

Conversation

@goutamadwant

Copy link
Copy Markdown

What is the purpose of the change?

Fixes #16368.

Fastjson2 JSONB deserialization can lose nested fields when multiple threads deserialize the same $ref-heavy payload for the same target class at the same time. In the failing case, shared lists referenced by multiple child objects can become null after concurrent deserialization.

This change routes both FastJson2ObjectInput#readObject overloads through a shared helper and synchronizes the fastjson2 parse per requested target class. The lock is backed by ClassValue, so it does not retain application classes or classloaders, and unrelated DTO classes can still deserialize concurrently.

The regression test serializes an object graph with shared nested lists, verifies a single read succeeds, then repeatedly deserializes the same payload from 200 threads while clearing fastjson2 reader caches between rounds. Without the fix, the test reports a non-zero count of null nested fields.

Tests:

  • Focused repro: FastJson2SerializationTest#testConcurrentReadObjectWithReferences
  • Targeted slice: FastJson2SerializationTest,TypeMatchTest
  • Surefire result: 807 tests, 0 failures, 0 errors, 0 skipped

Checklist

  • Make sure there is a GitHub_issue field for the change.
  • Write a pull request description that is detailed enough to understand what the pull request does, how, and why.
  • Write necessary unit-test to verify your logic correction.
  • Make sure GitHub actions can pass.

@codecov-commenter

codecov-commenter commented Jul 3, 2026

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 70.00000% with 3 lines in your changes missing coverage. Please review.
✅ Project coverage is 60.87%. Comparing base (d0bf5c3) to head (294e363).
⚠️ Report is 1 commits behind head on 3.3.

Files with missing lines Patch % Lines
...mmon/serialize/fastjson2/FastJson2ObjectInput.java 70.00% 1 Missing and 2 partials ⚠️
Additional details and impacted files
@@            Coverage Diff            @@
##                3.3   #16369   +/-   ##
=========================================
  Coverage     60.86%   60.87%           
- Complexity    11763    11772    +9     
=========================================
  Files          1953     1953           
  Lines         89262    89266    +4     
  Branches      13471    13470    -1     
=========================================
+ Hits          54331    54337    +6     
- Misses        29329    29349   +20     
+ Partials       5602     5580   -22     
Flag Coverage Δ
integration-tests-java21 32.15% <70.00%> (+0.04%) ⬆️
integration-tests-java8 32.24% <70.00%> (+0.08%) ⬆️
samples-tests-java21 32.19% <70.00%> (+0.04%) ⬆️
samples-tests-java8 29.81% <0.00%> (+0.01%) ⬆️
unit-tests-java11 59.08% <60.00%> (-0.03%) ⬇️
unit-tests-java17 58.55% <60.00%> (-0.05%) ⬇️
unit-tests-java21 58.58% <60.00%> (-0.02%) ⬇️
unit-tests-java25 58.53% <60.00%> (-0.01%) ⬇️
unit-tests-java8 59.09% <60.00%> (-0.01%) ⬇️

Flags with carried forward coverage won't be shown. Click here to find out more.

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

zrlw

This comment was marked as outdated.

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Pull request overview

This PR addresses a fastjson2 JSONB concurrency issue where $ref-heavy payloads can deserialize incorrectly under multi-threaded access, leading to lost nested fields (e.g., shared lists becoming null). The fix introduces a synchronized parsing path in FastJson2ObjectInput and adds a regression test to reproduce the concurrent $ref deserialization failure.

Changes:

  • Route both FastJson2ObjectInput#readObject overloads through a shared parseObject(...) helper.
  • Synchronize fastjson2 JSONB parsing using a per-Class lock (ClassValue) to prevent concurrent corruption.
  • Add a concurrency regression test that stresses $ref resolution under high thread counts and cache resets.

Reviewed changes

Copilot reviewed 2 out of 2 changed files in this pull request and generated 3 comments.

File Description
dubbo-serialization/dubbo-serialization-fastjson2/src/main/java/org/apache/dubbo/common/serialize/fastjson2/FastJson2ObjectInput.java Adds synchronized parse helper guarded by a ClassValue lock to avoid concurrent $ref corruption.
dubbo-serialization/dubbo-serialization-fastjson2/src/test/java/org/apache/dubbo/common/serialize/fastjson2/FastJson2SerializationTest.java Adds a regression test for concurrent $ref deserialization and cache-clearing repro.

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

Comment on lines +714 to +732
for (int i = 0; i < threadCount; i++) {
Thread thread = new Thread(() -> {
try {
barrier.await();
if (countNullIds(serialization, url, bytes) > 0) {
roundNullTasks.incrementAndGet();
}
} catch (Throwable throwable) {
failure.compareAndSet(null, throwable);
} finally {
endLatch.countDown();
}
});
thread.start();
}
endLatch.await();
if (failure.get() != null) {
throw new AssertionError("Concurrent deserialization failed", failure.get());
}
Comment on lines +714 to +716
for (int i = 0; i < threadCount; i++) {
Thread thread = new Thread(() -> {
try {
Comment on lines +179 to +181
private <T> T parseObject(byte[] bytes, Class<T> cls, Fastjson2SecurityManager.Handler securityFilter) {
synchronized (getParseLock(cls)) {
if (securityFilter.isCheckSerializable()) {

@zrlw zrlw left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

fastjson2 loses fields "when initializing readers concurrently for the first time". Once the reader cache is warmed, subsequent concurrent decodes are safe. A better-fitting fix:
AtomicBoolean warmed — take the lock only until warmed flips to true, then no-op the lock path.

@SuppressWarnings("unchecked")
private void clearObjectReaderCache() throws Exception {
ObjectReaderProvider provider = JSONFactory.getDefaultObjectReaderProvider();
for (String fieldName : new String[] {"cache", "cacheFieldBased"}) {

@zrlw zrlw Jul 29, 2026

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Reflecting on internal fields means the test's effectiveness depends on the specific fastjson2 version. When fastjson2 renames cache in a point release, this test will fail.

Options:

Run each round in a fresh classloader / JVM to get a clean provider,
Explicitly document that this test is meaningful only within a specific fastjson2 version range.

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

Labels

type/bug Bugs to being fixed

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Bug] Concurrent deserialization with $ref references produces null fields in FastJson2Serialization

4 participants