Nested WritableJson.toByteArray on the same thread corrupts both results
Spring Boot 4.2.0-SNAPSHOT, main at commit f2abe77da5, reproduced on JDK 25.0.5 and 17.0.20.1.
With structured logging configured for both console and file output (for example logging.structured.format.console=ecs, logging.structured.format.file=logstash, logging.file.name=app.log), log one event whose key-value value, or a member added through a StructuredLoggingJsonMembersCustomizer, has a toString() that itself logs on the same thread. The console line for the outer event comes out as only the tail of its JSON, something like ...0"} with everything before that missing, and the start of the outer event's JSON turns up stitched onto the front of the nested event in the file output instead. Nothing throws. We saw this on both Logback and Log4j2.
Minimal reproduction, no logging involved, at the WritableJson level:
WritableJson inner = (out) -> out.append("BBB");
WritableJson outer = (out) -> {
out.append("AAA");
byte[] innerBytes = inner.toByteArray(StandardCharsets.UTF_8);
System.out.println("inner: " + new String(innerBytes, StandardCharsets.UTF_8));
out.append("CCC");
};
System.out.println("outer: " + new String(outer.toByteArray(StandardCharsets.UTF_8), StandardCharsets.UTF_8));
Expected: inner: BBB and outer: AAACCC.
Actual: inner: AAABBB and outer: CCC. The inner call picks up everything the outer call had already written as if it were its own output, and the outer call loses it.
The same thing happens going through JsonWriter: with JsonWriter.standard().write(value).toByteArray(UTF_8), where value.toString() itself computes JsonWriter.standard().write("inner").toByteArray(UTF_8) and returns X, the inner bytes come out as ""inner" and the outer bytes come out as X".
Mechanism: WritableJson.toByteArray(Charset) uses one AppendableByteArray cached per thread, keyed by charset (AppendableByteArray.get(Charset)). If a second toByteArray call with the same charset starts on the same thread while the first call is still writing, both calls get handed the same cached instance. The inner call reads back whatever the outer call had appended so far as if it were its own output, and its finally { reset(); } then clears the buffer out from under the still-running outer call, so everything the outer call wrote before the nested call started disappears.
This is reachable because of how the buffer is cached, not because of anything new. Before commit 2fffebe214 (which introduced AppendableByteArray to fix gh-49428's GC pressure), each toByteArray call built its own ByteArrayOutputStream and writer, so a nested call had nothing shared to see. The per-thread cache is what makes the two calls collide now. One way to fix it: have AppendableByteArray.get mark the cached instance as in use while a call is in flight, and hand a nested call on the same thread a temporary instance instead of the cached one.
One thing worth flagging for whoever looks at a fix: if the console and file appenders have different log level thresholds, part of a console-only event's bytes can end up only in the file output, or vice versa, since the corruption happens before either appender does its own formatting.
@dgomesbr could you please assign the PR to me
From the run that I did here is the possible solution that I would like to propose for the same:
The issue appears to be caused by reentrant calls to WritableJson.toByteArray() sharing the same thread-local AppendableByteArray instance. A possible fix would be to introduce an inUse flag in AppendableByteArray to track buffer ownership. If the cached buffer is already in use, nested calls should receive a temporary instance instead of reusing it. The buffer should also be reset and released in a finally block to ensure proper cleanup, even when serialization fails. This would prevent nested calls from corrupting the outer serialization while preserving the existing thread-local caching optimization for normal sequential calls. Regression tests covering nested serialization, different charsets, and exception handling would help verify the fix.
One more regression case is a surrogate pair split across appends. The pending highSurrogate state can join code units from two different serializations:
byte[][] innerBytes = new byte[1][];
WritableJson inner = out -> out.append('\uDE00');
WritableJson outer = out -> {
out.append('\uD83D');
innerBytes[0] = inner.toByteArray(StandardCharsets.UTF_8);
out.append('\uDE00');
};
byte[] outerBytes = outer.toByteArray(StandardCharsets.UTF_8);
With isolated state, the inner bytes should be 3f (replacement for the lone low surrogate) and the outer bytes f0 9f 98 80 (the complete pair). The current shared buffer produces the reverse: inner f0 9f 98 80, outer 3f. This also exercises the pending character state, so it would catch a fix that only saves and restores the accumulated bytes.
@likhithrajuuu go ahead and open the PR.
Your direction matches what I was thinking when I filed this: an in-use flag on the cached instance, a temporary one for the nested call, cleanup in a finally block so a failed serialization doesn't leave anything dangling. @krotname's surrogate-pair case above is a real gap in that design as stated. Whatever you end up saving and restoring (or whatever gets moved onto the temporary instance) needs to include that pending character, not just the accumulated bytes.
@likhithrajuuu Please hold off on a PR until we've triaged the issue. Once we've accepted it then contributions are welcome as long as it's not assigned.
@philwebb once you have triaged the issue. Please assign this bug to me Thanks!