Skip to content

[Fix][Transform-V2] Preserve vector input buffers during SQL evaluation - #12335

Merged
davidzollo merged 4 commits into
apache:devfrom
goutamadwant:fix/vector-non-mutating-reads
Oct 4, 2026
Merged

davidzollo merged 4 commits into
apache:devfrom
goutamadwant:fix/vector-non-mutating-reads

Conversation

@goutamadwant

Copy link
Copy Markdown
Collaborator

Purpose of this pull request

Closes #12334.

Read an ordered duplicate in the SQL vector conversion path instead of consuming the caller's ByteBuffer. Keep the shared VectorUtils consuming-conversion contract unchanged.

Extend the existing vector/SQL tests and E2E fixture for repeated reads, same-buffer operands, downstream reuse, buffer variants and failure paths. Update EN/ZH documentation.

Does this PR introduce any user-facing change?

Yes. Reusing one vector in multiple SQL expressions no longer advances its input buffer or causes a subsequent read to fail with BufferUnderflowException. Position, limit, mark, order and contents are preserved, including when decoding fails.

No API, configuration, schema or state-format changes. This adds a buffer view, not a full byte-buffer copy. It does not change vector arithmetic or redefine malformed-buffer dimensions. Reproduced on current dev; released versions were not separately tested.

How was this patch tested?

  • Before the fix, all 13 added regression invocations failed on both Java 8 and Java 11; the 19 existing cases passed.
  • Full transform reactor on Java 8 and Java 11: 1,170 transform tests passed per JDK, with no failures, errors or skips.
  • Combined affected-suite validation with the arithmetic fix: 651 transform tests and five VectorUtils tests passed per JDK.
  • Targeted Java 11 Zeta execution: the original transform JAR failed with buffer underflow; the combined fixed JAR passed. This used an earlier snapshot distribution with the new transform JAR overlaid, not the full Flink/Spark matrix.
  • Root Spotless and Java 11 root verification passed on the combined integration tree, including distribution packaging.
./mvnw -B -pl seatunnel-transforms-v2 -am package -Dskip.ui=true
./mvnw spotless:apply
./mvnw -q -DskipTests verify

Check list

  • New Jar binary package / license notice: not applicable; no dependency added.
  • User-facing documentation updated in EN/ZH.
  • Incompatible changes reviewed: no configuration, API, schema or state migration; the corrected read-side effect is documented.
  • Connector checklist (plugin mapping, distribution POM, CI labels, connector E2E and plugin_config): not applicable; no connector code changed. The existing transform E2E fixture was extended.

@DanielLeens DanielLeens 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.

What Problem Does This PR Solve?

VectorFunction.convertToFloatArray(Object) (Zeta SQL engine, seatunnel-transforms-v2/.../sql/zeta/functions/VectorFunction.java) passed the caller's ByteBuffer vector value directly into VectorUtils.toFloatArray(ByteBuffer), which reads it with relative (position-advancing) getFloat() calls. Since ZetaSQLFunction.computeForValue resolves a Column reference with return inputFields[index]; (line ~327), every SQL reference to the same vector column inside one row evaluation returns the same ByteBuffer instance. The first vector function call that touches it consumes its position; any second read of that same instance — a repeated projection (VECTOR_DIMS(v) used twice), a two-argument function fed the same column twice (L1_DISTANCE(v, v)), or a raw pass-through of v evaluated after a function call — either throws BufferUnderflowException or silently hands downstream a buffer with position == capacity (i.e. an apparently empty vector). This is reproducible through the real SQLTransform execution path, not just direct unit calls (see issue #12334). The fix reads through a duplicate() of the buffer instead of the original, so the caller's buffer is never mutated.

1. Code Change Review

1.1 Core Logic Analysis

Before:

private static Float[] convertToFloatArray(Object obj) {
    if (obj instanceof ByteBuffer) {
        return VectorUtils.toFloatArray((ByteBuffer) obj);
    }
    ...

After:

private static Float[] convertToFloatArray(Object obj) {
    if (obj instanceof ByteBuffer) {
        ByteBuffer buffer = (ByteBuffer) obj;
        // A vector can be shared by multiple expressions and downstream consumers.
        return VectorUtils.toFloatArray(buffer.duplicate().order(buffer.order()));
    }
    ...

Key findings:

  1. Root cause confirmed via the real call chain, not just the helper. ZetaSQLFunction.computeForValue returns inputFields[index] by reference for a Column expression (ZetaSQLFunction.java:327), so a query such as SELECT v, VECTOR_DIMS(v), L1_DISTANCE(v, v) FROM dual genuinely aliases the same ByteBuffer object across every reference within one row. convertToFloatArray is the single entry point every vector function in this file funnels through (cosineDistance, l1Distance, l2Distance, vectorDims, vectorNorm, innerProduct, vectorTruncate, vectorRandomProjection, vectorSparseProjection, vectorNormalize), so fixing it here fixes all of them in one place — this is the correct root-cause location, not a symptom patch.
  2. duplicate() is the right non-destructive primitive, and exception-safe. ByteBuffer.duplicate() shares content but gets its own independent position/limit/mark, snapshotted from the original at the moment of the call, and the original is never touched afterward — including when VectorUtils.toFloatArray throws BufferUnderflowException partway through (malformed/short buffer). That is exactly what VectorFunctionTest.testFailedVectorReadPreservesBuffer verifies: position/limit are provably unchanged even on a failed read. A mark/reset-based alternative would have needed a try/finally to guarantee the same exception-safety; duplicate() gets it for free.
  3. The explicit .order(buffer.order()) is necessary, not decorative. ByteBuffer.duplicate()'s byte-order behavior is a well-known JDK gotcha (historically documented as resetting to BIG_ENDIAN, and easy to get wrong even where current implementations preserve it). Without this call, a vector buffer built with LITTLE_ENDIAN order (e.g. from a source other than VectorUtils.toByteBuffer, which defaults to BIG_ENDIAN) would silently decode to wrong float values on the very first read post-fix. The PR gets this right, and VectorFunctionTest.vectorBuffers() explicitly parameterizes both BIG_ENDIAN/LITTLE_ENDIAN plus heap/direct/read-only/sliced/offset buffer variants — good defensive test breadth for a ByteBuffer correctness fix.
  4. Zeta is the only affected engine; the Calcite SQL path was already immune, correctly left untouched. The parallel Calcite vector UDFs (transform/calcite/udf/L1DistanceFunction.java etc.) take byte[] arguments and do ByteBuffer.wrap(v1) fresh on every call — a new zero-position wrapper each time, so the aliasing bug can't occur there even for L1_DISTANCE(v, v)-style self-reference. Good scope discipline: the PR doesn't touch code that isn't broken.
  5. Normal-path reach confirmed. This is not an edge-case-only fix — any production SQL transform job that references a vector column more than once in one query (a very ordinary pattern: dimension check + distance, pass-through + derived metric, dimensionality reduction fan-out as in the extended e2e fixture) hits this on the normal execution path today, not only on restore/error/race paths.

1.2 Compatibility Impact

Fully compatible.

  • No config option, public API, SPI, or state/checkpoint format is touched; this is a pure computation-path fix inside a stateless SQL function.
  • For any query that references a given vector value only once (the common case that was silently working before), the read semantics for that first read are unchanged: same starting position, same byte order (explicitly preserved via .order(buffer.order())), same resulting Float[] values. Output is bit-for-bit identical to before.
  • For queries that reference a vector value more than once, the prior behavior was either an outright job failure (BufferUnderflowException) or a silently corrupted downstream value (leftover buffer at position == capacity, i.e. effectively empty) — never a "correct but different" result that some existing job could have been depending on. This PR turns broken behavior into correct behavior; there is no plausible currently-succeeding job whose output this changes.

1.3 Performance / Side-Effect Analysis

Each convertToFloatArray(ByteBuffer) call now allocates one extra short-lived ByteBuffer "view" object (duplicate() shares the backing array/memory — no data copy, just a small header object). This runs once per vector-function argument per row evaluation, so on very large vector-heavy batch/stream jobs it does add allocation pressure. Given the requirement to avoid mutating the caller's buffer without an unsafe mark/reset dance, this is a reasonable, minimal cost — flagged below as a non-blocking note rather than a blocker.

1.4 Error Handling and Logging

No logging added or changed (correctly — nothing here warrants a log line). One pre-existing, not-introduced-by-this-PR observation is listed as Issue 2 below.

2. Code Quality Assessment

2.1 Standards / comment completeness

The one-line functional change is annotated with a comment explaining why (// A vector can be shared by multiple expressions and downstream consumers.), consistent with the project's "explain intent/constraint, not restate code" convention. No new public methods/fields were introduced that would need their own Javadoc. License headers are unaffected (no new files).

2.2 Test coverage

Excellent and well-targeted, at three levels:

  • Unit (helper level): VectorFunctionTest.testVectorReadsPreserveBuffer is parameterized across byte order (BE/LE) x buffer kind (heap, direct, read-only, sliced-with-offset, position-offset) and re-runs the full function set twice per buffer to prove idempotent, non-destructive reads; testFailedVectorReadPreservesBuffer proves state is preserved even when the read throws; testZeroVectorNormalizationPreservesBuffer covers the zero-vector early-return path.
  • Unit (SQL level): SQLVectorFunctionTest.testRepeatedVectorExpressionsAndPassThrough runs the fix through the real SQLTransform/row-evaluation path (not just the helper directly) with a repeated column reference, a self-distance call, and a raw pass-through column, run twice, and asserts the pass-through field stays assertSame with position() == 0.
  • E2E: func_vector.conf was extended with a first-stage normalize and a second-stage query that repeats VECTOR_DIMS, adds L1_DISTANCE(vector_field, vector_field), and reduces the same field three more times — this is precisely the shape of query that reproduced the bug, run through Zeta end to end.

This directly satisfies "does the PR add a test that actually exercises buffer reuse across multiple evaluations/rows" — yes, at unit, SQL-transform, and e2e granularity. Per the PR description, the added regression cases (13 invocations) failed pre-fix on both Java 8/11 and the full transform reactor (1,170 tests) passed post-fix; I did not re-execute the suite myself (static review), but the test design and JDK-object-model reasoning above corroborate that claim.

Stability rating: Stable. The tests are deterministic (fixed float inputs, seeded PRNG-independent assertions, no timing/concurrency dependence) and exercise real code paths rather than mocks.

2.3 Docs

EN and ZH docs/.../sql-functions.md are updated with matching, accurate one-line notes on the new non-consuming contract. Good — keeps docs and code in sync as required.

3. Architectural Soundness

3.1 Precise fix vs. workaround vs. long-term

This is a precise, root-cause fix at the single call site that actually holds a caller-visible, position-mutable reference to a shared buffer, and it explicitly avoids widening the change into VectorUtils.toFloatArray's shared consuming-conversion contract (used elsewhere, e.g. the Calcite UDFs' fresh-wrap pattern, where consuming is harmless). That is the right minimal-blast-radius choice: changing the shared utility's contract would ripple into every caller and require re-auditing all of them, for no benefit here. This is the long-term-correct fix, not a stopgap.

3.2 Maintainability

Trivial to maintain: one guarded line, well-commented, funnels through the single existing private helper all vector functions already share.

3.3 Extensibility

Because the fix lives in the shared convertToFloatArray helper, any vector function added to this class in the future automatically inherits non-destructive read semantics for free — good DRY property.

3.4 Historical compatibility

No state, checkpoint/savepoint, or serialization format is involved (pure per-row computation), so there is no upgrade/restore compatibility surface to evaluate here. Config/API surface is unchanged, consistent with the "Fully compatible" verdict in 1.2.

Related, out-of-scope observation (not a blocker for this PR): the same pattern — passing a persistent ByteBuffer value directly into VectorUtils.toFloatArray without duplicating — also exists in seatunnel-connectors-v2/connector-elasticsearch/.../serialize/ElasticsearchRowSerializer.java:230. I have not traced whether any code path re-reads that same buffer instance after serialization (sink-side, so likely lower risk than mid-pipeline reuse, but not verified), and fixing it is out of scope for a Transform-V2 SQL fix. Worth a follow-up issue for whoever owns that connector to check.

4. Issue Summary

# Issue Location Severity Raised by another reviewer
1 Extra ByteBuffer.duplicate() allocation per vector-function argument per row (no data copy, but adds allocation pressure in very high-throughput vector workloads) seatunnel-transforms-v2/src/main/java/org/apache/seatunnel/transform/sql/zeta/functions/VectorFunction.java:188 Low (non-blocking, inherent cost of the correct fix) No
2 BufferUnderflowException on malformed/short vector buffers still propagates raw, without row/field context (pre-existing behavior, not introduced or worsened by this PR; confirmed unchanged by testFailedVectorReadPreservesBuffer) seatunnel-transforms-v2/src/main/java/org/apache/seatunnel/transform/sql/zeta/functions/VectorFunction.java:184-205 Low (informational, pre-existing, out of scope) No
3 Same buffer-consuming-read pattern (VectorUtils.toFloatArray(buffer) on a possibly-shared, non-duplicated buffer) exists outside this PR's scope seatunnel-connectors-v2/connector-elasticsearch/src/main/java/org/apache/seatunnel/connectors/seatunnel/elasticsearch/serialize/ElasticsearchRowSerializer.java:230 Info (out of scope, suggest follow-up issue) No

No correctness, compatibility, or stability blockers were found.

5. Merge Recommendation

Approve, pending green CI. At review time, the fork's Build check for this PR's head commit (03e7a6f) is still in progress (not failed) — I did not observe a failure to diagnose, so no CI-caused blocker is being carried here; please re-confirm the check is green before merging.

  • Blockers: None (source-code side). The only open item is confirming CI completes green on the current head.
  • Recommended fixes (non-blocking, optional): none required for this PR; issues 1-3 above are informational/low-severity and can be left as-is or tracked separately.
  • Overall assessment: This is a well-diagnosed, correctly root-caused, minimally-scoped bug fix. The reported problem is real and reproducible through the actual Zeta SQL row-evaluation path (verified by tracing ZetaSQLFunction.computeForValue's Column resolution back to the same aliased ByteBuffer instance), the fix uses the right non-destructive, exception-safe JDK primitive with the necessary byte-order guard, it correctly leaves the unaffected Calcite path and the shared VectorUtils contract untouched, and it is backed by unit, SQL-transform, and e2e regression coverage that specifically reproduces the reported scenarios (repeated projection, self-distance, pass-through). No better alternative architecture is warranted here — fixing the shared VectorUtils.toFloatArray utility instead would be a larger, unnecessarily invasive change for the same outcome, as the PR description itself correctly notes.

Signed-off-by: Goutam Adwant <workwithgoutam@gmail.com>
@goutamadwant

Copy link
Copy Markdown
Collaborator Author

Updated the branch with dev's merged NebulaGraph/RocketMQ fixes. The vector-input preservation patch is unchanged, and all 32 focused vector/SQL tests pass on Java 11. Fresh CI is queued.

Signed-off-by: Goutam Adwant <workwithgoutam@gmail.com>
@DanielLeens

Copy link
Copy Markdown
Contributor

Thanks for the update, @goutamadwant! I checked the PR and the head commit is still 63c14e7a - the same commit I already reviewed and approved, so from my side that approval still stands and I don't need to re-review the vector-buffer fix itself.

I don't see a new commit reflecting the dev sync (NebulaGraph/RocketMQ fixes) on the PR yet, so I can't independently confirm that merge landed cleanly or that CI ran against it. Once the updated branch is actually pushed (i.e. the head SHA changes) and a fresh CI run completes, I'll take another look and confirm the Build check is green before we move to merge. No action needed from me until then.

@DanielLeens

Copy link
Copy Markdown
Contributor

Following up on my own note above, since the condition I was waiting for has now happened: the branch was pushed and the head SHA changed (63c14e7a -> fe946b0f893334f, via Merge remote-tracking branch 'upstream/dev').

I diffed 63c14e7a...fe946b0f893334f directly: it's 44 files, all outside this PR's own scope (other connectors' docs, JDBC/CDC/Redis/SMB/Fluss files, dist license files, etc.) — nothing under seatunnel-transforms-v2 or the vector/SQL docs this PR touches. So the merge landed cleanly with no conflicts silently resolved into the vector-buffer fix itself, and my original approval (on 03e7a6fa, the commit that actually contains the fix) still stands unchanged.

CI on this new head is still running as I write this (Code style in progress, changes queued, Dead links/License header green so far) — I'll take one more look once it finishes to confirm the Build check is green before this is ready to merge. No action needed from you in the meantime.

@davidzollo davidzollo 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.

Thank you @goutamadwant for protecting the vector input buffers during SQL evaluation. A subtle correctness fix, nicely done. Approving: CI is green and the review feedback is addressed. Merging via the queue.

@davidzollo
davidzollo added this pull request to the merge queue Oct 4, 2026
Merged via the queue into apache:dev with commit dc7c3d0 Oct 4, 2026
4 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Bug][Transform-V2] SQL vector functions consume input buffers

3 participants