Skip to content

fix: add binary string metadata foundation - #26906

Merged
XuPeng-SH merged 29 commits into
matrixorigin:mainfrom
ck89119:issue-25295-binary-metadata
Aug 13, 2026
Merged

XuPeng-SH merged 29 commits into
matrixorigin:mainfrom
ck89119:issue-25295-binary-metadata

Conversation

@ck89119

@ck89119 ck89119 commented Aug 10, 2026

Copy link
Copy Markdown
Contributor

What type of PR is this?

  • API-change
  • BUG
  • Improvement
  • Documentation
  • Feature
  • Test and CI
  • Code Refactoring

Which issue(s) this PR fixes:

issue #25295

What this PR does / why we need it:

This is layer 1 of the replacement for draft PR #26750.

It introduces the binary-string metadata foundation shared by later semantic fixes:

  • stores binary-string provenance per vector row and preserves it across vector/batch copy APIs;
  • transports prepared-parameter metadata through pipeline process codecs;
  • gates the new wire metadata on the required MORPC protocol version;
  • adds focused vector, batch, spool, and process codec regressions.

Validation:

  • owning-package and dependent-consumer unit tests passed;
  • owning-package build and vet passed;
  • generated protobuf output is up to date;
  • CI-equivalent incremental coverage: 83.76%.

@qodo-code-review

Copy link
Copy Markdown

Qodo reviews are paused for this user.

Troubleshooting steps vary by plan Learn more →

On a Teams plan?
Reviews resume once this user has a paid seat and their Git account is linked in Qodo.
Link Git account →

Using GitHub Enterprise Server, GitLab Self-Managed, or Bitbucket Data Center?
These require an Enterprise plan - Contact us
Contact us →

@XuPeng-SH XuPeng-SH 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.

Blocking: the value-preserving window functions drop row-level binary-string provenance.

In pkg/sql/colexec/aggexec/window.go, valueEntry (around lines 777-825) records the payload and PrepareParamKind, but not vec.GetBinaryStringMetadataAt(row). The LAG, LEAD, FIRST_VALUE, and LAST_VALUE flush paths append the raw value and restore only the prepared-parameter kind; NTH_VALUE delegates to the FIRST_VALUE implementation. A binary-marked VARCHAR therefore becomes an ordinary text VARCHAR after this operator, allowing downstream byte-sensitive functions to change semantics.

I reproduced this at head 6472b2b306684ce1f96e4c09ab3b9d1a7b2d24ca with FIRST_VALUE: the input row's binary-string metadata was true before Fill, but the output metadata was false after Flush.

Please carry the per-row binary-string bit in valueEntry, restore it for every emitted non-NULL winner, and add mixed text/binary regressions covering LAG, LEAD, FIRST_VALUE, LAST_VALUE, and NTH_VALUE.

Non-blocking performance observation: Vector.Copy now adds a second linear hasPrepareParamValueExcept scan for ordinary copies into sparse/pre-sized destinations. In a reverse-fill benchmark at 16,384 rows, this head took about 799 ms versus 551 ms at the base and remains quadratic. Please consider deriving the “other non-NULL row exists” condition from maintained length/null counts instead of rescanning the vector.

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

P1: Preserve row-level binary-string provenance through value window functions.

This PR makes byte-string provenance row-exact, but valueWindowExec.Fill records only the payload and PrepareParamKind in valueEntry. All non-NULL flush paths restore only that kind; none restores vec.GetBinaryStringMetadataAt(row). Thus a binary-marked VARCHAR selected by LAG, LEAD, FIRST_VALUE, LAST_VALUE, or NTH_VALUE becomes ordinary text and can change downstream byte-sensitive semantics.

Carry the binary bit in valueEntry, restore it for every emitted winner, and add mixed text/binary coverage for all five functions (NTH_VALUE can share the FIRST_VALUE path but still needs behavior coverage).

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

Deep-reviewed exact head 6472b2b306684ce1f96e4c09ab3b9d1a7b2d24ca, including the existing same-head review history.

[P1] Preserve binary-string provenance in value window functions.

valueWindowExec.Fill stores the payload and PrepareParamKind in valueEntry, but does not store vec.GetBinaryStringMetadataAt(row). The LAG, LEAD, FIRST_VALUE, and LAST_VALUE flush paths rebuild the selected value and restore only the prepare-parameter kind; NTH_VALUE delegates to FIRST_VALUE. A binary-marked VARCHAR selected by any of these functions therefore becomes ordinary text and can change the semantics of downstream byte-sensitive expressions.

I reproduced this independently with a focused FIRST_VALUE test on this exact head: both result rows carried the selected raw payload, but GetBinaryStringMetadataAt returned false. Please carry the row-level binary flag in valueEntry, restore it for every emitted non-NULL winner, and add mixed binary/text coverage for LAG, LEAD, FIRST_VALUE, LAST_VALUE, and NTH_VALUE.

@XuPeng-SH XuPeng-SH 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.

Requesting changes for three deterministic P1 correctness/lifecycle defects found at head b76b4ad17180836d1b1bd237db862a9ecd5c611a:

  1. MAX_BY copies binary provenance while the destination row is still NULL. In copyWinner, SetRawBytesAtFrom runs before UnsetNull, while SetIsBinaryStringAt ignores NULL destinations. A two-group reproduction loses binary metadata for text→binary order and incorrectly inherits binary metadata for binary→text order.

    for i := range dst {
    if src[i].IsNull(uint64(srcRows[i])) {
    dst[i].SetNull(uint64(dstRow))
    continue
    }
    if err := dst[i].SetRawBytesAtFrom(dstRow, src[i], srcRows[i], exec.mp); err != nil {
    return err
    }
    dst[i].UnsetNull(uint64(dstRow))
    if i == 0 {

  2. The row-mode aggregate trailer drops a uniform binary summary. With heterogeneous prepared-parameter kinds and uniformly binary winners, binaryRows[i] is absent because the vector is scalar, but the row encoder never falls back to binarySummaries[i]. The v18 GROUP → partial → MERGE GROUP path deterministically restores {true,true} as {false,false}.

    if rowsVersion && rowCount != 0 {
    if int64(rowCount) > int64(prepareParamKindTrailerMaxRows) {
    return moerr.NewInternalErrorf(ctx,
    "aggregate prepared parameter row count %d exceeds limit", rowCount)
    }
    buf.WriteByte(prepareParamKindTrailerRowsMarker)
    encodedRows := int32(rowCount)
    buf.Write(types.EncodeInt32(&encodedRows))
    for row := 0; row < rowCount; row++ {
    kind := vector.PrepareParamNone
    if i < len(rows) && len(rows[i]) != 0 {
    kind = rows[i][row]
    }
    if kind > vector.PrepareParamBoolean {
    return moerr.NewInternalErrorf(ctx,
    "invalid aggregate prepared parameter row kind %d", kind)
    }
    encoded := byte(kind)
    if version == prepareParamKindTrailerBinaryVersion && i < len(binaryRows) &&
    len(binaryRows[i]) != 0 && binaryRows[i][row] {
    encoded |= prepareParamKindTrailerRowsMarker
    }
    buf.WriteByte(encoded)

  3. Append rollback panics after a valid bitmap-to-scalar normalization. A successful earlier-column UnionBatch can collapse an all-true row sidecar to scalar form. If a later column is rejected by the allocation account, RollbackAppend panics with binary-string sidecar lost during append rollback instead of returning the retryable capacity error required by HashBuild spill recovery.

    func (v *Vector) RollbackAppend(checkpoint AppendCheckpoint, attemptedRows int) {
    if checkpoint.length < 0 || checkpoint.length > v.length ||
    checkpoint.areaLength < 0 || checkpoint.areaLength > len(v.area) ||
    attemptedRows < 0 {
    panic("invalid vector append checkpoint")
    }
    end := max(v.length, checkpoint.length+attemptedRows)
    nulls.RemoveRange(&v.nsp, uint64(checkpoint.length), uint64(end))
    nulls.RemoveRange(&v.gsp, uint64(checkpoint.length), uint64(end))
    v.length = checkpoint.length
    v.area = v.area[:checkpoint.areaLength]
    // A failed varlen append may already have exposed shared or partial area
    // layout. Roll back logical lengths, but keep this proof fail-closed.
    v.areaDisjoint = checkpoint.areaDisjoint && v.areaDisjoint
    v.sorted = checkpoint.sorted
    if checkpoint.hadPrepareParamKinds {
    if len(v.prepareParamKinds) < checkpoint.length {
    panic("prepared parameter sidecar lost during append rollback")
    }
    clear(v.prepareParamKinds[checkpoint.length:])
    v.prepareParamKinds = v.prepareParamKinds[:checkpoint.length]
    } else {
    v.releasePrepareParamKinds()
    }
    v.prepareParamKind = checkpoint.prepareParamKind
    v.prepareParamKindSeen = checkpoint.prepareParamKindSeen
    if checkpoint.hadBinaryStringRows {
    if v.binaryStringRows == nil || !v.binaryStringRowsActive {
    panic("binary-string sidecar lost during append rollback")
    }
    v.binaryStringRows.RemoveRange(uint64(checkpoint.length), uint64(end))
    v.binaryString = checkpoint.binaryString
    } else {
    v.setBinaryStringScalar(checkpoint.binaryString)

All three were reproduced against the exact PR head. Focused neighboring tests in aggexec, group, vector, and colexec pass, so these are missing boundary cases rather than a broken local test setup.

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

Deep re-review of exact head b76b4ad17180836d1b1bd237db862a9ecd5c611a, including all prior review history. The earlier value-window blocker is closed by 7c795f3dc9, but three P1 correctness/lifecycle blockers remain and I reproduced each independently.

  1. [P1] MAX_BY loses or inherits the wrong row-level binary provenance across groups. In pkg/sql/colexec/aggexec/maxby.go:288-297, copyWinner calls SetRawBytesAtFrom while a new destination group row is still NULL. SetIsBinaryStringAt ignores NULL rows, then UnsetNull exposes the previous scalar provenance. With two groups ordered text then binary, the expected {false,true} becomes {false,false}; reversing them produces the inverse inheritance. Unset the destination NULL before the metadata-aware copy (with failure rollback), or publish payload/null/metadata atomically, and add both transition orders.

  2. [P1] The row-form aggregate trailer drops a uniform binary summary. In pkg/sql/colexec/group/prepare_param_kind.go:145-167, heterogeneous prepared-parameter kinds select row encoding, but the binary bit is read only from binaryRows[i]. A uniformly binary winner vector is represented by binarySummaries[i]=true with no row bitmap, so encoding two heterogeneous-kind rows and decoding them changes {true,true} to {false,false}. Row encoding must fall back to the scalar binary summary when the row sidecar is absent; cover the v18 GROUP -> partial -> MERGE GROUP path.

  3. [P1] Valid sidecar normalization makes append rollback panic. RollbackAppend at pkg/container/vector/vector.go:353-359 requires an active row bitmap whenever the checkpoint had one. However, a successful UnionBatch can legitimately normalize an all-true active bitmap to scalar form before a later column fails. Rolling back that batch then panics with binary-string sidecar lost during append rollback instead of returning the capacity error used by spill recovery. I reproduced this with a two-row all-true active sidecar, one successful binary append, and rollback. The checkpoint/rollback contract must restore the logical representation regardless of an equivalent active-to-scalar normalization.

Focused existing binary/provenance tests in vector, aggexec, and group pass with the required CGO/usearch setup, confirming these are uncovered boundary cases rather than setup failures.

@XuPeng-SH XuPeng-SH 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.

Deep-reviewed exact head 6e4bccc. The previous MAX_BY, aggregate trailer, and append rollback blockers are closed. Focused tests across the affected vector, batch, process, aggregation, spill, dispatch, compile, frontend, and shard-service paths pass; no new blocking correctness or lifecycle issues found.

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

Deep re-review completed on exact head 4b03f53.

The previously requested changes are closed: value-window provenance is preserved, MAX_BY now updates payload/null/provenance atomically, row-mode aggregate trailers retain uniform binary summaries, and append rollback handles both bitmap normalization and stale null extents. I also reviewed the aggregate/group spill and MORPC v18 gating paths and found no remaining correctness blocker.

Local validation (with required CGO/thirdparties setup) passed for vector, batch, aggexec, group, dispatch, and process packages. The current Ubuntu UT check failure is an unrelated checkout failure fetching the contributor branch, before tests ran.

This branch was previously deployed

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

Labels

kind/bug Something isn't working size/XXL Denotes a PR that changes 2000+ lines

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants