Repository navigation
Description
Why do you want to refactor this code?
Follow-up to #31944, inspected at 0ec56525a6687e2a9698ee9ba771fafb2ba98606. That PR adds a scoped mixed DATETIME/TIMESTAMP index optimization and a separate time-zone plan-cache fix. The original wrong-result issue #31619 was addressed by #31624.
The follow-up opportunity is to consolidate responsibilities, while retaining the validated access path and its safety contracts. This is an architectural improvement request, not a newly demonstrated correctness defect or a request to replace the implementation solely because of its size.
MO already has function-semantic APIs such as IsRuntimeConstant, IsStatementConstant, GetFunctionValueUnstableByID, and diagnostic/folding restrictions, together with ordinary index selection, catalog resolution, plan-cache and compile owners. The temporal path additionally carries function-specific bound admission, planning intent/native relation capture, and an access-path replan marker across planner, frontend and compile. Identify which responsibilities can move into existing owners, and remove the replaced implementation in the same change.
MO-specific suitability and constraints
- Physical secondary indexes are separate hidden tables. Base/index schema, tenant and authorization, transaction/snapshot/workspace identity, and borrowed relation lifetime must stay consistent. A scalar bound or cost estimate does not establish those facts.
- Value repeatability, permission to evaluate early, and permission to fold are different properties. Legacy volatility flags also protect diagnostics and settings. Unknown functions, UDFs and external effects must remain conservative; absence of a flag is not proof of purity.
- A fresh runtime value does not guarantee a suitable cached access path. Sparse-to-dense transitions can require recosting even when predicate execution uses the correct value. Conversely, permanently ineligible statements must not lose cache reuse because they contain a temporal expression.
- Execution can cross CNs and retry/rebuild boundaries. Statement clock, time zone, parameter provenance, placement and transport must agree with the actual execution. Preserve the repository's supported upgrade contract.
Describe the solution you'd like
Start with an inventory of the current owners and consumers, then propose the smallest change that establishes these boundaries:
| Responsibility | Expected ownership |
|---|---|
| Value stability, early-evaluation safety, diagnostics and parameter provenance | Existing function/expression semantics and evaluation facilities; add only the missing facts required by actual consumers. |
| SQL comparison domain and physical range derivation | Typed comparison/range code, including time-zone and precision rules. Make exact predicates and necessary candidate filters explicit to their consumers. |
| Authorized table/index resolution and read identity | Ordinary resolver and statement/transaction owner, with an explicit borrowed-result contract where needed. |
| Plan dependencies, reuse and rebuild | Existing ordinary/prepared cache and compile owners, distinguishing execution values, value-dependent access choices, and session/schema dependencies. |
| Access selection, costing, pruning and residual execution | Existing index selector and reader/compiler paths. Type-specific logic supplies validated inputs rather than creating a second selection or execution policy. |
Implementation expectations:
- Reuse existing semantic predicates before adding another classification. Shared early evaluation must preserve errors, warning multiplicity, NULL/empty-input and lazy-evaluation behavior; a function name check may be removed only when an equally strong semantic proof replaces it.
- Keep the range invariant: every row for which the SQL predicate is TRUE must pass the physical candidate. A necessary range retains the full original predicate before any LIMIT or other early stop. Preserve temporal precision, zero/sentinel and physical-tail handling.
- Evaluate whether ordinary resolution can explicitly supply the authorized relation and read identity needed by costing/publication, reducing ambient capture state. Preserve nested planning, EXPLAIN, reentry, cancellation, cleanup, DDL and tenant boundaries. Borrowed relations retain their existing cleanup owner. Merely renaming the current scope or adding a wrapper is not consolidation.
- Express execution-dependent access decisions through the existing plan dependency/rebuild boundary where that is sufficient. Preserve both sparse-to-dense recosting and reuse for unaffected ordinary/prepared statements. Do not globally rebind every stable function or weaken time-zone invalidation to simplify one index case.
- Reuse existing selector, metadata and resource-budget ownership. Account for extra resolutions, metadata walks, allocations and copies; a cleaner interface must not hide new I/O, subscriptions or unbounded work. Cost estimates must remain separate from authorization and snapshot proofs.
- Delete superseded traversals, state, flags, wrappers and execution routes when their protection has moved to the established owner. Any abstraction must have concrete existing consumers and lower total complexity; a general framework is not the objective.
Publish and review a versioned design before this cross-subsystem refactor. Map each proposed deletion to the owner that supplies its former guarantee, identify responsibilities that should remain type-specific, and record any simplification that is not suitable for MO. Reconcile the implementation baseline with the actual status of #31944 when work starts.
Acceptance criteria
- A before/after responsibility map demonstrates fewer duplicated decisions or independent state owners, rather than moved code or compatibility wrappers. Scope and supported SQL behavior remain explicit.
- Existing SQL result, metadata and error/warning contracts are preserved across direct SQL, ordinary reuse, SQL and binary prepared execution, EXPLAIN/ANALYZE, time-zone/clock changes, and schema/index changes. Runtime value freshness and access-path recosting are tested independently.
- Negative cases cover volatile/side-effecting/throwing or warning-producing bounds, parameter/NULL transitions, unsupported shapes, cancellation/deadlines, and failure before publication. Failures leave no partial plan or retained statement/transaction ownership.
- Hidden-index authorization, base/index read pairing, nested planning and relevant two-CN execution/transport paths retain their guarantees. Existing fixtures and independent SQL controls are reused; typed plan assertions do not replace row-result or diagnostic checks.
- Paired measurements on the final revision retain the selective covering-index benefit and appropriate BASE controls across shuffled/ordered and sparse/dense layouts, plus same-domain and ordinary/prepared workloads. Use the immediate pre-refactor implementation as the regression baseline; keep any separate main comparison clearly attributed. Report exact baseline/head binaries, workload order, warmup, p50/p95, CPU, allocations and scanned work. Establish same-source variability and investigate repeatable latency increases above 10%; unresolved signals remain explicit rather than being waived by gains elsewhere.
- Report planning/constructor cost separately from end-to-end SQL cost. Historical prepared outliers from perf: optimize mixed temporal index scans and fix time-zone plan caching #31944 are not claimed fixed by an isolated non-reproduction. Replaced production and test paths are removed while preserving distinct regression oracles.
Describe alternatives you've considered
- Retain the current scoped implementation where an existing owner cannot provide the same guarantee more simply. Specialization with a clear contract can be appropriate; no safety check should be removed merely to reduce line count.
- Consolidate one complete responsibility at a time within existing facilities. Prefer this to introducing a general expression, metadata or dynamic-plan framework without demonstrated consumers and measured benefit.
Additional information
Starting points at the inspected PR revision:
pkg/sql/plan/function/function.go: constant/evaluation semantics and diagnostic restrictions.pkg/sql/plan/temporal_candidate_admission.goandtemporal_original_analysis.go: bound admission, original-owner proof and cache-lifetime classification.pkg/frontend/temporal_native_scope.go,pkg/sql/plan/temporal_planning_scope.goandpkg/vm/engine/temporal_index.go: statement/native relation ownership and read identity.pkg/sql/plan/temporal_cbo_access.go,temporal_candidate_index_only.go, ordinary index construction, frontend plan-cache and compile consumers: selection, publication and execution dependencies.
Expanding admission to currently unsupported prepared, named-zone, FORCE/LIMIT, join or non-covering cases is separate work requiring its own semantic and performance evidence.
Activity
refactor: integrate temporal index planning with shared owners (#32341)
XuPeng-SH commentedon Nov 9, 2026
QA 交接(不代表验收通过)
#32341 已于 2026-11-09T02:28:04Z 合入 main,merge SHA c99234d,关联本 issue #32318 的 temporal index shared-owner 重构。已读取本 issue 完整正文/空评论及 PR 完整讨论和评审;最终 b047c68 评审 approve,旧 API 迁移及配对性能验证项已由后续实现/报告解决,未发现适用于当前合并范围的已验证反例或未完成开发 follow-up。
范围:比较域/必要范围、bounded costing、授权 borrowed relation、缓存依赖与 compile/retry 的执行证明整合到现有 owner,保留完整 SQL residual。CandidateFilter 不授权隐藏索引访问,缓存值新鲜也不替代 access-path recosting。外部 CompilerContext 实现需适配显式 resolver output。命名时区、prepared temporal inversion、join、LIMIT/OFFSET、非覆盖回表及分布式 candidate scan 继续保守 fallback;不是开放这些新路径。
真实验证证据:最终评审报告完整 planner/compiler/value_scan/readutil normal 通过(2 planner 子测跳过),16 focused frontend 与2 public SQL roots、7 targeted race roots及31/100次重复通过,5 consumer packages vet 和801 BuildPlan/69 resolver API审计通过。作者另报告较早 normal/race、严格双CN Proxy BVT、真实4.2.8停止服务升级及同main配对性能控制。以上均为远端报告,本轮未本地运行产品测试或性能测试,未独立核验原始执行日志。
限制:最终评审时核心 CI pending,frontend/race为focused;广泛多CN/BVT、升级和性能证据有历史修订归属,不能当作本轮最终merge实测。旧混合负载约+13% p95信号未被后续prepared长采样完全解释,native allocations未测,进程CPU/Go bytes含后台工作;不宣称零开销或生产性能改善。停止式4.2升级不代表混版本执行或降级通过。独立#31611 ALTER/async-index冲突未修复,Fulltext2 fixture调整不等于修复它。
请 QA 对 merged revision 验证 direct/ordinary reuse/SQL与binary prepared、EXPLAIN/ANALYZE 的结果/metadata/错误告警一致性,时区/clock/参数NULL和schema/index改变后的 recost与cache复用;重点核对必要范围无假阴性、完整residual在LIMIT前保留、隐藏索引权限撤销/重授、base/index读身份、borrowed lifetime、取消/重试失败后无部分发布。复核两CN运输与fallback、旧zone-map all-ff边界和共享元数据不被并发修改。按issue要求区分planning与端到端成本、同源码波动和准确baseline/head,并跟进历史尾延迟限制。
移除研发负责人,改派唯一 Ariznawlll;保持 open,不自动要求backport。