Skip to content

fix(#6180, #6176): a truncated batch upload is never served its own bytes again - #6215

Merged
lvca merged 2 commits into
mainfrom
issue-6180-truncated-batch-replay
Aug 15, 2026
Merged

lvca merged 2 commits into
mainfrom
issue-6180-truncated-batch-replay

Conversation

@lvca

@lvca lvca commented Aug 15, 2026

Copy link
Copy Markdown
Member

Two issues, one defect: POST /api/v1/batch could apply records the client never sent in that request.

What was happening

Issue5470BatchStreamStallIT.aBodyShorterThanItsContentLengthIsNotReportedAsSuccess has been red on main with
409 Conflict where it expects 408. #6180 read that correctly: 409 is the duplicate-key mapping, and the ids in
that payload are unique within it and unique in a fresh database, so reaching it means the records were inserted
twice. #6176 filed the same failure from the status-code end.

Measured before changing anything, by instrumenting the handler's body stream on a 100-record upload cut after
4600 bytes:

read  before=0    read=4600  head=[{"@type":"vertex",...,"id":3000000}|...]     <- the payload
available() threw java.io.IOException: UT000128: Remote peer closed connection before all data could be read
    at java.base/sun.nio.cs.StreamDecoder.inReady(StreamDecoder.java:430)
read  before=4600 read=8192  head=[POST /api/v1/batch/graph?vertexBatchSize=1 HTTP/1.1|Host: 1]

The second read is the connection's own request head. The chain:

  1. UndertowInputStream.readIntoBufferNonBlocking allocates a pooled buffer before the channel read that
    throws, and does not release it on the way out. The buffer stays on the stream, holding whatever the pool last
    left in it - identified here by object identity as the very buffer that held this connection's request head and
    body (limit 16364 = capacity, zeros past byte 4801).
  2. The next read() sees a non-null buffer and is served from it without touching the channel at all.
  3. What reaches the failure is InputStreamReader: it probes with available() between decodes
    (StreamDecoder.inReady) and swallows the IOException. The failure that should have ended the load
    disappears, and the replay is parsed as payload.

Sent in two record-aligned chunks, the replay is whole records: reads of 8192 and 8172 bytes past the end of the
upload, starting at the exact record the second chunk started with, and 40284 bytes consumed against the 23920 the
client sent. On a type with a unique index those re-applied records collide and the load is answered 409 for a key
the client sent once. On a type without one - what a bulk load usually has - they duplicate rows and the load is
answered 200.

One correction to #6176's second claim: the "interrupted after 0 vertices and 0 edges" log line quoted there
belongs to the sibling test stalledClientIsCutOffAndAnswered, which legitimately reports 0 - it sends a single
vertex with the default vertexBatchSize, so nothing has been flushed when the client goes silent. The resume
counts were never lost.

The fix

PostBatchHandler.CountingInputStream ends a body that has failed:

  • the first failure is remembered, whether it surfaces on a read or on a probe;
  • the probe answers -1 - Undertow's own "the body is finished", which bodyEndedEarly/drainAlreadyBuffered
    already read - so the decoder stops asking instead of swallowing anything;
  • every later read is refused with the recorded failure itself, so the load takes the truncated-body path it was
    always meant to take: 408, the counts needed to resume, and not one record the client did not send.

The follower-to-leader forwarding path now reads through the same guarded stream, so a cut upload cannot relay a
replay of itself to the leader either.

Every answer carries bytesRead now, not only the successful one: on a truncated load that is where a client
learns how far the server got, and it is the number that says the server read no further than the client wrote.
The OpenAPI batch response and error schemas were completed to match what both bodies have carried since #5618
(bytesRead, linesRead, linesSkipped, verticesWithoutId).

Verification

  • PostBatchHandlerBodyFailureTest (new, 4 tests) drives the stream directly - the only way to reproduce a body
    that fails on a probe and then offers bytes anyway. 3 of the 4 go red with the guard removed; the fourth is
    the intact-body control.
  • Issue5470BatchStreamStallIT: the existing truncation test now asserts bytesRead, and fails without the fix
    with 20964 bytes read against the 4600 sent
    . A new test covers the record-aligned shape, where the replay
    carries whole records; its javadoc says plainly that it is the shape and not the detector, because which buffer
    the pool hands back is not under a test's control.
  • Green: Issue5470BatchStreamStallIT, Issue5470BatchErrorDeliveryIT, PostBatchHandlerIT,
    Issue5618BatchLineAccountingIT (48 tests); RemoteGraphBatchIT, OpenApiSpecGenerationIT,
    UngatedHandlerCrossDatabaseIT, UngatedHandlerPerTypeAclIT (33); PostBatchHandlerBodyFailureTest,
    PostBatchHandlerForwardRequestTest, CoreApiSpecTest (19).

Closes #6180, closes #6176.

…ytes again

POST /api/v1/batch could load records the client never sent in that request: its own request head, and a replay
of records it had already committed. On a type with a unique index the replay collided with what it duplicated,
and the load was answered 409 Conflict for a key the client had sent exactly once instead of the 408 and the
partial-commit counts a truncated upload is contracted to get (#6176). On a type without one - which is what a
bulk load usually has - it duplicated rows and answered 200.

Measured before changing anything, by instrumenting the body stream of a 100-record upload cut after 4600 bytes:

  read  before=0    read=4600  head=[{"@type":"vertex",...,"id":3000000}|...]
  available() threw java.io.IOException: UT000128: Remote peer closed connection before all data could be read
      at java.base/sun.nio.cs.StreamDecoder.inReady(StreamDecoder.java:430)
  read  before=4600 read=8192  head=[POST /api/v1/batch/graph?vertexBatchSize=1 HTTP/1.1|Host: 1]

The connection is what lies, and the reader is what asks it. UndertowInputStream.readIntoBufferNonBlocking takes
a buffer from the pool BEFORE the channel read that throws and does not give it back, so the buffer stays on the
stream holding whatever the pool last left in it - identified here by object identity as the very buffer that
held this connection's request head and body (limit 16364 = capacity, zeros past byte 4801). The next read is
served from it without the channel being touched at all. What reaches the failure is InputStreamReader, which
probes with available() between decodes (StreamDecoder.inReady) and SWALLOWS the IOException: the failure that
should have ended the load disappears, and the parser is handed the replay as payload. Sent in two record-aligned
chunks, that replay is whole records - reads of 8192 and 8172 bytes past the end of the upload, starting at the
exact record the second chunk started with, and 40284 bytes consumed against the 23920 the client sent.

CountingInputStream now ends a body that has failed. The first failure is remembered whether it surfaces on a
read or on a probe; the probe answers -1, which is Undertow's own "the body is finished" and exactly what the
handler's truncation check already reads, so the decoder stops asking instead of swallowing anything; and every
later read is refused with the recorded failure itself, which sends the load down the truncated-body path it was
always meant to take - 408, the counts needed to resume, and not one record the client did not send. A follower
relaying a batch to the leader reads through the same guarded stream, so a cut upload cannot relay a replay of
itself onward either.

Every answer now carries bytesRead, not only the successful one. On a truncated load that is where a client
learns how far the server got, and it is the number that says the server read no further than the client wrote:
Issue5470BatchStreamStallIT asserts it in both truncation tests, and the existing one fails without the fix with
20964 bytes read against the 4600 sent. The OpenAPI batch response and error schemas were completed to match what
both bodies have actually carried since #5618: bytesRead, linesRead, linesSkipped and verticesWithoutId.

Tests: PostBatchHandlerBodyFailureTest drives the stream directly, which is the only way to reproduce a body that
fails on a probe and then offers bytes anyway; 3 of its 4 tests go red with the guard removed (the fourth is the
intact-body control). The record-aligned IT is the shape rather than the detector - which buffer the pool hands
back is not under a test's control - and says so. Verified green: 4 batch IT classes (48 tests), 4 more that
touch the endpoint (33), and the handler and OpenAPI unit tests (19).

Closes #6180, closes #6176.
@mergify

mergify Bot commented Aug 15, 2026

Copy link
Copy Markdown
Contributor

Tick the box to add this pull request to the merge queue (same as @mergifyio queue).

  • Queue this pull request

@codacy-production

codacy-production Bot commented Aug 15, 2026 •

Copy link
Copy Markdown

Up to standards ✅

🟢 Issues 0 issues

Results:
0 new issues

View in Codacy

🟢 Metrics 10 complexity

Metric Results
Complexity 10

View in Codacy

🟢 Coverage 85.37% diff coverage

Metric Results
Coverage variation Report missing for 82db25a1
Diff coverage ✅ 85.37% diff coverage

View coverage diff in Codacy

Coverage variation details
Coverable lines Covered lines Coverage
Common ancestor commit (82db25a) Report Missing Report Missing Report Missing
Head commit (5382f09) 190567 137598 72.20%

Coverage variation is the difference between the coverage for the head and common ancestor commits of the pull request branch: <coverage of head commit> - <coverage of common ancestor commit>

Diff coverage details
Coverable lines Covered lines Diff coverage
Pull request (#6215) 41 35 85.37%

Diff coverage is the percentage of lines that are covered by tests out of the coverable lines that the pull request added or modified: <covered lines added or modified>/<coverable lines added or modified> * 100%

1 Codacy didn't receive coverage data for the commit, or there was an error processing the received data. Check your integration for errors and validate that your coverage setup is correct.

NEW Get contextual insights on your PRs based on Codacy's metrics, along with PR and Jira context, without leaving GitHub. Enable AI reviewer
TIP This summary will be updated as you push new changes.

@claude

claude Bot commented Aug 15, 2026

Copy link
Copy Markdown

Review

Solid fix, and unusually well-verified for a bug this subtle (pooled-buffer reuse across a failed non-blocking read is not something you can reliably reproduce in CI, so the direct unit test that fakes the "fails-on-probe-then-offers-stale-bytes" connection in PostBatchHandlerBodyFailureTest is the right way to pin this down deterministically, on top of the IT that demonstrates the real shape).

Correctness

  • The core fix is sound: refuseIfBodyFailed() guards both read() overloads, so once a failure is recorded (whether surfaced by a real read or discovered via available()), no further byte - stale or otherwise - can reach the parser. That's the actual hole closed; converting the probe's available() into -1 is just what lets the failure be discovered without InputStreamReader swallowing an exception first.
  • close() correctly stops treating a failed body as reusable (bodyFailure == null && (...)), so the connection is retired instead of pooled for the next request - important since draining a failed body proves nothing about its true state.
  • bodyEndedEarly()'s call into drainAlreadyBuffered() still calls in.available() (the raw, unwrapped stream) rather than this.available(). That looks intentional rather than a leftover oversight: this.available() deliberately erases the BROKEN vs END_OF_BODY distinction into a single -1, which drainAlreadyBuffered's caller (close()) actually depends on to decide whether the connection is reusable. Worth a one-line comment on drainAlreadyBuffered calling out why it bypasses the override, since it's easy for a future change to "simplify" that into this.available() and quietly reintroduce a connection-reuse bug.
  • Threading: CountingInputStream's fields (bodyFailure, bytesRead, endOfBody) aren't volatile. For the forwarding path, the JDK HttpClient's BodyPublishers.ofInputStream reads the stream from its own internal thread rather than the caller's. In practice this is safe because HTTP_CLIENT.send(...) blocks until the response completes, and that join provides the happens-before edge - but it's a pre-existing property of the class, not something introduced here, so not a blocker.

Design / reuse

  • Threading CountingInputStream through every response-building method instead of re-deriving bytesRead was the right call over, say, stashing it as a field elsewhere - keeps addLineAccounting as the single place that assembles the accounting fields, and the bytesRead move into that shared method removes the duplication that existed between the success path and the error paths.
  • Widening CountingInputStream from private to package-private purely so the test can drive it directly is a reasonable trade - it's still contained to the package, and the alternative (reflection, or duplicating the class in test scope) would be worse.

Tests

  • PostBatchHandlerBodyFailureTest is the strongest part of this PR - it isolates the exact interaction (a stream that fails on available() then serves stale bytes) without needing a real Undertow connection, and directly demonstrates the fix would regress if refuseIfBodyFailed() were removed.
  • The new Issue5470BatchStreamStallIT.aTruncatedUploadIsNotServedItsOwnBytesAgain is honestly self-aware in its javadoc about being "the shape and not the detector" since it depends on which buffer Undertow's pool happens to hand back - that's a good disclosure rather than a flaky test dressed up as deterministic. The companion assertion added to the existing aBodyShorterThanItsContentLengthIsNotReportedAsSuccess (bytesRead must equal bytes sent) is the one that reliably catches a regression, which is the right division of labor.
  • OpenAPI schema tests (CoreApiSpecTest) were updated in lockstep with the schema changes - good, since these are exactly the kind of change that silently drifts otherwise.

Nits

  • CountingInputStream.hasBodyFailed() is only called from the test, never from production code (isEndOfBody() has the same shape but is at least used in bodyEndedEarly()). Not a problem, just flagging it in case it was meant to replace a production check somewhere and that wire-up got dropped.
  • The javadoc on available()/close()/the class itself is quite dense (multi-paragraph, with inline evidence/measurements). It matches the file's existing style, so not asking for a change, just noting it reads more like an incident writeup than a comment in a few spots.

Security
No concerns - this closes a real integrity issue (bytes from a connection's own leftover buffer being applied as if they were payload), and the fix is a stricter guard, not a relaxation of one. The database-level authorization check ordering (checkAuthorizationOnDatabase before forwarding) is untouched by this change.

Nothing here blocks merging; the drainAlreadyBuffered/in.available() comment is the only suggestion I'd actually act on.

@codecov

codecov Bot commented Aug 15, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 82.92683% with 7 lines in your changes missing coverage. Please review.
✅ Project coverage is 69.98%. Comparing base (8b9ec35) to head (5382f09).
⚠️ Report is 3 commits behind head on main.

Files with missing lines Patch % Lines
...arcadedb/server/http/handler/PostBatchHandler.java 79.41% 6 Missing and 1 partial ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main    #6215      +/-   ##
==========================================
- Coverage   70.00%   69.98%   -0.02%     
==========================================
  Files        1836     1836              
  Lines      158151   158224      +73     
  Branches    33370    33384      +14     
==========================================
+ Hits       110717   110738      +21     
- Misses      33578    33630      +52     
  Partials    13856    13856              

☔ 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.

@lvca lvca self-assigned this Aug 15, 2026
@lvca lvca added this to the 26.9.1 milestone Aug 15, 2026
@lvca
lvca merged commit 12468cb into main Aug 15, 2026
14 checks passed
@lvca
lvca deleted the issue-6180-truncated-batch-replay branch August 15, 2026 21:44
@claude

claude Bot commented Aug 15, 2026

Copy link
Copy Markdown

Review

Thorough fix with strong test coverage (unit tests that drive CountingInputStream directly plus the socket-level IT that reproduces the record-aligned replay). The root-cause writeup in the description and Javadoc is excellent and made this easy to verify. A few notes below, nothing blocking.

Correctness

drainAlreadyBuffered() bypasses the new failure-memoization guard (minor, currently benign)

drainAlreadyBuffered (line ~875) calls the raw in.available() field access instead of this.available(), so it does not go through the new bodyFailure-recording try/catch in the overridden available(). If this method were ever the first caller to observe a channel failure (before anything routed through the guarded available()/read() overrides), the IOException would be swallowed into BufferedDrain.BROKEN locally without ever setting bodyFailure on the stream. A later, separate call to the public available() on the same (already-poisoned, per the pooled-buffer bug this PR fixes) underlying stream could then get served stale bytes without exception and without bodyFailure being set, since bodyFailure is still null at that point - i.e., a narrower instance of the exact bug being fixed here.

In the current code this looks unreachable: both CsvBatchRecordStream and JsonlBatchRecordStream always wrap the CountingInputStream in an InputStreamReader first, so any real channel failure is always observed by the guarded available()/read() override before bodyEndedEarly()/close() ever call drainAlreadyBuffered(). But that's an implicit invariant, not an enforced one - worth either a one-line comment noting the dependency, or (more robustly) having drainAlreadyBuffered() route its probe through this.available()/this.read() so the guard applies uniformly regardless of call order.

Style / consistency

Doc formatting nit - docs/release-26.9.1.md: the new section ends with two issue-reference lines on consecutive lines with no blank line separating them from the following ## heading:

[#6180](https://github.com/ArcadeData/arcadedb/issues/6180)
[#6176](https://github.com/ArcadeData/arcadedb/issues/6176)
## A materialized-view refresh is one transaction...

Every other multi-issue entry in this file uses one line with comma-separated links (e.g. [#6040](...), [#6041](...)), and every section elsewhere has a blank line before the next ##. Worth conforming to the existing convention for consistency, even though CommonMark parses the heading fine either way.

Test coverage

Coverage looks solid:

  • PostBatchHandlerBodyFailureTest isolates the exact failure mode (probe fails, stale buffer offered) without depending on Undertow's actual pooling behavior - good, since that behavior isn't test-controllable.
  • The updated Issue5470BatchStreamStallIT asserts bytesRead on the pre-existing truncation test and adds a record-aligned variant, with clear javadoc explaining why the new test is "the shape and not the detector."
  • CoreApiSpecTest was updated to match the schema additions.

One thing I didn't see covered: a test where the forwarding path (forwardBatchToLeader) hits a body failure mid-relay - PostBatchHandlerForwardRequestTest is mentioned as green in the PR description but the diff doesn't show new assertions there for the guarded-stream behavior specifically. If that's already covered by existing assertions in that class, disregard.

Nothing else flagged

No security concerns (the fix tightens data integrity guarantees, doesn't loosen any), no performance concerns (the guard is O(1) per call and only relevant on the failure path), and the CountingInputStream visibility widening to package-private is scoped correctly for the new test.

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

Labels

None yet

Projects

None yet

1 participant