Skip to content

feat: fulltext2 — complete rewrite of fulltext index and add a position-free BM25 full-text retrieval index - #25904

Merged
fengttt merged 1186 commits into
matrixorigin:mainfrom
cpegeric:fulltext2_only
Aug 12, 2026
Merged

fengttt merged 1186 commits into
matrixorigin:mainfrom
cpegeric:fulltext2_only

Conversation

@cpegeric

@cpegeric cpegeric commented Jul 20, 2026 •

Copy link
Copy Markdown
Contributor

What type of PR is this?

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

Which issue(s) this PR fixes:

issue ##25541

What this PR does / why we need it:

Summary

Adds fulltext2, a new first-class full-text index type built around a WAND / block-max ranked-retrieval engine, and removes the standalone bm25 index (its ranked-retrieval capability is now subsumed by fulltext2's POSITION_FREE mode). fulltext2 is a distinct algo from classic fulltext — not a variant — so it carries its own contract, on-disk format, plugin, CDC path, and query surface.

Classic fulltext keeps positional term data for exact phrase/boolean/NL semantics. fulltext2 adds a position-free build option that drops positions (keeping the FST term dictionary), yielding a much smaller, faster, ranked bag-of-words index — while still supporting a positional build for phrase/boolean parity when you want it.

Gated behind the experimental_fulltext2_index session variable.

Motivation

The earlier "WAND retrieval" experiment proved that ranked BM25 retrieval does not fit as a fulltext parser-mode variant (boolean/phrase/NL need term positions the position-free binary index cannot serve). Rather than graft ranked retrieval onto classic fulltext or maintain a separate bm25 index type, we make it its own index type with a clean contract, and fold the old bm25 engine into it.

SQL surface

DDL — a distinct index type via the USING/index-type seam, with a configurable tokenizer and a position-free option:

SET experimental_fulltext2_index = 1;

-- positional (phrase / boolean / NL capable); parser defaults to ngram
CREATE FULLTEXT2 INDEX idx ON t(body);
CREATE FULLTEXT2 INDEX idx ON t(body) WITH PARSER gojieba;

-- position-free, ranked bag-of-words — requires WITH PARSER gojieba
CREATE FULLTEXT2 INDEX idx ON t(body) WITH PARSER gojieba POSITION_FREE=TRUE;

Full CREATE option grammar — CREATE FULLTEXT2 INDEX name ON t(cols) <options>, where <options> may combine, in any order:

Option Values Meaning
WITH PARSER ngram (default) · gojieba · json · json_value tokenizer
POSITION_FREE TRUE · FALSE (default) drop positions → ranked bag-of-words only (requires gojieba)
AUTO_UPDATE TRUE · FALSE (default) enable the idxcron scheduled auto-maintenance for this index
DAY / HOUR / SECOND integer the auto-maintenance cadence (combined; e.g. DAY=1 = compact daily)
MAX_INDEX_CAPACITY integer per-segment doc capacity (drives tiered-merge fullness)
ASYNC / FORCE_SYNC flag build the initial index asynchronously (CDC) vs synchronously
-- gojieba, position-free, with daily auto-maintenance:
CREATE FULLTEXT2 INDEX idx ON t(body)
  WITH PARSER gojieba POSITION_FREE=TRUE AUTO_UPDATE=TRUE DAY=1;

-- capacity-bounded segments + hourly auto-maintenance:
CREATE FULLTEXT2 INDEX idx ON t(body)
  MAX_INDEX_CAPACITY=100000 AUTO_UPDATE=TRUE HOUR=6;

AUTO_UPDATE=TRUE + DAY/HOUR/SECOND are stored in the index's algo-params and read by the idxcron executor, which schedules a periodic MERGE/REBUILD (see Maintenance below). POSITION_FREE=TRUE is only valid with WITH PARSER gojieba; a bare POSITION_FREE=TRUE (defaults to ngram) and WITH PARSER ngram POSITION_FREE=TRUE are both rejected at DDL — ngram/json emit overlapping tokens meaningless without positions, so they can only build a positional index.

Query — ranked retrieval mode alongside the classic modes:

-- ranked bag-of-words top-K (works on a POSITION_FREE index)
SELECT * FROM t WHERE MATCH(body) AGAINST('query terms' IN BM25 MODE) LIMIT 10;

-- NL / BOOLEAN / phrase still available on a *positional* fulltext2 index
SELECT * FROM t WHERE MATCH(body) AGAINST('+cat -dog' IN BOOLEAN MODE);

Maintenance — ALTER … REINDEX (MERGE / REBUILD / retune)

fulltext2 maintains a tiered index: a tag=0 base (built from source) plus a tag=1 CDC tail of incremental inserts/deletes. ALTER TABLE … ALTER REINDEX <name> FULLTEXT2 <option> drives compaction and retuning:

-- MERGE: fold the tag=1 CDC tail into the tag=0 base (in place, keeps the current
-- position-free/positional mode). Cheap incremental compaction.
ALTER TABLE t ALTER REINDEX ft FULLTEXT2 MERGE;

-- REBUILD (no option): drop the tail AND rebuild the base entirely from source.
-- Use when the dead-doc ratio is high or to recover a partially-materialized index.
ALTER TABLE t ALTER REINDEX ft FULLTEXT2;

-- Retune POSITION_FREE both ways (a REBUILD from source under the new mode).
-- Tri-state parse distinguishes =FALSE from "unset", so it toggles deterministically:
ALTER TABLE t ALTER REINDEX ft FULLTEXT2 POSITION_FREE=FALSE;  -- → positional (phrase/boolean work)
ALTER TABLE t ALTER REINDEX ft FULLTEXT2 POSITION_FREE=TRUE;   -- → position-free (IN BM25 MODE only)

-- FORCE_SYNC: run the reindex synchronously instead of via async CDC.
ALTER TABLE t ALTER REINDEX ft FULLTEXT2 MERGE FORCE_SYNC;

Scheduled (idxcron) maintenance. When the index was created AUTO_UPDATE=TRUE with a DAY/HOUR/SECOND cadence, the idxcron executor runs the same reindex action automatically on that interval, choosing MERGE vs REBUILD by the dead-doc ratio (a tail past the dead-doc threshold rebuilds; otherwise it merges). No manual ALTER … REINDEX is needed in that mode.

Architecture

  • Engine (pkg/fulltext2/): segment build sink, delta+varint block-postings format, FST term dictionary, block-max WAND top-k, dense boolean evaluator, block-by-block phrase intersection, multi-segment index with global corpus stats + per-segment liveness/deletes, mmap'd base segments, CDC tail builder, and MERGE compaction.
  • fulltext2 AlgoPlugin (pkg/fulltext2/plugin/{plan,compile,runtime,idxcron,iscp}): five hook sets, all with var _ Hooks compile-time assertions; routed through the indexplugin.Get(algo) registry (no new per-algo switch in plan/compile). Blank-imported in indexplugin/all and indexplugin/iscp.
  • SQL-plan integration: apply_indices_fulltext2.go / apply_indices_match.go route MATCH … AGAINST to the fulltext2_search TVF with ORDER BY score DESC + LIMIT pushdown; fulltext2_compact.go drives compaction.
  • TVFs: fulltext2_{create,search,compact}.
  • CDC + idxcron: async incremental maintenance (CREATE→sync→query→REINDEX→DROP), scheduled MERGE/REBUILD.

Tokenizers

ngram (default), gojieba (CJK word segmentation), json (JSON values flattened to text, then tokenized as ngram), and json_value (each leaf value indexed as one whole atomic token — classic-fulltext json_value parity), with tokenization parity between build and query. POSITION_FREE is supported only with gojieba — ngram and json produce overlapping/redundant tokens that can't be reconstructed without positions, so they always build a positional index (and are rejected if POSITION_FREE=TRUE is requested).

Performance & footprint

Position-free build is materially smaller and faster than both classic fulltext and the old bm25 index. Residency wins: block-compressed mmap postings + lazy directory (decode a term's block-max entry on lookup), lazy positions section, dense O(N) boolean evaluator, insertion-sort WAND pivot loop (no per-iteration alloc), and a cached cursor curDoc with inline in-block skip.

Safety / guards

  • Reject a FULLTEXT + FULLTEXT2 index on the same column set at DDL.
  • Reject NL/BOOLEAN/phrase modes on a POSITION_FREE index with a clear message.
  • OOM defenses: bounded top-k heap (uncapped LIMIT no longer OOMs), fail-fast memory guard on CDC tail load, off-heap posting decode, corrupt-frame / uvarint-overflow guards on read.
  • Injective per-row keys for temporal/decimal PKs (no data loss); CDC hands uuid/decimal/datetime as typed strings (no types.EncodeValue panics).
  • ALTER ADD FULLTEXT no longer locks its not-yet-created hidden table.
  • Experimental-flag gated; restore/clone supported.

Testing

New BVT suites under test/distributed/cases/fulltext2/ and pessimistic_transaction/fulltext2/: functional sync, POSITION_FREE + IN BM25 MODE, parser coverage (ngram/gojieba/json_value), membership prefilter, ORDER-BY/LIMIT pushdown, FULLTEXT+FULLTEXT2 conflict rejection, async CDC convergence, MERGE/REBUILD, restore/clone, and bugfix regressions. Extensive engine unit tests in pkg/fulltext2/ (boolean parity, phrase-exact, CJK, multi-segment, mmap, serialize round-trip).

Compatibility

New opt-in index type behind an experimental flag; no change to classic fulltext behavior or on-disk format. Fulltext2 reports as FULLTEXT in information_schema / SHOW INDEX (correct MySQL taxonomy).

cpegeric and others added 30 commits July 10, 2026 16:36
golangci-lint flagged 7 files with mis-sorted imports (the pkg/bm25/wand import
placed after pkg/catalog/pkg/common instead of alphabetically before them).

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
The bm25 queries had ORDER BY id, which re-sorted the ranked top-k back into id
order and hid the BM25 ranking the index actually produces. WHERE BM25(...) LIMIT k
already returns deterministic BM25-ranked top-k (the planner injects the score
sort), so ORDER BY id was both redundant and misleading. Removed it across all bm25
cases and regenerated the results, which now show the real ranked order (verified
stable across repeated runs). All bm25 BVTs pass 100%.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Second self-review found two issues in the BM25()-verb surface:

1. FullTextMatchExpr.Format() hardcoded "MATCH (" and ignored the new IsBm25 flag,
   so a BM25() expression deparsed back to MATCH() — a parse->bind->format closure
   gap. Any deparse+reparse path (e.g. CTAS's CreateAsSelectSql) would lose IsBm25 and
   re-bind to the classic fulltext index. Now emits "BM25 (" when IsBm25 (and no mode
   clause — BM25 is always ranked). The pattern stays unquoted, matching the existing
   (tested) classic MATCH Format behavior. Added parser round-trip tests. (The unquoted
   pattern makes CTAS-over-MATCH/BM25 fail identically — a pre-existing classic-fulltext
   limitation, out of scope here.)

2. bm25_match_score (function id 550) was registered but never emitted: a matched bm25
   projection is replaced by the join's score ColRef, and an unmatched one keeps the
   float32 overload of bm25_match itself. Dropped the dead id/name-map/registration
   (FUNCTION_END_NUMBER 551->550).

bm25 BVTs 322/322; function-id golden + parser round-trip tests pass.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
CI patch-coverage gate flagged bm25 files below 0.75 (BVT-covered code doesn't
count toward Go unit coverage). Add CPU unit tests:

- apply_indices_bm25_test.go: findMatchBm25Index, findBm25IndexTables,
  buildBm25SearchTableFunc, and the shared apply_indices_match helpers
  (equalsMatchFunc / findEqualMatchFunc / matchRewriteContextNodeID). Lifts both
  files to ~78-100% per function.
- tree/fulltext_match_test.go: NewBm25MatchFuncExpression + Format (BM25 deparses
  as BM25 with no mode; classic MATCH keeps its mode) + Valid rejects empty
  cols/pattern.
- tokenizer/word_id_test.go: WordID resolves a dict word to a stable id and
  returns ok=false for out-of-dict tokens.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Cover bm25_create / bm25_search / bm25_compact Prepare (now 100%) and the start()
config/arg validation branches (bad type, non-const, empty, malformed JSON, bad
capacity, wrong arg count). The main build/search loop stays BVT-covered — it needs
a live WAND index + cache that unit tests can't cheaply stand up.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Resolve conflicts:
- pkg/vectorindex/{cagra,ivfpq}/search_gpu.go: keep cuvs's [B,Q] quantizer
  generics + []B query check; adopt main's ClampSearchLimit/SearchResultPreallocate
  limit-and-allocation hardening (drop the superseded limit:=rt.Limit and []float32
  check).
- pkg/container/vector/vector.go: combine cuvs's narrow-type (bf16/f16/int8/uint8)
  InplaceSortAndCompact cases + helper with main's default:return + SetSorted(true);
  re-add the "sort" import.
- Makefile: combine cuvs's $(GOEXPERIMENT_OPT)/$(GO) with main's $(GO_MODULE_MODE).

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Brings main's changes (via cuvs_quantize) into the bm25 branch. One conflict in
apply_indices_fulltext.go: keep the unified findEqualMatchFunc (bm25's shared helper)
and adopt main's fulltext pagination block (paginationLimit/paginationOffset ->
buildCandidateLimit -> limitExpr, with the internalLimit=nil relevance guard when an
explicit sort is present).

Because bm25 and classic fulltext share the unified applyJoinFullTextIndices, main's
pagination applies to bm25_search too — verified: BM25 LIMIT k pushes the limit into
the WAND walk, LIMIT/OFFSET paginates correctly, and BM25 ... ORDER BY <other col>
LIMIT k does NOT push the limit into bm25_search (relevance guard). bm25 BVTs 322/322;
fulltext_bm25 202/202.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Two changes to the bm25 plugin surface:

1. Parser: bm25 only ever tokenizes with the shared jieba tokenizer (both
   bm25_create and bm25_search hardcode it and never read the parser param), so
   accepting ngram was misleading — a user asking for ngram silently got jieba.
   Restrict supportedParsers to {gojieba, default} (default is a gojieba alias).

2. Experimental gate: bm25 is now feature-gated behind the experimental_bm25_index
   session var (default off), mirroring experimental_hnsw_index. ExperimentalFlag()
   returns Bm25IndexFlag; HandleCreateIndex re-checks it on the frontend path (the
   framework gate in pkg/sql/compile/util.go covers CREATE TABLE ... index). New
   system var in variables.go.

All bm25 BVTs set experimental_bm25_index=1 before CREATE INDEX; new bm25_gate case
asserts the gate (off -> rejected, on -> works) and ngram rejection is covered in the
runtime unit test. bm25 fulltext-dir 341/341, pessimistic 94/94. Benchmark connect()
enables the flag too.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
# Conflicts:
#	pkg/sql/colexec/external/parquet.go
# Conflicts:
#	pkg/sql/parsers/dialect/mysql/mysql_sql.go
# Conflicts:
#	pkg/sql/parsers/dialect/mysql/mysql_sql.go
Design for FULLTEXT2 — a new WAND-based positional fulltext index type
(CREATE FULLTEXT2 INDEX ...), a keyword sibling of FULLTEXT that leaves the
existing FULLTEXT index untouched as the baseline/oracle. Own plugin + WAND
engine (FST term dict backbone, positional postings, operator-tree evaluator),
supports gojieba + dictionary-free ngram, all fulltext modes/operators incl.
prefix, and both TF-IDF and BM25 scoring. Reuses the shared plugin framework
(CDC/cache/idxcron/routing). Phased P0-P4 with A/B golden parity vs FULLTEXT.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Per design review: keep the classic FULLTEXT index type and select the WAND
engine via a numeric VERSION index_option (default 1) instead of a new FULLTEXT2
keyword/algo. Migrate in place with ALTER ... REINDEX ... VERSION=2. The v2 engine
lives in a separate pkg/fulltext2/ package; the fulltext plugin is a thin
version-router that calls v1 verbatim, preserving it as the baseline/oracle.
No grammar keyword, no new index type, no coexistence ambiguity.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
First slice of the fulltext v2 engine (VERSION=2 selects the WAND engine; see
fulltext2.md). This adds only the DDL param + plumbing — no engine yet, classic
fulltext unchanged:

- Grammar: `VERSION equal_opt INTEGRAL` numeric index-option (non-reserved keyword,
  goyacc regen 0 conflicts), mirroring MAX_INDEX_CAPACITY; merged in index_option_list.
- tree.IndexOption.Version field + Format + emptiness guard.
- catalog.IndexAlgoParamVersion ("version") + SHOW CREATE rendering.
- fulltext plugin buildFullTextParams records version in algo_params only when >= 2,
  so classic (unset/1) indexes carry no version and are byte-for-byte unchanged.

Tests: parser roundtrip (CREATE FULLTEXT INDEX ... VERSION 2) + buildFullTextParams
version plumbing unit test. build/vet/test green.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Update fulltext2.md P0 phase: the VERSION index-option → algo_params plumbing
is landed (commit 13ff1e4); the version-router and pkg/fulltext2/ engine
skeleton remain.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Establish the maintenance-model fork for fulltext v2 (VERSION=2, the WAND
engine): v2 is CDC-only (always async), whereas classic v1 stays synchronous
(opt-in async via the async param).

Rather than fake the async param on a v2 index, or make the static catalog
SyncDescriptor param-aware (which forces "" at every param-less caller), add a
canonical async resolver in the plugin layer:

  indexplugin.IsAsync(algo, params) = AlwaysAsync(algo, params) || IndexParamAsync(params)
  indexplugin.AlwaysAsync(algo, params) = SyncDescriptor().AlwaysAsync (algo identity:
      hnsw/bm25/cagra/ivfpq) OR catalog.IndexAlgoParamVersionOf(params) >= 2 (fulltext v2)

catalog keeps only the pure-param primitives: new IndexAlgoParamVersionOf, and
IndexParamAsync (renamed from IsIndexAsync — distinct from IsAsync). A complete
AlwaysAsync needs the plugin registry, so it can't live in catalog.

Every fulltext async-decision site (compile CREATE, the fulltext DML maintenance
builders, CDC-validity, clone-skip) now routes through IsAsync, collapsing the
hand-written 'd.AlwaysAsync || IsIndexAsync' combines. Vector/bm25 build-timing
sites keep the raw-param call (IndexParamAsync) — using IsAsync there would force
always-async algos to never inline-build. Only fulltext behavior changes, and
only for v2 (IsAsync is identical to the param for v1).

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Start the WAND fulltext v2 engine package. This slice lays the segment
format's backbone (the sorted, dictionary-free term dictionary) and its
compact on-disk encoding; postings/docmap serialize+load and the build
sink follow.

- doc.go: package + segment-format doc (fulltext2.md §4) — the three-axis
  divergence from bm25, dictionary-free sorted term dict, scorer-agnostic
  raw block-max.
- segment.go: in-memory Segment (positional analogue of bm25's WandModel) —
  docmap (pks/docLen) + AvgDocLen + Recency; termPostings mirrors bm25's but
  adds per-doc positions and keeps maxTf/block-max raw so one segment serves
  both TF-IDF and BM25. Build-side term dict is a string-keyed map + sorted
  key list.
- termdict.go: the on-disk term dict as a vellum FST (term -> posting-offset
  uint64). Exact get + prefix iteration (word*) via a byte-successor range.
  vellum is byte-oriented and UTF-8 byte order == code-point order, so Go's
  string sort is already the FST's required insertion order and CJK/Unicode
  terms need no special handling.
- tests: term-dict lookup/prefix/boundary (segment_test), FST get + prefix +
  Chinese/CJK + prefixSuccessor (termdict_test).

Adds github.com/blevesearch/vellum v1.2.0 (MIT; battle-tested Go FST, used by
Bleve). Transitively bumps spf13/cobra 1.8.0->1.10.2 + pflag (vellum CLI deps);
verified pkg/vm/engine/tae/rpc (cobra user) still builds.

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

Complete the P0.3 segment format — Serialize/Deserialize round-trip on the
same multi-member tar shape bm25 uses, so the shared storage/CDC framing
carries both engines uniformly.

- Serialize: three members — docmap (pkType + N + ord->pk + ord->docLen),
  termdict (the vellum FST, term -> ordinal), postings (per sorted term: df,
  docIDs, tfs, and the per-doc POSITIONS list). Deterministic output.
- Deserialize: streams the archive into a LOADED segment (dict FST + loaded[]
  postings by ordinal; build-side terms map stays nil). LookupLoaded resolves
  term -> ordinal -> posting list. AvgDocLen and the raw score-UB fields
  (maxTf/minDocLen/block-max) are intentionally NOT stored — AvgDocLen is a
  cross-segment aggregate and block-max is derived by the scorer (P1).
- docmap + PK codec (int/varchar/uuid/temporal/decimal) are byte-for-byte
  bm25's — both engines store any-typed source PKs identically. Copied for now
  (a shared pk-codec package is the right home once a third user appears).
- tests: round-trip fidelity for int64/varchar/datetime PKs + positions + CJK
  term, determinism (checksum), empty segment.

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

The first end-to-end search over a fulltext2 segment: MATCH(col) AGAINST('q')
natural-language mode = exact contiguous phrase (MatrixOne NL semantics, §6).

- search.go (tokenizer-free core): SearchPhrase intersects the query terms'
  posting lists (bounded by the rarest term), verifies positional adjacency
  exactly (countPhrase; handles repeated query terms), scores the matched docs
  and returns top-k, score desc, ties by ascending ord. TfIdf (w·tf·idf²) and
  BM25 (idf²·bm25Factor, K1=1.5/B=0.75) with squared idf; idf uses the phrase
  document frequency. Correctness-first — no WAND block-max early termination
  yet (layers on later without changing results). Runs on build-side or loaded
  segments via a unified lookup.
- build.go: BuildSegmentFromDocs tokenizes docs (per-doc token positions →
  postings) into a queryable segment; SearchText tokenizes the query the same
  way. Minimal build path (seed for the CDC/sync sink) reusing pkg/monlp/
  tokenizer (SimpleTokenizer: dict-free, CJK-aware).
- search_test.go: runnable fulltext text cases — phrase doc-sets, non-contiguous
  rejected, TF-IDF vs BM25 ordering (length normalization), top-k, and identical
  results after serialize→deserialize.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Add BOOLEAN-mode execution over the positional segment (MySQL semantics):
+clause = MUST (AND), -clause = MUST-NOT, bare clause = SHOULD (OR); a clause is
a single TERM, a contiguous "PHRASE", or a word* PREFIX.

- boolean.go: BoolQuery + SearchBoolean evaluator. Each clause evaluates to a
  (doc -> score) map (present docs are keys even at score 0, so MUST/presence is
  exact); MUST intersects, MUST-NOT excludes, SHOULD unions and adds score.
  Prefix expands via the FST (loaded) or sorted keys (build-side) and takes the
  MAX impact over expanded terms (§6). ParseBoolean + scanBoolean are a
  self-contained top-level parser (+/- prefix, "quoted phrase", trailing *),
  tokenizing each clause with the index tokenizer for build/query consistency;
  the fulltext.ParsePattern front-end is translated into these clauses at
  plugin-integration time.
- search.go: extract matchPhrase / idfSquared / scoreTerm / avgDocLenOrMean from
  SearchPhrase so boolean phrase clauses and NL share one positional core.
- termdict.go: prefixTerms materializes a word* expansion off the FST iterator.
- tests: + - " " *, bare OR, required-absent, non-contiguous phrase rejected,
  and the loaded-segment (FST prefix) path; scanBoolean unit test.

The > < ~ weight operators and nested ( ) groups reuse this clause machinery and
land in a later slice.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Complete the boolean operator surface over the positional segment:
- > / < scale a SHOULD clause's impact ×1.1 / ×0.9 (boost / demote) without
  changing membership.
- ~ is a score-only penalty (×−1.0): a matched ~term LOWERS the score but does
  not by itself include the doc (noise-word). New 'adjust' bucket, applied to
  the candidate set after MUST/SHOULD.
- ( ) groups: a recursive clause whose score is the MAX of its children (§6) and
  whose presence is their union (OR); nestable and prefixable (+(a b), >(a b)).

Clause gains a weight + children; the scanner is now recursive (scanRange) over
+ - > < ~, quoted, trailing *, and ( ). evalClause handles the group case and
applies the weight; SearchBoolean threads the ~ADJUST maps.

tests: groups (AND-of-group, bare OR, nested), > boost flips rank order, ~
penalty sinks-but-keeps matches, all on build-side and loaded (FST) segments;
recursive scanner unit test.

The remaining P2 item is OR-WAND block-max early termination (perf; results
unchanged).

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Add classic term-level WAND (Broder 2003) for the pure OR-of-single-terms path
(§6 'boolean bare terms → disjunctive OR-WAND top-k'):

- wand.go: per-term posting cursors carry a max-impact upper bound (weight ·
  idf² · f(maxTf[, minDocLen])); a bounded top-k min-heap gives threshold θ; the
  pivot/skip loop never scores a document whose summed upper bounds can't reach
  θ. The heap tiebreaks (score asc, ord desc) so eviction drops the largest-ord
  doc among equals — making WAND's top-k byte-identical to the full scan's
  (score desc, ord asc) for EVERY k, ties included. Results unchanged; only work
  avoided. (Block-max WAND, using the per-block bounds, is a later tightening.)
- boolean.go: SearchBoolean routes a WAND-eligible query (disjunctiveTerms:
  should-only single terms, no MUST/MUST-NOT/~/phrase/prefix/group) to searchWAND;
  everything else uses the full evaluator (renamed searchBooleanFull).
- serialize.go: derive per-term maxTf/minDocLen at load (deriveTermStats) so
  WAND's bounds work on deserialized segments too.
- wand_test.go: exhaustive parity — WAND == full scan for all k, TfIdf + BM25,
  on the small corpus and a 60-doc synthetic corpus, build-side and loaded; plus
  a routing check.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
cpegeric and others added 2 commits August 10, 2026 11:54
BuildSegmentFromTokenized / BuildSegmentFromDocs allocated a fresh
`local := make(map[string][]int32)` per document to group a document's
positions by term before folding them into the global term->postings map.
On a 300k-doc corpus that is 300k map allocations plus a map assign per
token; a CPU profile put the two map lines (per-token local assign +
per-term global assign) at ~21% of the whole CREATE FULLTEXT2 build.

Since documents are processed in ascending ord and a document's tokens are
contiguous, the last buildEntry for a term is always the current document's
when the term repeats within it. addPosting() exploits that: it appends
straight into the global map, extending the open entry's positions in place
on a repeat. This removes the per-document map entirely (no per-token map
WRITE, no per-doc allocation) and preserves the invariants assembleTerms
relies on: global[w] stays ascending by ord, a term's within-doc repeats
collapse into one entry (tf = len(positions), df = len(entries)).

Result on the 300k build: mapassign_faststr 13.5s -> out of the hot set,
per-doc map allocations gone, total build CPU ~90.5s -> ~84s. The residual
per-token map READ (string hash to locate the postings list) is inherent to
inverted-index construction. addPosting inlines at both call sites.

Verified: full pkg/fulltext2 unit suite green; end-to-end on a 300k index
single-term, order-sensitive positional phrase (forward 492 vs reversed 0),
and boolean-OR queries all correct.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Conflict was limited to the generated parser pkg/sql/parsers/dialect/mysql/mysql_sql.go;
mysql_sql.y merged cleanly, so mysql_sql.go was regenerated from the merged grammar
(goyacc, no shift/reduce conflicts) rather than hand-resolved. Full `make build` passes.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
@cpegeric

Copy link
Copy Markdown
Contributor Author

fixed

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

Reviewed current head 98473186db6fa8823c22eb9269302c5a186625b6 with origin/main synced to ff25f27397ab7f1a2952eec98497bfb58419e2c2 (merge base 873b50b5c6ec0b7d9c08b87cc4d565bbcaeeaaef). All 31 checks are terminal with no failures. The DF, frame-length, varlena-capacity, checkpoint-INCLUDE, and cross-blob LWW findings from my previous review are fixed on this head.

[P1] Bound chronological CDC frame spooling instead of retaining one file per op run

pkg/fulltext2/tailbuild.go:114-135 seals on every delete/insert switch; seal and sealDeletes then create a distinct temp file and append it to frames (:165-170, :187-192). Nothing consumes those files until Finish returns the entire slice (:196-208), after which RunFulltext2 issues load SQL for every frame in one final transaction (pkg/iscp/fulltext2_consumer.go:84-107). The document/posting caps only bound the currently open run, not the number of sealed files or frame descriptors retained for the iteration.

This is reachable through the normal producer path. sinkTail orders equal-timestamp DELETE before INSERT (pkg/iscp/index_consumer.go:621-650), and sinkDelete / sinkInsert flush the writer whenever the operation changes (:680-721). Therefore a stream of single-row UPDATE transactions arrives as DELETE, INSERT, DELETE, INSERT, ..., producing two temp files and later two load operations per transaction. An iteration may cover a 30-minute change window (pkg/iscp/executor.go:503-505) and has no row or transaction bound: even 100 such updates per second retain roughly 360,000 files before persistence. This can exhaust local inodes/disk metadata, make directory cleanup and the final transaction pathological, and stall the fulltext2 watermark; retrying processes the same interval again.

Please preserve chronological recency with bounded spooling, for example a bounded number of append-only spool files plus frame offsets or incremental transactional persistence, rather than one filesystem object per op run. Add a regression with many alternating cross-blob delete/insert runs that proves both LWW correctness and a bounded spool/file count.

@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 current head 98473186db6fa8823c22eb9269302c5a186625b6. I understand the intended shape as an opt-in, independent fulltext2 engine: exact ranked top-K retrieval, optional position-free BM25, positional phrase/boolean search, INCLUDE-based prefilter/covering, and complete CREATE/CDC/MERGE/REBUILD/cache/restore integration.

The previous live-DF, corrupt frame-length allocation, wide PK/INCLUDE budget, checkpoint INCLUDE, and cross-blob LWW blockers are fixed on this head. I also checked the latest posting-assembly optimization: its document-order/contiguous-token preconditions hold at both build entry points, so it preserves TF/DF/position semantics while removing the per-document map.

Requesting changes for one remaining principle-level availability blocker: chronological CDC spooling still retains one filesystem object and descriptor per operation run until the whole ISCP iteration finishes, then persists every frame in one final transaction. This is normal UPDATE traffic, not an adversarial corner. My focused reproduction on the exact head fed 100 separate DELETE/UPSERT blob pairs for one PK and Finish retained 200 frame descriptors backed by 200 temp files; neither the document nor posting capacity bounds that count. The inline comment has the required closure.

I am not blocking on the documented eventual cross-CN cache freshness contract, direct catalog/plugin dispatch cleanup, or expected-output trailing spaces; those can remain follow-ups. All 31 current GitHub checks are terminal with no failures. Locally, the full fulltext2/plugin suites and affected ISCP/planner/table-function/checkpoint/cache/catalog suites pass; fulltext2+cache pass under -race; affected packages pass go vet; and the head merges cleanly with latest main@b0bbeeffea21ece3c288c9aa47d60658bbed6f5f.

Comment thread pkg/fulltext2/tailbuild.go Outdated
if err := os.WriteFile(path, framed, 0o600); err != nil {
return err
}
t.frames = append(t.frames, TailSegment{Path: path, FrameLen: len(framed)})

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[P1 availability] This append makes the number of retained spool objects depend on operation-run count, not on any configured capacity. The normal ISCP UPDATE path emits DELETE then INSERT/UPSERT blobs, and each switch seals the open run; on this head, 100 such single-row updates retained 200 TailSegment descriptors and 200 temp files for one PK. All remain until Finish, after which RunFulltext2 executes every load_file in one final transaction. A 30-minute iteration therefore has no file/inode/metadata or final-transaction bound and can stall the watermark; retry repeats the interval. Preserve chronological LWW with a bounded number of append-only spool files plus offsets, or persist incrementally with a safe watermark boundary, and add a many-alternating-run regression that asserts both LWW and a bounded object count.

The CDC TailBuilder spilled each sealed frame (one insert segment or one
delete frame per op run) to its OWN temp file via os.WriteFile. Under an
alternating DELETE,INSERT,... stream — a burst of single-row UPDATE
transactions, which sinkTail emits as D,I,D,I... one-row blobs — that is one
file per op run, up to hundreds of thousands of temp files retained for a
30-minute iteration, exhausting inodes/dir metadata.

Pack frames into a rolling spool file instead: writeFrame appends each framed
blob to a current os.File and rolls to a new file when it would exceed
DefaultTailSpoolRollBytes (128 MiB); TailSegment gains an Offset so a frame is
{Path, Offset, FrameLen}. So the file count is O(total bytes / 128 MiB), not
one-per-op-run. A frame is never split across files (a frame larger than the
cap gets its own file), so load_file always addresses a contiguous range.

The chronological seal is UNCHANGED — still one frame per op run, same order,
same per-frame chunk_id (chunkID += FrameChunkCount) — so last-writer-wins
recency and the persisted storage rows are byte-for-byte identical to the
file-per-frame layout; only temp-file storage changed. fileChunkInsertSqls
gains a baseOffset param (0 for a whole-file base segment, the frame Offset for
a packed tail frame) so load_file reads file://path?offset=Offset+chunkOff.
Finish closes the spool file so persist reads flushed bytes; Cleanup closes it
then RemoveAll's the per-iteration temp dir (unchanged single-shot cleanup).

Verified: full pkg/fulltext2 suite (incl. -race) and pkg/iscp green; new
TestCdcPackedSpoolBoundedFiles proves a bounded file count (2n op-runs pack
into one default spool file, and roll to a bounded few under a small cap) with
frames/chunks and LWW unchanged; TestFileChunkInsertSqls asserts the packed
non-zero-offset load_file ranges. Live 50K CDC-ingest bench: pure-CDC path
fully searchable with query parity to the sync build (p50 0.28 ms both).

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
@cpegeric

Copy link
Copy Markdown
Contributor Author

Deep-reviewed current head 98473186db6fa8823c22eb9269302c5a186625b6. I understand the intended shape as an opt-in, independent fulltext2 engine: exact ranked top-K retrieval, optional position-free BM25, positional phrase/boolean search, INCLUDE-based prefilter/covering, and complete CREATE/CDC/MERGE/REBUILD/cache/restore integration.

The previous live-DF, corrupt frame-length allocation, wide PK/INCLUDE budget, checkpoint INCLUDE, and cross-blob LWW blockers are fixed on this head. I also checked the latest posting-assembly optimization: its document-order/contiguous-token preconditions hold at both build entry points, so it preserves TF/DF/position semantics while removing the per-document map.

Requesting changes for one remaining principle-level availability blocker: chronological CDC spooling still retains one filesystem object and descriptor per operation run until the whole ISCP iteration finishes, then persists every frame in one final transaction. This is normal UPDATE traffic, not an adversarial corner. My focused reproduction on the exact head fed 100 separate DELETE/UPSERT blob pairs for one PK and Finish retained 200 frame descriptors backed by 200 temp files; neither the document nor posting capacity bounds that count. The inline comment has the required closure.

I am not blocking on the documented eventual cross-CN cache freshness contract, direct catalog/plugin dispatch cleanup, or expected-output trailing spaces; those can remain follow-ups. All 31 current GitHub checks are terminal with no failures. Locally, the full fulltext2/plugin suites and affected ISCP/planner/table-function/checkpoint/cache/catalog suites pass; fulltext2+cache pass under -race; affected packages pass go vet; and the head merges cleanly with latest main@b0bbeeffea21ece3c288c9aa47d60658bbed6f5f.

fixed

@aunjgr aunjgr left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Reviewed exact head f4a7343 with all 31 checks terminal and passing.

[P1] Bound the retained frame and final persistence work, not only the number of spool files.

Packing frames into rolling files fixes inode growth, but TailBuilder still appends one TailSegment descriptor per DELETE or INSERT operation run and Finish returns the entire unbounded slice. RunFulltext2 then calls TailFileInsertSqls and RunSql separately for every frame inside one final transaction. Normal UPDATE traffic still produces two frames per transaction; at 100 updates per second over the documented 30-minute iteration this is about 360,000 retained descriptors and 360,000 SQL executions before the watermark can advance. The new test explicitly preserves more than one frame per update and asserts only one backing file, so it does not close the descriptor, round-trip, transaction-size, or retry amplification part of the prior availability finding.

Stream or batch frame metadata and persistence with explicit bounds while preserving chronological recency and an idempotent watermark boundary, and assert bounded descriptors, SQL batches, and transaction work under many alternating cross-blob updates.

cpegeric and others added 2 commits August 11, 2026 10:53
…ound-trips)

The ISCP consumer persisted the CDC tail one frame at a time: per frame it
called TailFileInsertSqls + RunSql and advanced chunk_id by FrameChunkCount. A
tiny frame is one chunk = one INSERT with a single VALUES tuple, so an
alternating DELETE/INSERT burst of N op-run frames cost ~N RunSql round-trips
inside the one persist transaction (the reviewer's round-trip amplification).

Batch the load_file rows ACROSS frames: framesInsertSqls emits the per-chunk
tuples for a SEQUENCE of file ranges, flushing at maxInsertTuples rows per
INSERT across frame boundaries, with chunk_ids contiguous from startChunkId and
the next free chunk_id returned. fileChunkInsertSqls now delegates to it
(single range — base-segment path unchanged); new TailFramesInsertSqls batches
the whole tail; the consumer issues one batched persist instead of a per-frame
loop. So N frames cost ~N/maxInsertTuples statements, all in the same atomic
transaction, with chunk_id ordering (recency / last-writer-wins) byte-identical
to the per-frame persist.

maxInsertTuples raised 100 -> 500: each row's load_file materializes up to
MaxChunkSize (64 KiB) into the storage engine's async object writer, so 500
caps the per-statement slice at ~32 MiB — kept well below hnsw's 2000 because
fulltext2 CDC persist is a BACKGROUND op. This is a secondary throttle: the
dominant memory bound is the TOTAL data per iteration, not the batch size.

Verified: full pkg/fulltext2 suite (incl. -race) and pkg/iscp green;
TestTailFramesInsertSqls asserts cross-frame batching (contiguous chunk_ids,
right statement count and next-chunk-id) and is robust to the constant; medium
self-review clean; live 50k pure-CDC-UPDATE run (alternating frames) drained
correctly with LWW intact.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Only conflict was the generated parser pkg/sql/parsers/dialect/mysql/mysql_sql.go;
mysql_sql.y merged cleanly, so mysql_sql.go was regenerated from the merged grammar
(goyacc, no shift/reduce conflicts) rather than hand-resolved. Full `make build` passes.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
@cpegeric

Copy link
Copy Markdown
Contributor Author

Reviewed exact head f4a7343 with all 31 checks terminal and passing.

[P1] Bound the retained frame and final persistence work, not only the number of spool files.

Packing frames into rolling files fixes inode growth, but TailBuilder still appends one TailSegment descriptor per DELETE or INSERT operation run and Finish returns the entire unbounded slice. RunFulltext2 then calls TailFileInsertSqls and RunSql separately for every frame inside one final transaction. Normal UPDATE traffic still produces two frames per transaction; at 100 updates per second over the documented 30-minute iteration this is about 360,000 retained descriptors and 360,000 SQL executions before the watermark can advance. The new test explicitly preserves more than one frame per update and asserts only one backing file, so it does not close the descriptor, round-trip, transaction-size, or retry amplification part of the prior availability finding.

Stream or batch frame metadata and persistence with explicit bounds while preserving chronological recency and an idempotent watermark boundary, and assert bounded descriptors, SQL batches, and transaction work under many alternating cross-blob updates.

Addressed in this PR:

  • Spool file count (the original finding — inode/dir-metadata pressure): the CDC tail no longer spills one temp file per op-run
    frame. Frames are packed into rolling spool files (128 MiB roll), so file count is O(total_bytes / 128 MiB) instead of
    O(op-runs).
  • INSERT round-trip amplification: the per-frame persist is replaced by a batched persist — load_file rows are accumulated
    across frames into multi-row INSERT … VALUES at 500 rows/statement, so an N-frame flush issues ~N/500statements instead ofN, all within the **same single atomic transaction**. chunk_id assignment (hence recency / last-writer-wins) is byte-identical to the per-frame path. 500 is deliberately conservative (each row's load_fileis ≤MaxChunkSize = 64 KiB, so a statement hands the
    storage engine's async object writer ≤ ~32 MiB — well below hnsw's 2000, since CDC persist is a background op).

Out of scope for this PR (ISCP engine, not fulltext-specific):

The remaining dimensions — retained frame descriptors, total transaction size, and retry replay — are all bounded by the total
change volume a single ISCP iteration ingests. The executor currently caps an iteration by time (DefaultMaxChangeInterval, 30
min) but not by work, so a high write rate can still make one iteration large. Bounding an iteration by work belongs in the
ISCP iteration/executor layer and applies equally to every index consumer (hnsw / ivfflat / cuvs / cdc), not just fulltext2 —
fixing it here would be a cross-cutting engine change. Tracking it separately; intentionally left out of this fulltext2 PR.

# Conflicts:
#	pkg/sql/plan/function/function_id.go
#	pkg/sql/plan/function/function_id_test.go

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

Reviewed exact head 3e963850eb1afb70dbc6a192d1a5fce38e1ae609 against freshly fetched origin/main=a2f89230085a0f6650ec7bb7017ba6b8a97c9efc (PR merge-base 75d61d06bfaa2c3a7f86bab5ccf461df42acf20f). All 31 checks are terminal with no failures. I also read the previous iamlinjunhong review, all review threads, and the PR conversation. The author explicitly says the residual descriptor, transaction-size, and retry dimensions are intentionally left out of this PR.

[P1] Bound the number of chronological CDC frames and the atomic persist/load work, not only backing files and SQL statements

The two new commits reduce inode use and batch 500 load_file tuples per INSERT, but they leave the core work unbounded. pkg/fulltext2/tailbuild.go:221,243 still appends one TailSegment for every INSERT or DELETE op-run, and Finish returns the whole slice. The new regression at pkg/fulltext2/cdc_lww_test.go:183-186 explicitly asserts that frames are not collapsed and remain one per op-run. TailFramesInsertSqls then copies every descriptor into another full slice and materializes all statement strings before execution (pkg/fulltext2/storage.go:204-209), while RunFulltext2 waits for channel close and persists all of them in one transaction before advancing the watermark (pkg/iscp/fulltext2_consumer.go:84-118).

This is reached by ordinary UPDATE traffic: the producer orders DELETE before INSERT and flushes on each operation switch (pkg/iscp/index_consumer.go:621-721), and a catch-up iteration may span 30 minutes without a row/work cap (pkg/iscp/executor.go:498-505). At 100 updates/s this still creates about 360,000 retained descriptors and persistent frame rows. Batching reduces the calls to about 720 statements, but does not bound the transaction, retry replay, or persistent segment count. On the read path, LoadTailSegments deserializes every INSERT frame into a separate Segment (pkg/fulltext2/storage.go:583-598), and every index load/query subsequently walks that segment set. A sufficiently busy or backlogged index can therefore time out the one-hour persist, fail to advance its watermark, replay the same window, or become unavailable from tail-segment explosion. This is fulltext2-specific amplification even though the iteration work limit belongs naturally in ISCP.

Please close the invariant at either ownership boundary: cap an ISCP iteration by work, or incrementally/coalescingly persist bounded fulltext2 frame metadata with an idempotent watermark boundary. The regression should prove bounded retained descriptors, atomic transaction work, and loaded segment count under many alternating cross-blob updates while preserving LWW order.

No additional P0/P2/P3 finding changes the verdict; the previously noted direct-dispatch and expected-output whitespace follow-ups remain non-blocking.

@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 3e96385 against current main a2f8923, focusing on the two commits after my prior review (rolling spool files and cross-frame SQL batching) and rechecking the producer, persistence, watermark, retry, and load paths. All current CI checks are terminal and successful. The previous DF, malformed-frame allocation, wide-value budget, restore, covered-sort, and cross-blob LWW blockers remain fixed. One P1 availability invariant is still not closed.

P1 — bound the chronological CDC work unit, not only its file and SQL-statement representation.

TailBuilder still appends one TailSegment descriptor for every INSERT/DELETE operation run and Finish returns the complete slice. The new TestCdcPackedSpoolBoundedFiles deliberately asserts that those frames are not collapsed. TailFramesInsertSqls then copies all descriptors to another ranges slice and materializes all statement strings before RunFulltext2 executes every statement in one transaction and only then advances the watermark. On load, LoadTailSegments reconstructs every INSERT frame as a separate Segment and every query walks that accumulated set.

The normal producer flushes DELETE and INSERT separately across an UPDATE. A catch-up iteration can span 30 minutes without a row/event/work cap, so at 100 updates/s this remains about 360,000 descriptors and persistent frames. Packing them into a few files and grouping 500 tuples per INSERT reduces inode and round-trip constants, but the atomic transaction size, retry replay, persistent segment count, index-load cost, and query cost remain unbounded. A timeout before watermark advancement replays the same large interval.

Please establish a bounded ownership boundary: either cap each ISCP iteration by events/bytes/work and advance an idempotent watermark per bounded unit, or persist/coalesce chronological frames incrementally with an equivalent bounded commit contract. The regression needs to bound retained descriptors, one-transaction work, and loaded segment count under many alternating cross-blob updates while preserving LWW. This is the unresolved closure of my prior request, not a request for a more elaborate spool implementation.

# Conflicts:
#	pkg/sql/parsers/dialect/mysql/mysql_sql.go
#	pkg/sql/plan/function/function_id.go
#	pkg/sql/plan/function/function_id_test.go

@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-re-reviewed exact head d297fd4541972b88e70e21ef2178ef11e27044c6 against current main c3ba9c7df14388956cb38d78681c6c35b75c42b8. This update is only a merge of main; it makes no change to the fulltext2 CDC builder, persistence, watermark, or load paths. All 31 current checks are terminal with no failures.

[P1] Bound the chronological CDC work unit, not only its backing files and SQL statement count

The previous availability blocker remains unchanged. TailBuilder.seal and sealDeletes still append one TailSegment for every INSERT/DELETE op-run, and Finish returns the entire slice. TestCdcPackedSpoolBoundedFiles explicitly requires these frames not to collapse and asserts more than one frame per update. TailFramesInsertSqls then copies all descriptors into a second ranges slice and materializes all statement strings, while RunFulltext2 waits for channel close and persists every statement in one transaction before advancing the watermark. On read, LoadTailSegments deserializes every INSERT frame into a separate Segment, so every index load and query inherits the accumulated segment count.

This is the ordinary producer path: sinkTail orders DELETE before INSERT, and sinkDelete / sinkInsert flush whenever the op changes. The only iteration bound is a 30-minute timestamp window; there is no event, byte, frame, or transaction-work bound. At 100 updates/s, one interval can still retain and persist about 360,000 frame descriptors. Packing them into a few spool files and batching 500 tuples per INSERT reduces constants, but leaves the atomic transaction, retry replay after a pre-watermark failure, persistent segment count, load cost, and query cost unbounded.

Please cap an ISCP iteration by events/bytes/work with an idempotent watermark boundary, or incrementally/coalescingly persist chronological frames under an equivalent bounded commit contract. Add a regression that bounds retained descriptors, one-transaction work, and loaded segment count under many alternating cross-blob updates while preserving LWW.

Current-head verification passed: the full pkg/fulltext2 package under race; TestConcurrentSearchQuery at -race -count=100; TestCdcPackedSpoolBoundedFiles at -race -count=85; all fulltext2/plugin/indexplugin suites; and focused ISCP, planner, table-function, and checkpoint fulltext2 suites. The existing packed-spool test passes precisely while confirming the unbounded frame-count dimension.

@cpegeric

Copy link
Copy Markdown
Contributor Author
  1. PR-description note

Add near the bottom of the PR body:

Known / deferred

Bounding the ISCP sync iteration into a bounded, idempotently-committed work unit is an
engine-level availability property shared by all index consumers (hnsw/ivfflat/cagra/ivfpq/
bm25/fulltext/fulltext2), not specific to fulltext2. Tracked separately in #26973.
This PR's rolling spool + cross-frame INSERT batching are constant-factor improvements only.

Refs #26973

  1. Terser reply (alternative to the longer one)

Confirmed against main — you're right on every link: the interval is collected whole
(iteration.go:240), the 8 KB Full()/500-tuple batching are constant-factor only, the
watermark advances once atomically at channel close inside the same txn
(fulltext2_consumer.go:115), a failure before it replays the whole interval
(iteration.go:335), and load builds one Segment per insert frame with no coalescing.
So the unbounded txn size, replay, segment count, and query cost are all real.

But this is a shared ISCP-engine property, not a fulltext2 one — index_consumer.go:242,377
(hnsw/ivfflat/bm25/fulltext) and cuvs_writer.go:394 (cagra/ivfpq) advance the watermark the
same way off the same un-split interval. fulltext2's spool + batching are constant-factor wins
over the baseline every other index already ships. The right fix is an engine-level
bounded-iteration + idempotent per-unit watermark contract (your option 1), which belongs in
pkg/iscp, not this PR — fixing it in fulltext2 alone would leave the vector/bm25 paths
unbounded and inconsistent.

Filed as #26973 with the regression you specified (bounds on retained descriptors,
one-transaction work, and loaded segment count under alternating cross-blob updates, LWW
preserved). Not a dismissal — the invariant stays open, just moved to the layer where it's
fixed once for all indexes. Can take the engine change next if you're aligned on that split.

@aunjgr aunjgr left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Re-reviewed exact head d297fd4 against merge base c3ba9c7. This head is a merge from main and does not close the prior availability blocker.

[P1] Bound the chronological CDC work unit, not only each spool file and INSERT statement.

TailBuilder still appends one TailSegment descriptor per INSERT or DELETE op-run and Finish returns the complete slice. TailFramesInsertSqls copies all descriptors into another ranges slice and materializes every SQL statement, while RunFulltext2 waits for channel close and persists the entire set in one transaction before advancing the watermark. The ordinary update path alternates DELETE and INSERT runs. With only the 30-minute timestamp window and no event, byte, frame, or transaction-work cap, 100 updates per second can retain and persist roughly 360,000 frames. Rolling 128 MiB spool files and batching 500 tuples reduce constants but do not bound descriptors, total spool data, transaction and retry work, persistent segment count, or query load cost.

Please cap the ISCP iteration by events, bytes, or work with an idempotent watermark boundary, or incrementally or coalescingly persist frames under an equivalent bounded commit contract. Add a regression that bounds retained descriptors, one-transaction work, and loaded segment count under many alternating cross-blob updates while preserving last-writer-wins.

Conflicts in pkg/sql/plan/apply_indices_fulltext.go and build_ddl.go: main's
matrixorigin#26972 removes optimizer index-visibility gating (catalog.IsIndexOptimizerEligible,
setIndexDefsVisibility, and pkg/catalog/index_visibility.go are deleted), while
this branch had restructured the same lines for fulltext2. Resolved by keeping
the branch's fulltext2 storage-def selection and BuildSessionVars capture, and
taking main's removal of both visibility calls.

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

@aptend aptend left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Deep re-review of exact head 15aaeb44aa7e336e78e76f6f825eba5ac9579bb5 against merge base ca845354162ca2b01feb391d7b5b6e029c609420. The commits after previously reviewed head d297fd4541972b88e70e21ef2178ef11e27044c6 are only a merge of current main; there is no change in pkg/fulltext2, pkg/iscp, pkg/indexplugin, the fulltext2 plugin, or its table functions. All current checks are terminal and green.

[P1] Bound the chronological CDC work unit; the prior availability blocker is unchanged.

TailBuilder.seal and sealDeletes still append one TailSegment descriptor for every INSERT/DELETE operation run (pkg/fulltext2/tailbuild.go:221,243), and Finish returns the complete slice (:253-266). TestCdcPackedSpoolBoundedFiles explicitly asserts that these frames remain uncollapsed (pkg/fulltext2/cdc_lww_test.go:183-186). TailFramesInsertSqls copies every descriptor into another full ranges slice and materializes all SQL statements (pkg/fulltext2/storage.go:204-209); RunFulltext2 waits for channel close, executes all of those statements in one transaction, and advances the watermark only at the end (pkg/iscp/fulltext2_consumer.go:82-118). LoadTailSegments then deserializes every INSERT frame into a separate searchable segment (pkg/fulltext2/storage.go:583-606).

Ordinary UPDATE traffic alternates DELETE and INSERT runs, while the iteration is capped only by a 30-minute timestamp window (pkg/iscp/executor.go:498-505) and has no event/byte/frame/transaction-work bound. Packing frames into rolling files and grouping 500 tuples per statement reduces inode and round-trip constants, but does not bound retained descriptors, total spool bytes, the atomic transaction and retry replay, persistent frame/segment count, index-load work, or per-query segment traversal. A busy or backlogged index can still time out before watermark advancement and replay the same unbounded interval.

Please cap each ISCP iteration by events/bytes/work with an idempotent watermark boundary, or incrementally/coalescingly persist chronological frames under an equivalent bounded commit contract. The regression should prove bounded retained descriptors, one-transaction work, and loaded segment count under many alternating cross-blob updates while preserving last-writer-wins ordering.

@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-re-reviewed exact head 15aaeb44aa7e336e78e76f6f825eba5ac9579bb5.

[P1] The chronological CDC work-unit bound is still unresolved.

This head is exactly a merge of prior reviewed head d297fd4541972b88e70e21ef2178ef11e27044c6 with main. The blocker-bearing paths are byte-identical between those heads:

  • pkg/fulltext2/tailbuild.go
  • pkg/iscp/fulltext2_sqlwriter.go
  • pkg/iscp/fulltext2_consumer.go
  • pkg/fulltext2/storage.go

Therefore ordinary alternating DELETE/UPSERT traffic can still create one retained TailSegment descriptor per operation run for an entire timestamp iteration. Finish returns the full slice, SQL generation copies/materializes the complete work set, one transaction persists it before watermark advancement, and load/query reconstruct and walk the resulting segment count. Spool-file packing and 500-tuple SQL batching bound constants, not descriptors, atomic transaction work, retry replay, persistent segments, or query work. The 30-minute interval remains the only outer bound.

Please cap each ISCP iteration by event/byte/work with an idempotent watermark boundary, or coalesce/persist chronological frames under an equivalent bounded commit contract. The regression must bound retained descriptors, one-transaction work, and loaded segment count under many alternating cross-blob updates while preserving last-write-wins.

All current CI checks are green, but this exact head makes no fulltext2 change relative to the previously blocked head, so REQUEST_CHANGES remains.

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.

9 participants