Skip to content

feat(#5001): advertise and negotiate Bolt 5.0-5.4 with version-gated wire encoding - #5059

Merged
robfrank merged 11 commits into
mainfrom
feat/5001-bolt-5x-negotiation
Jul 7, 2026
Merged

robfrank merged 11 commits into
mainfrom
feat/5001-bolt-5x-negotiation

Conversation

@robfrank

@robfrank robfrank commented Jul 6, 2026

Copy link
Copy Markdown
Collaborator

What does this PR do?

Advertises Bolt 5.0 through 5.4 in the handshake (previously 3.0/4.0/4.4 only) and version-gates the outbound wire encoders so a 5.x driver connects natively instead of silently downgrading to 4.4. Closes conformance scenario PROTO-002.

The negotiated Bolt major version is the single switch, threaded through the per-message PackStreamWriter:

  • Graph elements - Node / Relationship / UnboundRelationship emit their Bolt 5.0 layouts (with element_id / start_node_element_id / end_node_element_id, field counts 4/8/4) when the negotiated major is >= 5, and stay byte-identical (3/5/3) on 4.x.
  • Temporals - a new BoltDateTimeStructure carries both epoch bases and emits the legacy 'F'/'f' signatures with the local epoch-second on 4.x, and the UTC 'I'/'i' signatures with the true UTC epoch-second on 5.0+.
  • Auth flow - a Bolt 5.1+ auth-less HELLO is now accepted and defers to the separate LOGON (resolving the standing NOTE (Bolt 5.1+) latent bug); AuthTokens.none() stays deliberately rejected. TELEMETRY (5.4) is acknowledged.
  • Handshake - SUPPORTED_VERSIONS advertises {5.4, 5.3, 5.2, 5.1, 5.0, 4.4, 4.0, 3.0}; the existing range-matching logic is unchanged, so 3.0/4.0/4.4 drivers negotiate exactly as before.

The change advertises 5.x and honors its wire deltas atomically, so the advertised Neo4j/5.26.0 compatible identity is honest up to Bolt 5.4. The 5.7/5.8 handshake manifest and 5.5/5.6 GQL notification metadata are intentionally out of scope (classic-handshake-only); manifest-capable drivers fall back to classic negotiation against the 5.4 ceiling.

Motivation

BoltNetworkExecutor.SUPPORTED_VERSIONS never advertised any Bolt 5.x version, so 5.x drivers worked only by an undocumented, untested silent downgrade to 4.4 - while the server still advertised a 5.26-compatible identity, setting a 5.x feature expectation the handshake did not honor. This closes that gap without lying to drivers: adding 5.x and honoring the element_id / UTC-datetime wire deltas land together, guarded by the existing real-driver type round-trip ITs.

Related issues

Additional Notes

Checklist

  • I have run the build using mvn clean package command (verified mvn -pl bolt verify: 275 unit + 110 IT green, including the real neo4j-java-driver ITs - BoltProtocolIT 78/78, temporal/type round-trip ITs - with no assertion changes needed)
  • My unit tests cover both failure and success scenarios (handshake negotiation matrix incl. no-match; version-gated struct field counts and datetime signatures at major 4 vs 5; auth-deferral truth table incl. none-rejected)

🤖 Generated with Claude Code

robfrank added 7 commits July 6, 2026 22:07
…UTC 'I'/'i')

BoltDateTimeStructure carries both epoch bases (local and true UTC) computed
at build time and picks signature + seconds at writeTo() from the writer's
negotiated Bolt major version. BoltStructureMapper.toTemporalStructure now
returns PackStreamStructure and builds BoltDateTimeStructure for the two
DateTime variants (offset and zone-id); Date/Time/LocalTime/LocalDateTime/
Duration are version-invariant and stay on BoltTemporalStructure.

Widened BoltTypeRoundTripTest's TYPE-010 assertion from BoltTemporalStructure
to PackStreamStructure since OffsetDateTime output is now a BoltDateTimeStructure.
Add BoltNetworkExecutor.deferAuthToLogon(), consumed in handleHello so a
Bolt 5.1+ HELLO with no auth fields is accepted and waits for the
subsequent LOGON message instead of being rejected as missing credentials.
Pre-5.1 HELLO-embedded auth and the explicit "none" scheme rejection are
unchanged. Also add BoltMessage.TELEMETRY (0x54) and TelemetryMessage,
acknowledged with SUCCESS so a Bolt 5.4 TELEMETRY message doesn't break
the connection.
Server now advertises Bolt 5.0-5.4 (Tasks 1-4), so PROTO-002 (5.x-only
driver negotiation) moves from expected-fail to passing in the shared
conformance spec. The e2e proto002_bolt5 xfail wrapper is unwrapped to
a direct assertion since it would now self-fail (assertExpectedFailure
fails loudly when the wrapped assertion passes). validate_spec.py's
REQUIRED_GAP_AREAS is narrowed to drop "protocol", since its only
#4890-tracked gap is closed (mirrors the existing precedent for
errors/type-roundtrip).
@mergify

mergify Bot commented Jul 6, 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

@gemini-code-assist gemini-code-assist Bot 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.

Code Review

This pull request implements Bolt 5.x version negotiation (supporting Bolt 5.0 through 5.4) and version-gates the outbound wire encoders (graph elements and datetime structures) based on the negotiated major version. It also introduces deferred authentication for Bolt 5.1+ handshakes and gracefully acknowledges TELEMETRY messages. Feedback on the changes points out that the version comparison logic in deferAuthToLogon is incorrect for future major versions (e.g., Bolt 6.0+) and should be performed lexicographically.

Important

The consumer version of Gemini Code Assist on GitHub is being sunset. Starting June 18, 2026, new organization installations will be blocked, and all code review activity will officially cease on July 17, 2026.
For more details on the timeline and next steps, please review the Help Documentation.

Comment on lines +1915 to +1920
static boolean deferAuthToLogon(final int protocolVersion, final String scheme, final String principal,
final String credentials) {
final int major = getMajorVersion(protocolVersion);
final int minor = getMinorVersion(protocolVersion);
return major >= 5 && minor >= 1 && scheme == null && principal == null && credentials == null;
}

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.

high

The version comparison logic in deferAuthToLogon is incorrect for future major versions (e.g., Bolt 6.0+). Comparing major >= 5 && minor >= 1 independently will return false if major is 6 and minor is 0. The comparison should be performed lexicographically: major > 5 || (major == 5 && minor >= 1).

  static boolean deferAuthToLogon(final int protocolVersion, final String scheme, final String principal,\n      final String credentials) {\n    final int major = getMajorVersion(protocolVersion);\n    final int minor = getMinorVersion(protocolVersion);\n    return (major > 5 || (major == 5 && minor >= 1)) && scheme == null && principal == null && credentials == null;\n  }

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Fixed in 5e490b7. The predicate is now lexicographic: `major > 5 || (major == 5 && minor >= 1)`.

Note on severity: this is a latent/defensive correctness fix rather than a live bug. SUPPORTED_VERSIONS caps the advertised ceiling at 5.4 and negotiateVersion() only selects an advertised version, so protocolVersion never reaches deferAuthToLogon with major >= 6 today (and there is no Bolt protocol 6.x - the 6.x is the driver version). The lexicographic form costs nothing and keeps the helper correct if a future change raises the ceiling. Added a regression case: deferAuthToLogon(0x00000006, null, null, null) asserts true.

@codacy-production

codacy-production Bot commented Jul 6, 2026 •

Copy link
Copy Markdown

Not up to standards ⛔

🔴 Issues 1 minor

Alerts:
⚠ 1 issue (≤ 0 issues of at least minor severity)

Results:
1 new issue

Category Results
CodeStyle 1 minor

View in Codacy

🟢 Metrics 19 complexity

Metric Results
Complexity 19

View in Codacy

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 Jul 6, 2026

Copy link
Copy Markdown

Code review: Bolt 5.0-5.4 negotiation (#5059)

Reviewed the full diff (executor, structures, temporal encoding, message parsing, tests, conformance). Overall this is a clean, well-scoped, and well-tested change. The core design decision - the negotiated major version as a single switch threaded through PackStreamWriter, with writeTo authoritative and SUPPORTED_VERSIONS/writer wiring flipped last and atomically - is sound and keeps 3.0/4.0/4.4 drivers byte-identical. Nice work.

Strengths

  • Temporal epoch handling is correct in both directions. Legacy F/f = wall-clock-as-UTC epoch (local.toEpochSecond(UTC)), I/i = true instant (local.toEpochSecond(offset)); the inbound decoders reconstruct the mirror of each. The mapper-driven round-trip tests (BoltDateTimeStructureTest) pin the epoch basis end-to-end, not just the factories in isolation - the right guard against a silent local-vs-UTC regression.
  • Version gating is localized. BoltNode/BoltRelationship/BoltUnboundRelationship only emit element_id when getBoltMajorVersion() >= 5; wire-level tests assert the tiny-struct field count (3->4, 5->8) and the element_id bytes.
  • Negotiation matrix is thorough - exact match, range fallback, no-match, 5.x-only drivers, mixed 5.x/4.4, padding/zero-stop, and the 5.1+ auth-deferral truth table (including none-rejected and 5.0-no-defer).
  • Bolt 5.0 (HELLO-embedded auth, no LOGON) vs 5.1+ (auth deferred to LOGON) is correctly distinguished by minor >= 1. Inbound temporal decoding stays version-agnostic (signature self-disambiguates), which is correct.

Minor findings (non-blocking)

  1. TELEMETRY is answered without a state guard. In processMessage, case TELEMETRY -> sendSuccess(Map.of()) responds SUCCESS regardless of connection state. Every other request handler either checks state or emits IGNORED while FAILED. Per the Bolt state machine, a server in FAILED must respond IGNORED to all requests except RESET; replying SUCCESS here could desync a strict driver. This is latent in practice - ArcadeDB never advertises a telemetry hint in HELLO metadata, so a compliant driver never sends TELEMETRY (as the TelemetryMessage Javadoc notes) - so severity is low, but folding it into the state-aware dispatch (IGNORED when FAILED) would be more correct and consistent with the surrounding handlers.

  2. getFieldCount() is now misleading for version-gated structs. BoltNode/BoltRelationship/BoltDateTimeStructure return the v4 base count (3/5/3) while writeTo emits the v5 count on major>=5. Only BoltPointStructure.writeTo consumes getFieldCount(), so this is harmless today, but a future struct relying on the interface method for its header would silently get the wrong count on v5. The comments do call writeTo authoritative; consider dropping getFieldCount() from these overrides (or documenting it as unused) to avoid a trap.

  3. BoltVersionNegotiationTest.negotiate() re-implements the production loop rather than exercising negotiateVersion(). Pragmatic given the method reads from a socket stream, but a divergence between the copy and the real loop (e.g. the outer break after a match) would not be caught. Extracting the pure matching step into a package-private helper that both the handler and the test call would remove the drift risk.

Nit

  • sendMessage allocates a fresh PackStreamWriter (+ ByteArrayOutputStream) per RECORD - pre-existing, not introduced here, but worth a follow-up given the GC-sensitivity emphasis in the codebase.

None of these block the merge. The correctness-critical paths (temporal epoch bases, field counts, negotiation, auth deferral) are right and backed by focused tests.

@claude

claude Bot commented Jul 6, 2026

Copy link
Copy Markdown

Review: Bolt 5.0-5.4 negotiation with version-gated wire encoding

Thorough, well-executed change. The single-switch design (negotiated major version threaded through PackStreamWriter) is clean, the 4.x path stays strictly additive/byte-identical, and the coupling with the existing real-driver round-trip ITs makes the "don't lie to the driver" invariant self-enforcing. Test coverage (negotiation matrix, per-struct field counts at major 4 vs 5, datetime signature/epoch switching, the auth-deferral truth table) is genuinely good. A few observations, none blocking.

Correctness / maintainability

  • getFieldCount() is now silently inconsistent with the wire on BoltNode/BoltRelationship/BoltUnboundRelationship. It returns the v4 base count (3/5/3) while writeTo emits 4/8/4 on Bolt 5. Today this is safe only because PackStreamWriter invokes writeTo (which is authoritative) and nothing consumes getFieldCount() on these outbound structs (BoltPointStructure is the only self-caller, on itself). It's documented in the comments, but it's a latent footgun: any future serialization path that trusts getFieldCount() would emit a header/field-count mismatch and corrupt the stream. Consider dropping the method from these structs (let writeTo be the sole contract) or having it assert it's unused. Flagging for future readers more than asking for a change.

  • TELEMETRY is acked in any connection state. In processMessage the TELEMETRY case sends SUCCESS unconditionally, with no state guard, so a client could send it pre-HELLO/pre-auth and receive SUCCESS. Harmless in practice (payload ignored, and a compliant driver only sends it when the server advertises telemetry hints, which ArcadeDB doesn't), but every other stateful handler gates on state; for consistency and defensiveness you may want to restrict the ack to READY.

Test structure

  • BoltVersionNegotiationTest.negotiate(...) re-implements the negotiation loop rather than exercising the production code path. The PR nicely removed the array drift by asserting against the real BoltNetworkExecutor.SUPPORTED_VERSIONS, but the algorithm is still duplicated in the test helper. If the matching logic in performHandshake() ever changes (e.g. range handling), these tests would keep passing against the stale copy. Extracting the inner loop into a package-private static int negotiateVersion(int[] clientVersions) and testing that directly would close the gap and shrink performHandshake().

Minor / positives

  • deferAuthToLogon correctly uses lexicographic >= 5.1 (major > 5 || (major == 5 && minor >= 1)) and relies on HelloMessage getters returning null for absent keys, which they do. Good.
  • The OffsetDateTime/ZonedDateTime split (fixed-offset zone -> F/I, named zone -> f/i) and the dual epoch bases (local.toEpochSecond(UTC) legacy vs local.toEpochSecond(offset) UTC) look right and are symmetric with the inbound decoder's dual-signature handling.
  • sendMessage reading getMajorVersion(protocolVersion) per message is fine since the handshake always completes first (pre-handshake protocolVersion == 0 -> major 0 -> 4.x path, and no BoltMessage is sent before then anyway).
  • TELEMETRY framing is safe: PackStreamReader fully consumes the structure before BoltMessage.parse dispatches, so ignoring the payload integer can't desync the stream.

Nice work closing PROTO-002 without weakening the 3.0/4.0/4.4 paths.

@robfrank

robfrank commented Jul 6, 2026

Copy link
Copy Markdown
Collaborator Author

Addressed in 28195df.

1. TELEMETRY without a state guard - Fixed. The case TELEMETRY now emits IGNORED when state == State.FAILED and SUCCESS otherwise, matching the Bolt state machine (IGNORED for every request but RESET while FAILED) and the per-handler pattern already used by handleRun/handlePull/handleDiscard/handleBegin. As you noted it is latent (no telemetry hint is advertised, so a compliant driver never sends it), but the guard makes it consistent with the surrounding handlers.

3. negotiate() duplicating the production loop - Fixed. Extracted a pure static int selectVersion(int[] clientVersions) on BoltNetworkExecutor; negotiateVersion() now calls it, and the tests negotiate()` helper delegates to it instead of re-implementing the match. The 23 negotiation cases now exercise the real matching logic, so a divergence (e.g. the outer break-after-match) can no longer hide. 85/85 unit tests green.

2. getFieldCount() misleading for version-gated structs - getFieldCount() is a PackStreamStructure interface method, so it cannot be dropped from the overrides; I took the "document it as unused" option in 1af3bbd, adding a comment on each accessor stating writeTo is authoritative and emits the v5 field count/UTC signature at major >= 5. Only BoltPointStructure.writeTo consumes the header idiom (a version-invariant struct), so there is no live mismatch.

Nit - per-RECORD PackStreamWriter allocation - Agreed it is worth a look, but it is pre-existing (not introduced by this PR) and a writer/buffer-reuse change carries its own correctness surface, so I am keeping it out of this PR`s scope as a follow-up rather than bundling a perf refactor into a protocol change.

Full module remains green (mvn -pl bolt verify: 275 unit + 110 IT, real neo4j-java-driver ITs included).

@robfrank

robfrank commented Jul 6, 2026

Copy link
Copy Markdown
Collaborator Author

This re-review landed on commit 5e490b79b; the two actionable items were pushed ~1 min later in 28195dfec, so they crossed in flight:

  • TELEMETRY acked in any state - Now guarded: case TELEMETRY emits IGNORED when state == State.FAILED and SUCCESS otherwise. I gated on FAILED (rather than a positive READY-only whitelist) to match the pattern every other request handler in processMessage uses (if (state == State.FAILED) { sendIgnored(); return; } in handleRun/handlePull/handleDiscard/handleBegin). A READY-only whitelist would additionally reject a TELEMETRY arriving in TX_READY, which the Bolt state machine permits, so FAILED->IGNORED / else->SUCCESS is both consistent here and not over-restrictive.

  • negotiate() duplicating the algorithm - Extracted static int selectVersion(int[] clientVersions); negotiateVersion() calls it and the test helper delegates to it, so the matching logic is no longer duplicated (I named it selectVersion rather than an overloaded negotiateVersion to keep it a pure, socket-free function). The 23 negotiation cases now exercise the real code path.

  • getFieldCount() inconsistency - It is a PackStreamStructure interface method with no writer/version context, so it structurally cannot return the version-correct count; writeTo (which has the negotiated version via the writer) is necessarily authoritative. Since the method cannot be dropped from an interface implementation, I documented it on each accessor (1af3bbdf0) noting writeTo is authoritative and getFieldCount() is the v4 base count. Only BoltPointStructure.writeTo consumes the header idiom, on a version-invariant struct.

Current HEAD 28195dfec, mvn -pl bolt verify green (275 unit + 110 IT).

@claude

claude Bot commented Jul 6, 2026

Copy link
Copy Markdown

Code Review: Bolt 5.0-5.4 negotiation with version-gated wire encoding

Reviewed the full diff (negotiation, version-gated structs, temporal encoding, auth deferral, TELEMETRY, and the conformance/e2e updates). This is a high-quality, well-documented, and thoroughly tested change. Threading a single negotiated Bolt major through PackStreamWriter and letting each structure's writeTo be authoritative is clean, and the wire deltas (element_id field counts 4/8/4, UTC I/i vs legacy F/f datetime) are gated correctly and land atomically with the advertised 5.x range. A few observations below, none blocking.

Correctness (verified, looks good)

  • Negotiation (selectVersion): client-preference-outer / server-preference-inner loop returns the highest server minor within a client's range, respects client ordering, and stops on zero padding. The negotiation matrix tests (exact, range, fallback, 5.x-only, mixed 5.x+4.4, no-match, padding) cover this well.
  • Version propagation: all outbound messages route through sendMessage, which stamps boltMajorVersion; writeValue passes the same writer into nested PackStreamStructure.writeTo, so the negotiated version reaches every nested graph element / temporal.
  • Temporal epoch bases: dateTimeWithOffset computes localEpoch = local.toEpochSecond(UTC) (legacy basis) and utcEpoch = local.toEpochSecond(offset) (true instant), and the inbound decoders mirror this per-signature. Round-trip is consistent for offset and zone-id variants, and mapperRoundTrip pins the mapper end-to-end.
  • Auth deferral: deferAuthToLogon uses a lexicographic >= 5.1 gate (so a hypothetical 6.0 still defers), requires all three auth fields null, and keeps the explicit "none" rejection on both the HELLO and LOGON paths.
  • TELEMETRY: correctly IGNORED when state == FAILED and SUCCESS-acked otherwise, matching the Bolt state-machine rule for the other request handlers.

Minor: orphaned/misplaced Javadoc after the extract selectVersion refactor

BoltNetworkExecutor.java:1891-1896 - the Javadoc describing deferAuthToLogon ("A Bolt 5.1+ HELLO carries no authentication...") now sits directly above selectVersion (1897-1903), so there are two stacked Javadoc blocks: the first is a dangling comment that attaches to nothing, and deferAuthToLogon (line 1923) is left undocumented. Looks like the method was extracted/moved but its doc was left behind. Suggest moving that block down to deferAuthToLogon.

Minor: getFieldCount() is now a latent trap on version-gated structs

BoltNode/BoltRelationship/BoltUnboundRelationship/BoltDateTimeStructure return the fixed v4.x count (3/5/3/3) while writeTo emits 4/8/4 on Bolt 5. Fine today because getFieldCount() is unused in the write path (only BoltPointStructure.writeTo calls it, self-consistently), and the comments call this out. But any future consumer that does writeStructureHeader(getSignature(), getFieldCount()) for these types (as BoltPointStructure does) would emit a header/body mismatch on a 5.x connection. Worth considering making getFieldCount() version-aware (or dropping it from the interface in favor of writeTo being the sole authority) to remove the footgun. Not required for this PR.

Test coverage

Strong. Unit tests assert the tiny-struct header byte flips (0xB0|5 -> 0xB0|8 for relationships, 0xB0|3 -> 0xB0|4 for nodes/unbound) at major 4 vs 5, datetime signature/epoch selection at both majors, the negotiation matrix incl. no-match and padding, and the auth-deferral truth table. The e2e proto002_bolt5 xfail is correctly unwrapped to a direct major >= 5 assertion, and the real neo4j-java-driver ITs reportedly pass unchanged (the important end-to-end guard).

Nits

  • TELEMETRY (0x54) is SUCCESS-acked even on a negotiated 4.x connection where a compliant driver would never send it. Harmless and consistent with the defensive intent, just noting it accepts a message outside the negotiated feature set.

Nice work - the "advertise + honor the wire deltas together, don't lie to drivers" framing is exactly right, and the scope boundaries (5.5/5.6 GQL notifications, 5.7/5.8 manifest handshake) are clearly documented.

I could not run mvn -pl bolt verify in this environment (build commands were gated), so the above is a static review; the author reports the bolt unit + IT suite green.

@robfrank

robfrank commented Jul 6, 2026

Copy link
Copy Markdown
Collaborator Author

Orphaned Javadoc after the selectVersion extraction - Good catch, that was a real mistake in 28195dfec: inserting selectVersion left deferAuthToLogons doc stranded above it and the method undocumented. Fixed in 226ee9c9c - selectVersion keeps its own Javadoc and the "A Bolt 5.1+ HELLO..." block is back directly above deferAuthToLogon.

getFieldCount() latent trap - It cannot be made version-aware: it is a no-arg PackStreamStructure interface method with no access to the negotiated version (only writeTo has that, via the writer), and being an interface override it cannot be dropped from these implementations. So writeTo is necessarily the sole authority; I have documented that on each accessor. A cleaner long-term fix would be to change the PackStreamStructure contract so header emission is owned entirely by writeTo (removing getFieldCount()/getSignature() from the interface, since only BoltPointStructure self-consumes them) - that is a wider refactor of the packstream layer and out of scope for this protocol change, but I can open a follow-up for it.

Nit - TELEMETRY SUCCESS-acked on a negotiated 4.x connection - Left intentionally permissive. TELEMETRY is only ever sent when the server advertises a telemetry hint (which ArcadeDB does not), so no compliant driver sends it on any version; gating the ack on major >= 5 would add a branch for a message that never legitimately arrives. The FAILED->IGNORED guard is the meaningful state check; beyond that a benign SUCCESS ack is the defensive choice.

HEAD 226ee9c9c; bolt module compiles clean and mvn -pl bolt verify remains green.

@claude

claude Bot commented Jul 6, 2026

Copy link
Copy Markdown

Code Review: Bolt 5.0-5.4 negotiation and version-gated wire encoding

Overall this is a clean, well-scoped, and thoroughly tested change. The design of threading a single negotiated major version through PackStreamWriter and letting each structure's writeTo() be authoritative is a good, low-risk approach, and backward compatibility with 4.x is preserved byte-for-byte. Nice work extracting selectVersion / deferAuthToLogon into pure, package-private functions so the tests exercise the real production logic instead of a drifting copy. A few observations below, mostly minor.

Strengths

  • Version gating is centralized and honest. Advertising 5.x and honoring the element_id / UTC-datetime wire deltas land together, so the Neo4j/5.26.0 compatible identity is no longer overselling.
  • Auth-deferral is correctly guarded. After a deferred 5.1+ HELLO, state = AUTHENTICATION, and handleRun/handleBegin require READY/TX_READY, so no query can run before LOGON authenticates. The truth-table test (incl. none-rejected and the lexicographic >= 5.1 case) is a good touch.
  • Backward compat verified. The 4.x datetime bases (localEpochSeconds) match the pre-change dateTimeWithOffset / zoneId encodings exactly, so 4.x drivers stay byte-identical.
  • Null-safety on element ids. BoltNode/BoltRelationship/BoltUnboundRelationship all default element ids to String.valueOf(id), so the new writeString(elementId) calls on the 5.x path can never NPE.
  • Test coverage is strong: the mapper-driven end-to-end datetime tests pin the epoch-basis argument the mapper feeds the factories (not just the factories in isolation), and the negotiation matrix now covers 5.x-only, mixed 5.x+4.4, and the padding/no-match edges.

Suggestions / points to consider

  1. getFieldCount() / getSignature() now disagree with writeTo() on Bolt 5 (latent trap). For BoltNode/BoltRelationship/BoltUnboundRelationship and BoltDateTimeStructure, getFieldCount() returns the 4.x count (3/5/3) and getSignature() returns the legacy signature, while writeTo() emits 4/8/4 fields and the UTC signature. This is safe today only because PackStreamWriter serializes structures exclusively via writeTo() and never consults getFieldCount()/getSignature() (I verified there are no other callers). It's documented in comments, but it's a real footgun for any future code that trusts those accessors. Consider either making them version-aware (they'd need the writer/version, which the interface doesn't provide) or dropping them from the interface if they're genuinely dead for serialization - at minimum the current state is worth calling out as tech debt.

  2. TELEMETRY is acknowledged in any non-FAILED state, with no version or state gate. Per the Bolt state machine, TELEMETRY is only valid in READY; here any non-FAILED state (e.g. AUTHENTICATION, STREAMING, TX_STREAMING) gets a SUCCESS. It's harmless in practice (only 5.4 drivers send it, and only in READY), and "accept defensively" is a reasonable stance, but it's slightly looser than the spec. Not blocking.

  3. connection_id uses Thread.currentThread().getId() in buildHelloSuccessMetadata() - deprecated since Java 21 in favor of threadId(). This is pre-existing code that was only moved by the refactor, so no regression, but since you're touching the method it'd be a cheap cleanup.

None of these are blockers. The core protocol work looks correct and the test suite (including the un-wrapped RemoteBoltDatabaseIT#proto002_bolt5 real-driver assertion) gives good confidence. 👍

Review generated with Claude Code. Static review only - I did not run the build/ITs; relying on the PR's stated mvn -pl bolt verify green run.

@codecov

codecov Bot commented Jul 6, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 90.00000% with 11 lines in your changes missing coverage. Please review.
✅ Project coverage is 65.61%. Comparing base (1df3470) to head (9536e36).
⚠️ Report is 86 commits behind head on main.

Files with missing lines Patch % Lines
...in/java/com/arcadedb/bolt/BoltNetworkExecutor.java 71.87% 7 Missing and 2 partials ⚠️
...arcadedb/bolt/structure/BoltDateTimeStructure.java 91.66% 2 Missing ⚠️
Additional details and impacted files
@@             Coverage Diff              @@
##               main    #5059      +/-   ##
============================================
- Coverage     65.81%   65.61%   -0.21%     
- Complexity      840      842       +2     
============================================
  Files          1687     1690       +3     
  Lines        134939   135485     +546     
  Branches      28859    28985     +126     
============================================
+ Hits          88809    88895      +86     
- Misses        33941    34463     +522     
+ Partials      12189    12127      -62     

☔ 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 commented Jul 7, 2026

Copy link
Copy Markdown
Collaborator Author

3. connection_id uses deprecated Thread.getId() - Fixed in 9536e36da: buildHelloSuccessMetadata() now uses Thread.currentThread().threadId(). threadId() returns the same value as getId(), so the emitted connection_id is byte-identical; it just drops the Java 21 deprecation. (275/275 bolt unit tests green, and the deprecation warning is gone.)

2. TELEMETRY acked in any non-FAILED state - Holding as-is. TELEMETRY is only sent when the server advertises a telemetry hint, which ArcadeDB never does, so it never legitimately arrives on any version or state; the FAILED->IGNORED guard is the one meaningful state check, and adding a READY-only whitelist would branch on states (AUTHENTICATION/STREAMING/TX_STREAMING) that can never receive a real TELEMETRY. Defensive SUCCESS is the intended stance, and as you note it is harmless and not blocking.

1. getFieldCount()/getSignature() vs writeTo() (tech debt) - Agreed this is the right long-term cleanup, but it is a packstream-layer change, not a protocol change: getFieldCount()/getSignature() are PackStreamStructure interface methods, and narrowing the contract so writeTo() is the sole header authority means touching every implementer (BoltNode/Relationship/UnboundRelationship/Path/Point/Temporal/DateTime) and the BoltStructureTest assertions that read them. That is broader than this PROTO-002 PR should carry, and it is inert today (verified: only BoltPointStructure.writeTo self-consumes the idiom, on a version-invariant struct). I have documented the accessors as non-authoritative on each struct; I will open a separate follow-up issue to remove them from the interface rather than bundle a serialization-layer refactor here.

HEAD 9536e36da.

@robfrank

robfrank commented Jul 7, 2026

Copy link
Copy Markdown
Collaborator Author

Follow-up for suggestion #1 (make writeTo() the sole header authority; drop getFieldCount()/getSignature() from PackStreamStructure) filed as #5082.

@claude

claude Bot commented Jul 7, 2026

Copy link
Copy Markdown

Code Review: Bolt 5.0-5.4 negotiation (#5059)

Reviewed the full diff, the surrounding BoltNetworkExecutor state machine, and the temporal/struct wire paths. This is a well-scoped, high-quality PR. The core design decision - advertising 5.x and honoring the element_id/UTC-datetime wire deltas atomically, guarded by the existing real-driver round-trip ITs - is exactly right and avoids the "advertise 5.26-compatible but silently downgrade" dishonesty the PR set out to fix.

Strengths

  • Clean single-switch threading. Routing the negotiated major through PackStreamWriter.boltMajorVersion(...) at writeTo time (rather than baking it in at mapping time) is the better mechanism: a datetime nested inside a node/map/list property is encoded correctly automatically, with no version param threaded through the mapper recursion. I confirmed the only new PackStreamWriter(...) in main code is in sendMessage (line 1698), and all RECORD output funnels through it - so the gate can't be bypassed.
  • Wire layouts are correct. Node 3->4, Relationship 5->8, UnboundRelationship 3->4; DateTime 'F'/'f'(local epoch) -> 'I'/'i'(UTC epoch). Both epoch bases are precomputed and the bare-Instant/Date/Calendar paths flow through the version-aware dateTimeWithOffset/BoltDateTimeStructure, so those are gated too - not just the two obvious ZonedDateTime branches.
  • Auth deferral is safe. After a deferred 5.1+ HELLO the connection stays in AUTHENTICATION; RUN/BEGIN require READY, so no query can execute before LOGON authenticates. Explicit "none" scheme stays rejected in both flows. The lexicographic >= 5.1 gate (major > 5 || (major == 5 && minor >= 1)) correctly avoids the major>=5 && minor>=1 trap for a hypothetical 6.0.
  • De-duplicated negotiation logic. Extracting selectVersion and having the unit test call the production method (instead of a drifting local copy of SUPPORTED_VERSIONS) is a real correctness win - the test can no longer pass against stale logic.
  • Test coverage is thorough - version matrix incl. no-match/padding-stop, per-major struct field counts via tiny-struct markers, datetime signatures at major 4 vs 5 through both the factories and the real mapper path, and the auth-deferral truth table incl. none-rejected.

Minor points (non-blocking)

  1. TELEMETRY acked in any non-FAILED state. processMessage returns SUCCESS for TELEMETRY whenever state != FAILED, including NEGOTIATION/AUTHENTICATION. Per the Bolt state machine TELEMETRY is only valid once READY. This is harmless and explicitly defensive (a compliant driver never sends it since the server advertises no telemetry hints), but if you want strict conformance you could scope the SUCCESS to READY/TX_READY and otherwise emit a protocol error, mirroring the other request handlers.

  2. getFieldCount() reports the v4 base count while writeTo emits the v5 count. I verified getFieldCount() is not consulted on the write path (structures serialize via writeTo), so there's no wire bug, and the comments explain the intent. Still, an accessor that disagrees with the bytes actually written is a mild footgun for a future caller - worth a one-line note on the PackStreamStructure#getFieldCount interface Javadoc that writeTo is authoritative for version-gated structs.

  3. Deprecated integer ids still sent on 5.x. Bolt 5.0 deprecates id/start_node_id/end_node_id (Neo4j emits -1); ArcadeDB still sends the real longs. That's valid for compatibility and arguably more useful, just noting it as a known deviation from Neo4j's own 5.x output in case a driver's strict mode ever complains.

  4. Planning docs in the tree. docs/superpowers/ adds ~840 lines of design spec + implementation plan. The PR says this is intentional; just confirm the team wants internal agent-planning artifacts committed to the main tree vs. kept in the PR description/issue.

Verification

Per the checklist the bolt module is green (275 unit + 110 IT, incl. the real neo4j-java-driver round-trip ITs) with no assertion changes needed for 4.x - which is the strongest signal that the 4.x path stayed byte-identical and the 5.x path is honest end-to-end.

Nice work. None of the above blocks merge.

🤖 Generated with Claude Code

@robfrank
robfrank merged commit 36b41e9 into main Jul 7, 2026
17 of 27 checks passed
@codacy-production

Copy link
Copy Markdown

Not up to standards ⛔

🔴 Issues 1 minor

Alerts:
⚠ 1 issue (≤ 0 issues of at least minor severity)

Results:
1 new issue

Category Results
CodeStyle 1 minor

View in Codacy

🟢 Metrics 19 complexity

Metric Results
Complexity 19

View in Codacy

🟢 Coverage 91.82% diff coverage · -7.50% coverage variation

Metric Results
Coverage variation ✅ -7.50% coverage variation
Diff coverage ✅ 91.82% diff coverage

View coverage diff in Codacy

Coverage variation details
Coverable lines Covered lines Coverage
Common ancestor commit (1df3470) 134939 101035 74.87%
Head commit (9536e36) 167288 (+32349) 112702 (+11667) 67.37% (-7.50%)

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 (#5059) 110 101 91.82%

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.

robfrank added a commit that referenced this pull request Aug 14, 2026
@robfrank
robfrank deleted the feat/5001-bolt-5x-negotiation branch August 26, 2026 09:12
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.

Bolt: decide and implement 5.x version negotiation

1 participant