Repository navigation
feat(sql): add read-only index statistics - #32698
Conversation
Qodo reviews are paused for this user.Troubleshooting steps vary by plan Learn more → On a Teams plan? Using GitHub Enterprise Server, GitLab Self-Managed, or Bitbucket Data Center? |
|
Queue requested — the merge queue status continues in this comment ↓. |
ff48976 to
b93130e
Compare
XuPeng-SH
left a comment
There was a problem hiding this comment.
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.
|
mo-bot review · Commit: Review completed. Read the assessment. |
XuPeng-SH
left a comment
There was a problem hiding this comment.
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 reportcaught_up: trueandlag_seconds: 0for 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 observedasync.caught_up=trueandanalysis.status=index_not_caught_upin 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
left a comment
There was a problem hiding this comment.
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.
|
mo-bot review · Commit: New discussion was assessed; the previous review remains unchanged. |
cpegeric
left a comment
There was a problem hiding this comment.
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
- Base-less fulltext2 generations read through a private per-call key, so the
@gen-0-<tail>ABA is gone. - The
training_sample_insufficientadvice fires only when a rebuild can reach30·lists(TrainingSampleLimit). validationPrivilegeCarrier,isUDFArgumentAuthorizationSourceand the privilege-tip extraction shareIsSourceResolvingTableFunction.- The prepared dependency records the snapshot (
prepareSchemaRefWithSnapshot). - The diagnostic loader takes the generation verified in the same transaction and skips the second lookup.
- Drift looks up sampled keys at the build snapshot and checks the source table id there.
- The historical check is the cheap
SourceVisibleAtSnapshot, failures are logged, and the forced build's count is reused (CountFromBuildTxn). - 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
readIndexStatsMaintenancesets 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
buildTSand stale-check capture. Stats never read them, and@gen/@statsentries never serve searches.
Validation at 9d0861fd8a (arm64)
go veton 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 fromTestSampledDrift.- The embedded
TestMoIndexStatsSQL 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.
…ble training limits
cpegeric
left a comment
There was a problem hiding this comment.
Re-reviewed b1703e358a against main (ca5325ce68). Approving.
- The
TestSampledDriftfailure 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/x86job isTestSendCommitDeadlineReturnsTxnUnknowninpkg/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.
|
mo-bot review · Commit: Review completed. Read the assessment. |
XuPeng-SH
left a comment
There was a problem hiding this comment.
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.
🚫 Left the queue · pull request dequeued39 min in the queue, with no time running CI. So far
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.
To get back in the queue
Merge conditions not met when it left the queue
Tick the box to put this pull request back in the merge queue (same as
2 merge conditions met
Times in UTC · dashboard · how the merge queue works |
What type of PR is this?
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 STATUSreports a retained canceled job ascanceled. The object-count interface documents the current local, non-partitioned scope of diagnostics.Validation
Tested
b1703e358aon upstreammainatca5325ce68(Linux amd64).1e-12. Counts, sampled vector copies and the original centroid still require exact equality.6.31025621614648e-34on the previous assertion. The corrected assertion passed 20 consecutive runs under the same overlay.go test -race -count=20 -run '^TestSampledDrift$' ./pkg/vectorindex/ivfflat/diagnosticpassed on the committed code.make thirdpartiesandGOMAXPROCS=4 make static-check-changed STATIC_CHECK_BASE=origin/mainpassed. Both pinned analyzers ran on the full graph with zero reported issues.Tested
9d0861fd8aon upstreammainat07d7baa32a.go test -count=1 ./pkg/indexstats/...and the embedded SQLTestMoIndexStatssuite passed.make thirdpartiesandGOMAXPROCS=4 make static-check-changed STATIC_CHECK_BASE=origin/mainpassed. Incremental selection expanded to the full graph with zero reported findings.Earlier validation
Tested
abc1b2502con upstreammainate17d554153.make thirdpartiespassed.GOMAXPROCS=4 make static-check-changed STATIC_CHECK_BASE=origin/mainselected the full graph. Both pinned analyzers passed with zero findings.Earlier performance validation on
091fc4c637