Skip to content

Fix IVFFLAT membership metadata and retry filtering - #29835

Merged
XuPeng-SH merged 4 commits into
matrixorigin:mainfrom
iamlinjunhong:fix/ivfflat-membership-28994-29042-29045
Oct 11, 2026
Merged

XuPeng-SH merged 4 commits into
matrixorigin:mainfrom
iamlinjunhong:fix/ivfflat-membership-28994-29042-29045

Conversation

@iamlinjunhong

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:

#28994
#29042
#29045

What this PR does / why we need it:

  • Preserve ENUM member metadata when IVFFLAT builds hidden origin-PK and INCLUDE columns, without copying source auto-increment behavior.
  • Keep exact membership filtering bound to the source origin PK after entries persistence or physical copies, while retaining the composite hidden-PK filter and storage Top-K path.
  • Accept the runtime VARCHAR representation produced for CHAR primary-key membership in PRE and AUTO retry validation, while rejecting reverse or unrelated type pairs.

Validation completed with focused and affected-package Go tests, go vet, go list, formatting, and diff checks. The issue reporters should verify the fixes after the PR is merged.

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

Request changes on 455216e06c65afcd181d8c4add4eca06d6f8fcb6 (base/merge-base 64b715a8234e272794185e2acc98ad58a8346c65).

I reviewed every changed hunk and traced the three issue contracts into their actual consumers. There is one independently reproduced transaction-read regression and a public-behavior validation gap.

  1. P1 — the new early return loses the physical PK sequence number. The existing workspace datasource then filters the rowid vector instead of the composite PK. A minimal test through the real readutil.NewReader / reader.Read / LocalDisttaeDataSource.Next uses one uncommitted entries row (source ID 42), the real centroid prefix_in predicate, and an exact 101-key integer domain. With identical test source:

    Revision Without membership With membership
    Base 64b715a823 end=false, rows=1 end=false, rows=1
    Head 455216e06c end=false, rows=1 end=true, rows=0

    The baseline command exits 0; head exits 1 on the retained-row oracle. This exercises the real internal reader/data-source boundary; I am not claiming a separately executed SQL frontend reproducer. SQL reachability is the existing required integer PRE route with a centroid-prefix scan and transaction-local entries. Preserve the shared initialization and cover this nearest in-memory control alongside the persisted fix.

  2. P2 — provide public regression coverage for ENUM and CHAR. The new synthetic-schema and validator tests cannot establish that ENUM index population/replay or CHAR PRE/AUTO retry actually returns the correct SQL result. Details are in the inline comment. The PR reports Go validation only; reporter verification after merging does not close these changed public contracts before merging.

Design and scope:

  • These are focused repairs of existing contracts; a new architecture/design document is unnecessary. Reusing the IVFFLAT schema hook and one directional membership type helper for its two consumers is appropriate. The optional runtime-filter key-codec contract explicitly excludes membership filters, so it does not replace this helper.
  • Consolidate the reader change with the existing column-selection branch. The old positive IVF/hasBF/last-origin-PK arm below the new branch is now unreachable for valid entries layouts. Also, SystemSI_IVFFLAT_TblCol_Entries_pk aliases IndexTablePrimaryColName, so selecting between these constants in setFilterHint adds no key-domain distinction. Keep one binding rule and the common initialization tail; this is directly relevant to the P1 failure.
  • No new state machine, store, retry worker, cache, plugin registration, GPU dependency, or parallel execution path is introduced. Existing generation/refcount ownership and scanner error/close cleanup remain in place. The strict null/cardinality/malformed-payload checks and directional type rejection are retained.
  • Performance changes are bounded to O(1) type admission, DDL type copying, and once-per-reader column mapping. The storage Top-K path remains selected. I found no demonstrated TP performance regression; no throughput benchmark was run.

Evidence and test quality:

  • Reused exact-head CI run 38068475872: affected owning packages selected by Ubuntu x86 race UT, build and SCA succeeded. Upgrade jobs were skipped and are not upgrade evidence.
  • Exact-head pessimistic compose BVT: vector_ivf_membership.sql 150/150, including persisted INT/BIGINT 0/1/99/100/101 and MATCH+IVF; vector_ivf_clone_sync.sql 14/14. These do not cover the transaction-local failure or the new ENUM/CHAR contract.
  • Independent differential probe: normal CGo, Go 1.27.1, darwin/arm64, repository wrapper; deterministic one-row workspace fixture, no cluster, sleeps, timing oracle, or altered product code. Temporary probe removed after recording both terminal results.
  • Increment reviewed separately: 6 production files +77/-18; 4 test files +131/-0; documentation/BVT/generated artifacts 0. The new tests are lightweight, but the reader test only checks column lists and misses the downstream PK-sequence consumer. No existing assertions were removed.

There were no earlier PR review threads to close. I also read the linked issue discussions: persistence/physical-copy and 100/101 boundaries have existing BVT evidence; the ENUM async/catalog and CHAR AUTO-retry public behavior claims are not yet closed by this PR's evidence. Please address the two findings before merge.

Comment thread pkg/vm/engine/readutil/reader.go Resolved

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

APPROVE at455216e06c65afcd181d8c4add4eca06d6f8fcb6 against base64b715a8234e272794185e2acc98ad58a8346c65. No confirmed blocker in the reviewed ten-file change.

The fix preserves ENUM's value-bearing metadata without copying source auto-increment constraints. Membership remains in the source origin-PK domain, while the persisted entries' composite key is retained for its separate physical pruning role. The reader selects both vectors explicitly rather than relying on copied Pkey.Names. CHAR-to-VARCHAR membership admission is deliberately directional; reverse and unrelated OID pairs remain rejected, and required membership still validates cardinality and NULLs.

Reviewed producers, required-filter/PRE consumers, persisted reader column selection and positive/negative test oracles. Current-head required CI, UT/SCA/coverage and proxy/pessimistic BVT are green. Focused/owning Go validation is reported by the author; it was not rerun locally in this pass. Diff whitespace checks pass. This approves the specific ENUM/membership repairs, not arbitrary key-domain coercion or all IVF filtering behavior.

Keep physical pkSeqNum initialization when binding origin-key membership.
Cover the real workspace reader with matching and excluded membership and
centroid controls; the original reader drops the matching row.

Restore original ENUM domains in CDC source casts, serialize enum ordinals
numerically, and transport nullable ENUMs through a valid numeric type.
Cover catalog reload, distinct domains, numeric and escaped labels, and delete.

Add public ENUM sync/async population and PK/NULL replay assertions plus a
13-row CHAR fixture proving AUTO executes PRE after an underfilled POST.

Validation: owning readutil, disttae and iscp tests; vet; incremental lint;
public SQL normal comparison 246/246 and same-instance repeat.
Encode committed ENUM values as typed tuples, retain their catalog domain,
and decode in the final hidden-table assignment. This preserves error
ordinal 0 from INSERT IGNORE without converting it to an empty display
label or re-running strict user-input validation.

Extend the existing writer and planner tests plus the async SQL case with
zero PK/INCLUDE, declared-empty, numeric-label, NULL, strict rejection,
and subsequent update/delete controls.

Validation: full ISCP and planner package tests, vet, incremental lint,
and two normal standalone BVT rounds (100/100 each), with zero database
and table residue between rounds.

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

Codex automated review

Reviewed git diff origin/main...HEAD at a13cd0b (21 files) against the three issue contracts (#28994 ENUM metadata, #29042 membership after persistence/physical copy, #29045 CHAR PK admission), tracing each producer/consumer pair instead of reading hunks in isolation.

Prior review findings — all verified addressed at this head

  • reader.go pkSeqNum: tryUpdateColumns no longer early-returns; filterState.pkSeqNum is assigned unconditionally at pkg/vm/engine/readutil/reader.go:198 after the IVF binding, and TestIvfWorkspaceReaderPreservesPhysicalPK drives the real NewReader/Read/LocalDisttaeDataSource.Next boundary with matching, source-key-excluded and centroid-excluded controls.
  • ENUM ordinal 0 (review 5483500004): convertSourceCol transports committed ENUMs as packed tuples (x'503d14' for ordinal 0, x'00' for NULL) and toIvfflatUpsert decodes via SERIAL_EXTRACT(srcN, 0 as ENUM(...)) only in the final assignment. UnpackNthElement returns Enum(uint16) and serialExtractExceptStrings appends it through el.(T) with no domain re-validation; base_binder.go's Typ.Enumvalues = args[2].Typ.Enumvalues then makes funcCastForEnumType short-circuit at pkg/sql/plan/make.go:1087. parseEnumValue still rejects 0, so user input stays strict — the BVT records cast(0 as enum('','2','1')) erroring while replayed ordinal 0 round-trips in PK and INCLUDE and survives the later delete ... where id+0 = 0.
  • Public ENUM/CHAR SQL coverage: vector_ivfflat_include_dml_sync covers sync + async ENUM with deliberately different PK/INCLUDE domains, mo_columns.attr_enum assertions, NULL and ordinal-0 replay; vector_ivf_membership adds a 13-row CHAR fixture whose @regex oracles prove PRE actually executed (Vector Index Scan inputRows=2 outputRows=2 + Runtime Filter Probe) while the FORCE branch's Table Scan shows inputBlocks=0 inputRows=0. Recording full explain analyze verbose text under @regex oracles matches the existing convention in vector_ivf_include_auto_retry.

Correctness checks that passed

  • MembershipKeyTypeCompatible's one-directional CHAR→VARCHAR rule matches reality: appendCastBeforeExprWithOverload preserves CHAR padding bytes and sets Typ.PadSpace, so producer and entries bytes are identical (scope_test.go pins "c1 "). CHAR never reaches the bitset path — docfilter.SupportsBitset is integer-only — so it uses the pad-space residual IN, never a byte-exact BF; the relaxation cannot corrupt BF matching, and integer PKs keep exact equality.
  • reader.go's [cpkey, __mo_index_pri_col] ordering matches ReadFilterMembership.search, which probes vectors[0] as PK and vectors[1] as the member vector. The i != pkPos guard prevents duplicates and colTypes is reassigned rather than appended, so columns.colTypes is not aliased. Gating on TableType == Entries instead of Pkey.Names is what fixes the physical-copy case; pk_filter_mem_test.go pins both the copied-def and physical-only variants.
  • copyIvfflatColumnType is strictly additive and matches the existing convention at build_index_util.go:203 and build_ddl.go:8362. It is also correct for SET (T_uint64 + Enumvalues is the documented isSetPlanType discriminator) and typed-array JSON (build_util.go:403). AutoIncr/constraints stay behind, asserted by the new plan test.
  • Tuple packing uses an 8-byte fixed buffer; the maximum encoding is 5 bytes (enumCode + uint16Code + 3-byte varint) and Err() is checked, so no silent truncation. No deallocator is involved, so omitting Close() leaks nothing. extractRowFromEveryVector yields types.Enum for T_enum, so the assertion matches the pre-existing one in convertColIntoSql.
  • The convertColIntoSql ENUM change ('2' → 2) carries no cross-package risk: pkg/cdc/util.go has its own untouched copy. For fulltext/hnsw the ENUM path was already unusable (DescString() → CAST(x as ENUM)), so nothing regresses.

Out-of-scope observation (pre-existing, not introduced here)
toIvfflatUpsert derives entryProj from projCols[len(projCols)-1], i.e. the last src column. With INCLUDE present that is the last INCLUDE column, not the vector at index 1, so async CDC using quantization 'int8'|'uint8' together with include(...) scales the wrong column. The indexing is semantically identical on origin/main (entryProj := cnames[len(cnames)-1], line 751) and predates this PR — it came from #25095, after INCLUDE landed in #24168 — and no existing BVT combines int8/uint8 quantization with INCLUDE. Worth a separate issue rather than a change here.

Local build/test was not possible in this worktree (CGo headers jemalloc.h/roaring.h/usearch.h absent), so the above is proven from code paths plus the PR's own recorded BVT expectations, not from a local run.

@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 follow-up review of a13cd0b07a9e0d18d34d35cd00f5bbecd61b14a8 against merge-base f42af4dfcba210fd91b6f1fc5d7b5a72704502ee: APPROVE. No remaining blocking finding in the complete implementation/test/result delta.

Design and ownership: source-key membership and the hidden physical composite PK now coexist in the reader's common initialization; no early return skips the physical sequence number needed by transaction-local reads. The directional VARCHAR-to-CHAR membership compatibility is shared by both consumers without weakening cardinality/NULL/payload checks. Hidden PK/INCLUDE columns copy value-bearing ENUM metadata without source constraints. Replay uses the existing typed tuple codec and the existing matching-domain assignment path, decoding only at the final projection; it does not introduce a second ENUM validator or turn strict user casts into permissive input.

All three earlier findings are closed by code and behavior evidence: physical-PK workspace filtering, public ENUM/CHAR regressions, and stored ENUM ordinal 0. For the last one, the regression distinguishes committed error ordinal 0 from the declared empty member, numeric labels and NULL, waits for real background maintenance, checks the active hidden version, and verifies a later zero-PK deletion/update still progresses. Strict user conversion still fails. The SERIAL_EXTRACT binder now carries the domain into assignment; the runtime decoder preserves the original ordinal, with NULL/type-mismatch/error handling retained.

Validation: fresh local focused tests exercise IvfflatSqlWriterEnumReplay, SerialExtractEnumDomain, IvfWorkspaceReaderPreservesPhysicalPK and IvfEntriesMembershipUsesOriginPrimaryKey. Reused exact-head CI run 38151634753, terminal success: the actual compose execution artifact records vector_ivf_membership.sql 160/160 and vector_ivfflat_include_dml_sync.sql 100/100, with zero failed/ignored/abnormal. The CHAR case explicitly checks an underfilled POST round followed by PRE and a nonexecuted FORCE fallback, rather than merely equal final rows.

Performance/unhappy paths: no additional TP scan, remote call, persistent state or lifecycle owner. Reader binding stays once per reader; domain reconstruction is once per emitted replay SQL, and tuple work is limited to ENUM replay fields. The small per-ENUM transport cost buys lossless committed-value recovery; no whole-query throughput claim is inferred. Existing writer reset and reader/vector ownership remain intact.

Accounting: implementation 9 files +123/-60; Go tests 8 files +339/-1; SQL cases/results 4 files +419/-0; documentation 0. Reviewed changed tests and expected results, not just production totals. No source changes or subagents.

@mergify mergify Bot added the queued label Oct 11, 2026
@mergify

mergify Bot commented Oct 11, 2026 •

Copy link
Copy Markdown
Contributor

Merge Queue Status

  • ✅ Entered queue — 2026-10-11 23:18 UTC · Rule: main · triggered by rule Automatic queue on approval for main
  • 🟠 Checks running · in-place
  • 🚫 Left the queue — 2026-10-11 23:23 UTC · at 1136fa83de433b53eb54e2cbc5170c480334f16b

This pull request spent 4 minutes 31 seconds in the queue, with no time running CI.

Reason

Pull request #29835 has been dequeued

Pull request from fork cannot be queued. This pull request comes from a fork, and Mergify needs the author's permission to update its branch.

The author needs to enable "Allow edits from maintainers" on this pull request.

Hint

You should look at the reason for the failure and decide if the pull request needs to be fixed or if you want to requeue it.
If you do update this pull request, it will automatically be requeued once the queue conditions match again.
If you think this was a flaky issue instead, you can requeue the pull request, without updating it, by posting a @mergifyio queue comment.

Waiting for any of
  • check-neutral = CI Required
  • check-skipped = CI Required
  • check-success = CI Required
All conditions

Tick the box to put this pull request back in the merge queue (same as @mergifyio queue).

  • Requeue this pull request

This branch was previously deployed

1 inactive deployment
ci — 1136fa83 Deployed Oct 12, 2026 by mergify[bot]
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/L Denotes a PR that changes [500,999] lines

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants