[Bug]: COPY ALTER during pending ASYNC IVFFLAT initialization drops training and returns empty ANN results

Open
#33,280 0 comments 0 reactions 1 assignee View on GitHub

Maintainers usually reply within 1 day

@cpegeric is already working on this.

Since Nov 26, 2026.

Assessment

This issue has not been assessed yet.

Description

kind/bug severity/s0

Description

Tested on MatrixOne main commit c0cef5c9cce2164fedd201c188bfffe4d2d09a96 (git_version() = c0cef5c) with experimental_ivf_index=1.

If an unrelated COPY ALTER (for example, ADD COLUMN) runs while ASYNC IVFFLAT initialization is still pending, the ALTER succeeds but the replacement index permanently loses its initialization path. Both centroids and entries remain empty. Indexed ANN returns no rows while mode=force returns the correct base-table rows.

Unlike a normal initialization failure, the replacement ISCP job keeps advancing its watermark and reports running with no visible error, so the false-empty index does not recover by waiting.

Runnable reproduction

The script includes an initialization-complete positive control followed by the pending-initialization failure. It discovers the hidden IVFFLAT tables from mo_catalog.mo_indexes; no hard-coded internal table names are needed.

Python reproducer (requires `pymysql`)
import time
import pymysql

conn = pymysql.connect(host='127.0.0.1', port=6001,
                       user='root', password='111', autocommit=True)
DB = 'qa_ivf_add_ready'

def fetch(cur, sql, params=None):
    cur.execute(sql, params)
    return cur.fetchall() if cur.description else ()

def hidden(cur, table, kind):
    rows = fetch(cur, """
        SELECT index_table_name FROM mo_catalog.mo_indexes
        WHERE algo='ivfflat' AND algo_table_type=%s
          AND table_id IN (
            SELECT rel_id FROM mo_catalog.mo_tables
            WHERE reldatabase=%s AND relname=%s)
    """, (kind, DB, table))
    return rows[0][0] if rows else None

def counts(cur, table):
    result = {}
    for kind in ('metadata', 'centroids', 'entries'):
        name = hidden(cur, table, kind)
        result[kind] = fetch(cur,
            f'SELECT COUNT(*) FROM {DB}.`{name}`')[0][0] if name else None
    return result

def wait_counts(cur, table, centroids, entries, timeout=40):
    deadline = time.time() + timeout
    last = None
    while time.time() < deadline:
        try:
            last = counts(cur, table)
            if last['centroids'] >= centroids and last['entries'] >= entries:
                return last
        except Exception as e:
            last = str(e).splitlines()[0][:500]
        time.sleep(0.25)
    return last

def run(cur, name, sql):
    try:
        rows = fetch(cur, sql)
        print(name, 'OK', rows)
    except Exception as e:
        print(name, 'ERR', str(e).splitlines()[0][:800])

with conn.cursor() as cur:
    cur.execute('SET experimental_ivf_index=1')
    cur.execute(f'DROP DATABASE IF EXISTS {DB}')
    cur.execute(f'CREATE DATABASE {DB}')
    cur.execute(f'USE {DB}')

    # Positive control: wait for training before the same COPY ALTER.
    cur.execute('CREATE TABLE ready_t(id INT PRIMARY KEY,v VECF32(2))')
    cur.execute("INSERT INTO ready_t VALUES(1,'[1,2]'),(2,'[3,4]')")
    cur.execute("CREATE INDEX ivf USING ivfflat ON ready_t(v) "
                "LISTS=1 OP_TYPE 'vector_l2_ops' ASYNC")
    print('ready-before-alter', wait_counts(cur, 'ready_t', 1, 2))
    run(cur, 'ready-alter', 'ALTER TABLE ready_t ADD COLUMN x INT DEFAULT 0')
    print('ready-after-alter', wait_counts(cur, 'ready_t', 1, 2))
    run(cur, 'ready-ann',
        "SELECT id FROM ready_t ORDER BY l2_distance(v,'[5,6]') "
        "LIMIT 2 BY RANK WITH OPTION 'mode=post'")

    # Failure: ALTER immediately, while the deferred build is still pending.
    cur.execute('CREATE TABLE pending_t(id INT PRIMARY KEY,v VECF32(2))')
    cur.execute("INSERT INTO pending_t VALUES(1,'[1,2]')")
    cur.execute("CREATE INDEX ivf USING ivfflat ON pending_t(v) "
                "LISTS=1 OP_TYPE 'vector_l2_ops' ASYNC")
    run(cur, 'pending-immediate-alter',
        'ALTER TABLE pending_t ADD COLUMN x INT DEFAULT 0')
    run(cur, 'pending-insert',
        "INSERT INTO pending_t(id,v,x) VALUES(2,'[3,4]',2)")
    print('pending-after-alter',
          wait_counts(cur, 'pending_t', 1, 2, timeout=30))
    run(cur, 'pending-ann',
        "SELECT id FROM pending_t ORDER BY l2_distance(v,'[5,6]') "
        "LIMIT 2 BY RANK WITH OPTION 'mode=post'")
    run(cur, 'pending-force',
        "SELECT id FROM pending_t ORDER BY l2_distance(v,'[5,6]') "
        "LIMIT 2 BY RANK WITH OPTION 'mode=force'")
    run(cur, 'pending-init-sql', """
        SELECT LENGTH(JSON_UNQUOTE(JSON_EXTRACT(job_spec,'$.InitSQL'))),
               watermark,job_status
        FROM mo_catalog.mo_iscp_log
        WHERE table_id IN (
          SELECT rel_id FROM mo_catalog.mo_tables
          WHERE reldatabase='qa_ivf_add_ready' AND relname='pending_t')
          AND drop_at IS NULL
    """)

Observed output:

ready-before-alter:    {'metadata': 3, 'centroids': 1, 'entries': 2}
ready-alter:           OK
ready-after-alter:     {'metadata': 3, 'centroids': 1, 'entries': 2}
ready-ann:             (2),(1)

pending-immediate-alter: OK
pending-insert:          OK
pending-after-alter:     {'metadata': 3, 'centroids': 0, 'entries': 0}
pending-ann:             ()
pending-force:           (2),(1)
pending InitSQL length:  0

In an independent reproduction, SHOW INDEX STATUS still reported running with Error_message=NULL, the base table contained both committed rows, and the replacement job's watermark advanced while centroids and entries remained zero. A second fresh database produced the same result.

Expected behavior

COPY ALTER must preserve or restart pending IVFFLAT training. Once the ALTER succeeds, the replacement index must eventually contain the source rows and return ANN results consistent with the exact-scan control. If initialization cannot safely be preserved, the ALTER should fail explicitly or the index should remain ineligible for indexed ANN until it is rebuilt; a running, error-free, permanently empty index is incorrect.

Code analysis and controls

pkg/sql/compile/alter.go handles an unaffected IVFFLAT index through AlterCopyInitSQL. At the tested commit, pkg/vectorindex/ivfflat/plugin/compile/compile.go returns an empty initialization SQL for this path, assuming metadata and centroids were cloned and entries can be rebuilt from the source log.

That assumption is false before initial training: the pending source has no centroids to clone. The replacement therefore has neither a model nor an ivf_create initialization statement. Replay can advance its watermark, but cannot create the missing centroids/entries.

Controls distinguish this from a general COPY ALTER problem:

  • Waiting for centroids/entries before the identical ADD COLUMN preserves the model and correct ANN results.
  • A no-ALTER ASYNC IVFFLAT control builds normally.
  • Immediate TRUNCATE TABLE followed by reinsertion also rebuilds correctly.

This also differs from the pending-RENAME defect: RENAME leaves stale non-empty InitSQL and repeated visible worker errors; COPY ALTER discards the pending initialization and registers empty InitSQL, with an advancing watermark and no error.

Duplicate check

Searched IVFFLAT COPY ALTER, ASYNC ADD COLUMN, empty InitSQL, and missing centroids/entries. #31611 concerns COPY ALTER itself failing during concurrent HNSW initialization; #29042 concerns PRE membership after an already-built IVFFLAT index is copied; #28837 concerns FULLTEXT2. None covers this pending-IVFFLAT empty-training path.

Dominant language
Go
Stars
1.9k
Forks
312
Avg merge
22h 59m
Merged PRs (30d)
736

Getting set up

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

More from matrixorigin/matrixone

All issues in matrixorigin/matrixone

Similar issues

More Go issues

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.