Skip to content

fix(#8674): end a streamed batch relay cut by the follower's body cap with the leader's in-band 413 - #8720

Merged
robfrank merged 4 commits into
mainfrom
fix/8674-streamed-batch-relay-cap-terminal-line
Oct 1, 2026
Merged

robfrank merged 4 commits into
mainfrom
fix/8674-streamed-batch-relay-cap-terminal-line

Conversation

@robfrank

@robfrank robfrank commented Sep 30, 2026 •

Copy link
Copy Markdown
Collaborator

Closes #8674

When a streamed (Accept: application/x-ndjson) batch upload sent to a follower is cut by the follower's arcadedb.server.httpBodyContentMaxSize after the leader has already started answering, relayNdJsonFromLeader now writes the in-band terminal line the leader writes for the same refusal: {"error": {..., "status": 413, "exception": "io.undertow.server.RequestTooBigException", "exceptionArgs": "<cap>", "verticesCreated", "edgesCreated", "partialCommit"}}. It is built by the same classifyError/buildErrorBody and carries the counters of the last relayed progress line. The follower's log now names this node's cap instead of blaming the leader relay. If the leader's answer already ends in a terminal line (summary or error), the relay adds nothing. The check asks the stream (CountingInputStream.refusedOverCap()) and not the failure, so it covers both a failed read and a leader answer that simply ends.

Important finding: this sub-path cannot be reached on the JDKs we ship with. On JDK 21, 25 and 27, an HTTP/1.1 HttpClient exchange hands back the response only after the request body has been published whole, even when the leader has already sent 200 and a progress line. So a cap trip always fails the send itself, and #8161's real 413 answers it before relayNdJsonFromLeader runs. I verified this with a raw-socket probe on all three JDKs, and theJdkClientHandsBackTheResponseOnlyOnceTheUploadIsPublished now pins it. The relay change is therefore a defense for the day that JDK behavior changes, and it is tested by driving the relay directly with a scripted leader answer. The same JDK behavior makes the existing comments in forwardBatchToLeader wrong ("the send completes as soon as the leader's response HEADERS arrive"). The consequence is that proxyBatchReadTimeout caps the whole streamed upload through a follower and progress lines are not incremental across the hop. That is filed as #8719, and the inline comment now points to it.

Test plan

  • Issue8674StreamedRelayBodyCapTerminalLineTest (9 tests after review cycles: the original 6 plus fragment, line-after-terminal, and summary+blank-line cases; real Undertow exchange, scripted leader answer):
    • cap trip, then aborted read -> progress line followed by one in-band 413 line with counters 7/0, partialCommit: true
    • cap trip, then the leader's answer ends cleanly -> same 413 line
    • cap trip before any progress line -> 413 line, counters 0, partialCommit: false
    • leader already wrote a terminal line -> no second terminal line
    • leader failure on a body under the cap -> no terminal line (existing contract kept)
    • JDK pin: the response is withheld while the upload is pending and delivered once it is published
  • With the fix disabled (tooBig = null), the 3 cap-trip tests fail and the 3 guards pass
  • Related suites green (124 tests): Issue8161*, Issue7738*, Issue8325*, Issue7526*, Issue7508*, Issue7603*, Issue8393*, Issue8486*, Issue8343*, PostBatchHandler*, PostBatchHandlerIT, NdJsonResultStream*, HardcodedTestServerPortsTest
  • ha-raft streaming batch ITs not run locally (the relay only behaves differently when the body was refused over the cap)

Coverage

Invariant: a streamed relay whose upload this node's cap refused never ends without a terminal line, and it never gets two.

Entry point Status
relayNdJsonFromLeader, read fails after the cap trip fixed here, tested
relayNdJsonFromLeader, clean EOF after the cap trip fixed here, tested
relayNdJsonFromLeader, leader already wrote a terminal line fixed here (no duplicate), tested
forwardBatchToLeader, cap trips before the response is handed back (every case on JDK 21/25/27) already covered by #8161 (Issue8161FollowerForwardBodyCapTest)
Other NDJSON relays reading a capped CountingInputStream none. grep -rn -e refusedOverCap -e relayNdJson -e "new CountingInputStream" server/src/main ha-raft/src/main finds only PostBatchHandler

Known gaps

Adversarial pass

The skill's Phase 1.5 subagent could not be spawned (no subagent tool in this run's toolset), so this was a self-review:

Review cycles

Cycle Head Changes claude review
1 7873815 initial fix + tests no blockers. Asked for counters from the last progress line rather than a trailing fragment (could misreport partialCommit: false), FINE log of the relay failure, no null guard
2 db08516 counters tracked per progress line, fragment test, FINE log, null guard dropped no blockers. Asked for a trailing blank line not to defeat terminal detection, no fragile {"progress" prefix gate, no 413 write when the client is gone, test lines from the real NdJsonResultStream, a summary terminal case
3 bd129bf per-event ended tracking (blank lines ignored), prefix gate removed, clientGone skips the write, leader-built test lines, summary+blank test no blockers. Asked for a sticky ended, leader-expiry kept in the cap log, comment tidy-up, "see #8719" on the pin assertion
4 d818474 sticky ended + test, expiry in the cap log, comments moved, pin message no blockers. Main suggestion: gate the per-line JSON parse with a cheap prefix check (see Deferred)

Deferred items

Not applied because max cycles was reached; left for the developer:

Final state

max-cycles-reached. Every review said nothing blocks the merge. One performance suggestion is deferred (above).

🤖 Generated with Claude Code

Summary by CodeRabbit

  • Bug Fixes
    • Oversized streamed batch uploads now receive a clear 413 error with the latest acknowledged progress counters, when available.
    • Prevented duplicate terminal error responses when the leader has already sent a final event.

… with the leader's in-band 413

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
@mergify

mergify Bot commented Sep 30, 2026 •

Copy link
Copy Markdown
Contributor

This pull request does not currently match the merge queue conditions, so it cannot be queued from here. The box comes back if it matches again.

@coderabbitai

coderabbitai Bot commented Sep 30, 2026 •

Copy link
Copy Markdown

Review in Change Stack →

Navigate logical layers of code changes, visualize relationships, and explore their blast radius.

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Advanced

Run ID: 5c8e9318-71af-4006-9462-eb1e0a5d6937

📥 Commits

Reviewing files that changed from the base of the PR and between 2fa02b3 and d818474.

📒 Files selected for processing (2)
  • server/src/main/java/com/arcadedb/server/http/handler/PostBatchHandler.java
  • server/src/test/java/com/arcadedb/server/http/handler/Issue8674StreamedRelayBodyCapTerminalLineTest.java

Included review availability: This review used your included allowance. Your plan provides up to 4 included reviews per hour; 1 remain after this review.


📝 Walkthrough

Walkthrough

The streamed batch relay now detects when the follower’s body-size cap interrupts a request. It tracks leader progress and terminal events, and writes an in-band 413 error when the cap is reached before a terminal event.

Changes

Streamed batch relay

Layer / File(s) Summary
Relay cap refusal and terminal handling
server/src/main/java/com/arcadedb/server/http/handler/PostBatchHandler.java, server/src/test/java/com/arcadedb/server/http/handler/Issue8674StreamedRelayBodyCapTerminalLineTest.java
The relay receives the request-body counter, tracks progress and terminal lines, and writes an in-band 413 when the follower’s cap is reached before a terminal line. Tests cover progress counters, terminal-line handling, leader read outcomes, under-cap failures, and response timing.

Priority: ➖ Normal

Estimated code review effort: 3 (Moderate) | ~25 minutes

Change: Bug fix · Severity of issue fixed: Medium

Suggested reviewers: lvca

Merge Risk: ⚪ Minimal · up to d8184

The relay adds a separately framed 413 without an identified merge-blocking regression. The change is mergeable after normal checks; current JDK response timing still limits live exercise of this path.

Security Architecture Review

Security architecture risk: 🔵 Low · up to d8184

The change preserves database authorization and upload-size enforcement while improving refusal reporting. No introduced security vulnerability was established. Remaining uncertainty concerns future runtimes that deliver responses during upload and client handling of a terminal error without a consistency bookmark.

Retained concerns
No architecture-level concerns identified.

Security review details

Security Blast Radius

  • inferred — The assessed exposure is an authenticated batch upload to a database the caller is authorized to access, involving the receiving follower, its selected leader, and that request’s partial mutations. The reviewed delta does not expand database authority or introduce another forwarding destination.

Trust Boundaries and Controls

  • observed — Attacker-supplied upload bytes remain behind the receiving node’s configured body cap. Forwarding still requires an authenticated username and cluster token, and carries that identity to the leader. The new error handling queries the recorded refusal; it does not disable the cap or grant additional authority.

Resilience and Maintainability Implications

  • observed — The relay retains bounded leader reads and client writes with resource closure. Client-write failure suppresses an additional refusal attempt. Other relay failures still leave an incomplete stream rather than manufacturing a successful terminal response, preserving the existing failure-containment contract.

Hardening Proposals

  • proposed — Before enabling a runtime that returns responses during upload, establish ordering between request-body termination and terminal-response selection, including a cap refusal arriving after response EOF. Also establish client recovery semantics when the follower-generated terminal error has no leader consistency bookmark. These are compatibility safeguards, not verified vulnerabilities.
🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 50.00% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 36 functions across 2 files. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly identifies issue #8674 and summarizes the primary change: adding an in-band 413 response when the follower body cap terminates a streamed batch relay.
Description check ✅ Passed The description provides a detailed change summary, motivation, related issues, test coverage, known gaps, and additional implementation notes. It does not reproduce every template heading or explicit…
Linked Issues check ✅ Passed The implementation meets #8674. relayNdJsonFromLeader checks CountingInputStream.refusedOverCap(), logs the local body-size cap, and appends an in-band 413 line built with classifyError and `bui…
Out of Scope Changes check ✅ Passed The changes stay within #8674. The production changes implement the streamed relay terminal-line and local-cap behavior. The test fixture and JDK response-timing test support coverage and explain why …
  • Fix all pre-merge checks with AI
✨ Finishing Touches 💡 1
📝 Generate docstrings 💡
  • Commit to this branch
  • Create a new PR
🧪 Generate unit tests (beta)
  • Commit to this branch
  • Create a new PR

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@codacy-production

codacy-production Bot commented Sep 30, 2026 •

Copy link
Copy Markdown

Up to standards ✅

🟢 Issues 0 issues

Results:
0 new issues

View in Codacy

🟢 Metrics 22 complexity

Metric Results
Complexity 22

View in Codacy

🟢 Coverage 85.71% diff coverage · -6.02% coverage variation

Metric Results
Coverage variation ✅ -6.02% coverage variation
Diff coverage ✅ 85.71% diff coverage

View coverage diff in Codacy

Coverage variation details
Coverable lines Covered lines Coverage
Common ancestor commit (2fa02b3) 200461 168972 84.29%
Head commit (d818474) 233091 (+32630) 182448 (+13476) 78.27% (-6.02%)

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 (#8720) 70 60 85.71%

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%

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 Sep 30, 2026

Copy link
Copy Markdown

Review of #8720

The change is small, well scoped and honest about its reach. The relay refactor keeps the existing contracts. Only the cap-trip branch changes, and the discrimination is made on the stream (refusedOverCap()) rather than on the exception. I found no blocking issues. A few points for consideration:

1. Counters come from the last line only (possible misreport)

writeRelayedCapRefusal takes verticesCreated/edgesCreated from lastLine. On a clean EOF, BufferedReader.readLine() returns a trailing partial line as if it were whole. That partial line is also relayed with a \n appended, so the comment "the relay only ever writes whole lines" is not strictly true for that case. The PR description notes the partial-line case and treats it as non-terminal, which is fine. But the same partial line then becomes lastLine, parseNdJsonLine returns null, and the 413 line reports verticesCreated: 0, partialCommit: false even though earlier progress lines reported real counts. A client that trusts partialCommit: false may re-POST the whole load and create duplicates.

Suggested fix: keep the counters from the last line that parsed as a progress event (two longs updated while relaying), instead of re-parsing lastLine at the end. The terminal check can then use the last parseable event. Parsing each relayed line would add cost on the hot path, so a cheaper option is to parse only when the line starts with {"progress". The alternative is to fall back to the last good counters when the parse fails.

A test for "progress line, then a truncated line, then a clean EOF after the cap trip" would pin whichever you choose.

2. Log attribution when the cap trips and the client write also failed

If the loop's out.write fails because the client went away and tooBig != null, the severe "refused because the request body exceeded ..." log is emitted and the actual write failure is dropped. Since the 413 write then fails too, this is low impact. Logging relayFailure at FINE in that branch would keep the evidence.

3. Dead-on-arrival production path

The PR shows that this branch is unreachable on JDK 21, 25 and 27. The pin test theJdkClientHandsBackTheResponseOnlyOnceTheUploadIsPublished and the link to #8719 make that maintainable. One cost remains: relayNdJsonFromLeader is now package-private and takes a nullable body only for the tests and the hypothetical future. That is acceptable, but body != null ? ... : null suggests a caller that passes null. The only production caller passes a non-null CountingInputStream, so the null guard could go, or be covered by a test.

4. Tests

  • Coverage of the four relay outcomes (read failure, clean EOF, no progress line, leader already terminal) plus the under-cap guard is good, and the fail-without-fix check is appreciated.
  • The pin test asserts that a future does NOT complete within 2s. That is the lower-bound shape CLAUDE.md allows, so a GC stall can only make it more true. Fine.
  • ScriptedLeader and the Undertow helper use new ServerSocket(0, ...) and addHttpListener(0, ...). This mirrors Issue7738StreamingBatchRelayReadDeadlineTest and HardcodedTestServerPortsTest passes per the description, but CLAUDE.md steers away from ephemeral-range binds. If a shared helper exists for this (StaticBaseServerTest.allocateFreePorts), it may be worth moving both tests over together in a follow-up.
  • The JDK-behavior pin is sensitive to the JDK on the CI matrix. If CI ever adds a JDK where the behavior differs, this test failing is the intended signal, and the message says so.
  • The description lists the ha-raft streaming batch ITs as not run. The relay only diverges on the refused-body path, so the risk is low, but a CI confirmation before merge would be good.

Style

Overall this is a good, safe defensive fix. I would address point 1 before merge, since it is the only place the new line could state something false.

…ine, not a trailing fragment

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
@claude

claude Bot commented Sep 30, 2026

Copy link
Copy Markdown

Review of #8720

Overall this is a well-scoped change. The core logic reads correctly, the "ask the stream, not the failure" design is sound (bodyFailure is volatile, so the cross-thread read from the relay thread is safe), and the PR is very honest that the path is unreachable on current JDKs and pins that with a test. The progress line format assumed by PROGRESS_EVENT_PREFIX and the counter field names match what streamRecords emits (PostBatchHandler.java:748-753 via NdJsonResultStream.writeEvent). No blocking issues. A few points worth considering:

Potential bugs / edge cases

  1. Trailing blank line defeats the terminal-line check (PostBatchHandler.java, lastLine = line in the relay loop). lastLine is the last line relayed, so a leader answer of ...\n{"summary":{...}}\n\n (or any trailing empty line) leaves lastLine == "", isTerminalNdJsonLine returns false, and a second (413) terminal line is appended after the summary. That breaks the stated invariant "never gets two". The leader does not emit blank lines today, but a proxy or a future encoder change could. Tracking a boolean sawTerminal (set when a non-blank relayed line parses as summary/error) instead of only the last line is more robust than testing the last line, and it also lets you avoid keeping lastLine around. It would be worth a test with a trailing \n.

  2. A missing or misparsed progress line silently reports partialCommit: false. readProgressCounters only parses lines that start with the exact string {"progress", and a parse failure leaves the counters at 0. The consequence of a wrong 0/false is the one your own test Javadoc describes (the client re-sends a load the leader already partly committed). The prefix coupling to JSONObject's serialization (key order, no whitespace) is fragile. Suggestion: drop the startsWith gate and let parseNdJsonLine decide (it is one parse per line, and progress lines are already small and rare), or at minimum make the test drive a line produced by the real NdJsonResultStream.writeEvent("progress", ...) rather than a hand-written literal, so a format change breaks the test instead of the semantics.

  3. Write timeout when the client itself is gone. If the loop failed because out.write failed (client disconnect, recorded as relayFailure) and the cap also tripped, the code still logs at the SEVERE-ish user-error level ("The client's stream ends with an in-band 413") and then attempts another write through WriteBoundedOutputStream, which may block up to streamingWriteTimeout() again. It is an edge of an edge given the path is unreachable today, but skipping the refusal write (and the "ends with an in-band 413" log claim) when the failure was a client-side write failure would be more accurate. Distinguishing the read failure from the write failure in the two-step try would do it.

Style / conventions (CLAUDE.md)

  • The test's ScriptedLeader uses new ServerSocket(0, ...), and Undertow.builder().addHttpListener(0, ...). CLAUDE.md says never new ServerSocket(0) (ephemeral range) and to take ports from StaticBaseServerTest.allocateFreePorts. HardcodedTestServerPortsTest evidently does not flag it (it targets hand-picked ports and server fixtures), and Issue7738StreamingBatchRelayReadDeadlineTest probably does the same, so this is consistent with the neighbouring test, but it is worth double-checking against the letter of the rule.
  • Several final opportunities are used well. The new constants (PROGRESS_EVENT_PREFIX) are declared in the middle of the class after the methods that use them; moving them to the top with the other constants would match the file's layout.
  • Comment volume in the new production code is high (multi-paragraph block comments at the relay, the Javadoc on writeRelayedCapRefusal, plus two comments explaining that the path is unreachable). CLAUDE.md prefers short WHY-only comments. The "unreachable on JDK 21/25/27" note is valuable and non-obvious, but it is stated three times (Javadoc on the method, the comment above the method, the block above refusedOverCap, plus the edit in forwardBatchToLeader). One place would be enough.
  • relayNdJsonFromLeader widened from private to package-private for the test. That is acceptable and documented.

Performance

No concerns: the extra work is one startsWith per relayed line and a JSON parse only for progress lines, which are rare. lastProgress as a long[2] fits the "primitive arrays" guidance.

Tests

Good coverage of the matrix (read failure vs clean EOF, fragment, no progress yet, leader already terminal, under-cap failure) and the JDK pin test is a nice tripwire. The PR description says the 3 cap-trip tests fail with the fix disabled, which is the right validation. Gaps: the trailing-blank-line case above, and a case where a summary (not just error) terminal line is already present, since isTerminalNdJsonLine has two branches but only the error one is exercised. The theJdkClientHandsBackTheResponseOnlyOnceTheUploadIsPublished test relies on a 2s TimeoutException window and a 50ms trickle, so it is timing sensitive under load, but a TimeoutException there is the "expected to time out" shape the CLAUDE.md guideline says is safe, so I would not change it. The unchecked box for the ha-raft streaming batch ITs is worth running or having CI confirm before merge.

Nice work on filing #8719 for the consequence on proxyBatchReadTimeout.

… 413 line when the client is gone

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
@claude

claude Bot commented Sep 30, 2026

Copy link
Copy Markdown

Review

Overall this is a careful, well-scoped defensive fix. The reasoning about JDK reachability is documented honestly (#8719 filed, comment in forwardBatchToLeader corrected), the terminal-line invariant ("never none, never two") is clear, and the tests drive the real Undertow exchange rather than mocking the output path. No blockers from me. A few things worth a look:

Code (PostBatchHandler.relayNdJsonFromLeader)

  1. ended is not sticky. ended = trackRelayedEvent(line, lastProgress); is overwritten by every later non-blank line. If a leader ever wrote a terminal line followed by any non-terminal line (e.g. a stray progress line, or a fragment), ended flips back to false and the relay appends a second terminal line, which violates the "never two" invariant the PR states. ended |= trackRelayedEvent(...) (or if (trackRelayedEvent(...)) ended = true;) makes it match the invariant. It is unlikely in practice, but it is a one-token fix and worth a test line.

  2. A JSON parse per relayed line on the hot path, even when the cap never trips. trackRelayedEvent builds a full JSONObject for every line and allocates the exception on non-JSON. Progress lines are small so this is probably fine, but CLAUDE.md asks us to be GC-conscious. A cheap prefix check (line.startsWith("{\"progress\"") / "{\"summary\"" / "{\"error\"") before parsing, or only parsing when body.refusedOverCap() != null (tracking counters lazily is the only thing that needs every line, and that could use the same prefix gate), would keep the common path allocation-light.

  3. Lost diagnostics in two branches.

    • If tooBig != null && ended and there was a relay failure, the else if is skipped only when tooBig != null && !ended, so that case is fine. But tooBig != null && ended with a clean EOF logs nothing about the cap, which is fine, just noting it is intentional.
    • If the cap tripped AND the leader read expired (leaderBody.hasExpired()), the timeout WARNING from logRelayFailure is now skipped in favor of the cap message. The cap is a reasonable primary cause, but consider mentioning the expiry in the cap log when leaderBody.hasExpired(), so an operator does not lose the "leader was silent for N ms" signal.
  4. Style nits.

    • The // Package-private so ... line sits between the Javadoc and the method signature. Fine for Java, but it reads oddly; a short @VisibleForTesting-style note in the Javadoc, or leaving it out (package-private in an http.handler package is self-evident from the test), would be tidier.
    • The two 3-line comment blocks that were moved into logRelayFailure (the "200 and part of the stream are already on the wire..." paragraph) now trail after the last statement of the method, so they read like orphaned comments. Consider moving them above the logRelayFailure call sites or into the method Javadoc.
    • trackRelayedEvent swallowing RuntimeException with an empty-ish catch: JSONObject.getJSONObject on a wrong shape is the only expected case, so catching it is OK, but a progress.has(...)-free path using the default-value getters (getLong(key, default) already used) makes the try/catch nearly redundant. Only getJSONObject("progress") can throw.

Tests

  • Good coverage: cap + failed read, cap + clean EOF, fragment not resetting counters, no-progress case, both terminal shapes, and the under-cap negative control. The "fix disabled -> 3 tests fail, 3 guards pass" check in the PR body is exactly the right way to show they discriminate.
  • new ServerSocket(0, ...) in ScriptedLeader (and Undertow.addHttpListener(0, ...)) goes against the CLAUDE.md "Test server ports" rule ("never new ServerSocket(0), the ephemeral range"). The PR says HardcodedTestServerPortsTest is green, so it is evidently not flagged by the scanner, and for a socket that is only used within a single test the collision risk is low. Still, if StaticBaseServerTest.allocateFreePorts(n) can be used here, that would follow the rule literally; otherwise a short comment on why ephemeral binding is safe for this loopback-only, self-connected socket would pre-empt the question.
  • The JDK pin test will go red on a JDK upgrade by design. That is the intent and the Javadoc explains it well. Since it is a behavior probe of the JDK rather than of ArcadeDB, consider whether a failure there should block unrelated CI runs or be tagged/explained in the assertion message so whoever hits it knows it is a signal, not a regression. The as(...) messages already help; adding "see A streamed batch forwarded by a follower gets no response until the upload ends, so proxyBatchReadTimeout caps the whole upload and progress lines are not incremental across the hop #8719" to the assertion description would close the loop.
  • The 2s sent.get(2, SECONDS) expecting TimeoutException is fine per the wall-clock guidance (a short wait expected to time out; a stall only makes it more true).
  • HttpURLConnection in relay(...) is never disconnected and the conn has no explicit close on failure paths; the read-timeout bounds it, so this is only tidiness.

Untested area

The ha-raft streaming batch ITs were not run locally (noted in the PR). Since the relay change only alters behavior under cap trips, the risk is low, but the parse-per-line change (point 2) does touch every streamed relay, so it would be good to see those ITs green in CI before merge.

Security / performance

No security concerns: the 413 line is built by the existing classifyError/buildErrorBody (so production mode still hides detail) and carries only counters already relayed to the client. Performance impact is limited to point 2.

…ce signal in the cap log, tidy comments

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
@claude

claude Bot commented Sep 30, 2026

Copy link
Copy Markdown

Review of PR 8720

The change is small and well reasoned. The terminal-line invariant is enforced correctly: one 413 line when the cap trip cuts the relay, none when the leader already ended the stream, and none when the leader fails on a body under the cap. I read the diff only and did not run the tests.

What looks good

  • refusedOverCap() reads a volatile bodyFailure, so checking the stream rather than the exception is safe across the JDK publisher thread and the relay thread.
  • clientGone is separated from the leader read failure, so the 413 write is not attempted on a dead client connection. relayFailure is non-null whenever clientGone is true, so the log branch cannot NPE.
  • The ended flag is sticky, which the tests cover.
  • The fragment case is handled: a cut last line does not reset the counters, so partialCommit cannot wrongly tell a client that nothing was committed.
  • Error construction reuses classifyError and buildErrorBody, in line with the reuse principle in CLAUDE.md.
  • The JDK reachability finding is documented honestly in the PR body and code comments, and the follow-up is filed as issue 8719.

Suggestions

  1. Per-line JSON parse on the relay hot path. trackRelayedEvent runs new JSONObject(line) on every relayed line, whether or not the cap ever trips. Progress lines are small, but this adds garbage on every streamed batch through a follower, to serve a path the PR says is unreachable on JDK 21, 25 and 27. CLAUDE.md asks for a light GC footprint. Consider a cheap prefix or indexOf check on the event key, and parse only progress lines (needed for the counters). summary and error can be detected without a full parse. Tracking only when body.refusedOverCap() != null does not work, because the counters must be captured as lines pass.

  2. Dead-in-production code versus cost. About 140 lines are added for a path the PR itself shows cannot run today. That is defensible as defense in depth. If issue 8719 is fixed so the response arrives incrementally, this path becomes live and these tests become the safety net, which argues for keeping it. Please note in 8719 that the two are coupled.

  3. JDK canary test. theJdkClientHandsBackTheResponseOnlyOnceTheUploadIsPublished will go red on any JDK or CI matrix change that alters this behavior. Its message says "not an ArcadeDB regression", which is intentional, but it will look like a blocking failure to whoever bumps the JDK. Consider making that a deliberate signal (for example an assumeTrue on the known JDK range, or a tag) so it does not read as a flaky build.

  4. Minor cleanups.

    • The call site checks !line.isBlank() and parseNdJsonLine repeats the check. Drop one.
    • parseNdJsonLine has a single caller and can be inlined.
    • The cap-trip log call has a long format string and a nested ternary. Building the suffix as a local final String would read better.
  5. Log level. The cap-trip log uses getUserSevereErrorLogLevel(), while the sibling logRelayFailure uses WARNING. This is probably intended, since a size refusal is a user error. Please confirm it matches the level used by the 8161 refusal for the same condition.

  6. Coverage. The unit tests cover relayNdJsonFromLeader well: cap trip with failed read, cap trip with clean EOF, fragment, no progress, leader terminal line, line after terminal, summary plus blank line, and leader failure under the cap. The PR notes the ha-raft streaming batch ITs were not run locally. Please confirm CI ran them, since forwardBatchToLeader now passes body into a method whose visibility changed to package-private.

The code matches project conventions (final usage, brace-less single-statement ifs, no System.out, no fully qualified names). I have no blocking concerns. Suggestion 1 is the only one I would want addressed before merge.

@codecov

codecov Bot commented Sep 30, 2026

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 77.14286% with 16 lines in your changes missing coverage. Please review.
✅ Project coverage is 75.99%. Comparing base (2fa02b3) to head (d818474).
⚠️ Report is 1 commits behind head on main.

Files with missing lines Patch % Lines
...arcadedb/server/http/handler/PostBatchHandler.java 77.14% 10 Missing and 6 partials ⚠️
Additional details and impacted files
@@             Coverage Diff              @@
##               main    #8720      +/-   ##
============================================
- Coverage     76.01%   75.99%   -0.02%     
+ Complexity     3655     3652       -3     
============================================
  Files          2067     2067              
  Lines        200461   200521      +60     
  Branches      42233    42243      +10     
============================================
+ Hits         152371   152386      +15     
- Misses        31531    31576      +45     
  Partials      16559    16559              

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

@robfrank
robfrank merged commit f93873e into main Oct 1, 2026
36 of 37 checks passed
robfrank added a commit that referenced this pull request Oct 6, 2026
… with the leader's in-band 413 (#8720)

(cherry picked from commit f93873e)
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