Skip to content

FIX: CREATE/ALTER/REPLACE VIEW persists unusable MATCH queries without a matching FULLTEXT index - #27171

Merged
aptend merged 26 commits into
matrixorigin:mainfrom
cpegeric:fulltext_view_fail
Aug 19, 2026
Merged

aptend merged 26 commits into
matrixorigin:mainfrom
cpegeric:fulltext_view_fail

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

What this PR does / why we need it:

What this fixes

Closes #27027.

CREATE VIEW … MATCH(col) AGAINST('x') was accepted even when no FULLTEXT index could serve
that MATCH. The view then failed on every SELECT with

20105: MATCH() AGAINST() function cannot be replaced by FULLTEXT INDEX and
       full table scan with fulltext search is not supported yet

and — the part that made it more than a nuisance — such a view aborted snapshot restore,
PITR and CLONE entirely
, because restore replays the stored CREATE VIEW. One unrunnable
legacy view made a whole account unrestorable.

Fixing that exposed why people write these views: a MATCH wrapped in anything at all was never
served. round(match(…),3), cast(…), match(…) * 100, match(…) > 0.5, a score selected
across a join — all threw 20105, so the error looked arbitrary rather than like a missing index.
This PR does both halves: refuse the view that can never run, and make the shapes people actually
write work.


Query shapes: before and after

Fixture used throughout (classic fulltext; fulltext2 behaves the same unless noted):

create table two(id int primary key, body text);
insert into two values (1,'hello'),(2,'hello hello'),(3,'hello hello hello'),
                       (4,'world'),(5,'hello hello world');
create fulltext index ft on two(body);

Scalar wrappers in the projection

SQL Before After
select id, match(body) against('hello') from two where match(body) against('hello') ok ok
select id, round(match(body) against('hello'),3) … 20105 ok
select id, cast(match(body) against('hello') as decimal(10,3)) … 20105 ok
select id, match(body) against('hello') * 100 … 20105 ok
select id, round(match(body) against('hello') + 1, 3) … 20105 ok
select id, match(…) as sc, round(match(…),3) as r … (bare and wrapped copy of one match) 20105 ok —
both resolve to the same stream

Score in a predicate

SQL Before After
… where match(body) against('hello') and match(body) against('hello') > 0.015 20105 ok
… where match(body) against('hello') and round(match(…),4) > 0.015 20105 ok
… where match(body) against('hello') and cast(match(…) as double) > 0.015 20105 ok
… where match(body) against('hello') and match(…) * 2 > 0.03 20105 ok
… where match(body) against('hello') and match(…) < 0.015 20105 ok
… where match(body) against('hello') and not (match(…) > 0.015) 20105 ok
… where match(body) against('hello') and (match(…) < 0.015 or id = 3) 20105 ok
select id from v where sc > 0.05 (view exposing the score as sc) 20105 ok
select id from (select id, match(…) as sc …) x where sc > 0.05 20105 ok

A wrapped MATCH with no bare MATCH to lean on

SQL Before After
select id from two where match(body) against('hello') > 0.015 20105 ok
select id, round(match(body) against('hello'),3) from two (no WHERE MATCH) 20105 ok
select count(*) from two where match(body) against('hello') > 0.015 20105 ok
select id from two where match(body) against('hello') > 0.015 limit 1 20105 ok
select id from two order by round(match(body) against('hello'),3) desc 20105 ok

Rows now come back in relevance order for these, exactly as a bare MATCH does — previously the
rewrite produced a SORT node with no keys at all.

Several MATCHes in one query

SQL Before After
select id, match(…'hello') h, match(…'world') w from two where match(…'hello') and match(…'world') ok ok
select id, round(match(…'world'),3) w … where match(…'hello') and match(…'world') 20105 ok — reports the
world score
select id, round(match(…'world'),3) … where match(…'hello') wrong number (silently the hello score) ok —
'world' gets its own stream
… where match(…'hello') and match(…'world') and match(…'world') > 0.1 20105 ok — reuses the 'world'
stream

JOIN

SQL Before After
select a.id, b.note from a join b on a.id=b.id where match(a.body) against('x') ok ok
select a.id, match(a.body) against('x') from a join b … 20105 ok
select a.id, round(match(a.body) against('x'),3) from a join b … 20105 ok
select a.id, match(a.body) against('x') sa, match(b.body) against('x') sb from a join b … 20105 ok —
different scores per table
select a.id from a join b … order by match(a.body) against('x') desc 20105 ok
select a.id from a join b … where match(a.body) against('x') > 0.02 20105 ok
select id from two where match(body) against('x') > 0.02 and id in (select id from jb) (SEMI) 20105 ok
self join a x join a y, each side its own MATCH 20105 ok
a left join b, MATCH on the outer side 20105 ok
UNION ALL of two joined fulltext queries; a CTE referenced twice 20105 ok

The cross-table row is the one worth a second look: sa and sb must be different numbers on
the same row
. Index parts are otherwise compared by column name, and with two tables in scope
match(a.body) and match(b.body) look identical — so resolution across a join is binding-tag
aware.
| select id, match(…) as sc, round(match(…),3) as r … (bare and wrapped copy of one match) | 20105 | ok —
both resolve to the same stream |

Score in a predicate

SQL Before After
… where match(body) against('hello') and match(body) against('hello') > 0.015 20105 ok
… where match(body) against('hello') and round(match(…),4) > 0.015 20105 ok
… where match(body) against('hello') and cast(match(…) as double) > 0.015 20105 ok
… where match(body) against('hello') and match(…) * 2 > 0.03 20105 ok
… where match(body) against('hello') and match(…) < 0.015 20105 ok
… where match(body) against('hello') and not (match(…) > 0.015) 20105 ok
… where match(body) against('hello') and (match(…) < 0.015 or id = 3) 20105 ok
select id from v where sc > 0.05 (view exposing the score as sc) 20105 ok
select id from (select id, match(…) as sc …) x where sc > 0.05 20105 ok

A wrapped MATCH with no bare MATCH to lean on

SQL Before After
select id from two where match(body) against('hello') > 0.015 20105 ok
select id, round(match(body) against('hello'),3) from two (no WHERE MATCH) 20105 ok
select count(*) from two where match(body) against('hello') > 0.015 20105 ok
select id from two where match(body) against('hello') > 0.015 limit 1 20105 ok
select id from two order by round(match(body) against('hello'),3) desc 20105 ok

Rows now come back in relevance order for these, exactly as a bare MATCH does — previously the
rewrite produced a SORT node with no keys at all.

Several MATCHes in one query

SQL Before After
select id, match(…'hello') h, match(…'world') w from two where match(…'hello') and match(…'world') ok ok
select id, round(match(…'world'),3) w … where match(…'hello') and match(…'world') 20105 ok — reports the
world score
select id, round(match(…'world'),3) … where match(…'hello') wrong number (silently the hello score) ok —
'world' gets its own stream
… where match(…'hello') and match(…'world') and match(…'world') > 0.1 20105 ok — reuses the 'world'
stream

JOIN

| SQL | Before | After |

  • New moerr.ErrFtMatchingKeyNotFound (20327) → MySQL ER_FT_MATCHING_KEY_NOT_FOUND (1191).
    Recognised by code and message text, because the background executor rebuilds the error on
    the way back and strips the code — verified end to end; a code-only guard did not fire.

3 · A wrapped MATCH is served (5987e15add, 3befd17a9e, c7c796efc3, 06d3bf8ab6,
4a2306eadd, 1fa54fe6c3, 5adc55823c, 8e113d37f3, 154241f0bc)

  • Resolved by argument, not by function name. equalsFullTextMatchFunc (pattern, mode, index
    parts) decides which stream answers a given MATCH — the same test that already builds eqmap.
  • A wrapped MATCH can drive the rewrite, from a membership-implying position only:
    AND-reachable, score > c (c ≥ 0) or score >= c (c > 0), through order-preserving wrappers.
  • Wired into the projection, aggregate and join-child dispatches, and into the fulltext2 covered
    fast path (reachable when the MATCH column is the primary key).
  • The lifted predicate goes in a Node_FILTER, not Node_JOIN.FilterList — the planner never
    sets that field and the executor never reads it, though EXPLAIN prints it.
  • Resolution over a join records what each child's rewrite served, then matches binding-tag aware.

4 · fulltext2 pushes a score range into the engine (c3a50a16eb)

An AND-reachable MATCH(…) <op> const becomes a fulltext2.ScoreRange handed to the search,
which drops out-of-range documents at streamSink.push* / runTopK instead of shipping them
across the join. A range, not a min_score, so >/>=/</<= and their AND-combinations are
| select id, match(…) as sc, round(match(…),3) as r … (bare and wrapped copy of one match) | 20105 | ok —
both resolve to the same stream |

Score in a predicate

SQL Before After
… where match(body) against('hello') and match(body) against('hello') > 0.015 20105 ok
… where match(body) against('hello') and round(match(…),4) > 0.015 20105 ok
… where match(body) against('hello') and cast(match(…) as double) > 0.015 20105 ok
… where match(body) against('hello') and match(…) * 2 > 0.03 20105 ok
… where match(body) against('hello') and match(…) < 0.015 20105 ok
… where match(body) against('hello') and not (match(…) > 0.015) 20105 ok
… where match(body) against('hello') and (match(…) < 0.015 or id = 3) 20105 ok
select id from v where sc > 0.05 (view exposing the score as sc) 20105 ok
select id from (select id, match(…) as sc …) x where sc > 0.05 20105 ok

A wrapped MATCH with no bare MATCH to lean on

SQL Before After
select id from two where match(body) against('hello') > 0.015 20105 ok
select id, round(match(body) against('hello'),3) from two (no WHERE MATCH) 20105 ok
select count(*) from two where match(body) against('hello') > 0.015 20105 ok
select id from two where match(body) against('hello') > 0.015 limit 1 20105 ok
select id from two order by round(match(body) against('hello'),3) desc 20105 ok

Rows now come back in relevance order for these, exactly as a bare MATCH does — previously the
rewrite produced a SORT node with no keys at all.

Several MATCHes in one query

SQL Before After
select id, match(…'hello') h, match(…'world') w from two where match(…'hello') and match(…'world') ok ok
select id, round(match(…'world'),3) w … where match(…'hello') and match(…'world') 20105 ok — reports the
world score
select id, round(match(…'world'),3) … where match(…'hello') wrong number (silently the hello score) ok —
'world' gets its own stream
… where match(…'hello') and match(…'world') and match(…'world') > 0.1 20105 ok — reuses the 'world'
stream

JOIN

SQL Before After
select a.id, b.note from a join b on a.id=b.id where match(a.body) against('x') ok ok
select a.id, match(a.body) against('x') from a join b … 20105 ok
select a.id, round(match(a.body) against('x'),3) from a join b … 20105 ok
select a.id, match(a.body) against('x') sa, match(b.body) against('x') sb from a join b … 20105 ok —
different scores per table
select a.id from a join b … order by match(a.body) against('x') desc 20105 ok
select a.id from a join b … where match(a.body) against('x') > 0.02 20105 ok
select id from two where match(body) against('x') > 0.02 and id in (select id from jb) (SEMI) 20105 ok
self join a x join a y, each side its own MATCH 20105 ok
a left join b, MATCH on the outer side 20105 ok
UNION ALL of two joined fulltext queries; a CTE referenced twice 20105 ok

The cross-table row is the one worth a second look: sa and sb must be different numbers on
the same row
. Index parts are otherwise compared by column name, and with two tables in scope
match(a.body) and match(b.body) look identical — so resolution across a join is binding-tag
aware.

Still unsupported — and why

SQL Result Reason
where match(body) against('x') > 0.5 or id = 4 20105 The stream is INNER JOINed, so a MATCH may only drive
from a position that implies index membership. Under OR the predicate need not hold for a returned row; harvesting it
silently dropped id = 4 (see below).
where not match(body) against('x') 20105 same
where match(body) against('x') < 0.015 (no bare MATCH) 20105 A non-matching document scores 0, so < c is
true for rows the stream does not contain. Needs the stream LEFT joined with a 0 default — MySQL's model, separate
change.
where match(body) against('x') >= 0 20105 same: relevance 0 satisfies it
prepared select match(body) against(?) … from a join b … where match(body) against(?) 20105 the two ? are
distinct expressions, so the projected MATCH matches no stream; over a join a projected MATCH can only be *resolved
against* a stream, not create one
correlated subquery + MATCH 20105 pre-existing — fails with no projected score either
MATCH + window function 20105 pre-existing planner gap
MATCH on a column with no FULLTEXT index 20105 correct, unchanged

Changes

1 · Refuse a view definition that can never run (78ccb8f6c0, 9227524b80, 4cfbd71b58)

  • New index-plugin hook ValidateViewDefinition(ctx, query), consulted for every registered
    algorithm from genViewTableDef on the optimized plan — a placeholder is only known to be
    unservable after the rewrite has had its chance.
  • fulltext and fulltext2 implement it via the shared RefuseUnservableMatch; the vector plugins
    return nil and document why (their distance functions are real kernels, so a missed index is a
    slow query, not a broken view).
  • Reachability walk from query.Steps, not the node arena — a successful rewrite abandons
    pre-rewrite nodes there, and scanning them refused valid views.
  • Skipped when optimizer_hints has switched applyIndices off: a diagnostic knob must not
    silently become DDL policy. Both readers now share splitOptimizerHint, so the guard can no
    longer believe a hint the optimizer actually ignored.

2 · A legacy unservable view no longer breaks restore (0d7356d079, 44d4ac95b1, f41277c837)

  • Tolerated in the dependency sort and the create loop, on all three paths: restoreViews
    (snapshot + clone), restoreViewsWithPitr, and restoreViewsFromTS (cluster snapshot — this
    one had no tolerance at all and still aborted an entire account restore).
  • The view stays in the toposort so dependents still order correctly, and any existing object of
    that name is left alone rather than dropped: the snapshot may hold an unservable definition
    while the target holds a working view whose index was recreated since. A stale object is an
    inconsistency; deleting a working one is data loss.
  • New moerr.ErrFtMatchingKeyNotFound (20327) → MySQL ER_FT_MATCHING_KEY_NOT_FOUND (1191).
    Recognised by code and message text, because the background executor rebuilds the error on
    the way back and strips the code — verified end to end; a code-only guard did not fire.

3 · A wrapped MATCH is served (5987e15add, 3befd17a9e, c7c796efc3, 06d3bf8ab6,
4a2306eadd, 1fa54fe6c3, 5adc55823c, 8e113d37f3, 154241f0bc)

  • Resolved by argument, not by function name. equalsFullTextMatchFunc (pattern, mode, index
    parts) decides which stream answers a given MATCH — the same test that already builds eqmap.
  • A wrapped MATCH can drive the rewrite, from a membership-implying position only:
    AND-reachable, score > c (c ≥ 0) or score >= c (c > 0), through order-preserving wrappers.
  • Wired into the projection, aggregate and join-child dispatches, and into the fulltext2 covered
    fast path (reachable when the MATCH column is the primary key).
  • The lifted predicate goes in a Node_FILTER, not Node_JOIN.FilterList — the planner never
    sets that field and the executor never reads it, though EXPLAIN prints it.
  • Resolution over a join records what each child's rewrite served, then matches binding-tag aware.

4 · fulltext2 pushes a score range into the engine (c3a50a16eb)

An AND-reachable MATCH(…) <op> const becomes a fulltext2.ScoreRange handed to the search,
which drops out-of-range documents at streamSink.push* / runTopK instead of shipping them
across the join. A range, not a min_score, so >/>=/</<= and their AND-combinations are
one object with the tightest bound per side. Each bound is widened outward by one float32 ULP
(SQL compares in double, the engine scores in float32) and the plan keeps its own Filter, so the
pushdown can only remove work, never rows. Classic fulltext has no scoring engine of its own and
is unchanged.

5 · vector_ivf_retry made deterministic (26864bfdc0)

Two cases asserted outcomes ivfflat clustering decides at random — a probe_limit = 1 row count
that varied 4↔5 between builds, and a limit 2 over a three-way distance tie where any two of
three rows were equally correct. Both reproduce on main; the branch only made them visible.

Behaviour changes reviewers should look at

Before After Note
CREATE VIEW with an unservable MATCH succeeded fails with ER 1191 intentional, MySQL parity. Existing views
unaffected — restore skips them
wrapped MATCH → 20105 returns rows the main capability change
where match(…) > 0.5 or id = 4 still 20105 may only drive from a membership-implying position
two different MATCHes in one query rows matching both (INNER JOIN) pre-existing for bare MATCH, now reachable
from more shapes. MySQL returns the others at relevance 0
projection-only MATCH only matching rows pre-existing; MySQL returns non-matching rows at relevance 0

Known gaps and decisions (deliberate — recorded so review needn't re-litigate them)

  • OR / NOT / < c cannot drive a stream — needs the stream LEFT joined with a 0 default.
  • Prepared statement projecting a score over a join — distinct ? placeholders.
  • Correlated subquery + MATCH, MATCH + window function — pre-existing gaps.
  • CLONE reports success while omitting an unservable view, consistent with the
    skipIfDependencyMissing=true it already passes.
  • DROP INDEX under a dependent view stays allowed — MySQL parity, measured (MySQL also
    permits DROP COLUMN / DROP TABLE under a view). Decision recorded in viewdef.go.
  • Wrapped-only streams get no runtime-filter probe — performance only, deferred rather than
    bundled into correctness fixes.

Testing

BVT on a clean instance:

suite result
fulltext 1328 / 1331 — 0 failed
fulltext2 566 / 566
vector 1528 / 1530 — 0 failed
snapshot 17738 / 17738
pitr 506 / 506

go test ./pkg/sql/plan ./pkg/frontend ./pkg/fulltext2 ./pkg/sql/colexec/table_function — ok.

New cases: fulltext_view_ddl, fulltext_wrapped_score, fulltext_join_score,
fulltext2_view_ddl, fulltext2_wrapped_score, vector_view_ddl,
snapshot_restore_unservable_view — plus unit tests for the view-definition walk, the
argument-aware resolution, the score-range construction and interval semantics, the stream sink
honouring a range, and hint-parser parity with handleOptimizerHints.

Thresholds in the new cases are deliberately discriminating — two search terms with distinct
expected scores, and LIMIT cases whose qualifying rows are not the top-scoring ones. An earlier
revision of this work passed a whole suite of sc > 0 assertions while attaching the lifted
predicate to Node_JOIN.FilterList: every matching row satisfies > 0, so a predicate that was
never applied looked identical to a correct one.

Snapshot restore and PITR were additionally verified by hand against a live server; the fulltext2
score-range pushdown is verified by a Go test that exercises the engine directly, because an
end-to-end result cannot distinguish "the engine filtered it" from "the Filter above did".

Review history

Two full review passes. The first found the Node_JOIN.FilterList no-op and the argument-matching
defect. The second found a MATCH under OR/NOT driving an INNER-JOINed stream — `where match(…)

0.5 or id = 4returned the empty set instead ofid = 4` — and the missing tolerance on the
cluster-snapshot restore path. Both rounds' findings are fixed or recorded above.

Every row in those tables is a shape I ran against a live server this session, not one I inferred from reading the
rewrite — including the ones in the "still unsupported" table, which is why each has a reason rather than a shrug.

cpegeric and others added 19 commits August 13, 2026 11:30
…rigin#27027)

CREATE VIEW, ALTER VIEW and CREATE OR REPLACE VIEW all accepted a defining SELECT
containing MATCH() AGAINST() with no FULLTEXT index able to serve it. The object
was persisted and every query against it then failed:

  ERROR 20105: not supported: MATCH() AGAINST() function cannot be replaced by
  FULLTEXT INDEX and full table scan with fulltext search is not supported yet.

Worse, ALTER and CREATE OR REPLACE reported success while replacing a working
definition with the broken one, so the old view was gone.

MATCH() AGAINST() binds to fulltext_match, a placeholder with no evaluable
implementation that the fulltext rewrite is expected to replace with an index
scan. When no index matches, the filter keeps fulltext_match and an unmatched
projection is converted to the equally unevaluable fulltext_match_score. Planning
still succeeds, so view DDL -- the one statement that STORES a query without
running it -- committed something that could never execute.

Fixed with a plan-layer plugin hook rather than a fulltext special case in the
SQL layer, so pkg/sql/plan gains no per-algorithm knowledge (it does not contain
the string "fulltext_match"):

  - planplugin.Hooks.ValidateViewDefinition, consulted for EVERY registered algo
  - planplugin.PlanCallsAnyFunc, the shared reachability walker
  - fulltext and fulltext2 refuse a surviving placeholder
  - the four vector plugins return nil

Vector returns nil because a vector index is an optimization, not a precondition:
l2_distance and friends are real kernels, so a view whose plan misses the index
still runs as a brute-force scan and sort. Verified with no index, with a
mismatched op_type, and under mode=force -- all plan as Sort -> Table Scan and
return correct rows.

Testing the OPTIMIZED plan reuses the planner's own matching decision instead of
restating findMatchFullTextIndex's rules (exact column-set match, storage-vs-
metadata index defs, literal-only mode argument), which would drift from it.
Rejecting before any DDL plan is emitted is also what makes ALTER and REPLACE
atomic: the existing view is simply never touched.

Two traversal details decide whether this works at all, and both cost a
false result before they were found:

Reachability. The walk follows Children from query.Steps, NOT the query.Nodes
array. That array is an append-only arena, and a SUCCESSFUL rewrite abandons its
pre-rewrite nodes in it -- the fulltext rewrite re-parents the scan under a join
with the index scan and leaves the original FILTER behind, still holding the
original fulltext_match. Scanning the arena rejected every CREATE VIEW carrying a
WHERE MATCH against a real FULLTEXT(body) index.

Completeness. plan.Node has 19 expression-bearing fields and Expr has variants
that nest further; walking a subset does not weaken the check, it silently
defeats it for the shapes that use the rest. `OVER (ORDER BY MATCH(...))` needs
BOTH the WinSpecList field AND descent into the Expr_W it holds, since the MATCH
sits in the WindowSpec's own OrderBy -- adding the field alone still let the view
persist. Every Expr field is now walked, anchored to the field list the planner's
own whole-node walkers use and widened beyond it.

Ten shapes with a valid index -- join, derived table, CTE, GROUP BY, ORDER BY
score, LIMIT, boolean mode, MATCH AND predicate, IN (subquery) -- were checked to
confirm the guard refuses only genuinely unservable definitions: all ten accepted.
A window MATCH is refused even WITH a matching index, correctly: the rewrite does
not reach into a window spec, so the direct query fails with the same 20105 and
the view could never run.

Tests: unit coverage at all three layers (walker: every expression list, window
specs, nesting, the orphan case, cycles and out-of-range ids; both fulltext
plugins; all four vector plugins asserting they never refuse), plus BVT cases for
fulltext, fulltext2 and vector. The vector case exists so this hook cannot regress
into rejecting index-less vector views. Every new unit case was confirmed to fail
with its field or descent removed.

Verified: fulltext 1220/1223 (3 ignored, 0 failed), fulltext2 474/474, vector
1526/1530 with only the pre-existing vector_ivf_retry tie-ordering failure, proven
by rebuilding from a clean stash.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
… PITR / clone

Self-review follow-up to the matrixorigin#27027 guard in the parent commit. Refusing view DDL
in genViewTableDef also refuses the CREATE VIEW that RESTORE, PITR and CLONE
replay from a snapshot -- and all three DROP the view immediately before
re-creating it:

  snapshot.go:1485 drop -> :1493 create   (canSkipRestoreViewError does not
                                           recognise the refusal, and RESTORE
                                           ACCOUNT passes skipIfDependencyMissing
                                           = false, so its skip path is
                                           unreachable anyway)
  pitr.go:1828     drop -> :1832 create   (no skip at all: bare `return err`)
  clone.go:1045    same helper

Views with an unservable MATCH could be created before the guard existed -- that
is precisely the population matrixorigin#27027 describes -- so a snapshot may legitimately
hold one. Letting the refusal escape turned "this account has one broken view"
into "this account cannot be restored", with the view already dropped and its
definition existing only inside the snapshot. Strictly worse than the bug fixed.

Both paths now skip such a view and continue, logging the database, table and the
fact that it is absent from the restored account.

The refusal gained its own error code to make that possible: ErrFtMatchingKeyNotFound
(20327), mapped to MySQL's ER_FT_MATCHING_KEY_NOT_FOUND. Identifying it by code
rather than by message keeps the wording free to change and keeps unrelated
ErrInvalidInput fatal during restore, so real corruption is never swallowed. It
also delivers the exact MySQL parity the issue asked for and the parent commit
could not provide:

  ERROR 1191 (HY000): Can't find FULLTEXT index matching the column list

Also from the same review pass:

  - PlanCallsAnyFunc now follows Expr_Sub, which nests two ways at once: a Child
    expression AND a NodeId edge that Children does not list. Flattening normally
    removes these, but "normally" is not a guarantee the walker can rely on; a
    MATCH surviving inside one would have been invisible.
  - The two fulltext plugins shared their ValidateViewDefinition body instead of
    carrying copies that can drift. Each still declares the hook, so the registry
    remains the source of truth for what an algorithm does.
  - The fulltext2 BVT case is brought to parity with the classic one (13 view
    shapes) and its rationale corrected: it cannot prove the refusal twice, since
    the policy is shared, but it does cover the fulltext2 ENGINE end to end. That
    earned its keep immediately -- fulltext2 is served by the fulltext2_search
    TVF, not fulltext_index_scan, and asserting the wrong one failed.

Tests: restoreViews skipping the refusal for BOTH values of
skipIfDependencyMissing while still restoring the remaining views, and an
unrelated error staying fatal; the error code / MySQL-code contract both paths
key on; Expr_Sub reachable only through the subquery edge. restoreViewsWithPitr
is not covered executably -- it calls GetSubscriptionMeta before the view loop,
which the mock session cannot satisfy -- and that limitation is recorded on the
test rather than papered over.

Verified: fulltext 1223/1226 (3 ignored, 0 failed), fulltext2 489/489,
pkg/frontend and pkg/indexplugin/plan unit tests green.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
…, not just at create

Manual end-to-end verification of the previous commit showed it did not actually
work: a database-level PITR restore still died with

  ERROR 1191 (HY000): Can't find FULLTEXT index matching the column list

Two separate reasons, neither of which the unit tests could see because they
inject the error directly into the mock executor.

1. The moerr code does not survive the background executor. Restore runs the
   stored CREATE VIEW through bh.Exec, which reconstructs the error on the way
   back, so IsMoErrCode(err, ErrFtMatchingKeyNotFound) was simply false at the
   call site. canSkipRestoreViewError has always paired its code checks with text
   checks for exactly this reason -- I read that function and did not ask why it
   hedged. isUnservableViewError now matches code OR the message, which moerr
   exports so the fallback cannot drift from the table entry.

2. The refusal escapes BEFORE the create loop. Both restore paths plan every view
   twice: a dependency toposort calls plan.BuildPlan on each stored CREATE VIEW to
   discover inter-view edges (snapshot.go:1606/1614, pitr.go:1787/1795) well
   before the loop that creates them. The skip added in the previous commit sat in
   the create loop and never ran.

The toposort now leaves such a view out of the graph. The restore loop only visits
sorted keys, so the view is neither dropped nor re-created and the restore
completes. Measured on a database-level PITR restore: the ordinary view and all
table data come back, the unrunnable view does not (that level rebuilds the
database). The comment records what was measured rather than what was intended --
an earlier draft claimed the target keeps its existing copy, which this run
disproved.

Verified end to end, since this is the part unit tests cannot reach:

  create index -> create view (valid) -> drop index  =>  stored view unrunnable
  RESTORE ACCOUNT sys DATABASE ft_pitr FROM PITR ...  =>  succeeds
    survivors: v_plain, plain_rows 4, docs_rows 4

Before: the same command aborted and took the whole account restore with it,
having already dropped the view.

Tests: the create-time skip keeps its coverage, plus the code-stripped form the
executor actually delivers (an error carrying only the message). The toposort
placement itself has no automated test -- sortedViewInfos needs a real compiler
context that the mock session cannot provide, and a BVT would have to restore an
entire account, which is destructive inside a shared suite. A self-contained case
using a dedicated non-sys account is the follow-up.

Verified: fulltext 1223/1226 (3 ignored, 0 failed), fulltext2 489/489,
pkg/frontend green.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
…e DROP INDEX decision

Two loose ends from the self-review pass.

1. The toposort placement now has an automated regression. Restore plans every
   stored view TWICE -- a dependency sort before the loop that creates them -- and
   the matrixorigin#27027 refusal surfaces in the sort. A previous fix guarded only the create
   loop and still aborted the whole restore; that was caught by manual testing,
   with nothing in CI to stop it coming back.

   snapshot_restore_unservable_view builds the legacy shape honestly: create a
   fulltext index, create a view over MATCH (valid at the time), then drop the
   index, leaving a stored view that can never run -- the same end state as a view
   created before the guard existed. Snapshot, mutate, restore.

   It runs entirely inside a dedicated account, because restoring at snapshot
   scope rebuilds the account and would be destructive against sys.

   Negative control: with ONLY the toposort skip disabled and the create-loop skip
   left in place, the restore fails at the RESTORE statement and the account is
   left broken. The case pins the PLACEMENT, not merely the presence of a skip
   somewhere -- which is exactly the distinction the earlier tests missed.

2. DROP INDEX is deliberately not guarded, and RefuseUnservableMatch now says so
   with the reasoning, so the next reader does not have to rediscover it.

   The guard establishes "view DDL does not CREATE something unrunnable", NOT "a
   persisted view is always runnable". Refusing DROP INDEX was considered and
   rejected because:

     - MySQL checks only foreign-key dependencies when dropping an index; views
       are not dependency-tracked and MySQL has no full-scan fallback for MATCH,
       so the view fails at query time there too. matrixorigin#27027 reports the same from
       MySQL 8.0.45 and explicitly scopes this lifecycle out.
     - It would buy no invariant. Measured here: with a view over MATCH(body),
       both `ALTER TABLE docs DROP COLUMN body` and `DROP TABLE docs` succeed and
       leave the view in the catalog failing on every query. Guarding one of three
       doors is inconsistency, not safety.
     - It would break drop-index / bulk-load / recreate-index, forcing every
       dependent view to be dropped and recreated around each reindex.

   The state is self-healing: recreating the index makes stored views work again.
   A stronger guarantee would have to cover DROP COLUMN and DROP TABLE too.

Verified: the new case passes and fails under its negative control; fulltext
1223/1226 (3 ignored, 0 failed); fulltext2 489/489.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
…witched off

The view guard infers "no FULLTEXT index can serve this MATCH" from the placeholder
surviving optimization. That inference is only sound while rewrites actually run,
and the global optimizer_hints variable can switch applyIndices off wholesale
(apply_indices.go): every placeholder then survives regardless of the catalog.

Measured with the guard unconditional:

  set global optimizer_hints = 'applyIndices=1';
  create view v as select id from docs where match(body) against('hello');
  ERROR 1191 (HY000): Can't find FULLTEXT index matching the column list

FULLTEXT(body) existed. Every fulltext view DDL in the cluster would fail this
way, naming a cause that provably does not hold, until someone connected it to a
hint set for unrelated plan debugging.

The guard now stands down while index application is disabled. Being permissive
there costs at most one unrunnable view, which the user can drop; being wrong
refuses working views cluster-wide and is far harder to diagnose. A diagnostic
knob must not quietly become DDL policy.

indexRewritesDisabled reads the same global in the same key=value form
parseOptimizeHints uses, rather than requiring a QueryBuilder that genViewTableDef
does not have.

Verified end to end: with the hint set a valid view is accepted and an index-less
one is too (the deliberate trade); once the hint is cleared the index-less view is
refused again and the valid one still returns rows. Unit test covers unset,
applyIndices=1, an explicit 0, embedded among other hints, other hints only,
surrounding spaces, a non-numeric value, a malformed pair, and a nil context; it
fails with the skip removed.

Verified: fulltext 1223/1226 (3 ignored, 0 failed), fulltext2 489/489,
pkg/sql/plan green.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Checking the reviewer's PLAUSIBLE "isolation vs inlined plan" finding turned it
into a CONFIRMED limitation, so the scope comment should not overstate what this
guard delivers.

A view is validated as a standalone SELECT, but querying it inlines the definition
into the surrounding statement and re-plans everything, which can reach a shape
the fulltext rewrite does not cover. Measured on a view over MATCH(body) with the
score projected: accepted at CREATE, and correct under an outer ORDER BY, a join,
an aggregate, a window, a nested view, a subquery and a union -- but `WHERE sc > 0`
on the score column fails at runtime with 20105.

Not a hole in this check, and not a regression: the identical shape fails as a
bare derived table with no view involved, so it is a pre-existing planner gap of
the same family as MATCH under a Window node.

The comment now says what is actually guaranteed -- "view DDL does not persist a
definition that cannot run ON ITS OWN" -- and lists both reasons the stronger
reading does not hold: inlining can change the plan, and DROP INDEX / DROP COLUMN
/ DROP TABLE are deliberately not guarded.

Comment only; no behaviour change.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
…n it

`WHERE sc > 0` on a view's score column -- and the same shape as a derived table
-- failed at runtime even though the fulltext index scan had been built right
beside the predicate:

  Join
    Table Scan   Filter Cond: (fulltext_match('hello', 0, body) > 0)   <- throws
    Table Function on fulltext_index_scan                              <- index IS used

Inlining substitutes the score alias with its definition and pushes the result
onto the base scan. getFullTextMatchFiltersFromScanNode only recognises a BARE
fulltext_match, so a comparison wrapping one is invisible to it: the placeholder
survives the rewrite, reaches execution, and raises the 20105 "cannot be replaced
by FULLTEXT INDEX" error.

Such predicates are now lifted off the scan alongside the bare matches and
re-attached to the JOIN once the score column exists, with the inner MATCH
rewritten to reference it. They cannot stay below the join: the score is produced
by the table function on the other side. Lifting happens before the pushdown
decision on purpose -- a predicate needing the score can never be pushed into the
index scan, so it must not make the pre-filter path look worthwhile.

Shared with the vector side rather than duplicated, which is the same defect it
fixed for wrapped distances in matrixorigin#26961: exprCallsFunc and replaceScoreFnInExpr are
the generic half of replaceDistFnInExpr. Vector decides WHAT to replace using
metric and query-vector tests; fulltext needs only the function name, so the two
share the walk and not the predicate. An index placeholder nested inside a
comparison, a cast or arithmetic is still a placeholder in both.

Scope, deliberately narrow. Only when exactly one MATCH was served: with several,
deciding which index scan's score a wrapped predicate refers to needs argument
matching this does not attempt, and guessing would report the wrong score. If the
score column cannot be resolved the predicates go back on the scan rather than
being dropped, since dropping one would silently widen the result set.

NOT fixed, and unchanged: a bare `WHERE MATCH(...) > 0` with no other MATCH still
raises 20105. No index scan is built there at all -- the filter list holds nothing
getFullTextMatchFiltersFromScanNode recognises -- so this lift never runs. Making
that work means changing index ELIGIBILITY, not predicate placement.

For the record, since it decides the semantics: MATCH returns a FLOAT relevance
score in MatrixOne, as in MySQL -- `DESC` on a view projecting one reports FLOAT,
and both fulltext_match and fulltext_match_score register as T_float32. The
"return true or false for filter" comment in func_fulltext.go describes the
placeholder's role in a WHERE clause, not its type. Comparing a score is therefore
meaningful, and swapping the placeholder for the score column is type-consistent.

Tests: unit coverage for both shared helpers -- nesting, expression lists,
per-occurrence node identity so a later pass cannot corrupt a shared node, and
unrelated expressions left alone -- plus BVT cases in fulltext and fulltext2 whose
EXPLAIN asserts the right TVF is still reached (fulltext_index_scan /
fulltext2_search), so the fix cannot be a silent fallback to a scan.

Verified: fulltext 1226/1229 (3 ignored, 0 failed), fulltext2 492/492, vector
1524/1528 with only the pre-existing vector_ivf_retry.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
The previous commit taught the rewrite to see through a wrapped MATCH in a
FILTER. The projection has the identical gap and it was still open:

  select id, round(match(body) against('hello'), 3) from docs
   where match(body) against('hello');
  ERROR 20105: MATCH() AGAINST() function cannot be replaced by FULLTEXT INDEX

The projection rewrite only replaces the positions getFullTextMatchFromProject
recognised -- bare fulltext_match calls -- so `round(match(...), 3)`,
`cast(match(...) as decimal)` and `match(...) * 100` were never reached. The
placeholder survived to execution and threw, even though the index scan had just
been built for the accompanying WHERE MATCH.

Sweeping whatever remains in the projection list closes it, reusing the walk
shared with the vector side (replaceScoreFnInExpr). Same single-served-MATCH
restriction as the filter half: with several, choosing WHICH index scan's score a
wrapped projection refers to needs argument matching this does not attempt, and
guessing would silently report the wrong score.

Verified values, not just absence of errors -- bare score 0.031008132 / 0.062016264:

  round(...,3)  -> 0.031, 0.062
  ... * 100     -> 3.1008, 6.2016
  cast decimal  -> 0.031, 0.062
  order by r    -> 3, 1   (correctly ranked by relevance)

BVT: fulltext_wrapped_score and fulltext2_wrapped_score, mirroring
vector_ivf_wrapped_dist (matrixorigin#26961) which pins the same shapes for wrapped
distances. Each covers CAST / ROUND / arithmetic / round(...+1) in projections,
ordering by the wrapped alias, six filter-side wrappings, the no-view derived
table, and EXPLAIN assertions that the right TVF is still reached -- so a
regression that "fixes" these by falling back to a scan fails too. Confirmed
against a negative control: with both sweeps disabled, 12 of 24 statements fail.

Both cases pin ft_relevancy_algorithm / ft2_relevancy_algorithm. They print raw
scores, and that setting is a session variable other cases in the same suites
change (fulltext_bm25 sets BM25), so without pinning the expected values depend on
run order -- caught only by running the whole suite, since standalone the case saw
the default and passed.

Verified: fulltext 1251/1254 (3 ignored, 0 failed), fulltext2 517/517, vector
1524/1528 with only the pre-existing vector_ivf_retry.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
…e JOIN

The wrapped-predicate lift added two commits ago returned WRONG ROWS. It attached
the rewritten predicate to joinNode.FilterList -- a field no planner code sets and
nothing evaluates. EXPLAIN prints it as `Filter Cond:`, so the plan looked correct
while the predicate was silently discarded:

  scores: id3 = 0.181, id4 = 0.0906
  sc > 0.1   ->  3, 4     (must be only 3)
  sc > 0.5   ->  3, 4     (must be EMPTY)

That is worse than the ERROR 20105 the lift replaced: an error is visible, wrong
data is not. Now a real Node_FILTER above the join, which the executor runs.

Verified with thresholds that EXCLUDE rows, on both plan shapes -- the plain join
and the bloom-filter pushdown nesting (reachable only with
fulltext_bloom_filter_pushdown = 1, which defaults to 0):

  plain     sc > 0.1 -> empty      sc > 0.5 -> empty     sc > 0 -> all matches
  pushdown  sc > 0.1 -> only id 3  sc > 0.5 -> empty     sc > 0.02 -> 3, 4

This also closes the untested outer-join path flagged as a known gap.

Why the bug survived: every threshold in the tests was `sc > 0`, which every
matching row satisfies, so a predicate that is never applied returns exactly the
same rows as a correct one. Ten shapes, an EXPLAIN inspection, and a full suite
all passed against a filter that did nothing. The BVT cases now use thresholds
that change the row set -- baseline `> 0` gives [1,3], the mid threshold gives
[3], the high one gives [] -- so a discarded predicate fails immediately.

Test hygiene, twice learned: every case asserting on a score now pins
ft_relevancy_algorithm / ft2_relevancy_algorithm as its FIRST statement, matching
the convention in fulltext1.sql, and restores the default at the end so it cannot
leak to the next case. Those variables are session-scoped and fulltext_bm25 sets
BM25, so an unpinned case passes standalone and fails inside the suite -- which
happened to fulltext_wrapped_score, and then again to fulltext_view_ddl when a
threshold was added to it. The snapshot case pins inside its account session,
where the queries actually run.

Verified: fulltext 1260/1263 (3 ignored, 0 failed), fulltext2 526/526.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
…rop stale views on restore

Review of the previous commits found the wrapped-MATCH rewrite reporting wrong
scores. It replaced every fulltext_match by NAME and guarded that with a count
of SERVED matches, which does not constrain the matches being rewritten:

  select id, round(match(body) against('world'),3) r
  from docs where match(body) against('hello');
    -> r reported the 'hello' relevance for rows containing no 'world' at all

equalsFullTextMatchFunc already compares pattern, mode and index parts -- it is
what builds eqmap -- so the rewrite now asks it which scan answers a given
MATCH, via replaceScoreFnInExprBy (a predicate-keyed sibling of the name-keyed
replaceScoreFnInExpr the vector side keeps). A MATCH no scan answers is left
alone and still raises 20105: an error is the honest answer for a MATCH no index
can evaluate, and it is what the query returns with no rewrite at all.

With the matcher deciding, both count guards go away, which also fixes a
projection carrying a bare AND a wrapped copy of one match (eqmap had already
collapsed them onto one scan, but the guard counted two and skipped the sweep),
and newly allows a lifted score predicate over several streams.

Also fixed:

- Candidate LIMIT vs the lift: lifting empties scanNode.FilterList, which flipped
  the `len(FilterList) == 0` gate and pushed the user LIMIT into the TVF as a
  candidate cap -- while the lifted predicate now runs ABOVE the join. Measured
  on a build with only that conjunct reverted: `... < 0.015 limit 1` returned 0
  rows and `limit 2` returned 1 of 3.
- tryApplyCoveredFulltext2 gets the same sweep, before the base-ColRef remap.
- indexRewritesDisabled trimmed whitespace while handleOptimizerHints does not,
  so `a=1, applyIndices=1` switched the matrixorigin#27027 view guard off while the rewrites
  it reasons about really ran. Both now use splitOptimizerHint.
- Restore/PITR marked an unservable view instead of dropping it from the
  toposort. Dropping it meant the restore loop never visited it and never ran the
  DROP, so wherever the target database is not rebuilt the OLD object stayed
  behind and the restore reported success over it. It is now dropped like any
  other restored view and only its CREATE is skipped.

Tests are discriminating -- two search terms with distinct expected scores, and
LIMIT thresholds whose qualifying rows are NOT the top-relevance ones, since the
earlier `sc > 0` style could not tell a correct predicate from one never applied.

fulltext 1276/1279, fulltext2 542/542, snapshot 17738/17738, pitr 506/506 (all 0
failed on a clean instance), vector 1524/1528 (pre-existing vector_ivf_retry).
Snapshot restore and PITR verified by hand: stale view dropped, restore succeeds.

Co-Authored-By: Claude Opus 5 <[email protected]>
getFullTextMatchFiltersFromScanNode and getFullTextMatchFromProject recognise
only a BARE fulltext_match sitting at a top-level position, so a MATCH nested in
a larger expression never entered ft_filters. When it was the query's ONLY match
the rewrite was not entered at all and the placeholder reached execution:

  select id from two where match(body) against('hello') > 0.015;   -> 20105
  select id, round(match(body) against('hello'),3) from two;       -> 20105
  select count(*) from two where match(body) against('hello') > 0; -> 20105

A wrapped MATCH could therefore only ride along with a bare one carrying
identical arguments. getWrappedFullTextMatches walks the scan filters and the
project list for nested MATCHes, resolves an index for each, and registers them
as their own streams; the argument-aware rewrite added in the previous commit
then resolves every reference to the right one.

Deduplicated with equalsFullTextMatchFunc against the bare matches and against
each other, so a wrapped copy of a match that already has a stream reuses it
instead of building a second -- the collapsing eqmap does for bare projections.
A MATCH no index can serve is skipped and still raises 20105.

Wired into the projection and the aggregate dispatch. The covered fulltext2 fast
path is skipped when a wrapped driver survives deduplication, since that is by
definition a second match needing a second stream it cannot produce.

Note the row semantics, unchanged and now reachable from more shapes: streams
are INNER JOINed, so a query naming two different MATCHes returns only documents
matching BOTH, and a projection-only MATCH returns only matching documents.
Bare multi-stream MATCH already behaved this way; MySQL would return the other
rows with relevance 0.

fulltext 1286/1289, fulltext2 552/552 (0 failed), vector 1524/1528 (pre-existing
vector_ivf_retry).

Co-Authored-By: Claude Opus 5 <[email protected]>
tryApplyCoveredFulltext2's sweep shipped without a test because I could not
construct a query that reaches it. It is reachable: guard (d) descends into the
MATCH's arguments, and while an indexed text column is rejected as an INCLUDE
column, it can be the PRIMARY KEY -- which is what makes it count as covered.

  create table covpk(body varchar(100) primary key, tag int);
  create fulltext2 index ci_covpk on covpk(body) include(tag);
  select body, tag, round(match(body) against('hello'),3) from covpk
   where match(body) against('hello');

EXPLAIN confirms the covered plan (fulltext2_search, no base-table JOIN) and the
wrapped scores equal the bare baseline. The code comment claimed include columns
were the way in, which is wrong -- corrected to the pk.

fulltext2 558/558, fulltext 1286/1289 (0 failed).

Co-Authored-By: Claude Opus 5 <[email protected]>
…child

applyFullTextFiltersForScanInJoin rewrites the filters of each INNER/SEMI join
input, and looked for bare matches only, so a wrapped predicate on a join child
threw even though the identical query without the join now works:

  select a.id, b.note from a join b on a.id = b.id
   where match(a.body) against('hello') > 0.02;    -> 20105

It has no project node, so the scan's own filters are the only place to look.

scanHasMatchedFullTextFilter now recognises wrapped matches too. Two guards
depend on it -- applyIndicesForFilters leaves such a scan to the fulltext path,
and removeSimpleProjections keeps the PROJECT above it as a rewrite boundary --
and a scan filtered only by `match(...) > 0.5` is just as much a fulltext scan
as one filtered by a bare MATCH. Without this its PROJECT boundary could be
dropped, exposing the scan under a WINDOW or outer JOIN where the scan-local
rewrite cannot run.

Tests cover the join and the IN-subquery/SEMI shape with thresholds that
discriminate in both directions (> keeps the high scorer, < keeps the low one).

fulltext 1293/1296, fulltext2 558/558 (0 failed), vector 1524/1528 (pre-existing
vector_ivf_retry), go test ./pkg/sql/plan ok.

Co-Authored-By: Claude Opus 5 <[email protected]>
Filtering by relevance across a join worked; selecting it did not:

  select a.id, b.note from a join b on a.id=b.id
   where match(a.body) against('hello');                     -- ok
  select a.id, match(a.body) against('hello') from a join b on a.id=b.id
   where match(a.body) against('hello');                     -- 20105

A join takes the per-child route: applyFullTextFiltersForJoinChildren rewrites
each TABLE_SCAN child on its own, with no project node in hand, so nothing ever
replaced a MATCH in the SELECT list above it and the placeholder reached
execution. This was true of a bare MATCH too, not only a wrapped one.

applyIndices recurses children before parents, so those fulltext scans and their
score columns already exist when the PROJECT is visited -- the missing piece was
only that the child rewrites return nothing to that call frame. They now record
what they served on the builder, and resolveProjectMatchesOverJoin resolves each
projected MATCH (and any ORDER BY MATCH, which is bound as its own expression)
against it.

The comparison had to get stricter. equalsFullTextMatchFunc compares index parts
by column NAME, which is sound while both sides belong to one scan; with two
tables in scope match(a.body) and match(b.body) look identical by name, and one
table's relevance would be reported for the other's. servedFullTextScoreSameTable
also requires the column's binding tag to match. The cross-table test pins it:
sa=0.031 and sb=0.093 on the SAME row, which name-only matching would collapse
into one number.

Covered by a new case: projected and wrapped scores over a join, cross-table,
ORDER BY MATCH, a self join (two bindings of one table), an outer join, and a
MATCH no index can serve still raising 20105.

fulltext 1318/1321, fulltext2 558/558 (0 failed), vector 1524/1528 (pre-existing
vector_ivf_retry), go test ./pkg/sql/plan ok.

Co-Authored-By: Claude Opus 5 <[email protected]>
…g one clustering

Two cases in vector_ivf_retry asserted outcomes that ivfflat clustering decides
at random, so the suite failed or passed depending on how k-means happened to
partition that build. Both failures reproduce on main and on this branch; the
"1 vs 2 failures" difference between branches was luck, not a code fix.

Test 5.4 -- `filter_col = 0 ... limit 5 by rank` -- ran with probe_limit = 1,
set a few lines earlier to force low recall for the fallback tests around it.
The 20 matching rows lie on one tight line and k-means splits them across the 5
lists differently from build to build, so the single probed cluster held 4 rows
in some runs and 5 in others; the recorded expectation of 4 was one of those.
The case is about "at least limit rows if available", not about recall, so it
now probes every cluster and restores probe_limit = 1 for the test below it.

Tests E.2 / E.3 on t_edge ordered a THREE-WAY TIE: the fixture used three unit
vectors, so every distance from '[0,0,0]' was exactly 1.0 and `limit 2` had no
deterministic answer -- (2,1) and (1,3) were equally correct. The vectors now
have distinct norms, giving distances 1, 2 and 3.

vector suite 1542/1544, 0 failed, three consecutive runs.

Co-Authored-By: Claude Opus 5 <[email protected]>
… by nothing

Self-review of the previous commits. A stream built for a WRAPPED-only match
belongs to neither filter_node_ids nor proj_node_ids -- there is no bare MATCH
position to record it against -- and those two lists are what the caller builds
the score-DESC keys from. So `where match(...) > 0.5`, whose only match is
wrapped, reached the SORT construction with NO keys:

  Project
    ->  Sort                 <- no "Sort Key:" line
          ->  Filter

which buffers rows to sort them by nothing and hands back join order, while the
identical query with a bare MATCH comes back by relevance. Ordering by every
stream's score (deduplicated against the keys the two loops already added) makes
the wrapped-only form return 3,2,5,1 exactly like the bare one.

Additive: with no wrapped-only stream, served covers precisely the filter and
projection nodes, which are already in the set, so existing plans are unchanged.

Also probed while sweeping, all behaving correctly and left as they are: UNION
ALL of two joined fulltext queries, a CTE referenced twice, a derived table, and
a LEFT JOIN projecting the nullable side's score (a clean 20105, not a bad plan).
Two shapes stay unsupported and are decision-logged rather than fixed here: a
correlated subquery with a MATCH (pre-existing -- it fails with no projected
score either, and that path is byte-identical under this diff), and a prepared
statement projecting a score over a join (its two '?' placeholders are distinct
expressions, so the projected MATCH matches no existing stream; over a join a
projected MATCH can only be resolved against a stream, not create one).

fulltext 1320/1323, fulltext2 558/558, vector 1528/1530 -- 0 failed, go test
./pkg/sql/plan ok.

Co-Authored-By: Claude Opus 5 <[email protected]>
…dropping views we cannot restore

Review of c7c796e..HEAD. The first is a correctness regression this branch
introduced and shipped.

getWrappedFullTextMatches harvested a MATCH out of ANY scan filter, including one
under OR or NOT. The stream a driver builds is INNER JOINed to the base scan,
which ANDs "this document is in the index result" onto the query, so:

  select id from two where match(body) against('hello') > 0.5 or id = 4;
  select id from two where not match(body) against('hello');

both returned the EMPTY SET instead of id 4 ('world', which contains no 'hello'
and is therefore absent from the stream). Before this branch they raised 20105 --
an error was turned into a silently wrong, under-counted result.

A MATCH may now drive only from a membership-implying position: reachable through
AND only, and comparing `score > c` (c >= 0) or `score >= c` (c > 0), either
operand order, through order-preserving wrappers (round/cast/floor/ceil) only.
Exactly the shapes a non-matching document, whose relevance is 0, cannot satisfy.
`score < c`, `>= 0`, OR and NOT no longer drive and raise 20105 as before.
Resolving a wrapped MATCH against a stream that a BARE MATCH already drives stays
unrestricted -- membership is implied there, so any comparison is free to filter
among the matching documents. Supporting `< c` needs the stream LEFT joined with
a relevance of 0 for missing rows (what MySQL reports), which is a separate change.

restoreViewsFromTS, the cluster-snapshot restore path and the widest blast radius
of matrixorigin#27027, had neither the sort-time nor the create-time tolerance and still
aborted an entire account restore on one unrunnable view. It now matches the
other two paths.

Restore no longer DROPs a view it cannot re-create; it leaves any existing object
of that name alone. Honest scope: the review reported this as live data loss, and
I could NOT reproduce it -- on every path I can construct (database snapshot
restore, database PITR, clone) the object disappears because the restore rebuilds
the database or the destination is new, never because of this DROP. Kept as
defense-in-depth: not dropping something we cannot replace needs no case analysis
of which paths rebuild. The mirror-image finding from the previous review pass
(stale object left standing) rests on the same unreachable premise.

ftJoinServed is documented as safe without a reset: a QueryBuilder is per
statement and binding tags are unique within a build.

fulltext 1328/1331, fulltext2 558/558, vector 1528/1530, snapshot 17738/17738,
pitr 506/506 -- 0 failed. go test ./pkg/sql/plan and ./pkg/frontend ok.

Co-Authored-By: Claude Opus 5 <[email protected]>
A `MATCH(...) <op> const` predicate was evaluated only in a Filter above the join,
so every scored document crossed the TVF boundary and was then thrown away. An
INCLUDE-column predicate on the same query pushes all the way in; the score could
not, because buildFilterPredicateJSON only peels predicates on BASE-TABLE columns
and the score is produced by the TVF itself.

The planner now turns the AND-reachable score comparisons on each fulltext2
stream into a relevance interval (fulltext2.ScoreRange) passed as the TVF's 5th
argument, and the engine drops out-of-range documents where they are produced:
streamSink.push* on the streaming path, runTopK's result slice on the top-k path.
A range rather than a single min_score, so >, >=, <, <= and their AND-combinations
are one object, and the tightest bound on each side wins.

Two things keep it from ever changing an answer:

  - AND-reachable only. Under an OR or a NOT the predicate need not hold for a
    returned row, so nothing may be dropped on its account. The BVT covers an OR
    that still returns its rows correctly through the Filter above.
  - Each bound is widened OUTWARD by one float32 ULP. SQL compares in double while
    the engine scores in float32, so a naively converted bound can round the wrong
    way; widening means the engine can only ever be too permissive. The plan keeps
    its Filter, which makes the final call.

Scope, stated plainly: this removes rows from the TVF->join boundary, it does NOT
yet prune the posting-list walk. WAND already maintains theta (wand.go) and a
lower bound could initialise it, which is the deeper win -- but theta lives behind
SearchBoolean/searchBooleanFull/Stream*, so threading it is a separate change.
Only a lower bound can prune; an upper bound cannot, since WAND prunes low scores
and enumerates the highest first.

runTopK filters AFTER the heap, so a range may only combine with a pushed LIMIT
when it has no upper bound. The planner already refuses to push a candidate LIMIT
whenever it lifts a score predicate, so that combination cannot arise today.

Classic fulltext has no scoring engine of its own and is unchanged.

Tests: ScoreRange interval semantics and streamSink honouring it (engine, direct
-- not inferred from end-to-end results), what may and may not be pushed
(planner), and BVT covering both bounds, inclusive bounds, an OR, and index usage.

fulltext2 566/566, fulltext 1328/1331, vector 1528/1530 -- 0 failed. go test
./pkg/fulltext2 ./pkg/sql/plan ./pkg/sql/colexec/table_function ok.

Co-Authored-By: Claude Opus 5 <[email protected]>
…dex rewrite

Remaining findings from the review of c7c796e..HEAD.

resolveProjectMatchesOverJoin returned true from applyIndicesForProject, which
skipped everything after it -- including the whole vector-index section
(buildVectorSortContextThroughJoin and the plugin ApplyForSort dispatch). A query
that both projects a MATCH over a join and orders by a vector distance lost its
vector index and silently fell back to brute force. It rewrites expressions in
place and builds no node, so it has no business ending the pass; it now falls
through, and the contract is stated on the function.

Cleanups from the same pass:
- sortNodeBelowProject re-implemented the existing resolveSortNode(node, 1).
- replaceScoreFnInExpr, the name-keyed wrapper, had zero production callers once
  fulltext moved to the argument-aware predicate; the vector side uses
  replaceDistFnInExpr. Its test moves to replaceScoreFnInExprBy, keeping the
  coverage that mattered (per-occurrence fresh nodes, nested rewrite, and now a
  nil-returning callback leaving a call untouched).

fulltext 1328/1331, fulltext2 566/566, vector 1528/1530 -- 0 failed, go test
./pkg/sql/plan ok.

Co-Authored-By: Claude Opus 5 <[email protected]>
@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 →

@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 review of exact head eaa53e4fe5b1fac5b0cba1dc18d4473342bbca84: REQUEST_CHANGES.

[P1] Widen fulltext2 score bounds in float32 space before engine pushdown. The current setMin/setMax moves the SQL float64 literal by one float64 ULP and then converts to float32. That conversion can still round inward, causing ScoreRange.contains to discard a row that satisfies the residual SQL predicate before the row reaches it.

Concrete exact-head cases:

  • lower bound v = 0.5000000447034836: setMin becomes float32 0.5000000596046448 > v; a score at that float32 value satisfies SQL score > v but is rejected by the exclusive pushed minimum;
  • upper bound v = 0.5000000149011612: setMax becomes 0.5 < v; a score of 0.5 satisfies SQL score < v but is rejected by the exclusive pushed maximum.

Please convert first and use outward math.Nextafter32 adjustment (or an equivalent invariant-preserving helper) so every lower bound is <= the SQL literal and every upper bound is >= it. Add midpoint regressions for >, >=, <, and <=; the existing exactly representable 0.5 cases cannot expose this.

I also reviewed the view-validation hook/reachable-plan walk and the three restore tolerance paths and found no additional blocker. Full pkg/sql/plan, pkg/fulltext2, pkg/sql/colexec/table_function, and pkg/frontend tests pass with the required CGo setup; git diff --check is clean.

@cpegeric

Copy link
Copy Markdown
Contributor Author

Eric correct me if I am wrong -- so this PR just print out an error message when a table does not have a fulltext index, it has nothing to do with view. Whether it is a view, or it is simple SQL statement, we should all error out.

simple SQL with fulltext index works but after adding REPLACE VIEW it don't resolve the index even index exists and try to fallback to SQL function which does not exist. This PR is to resolve index when index exists in REPLACE VIEW case.

cpegeric and others added 2 commits August 17, 2026 09:49
detectFullTextGuard reserves the TABLE_SCAN that the fulltext rewrite is about to
consume, so applyIndicesForFilters leaves it alone rather than turning it into a
secondary-index scan first. Its predicate was the pre-widening one -- a bare MATCH
in the select list or a MATCH filter -- while applyIndicesForProject now also
rewrites off wrapped MATCHes. A scan whose only MATCH is wrapped went unreserved.

The consequence is not a missed optimization. With any ordinary index on a filtered
column the regular-index rule takes the scan first, and when the project is finally
visited resolveFullTextIndexPath no longer finds a base scan to serve from, so the
MATCH survives into the executed plan and throws 20105 -- defeating, for this shape,
the projected-wrapped-MATCH support this branch adds.

Two plans differing only by a round() wrapper, over a table with a fulltext index
and an ordinary index on the filtered column:

                                  bare      wrapped
  detectFullTextGuard             [scan]    []
  isScanProtected                 true      false
  wrapped matches driving rewrite -         1
  fulltext index scans built      1         0
  unserved fulltext_match left    0         1   -> 20105

scanHasMatchedFullTextFilter, widened earlier for the same reason, cannot cover this
case: there is no fulltext filter on the scan at all, so the project guard was the
only thing that could reserve it.

Both arms of the predicate now match applyIndicesForProject exactly, aggregate
included. The regression test pins the two together and keeps the bare case as the
control, since the bare form working is what makes the gap easy to miss.

Latent on main as well -- detectFullTextGuard is identical there and predates this
branch's merge base. The widened rewrite is what makes it reachable.

Verified: new test fails with the predicate reverted and passes with it; full
pkg/sql/plan suite and go vet clean.

Co-Authored-By: Claude Opus 5 <[email protected]>
The bounds pushed into the fulltext2 engine were nudged by one float64 ULP and then
converted to float32. float64->float32 rounds to NEAREST, so when the literal sits
more than half a float32 ULP from its neighbour the nudge is swallowed and the bound
lands on the WRONG side of the literal. The engine drops rows outside the range
before the plan's own Filter runs, so an inward bound silently loses rows that
satisfy the SQL predicate.

Two literals that do it, both reachable from ordinary SQL:

  score > 0.5000000447034836 -> Min became 0.5000000596046448, ABOVE the literal, so
    a score of exactly 0.5000000596046448 -- which satisfies the predicate -- was
    rejected by the exclusive minimum.
  score < 0.5000000149011612 -> Max became 0.5, BELOW the literal, so a score of
    exactly 0.5 -- which satisfies the predicate -- was rejected by the exclusive
    maximum.

The adjustment has to happen after the conversion, in float32 space. scoreBoundDown
and scoreBoundUp convert first and step outward with Nextafter32 only when the
conversion landed inward, restoring the invariant the engine relies on: Min <= the
SQL literal, Max >= it. It is also tighter than an unconditional widen -- an exactly
representable literal such as 0.5 now needs no slack at all.

Existing coverage could not catch this: every case used 0.5, which is exactly
representable, so both the old and new code agree on it. The new regressions use
literals strictly between two float32 values, one per operator (>, >=, <, <=), and
assert both the invariant and that a probe score satisfying the SQL predicate is
still admitted by the pushed range. A sweep over float32 neighbourhoods and their
midpoints pins the helpers directly. All four operator cases fail against the
previous conversion.

Also corrects the two doc comments that described the old unconditional one-ULP
widen.

Reported in review of eaa53e4.

Co-Authored-By: Claude Opus 5 <[email protected]>
@cpegeric

Copy link
Copy Markdown
Contributor Author

Deep review of exact head eaa53e4fe5b1fac5b0cba1dc18d4473342bbca84: REQUEST_CHANGES.

[P1] Widen fulltext2 score bounds in float32 space before engine pushdown. The current setMin/setMax moves the SQL float64 literal by one float64 ULP and then converts to float32. That conversion can still round inward, causing ScoreRange.contains to discard a row that satisfies the residual SQL predicate before the row reaches it.

Concrete exact-head cases:

  • lower bound v = 0.5000000447034836: setMin becomes float32 0.5000000596046448 > v; a score at that float32 value satisfies SQL score > v but is rejected by the exclusive pushed minimum;
  • upper bound v = 0.5000000149011612: setMax becomes 0.5 < v; a score of 0.5 satisfies SQL score < v but is rejected by the exclusive pushed maximum.

Please convert first and use outward math.Nextafter32 adjustment (or an equivalent invariant-preserving helper) so every lower bound is <= the SQL literal and every upper bound is >= it. Add midpoint regressions for >, >=, <, and <=; the existing exactly representable 0.5 cases cannot expose this.

I also reviewed the view-validation hook/reachable-plan walk and the three restore tolerance paths and found no additional blocker. Full pkg/sql/plan, pkg/fulltext2, pkg/sql/colexec/table_function, and pkg/frontend tests pass with the required CGo setup; git diff --check is clean.

fixed

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

The prior score-range correctness blocker is closed: bounds are now converted and widened outward in float32 space, preserving lower <= SQL literal <= upper at midpoint cases for all four comparison operators. The added wrapped-MATCH scan guard also aligns the guard predicate with the rewrite predicate and prevents a regular index rewrite from consuming the required base scan first.

Focused current-head planner and fulltext2 score-range tests passed. The index-plugin audit found no new per-algorithm dispatch, import-cycle, registration, or assertion regression.

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

Re-reviewed the exact current head and the full review history. The prior float64-to-float32 inward-rounding blocker is fixed correctly: conversion now happens first and only inward results are stepped outward with Nextafter32, maintaining lower <= SQL literal <= upper, with midpoint and neighborhood regressions. I also checked the subsequent wrapped-projection MATCH scan reservation against the actual rewrite predicate; it closes the ordinary-index preemption path for bare, wrapped, and aggregate cases. CI is green on this head. No remaining blocking issue found.

@aptend
aptend merged commit 3da66f2 into matrixorigin:main Aug 19, 2026
26 checks passed
XuPeng-SH added a commit that referenced this pull request Aug 27, 2026
## What type of PR is this?

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

## Which issue(s) this PR fixes:

issue #25541

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

This is a bounded backport of the FULLTEXT2 behavior closure from the
fixed
`upstream/main` reference to `4.2-dev`. It keeps FULLTEXT2 distinct from
classic FULLTEXT and preserves the target branch's parser/PERFORM/pipe
contracts.

Source/target closure:

- source `upstream/main`: `8e616a693458652cc26b3c4be45c6602dff298d4`
- target `upstream/4.2-dev`: `d2393868a7aaa6343518d80849fe4696aa3577e9`
- exact fork head: `325686d29c17b3729f32b837b5bc2144d33f0a9b`
- #25904 core: `966acb2a92bb740e57b0b7a181df2d21956e1d3`,
`0eb9a921ece274c956447640b41ad2a255079e8d`,
`403a99fb65304e75b82e75793448f0690a871d0e`,
`bfa83f42737ca6304c0af3f6913e70ccc961464`
- #27165 phrase-position decode:
`2b142144c3c24a2100d7d313e952717025d56aeb`
- #27171 FT2-only wrapped score/range closure:
`835e046faa9242dbe288bd72364a475e2132bbed`
- #27461/#27462 cache and cold-load closure:
`e4abf5e90d0b5e09590571ca78447e50806527c`
- #27598 readiness BVT closure:
`e3a7440e2ac32bac780669f33c656960e22cff22`

Current-head review repairs:

- Reverse constant-left `<`/`<=` before harvesting a lower-bound MATCH
membership driver; reject constant-left `>`/`>=` upper bounds
fail-closed.
- Route all FULLTEXT2 ISCP consumer errors through the non-blocking
helper and
  report `ctx.Err()` on cancellation.
- Restore the execution-level `fulltext2_wrapped_score.sql/.result` BVT
pair
  and replace restore/clone fixed sleeps with readiness waits.
- Refresh the ancestor-accurate backport manifest and clear all
  `git diff --check` trailing whitespace findings.
- Trim FULLTEXT2 SHOW CREATE option padding only at the terminal output
  boundary, preserving the shared renderer and vector-index behavior.
- Route wrapped-only FULLTEXT2 score predicates on either INNER JOIN
child
through the existing wrapped rewrite and keep the score comparison in a
  post-rewrite FILTER.

## Validation

- `make -C pkg/sql/parsers/dialect/mysql` — PASS
- `make generate-pb` — PASS; protoc 29.3 descriptor-only churn was
discarded
  and no unexpected generated diff remains
- `go test -mod=readonly ./pkg/fulltext2/... ./pkg/iscp ./pkg/sql/plan`
— PASS
- current-head focused `GOWORK=off go test -mod=readonly -count=1
-timeout 120s -run '^TestFulltext2WrappedMatchJoinChild$'
./pkg/sql/plan` — PASS
- current-head `GOWORK=off go test -mod=readonly -count=1
./pkg/sql/plan` — PASS
- current-head `GOWORK=off go build -mod=readonly ./pkg/sql/plan` and
  `GOWORK=off go vet -mod=readonly ./pkg/sql/plan` — PASS
- current-head SCA repair — removed the unreferenced
`applyJoinFullTextIndices`
wrapper; targeted plan tests, build, and vet pass; exact-head remote SCA
is
  pending
- current-head focused SHOW CREATE regression and catalog option tests —
PASS
- local `mo-cgo-test` wrapper — BLOCKED by missing `cgo/libmo.dylib`; no
CGo
  wrapper pass is claimed
- `go test -race -mod=readonly ./pkg/fulltext2/... ./pkg/iscp` — PASS
- `go build -mod=readonly ./cmd/mo-service` — PASS (macOS linker
rpath/path
  warnings only)
- base differential — exact target
`d2393868a7aaa6343518d80849fe4696aa3577e9`
  rejects `CREATE FULLTEXT2 INDEX`; this exact head parses it as
  `INDEX_CATEGORY_FULLTEXT2`
- BVT source parity and no-fixed-sleep scan — PASS
- canonical wrapped-score BVT now covers wrapped-only MATCH on both
INNER JOIN
child positions with qualifying and rejecting thresholds; exact-head
remote
  BVT remains pending
- exact-head semantic preflight — `PASS semantic=PASS`, diff hash
  `efc51153938b14e051372026b296c06e05696385ac674fa7f05f3a7217741d09`

## Scope and acceptance boundaries

- `QA required: yes`
- The PR was opened as Draft for preflight and is now **Ready for
review**.
Required CI, formal reviews, and Mergify remain pending; no remote pass
is
  claimed until they bind to this exact head.
- Build success, index creation/readiness, and elapsed workload duration
are
  not acceptance by themselves. No classic FULLTEXT result, fixed-commit
  product acceptance claim, or formal QPS claim is used here.
- The 2.3M frozen corpus and shared `freetier-01` workload remain
post-merge
gates. After merge, only the official immutable image/release workflow
may
produce the tag/digest; `freetier-01` must be upgraded through the
reviewed
GitOps `environment=new-dev + mode=mo + action=set` PR. No local image,
direct `4.2-dev` push, direct GitOps edit, kubectl mutation, or pod
restart
  is authorized.
- The first post-release test is a unique-database 15-minute
small-corpus
FULLTEXT2 shakeout with readiness polling, token-bucket DML, C1/C10
readers,
  and an independent correctness ledger. Only `MEASURED_PASS` with zero
correctness errors, no backlog, and complete observations may unlock the
  low-load two-hour continuous run.

Please keep issue #25541 open until QA explicitly reports PASS/FAIL.

---------

Co-authored-by: Eric Lam <[email protected]>
Co-authored-by: XuPeng-SH <[email protected]>
VioletQwQ-0 pushed a commit to VioletQwQ-0/matrixone that referenced this pull request Sep 17, 2026
…t a matching FULLTEXT index (matrixorigin#27171)

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

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



  ## What this fixes

  Closes matrixorigin#27027.

`CREATE VIEW … MATCH(col) AGAINST('x')` was accepted even when no
FULLTEXT index could serve
  that MATCH. The view then failed on every `SELECT` with

  ```
20105: MATCH() AGAINST() function cannot be replaced by FULLTEXT INDEX
and
         full table scan with fulltext search is not supported yet
  ```

and — the part that made it more than a nuisance — such a view **aborted
snapshot restore,
PITR and CLONE entirely**, because restore replays the stored `CREATE
VIEW`. One unrunnable
  legacy view made a whole account unrestorable.

Fixing that exposed *why* people write these views: a MATCH wrapped in
anything at all was never
served. `round(match(…),3)`, `cast(…)`, `match(…) * 100`, `match(…) >
0.5`, a score selected
across a join — all threw 20105, so the error looked arbitrary rather
than like a missing index.
This PR does both halves: refuse the view that can never run, and make
the shapes people actually
  write work.

  ---

  ## Query shapes: before and after

Fixture used throughout (classic fulltext; fulltext2 behaves the same
unless noted):

  ```sql
  create table two(id int primary key, body text);
insert into two values (1,'hello'),(2,'hello hello'),(3,'hello hello
hello'),
                         (4,'world'),(5,'hello hello world');
  create fulltext index ft on two(body);
  ```

  ### Scalar wrappers in the projection

  | SQL | Before | After |
  |---|---|---|
| `select id, match(body) against('hello') from two where match(body)
against('hello')` | ok | ok |
| `select id, round(match(body) against('hello'),3) …` | **20105** | ok
|
| `select id, cast(match(body) against('hello') as decimal(10,3)) …` |
**20105** | ok |
  | `select id, match(body) against('hello') * 100 …` | **20105** | ok |
| `select id, round(match(body) against('hello') + 1, 3) …` | **20105**
| ok |
| `select id, match(…) as sc, round(match(…),3) as r …` (bare **and**
wrapped copy of one match) | **20105** | ok —
  both resolve to the same stream |

  ### Score in a predicate

  | SQL | Before | After |
  |---|---|---|
| `… where match(body) against('hello') and match(body) against('hello')
> 0.015` | **20105** | ok |
| `… where match(body) against('hello') and round(match(…),4) > 0.015` |
**20105** | ok |
| `… where match(body) against('hello') and cast(match(…) as double) >
0.015` | **20105** | ok |
| `… where match(body) against('hello') and match(…) * 2 > 0.03` |
**20105** | ok |
| `… where match(body) against('hello') and match(…) < 0.015` |
**20105** | ok |
| `… where match(body) against('hello') and not (match(…) > 0.015)` |
**20105** | ok |
| `… where match(body) against('hello') and (match(…) < 0.015 or id =
3)` | **20105** | ok |
| `select id from v where sc > 0.05` (view exposing the score as `sc`) |
**20105** | ok |
| `select id from (select id, match(…) as sc …) x where sc > 0.05` |
**20105** | ok |

  ### A wrapped MATCH with no bare MATCH to lean on

  | SQL | Before | After |
  |---|---|---|
| `select id from two where match(body) against('hello') > 0.015` |
**20105** | ok |
| `select id, round(match(body) against('hello'),3) from two` *(no WHERE
MATCH)* | **20105** | ok |
| `select count(*) from two where match(body) against('hello') > 0.015`
| **20105** | ok |
| `select id from two where match(body) against('hello') > 0.015 limit
1` | **20105** | ok |
| `select id from two order by round(match(body) against('hello'),3)
desc` | **20105** | ok |

Rows now come back in **relevance order** for these, exactly as a bare
MATCH does — previously the
  rewrite produced a `SORT` node with no keys at all.

  ### Several MATCHes in one query

  | SQL | Before | After |
  |---|---|---|
| `select id, match(…'hello') h, match(…'world') w from two where
match(…'hello') and match(…'world')` | ok | ok |
| `select id, round(match(…'world'),3) w … where match(…'hello') and
match(…'world')` | **20105** | ok — reports the
  **world** score |
| `select id, round(match(…'world'),3) … where match(…'hello')` |
**wrong number** (silently the *hello* score) | ok —
  `'world'` gets its own stream |
| `… where match(…'hello') and match(…'world') and match(…'world') >
0.1` | **20105** | ok — reuses the `'world'`
  stream |

  ### JOIN

  | SQL | Before | After |
  |---|---|---|
| `select a.id, b.note from a join b on a.id=b.id where match(a.body)
against('x')` | ok | ok |
| `select a.id, match(a.body) against('x') from a join b …` | **20105**
| ok |
| `select a.id, round(match(a.body) against('x'),3) from a join b …` |
**20105** | ok |
| `select a.id, match(a.body) against('x') sa, match(b.body)
against('x') sb from a join b …` | **20105** | ok —
  **different scores per table** |
| `select a.id from a join b … order by match(a.body) against('x') desc`
| **20105** | ok |
| `select a.id from a join b … where match(a.body) against('x') > 0.02`
| **20105** | ok |
| `select id from two where match(body) against('x') > 0.02 and id in
(select id from jb)` (SEMI) | **20105** | ok |
  | self join `a x join a y`, each side its own MATCH | **20105** | ok |
  | `a left join b`, MATCH on the outer side | **20105** | ok |
| UNION ALL of two joined fulltext queries; a CTE referenced twice |
**20105** | ok |

The cross-table row is the one worth a second look: `sa` and `sb` must
be **different numbers on
the same row**. Index parts are otherwise compared by column *name*, and
with two tables in scope
`match(a.body)` and `match(b.body)` look identical — so resolution
across a join is binding-tag
  aware.
| `select id, match(…) as sc, round(match(…),3) as r …` (bare **and**
wrapped copy of one match) | **20105** | ok —
  both resolve to the same stream |

  ### Score in a predicate

  | SQL | Before | After |
  |---|---|---|
| `… where match(body) against('hello') and match(body) against('hello')
> 0.015` | **20105** | ok |
| `… where match(body) against('hello') and round(match(…),4) > 0.015` |
**20105** | ok |
| `… where match(body) against('hello') and cast(match(…) as double) >
0.015` | **20105** | ok |
| `… where match(body) against('hello') and match(…) * 2 > 0.03` |
**20105** | ok |
| `… where match(body) against('hello') and match(…) < 0.015` |
**20105** | ok |
| `… where match(body) against('hello') and not (match(…) > 0.015)` |
**20105** | ok |
| `… where match(body) against('hello') and (match(…) < 0.015 or id =
3)` | **20105** | ok |
| `select id from v where sc > 0.05` (view exposing the score as `sc`) |
**20105** | ok |
| `select id from (select id, match(…) as sc …) x where sc > 0.05` |
**20105** | ok |

  ### A wrapped MATCH with no bare MATCH to lean on

  | SQL | Before | After |
  |---|---|---|
| `select id from two where match(body) against('hello') > 0.015` |
**20105** | ok |
| `select id, round(match(body) against('hello'),3) from two` *(no WHERE
MATCH)* | **20105** | ok |
| `select count(*) from two where match(body) against('hello') > 0.015`
| **20105** | ok |
| `select id from two where match(body) against('hello') > 0.015 limit
1` | **20105** | ok |
| `select id from two order by round(match(body) against('hello'),3)
desc` | **20105** | ok |

Rows now come back in **relevance order** for these, exactly as a bare
MATCH does — previously the
  rewrite produced a `SORT` node with no keys at all.

  ### Several MATCHes in one query

  | SQL | Before | After |
  |---|---|---|
| `select id, match(…'hello') h, match(…'world') w from two where
match(…'hello') and match(…'world')` | ok | ok |
| `select id, round(match(…'world'),3) w … where match(…'hello') and
match(…'world')` | **20105** | ok — reports the
  **world** score |
| `select id, round(match(…'world'),3) … where match(…'hello')` |
**wrong number** (silently the *hello* score) | ok —
  `'world'` gets its own stream |
| `… where match(…'hello') and match(…'world') and match(…'world') >
0.1` | **20105** | ok — reuses the `'world'`
  stream |

  ### JOIN

  | SQL | Before | After |
- New `moerr.ErrFtMatchingKeyNotFound` (20327) → MySQL
`ER_FT_MATCHING_KEY_NOT_FOUND` (1191).
Recognised by code **and** message text, because the background executor
rebuilds the error on
the way back and strips the code — verified end to end; a code-only
guard did not fire.

**3 · A wrapped MATCH is served** (`5987e15add`, `3befd17a9e`,
`c7c796efc3`, `06d3bf8ab6`,
  `4a2306eadd`, `1fa54fe6c3`, `5adc55823c`, `8e113d37f3`, `154241f0bc`)

- **Resolved by argument, not by function name.**
`equalsFullTextMatchFunc` (pattern, mode, index
parts) decides which stream answers a given MATCH — the same test that
already builds `eqmap`.
- A wrapped MATCH can **drive** the rewrite, from a membership-implying
position only:
AND-reachable, `score > c` (c ≥ 0) or `score >= c` (c > 0), through
order-preserving wrappers.
- Wired into the projection, aggregate and join-child dispatches, and
into the fulltext2 covered
    fast path (reachable when the MATCH column is the primary key).
- The lifted predicate goes in a `Node_FILTER`, **not**
`Node_JOIN.FilterList` — the planner never
sets that field and the executor never reads it, though `EXPLAIN` prints
it.
- Resolution over a join records what each child's rewrite served, then
matches binding-tag aware.

  **4 · fulltext2 pushes a score range into the engine** (`c3a50a16eb`)

An AND-reachable `MATCH(…) <op> const` becomes a `fulltext2.ScoreRange`
handed to the search,
which drops out-of-range documents at `streamSink.push*` / `runTopK`
instead of shipping them
across the join. A range, not a `min_score`, so `>`/`>=`/`<`/`<=` and
their AND-combinations are
| `select id, match(…) as sc, round(match(…),3) as r …` (bare **and**
wrapped copy of one match) | **20105** | ok —
  both resolve to the same stream |

  ### Score in a predicate

  | SQL | Before | After |
  |---|---|---|
| `… where match(body) against('hello') and match(body) against('hello')
> 0.015` | **20105** | ok |
| `… where match(body) against('hello') and round(match(…),4) > 0.015` |
**20105** | ok |
| `… where match(body) against('hello') and cast(match(…) as double) >
0.015` | **20105** | ok |
| `… where match(body) against('hello') and match(…) * 2 > 0.03` |
**20105** | ok |
| `… where match(body) against('hello') and match(…) < 0.015` |
**20105** | ok |
| `… where match(body) against('hello') and not (match(…) > 0.015)` |
**20105** | ok |
| `… where match(body) against('hello') and (match(…) < 0.015 or id =
3)` | **20105** | ok |
| `select id from v where sc > 0.05` (view exposing the score as `sc`) |
**20105** | ok |
| `select id from (select id, match(…) as sc …) x where sc > 0.05` |
**20105** | ok |

  ### A wrapped MATCH with no bare MATCH to lean on

  | SQL | Before | After |
  |---|---|---|
| `select id from two where match(body) against('hello') > 0.015` |
**20105** | ok |
| `select id, round(match(body) against('hello'),3) from two` *(no WHERE
MATCH)* | **20105** | ok |
| `select count(*) from two where match(body) against('hello') > 0.015`
| **20105** | ok |
| `select id from two where match(body) against('hello') > 0.015 limit
1` | **20105** | ok |
| `select id from two order by round(match(body) against('hello'),3)
desc` | **20105** | ok |

Rows now come back in **relevance order** for these, exactly as a bare
MATCH does — previously the
  rewrite produced a `SORT` node with no keys at all.

  ### Several MATCHes in one query

  | SQL | Before | After |
  |---|---|---|
| `select id, match(…'hello') h, match(…'world') w from two where
match(…'hello') and match(…'world')` | ok | ok |
| `select id, round(match(…'world'),3) w … where match(…'hello') and
match(…'world')` | **20105** | ok — reports the
  **world** score |
| `select id, round(match(…'world'),3) … where match(…'hello')` |
**wrong number** (silently the *hello* score) | ok —
  `'world'` gets its own stream |
| `… where match(…'hello') and match(…'world') and match(…'world') >
0.1` | **20105** | ok — reuses the `'world'`
  stream |

  ### JOIN

  | SQL | Before | After |
  |---|---|---|
| `select a.id, b.note from a join b on a.id=b.id where match(a.body)
against('x')` | ok | ok |
| `select a.id, match(a.body) against('x') from a join b …` | **20105**
| ok |
| `select a.id, round(match(a.body) against('x'),3) from a join b …` |
**20105** | ok |
| `select a.id, match(a.body) against('x') sa, match(b.body)
against('x') sb from a join b …` | **20105** | ok —
  **different scores per table** |
| `select a.id from a join b … order by match(a.body) against('x') desc`
| **20105** | ok |
| `select a.id from a join b … where match(a.body) against('x') > 0.02`
| **20105** | ok |
| `select id from two where match(body) against('x') > 0.02 and id in
(select id from jb)` (SEMI) | **20105** | ok |
  | self join `a x join a y`, each side its own MATCH | **20105** | ok |
  | `a left join b`, MATCH on the outer side | **20105** | ok |
| UNION ALL of two joined fulltext queries; a CTE referenced twice |
**20105** | ok |

The cross-table row is the one worth a second look: `sa` and `sb` must
be **different numbers on
the same row**. Index parts are otherwise compared by column *name*, and
with two tables in scope
`match(a.body)` and `match(b.body)` look identical — so resolution
across a join is binding-tag
  aware.

  ### Still unsupported — and why

  | SQL | Result | Reason |
  |---|---|---|
| `where match(body) against('x') > 0.5 or id = 4` | 20105 | The stream
is INNER JOINed, so a MATCH may only *drive*
from a position that implies index membership. Under `OR` the predicate
need not hold for a returned row; harvesting it
  silently dropped `id = 4` (see below). |
  | `where not match(body) against('x')` | 20105 | same |
| `where match(body) against('x') < 0.015` *(no bare MATCH)* | 20105 | A
non-matching document scores 0, so `< c` is
true for rows the stream does not contain. Needs the stream LEFT joined
with a 0 default — MySQL's model, separate
  change. |
| `where match(body) against('x') >= 0` | 20105 | same: relevance 0
satisfies it |
| prepared `select match(body) against(?) … from a join b … where
match(body) against(?)` | 20105 | the two `?` are
distinct expressions, so the projected MATCH matches no stream; over a
join a projected MATCH can only be *resolved
  against* a stream, not create one |
| correlated subquery + MATCH | 20105 | pre-existing — fails with no
projected score either |
  | MATCH + window function | 20105 | pre-existing planner gap |
| MATCH on a column with no FULLTEXT index | 20105 | correct, unchanged
|

  ---

  ## Changes

**1 · Refuse a view definition that can never run** (`78ccb8f6c0`,
`9227524b80`, `4cfbd71b58`)

- New index-plugin hook `ValidateViewDefinition(ctx, query)`, consulted
for every registered
algorithm from `genViewTableDef` on the *optimized* plan — a placeholder
is only known to be
    unservable after the rewrite has had its chance.
- fulltext and fulltext2 implement it via the shared
`RefuseUnservableMatch`; the vector plugins
return nil and document why (their distance functions are real kernels,
so a missed index is a
    slow query, not a broken view).
- Reachability walk from `query.Steps`, not the node arena — a
successful rewrite abandons
    pre-rewrite nodes there, and scanning them refused valid views.
- Skipped when `optimizer_hints` has switched `applyIndices` off: a
diagnostic knob must not
silently become DDL policy. Both readers now share `splitOptimizerHint`,
so the guard can no
    longer believe a hint the optimizer actually ignored.

**2 · A legacy unservable view no longer breaks restore** (`0d7356d079`,
`44d4ac95b1`, `f41277c837`)

- Tolerated in the dependency sort *and* the create loop, on **all
three** paths: `restoreViews`
(snapshot + clone), `restoreViewsWithPitr`, and `restoreViewsFromTS`
(cluster snapshot — this
one had no tolerance at all and still aborted an entire account
restore).
- The view stays in the toposort so dependents still order correctly,
and any existing object of
that name is **left alone** rather than dropped: the snapshot may hold
an unservable definition
while the target holds a working view whose index was recreated since. A
stale object is an
    inconsistency; deleting a working one is data loss.
- New `moerr.ErrFtMatchingKeyNotFound` (20327) → MySQL
`ER_FT_MATCHING_KEY_NOT_FOUND` (1191).
Recognised by code **and** message text, because the background executor
rebuilds the error on
the way back and strips the code — verified end to end; a code-only
guard did not fire.

**3 · A wrapped MATCH is served** (`5987e15add`, `3befd17a9e`,
`c7c796efc3`, `06d3bf8ab6`,
  `4a2306eadd`, `1fa54fe6c3`, `5adc55823c`, `8e113d37f3`, `154241f0bc`)

- **Resolved by argument, not by function name.**
`equalsFullTextMatchFunc` (pattern, mode, index
parts) decides which stream answers a given MATCH — the same test that
already builds `eqmap`.
- A wrapped MATCH can **drive** the rewrite, from a membership-implying
position only:
AND-reachable, `score > c` (c ≥ 0) or `score >= c` (c > 0), through
order-preserving wrappers.
- Wired into the projection, aggregate and join-child dispatches, and
into the fulltext2 covered
    fast path (reachable when the MATCH column is the primary key).
- The lifted predicate goes in a `Node_FILTER`, **not**
`Node_JOIN.FilterList` — the planner never
sets that field and the executor never reads it, though `EXPLAIN` prints
it.
- Resolution over a join records what each child's rewrite served, then
matches binding-tag aware.

  **4 · fulltext2 pushes a score range into the engine** (`c3a50a16eb`)

An AND-reachable `MATCH(…) <op> const` becomes a `fulltext2.ScoreRange`
handed to the search,
which drops out-of-range documents at `streamSink.push*` / `runTopK`
instead of shipping them
across the join. A range, not a `min_score`, so `>`/`>=`/`<`/`<=` and
their AND-combinations are
one object with the tightest bound per side. Each bound is widened
outward by one float32 ULP
(SQL compares in double, the engine scores in float32) and the plan
keeps its own Filter, so the
pushdown can only remove work, never rows. Classic fulltext has no
scoring engine of its own and
  is unchanged.

  **5 · `vector_ivf_retry` made deterministic** (`26864bfdc0`)

Two cases asserted outcomes ivfflat clustering decides at random — a
`probe_limit = 1` row count
that varied 4↔5 between builds, and a `limit 2` over a **three-way
distance tie** where any two of
three rows were equally correct. Both reproduce on `main`; the branch
only made them visible.

  ## Behaviour changes reviewers should look at

  | Before | After | Note |
  |---|---|---|
| `CREATE VIEW` with an unservable MATCH succeeded | fails with ER 1191
| intentional, MySQL parity. Existing views
  unaffected — restore skips them |
  | wrapped MATCH → 20105 | returns rows | the main capability change |
| `where match(…) > 0.5 or id = 4` | still 20105 | may only drive from a
membership-implying position |
| two different MATCHes in one query | rows matching **both** (INNER
JOIN) | pre-existing for bare MATCH, now reachable
  from more shapes. MySQL returns the others at relevance 0 |
| projection-only MATCH | only matching rows | pre-existing; MySQL
returns non-matching rows at relevance 0 |

## Known gaps and decisions (deliberate — recorded so review needn't
re-litigate them)

- **`OR` / `NOT` / `< c` cannot drive a stream** — needs the stream LEFT
joined with a 0 default.
- **Prepared statement projecting a score over a join** — distinct `?`
placeholders.
- **Correlated subquery + MATCH**, **MATCH + window function** —
pre-existing gaps.
- **CLONE** reports success while omitting an unservable view,
consistent with the
    `skipIfDependencyMissing=true` it already passes.
- **`DROP INDEX` under a dependent view stays allowed** — MySQL parity,
measured (MySQL also
permits `DROP COLUMN` / `DROP TABLE` under a view). Decision recorded in
`viewdef.go`.
- **Wrapped-only streams get no runtime-filter probe** — performance
only, deferred rather than
    bundled into correctness fixes.

  ## Testing

  BVT on a clean instance:

  | suite | result |
  |---|---|
  | fulltext | 1328 / 1331 — 0 failed |
  | fulltext2 | 566 / 566 |
  | vector | 1528 / 1530 — 0 failed |
  | snapshot | 17738 / 17738 |
  | pitr | 506 / 506 |

`go test ./pkg/sql/plan ./pkg/frontend ./pkg/fulltext2
./pkg/sql/colexec/table_function` — ok.

New cases: `fulltext_view_ddl`, `fulltext_wrapped_score`,
`fulltext_join_score`,
  `fulltext2_view_ddl`, `fulltext2_wrapped_score`, `vector_view_ddl`,
`snapshot_restore_unservable_view` — plus unit tests for the
view-definition walk, the
argument-aware resolution, the score-range construction and interval
semantics, the stream sink
  honouring a range, and hint-parser parity with `handleOptimizerHints`.

**Thresholds in the new cases are deliberately discriminating** — two
search terms with distinct
expected scores, and LIMIT cases whose qualifying rows are *not* the
top-scoring ones. An earlier
revision of this work passed a whole suite of `sc > 0` assertions while
attaching the lifted
predicate to `Node_JOIN.FilterList`: every matching row satisfies `> 0`,
so a predicate that was
  never applied looked identical to a correct one.

Snapshot restore and PITR were additionally verified by hand against a
live server; the fulltext2
score-range pushdown is verified by a Go test that exercises the engine
directly, because an
end-to-end result cannot distinguish "the engine filtered it" from "the
Filter above did".

  ## Review history

Two full review passes. The first found the `Node_JOIN.FilterList` no-op
and the argument-matching
defect. The second found a MATCH under `OR`/`NOT` driving an
INNER-JOINed stream — `where match(…)
> 0.5 or id = 4` returned the empty set instead of `id = 4` — and the
missing tolerance on the
cluster-snapshot restore path. Both rounds' findings are fixed or
recorded above.

Every row in those tables is a shape I ran against a live server this
session, not one I inferred from reading the
rewrite — including the ones in the "still unsupported" table, which is
why each has a reason rather than a shrug.

---------

Co-authored-by: Claude Opus 5 (1M context) <[email protected]>
VioletQwQ-0 pushed a commit to VioletQwQ-0/matrixone that referenced this pull request Sep 17, 2026
…t a matching FULLTEXT index (matrixorigin#27171)

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

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



  ## What this fixes

  Closes matrixorigin#27027.

`CREATE VIEW … MATCH(col) AGAINST('x')` was accepted even when no
FULLTEXT index could serve
  that MATCH. The view then failed on every `SELECT` with

  ```
20105: MATCH() AGAINST() function cannot be replaced by FULLTEXT INDEX
and
         full table scan with fulltext search is not supported yet
  ```

and — the part that made it more than a nuisance — such a view **aborted
snapshot restore,
PITR and CLONE entirely**, because restore replays the stored `CREATE
VIEW`. One unrunnable
  legacy view made a whole account unrestorable.

Fixing that exposed *why* people write these views: a MATCH wrapped in
anything at all was never
served. `round(match(…),3)`, `cast(…)`, `match(…) * 100`, `match(…) >
0.5`, a score selected
across a join — all threw 20105, so the error looked arbitrary rather
than like a missing index.
This PR does both halves: refuse the view that can never run, and make
the shapes people actually
  write work.

  ---

  ## Query shapes: before and after

Fixture used throughout (classic fulltext; fulltext2 behaves the same
unless noted):

  ```sql
  create table two(id int primary key, body text);
insert into two values (1,'hello'),(2,'hello hello'),(3,'hello hello
hello'),
                         (4,'world'),(5,'hello hello world');
  create fulltext index ft on two(body);
  ```

  ### Scalar wrappers in the projection

  | SQL | Before | After |
  |---|---|---|
| `select id, match(body) against('hello') from two where match(body)
against('hello')` | ok | ok |
| `select id, round(match(body) against('hello'),3) …` | **20105** | ok
|
| `select id, cast(match(body) against('hello') as decimal(10,3)) …` |
**20105** | ok |
  | `select id, match(body) against('hello') * 100 …` | **20105** | ok |
| `select id, round(match(body) against('hello') + 1, 3) …` | **20105**
| ok |
| `select id, match(…) as sc, round(match(…),3) as r …` (bare **and**
wrapped copy of one match) | **20105** | ok —
  both resolve to the same stream |

  ### Score in a predicate

  | SQL | Before | After |
  |---|---|---|
| `… where match(body) against('hello') and match(body) against('hello')
> 0.015` | **20105** | ok |
| `… where match(body) against('hello') and round(match(…),4) > 0.015` |
**20105** | ok |
| `… where match(body) against('hello') and cast(match(…) as double) >
0.015` | **20105** | ok |
| `… where match(body) against('hello') and match(…) * 2 > 0.03` |
**20105** | ok |
| `… where match(body) against('hello') and match(…) < 0.015` |
**20105** | ok |
| `… where match(body) against('hello') and not (match(…) > 0.015)` |
**20105** | ok |
| `… where match(body) against('hello') and (match(…) < 0.015 or id =
3)` | **20105** | ok |
| `select id from v where sc > 0.05` (view exposing the score as `sc`) |
**20105** | ok |
| `select id from (select id, match(…) as sc …) x where sc > 0.05` |
**20105** | ok |

  ### A wrapped MATCH with no bare MATCH to lean on

  | SQL | Before | After |
  |---|---|---|
| `select id from two where match(body) against('hello') > 0.015` |
**20105** | ok |
| `select id, round(match(body) against('hello'),3) from two` *(no WHERE
MATCH)* | **20105** | ok |
| `select count(*) from two where match(body) against('hello') > 0.015`
| **20105** | ok |
| `select id from two where match(body) against('hello') > 0.015 limit
1` | **20105** | ok |
| `select id from two order by round(match(body) against('hello'),3)
desc` | **20105** | ok |

Rows now come back in **relevance order** for these, exactly as a bare
MATCH does — previously the
  rewrite produced a `SORT` node with no keys at all.

  ### Several MATCHes in one query

  | SQL | Before | After |
  |---|---|---|
| `select id, match(…'hello') h, match(…'world') w from two where
match(…'hello') and match(…'world')` | ok | ok |
| `select id, round(match(…'world'),3) w … where match(…'hello') and
match(…'world')` | **20105** | ok — reports the
  **world** score |
| `select id, round(match(…'world'),3) … where match(…'hello')` |
**wrong number** (silently the *hello* score) | ok —
  `'world'` gets its own stream |
| `… where match(…'hello') and match(…'world') and match(…'world') >
0.1` | **20105** | ok — reuses the `'world'`
  stream |

  ### JOIN

  | SQL | Before | After |
  |---|---|---|
| `select a.id, b.note from a join b on a.id=b.id where match(a.body)
against('x')` | ok | ok |
| `select a.id, match(a.body) against('x') from a join b …` | **20105**
| ok |
| `select a.id, round(match(a.body) against('x'),3) from a join b …` |
**20105** | ok |
| `select a.id, match(a.body) against('x') sa, match(b.body)
against('x') sb from a join b …` | **20105** | ok —
  **different scores per table** |
| `select a.id from a join b … order by match(a.body) against('x') desc`
| **20105** | ok |
| `select a.id from a join b … where match(a.body) against('x') > 0.02`
| **20105** | ok |
| `select id from two where match(body) against('x') > 0.02 and id in
(select id from jb)` (SEMI) | **20105** | ok |
  | self join `a x join a y`, each side its own MATCH | **20105** | ok |
  | `a left join b`, MATCH on the outer side | **20105** | ok |
| UNION ALL of two joined fulltext queries; a CTE referenced twice |
**20105** | ok |

The cross-table row is the one worth a second look: `sa` and `sb` must
be **different numbers on
the same row**. Index parts are otherwise compared by column *name*, and
with two tables in scope
`match(a.body)` and `match(b.body)` look identical — so resolution
across a join is binding-tag
  aware.
| `select id, match(…) as sc, round(match(…),3) as r …` (bare **and**
wrapped copy of one match) | **20105** | ok —
  both resolve to the same stream |

  ### Score in a predicate

  | SQL | Before | After |
  |---|---|---|
| `… where match(body) against('hello') and match(body) against('hello')
> 0.015` | **20105** | ok |
| `… where match(body) against('hello') and round(match(…),4) > 0.015` |
**20105** | ok |
| `… where match(body) against('hello') and cast(match(…) as double) >
0.015` | **20105** | ok |
| `… where match(body) against('hello') and match(…) * 2 > 0.03` |
**20105** | ok |
| `… where match(body) against('hello') and match(…) < 0.015` |
**20105** | ok |
| `… where match(body) against('hello') and not (match(…) > 0.015)` |
**20105** | ok |
| `… where match(body) against('hello') and (match(…) < 0.015 or id =
3)` | **20105** | ok |
| `select id from v where sc > 0.05` (view exposing the score as `sc`) |
**20105** | ok |
| `select id from (select id, match(…) as sc …) x where sc > 0.05` |
**20105** | ok |

  ### A wrapped MATCH with no bare MATCH to lean on

  | SQL | Before | After |
  |---|---|---|
| `select id from two where match(body) against('hello') > 0.015` |
**20105** | ok |
| `select id, round(match(body) against('hello'),3) from two` *(no WHERE
MATCH)* | **20105** | ok |
| `select count(*) from two where match(body) against('hello') > 0.015`
| **20105** | ok |
| `select id from two where match(body) against('hello') > 0.015 limit
1` | **20105** | ok |
| `select id from two order by round(match(body) against('hello'),3)
desc` | **20105** | ok |

Rows now come back in **relevance order** for these, exactly as a bare
MATCH does — previously the
  rewrite produced a `SORT` node with no keys at all.

  ### Several MATCHes in one query

  | SQL | Before | After |
  |---|---|---|
| `select id, match(…'hello') h, match(…'world') w from two where
match(…'hello') and match(…'world')` | ok | ok |
| `select id, round(match(…'world'),3) w … where match(…'hello') and
match(…'world')` | **20105** | ok — reports the
  **world** score |
| `select id, round(match(…'world'),3) … where match(…'hello')` |
**wrong number** (silently the *hello* score) | ok —
  `'world'` gets its own stream |
| `… where match(…'hello') and match(…'world') and match(…'world') >
0.1` | **20105** | ok — reuses the `'world'`
  stream |

  ### JOIN

  | SQL | Before | After |
- New `moerr.ErrFtMatchingKeyNotFound` (20327) → MySQL
`ER_FT_MATCHING_KEY_NOT_FOUND` (1191).
Recognised by code **and** message text, because the background executor
rebuilds the error on
the way back and strips the code — verified end to end; a code-only
guard did not fire.

**3 · A wrapped MATCH is served** (`5987e15add`, `3befd17a9e`,
`c7c796efc3`, `06d3bf8ab6`,
  `4a2306eadd`, `1fa54fe6c3`, `5adc55823c`, `8e113d37f3`, `154241f0bc`)

- **Resolved by argument, not by function name.**
`equalsFullTextMatchFunc` (pattern, mode, index
parts) decides which stream answers a given MATCH — the same test that
already builds `eqmap`.
- A wrapped MATCH can **drive** the rewrite, from a membership-implying
position only:
AND-reachable, `score > c` (c ≥ 0) or `score >= c` (c > 0), through
order-preserving wrappers.
- Wired into the projection, aggregate and join-child dispatches, and
into the fulltext2 covered
    fast path (reachable when the MATCH column is the primary key).
- The lifted predicate goes in a `Node_FILTER`, **not**
`Node_JOIN.FilterList` — the planner never
sets that field and the executor never reads it, though `EXPLAIN` prints
it.
- Resolution over a join records what each child's rewrite served, then
matches binding-tag aware.

  **4 · fulltext2 pushes a score range into the engine** (`c3a50a16eb`)

An AND-reachable `MATCH(…) <op> const` becomes a `fulltext2.ScoreRange`
handed to the search,
which drops out-of-range documents at `streamSink.push*` / `runTopK`
instead of shipping them
across the join. A range, not a `min_score`, so `>`/`>=`/`<`/`<=` and
their AND-combinations are
| `select id, match(…) as sc, round(match(…),3) as r …` (bare **and**
wrapped copy of one match) | **20105** | ok —
  both resolve to the same stream |

  ### Score in a predicate

  | SQL | Before | After |
  |---|---|---|
| `… where match(body) against('hello') and match(body) against('hello')
> 0.015` | **20105** | ok |
| `… where match(body) against('hello') and round(match(…),4) > 0.015` |
**20105** | ok |
| `… where match(body) against('hello') and cast(match(…) as double) >
0.015` | **20105** | ok |
| `… where match(body) against('hello') and match(…) * 2 > 0.03` |
**20105** | ok |
| `… where match(body) against('hello') and match(…) < 0.015` |
**20105** | ok |
| `… where match(body) against('hello') and not (match(…) > 0.015)` |
**20105** | ok |
| `… where match(body) against('hello') and (match(…) < 0.015 or id =
3)` | **20105** | ok |
| `select id from v where sc > 0.05` (view exposing the score as `sc`) |
**20105** | ok |
| `select id from (select id, match(…) as sc …) x where sc > 0.05` |
**20105** | ok |

  ### A wrapped MATCH with no bare MATCH to lean on

  | SQL | Before | After |
  |---|---|---|
| `select id from two where match(body) against('hello') > 0.015` |
**20105** | ok |
| `select id, round(match(body) against('hello'),3) from two` *(no WHERE
MATCH)* | **20105** | ok |
| `select count(*) from two where match(body) against('hello') > 0.015`
| **20105** | ok |
| `select id from two where match(body) against('hello') > 0.015 limit
1` | **20105** | ok |
| `select id from two order by round(match(body) against('hello'),3)
desc` | **20105** | ok |

Rows now come back in **relevance order** for these, exactly as a bare
MATCH does — previously the
  rewrite produced a `SORT` node with no keys at all.

  ### Several MATCHes in one query

  | SQL | Before | After |
  |---|---|---|
| `select id, match(…'hello') h, match(…'world') w from two where
match(…'hello') and match(…'world')` | ok | ok |
| `select id, round(match(…'world'),3) w … where match(…'hello') and
match(…'world')` | **20105** | ok — reports the
  **world** score |
| `select id, round(match(…'world'),3) … where match(…'hello')` |
**wrong number** (silently the *hello* score) | ok —
  `'world'` gets its own stream |
| `… where match(…'hello') and match(…'world') and match(…'world') >
0.1` | **20105** | ok — reuses the `'world'`
  stream |

  ### JOIN

  | SQL | Before | After |
  |---|---|---|
| `select a.id, b.note from a join b on a.id=b.id where match(a.body)
against('x')` | ok | ok |
| `select a.id, match(a.body) against('x') from a join b …` | **20105**
| ok |
| `select a.id, round(match(a.body) against('x'),3) from a join b …` |
**20105** | ok |
| `select a.id, match(a.body) against('x') sa, match(b.body)
against('x') sb from a join b …` | **20105** | ok —
  **different scores per table** |
| `select a.id from a join b … order by match(a.body) against('x') desc`
| **20105** | ok |
| `select a.id from a join b … where match(a.body) against('x') > 0.02`
| **20105** | ok |
| `select id from two where match(body) against('x') > 0.02 and id in
(select id from jb)` (SEMI) | **20105** | ok |
  | self join `a x join a y`, each side its own MATCH | **20105** | ok |
  | `a left join b`, MATCH on the outer side | **20105** | ok |
| UNION ALL of two joined fulltext queries; a CTE referenced twice |
**20105** | ok |

The cross-table row is the one worth a second look: `sa` and `sb` must
be **different numbers on
the same row**. Index parts are otherwise compared by column *name*, and
with two tables in scope
`match(a.body)` and `match(b.body)` look identical — so resolution
across a join is binding-tag
  aware.

  ### Still unsupported — and why

  | SQL | Result | Reason |
  |---|---|---|
| `where match(body) against('x') > 0.5 or id = 4` | 20105 | The stream
is INNER JOINed, so a MATCH may only *drive*
from a position that implies index membership. Under `OR` the predicate
need not hold for a returned row; harvesting it
  silently dropped `id = 4` (see below). |
  | `where not match(body) against('x')` | 20105 | same |
| `where match(body) against('x') < 0.015` *(no bare MATCH)* | 20105 | A
non-matching document scores 0, so `< c` is
true for rows the stream does not contain. Needs the stream LEFT joined
with a 0 default — MySQL's model, separate
  change. |
| `where match(body) against('x') >= 0` | 20105 | same: relevance 0
satisfies it |
| prepared `select match(body) against(?) … from a join b … where
match(body) against(?)` | 20105 | the two `?` are
distinct expressions, so the projected MATCH matches no stream; over a
join a projected MATCH can only be *resolved
  against* a stream, not create one |
| correlated subquery + MATCH | 20105 | pre-existing — fails with no
projected score either |
  | MATCH + window function | 20105 | pre-existing planner gap |
| MATCH on a column with no FULLTEXT index | 20105 | correct, unchanged
|

  ---

  ## Changes

**1 · Refuse a view definition that can never run** (`78ccb8f6c0`,
`9227524b80`, `4cfbd71b58`)

- New index-plugin hook `ValidateViewDefinition(ctx, query)`, consulted
for every registered
algorithm from `genViewTableDef` on the *optimized* plan — a placeholder
is only known to be
    unservable after the rewrite has had its chance.
- fulltext and fulltext2 implement it via the shared
`RefuseUnservableMatch`; the vector plugins
return nil and document why (their distance functions are real kernels,
so a missed index is a
    slow query, not a broken view).
- Reachability walk from `query.Steps`, not the node arena — a
successful rewrite abandons
    pre-rewrite nodes there, and scanning them refused valid views.
- Skipped when `optimizer_hints` has switched `applyIndices` off: a
diagnostic knob must not
silently become DDL policy. Both readers now share `splitOptimizerHint`,
so the guard can no
    longer believe a hint the optimizer actually ignored.

**2 · A legacy unservable view no longer breaks restore** (`0d7356d079`,
`44d4ac95b1`, `f41277c837`)

- Tolerated in the dependency sort *and* the create loop, on **all
three** paths: `restoreViews`
(snapshot + clone), `restoreViewsWithPitr`, and `restoreViewsFromTS`
(cluster snapshot — this
one had no tolerance at all and still aborted an entire account
restore).
- The view stays in the toposort so dependents still order correctly,
and any existing object of
that name is **left alone** rather than dropped: the snapshot may hold
an unservable definition
while the target holds a working view whose index was recreated since. A
stale object is an
    inconsistency; deleting a working one is data loss.
- New `moerr.ErrFtMatchingKeyNotFound` (20327) → MySQL
`ER_FT_MATCHING_KEY_NOT_FOUND` (1191).
Recognised by code **and** message text, because the background executor
rebuilds the error on
the way back and strips the code — verified end to end; a code-only
guard did not fire.

**3 · A wrapped MATCH is served** (`5987e15add`, `3befd17a9e`,
`c7c796efc3`, `06d3bf8ab6`,
  `4a2306eadd`, `1fa54fe6c3`, `5adc55823c`, `8e113d37f3`, `154241f0bc`)

- **Resolved by argument, not by function name.**
`equalsFullTextMatchFunc` (pattern, mode, index
parts) decides which stream answers a given MATCH — the same test that
already builds `eqmap`.
- A wrapped MATCH can **drive** the rewrite, from a membership-implying
position only:
AND-reachable, `score > c` (c ≥ 0) or `score >= c` (c > 0), through
order-preserving wrappers.
- Wired into the projection, aggregate and join-child dispatches, and
into the fulltext2 covered
    fast path (reachable when the MATCH column is the primary key).
- The lifted predicate goes in a `Node_FILTER`, **not**
`Node_JOIN.FilterList` — the planner never
sets that field and the executor never reads it, though `EXPLAIN` prints
it.
- Resolution over a join records what each child's rewrite served, then
matches binding-tag aware.

  **4 · fulltext2 pushes a score range into the engine** (`c3a50a16eb`)

An AND-reachable `MATCH(…) <op> const` becomes a `fulltext2.ScoreRange`
handed to the search,
which drops out-of-range documents at `streamSink.push*` / `runTopK`
instead of shipping them
across the join. A range, not a `min_score`, so `>`/`>=`/`<`/`<=` and
their AND-combinations are
one object with the tightest bound per side. Each bound is widened
outward by one float32 ULP
(SQL compares in double, the engine scores in float32) and the plan
keeps its own Filter, so the
pushdown can only remove work, never rows. Classic fulltext has no
scoring engine of its own and
  is unchanged.

  **5 · `vector_ivf_retry` made deterministic** (`26864bfdc0`)

Two cases asserted outcomes ivfflat clustering decides at random — a
`probe_limit = 1` row count
that varied 4↔5 between builds, and a `limit 2` over a **three-way
distance tie** where any two of
three rows were equally correct. Both reproduce on `main`; the branch
only made them visible.

  ## Behaviour changes reviewers should look at

  | Before | After | Note |
  |---|---|---|
| `CREATE VIEW` with an unservable MATCH succeeded | fails with ER 1191
| intentional, MySQL parity. Existing views
  unaffected — restore skips them |
  | wrapped MATCH → 20105 | returns rows | the main capability change |
| `where match(…) > 0.5 or id = 4` | still 20105 | may only drive from a
membership-implying position |
| two different MATCHes in one query | rows matching **both** (INNER
JOIN) | pre-existing for bare MATCH, now reachable
  from more shapes. MySQL returns the others at relevance 0 |
| projection-only MATCH | only matching rows | pre-existing; MySQL
returns non-matching rows at relevance 0 |

## Known gaps and decisions (deliberate — recorded so review needn't
re-litigate them)

- **`OR` / `NOT` / `< c` cannot drive a stream** — needs the stream LEFT
joined with a 0 default.
- **Prepared statement projecting a score over a join** — distinct `?`
placeholders.
- **Correlated subquery + MATCH**, **MATCH + window function** —
pre-existing gaps.
- **CLONE** reports success while omitting an unservable view,
consistent with the
    `skipIfDependencyMissing=true` it already passes.
- **`DROP INDEX` under a dependent view stays allowed** — MySQL parity,
measured (MySQL also
permits `DROP COLUMN` / `DROP TABLE` under a view). Decision recorded in
`viewdef.go`.
- **Wrapped-only streams get no runtime-filter probe** — performance
only, deferred rather than
    bundled into correctness fixes.

  ## Testing

  BVT on a clean instance:

  | suite | result |
  |---|---|
  | fulltext | 1328 / 1331 — 0 failed |
  | fulltext2 | 566 / 566 |
  | vector | 1528 / 1530 — 0 failed |
  | snapshot | 17738 / 17738 |
  | pitr | 506 / 506 |

`go test ./pkg/sql/plan ./pkg/frontend ./pkg/fulltext2
./pkg/sql/colexec/table_function` — ok.

New cases: `fulltext_view_ddl`, `fulltext_wrapped_score`,
`fulltext_join_score`,
  `fulltext2_view_ddl`, `fulltext2_wrapped_score`, `vector_view_ddl`,
`snapshot_restore_unservable_view` — plus unit tests for the
view-definition walk, the
argument-aware resolution, the score-range construction and interval
semantics, the stream sink
  honouring a range, and hint-parser parity with `handleOptimizerHints`.

**Thresholds in the new cases are deliberately discriminating** — two
search terms with distinct
expected scores, and LIMIT cases whose qualifying rows are *not* the
top-scoring ones. An earlier
revision of this work passed a whole suite of `sc > 0` assertions while
attaching the lifted
predicate to `Node_JOIN.FilterList`: every matching row satisfies `> 0`,
so a predicate that was
  never applied looked identical to a correct one.

Snapshot restore and PITR were additionally verified by hand against a
live server; the fulltext2
score-range pushdown is verified by a Go test that exercises the engine
directly, because an
end-to-end result cannot distinguish "the engine filtered it" from "the
Filter above did".

  ## Review history

Two full review passes. The first found the `Node_JOIN.FilterList` no-op
and the argument-matching
defect. The second found a MATCH under `OR`/`NOT` driving an
INNER-JOINed stream — `where match(…)
> 0.5 or id = 4` returned the empty set instead of `id = 4` — and the
missing tolerance on the
cluster-snapshot restore path. Both rounds' findings are fixed or
recorded above.

Every row in those tables is a shape I ran against a live server this
session, not one I inferred from reading the
rewrite — including the ones in the "still unsupported" table, which is
why each has a reason rather than a shrug.

---------

Co-authored-by: Claude Opus 5 (1M context) <[email protected]>
VioletQwQ-0 pushed a commit to VioletQwQ-0/matrixone that referenced this pull request Sep 17, 2026
…t a matching FULLTEXT index (matrixorigin#27171)

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

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



  ## What this fixes

  Closes matrixorigin#27027.

`CREATE VIEW … MATCH(col) AGAINST('x')` was accepted even when no
FULLTEXT index could serve
  that MATCH. The view then failed on every `SELECT` with

  ```
20105: MATCH() AGAINST() function cannot be replaced by FULLTEXT INDEX
and
         full table scan with fulltext search is not supported yet
  ```

and — the part that made it more than a nuisance — such a view **aborted
snapshot restore,
PITR and CLONE entirely**, because restore replays the stored `CREATE
VIEW`. One unrunnable
  legacy view made a whole account unrestorable.

Fixing that exposed *why* people write these views: a MATCH wrapped in
anything at all was never
served. `round(match(…),3)`, `cast(…)`, `match(…) * 100`, `match(…) >
0.5`, a score selected
across a join — all threw 20105, so the error looked arbitrary rather
than like a missing index.
This PR does both halves: refuse the view that can never run, and make
the shapes people actually
  write work.

  ---

  ## Query shapes: before and after

Fixture used throughout (classic fulltext; fulltext2 behaves the same
unless noted):

  ```sql
  create table two(id int primary key, body text);
insert into two values (1,'hello'),(2,'hello hello'),(3,'hello hello
hello'),
                         (4,'world'),(5,'hello hello world');
  create fulltext index ft on two(body);
  ```

  ### Scalar wrappers in the projection

  | SQL | Before | After |
  |---|---|---|
| `select id, match(body) against('hello') from two where match(body)
against('hello')` | ok | ok |
| `select id, round(match(body) against('hello'),3) …` | **20105** | ok
|
| `select id, cast(match(body) against('hello') as decimal(10,3)) …` |
**20105** | ok |
  | `select id, match(body) against('hello') * 100 …` | **20105** | ok |
| `select id, round(match(body) against('hello') + 1, 3) …` | **20105**
| ok |
| `select id, match(…) as sc, round(match(…),3) as r …` (bare **and**
wrapped copy of one match) | **20105** | ok —
  both resolve to the same stream |

  ### Score in a predicate

  | SQL | Before | After |
  |---|---|---|
| `… where match(body) against('hello') and match(body) against('hello')
> 0.015` | **20105** | ok |
| `… where match(body) against('hello') and round(match(…),4) > 0.015` |
**20105** | ok |
| `… where match(body) against('hello') and cast(match(…) as double) >
0.015` | **20105** | ok |
| `… where match(body) against('hello') and match(…) * 2 > 0.03` |
**20105** | ok |
| `… where match(body) against('hello') and match(…) < 0.015` |
**20105** | ok |
| `… where match(body) against('hello') and not (match(…) > 0.015)` |
**20105** | ok |
| `… where match(body) against('hello') and (match(…) < 0.015 or id =
3)` | **20105** | ok |
| `select id from v where sc > 0.05` (view exposing the score as `sc`) |
**20105** | ok |
| `select id from (select id, match(…) as sc …) x where sc > 0.05` |
**20105** | ok |

  ### A wrapped MATCH with no bare MATCH to lean on

  | SQL | Before | After |
  |---|---|---|
| `select id from two where match(body) against('hello') > 0.015` |
**20105** | ok |
| `select id, round(match(body) against('hello'),3) from two` *(no WHERE
MATCH)* | **20105** | ok |
| `select count(*) from two where match(body) against('hello') > 0.015`
| **20105** | ok |
| `select id from two where match(body) against('hello') > 0.015 limit
1` | **20105** | ok |
| `select id from two order by round(match(body) against('hello'),3)
desc` | **20105** | ok |

Rows now come back in **relevance order** for these, exactly as a bare
MATCH does — previously the
  rewrite produced a `SORT` node with no keys at all.

  ### Several MATCHes in one query

  | SQL | Before | After |
  |---|---|---|
| `select id, match(…'hello') h, match(…'world') w from two where
match(…'hello') and match(…'world')` | ok | ok |
| `select id, round(match(…'world'),3) w … where match(…'hello') and
match(…'world')` | **20105** | ok — reports the
  **world** score |
| `select id, round(match(…'world'),3) … where match(…'hello')` |
**wrong number** (silently the *hello* score) | ok —
  `'world'` gets its own stream |
| `… where match(…'hello') and match(…'world') and match(…'world') >
0.1` | **20105** | ok — reuses the `'world'`
  stream |

  ### JOIN

  | SQL | Before | After |
  |---|---|---|
| `select a.id, b.note from a join b on a.id=b.id where match(a.body)
against('x')` | ok | ok |
| `select a.id, match(a.body) against('x') from a join b …` | **20105**
| ok |
| `select a.id, round(match(a.body) against('x'),3) from a join b …` |
**20105** | ok |
| `select a.id, match(a.body) against('x') sa, match(b.body)
against('x') sb from a join b …` | **20105** | ok —
  **different scores per table** |
| `select a.id from a join b … order by match(a.body) against('x') desc`
| **20105** | ok |
| `select a.id from a join b … where match(a.body) against('x') > 0.02`
| **20105** | ok |
| `select id from two where match(body) against('x') > 0.02 and id in
(select id from jb)` (SEMI) | **20105** | ok |
  | self join `a x join a y`, each side its own MATCH | **20105** | ok |
  | `a left join b`, MATCH on the outer side | **20105** | ok |
| UNION ALL of two joined fulltext queries; a CTE referenced twice |
**20105** | ok |

The cross-table row is the one worth a second look: `sa` and `sb` must
be **different numbers on
the same row**. Index parts are otherwise compared by column *name*, and
with two tables in scope
`match(a.body)` and `match(b.body)` look identical — so resolution
across a join is binding-tag
  aware.
| `select id, match(…) as sc, round(match(…),3) as r …` (bare **and**
wrapped copy of one match) | **20105** | ok —
  both resolve to the same stream |

  ### Score in a predicate

  | SQL | Before | After |
  |---|---|---|
| `… where match(body) against('hello') and match(body) against('hello')
> 0.015` | **20105** | ok |
| `… where match(body) against('hello') and round(match(…),4) > 0.015` |
**20105** | ok |
| `… where match(body) against('hello') and cast(match(…) as double) >
0.015` | **20105** | ok |
| `… where match(body) against('hello') and match(…) * 2 > 0.03` |
**20105** | ok |
| `… where match(body) against('hello') and match(…) < 0.015` |
**20105** | ok |
| `… where match(body) against('hello') and not (match(…) > 0.015)` |
**20105** | ok |
| `… where match(body) against('hello') and (match(…) < 0.015 or id =
3)` | **20105** | ok |
| `select id from v where sc > 0.05` (view exposing the score as `sc`) |
**20105** | ok |
| `select id from (select id, match(…) as sc …) x where sc > 0.05` |
**20105** | ok |

  ### A wrapped MATCH with no bare MATCH to lean on

  | SQL | Before | After |
  |---|---|---|
| `select id from two where match(body) against('hello') > 0.015` |
**20105** | ok |
| `select id, round(match(body) against('hello'),3) from two` *(no WHERE
MATCH)* | **20105** | ok |
| `select count(*) from two where match(body) against('hello') > 0.015`
| **20105** | ok |
| `select id from two where match(body) against('hello') > 0.015 limit
1` | **20105** | ok |
| `select id from two order by round(match(body) against('hello'),3)
desc` | **20105** | ok |

Rows now come back in **relevance order** for these, exactly as a bare
MATCH does — previously the
  rewrite produced a `SORT` node with no keys at all.

  ### Several MATCHes in one query

  | SQL | Before | After |
  |---|---|---|
| `select id, match(…'hello') h, match(…'world') w from two where
match(…'hello') and match(…'world')` | ok | ok |
| `select id, round(match(…'world'),3) w … where match(…'hello') and
match(…'world')` | **20105** | ok — reports the
  **world** score |
| `select id, round(match(…'world'),3) … where match(…'hello')` |
**wrong number** (silently the *hello* score) | ok —
  `'world'` gets its own stream |
| `… where match(…'hello') and match(…'world') and match(…'world') >
0.1` | **20105** | ok — reuses the `'world'`
  stream |

  ### JOIN

  | SQL | Before | After |
- New `moerr.ErrFtMatchingKeyNotFound` (20327) → MySQL
`ER_FT_MATCHING_KEY_NOT_FOUND` (1191).
Recognised by code **and** message text, because the background executor
rebuilds the error on
the way back and strips the code — verified end to end; a code-only
guard did not fire.

**3 · A wrapped MATCH is served** (`5987e15add`, `3befd17a9e`,
`c7c796efc3`, `06d3bf8ab6`,
  `4a2306eadd`, `1fa54fe6c3`, `5adc55823c`, `8e113d37f3`, `154241f0bc`)

- **Resolved by argument, not by function name.**
`equalsFullTextMatchFunc` (pattern, mode, index
parts) decides which stream answers a given MATCH — the same test that
already builds `eqmap`.
- A wrapped MATCH can **drive** the rewrite, from a membership-implying
position only:
AND-reachable, `score > c` (c ≥ 0) or `score >= c` (c > 0), through
order-preserving wrappers.
- Wired into the projection, aggregate and join-child dispatches, and
into the fulltext2 covered
    fast path (reachable when the MATCH column is the primary key).
- The lifted predicate goes in a `Node_FILTER`, **not**
`Node_JOIN.FilterList` — the planner never
sets that field and the executor never reads it, though `EXPLAIN` prints
it.
- Resolution over a join records what each child's rewrite served, then
matches binding-tag aware.

  **4 · fulltext2 pushes a score range into the engine** (`c3a50a16eb`)

An AND-reachable `MATCH(…) <op> const` becomes a `fulltext2.ScoreRange`
handed to the search,
which drops out-of-range documents at `streamSink.push*` / `runTopK`
instead of shipping them
across the join. A range, not a `min_score`, so `>`/`>=`/`<`/`<=` and
their AND-combinations are
| `select id, match(…) as sc, round(match(…),3) as r …` (bare **and**
wrapped copy of one match) | **20105** | ok —
  both resolve to the same stream |

  ### Score in a predicate

  | SQL | Before | After |
  |---|---|---|
| `… where match(body) against('hello') and match(body) against('hello')
> 0.015` | **20105** | ok |
| `… where match(body) against('hello') and round(match(…),4) > 0.015` |
**20105** | ok |
| `… where match(body) against('hello') and cast(match(…) as double) >
0.015` | **20105** | ok |
| `… where match(body) against('hello') and match(…) * 2 > 0.03` |
**20105** | ok |
| `… where match(body) against('hello') and match(…) < 0.015` |
**20105** | ok |
| `… where match(body) against('hello') and not (match(…) > 0.015)` |
**20105** | ok |
| `… where match(body) against('hello') and (match(…) < 0.015 or id =
3)` | **20105** | ok |
| `select id from v where sc > 0.05` (view exposing the score as `sc`) |
**20105** | ok |
| `select id from (select id, match(…) as sc …) x where sc > 0.05` |
**20105** | ok |

  ### A wrapped MATCH with no bare MATCH to lean on

  | SQL | Before | After |
  |---|---|---|
| `select id from two where match(body) against('hello') > 0.015` |
**20105** | ok |
| `select id, round(match(body) against('hello'),3) from two` *(no WHERE
MATCH)* | **20105** | ok |
| `select count(*) from two where match(body) against('hello') > 0.015`
| **20105** | ok |
| `select id from two where match(body) against('hello') > 0.015 limit
1` | **20105** | ok |
| `select id from two order by round(match(body) against('hello'),3)
desc` | **20105** | ok |

Rows now come back in **relevance order** for these, exactly as a bare
MATCH does — previously the
  rewrite produced a `SORT` node with no keys at all.

  ### Several MATCHes in one query

  | SQL | Before | After |
  |---|---|---|
| `select id, match(…'hello') h, match(…'world') w from two where
match(…'hello') and match(…'world')` | ok | ok |
| `select id, round(match(…'world'),3) w … where match(…'hello') and
match(…'world')` | **20105** | ok — reports the
  **world** score |
| `select id, round(match(…'world'),3) … where match(…'hello')` |
**wrong number** (silently the *hello* score) | ok —
  `'world'` gets its own stream |
| `… where match(…'hello') and match(…'world') and match(…'world') >
0.1` | **20105** | ok — reuses the `'world'`
  stream |

  ### JOIN

  | SQL | Before | After |
  |---|---|---|
| `select a.id, b.note from a join b on a.id=b.id where match(a.body)
against('x')` | ok | ok |
| `select a.id, match(a.body) against('x') from a join b …` | **20105**
| ok |
| `select a.id, round(match(a.body) against('x'),3) from a join b …` |
**20105** | ok |
| `select a.id, match(a.body) against('x') sa, match(b.body)
against('x') sb from a join b …` | **20105** | ok —
  **different scores per table** |
| `select a.id from a join b … order by match(a.body) against('x') desc`
| **20105** | ok |
| `select a.id from a join b … where match(a.body) against('x') > 0.02`
| **20105** | ok |
| `select id from two where match(body) against('x') > 0.02 and id in
(select id from jb)` (SEMI) | **20105** | ok |
  | self join `a x join a y`, each side its own MATCH | **20105** | ok |
  | `a left join b`, MATCH on the outer side | **20105** | ok |
| UNION ALL of two joined fulltext queries; a CTE referenced twice |
**20105** | ok |

The cross-table row is the one worth a second look: `sa` and `sb` must
be **different numbers on
the same row**. Index parts are otherwise compared by column *name*, and
with two tables in scope
`match(a.body)` and `match(b.body)` look identical — so resolution
across a join is binding-tag
  aware.

  ### Still unsupported — and why

  | SQL | Result | Reason |
  |---|---|---|
| `where match(body) against('x') > 0.5 or id = 4` | 20105 | The stream
is INNER JOINed, so a MATCH may only *drive*
from a position that implies index membership. Under `OR` the predicate
need not hold for a returned row; harvesting it
  silently dropped `id = 4` (see below). |
  | `where not match(body) against('x')` | 20105 | same |
| `where match(body) against('x') < 0.015` *(no bare MATCH)* | 20105 | A
non-matching document scores 0, so `< c` is
true for rows the stream does not contain. Needs the stream LEFT joined
with a 0 default — MySQL's model, separate
  change. |
| `where match(body) against('x') >= 0` | 20105 | same: relevance 0
satisfies it |
| prepared `select match(body) against(?) … from a join b … where
match(body) against(?)` | 20105 | the two `?` are
distinct expressions, so the projected MATCH matches no stream; over a
join a projected MATCH can only be *resolved
  against* a stream, not create one |
| correlated subquery + MATCH | 20105 | pre-existing — fails with no
projected score either |
  | MATCH + window function | 20105 | pre-existing planner gap |
| MATCH on a column with no FULLTEXT index | 20105 | correct, unchanged
|

  ---

  ## Changes

**1 · Refuse a view definition that can never run** (`78ccb8f6c0`,
`9227524b80`, `4cfbd71b58`)

- New index-plugin hook `ValidateViewDefinition(ctx, query)`, consulted
for every registered
algorithm from `genViewTableDef` on the *optimized* plan — a placeholder
is only known to be
    unservable after the rewrite has had its chance.
- fulltext and fulltext2 implement it via the shared
`RefuseUnservableMatch`; the vector plugins
return nil and document why (their distance functions are real kernels,
so a missed index is a
    slow query, not a broken view).
- Reachability walk from `query.Steps`, not the node arena — a
successful rewrite abandons
    pre-rewrite nodes there, and scanning them refused valid views.
- Skipped when `optimizer_hints` has switched `applyIndices` off: a
diagnostic knob must not
silently become DDL policy. Both readers now share `splitOptimizerHint`,
so the guard can no
    longer believe a hint the optimizer actually ignored.

**2 · A legacy unservable view no longer breaks restore** (`0d7356d079`,
`44d4ac95b1`, `f41277c837`)

- Tolerated in the dependency sort *and* the create loop, on **all
three** paths: `restoreViews`
(snapshot + clone), `restoreViewsWithPitr`, and `restoreViewsFromTS`
(cluster snapshot — this
one had no tolerance at all and still aborted an entire account
restore).
- The view stays in the toposort so dependents still order correctly,
and any existing object of
that name is **left alone** rather than dropped: the snapshot may hold
an unservable definition
while the target holds a working view whose index was recreated since. A
stale object is an
    inconsistency; deleting a working one is data loss.
- New `moerr.ErrFtMatchingKeyNotFound` (20327) → MySQL
`ER_FT_MATCHING_KEY_NOT_FOUND` (1191).
Recognised by code **and** message text, because the background executor
rebuilds the error on
the way back and strips the code — verified end to end; a code-only
guard did not fire.

**3 · A wrapped MATCH is served** (`5987e15add`, `3befd17a9e`,
`c7c796efc3`, `06d3bf8ab6`,
  `4a2306eadd`, `1fa54fe6c3`, `5adc55823c`, `8e113d37f3`, `154241f0bc`)

- **Resolved by argument, not by function name.**
`equalsFullTextMatchFunc` (pattern, mode, index
parts) decides which stream answers a given MATCH — the same test that
already builds `eqmap`.
- A wrapped MATCH can **drive** the rewrite, from a membership-implying
position only:
AND-reachable, `score > c` (c ≥ 0) or `score >= c` (c > 0), through
order-preserving wrappers.
- Wired into the projection, aggregate and join-child dispatches, and
into the fulltext2 covered
    fast path (reachable when the MATCH column is the primary key).
- The lifted predicate goes in a `Node_FILTER`, **not**
`Node_JOIN.FilterList` — the planner never
sets that field and the executor never reads it, though `EXPLAIN` prints
it.
- Resolution over a join records what each child's rewrite served, then
matches binding-tag aware.

  **4 · fulltext2 pushes a score range into the engine** (`c3a50a16eb`)

An AND-reachable `MATCH(…) <op> const` becomes a `fulltext2.ScoreRange`
handed to the search,
which drops out-of-range documents at `streamSink.push*` / `runTopK`
instead of shipping them
across the join. A range, not a `min_score`, so `>`/`>=`/`<`/`<=` and
their AND-combinations are
one object with the tightest bound per side. Each bound is widened
outward by one float32 ULP
(SQL compares in double, the engine scores in float32) and the plan
keeps its own Filter, so the
pushdown can only remove work, never rows. Classic fulltext has no
scoring engine of its own and
  is unchanged.

  **5 · `vector_ivf_retry` made deterministic** (`26864bfdc0`)

Two cases asserted outcomes ivfflat clustering decides at random — a
`probe_limit = 1` row count
that varied 4↔5 between builds, and a `limit 2` over a **three-way
distance tie** where any two of
three rows were equally correct. Both reproduce on `main`; the branch
only made them visible.

  ## Behaviour changes reviewers should look at

  | Before | After | Note |
  |---|---|---|
| `CREATE VIEW` with an unservable MATCH succeeded | fails with ER 1191
| intentional, MySQL parity. Existing views
  unaffected — restore skips them |
  | wrapped MATCH → 20105 | returns rows | the main capability change |
| `where match(…) > 0.5 or id = 4` | still 20105 | may only drive from a
membership-implying position |
| two different MATCHes in one query | rows matching **both** (INNER
JOIN) | pre-existing for bare MATCH, now reachable
  from more shapes. MySQL returns the others at relevance 0 |
| projection-only MATCH | only matching rows | pre-existing; MySQL
returns non-matching rows at relevance 0 |

## Known gaps and decisions (deliberate — recorded so review needn't
re-litigate them)

- **`OR` / `NOT` / `< c` cannot drive a stream** — needs the stream LEFT
joined with a 0 default.
- **Prepared statement projecting a score over a join** — distinct `?`
placeholders.
- **Correlated subquery + MATCH**, **MATCH + window function** —
pre-existing gaps.
- **CLONE** reports success while omitting an unservable view,
consistent with the
    `skipIfDependencyMissing=true` it already passes.
- **`DROP INDEX` under a dependent view stays allowed** — MySQL parity,
measured (MySQL also
permits `DROP COLUMN` / `DROP TABLE` under a view). Decision recorded in
`viewdef.go`.
- **Wrapped-only streams get no runtime-filter probe** — performance
only, deferred rather than
    bundled into correctness fixes.

  ## Testing

  BVT on a clean instance:

  | suite | result |
  |---|---|
  | fulltext | 1328 / 1331 — 0 failed |
  | fulltext2 | 566 / 566 |
  | vector | 1528 / 1530 — 0 failed |
  | snapshot | 17738 / 17738 |
  | pitr | 506 / 506 |

`go test ./pkg/sql/plan ./pkg/frontend ./pkg/fulltext2
./pkg/sql/colexec/table_function` — ok.

New cases: `fulltext_view_ddl`, `fulltext_wrapped_score`,
`fulltext_join_score`,
  `fulltext2_view_ddl`, `fulltext2_wrapped_score`, `vector_view_ddl`,
`snapshot_restore_unservable_view` — plus unit tests for the
view-definition walk, the
argument-aware resolution, the score-range construction and interval
semantics, the stream sink
  honouring a range, and hint-parser parity with `handleOptimizerHints`.

**Thresholds in the new cases are deliberately discriminating** — two
search terms with distinct
expected scores, and LIMIT cases whose qualifying rows are *not* the
top-scoring ones. An earlier
revision of this work passed a whole suite of `sc > 0` assertions while
attaching the lifted
predicate to `Node_JOIN.FilterList`: every matching row satisfies `> 0`,
so a predicate that was
  never applied looked identical to a correct one.

Snapshot restore and PITR were additionally verified by hand against a
live server; the fulltext2
score-range pushdown is verified by a Go test that exercises the engine
directly, because an
end-to-end result cannot distinguish "the engine filtered it" from "the
Filter above did".

  ## Review history

Two full review passes. The first found the `Node_JOIN.FilterList` no-op
and the argument-matching
defect. The second found a MATCH under `OR`/`NOT` driving an
INNER-JOINed stream — `where match(…)
> 0.5 or id = 4` returned the empty set instead of `id = 4` — and the
missing tolerance on the
cluster-snapshot restore path. Both rounds' findings are fixed or
recorded above.

Every row in those tables is a shape I ran against a live server this
session, not one I inferred from reading the
rewrite — including the ones in the "still unsupported" table, which is
why each has a reason rather than a shrug.

---------

Co-authored-by: Claude Opus 5 (1M context) <[email protected]>

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.

[Bug]: CREATE/ALTER/REPLACE VIEW persists unusable MATCH queries without a matching FULLTEXT index

6 participants