Repository navigation
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? |
84eab93 to
a21c467
Compare
a21c467 to
be88aa5
Compare
XuPeng-SH
left a comment
There was a problem hiding this comment.
结论:当前不建议合入,存在两个阻断问题(由于 PR 作者为当前账号,GitHub 不允许自审 REQUEST_CHANGES,以下以 COMMENT review 提交)。
- [P1] 不要把租户过滤后的结果发布为全局物理表统计
refreshAnalyzeTableStats 在 mysql_cmd_executor.go:2180 只依据 JSON rewrite hint 判断 observation 是否可发布,随后在 :2187 将 cluster/system table 映射到 sys 物理统计 key。但 planner 会在 query_builder.go:12013-12069 为非 sys 租户的 cluster table 自动添加 account_id=currentAccountID 过滤,该隐式过滤不会出现在 rewrite hint 中。
因此 tenant A 执行 ANALYZE 得到的是 tenant A 子集的 count/NDV,却会覆盖 sys 物理表的全局 stats,并影响同一 CN 上其他租户的优化计划。查询结果本身未必错误,但可能导致错误 cardinality、join/shuffle 选择、spill、OOM 和严重延迟回退,存在跨租户统计污染。
请基于实际 plan 的扫描域判断 publication safety;至少禁止非 sys 租户对 cluster table 及所有隐式 account-filtered system table 发布 observation。请补充 sys + 两个 tenant 的确定性 BVT,验证 tenant ANALYZE 不会写入 sys 物理统计 key。
- [P2] schema version 校验与 stats cache 发布之间存在 TOCTOU
stats.go:1505-1512 重新读取并校验最新 TableDef,但随后在 :1516 进入 publishStatsForGeneration,最终在 :1625 写入 statsInfoMap。catalog ALTER 使用独立的 tableChange 锁,而 generation gate 只保护 subscription 生命周期;ALTER/drop-replay 可以保持同一 table ID、递增 schema version。因此可能发生:
校验 V1 -> 并发 ALTER 到 V2 -> 把 V1 的 NDV 发布到 V2。
这会把旧 schema observation 绑定到 replacement same-name column,违反设计文档的 schema safety invariant。请让 schema generation/token 校验与 cache swap 原子化(或在发布点再次以原子方式验证),并增加 barrier-based deterministic test 覆盖校验后、发布前 ALTER 的窗口。
当前验证:git diff --check 和 go vet 通过;本地 Go test 受 Darwin libmo.dylib 环境限制未执行测试体。
LeftHandCold
left a comment
There was a problem hiding this comment.
Reviewed exact HEAD c9956c1. No blocking findings.
Verified the full ANALYZE observation path: count/NDV parsing is fail-closed and preserves the SQL-visible result; tenant-filtered and relation-rewritten scans cannot publish table-wide values; schema validation and cache swap are linearized under the catalog table-change lock; frontend/internal planner caches require the matching TableDef version; unversioned remote export rejects schema-bound observations while legacy engines retain metadata-only behavior. Failure/cancellation preserves last-good stats, same-table publication remains serialized, and the added per-table version metadata is removed with the stats-cache lifetime.
Validation reviewed: invalid/overflow/empty-table cases, tenant-domain BVT, ALTER/DROP/TRUNCATE barriers, remote/local separation, legacy fallback, race repetitions, and exact-head build/coverage evidence. Local focused Go compilation was additionally attempted but this Darwin checkout lacks the repository C headers (jemalloc/xxhash/roaring/usearch); this is an environment limitation, not a PR failure.
|
CI fix pushed at Root cause: Proxy/multi-CN execution evaluates scalar scan constants into Fix: HASH and RANGE now share one Fold-normalization boundary. The predicate value is cloned and decoded once per predicate before reuse across partitions, preserving the reusable scan filter and avoiding O(partition-count) repeated Fold decoding. Literal predicates remain on the allocation-free fast path. Validation: the focused regression reproduces the exact NYI on the unfixed revision and passes after the fix; added folded RANGE equality and nested OR coverage; full |
XuPeng-SH
left a comment
There was a problem hiding this comment.
结论:当前应 REQUEST_CHANGES,但 GitHub 不允许 PR 作者对自己的 PR 设置该状态,故以正式 review comment 记录同等 blocker。
[P1] partition pruning can panic on folded NULL/empty scalar values.
在 pkg/partitionprune/filter.go 中,新的 normalizePartitionValue 会在 RANGE/HASH pruning 前转换 folded RHS。但 EvalFoldExpr 对 scalar NULL 使用空 Fold.Data(合法空字符串同样是零长度数据),而 getConstantFromBytes 对零长度数据返回 (nil, nil)。随后 ConvertFoldExprToNormal 构造 Expr_Lit{Lit:nil}。filterResult 执行替换后的分区表达式时,literal executor 可能得到 nil vector,并在 FixedVectorExpressionExecutor.Eval 的 resultVector.SetLength 处解引用,触发 CN panic。
可达路径:prepared 或 remote/multi-CN 的 partition_key = ?,参数为 NULL;RANGE 字符串分区使用空字符串也会进入相同路径。ReplaceFoldExpr -> EvalFoldExpr -> partitionprune.Filter 的真实生命周期中,未支持的 scalar 类型也有同样的 silent-nil 风险。这是 correctness/availability 问题,不只是 pruning 变差。
请系统性修复:
- Fold 编码/解码必须区分 NULL 与合法零长度值;
- unsupported/malformed value 不得生成 nil literal,可明确报错或保守扫描全部分区;
- 增加真实 Fold 生命周期的 RANGE/HASH 端到端测试:NULL、empty string/binary、temporal/decimal、malformed Fold、remote scope;
- 保持普通非 NULL literal 的 allocation-free fast path,不能错误裁剪分区或 panic。
XuPeng-SH
left a comment
There was a problem hiding this comment.
结论:当前应 REQUEST_CHANGES,但 GitHub 不允许 PR 作者对自己的 PR 设置该状态,故以正式 review comment 记录同等 blocker。\n\n[P1] partition pruning can panic on folded NULL/empty scalar values.\n\n在 pkg/partitionprune/filter.go 中,新的 normalizePartitionValue 会在 RANGE/HASH pruning 前转换 folded RHS。但 EvalFoldExpr 对 scalar NULL 使用空 Fold.Data(合法空字符串同样是零长度数据),而 getConstantFromBytes 对零长度数据返回 (nil, nil)。随后 ConvertFoldExprToNormal 构造 Expr_Lit{Lit:nil}。filterResult 执行替换后的分区表达式时,literal executor 可能得到 nil vector,并在 FixedVectorExpressionExecutor.Eval 的 resultVector.SetLength 处解引用,触发 CN panic。\n\n可达路径:prepared 或 remote/multi-CN 的 partition_key = ?,参数为 NULL;RANGE 字符串分区使用空字符串也会进入相同路径。ReplaceFoldExpr -> EvalFoldExpr -> partitionprune.Filter 的真实生命周期中,未支持的 scalar 类型也有同样的 silent-nil 风险。这是 correctness/availability 问题,不只是 pruning 变差。\n\n请系统性修复:Fold 编码/解码必须区分 NULL 与合法零长度值;unsupported/malformed value 不得生成 nil literal,可明确报错或保守扫描全部分区;增加真实 Fold 生命周期的 RANGE/HASH 端到端测试(NULL、empty string/binary、temporal/decimal、malformed Fold、remote scope);保持普通非 NULL literal 的 allocation-free fast path,不能错误裁剪分区或 panic。
|
Resolved the Fold normalization blocker in 40636dd.
Local evidence at this head: package test binary compiled and linked successfully with go test -c; go vet and git diff --check passed. Direct local execution is unavailable because the clean worktree has no matching stamped libmo.dylib and the repository wrapper correctly rejected reuse of the mismatched primary-worktree native artifact. CI has been triggered by the push; not waiting for it. |
|
系统性修复已推送到最新 HEAD
最终验证:
CI 已由 push 触发,按要求不等待。 |
XuPeng-SH
left a comment
There was a problem hiding this comment.
结论:latest head 283d587f23d 仍应 REQUEST_CHANGES。由于当前 GitHub 账号是 PR 作者,平台不允许 self-review 设置该状态,因此以正式 COMMENT review 记录同等 blocker。
[P2] 请求已经取消后,schema-bound stats 仍可被发布
refreshStatsWithMode 在 pkg/vm/engine/disttae/stats.go:1602 做完最后一次 statsRefreshCancellationCause(ctx) 检查后,先应用 options,再进入 publishStatsForGenerationAtTableVersion。后者可能在 catalog tableChange.RLock 和 gs.mu 上等待;真正写 statsInfoMap 的 publishStatsForGenerationLocked 只检查 gs.ctx,没有检查本次请求的 ctx。
因此存在确定性交错:
- ANALYZE 完成对象统计并通过 line 1602 的取消检查;
- 发布被一个 catalog writer(也可以是
gs.mu持有者)阻塞; - 客户端断开、statement timeout 或显式 cancel 使请求 context 结束;
- 锁释放后,旧请求仍在 line 1784 写入 schema-bound stats;
refreshStatsWithMode返回成功,frontend 随后推进 optimizer-stats generation 并缓存该值。
这违反本 PR design §4 的契约:cancellation 应保留 previous cache value 和 plan generation。它也不是只能在几条指令间命中的微小窗口;新增的 catalog 锁等待会放大这个窗口,并让已取消请求继续阻塞到锁可用。
请把 request context 带到最终 publication boundary,在同时取得 catalog schema fence 与 gs.mu 后、cache swap 前重新读取 durable cancellation predicate。若此时已取消,应不写 statsInfoMap/tableDefVersions,返回原始 cancellation cause,frontend 也不得 advance generation。请增加 barrier-based deterministic test:在最终 version fence 内阻塞发布,取消请求后再放行,断言返回 cancellation、last-good stats/version tag 不变且 frontend generation 不推进。
其余复核结论:此前 tenant-domain、schema ALTER TOCTOU、Fold NULL/nullable、remote routing/full payload/response release 等问题在 latest head 均已正确关闭;未发现额外 correctness、性能、死锁、OOM 或错误分区裁剪 blocker。exact-head Linux UT、SCA、shared build、Proxy BVT、multi-CN pessimistic BVT 和 coverage 均通过;git diff --check 通过。本地聚焦测试由仓库 macOS/CGo wrapper 正确拒绝,因为隔离 worktree 与 primary worktree 的 native inputs 不同、不可安全复用 libmo.dylib,不计为代码失败。
XuPeng-SH
left a comment
There was a problem hiding this comment.
Follow-up to review #5108116884: fixed in 6555e4af92.
The request context now reaches both publication paths. The final request/owner cancellation check runs under gs.mu after the generation check (the last potentially blocking application lock) and immediately before the cache swap. Cancellation that wins returns its original cause and preserves the last-good stats plus schema binding; publication that wins is treated as committed.
A deterministic phase-barrier test cancels after catalog version validation and before the swap, then verifies that neither the stats pointer nor the bound table version changes. The frontend failure test now also asserts that the optimizer generation/clock does not advance.
Latest-head local evidence: focused disttae/frontend UT passed; publication race test passed 50 repetitions under -race; full pkg/vm/engine/disttae passed under -race; affected-package go vet and git diff --check passed. The change adds one O(1) context check only on explicit stats publication, with no per-object or planner hot-path work.
I cannot approve my own PR, but the blocker from that review is resolved.
There was a problem hiding this comment.
Deep re-review completed for exact head 6555e4a against base 2004c61.
I read the complete review/comment history and the full PR diff, then reviewed the incremental fix from the previously audited head 283d587. The earlier tenant-domain, schema-TOCTOU, folded-value/nullable-vector, and remote-transport issues remain closed. The latest change also closes the remaining cancellation race: request and owner cancellation are now re-read after the last potentially blocking generation check, while the schema fence and stats lock are held, immediately before the cache swap. The barrier test preserves both last-good stats and its schema-version tag; the frontend failure path preserves its generation/clock and cached plan.
No blocking findings remain.
Validation on this exact head:
- git diff --check
- full tests for disttae and frontend
- focused race test for the versioned publication/cancellation fence: 100 repetitions
- focused frontend publication failure/cache-boundary race tests: 20 repetitions
- go vet for disttae and frontend
The prior package matrix, partition-pruning race tests, and ANALYZE/partition BVT structural checks also passed before the final delta; the final delta only changes the cancellation publication path and its tests/docs.
What changed
ANALYZE TABLEalready performs a table-wideapprox_count_distinctscan, but the result was only returned to the client. Optimizer statistics were rebuilt independently from per-object scalar NDVs, which cannot recover global NDV when object value sets overlap.This PR:
count(*)to the existing internal ANALYZE aggregate scan and removes that internal column before returning the result;NDV/NULL <= rowsbounds, physical table identity, and schema version before cache replacement;Design:
docs/design/analyze_table_wide_ndv_publication.mdRelated to #27728.
First-principles rationale
Per-object scalar NDVs are insufficient: the same object row counts, zonemaps, and local NDVs can represent fully overlapping or fully disjoint value sets, whose global NDVs differ by the object count. The correct owner is the table-wide observation ANALYZE already computes.
A global stats key represents one complete physical object. Therefore a tenant-filtered subset cannot publish to that key. Likewise, checking schema version before publication is insufficient: validation and cache swap must share one catalog linearization point. If publication wins the catalog read lock it precedes ALTER; if ALTER wins, the stale observation is rejected.
Schema-version safety is a consumer property, not a blanket ban on unversioned local access. Planner reads carry a table-definition version and must match it. Remote CN export has no version on the existing wire contract and must fail closed. Local
table_statsis diagnostic and must still observe a successful local ANALYZE publication. These call semantics now have separate interfaces and tests.No extra table scan, persistent state, goroutine, retry loop, or unbounded state is added. The hot query-planning path is unchanged; the added catalog read lock is taken only during explicit ANALYZE publication and covers the bounded generation check plus map swap.
Performance evidence
Host:
10.222.1.55, 16 execution workers, NVMe data/spill. Production source wasd2e247f32c; final headc9956c1bfechanges only a delegation test, has an empty production-source diff from that binary, and was separately rebuilt successfully on the same host.10M distinct URL-shaped VARCHAR values with a long common prefix and randomized distinguishing suffix:
hash(URL)The three post-ANALYZE executions were 1.296s, 1.257s, and 1.282s: about 6.49x faster on the target shape. ANALYZE itself took 0.268s. Its visible approximate NDV was 10,025,433; cache publication correctly capped it by the exact 10,000,000-row upper bound.
This is deliberately not claimed as a universal speedup. A 10M sequential-suffix control was already estimated at 2,896,500 NDV, already selected hash shuffle, and ran in 1.023s before ANALYZE. A 1M-row/100-NDV control remained non-shuffled after ANALYZE. The benefit occurs when non-mergeable object summaries materially underestimate a genuinely high global NDV and cross the planner's shuffle decision boundary.
Validation
Recorded validation head
c9956c1bfe, rebased onto9f711e2134:pkg/sql/util,pkg/sql/plan,pkg/sql/compile,pkg/frontend,pkg/vm/engine,pkg/vm/engine/disttae/cache,pkg/vm/engine/disttae, andpkg/cnservice: pass;go vetfor the same packages with repository CGo flags and readonly module resolution: pass;-race -count=100: pass;EntireEngineforwarding/fallback, and concurrent remote-response/local-publication regressions are covered; the new handler and export/delegation methods report 100% function coverage;make -j12) ofc9956c1bfe: pass;git diff --check: pass.The 55 black-box run initially caught a real regression:
table_stats()returned0/nullafter ANALYZE because the schema fence rejected every unversioned reader. The fix separates local diagnostic reads from remote CN export instead of weakening planner version checks or changing expected output.Latest cancellation-race follow-up
Deep review found a final publication race: request cancellation could become durable after the pre-publication check but while waiting for the catalog or statistics locks, allowing the stale candidate to replace
statsInfoMapand then advance the frontend generation.Latest head
6555e4af92carries the request context into both versioned and metadata-only publication paths. Generation and schema fencing complete first; request andGlobalStatsowner cancellation are then checked undergs.muimmediately before the bounded cache swap. If cancellation wins, the original cause is returned and the last-good stats, schema binding, frontend generation, session cache, and plan cache remain unchanged. If the swap wins first, publication is committed and later cancellation does not create a partial rollback. The ordering retains the establishedgs.mu -> updatingMulock order and adds one O(1) context check only to explicit refresh publication, not to object traversal or query-planning hot paths.Deterministic phase-barrier coverage cancels after schema validation but before the final swap and verifies no publication. Latest-head local validation passed focused disttae/frontend UT, 50 repeated race runs of the publication test, the complete disttae package under
-race, affected-packagego vet, andgit diff --check.QA test plan
ANALYZE TABLE t(v). Verify the visible result remains one NDV column,table_statsreports NDV near row count, andEXPLAIN ANALYZEselects distributed hash shuffle withoutMergeGroupspill.NDV/NULL <= rowscapping.mo_database,mo_tables,mo_columns,statement_info,metric, andsql_statement_cu.table_statsstill shows the successful ANALYZE result and version-matching local plans consume it.