Skip to content

fix(vectorindex): don't retain an empty index generation, and keep a base index across COPY ALTER - #29028

Merged
XuPeng-SH merged 9 commits into
matrixorigin:mainfrom
cpegeric:bug_29011
Sep 17, 2026
Merged

XuPeng-SH merged 9 commits into
matrixorigin:mainfrom
cpegeric:bug_29011

Conversation

@cpegeric

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 #29011

What this PR does / why we need it:

Two defects that both leave a vector index serving from a generation that has no real index behind it.

1. An empty generation must not be retained in the cache

An early query during an ASYNC index build could load a not-ready / empty generation. Because the
async build populates the same version in place, the query CN then kept that empty generation
under the final cache key — so after the build committed, that CN went on serving stale results.

For ivfflat an empty index is a single NULL-vector centroid placeholder, so LoadCentroids leaves
Centroids nil and every query routes to bucket 1; lacking IsStale, ivfflat never self-healed
until a reindex or restart. hnsw/ivfpq/cagra self-healed through the IsStale sweep, but only after
the ~10 min window.

The shared VectorIndexCache already declines to retain a generation whose search struct reports
EmptyGeneration() == true (served, but not cached, so the next query reloads). This implements
that optional hook for all four algorithms:

algo empty generation
ivfflat Index != nil && Index.Centroids == nil
hnsw no models, or every readable model empty
ivfpq MultiIndex == nil && Overflow == nil (GPU)
cagra MultiIndex == nil && Overflow == nil (GPU)

hnsw fails closed: a model whose size cannot be read (nil usearch handle, or a failing
Len()) counts as populated, because reading it as vector-less would evict a full generation and
re-stream every model file on the next query.

Two invariants are recorded in comments so they are not re-litigated in review:

  • ivfflat deliberately ignores the entries table. The centroids are the only part the cache holds
    resident, so a Centroids == nil generation retains nothing either way — not caching it costs one
    re-read of the single placeholder row. Counting bucket-1 entries as "populated" would also re-open
    this issue whenever entries land under the version before the build commits the real centroids.
  • cagra/ivfpq: MultiIndex == nil is exactly buildMultiIndex's "no sub-index AND no overflow";
    the Overflow term is redundant and kept deliberately. A loaded sub-index whose rows were all
    CDC-deleted stays cached.

2. A COPY ALTER left cagra/ivfpq with no base index at all

CAGRA and IVF-PQ are identity-always-async, so cloneUnaffectedIndexes SKIPS the whole index
(SkipWholeIndex) and the replacement table's hidden index tables start empty. Their ISCP
consumer cannot repopulate them: CagraSync/IvfpqSync are stateless across flushes and only
APPEND tag=1 event chunks — the tag=0 sub-index is written solely by cagra_create/ivfpq_create.
AlterCopyInitSQL returned (false, ""), so the ts=0 replay left the whole table living in the CDC
tail with no base index: every query brute-forced the overflow, and a table large enough made that
overflow refuse admission on load.

Both now return the ALTER TABLE … ALTER REINDEX … <algo> FORCE_SYNC InitSQL with
startFromNow=true, run post-commit by the CDC's first iteration, arming the tail at the post-build
watermark — the same shape as their own RestoreInitSQL and as fulltext2's fix for #28837.

The rule is each algorithm's own async-CREATE choice, which faces the identical "empty hidden tables

  • ts=0 replay" situation: hnsw passes "" there because HnswSync builds the usearch model from the
    event stream, so its AlterCopyInitSQL stays ""; cuvs stashes the build SQL there, and now here
    too. The hooks.go / alter.go contracts previously claimed every algorithm but fulltext2 rebuilds
    from the ts=0 replay — never true for cuvs — and are corrected.

Test plan

Unit tests (all green on a GPU build — MO_CL_CUDA=1):

  • TestIvfflatEmptyGeneration — the real NULL-placeholder → Centroids == nil chain through Load,
    plus the built and not-loaded cases.
  • TestHnswEmptyGeneration — no models, all-empty models, a populated model, and an unreadable model
    (fail-closed).
  • TestIvfpqEmptyGeneration* / TestCagraEmptyGeneration* (//go:build gpu) — driven through the
    real load chain (buildOverflow → buildMultiIndex), covering the empty generation, the CDC-only
    small-data generation, and a real GpuIvfPq/GpuCagra sub-index. Mutation-checked: forcing the
    predicate to false fails the empty cases, forcing it to true fails both non-empty cases.
  • TestAlterCopyInitSQL (cagra + ivfpq) — the exact REINDEX SQL, backtick escaping in db/table/index
    identifiers, startFromNow == true, and the fail-closed missing-metadata-def path.

BVT:

  • gpu_cases/pessimistic_transaction/vector/vector_{cagra,ivfpq}_copy_alter.sql (new) — assert a
    tag=0 base before AND after ALTER TABLE … ADD COLUMN, plus correct search, row count and the new
    column. This is a gate, not smoke: the has_base probe reads 0 immediately after the ALTER and
    flips to 1 only once the seeded REINDEX runs. Both pass 46/46 on a GPU box.
  • cases/pessimistic_transaction/vector/vector_ivf_async_empty_cache.sql — end-to-end coverage of the
    async-build → warm → query flow; passes 19/19. Labelled as smoke coverage, since the not-ready
    window cannot be held open from SQL and its assertions also pass pre-fix; the deterministic proof is
    TestIvfflatEmptyGeneration.

Also verified live on a GPU box: after alter table t add column b int, the replacement ivfpq
storage table carries a tag=0 chunk within 15s, search returns the true neighbour, and all 200 rows
plus the new column survive.

cpegeric and others added 4 commits September 16, 2026 17:27
…matrixorigin#29011)

An early query during an ASYNC index build could load a not-ready / empty
generation and, because the async build populates the same version in place, the
query CN retained that empty generation under the final cache key -- so after the
build committed the real index that CN kept serving stale results. For ivfflat an
empty index is a single NULL-vector centroid placeholder, so LoadCentroids leaves
Centroids nil and every query routes to bucket 1; lacking IsStale, ivfflat never
self-healed until a reindex/restart. hnsw/ivfpq/cagra self-healed via the IsStale
sweep, but only after the ~10min window.

The shared VectorIndexCache already declines to retain a generation whose search
struct reports EmptyGeneration()==true (served but not cached, so the next query
reloads). Implement that optional hook for all four algorithms:

  - ivfflat: Index != nil && Index.Centroids == nil
  - hnsw:    no models, or every loaded model empty (0 vectors)
  - ivfpq:   MultiIndex == nil && Overflow == nil   (GPU)
  - cagra:   MultiIndex == nil && Overflow == nil   (GPU)

Unit tests cover ivfflat (the real NULL-placeholder -> Centroids nil chain via
Load, plus built and not-loaded cases) and hnsw. A BVT reproduces the issue's
async-build scenario end to end: it warms the ivf cache during the not-ready
window (via the Vector Index Scan), waits for the build to commit all entries,
then asserts the query returns the true nearest neighbor.

ivfpq/cagra are //go:build gpu and require a GPU box to build/test.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…xorigin#29011)

The EmptyGeneration hook landed for all four algorithms, but only ivfflat and hnsw
had unit coverage -- ivfpq/cagra are //go:build gpu. Add the GPU-tagged tests, driven
through the real load chain (buildOverflow then buildMultiIndex) rather than hand-set
fields, so they hold the predicate to the state a load actually produces:

  - no metadata rows, or rows whose models carry neither a deserialized sub-index nor
    CDC overflow -> MultiIndex nil -> EmptyGeneration true, and the result the cache
    serves from that generation is empty
  - CDC-only (small-data) generation: the tag=1 tail alone builds a brute-force
    overflow -> false, so a searchable generation is not evicted after every query
  - a deserialized base sub-index (a real GpuIvfPq / GpuCagra built in-test) -> false

Verified by mutation: forcing the predicate to false fails the empty cases in both
packages, forcing it to true fails both non-empty cases.

The shared cache path was reached only by fulltext2 when it was written; its comments
and eviction reason still said so. Generalize both and rename the reason to
"empty-generation" -- it is observability only (notifyCacheInvalidated has no
production implementer that reads it).

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01V5spSTbNWzypi8AFat9bfi
…in#29011)

Review follow-ups on the empty-generation hook.

hnsw's EmptyGeneration skipped a model whose Empty() errored (nil usearch handle, or a
failing usearch Len) and, if no other model answered cleanly, reported the whole
generation vector-less -- evicting a populated index and re-streaming every model file on
the next query. Count an unreadable model as populated instead: the opposite mistake only
keeps a vector-less generation until the IsStale sweep, which hnsw has.

Also state two invariants the predicates rely on, so they are not re-litigated:

  - ivfflat: entries deliberately do NOT enter the predicate. The centroids are the only
    part the cache holds resident, so a Centroids-nil generation retains nothing either
    way -- not caching it costs one re-read of the single placeholder row, and counting
    bucket-1 entries as populated would re-open this issue whenever entries land under the
    version before the build commits the real centroids.
  - cagra/ivfpq: MultiIndex nil is exactly buildMultiIndex's "no sub-index AND no
    overflow"; the Overflow term is redundant and kept deliberately. A loaded sub-index
    whose rows were all CDC-deleted stays cached.

The ivfflat BVT is labelled for what it is: end-to-end smoke coverage of the async-build
flow, not a pre/post gate (the not-ready window cannot be held open from SQL). The
deterministic proof is TestIvfflatEmptyGeneration.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01V5spSTbNWzypi8AFat9bfi
…cement keeps a base

CAGRA and IVF-PQ are identity-always-async, so a COPY ALTER's cloneUnaffectedIndexes
SKIPS the whole index (SkipWholeIndex) and the replacement table's hidden index tables
start EMPTY. Their ISCP consumer cannot repopulate them: CagraSync/IvfpqSync are stateless
across flushes and only APPEND tag=1 event chunks -- the tag=0 sub-index is written solely
by cagra_create/ivfpq_create. AlterCopyInitSQL returned (false, ""), so the ts=0 replay
left the whole table in the CDC tail with no base index at all: every query brute-forced
the overflow, and a table large enough made that overflow refuse admission on load.

Return the REINDEX FORCE_SYNC InitSQL instead, run post-commit by the CDC's first
iteration, then arm the tail at the post-build watermark -- the same shape as these
algorithms' own RestoreInitSQL and as fulltext2's fix for matrixorigin#28837. The rule is each algo's
own async-CREATE choice: hnsw passes "" there because HnswSync builds the usearch model
from the event stream, and its AlterCopyInitSQL stays "" for the same reason; cuvs stashes
the build SQL there, and now here too.

Verified on a GPU box: after `alter table t add column b int` the replacement ivfpq
storage table carries a tag=0 chunk within 15s, search returns the true neighbor, and all
rows plus the new column survive. Two GPU BVT cases assert it end to end (the has_base
probe reads 0 right after the ALTER and flips to 1 only once the seeded REINDEX runs, so
it is a gate, not smoke); unit tests cover the SQL, the identifier escaping, and the
fail-closed missing-metadata-def path.

The hooks.go and alter.go contracts said every algorithm but fulltext2 rebuilds from the
ts=0 replay -- never true for cuvs. Corrected to the real rule.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01V5spSTbNWzypi8AFat9bfi
@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 →

@mergify mergify Bot added the kind/bug Something isn't working label Sep 16, 2026
@matrix-meow matrix-meow added the size/XL Denotes a PR that changes [1000, 1999] lines label Sep 16, 2026
@cpegeric cpegeric changed the title Bug 29011 fix(vectorindex): don't retain an empty index generation, and keep a base index across COPY ALTER Sep 16, 2026

@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(当前 head e6e1e56d23d93914495277fc5f6ea631d10a16a4)。

P2 blocker — Search error path can retain an empty generation permanently

In cache.go#L1014-L1049, an entry can finish Load with emptyGen=true), but if the subsequent algorithm Searchreturns an error, the function returns at line 1038 before the!loaded && emptyGen` eviction at line 1048.

A reachable IVF-FLAT sequence is:

  1. During the async-build window, Load reads the NULL-centroid placeholder, so Centroids == nil and emptyGen == true.
  2. The following entries scan fails or is cancelled; IVF propagates that error (ivfflat/search.go#L821-L871).
  3. The cache returns the error while the STATUS_LOADED entry remains in IndexMap.
  4. A later successful query sees loaded == true, so the empty-generation eviction condition is skipped. IVF-FLAT has no IsStale; after real centroids are committed under the same version, this CN can continue using the bucket-1-only routing entry and refresh its TTL indefinitely.

Please evict/retire the exact empty generation on this post-load Search error (while preserving the existing retry/lifecycle ownership rules), and add a deterministic regression test covering: empty load → entries-search error/cancellation → build commits the same version → next query reloads real centroids. The current empty-generation unit test does not cover this cache failure/retry closure.

Non-blocking notes:

  • The normal successful empty-generation path and the CAGRA/IVF-PQ COPY ALTER FORCE_SYNC seeding look reasonable.
  • Required, SCA, UT, coverage, build and CPU BVT checks pass; Upgrade CI is skipped. GPU validation is described in the PR body but is not independently visible in the current required checks.

…fails (matrixorigin#29011)

The not-cache-empty rule was applied only on the success path. A query that LOADED a
generation and then failed -- an IVF-FLAT entries scan that errors or is cancelled -- left
that entry resident at STATUS_LOADED and returned. Only the loader ever retires an empty
generation (a later caller finds loaded==true and skips it) and IVF-FLAT has no IsStale,
so the stranded generation kept answering from the NULL-centroid placeholder, routing
every query to bucket 1 for as long as traffic refreshed its TTL -- the same defect this
issue is about, reached through the error path.

Fold the rule into one retireEmptyGeneration helper and call it on both the success and
the post-load error path, in Search and SearchInto. Ownership is unchanged: only the
loader retires, the retryable errIndexDestroyed path still loops without evicting, and a
POPULATED generation whose query failed stays cached -- a transient error says nothing
about the index.

TestCacheNotCacheEmptyRetiresOnSearchError is the failure-path twin of
TestCacheNotCacheEmptyReloadsBase: empty load -> search error -> the base is committed
under the same key -> the next query reloads and returns it, with no RemoveIdle and no
HouseKeeping in between. Mutation-checked (dropping the error-path call fails it), covers
Search and SearchInto, and asserts the populated-generation-survives-an-error case.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01V5spSTbNWzypi8AFat9bfi

@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 review of current head 0efc510.

The previous P2 is closed: after a successful Load, both Search and SearchInto now retire an empty generation on non-retryable search errors as well as on the success path. The per-iteration flag reset avoids judging a retry by the prior attempt, and the regression test covers error-path eviction, same-version reload, SearchInto, and retention of a populated generation.

I also audited the algorithm-specific EmptyGeneration predicates, the CAGRA/IVF-PQ COPY ALTER FORCE_SYNC seed and identifier quoting, cache eviction ownership, and the added CPU/GPU test coverage. No evidence-backed P0/P1/P2 remains. Required CI contexts are green; Upgrade/3.0 checks are skipped.

Decision: APPROVE.

@mergify mergify Bot added the queued label Sep 17, 2026
@mergify

mergify Bot commented Sep 17, 2026 •

Copy link
Copy Markdown
Contributor

Merge Queue Status

  • ✅ Entered queue — 2026-09-17 00:45 UTC · Rule: main · triggered by rule Automatic queue on approval for main
  • 🟠 Checks running · in-place
  • 🚫 Left the queue — 2026-09-17 00:48 UTC · at 39b53cbf948deac501c8e4c67493ab6efc0638d5

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

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

Reason

Pull request #29028 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.

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

  • Requeue this pull request

@XuPeng-SH
XuPeng-SH merged commit 4750501 into matrixorigin:main Sep 17, 2026
20 of 21 checks passed
@mergify mergify Bot added dequeued and removed queued labels Sep 17, 2026
VioletQwQ-0 pushed a commit to VioletQwQ-0/matrixone that referenced this pull request Sep 17, 2026
… base index across COPY ALTER (matrixorigin#29028)

## What type of PR is this?

- [ ] API-change
- [x] BUG
- [ ] Improvement
- [ ] Documentation
- [ ] Feature
- [ ] Test and CI
- [ ] Code Refactoring

## Which issue(s) this PR fixes:

issue matrixorigin#29011

## What this PR does / why we need it:

Two defects that both leave a vector index serving from a generation
that has no real index behind it.

  ### 1. An empty generation must not be retained in the cache

An early query during an ASYNC index build could load a not-ready /
empty generation. Because the
async build populates the **same version in place**, the query CN then
kept that empty generation
under the final cache key — so after the build committed, that CN went
on serving stale results.

For ivfflat an empty index is a single NULL-vector centroid placeholder,
so `LoadCentroids` leaves
`Centroids` nil and every query routes to bucket 1; lacking `IsStale`,
ivfflat never self-healed
until a reindex or restart. hnsw/ivfpq/cagra self-healed through the
`IsStale` sweep, but only after
  the ~10 min window.

The shared `VectorIndexCache` already declines to retain a generation
whose search struct reports
`EmptyGeneration() == true` (served, but not cached, so the next query
reloads). This implements
  that optional hook for all four algorithms:

  | algo | empty generation |
  |---|---|
  | ivfflat | `Index != nil && Index.Centroids == nil` |
  | hnsw | no models, or every readable model empty |
  | ivfpq | `MultiIndex == nil && Overflow == nil` (GPU) |
  | cagra | `MultiIndex == nil && Overflow == nil` (GPU) |

hnsw fails **closed**: a model whose size cannot be read (nil usearch
handle, or a failing
`Len()`) counts as populated, because reading it as vector-less would
evict a full generation and
  re-stream every model file on the next query.

Two invariants are recorded in comments so they are not re-litigated in
review:

* **ivfflat deliberately ignores the entries table.** The centroids are
the only part the cache holds
resident, so a `Centroids == nil` generation retains nothing either way
— not caching it costs one
re-read of the single placeholder row. Counting bucket-1 entries as
"populated" would also re-open
this issue whenever entries land under the version before the build
commits the real centroids.
* **cagra/ivfpq**: `MultiIndex == nil` is exactly `buildMultiIndex`'s
"no sub-index AND no overflow";
the `Overflow` term is redundant and kept deliberately. A loaded
sub-index whose rows were all
    CDC-deleted stays cached.

  ### 2. A COPY ALTER left cagra/ivfpq with no base index at all

CAGRA and IVF-PQ are identity-always-async, so `cloneUnaffectedIndexes`
SKIPS the whole index
(`SkipWholeIndex`) and the replacement table's hidden index tables start
**empty**. Their ISCP
consumer cannot repopulate them: `CagraSync`/`IvfpqSync` are stateless
across flushes and only
APPEND tag=1 event chunks — the tag=0 sub-index is written solely by
`cagra_create`/`ivfpq_create`.
`AlterCopyInitSQL` returned `(false, "")`, so the ts=0 replay left the
whole table living in the CDC
tail with no base index: every query brute-forced the overflow, and a
table large enough made that
  overflow refuse admission on load.

Both now return the `ALTER TABLE … ALTER REINDEX … <algo> FORCE_SYNC`
InitSQL with
`startFromNow=true`, run post-commit by the CDC's first iteration,
arming the tail at the post-build
watermark — the same shape as their own `RestoreInitSQL` and as
fulltext2's fix for matrixorigin#28837.

The rule is each algorithm's own async-CREATE choice, which faces the
identical "empty hidden tables
+ ts=0 replay" situation: hnsw passes `""` there because `HnswSync`
builds the usearch model from the
event stream, so its `AlterCopyInitSQL` stays `""`; cuvs stashes the
build SQL there, and now here
too. The `hooks.go` / `alter.go` contracts previously claimed every
algorithm but fulltext2 rebuilds
  from the ts=0 replay — never true for cuvs — and are corrected.

  ## Test plan

  **Unit tests** (all green on a GPU build — `MO_CL_CUDA=1`):

* `TestIvfflatEmptyGeneration` — the real NULL-placeholder → `Centroids
== nil` chain through `Load`,
    plus the built and not-loaded cases.
* `TestHnswEmptyGeneration` — no models, all-empty models, a populated
model, and an unreadable model
    (fail-closed).
* `TestIvfpqEmptyGeneration*` / `TestCagraEmptyGeneration*` (`//go:build
gpu`) — driven through the
real load chain (`buildOverflow` → `buildMultiIndex`), covering the
empty generation, the CDC-only
small-data generation, and a real `GpuIvfPq`/`GpuCagra` sub-index.
Mutation-checked: forcing the
predicate to `false` fails the empty cases, forcing it to `true` fails
both non-empty cases.
* `TestAlterCopyInitSQL` (cagra + ivfpq) — the exact REINDEX SQL,
backtick escaping in db/table/index
identifiers, `startFromNow == true`, and the fail-closed
missing-metadata-def path.

  **BVT:**

*
`gpu_cases/pessimistic_transaction/vector/vector_{cagra,ivfpq}_copy_alter.sql`
(new) — assert a
tag=0 base before AND after `ALTER TABLE … ADD COLUMN`, plus correct
search, row count and the new
column. This is a gate, not smoke: the `has_base` probe reads `0`
immediately after the ALTER and
flips to `1` only once the seeded REINDEX runs. Both pass 46/46 on a GPU
box.
*
`cases/pessimistic_transaction/vector/vector_ivf_async_empty_cache.sql`
— end-to-end coverage of the
async-build → warm → query flow; passes 19/19. Labelled as smoke
coverage, since the not-ready
window cannot be held open from SQL and its assertions also pass
pre-fix; the deterministic proof is
    `TestIvfflatEmptyGeneration`.

Also verified live on a GPU box: after `alter table t add column b int`,
the replacement ivfpq
storage table carries a tag=0 chunk within 15s, search returns the true
neighbour, and all 200 rows
  plus the new column survive.

---------

Co-authored-by: Claude Opus 4.8 (1M context) <[email protected]>
Co-authored-by: mergify[bot] <37929162+mergify[bot]@users.noreply.github.com>
VioletQwQ-0 pushed a commit to VioletQwQ-0/matrixone that referenced this pull request Sep 17, 2026
… base index across COPY ALTER (matrixorigin#29028)

## What type of PR is this?

- [ ] API-change
- [x] BUG
- [ ] Improvement
- [ ] Documentation
- [ ] Feature
- [ ] Test and CI
- [ ] Code Refactoring

## Which issue(s) this PR fixes:

issue matrixorigin#29011

## What this PR does / why we need it:

Two defects that both leave a vector index serving from a generation
that has no real index behind it.

  ### 1. An empty generation must not be retained in the cache

An early query during an ASYNC index build could load a not-ready /
empty generation. Because the
async build populates the **same version in place**, the query CN then
kept that empty generation
under the final cache key — so after the build committed, that CN went
on serving stale results.

For ivfflat an empty index is a single NULL-vector centroid placeholder,
so `LoadCentroids` leaves
`Centroids` nil and every query routes to bucket 1; lacking `IsStale`,
ivfflat never self-healed
until a reindex or restart. hnsw/ivfpq/cagra self-healed through the
`IsStale` sweep, but only after
  the ~10 min window.

The shared `VectorIndexCache` already declines to retain a generation
whose search struct reports
`EmptyGeneration() == true` (served, but not cached, so the next query
reloads). This implements
  that optional hook for all four algorithms:

  | algo | empty generation |
  |---|---|
  | ivfflat | `Index != nil && Index.Centroids == nil` |
  | hnsw | no models, or every readable model empty |
  | ivfpq | `MultiIndex == nil && Overflow == nil` (GPU) |
  | cagra | `MultiIndex == nil && Overflow == nil` (GPU) |

hnsw fails **closed**: a model whose size cannot be read (nil usearch
handle, or a failing
`Len()`) counts as populated, because reading it as vector-less would
evict a full generation and
  re-stream every model file on the next query.

Two invariants are recorded in comments so they are not re-litigated in
review:

* **ivfflat deliberately ignores the entries table.** The centroids are
the only part the cache holds
resident, so a `Centroids == nil` generation retains nothing either way
— not caching it costs one
re-read of the single placeholder row. Counting bucket-1 entries as
"populated" would also re-open
this issue whenever entries land under the version before the build
commits the real centroids.
* **cagra/ivfpq**: `MultiIndex == nil` is exactly `buildMultiIndex`'s
"no sub-index AND no overflow";
the `Overflow` term is redundant and kept deliberately. A loaded
sub-index whose rows were all
    CDC-deleted stays cached.

  ### 2. A COPY ALTER left cagra/ivfpq with no base index at all

CAGRA and IVF-PQ are identity-always-async, so `cloneUnaffectedIndexes`
SKIPS the whole index
(`SkipWholeIndex`) and the replacement table's hidden index tables start
**empty**. Their ISCP
consumer cannot repopulate them: `CagraSync`/`IvfpqSync` are stateless
across flushes and only
APPEND tag=1 event chunks — the tag=0 sub-index is written solely by
`cagra_create`/`ivfpq_create`.
`AlterCopyInitSQL` returned `(false, "")`, so the ts=0 replay left the
whole table living in the CDC
tail with no base index: every query brute-forced the overflow, and a
table large enough made that
  overflow refuse admission on load.

Both now return the `ALTER TABLE … ALTER REINDEX … <algo> FORCE_SYNC`
InitSQL with
`startFromNow=true`, run post-commit by the CDC's first iteration,
arming the tail at the post-build
watermark — the same shape as their own `RestoreInitSQL` and as
fulltext2's fix for matrixorigin#28837.

The rule is each algorithm's own async-CREATE choice, which faces the
identical "empty hidden tables
+ ts=0 replay" situation: hnsw passes `""` there because `HnswSync`
builds the usearch model from the
event stream, so its `AlterCopyInitSQL` stays `""`; cuvs stashes the
build SQL there, and now here
too. The `hooks.go` / `alter.go` contracts previously claimed every
algorithm but fulltext2 rebuilds
  from the ts=0 replay — never true for cuvs — and are corrected.

  ## Test plan

  **Unit tests** (all green on a GPU build — `MO_CL_CUDA=1`):

* `TestIvfflatEmptyGeneration` — the real NULL-placeholder → `Centroids
== nil` chain through `Load`,
    plus the built and not-loaded cases.
* `TestHnswEmptyGeneration` — no models, all-empty models, a populated
model, and an unreadable model
    (fail-closed).
* `TestIvfpqEmptyGeneration*` / `TestCagraEmptyGeneration*` (`//go:build
gpu`) — driven through the
real load chain (`buildOverflow` → `buildMultiIndex`), covering the
empty generation, the CDC-only
small-data generation, and a real `GpuIvfPq`/`GpuCagra` sub-index.
Mutation-checked: forcing the
predicate to `false` fails the empty cases, forcing it to `true` fails
both non-empty cases.
* `TestAlterCopyInitSQL` (cagra + ivfpq) — the exact REINDEX SQL,
backtick escaping in db/table/index
identifiers, `startFromNow == true`, and the fail-closed
missing-metadata-def path.

  **BVT:**

*
`gpu_cases/pessimistic_transaction/vector/vector_{cagra,ivfpq}_copy_alter.sql`
(new) — assert a
tag=0 base before AND after `ALTER TABLE … ADD COLUMN`, plus correct
search, row count and the new
column. This is a gate, not smoke: the `has_base` probe reads `0`
immediately after the ALTER and
flips to `1` only once the seeded REINDEX runs. Both pass 46/46 on a GPU
box.
*
`cases/pessimistic_transaction/vector/vector_ivf_async_empty_cache.sql`
— end-to-end coverage of the
async-build → warm → query flow; passes 19/19. Labelled as smoke
coverage, since the not-ready
window cannot be held open from SQL and its assertions also pass
pre-fix; the deterministic proof is
    `TestIvfflatEmptyGeneration`.

Also verified live on a GPU box: after `alter table t add column b int`,
the replacement ivfpq
storage table carries a tag=0 chunk within 15s, search returns the true
neighbour, and all 200 rows
  plus the new column survive.

---------

Co-authored-by: Claude Opus 4.8 (1M context) <[email protected]>
Co-authored-by: mergify[bot] <37929162+mergify[bot]@users.noreply.github.com>

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/XL Denotes a PR that changes [1000, 1999] lines

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants