Repository navigation
[Fix][Transform-V2] Preserve vector input buffers during SQL evaluation - #12335
Conversation
DanielLeens
left a comment
There was a problem hiding this comment.
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:
- Root cause confirmed via the real call chain, not just the helper.
ZetaSQLFunction.computeForValuereturnsinputFields[index]by reference for aColumnexpression (ZetaSQLFunction.java:327), so a query such asSELECT v, VECTOR_DIMS(v), L1_DISTANCE(v, v) FROM dualgenuinely aliases the sameByteBufferobject across every reference within one row.convertToFloatArrayis 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. 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 whenVectorUtils.toFloatArraythrowsBufferUnderflowExceptionpartway through (malformed/short buffer). That is exactly whatVectorFunctionTest.testFailedVectorReadPreservesBufferverifies: position/limit are provably unchanged even on a failed read. A mark/reset-based alternative would have needed atry/finallyto guarantee the same exception-safety;duplicate()gets it for free.- 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 toBIG_ENDIAN, and easy to get wrong even where current implementations preserve it). Without this call, a vector buffer built withLITTLE_ENDIANorder (e.g. from a source other thanVectorUtils.toByteBuffer, which defaults toBIG_ENDIAN) would silently decode to wrong float values on the very first read post-fix. The PR gets this right, andVectorFunctionTest.vectorBuffers()explicitly parameterizes bothBIG_ENDIAN/LITTLE_ENDIANplus heap/direct/read-only/sliced/offset buffer variants — good defensive test breadth for aByteBuffercorrectness fix. - 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.javaetc.) takebyte[]arguments and doByteBuffer.wrap(v1)fresh on every call — a new zero-position wrapper each time, so the aliasing bug can't occur there even forL1_DISTANCE(v, v)-style self-reference. Good scope discipline: the PR doesn't touch code that isn't broken. - 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 resultingFloat[]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 atposition == 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.testVectorReadsPreserveBufferis 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;testFailedVectorReadPreservesBufferproves state is preserved even when the read throws;testZeroVectorNormalizationPreservesBuffercovers the zero-vector early-return path. - Unit (SQL level):
SQLVectorFunctionTest.testRepeatedVectorExpressionsAndPassThroughruns the fix through the realSQLTransform/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 staysassertSamewithposition() == 0. - E2E:
func_vector.confwas extended with a first-stage normalize and a second-stage query that repeatsVECTOR_DIMS, addsL1_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'sColumnresolution back to the same aliasedByteBufferinstance), 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 sharedVectorUtilscontract 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 sharedVectorUtils.toFloatArrayutility 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>
|
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>
|
Thanks for the update, @goutamadwant! I checked the PR and the head commit is still 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. |
|
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 ( I diffed CI on this new head is still running as I write this ( |
davidzollo
left a comment
There was a problem hiding this comment.
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.
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?
Check list