Skip to content

fix(plan): align DATE_FORMAT CTAS metadata - #27870

Merged
XuPeng-SH merged 21 commits into
matrixorigin:mainfrom
daviszhen:codex/24436-date-format-metadata
Sep 6, 2026
Merged

XuPeng-SH merged 21 commits into
matrixorigin:mainfrom
daviszhen:codex/24436-date-format-metadata

Conversation

@daviszhen

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 #24436

What this PR does / why we need it:

  • derive DATE_FORMAT and TIME_FORMAT VARCHAR widths from literal format patterns using MySQL-compatible format bounds while retaining a conservative bound for dynamic patterns
  • keep these functions nullable because invalid temporal inputs can synthesize NULL
  • preserve quotes and case-sensitive format spelling in expression-derived CTAS column names
  • enable the existing DATE_FORMAT CTAS BVT assertions for varchar(134) DEFAULT NULL

Validation:

  • full pkg/sql/plan and pkg/sql/plan/function tests
  • go vet for both packages
  • make build
  • local mo-service reproduction of SHOW CREATE, DESC, and SELECT

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

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

The primary %W %M %Y case, nullable metadata, case-sensitive heading, and MySQL format-length table are implemented consistently, but the new narrowed width is not a safe upper bound for MatrixOne execution semantics on exact head d7cd750.

[P1] Do not create DATE_FORMAT/TIME_FORMAT result types narrower than values the same function can produce for valid MatrixOne inputs.

Three deterministic counterexamples:

  1. MatrixOne TIME supports hours through 2562047787. timeFormat writes the complete hour for %H/%k and %T, while mysqlDateFormatWidth returns only 7 for %H/%k and 8 for %T. A positive %H result is 10 characters; a negative one is 11 because timeFormat prepends the sign.
  2. The sign is prepended for every non-empty negative TIME format. Therefore TIME_FORMAT(negative_time, %i) can return -59 (3 characters), while the inferred width is 2.
  3. Existing TestDateFormatZeroDatetimeMatchesMySQL pins DATE_FORMAT(ZeroDatetime, %U|%u|%V) to 613566757|613566757|613566757 (29 characters), while the new inferred width is 8.

These are supported current-system values, not hypothetical invalid states. Propagating the under-bound type into CTAS can cause data-too-long failures or truncation during materialization. A temporary exact-head invariant test comparing inferred widths with these already-supported output domains failed all three cases (7 < 10, 2 < 3, and 8 < 29). I also confirmed with MySQL 8.0.44 that blindly copying its narrow TIME_FORMAT metadata can itself make CTAS fail with Data too long, so that table cannot be used as an unconditional storage-capacity contract for MatrixOnes wider TIME domain.

Please keep the MySQL-compatible bounds where they safely cover output, but account for MatrixOnes sign/full TIME range and the zero-date week sentinel (or first align those execution semantics), and add CTAS value-materialization regressions for these cases. Exact-head focused tests and CI otherwise pass; no performance blocker was found.

@daviszhen

Copy link
Copy Markdown
Contributor Author

Follow-up commit cd10dd0 also makes BindContext output-column provenance lazy: the map is created only on the first metadata write, while set-operation/view boundaries still install explicit entries when required. [Verify Go package graph]
mkdir -p install
mkdir -p install/include install/lib
using verified cached download: install/lib/onnxruntime_arm64.dylib
cp -r /Users/pengzhen/Documents/GitHub/matrixone-pr27870/thirdparties/install/lib /Users/pengzhen/Documents/GitHub/matrixone-pr27870/
make[1]: Nothing to be done for `all'.
[Stage jieba dict]
rm -rf /Users/pengzhen/Documents/GitHub/matrixone-pr27870/dict
cp -r /Users/pengzhen/Documents/GitHub/matrixone-pr27870/pkg/monlp/tokenizer/dict /Users/pengzhen/Documents/GitHub/matrixone-pr27870/dict
[Build binary]
CGO_CFLAGS="-I/Users/pengzhen/Documents/GitHub/matrixone-pr27870/cgo -I/Users/pengzhen/Documents/GitHub/matrixone-pr27870/thirdparties/install/include " go build -mod=readonly -ldflags="-extldflags '-L/Users/pengzhen/Documents/GitHub/matrixone-pr27870/cgo -lmo -L/Users/pengzhen/Documents/GitHub/matrixone-pr27870/thirdparties/install/lib -Wl,-rpath,@executable_path/lib' -X 'github.com/matrixorigin/matrixone/pkg/version.GoVersion=go version go1.26.5 darwin/arm64' -X 'github.com/matrixorigin/matrixone/pkg/version.BranchName=codex/27870-review' -X 'github.com/matrixorigin/matrixone/pkg/version.CommitID=cd10dd0f4b' -X 'github.com/matrixorigin/matrixone/pkg/version.BuildTime=1788352583' -X 'github.com/matrixorigin/matrixone/pkg/version.Version=codex/27870-review'" -o mo-service ./cmd/mo-service and the focused plan tests/vet pass with the follow-up.

@daviszhen

Copy link
Copy Markdown
Contributor Author

Follow-up commit cd10dd0 makes BindContext output-column provenance lazy: the map is created only on the first metadata write, while set-operation/view boundaries still install explicit entries when required. make build and the focused plan tests/vet pass with the follow-up.

@daviszhen

Copy link
Copy Markdown
Contributor Author

The failed Ubuntu UT rerun exposed a second flaky assertion in TestRequestCanBeFilter: moerr.AttachCause can return an errors.Join containing the context deadline and its cause, so exact error equality is not stable. Commit 7bc63532c3 changes the test to require.ErrorIs, with local go test ./pkg/lockservice -run ^TestRequestCanBeFilter$ -count=50 and make build passing. A fresh full CI run is now in progress: 33652227169.

@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-review of exact head 7bc63532c335b94162e2c9553a7e59bae7c15e81. The previous width/nullability, direct/nested expression, CTE/derived-star, ROLLUP/window, apostrophe, sparse-allocation, and flaky lockservice-test issues are closed, and substantive CI is green. One reachable propagation gap remains.

[P1 correctness] JOIN USING star expansion drops the case-sensitive heading provenance again.

The new provenance is copied for ordinary leaf columns in doUnfoldStar, but a merged USING column is appended only as using.col at pkg/sql/plan/bind_context.go:544-568; no provenance from the selected binding is appended to the output map. The outer star then receives an empty provenance at pkg/sql/plan/query_builder.go:10400-10408, so CTAS applies full lowercasing at pkg/sql/plan/build_ddl.go:1452-1455.

I ran this deterministic full-planner counterexample on the exact head:

CREATE TABLE time02 AS
SELECT *
FROM (SELECT DATE_FORMAT(col2, '%M') FROM time01) a
JOIN (SELECT DATE_FORMAT(col2, '%M') FROM time01) b
USING (`date_format(col2, '%M')`);

Expected target column: date_format(col2, '%M').

Actual target column: date_format(col2, '%m').

The focused exact-head regression failed with that exact mismatch. This is the same externally visible expression-identity contract as the reported issue, reached through a normal JOIN USING boundary rather than a theoretical malformed state. Please propagate structural heading provenance for a merged USING output when its contributing columns agree; when they disagree, define a deterministic safe rule rather than selecting stale metadata. Add the derived JOIN USING plus star CTAS regression. No other confirmed correctness, performance, or unhappy-path blocker was found in this pass.

@daviszhen

Copy link
Copy Markdown
Contributor Author

Fresh CI run 33652227169 is now green. Ubuntu UT, SCA, UT Coverage, final Coverage merge, both BVT jobs, and the shared build all passed on head 7bc63532c3. The failing checks are resolved.

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

[P1 correctness] Preserve case-sensitive format-literal heading provenance for JOIN USING star expansion.

pkg/sql/plan/bind_context.go:544-568 emits each merged USING column into exprs and names, but it never copies the selected binding’s headingProvenance into provenances. The later star path at pkg/sql/plan/query_builder.go:10401-10408 consequently appends an empty provenance, and CTAS normalizes the whole heading at pkg/sql/plan/build_ddl.go:1439-1464.

This is reachable with:

CREATE TABLE time02 AS
SELECT *
FROM (SELECT DATE_FORMAT(col2, '%M') FROM time01) a
JOIN (SELECT DATE_FORMAT(col2, '%M') FROM time01) b
USING (`date_format(col2, '%M')`);

The expected target name is date_format(col2, '%M'); the current flow loses the literal segment at the USING boundary and produces date_format(col2, '%m'). This changes a case-sensitive DATE_FORMAT pattern and can again collapse CTAS output identities. Propagate structural heading provenance for the chosen/merged USING output (with a deterministic rule when contributors disagree), and add the derived-JOIN-USING-plus-star CTAS regression.

@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-review of exact head ab03091e4cbbc8fc06c74101d2c1f43c31d08c21. The previous width/nullability, direct and nested heading, CTE/derived/UNION/ROLLUP/window propagation blockers are closed. The new JOIN ... USING handling also preserves identical provenance and safely falls back when FULL JOIN arms disagree. The sparse metadata path is reasonable, and I found no material execution-performance or liveness regression there. One blocking planner-panic class remains.

[P1 correctness/availability] pkg/sql/plan/query_builder.go:10866 must not invoke the generic AST Accept walker over an arbitrary expression. Once the text prefilter sees DATE_FORMAT(/TIME_FORMAT(, captureHeadingProvenance recursively visits the complete cloned expression, but multiple legal child nodes explicitly panic in Accept: IntervalExpr (expr.go:1764), VarExpr (expr.go:1862), Subquery (expr.go:827), and ExprList (expr.go:860). Deterministic examples include:

CREATE TABLE t AS SELECT DATE_FORMAT(col2 + INTERVAL 1 DAY, '%M') FROM time01;
CREATE TABLE t AS SELECT CONCAT(DATE_FORMAT(col2, '%M'), @suffix) FROM time01;

The first is an ordinary date-arithmetic shape. Both pass containsDateTimeFormatHeading, then descend through FuncExpr.Accept into an unimplemented child and panic instead of producing a plan or a normal SQL error. The textual prefilter can additionally false-positive when ordinary literal text merely contains DATE_FORMAT(. Current green CI does not exercise these AST shapes.

Please replace this with a panic-free structural traversal/formatter capture, structurally identify actual DATE_FORMAT/TIME_FORMAT calls rather than rendered substrings, and add CTAS regressions covering at least interval operands, user variables, a nested subquery/list shape that is accepted by the grammar, and a literal-text false positive.

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

The previous Accept-panic blocker is fixed on 4a0f0372ae92, but two blockers remain.

  1. [P1 correctness] A DATE_FORMAT/TIME_FORMAT nested under a scalar subquery still loses literal-case provenance.

containsDateTimeFormatExpr explicitly says it handles Subquery, but its type switch has no *tree.Subquery branch (lines 10825-10953). Therefore this valid expression returns false before captureHeadingProvenance runs:

CREATE TABLE time02 AS
SELECT (SELECT DATE_FORMAT(col2, '%M') FROM time01 LIMIT 1);

formatSelectExpressionHeading returns empty provenance, and normalizeCTASColumnName lowercases the whole heading at lines 1453-1454, changing %M (month name) to %m (numeric month). MySQL 8.0 preserves %M in the resulting default column name. The new test named “subquery operand” covers a subquery inside DATE_FORMAT's first argument; it does not cover DATE_FORMAT nested inside a scalar-subquery heading, so it cannot catch this omission. Please cover the actual nesting direction and preserve the literal segment through it.

  1. [Design gate] The fix has become a planner-wide metadata architecture without an approved design.

The current PR adds 835 and removes 83 production lines across QueryBuilder, BindContext, Binding, CTE reuse, UNION, JOIN USING, star expansion, ROLLUP/window rewrite, and CTAS. It introduces a new sparse provenance channel and a 300+ line hand-maintained AST traversal. This crosses the repository's major-refactor size/core-abstraction threshold; the issue/PR body is not a versioned design and does not define the complete expression domain, propagation/clearing rules, ownership, alternatives, or a completeness mechanism when new AST nodes are added. The repeated sequence of wrapper/CTE/ROLLUP/JOIN/panic/subquery misses is a direct consequence of that missing closed model.

Please add and get approval on a stable design revision before extending this walker again. At minimum it should define one structural heading representation/owner, every propagation and semantic-reset boundary, how AST traversal remains total and complete as node types evolve, the ordinary-query allocation bound, and public counterexample coverage. Then align the implementation to that design rather than adding another isolated branch.

Exact-head CI is green. I found no separate liveness or hot-path execution blocker; the common-path maps remain lazy. Local counterexample execution was not used as pass/fail evidence because the isolated macOS worktree lacks its exact cgo/libmo.dylib; the concrete parser/control-flow path above is source-complete.

@daviszhen

Copy link
Copy Markdown
Contributor Author

补充了设计修订版 c0a9712722:docs/design/20260906-ctas-heading-provenance.md。

设计要点:

  • BindContext 按输出 ordinal 持有稀疏、结构化 heading provenance,不按已折叠的列名查找。
  • provenance 唯一生产点是 formatter:普通 pass 检测 DATE_FORMAT/TIME_FORMAT,命中后第二 pass 记录 string-literal ranges;嵌套表达式、标量子查询和 UNION 复用同一个 formatter context,不再维护 planner 手写 AST walker。
  • 明确 alias、CTE/derived/star、UNION、ROLLUP/window、JOIN USING 的传播与清除规则;JOIN USING 贡献不一致时安全清除。
  • 普通表达式保持单次格式化和 lazy/sparse allocation,不引入反射或 protobuf/wire 字段。

请先 review 这版设计;后续实现 commit 将按该边界替换手写遍历,并补 scalar-subquery 回归。

@daviszhen

Copy link
Copy Markdown
Contributor Author

设计修订已按 c0a9712722 落地,最新实现为 e159fcfe68,并已用普通 merge 合入最新 upstream/main(061a343d71),PR 的 BEHIND 状态已处理。

实现变化:

  • 将 DATE_FORMAT/TIME_FORMAT heading provenance 的生产点下沉到 parser formatter:普通 pass 检测函数,命中后第二 pass 记录 string-literal ranges。
  • formatter context 会自然穿过 wrapper、标量子查询、UNION 等渲染边界,移除 QueryBuilder 中约 380 行手写 AST walker,避免 Subquery/新 AST 节点遗漏和 Accept panic。
  • 保留按输出 ordinal 的稀疏结构化传播规则;dynamic format、显式 alias 和不一致 JOIN USING 仍安全回退到普通 lower-case 规范化。
  • 新增 formatter literal-position 测试,以及真实 CTAS planner 回归:SELECT (SELECT DATE_FORMAT(col2, %M) FROM time01 LIMIT 1) 保留 %M。

本地验证:

  • go test ./pkg/sql/parsers/tree -count=1
  • go test ./pkg/sql/plan ./pkg/sql/plan/function -count=1
  • go vet ./pkg/sql/plan ./pkg/sql/plan/function

以上均通过,请按设计文档和最新实现重新 review。

@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-review of exact head daac69bc2fd57d912dfc8513ebfb657b1be6ca26. The previous scalar-subquery, JOIN USING, ROLLUP/window, dynamic-pattern, and sparse-allocation blockers are closed, and substantive CI is green. One reachable literal-form gap remains.

[P1 correctness] Preserve binary-introduced format literals in CTAS headings.

The formatter capture records positions only when FmtCtx.WriteValue receives P_char. A legal _binary '...' string is represented as P_ScoreBinary, so a DATE_FORMAT/TIME_FORMAT expression is detected but its case-sensitive format operand produces no literal range. formatSelectExpressionHeading then falls back to the first-pass heading, and CTAS lowercases the complete text.

I reproduced this on the exact head with a temporary full-planner test:

CREATE TABLE time02 AS
SELECT DATE_FORMAT(col2, _binary '%M') FROM time01;

Binding succeeds, but the generated target name is date_format(col2, %m); the supported %M operand was changed to the semantically different %m. The temporary test was removed after reproduction.

Please make formatter provenance cover string-like binary literal nodes as well as ordinary P_char literals, retaining a stable binary-introducer representation and the literal byte range. Add direct and transparent-boundary CTAS regressions for _binary '%M' (and TIME_FORMAT), while keeping binary identifiers and dynamic operands on the normal lowercase path. This is a supported parser/binder path, not a malformed or theoretical state.

@daviszhen

Copy link
Copy Markdown
Contributor Author

Addressed the latest P1 in commit eb45268e5c.

FmtCtx now treats P_ScoreBinary as a string-literal provenance source when single-quote capture is enabled, preserves the stable _binary '...' spelling, and records the complete literal range. Added direct and transparent-boundary CTAS regressions for binary DATE_FORMAT and TIME_FORMAT literals.

Validation: parser-tree focused tests and MySQL parser focused tests passed; the focused planner test is blocked locally because the workstation lacks usearch.h, jemalloc.h, xxhash.h, and roaring.h. The ordinary push is complete and the new CI run is in progress.

@daviszhen

Copy link
Copy Markdown
Contributor Author

已修复并推送最新 head:15b8e7f3ac(test(plan): use time input for binary time format)。

  • 根因:binary TIME_FORMAT 回归误把 DATETIME 列 col2 作为时间参数;CI 正确拒绝了 [DATETIME VARBINARY]。
  • 修复:在 planner fixture 增加 time_col TIME,两条 TIME_FORMAT(_binary '%H') 回归改用该列;binary literal provenance 实现本身保留不变。
  • 验证:go test ./pkg/sql/parsers/tree -run 'TestFmtCtxCaptures(BinaryDateFormatLiteral|DateFormatLiteralsThroughScalarSubquery)$' -count=1 通过,git diff --check 通过。
  • planner 定向测试因工作站缺少 xxhash.h、roaring.h、usearch.h 无法本地编译;新 head 的 required checks 已自动触发,未重复触发旧 job。

@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-review of exact head 15b8e7f3ac477787d1db0bde733d5679e089bccb. The prior width/nullability, wrapper/scalar-subquery, CTE/derived/UNION/ROLLUP/window/JOIN-USING, AST-totality, sparse-allocation, and binary-introduced literal blockers are closed.

I rechecked the complete change map and the latest binary-literal delta from daac69bc2f: P_ScoreBinary now has a stable _binary '…' representation and a complete literal range, while dynamic operands still fall back to ordinary identifier normalization. The TIME_FORMAT regression now uses a real TIME input. Runtime output bounds cover MatrixOne’s extended TIME hours/sign and zero-date week sentinel; the apparent negative week-year branch is not reachable through the storable DATETIME domain used by this overload. Ordinary headings stay on the single-pass/lazy path.\n\nSubstantive exact-head CI is green. I found no remaining correctness, performance, liveness, or unhappy-path blocker.

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/XL Denotes a PR that changes [1000, 1999] lines

Projects

None yet

Development

Successfully merging this pull request may close these issues.

6 participants