Skip to content

feat(sql): add read-only index statistics - #32698

Merged
XuPeng-SH merged 17 commits into
matrixorigin:mainfrom
aptend:feat/index-stats-readonly
Nov 26, 2026
Merged

XuPeng-SH merged 17 commits into
matrixorigin:mainfrom
aptend:feat/index-stats-readonly

Conversation

@aptend

@aptend aptend commented Nov 13, 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:

Related to #30346.

What this PR does / why we need it:

Add mo_index_stats(database, table, index [, options]) for primary, unique, ordinary secondary, IVF_FLAT and fulltext v1/v2 indexes. The four-column result contains type-specific JSON metrics and separate IVF centroid rows. The caller needs SELECT on the resolved source. Temporary, partitioned and subscription tables are unsupported.

Report exact entry counts and logical key cardinality, normalized IVF center mismatch and bucket imbalance, fulltext vocabulary/document-frequency aggregates and available async progress. Index plugins configure diagnostics, execute them and produce their result rows. IVF geometry streams index entries and uses stored bounds to reconstruct quantized vectors. Fulltext2 statistics reuse the snapshot-matching cache generation under the existing memory budget.

IVF builds record an optional baseline for their generation. The summary uses it to report source growth, training sample adequacy and sampled drift. Fulltext2 reports tail size and estimated dead fraction and uses the scheduler's rules for MERGE and REBUILD suggestions. The statistics call reports advice without running maintenance.

Existing three-argument calls return normal statistics. For IVF, a fourth argument of '{}' enables the deep check with default options. It scans the source to measure how many exact top-10 neighbors fall in the probed buckets and can optionally compare sampled retraining gains. Async deep checks require a watermark covering the same source read view. See the design and option defaults.

Review follow-up

  • Async summaries and deep analysis use the same snapshot of the persisted job watermark. Coverage and lag remain unknown when job history is unavailable.

  • IVF uses the same training sample limit for its build and its REINDEX advice. Drift looks up sampled index keys directly in the build snapshot, including keys with a pending CDC deletion. Baseline publication checks local source writes and creation, logs lookup failures, and reuses the count already taken by a forced build.

  • Fulltext2 reuses verified base-bearing generations. When compaction leaves no base, tail chunk numbers can repeat. Those reads use a private, memory-budgeted entry that is released after the call. Diagnostics capture the generation once before admitting it.

  • Source SELECT follows the function through planner rewrites, and prepared dependencies retain the resolved snapshot. Index-specific errors are raised at execution after source authorization. Database and table literals follow ordinary identifier folding in lower_case_table_names=1.

  • SHOW INDEX STATUS reports a retained canceled job as canceled. The object-count interface documents the current local, non-partitioned scope of diagnostics.

Validation

Tested b1703e358a on upstream main at ca5325ce68 (Linux amd64).

  • Compared computed diagnostic ratios with an absolute tolerance of 1e-12. Counts, sampled vector copies and the original centroid still require exact equality.
  • An isolated Go test overlay forced fused multiply-add in the bucket mean update and reproduced the reported 6.31025621614648e-34 on the previous assertion. The corrected assertion passed 20 consecutive runs under the same overlay.
  • The complete IVF diagnostic package passed. go test -race -count=20 -run '^TestSampledDrift$' ./pkg/vectorindex/ivfflat/diagnostic passed on the committed code.
  • make thirdparties and GOMAXPROCS=4 make static-check-changed STATIC_CHECK_BASE=origin/main passed. Both pinned analyzers ran on the full graph with zero reported issues.

Tested 9d0861fd8a on upstream main at 07d7baa32a.

  • A named-snapshot SQL regression reproduced the false caught-up result on the previous implementation. After the fix, the historical summary retains its original watermark and lag after the live index catches up. The deep check agrees with each view.
  • go test -count=1 ./pkg/indexstats/... and the embedded SQL TestMoIndexStats suite passed.
  • make thirdparties and GOMAXPROCS=4 make static-check-changed STATIC_CHECK_BASE=origin/main passed. Incremental selection expanded to the full graph with zero reported findings.

Earlier validation

Tested abc1b2502c on upstream main at e17d554153.

  • make thirdparties passed. GOMAXPROCS=4 make static-check-changed STATIC_CHECK_BASE=origin/main selected the full graph. Both pinned analyzers passed with zero findings.
  • Targeted Go tests passed for the planner, frontend, table functions, index statistics, Fulltext2, IVF compilation and diagnostics, and disttae. Embedded SQL tests passed for permission-error ordering, a pending async delete, and two compact-to-empty Fulltext2 cycles with distinct document and term counts.
  • Regression tests also covered generation-capture retry, cache reuse across transactions, inherited snapshot dependencies and the IVF sample cap at 500 lists and 100,000 rows.

Earlier performance validation on 091fc4c637

  • On a local table of 1,000,000 vectors, a 2,560-key bucket lookup read 2,560 source rows versus 17,697,600 before. The historical lookup read 5,120 source rows versus 18,101,568. Both returned identical key-level results before and after.
  • On 200,000 documents with a 90 MiB cache, two rounds of eight concurrent Fulltext2 diagnostics went from six admission failures to zero. After inserting one more document, the historical snapshot still returned 200,000 documents and the current view returned 200,001.

@qodo-code-review

Copy link
Copy Markdown

Qodo reviews are paused for this user.

Troubleshooting steps vary by plan Learn more →

On a Teams plan?
Reviews resume once this user has a paid seat and their Git account is linked in Qodo.
Link Git account →

Using GitHub Enterprise Server, GitLab Self-Managed, or Bitbucket Data Center?
These require an Enterprise plan - Contact us
Contact us →

@mergify

mergify Bot commented Nov 13, 2026 •

Copy link
Copy Markdown
Contributor

Queue requested — the merge queue status continues in this comment ↓.

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

mo-bot review · mo-bot-local · review

Commit: 5285057be7a0156b77ab8711e906cdb31374b683

Assessment: request_changes

The same-head follow-up changes the prior approval. Fulltext2 can return stale statistics after an empty merge or keep failing after a transient load error. The IVF and planner findings affect cohort accuracy, rebuild advice, SELECT enforcement, catalog validation, and build cost. The existing plugin, cache admission, and typed-key lookup mechanisms remain useful foundations for the fixes.

Model: gpt-6.2-sol / xhigh

Session: 01a1ee80-0d82-7030-a965-b51f496c3054 · slot 2 · generation 1

  • P2 pkg/fulltext2/index_stats.go:193: Cache statistics for a tail-only Fulltext2 index, let CDC apply deletions of all its documents, merge the empty index, and then append new documents.
    Impact: A later call can reuse the first corpus's cached generation and return stale document and term counts.
    Evidence: CompactSegments deletes the old bases and tail and writes no replacement base when no live documents remain. NextTailChunkIdSql then restarts chunk allocation at 1, so the base timestamp and maximum tail chunk can repeat. MERGE removes only the local bare cache key. Use a generation identity that remains distinct across this reset, including on other CNs, while preserving reuse across snapshots of the same generation.

  • P2 pkg/fulltext2/search_cache.go:219: A diagnostic cache miss loads a nonempty index, then the final generation query fails transiently.
    Impact: Later reads of that generation can keep returning a generation mismatch after the original error clears. Reads can renew the entry's TTL.
    Evidence: Load returns success with genValid false. ReadStats rejects the resident entry, cache.use retires only an empty generation on this error path, and checkStale skips generation keys. Require successful generation capture before publishing a diagnostic entry, or retire the exact failed entry so a later read can reload.

  • P2 pkg/sql/plan/window_binder.go:921: A scalar simplification or unused SQL UDF argument removes a bound mo_index_stats scan.
    Impact: The rewritten statement can succeed without the documented SELECT privilege on the diagnostic source. The eliminated scan returns no diagnostic rows.
    Evidence: The frontend recognizes mo_index_stats at authenticate.go:7521. The planner's privilege carrier and UDF source collector at base_binder.go:5846 recognize only table_changes among function scans. Preserve the diagnostic source and function discriminator through both rewrites and cover the privilege check on the final plan.

  • P2 pkg/indexstats/sqlreader/health.go:172: An async IVF entry is sampled after its source row has been deleted but before CDC applies the deletion to the index.
    Impact: A key that existed at build time is classified as new, skewing cohort counts, residual ratios, and hot-bucket metrics.
    Evidence: The historical join takes its sampled keys from a filter on the current source at line 219. A deleted key cannot reach the historical side, and diagnostic.Drift treats a missing membership result as new. Apply the typed key filter to the historical source or mark the cohort unavailable when current membership cannot establish it.

  • P2 pkg/vectorindex/ivfflat/diagnostic/health.go:86: Request health statistics for 100,000 indexed vectors with 500 lists and a configured 10 percent training rate.
    Impact: The function recommends a potentially expensive REINDEX that cannot reach its stated training target with those settings. The same advice can recur after every successful rebuild.
    Evidence: The advice compares total rows against 15,000. The sampling policy at ivf_create.go:358–384 caps the build at 10,000 samples in this case, and 500 lists is within the documented size band. Use the build's effective sampling policy to check whether the action can reach the target, and expose the shortfall without an action when it cannot.

  • P3 pkg/sql/plan/index_stats.go:119: Prepare a query through a historical view whose body calls mo_index_stats.
    Impact: The dependency is validated as a current table and can cause needless reprepare after current catalog changes. Ordinary cached queries can also rebuild because the cache validator tries to resolve the function's synthetic schema as a table.
    Evidence: The source is resolved with ctx.snapshot and the scan carries that snapshot, but prepareSchemaRef clears it. The frontend skips current-schema checks for historical dependencies at computation_wrapper.go:2236. Ordinary cache validation at mysql_cmd_executor.go:4556 special-cases table_changes alone. Record the snapshot-bound source dependency and use it for both reuse paths.

  • P3 pkg/sql/colexec/table_function/ivf_build_info.go:47: Build an IVF index on a source with persisted objects, including a forced async rebuild.
    Impact: The build incurs extra object and commit-timestamp reads solely to set an optional cohort flag. A transient read failure disables historical cohorts for that generation. The forced async path also repeats the source count in the same transaction.
    Evidence: SourceCommitTS with an empty threshold computes the exact maximum, including appendable and tombstone reads, and the caller discards the timestamp. Use the engine's workspace-write check for the committed-view predicate. Reuse the compiler's count when it came from the training transaction, and retain the fresh count when ISCP starts training in a later transaction.

Validation:

  • Matched the clean head, merge base, frozen patch, and pinned policy. The whitespace check passed and all 19 discussion keys were accounted for. See receipts 1795428764470524260-3 and 1795428921838683026-3.

  • Private temporary filesystem and loopback preflight passed. See receipt 1795428743403774438-3.

  • Matched the prior same-head receipts 1795424644882427068-2 and 1795424693578351143-2 to retained logs. All 17 selected packages recorded passing tests, including embedded SQL for key, Fulltext, Fulltext2, IVF, and async IVF diagnostics.

Limitations:

  • The follow-up findings follow from source traces. The retained tests cover the earlier review paths, and the newly identified triggers were not replayed end to end.

  • IVF build overhead was established from the I/O path. Its wall-clock impact at scale was not measured.

@XuPeng-SH

XuPeng-SH commented Nov 23, 2026 •

Copy link
Copy Markdown
Contributor

mo-bot review · mo-bot-local · done

Commit: abc1b2502c550250ce8459e1a6118a2d5100bf31

Review completed. Read the assessment.

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

mo-bot review · mo-bot-local · review

Commit: abc1b2502c550250ce8459e1a6118a2d5100bf31

Assessment: request_changes

The revision addresses the prior cache, authorization, and IVF build findings while reusing the existing plugin and maintenance owners. The async summary can still report that an index has caught up when the snapshot being measured shows it lagging.

Model: gpt-6.2-sol / xhigh

Session: 01a1f0a0-5126-78f3-9ab8-ef4e87f2f119 · slot 0 · generation 3

  • P2 pkg/indexstats/sqlreader/metadata.go:139: Query index statistics through a snapshot taken while the async index lagged, after ISCP has caught up in the current view.
    Impact: The summary can report caught_up: true and lag_seconds: 0 for index contents that still lag the source in the reported snapshot. Operators can mistake stale results for a fully maintained index.
    Evidence: The summary reads the watermark in a fresh system transaction. Deep analysis reads it in the same view as the index. The embedded SQL probe observed async.caught_up=true and analysis.status=index_not_caught_up in the same result after the current-view control passed. See snapshot-coverage-repeat.jsonl and checks/1795437053692073291-2.json. Use same-view progress for coverage and lag, and return unknown when that progress is unavailable. The latest job state can still be reported separately.

Validation:

  • Verified the frozen patch, pinned policy, native inputs, isolation preflight, and all 21 discussion keys. Receipt and log mappings are in review-validation.md.

  • Ten focused packages passed, with 46 top-level tests including embedded SQL for key indexes, classic Fulltext, Fulltext2, IVF, and async IVF. See focused-tests.jsonl and checks/1795436956278347482-2.json.

  • Frozen CI recorded passing shared build, Ubuntu unit and Coverage lanes, static analysis, and both enabled multi-CN BVT lanes.

Limitations:

  • Local SQL checks used the embedded fixture. The exact diagnostic cases selected by multi-CN CI are unverified.

  • Upgrade CI was skipped. The large-data performance measurements were author-reported on an earlier revision.

@gouhongshen gouhongshen left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Codex automated review

I reviewed commit abc1b25 (79 files, +7494/−160) against origin/main, after first loading all nine PR reviews and eleven issue comments. The change adds the read-only mo_index_stats table function with plugin-owned diagnostics for key, IVF_FLAT, classic fulltext and fulltext2 indexes, health/deep-analysis extensions, an engine VisibleObjectCount capability, a shared ISCP metadata package, and SELECT-privilege enforcement on the resolved source. I traced every previously raised finding to its fix in the current head: base-less fulltext2 generations now use exclusive non-cached loads; generation capture is verified before cache publication; the three privilege-carrier sites, checkModify and publication scoping all recognize mo_index_stats through one shared predicate; drift membership filters the build snapshot so pending CDC deletions are classified correctly; the training-sample REINDEX advice now checks the same shared attainable TrainingSampleLimit used by builds; prepared dependencies record the snapshot; tail frames are counted from frame metadata with a payload fallback only for legacy tails; tail bytes, primary-key column sizing, JSON null rejection, SourceVisibleAtSnapshot, forced-build count reuse and identifier case folding are all implemented as requested. One earlier reviewer (mo-bot) still holds a request-changes at this exact head for a single unaddressed P2: the async summary in pkg/indexstats/sqlreader/metadata.go observes mo_iscp_log in a fresh system transaction while the rest of the row is snapshot-scoped, so a lagging snapshot can be reported as caught up. That finding is raised by another reviewer and unaddressed, so per the non-duplication rule it stays out of my findings and I only record its status here; my own trace confirms the same evidence and that the deep-analysis endpoint already uses same-view progress. Beyond that, my independent pass over authorization ordering, planner rewrites, cache concurrency and eviction protection, streaming resource cleanup, cohort and coverage math, probe-limit bounds and unhappy paths found no new blocking or non-blocking defect; the risky-looking costs (exact SourceCommitTS bar per async call, exclusive diagnostic loads for base-less generations, one source COUNT per IVF health read) are explicit documented design decisions with tests. Verification limitation: only pkg/indexstats is independently runnable in this checkout with Go 1.27.1 and passed (TestAnalyzeOptions PASS); the other touched packages (fulltext2, vectorindex/cache, ivfflat/diagnostic, iscp/metadata, sql/colexec, sqlintegration) cannot build because the checkout's third-parties cgo headers (roaring.h, xxhash.h, usearch.h, jemalloc.h) are absent and building them via make thirdparties is out of scope for this review, so those suites' passes remain author- and CI-reported rather than locally re-verified.

@XuPeng-SH

XuPeng-SH commented Nov 23, 2026 •

Copy link
Copy Markdown
Contributor

mo-bot review · mo-bot-local · done

Commit: abc1b2502c550250ce8459e1a6118a2d5100bf31

New discussion was assessed; the previous review remains unchanged.

@cpegeric cpegeric 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 9d0861fd8a against main (07d7baa32a). Requesting changes for one failing unit test; everything else from my previous review is resolved.

Please fix

TestSampledDrift fails on arm64
pkg/vectorindex/ivfflat/diagnostic/health_test.go:123

It fails 20/20 on arm64 (macOS), with and without -race:

--- FAIL: TestSampledDrift (0.00s)
    health_test.go:123:
        Error:      Should be zero, but was 6.31025621614648e-34

require.Zero(t, g.Mismatch) compares a floating-point result exactly. On arm64 the fused multiply-add leaves a residue of about 1e-34; amd64 CI passes. Suggest require.InDelta(t, 0, g.Mismatch, 1e-12), and check the other exact float assertions in this file the same way.

Resolved since 5285057be7

  1. Base-less fulltext2 generations read through a private per-call key, so the @gen-0-<tail> ABA is gone.
  2. The training_sample_insufficient advice fires only when a rebuild can reach 30·lists (TrainingSampleLimit).
  3. validationPrivilegeCarrier, isUDFArgumentAuthorizationSource and the privilege-tip extraction share IsSourceResolvingTableFunction.
  4. The prepared dependency records the snapshot (prepareSchemaRefWithSnapshot).
  5. The diagnostic loader takes the generation verified in the same transaction and skips the second lookup.
  6. Drift looks up sampled keys at the build snapshot and checks the source table id there.
  7. The historical check is the cheap SourceVisibleAtSnapshot, failures are logged, and the forced build's count is reused (CountFromBuildTxn).
  8. Index-specific validation errors are carried in the plan and raised at execution, after authorization.

The async-coverage finding is also resolved: the summary and the deep check read the job watermark in the diagnostic transaction's snapshot, and coverage and lag stay unknown without job history. lower_case_table_names=1 now folds the database and table literals.

Checked

  • The system-identity copy in readIndexStatsMaintenance sets overrides on the copy only. The caller's process is unchanged.
  • The ConvertGoError(...).(*moerr.Error) assertion is safe, because every branch returns *moerr.Error.
  • The diagnostic loader skips the buildTS and stale-check capture. Stats never read them, and @gen/@stats entries never serve searches.

Validation at 9d0861fd8a (arm64)

  • go vet on the indexstats, fulltext2 and IVF packages is clean.
  • pkg/indexstats/..., the IVF, fulltext and fulltext2 plugin packages, and the focused plan, table-function, frontend and fulltext2 tests pass, apart from TestSampledDrift.
  • The embedded TestMoIndexStats SQL suite passes.

Keep source SELECT checks for diagnostics inside same-target DML. Count async IVF training rows in the worker transaction, and use frame metadata to distinguish logical Fulltext2 frames from chunks. Cover mixed legacy tails and committed source changes in SQL tests.
Count snapshot-visible objects directly, read complete Fulltext2 tail sizes from frame metadata, and reject explicit null analysis options. Preserve the exact same-snapshot byte count for legacy tails.

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

Superseded by my approval below. Role row/column rules (add rule) are intentionally not applied to mo_index_stats, the same as SHOW INDEX. No change is needed.

@cpegeric cpegeric 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 b1703e358a against main (ca5325ce68). Approving.

  • The TestSampledDrift failure from my previous review is fixed. The IVF diagnostic package passes on arm64, also with -race -count=20.
  • The rebase left the other commits unchanged. The PR's packages pass locally (arm64, TZ=UTC).
  • The failing UT Test on Ubuntu/x86 job is TestSendCommitDeadlineReturnsTxnUnknown in pkg/txn/rpc. This PR doesn't touch that package and the test uses a 100 ms deadline. Please rerun the job.

Decision (2026-11-25): mo_index_stats doesn't apply role row/column rules (alter role … add rule), the same as SHOW INDEX. No change is needed.

@XuPeng-SH

XuPeng-SH commented Nov 26, 2026 •

Copy link
Copy Markdown
Contributor

mo-bot review · mo-bot-local · done

Commit: ce482830a3df8738513be91a9ae42ced47e13ca6

Review completed. Read the assessment.

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

mo-bot review · mo-bot-local · review

Commit: ce482830a3df8738513be91a9ae42ced47e13ca6

Assessment: approve

The feature reuses the existing index plugins, cache and maintenance policies. Its optional version-bound IVF baseline and bounded analysis support the requested health measurements. The earlier concerns about authorization, snapshot-scoped progress and cache generations are addressed, and the index owner accepted the documented row and column rule behavior. No actionable findings remain.

Model: gpt-6.1-terra / max

Session: 01a216cc-0c27-73a3-a600-f29a1a26e437 · slot 1 · generation 19

Validation:

  • Private /tmp and loopback preflight passed; receipt checks/1795680411829390852-2.json.

  • Focused diagnostic, planner, authorization and plugin tests passed across 10 packages; receipt checks/1795681027387620749-2.json and focused-tests-retry.log.

  • Four single-CN public SQL integration tests passed for key, IVF, async and fulltext statistics; receipt checks/1795681086705326624-2.json and sqlintegration.log.

  • The cache read-versus-eviction lifetime test passed 20 times under the race detector; receipt checks/1795681221889917241-2.json and cache-race.log.

  • Diff and plugin-boundary checks passed. All 28 discussion keys are accounted for, and evidence-reconciliation.log matches the claimed checks to zero-exit receipts for the assigned head.

Limitations:

  • No predecessor-binary upgrade, multi-CN or performance benchmark was run. The single-CN SQL tests covered missing and stale IVF build metadata.

  • The first focused test invocation used an incorrectly quoted linker argument and was interrupted after link failures. It is not counted as product validation; the corrected run passed.

@mergify

mergify Bot commented Nov 26, 2026 •

Copy link
Copy Markdown
Contributor

🚫 Left the queue · pull request dequeued

39 min in the queue, with no time running CI.

So far

  • ✅ Entered the queue Thu 26 Nov, 08:24 · rule main · triggered by rule Automatic queue on approval for main
  • ⏹️ Testing stopped · in place
  • 🚫 Left the queue 09:03 · 386746e

Reason

Pull request #32698 has been dequeued

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

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

To get back in the queue

  • Push a change if one is needed: the pull request is queued again once its queue conditions match.
  • If no change is needed, tick the box below to queue it again as it is.

Merge conditions not met when it left the queue

  • any of · required by GitHub branch protection:
    • check-neutral = CI Required
    • check-skipped = CI Required
    • check-success = CI Required

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

  • Requeue this pull request
2 merge conditions met
  • #review-threads-unresolved = 0 · required by GitHub branch protection
  • github-review-approved · required by GitHub branch protection

Times in UTC · dashboard · how the merge queue works

@XuPeng-SH XuPeng-SH mentioned this pull request Nov 26, 2026
1 task done

This branch was successfully deployed

No deployments
ci — 386746e7 Deployed Nov 26, 2026 by mergify[bot]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

dequeued kind/feature size/XL Denotes a PR that changes [1000, 1999] lines

Projects

None yet

Development

Successfully merging this pull request may close these issues.

6 participants