Skip to content

fix(plan): make binary string result domains lossless - #27841

Merged
mergify[bot] merged 35 commits into
matrixorigin:mainfrom
ck89119:issue-27218-main
Sep 3, 2026
Merged

mergify[bot] merged 35 commits into
matrixorigin:mainfrom
ck89119:issue-27218-main

Conversation

@ck89119

@ck89119 ck89119 commented Aug 29, 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:

issue #27218

What this PR does / why we need it:

  • introduces checked result-width derivation with explicit known/unknown bounds
  • promotes binary results beyond the VARBINARY limit to BLOB without capping metadata
  • preserves original source-width metadata for CONVERT(... USING binary) before execution casts
  • makes default CHAR(...) binary and lowers explicit USING variants through CONVERT
  • aligns expanding string functions, runtime size limits, and CTAS materialization with the declared result domain
  • adds boundary coverage for 0/1, 65534/65535/65536, 70,000-byte results, overflow, fixed source types, and CTAS metadata

Scope note: REGEXP result-domain expansion and its required pre-materialization memory admission are intentionally excluded from this PR and remain open for a separately linked complete fix.

Validation:

  • .agents/skills/mo-dev/scripts/mo-cgo-test -count=1 -timeout=300s ./pkg/sql/plan/function

  • .agents/skills/mo-dev/scripts/mo-cgo-test -count=1 -timeout=300s ./pkg/sql/plan

  • .agents/skills/mo-dev/scripts/mo-cgo-test -count=1 -timeout=240s ./pkg/sql/parsers/dialect/mysql

  • git diff --check

  • ./run.sh -n -g -p .../dtype/binary_string_result_domain.test (twice on the same clean-ready instance: 21/21 passed each run)

  • final self-review: PASS, no unresolved blockers

Review-gap fixes at 828a7c389c:

  • preserve BLOB/VARBINARY/BINARY inputs through CONVERT and expanding-function overload resolution
  • derive lossless MAKE_SET, EXPORT_SET, and QUOTE widths
  • preflight LPAD/RPAD encoded-byte size and MPool allocation before constructing large results
  • refresh information_schema.COLUMNS for already-upgraded v4.0.6 tenants
  • preserve CONVERT USING syntax through formatter/reparse and CTAS

Second review round at d18ea05c1d:

  • preserve true binary inputs and invalid UTF-8 bytes through QUOTE
  • perform checked MPool admission before expanding REPEAT/REPLACE/INSERT/PAD results; PAD sizing is allocation-free
  • derive literal-dependent VARBINARY widths for REPEAT and LPAD/RPAD while keeping dynamic bounds as BLOB
  • updated focused BVT: 23/23 passed

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

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

Two result-domain regressions remain. The decimal case under-declares a legal runtime value and can break protocol/CTAS correctness; the fixed-scalar case broadly over-promotes bounded expressions and changes public metadata. Please address both and add binder/CTAS regression coverage.

Comment thread pkg/sql/plan/function/list_builtIn.go Resolved

@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 review completed on exact head 69f2eb6. I found no blocking correctness, performance, or unhappy-path issue. The Known/Unknown width model and VARBINARY-to-BLOB promotion preserve the declared-domain invariant across binder, protocol metadata, CTAS, and information_schema. I also checked literal refinement, binary/text overload preservation, invalid UTF-8 sizing, zero/negative/overflow boundaries, and MPool failure handling. The direct varlena writer admits descriptor and area capacity before publication and rolls logical state back on writer/allocation failure. Focused exact-head parser, function, and vector tests passed; exact-head CI is green. Non-blocking cleanup: the two root CLAUDE_TODO files are historical work logs and can be removed or moved out of the repository in a follow-up.

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

Blocking findings on exact head 69f2eb6:

  • P1 — legal DECIMAL values can exceed the declared result domain (pkg/sql/plan/function/string_result_domain.go:123). The bound for every decimal family is Width + 2, but DECIMAL(M,M) needs M + 3 bytes for a negative value: sign, leading zero, decimal point, and M fractional digits. For example, CREATE TABLE t AS SELECT CONVERT(CAST(-0.99 AS DECIMAL(2,2)) USING binary) AS v; declares VARBINARY(4) while the cast produces the 5-byte value -0.99. That breaks the expression/protocol/CTAS domain invariant and can reject or truncate a legal result. Please handle Scale == Width for decimal64/128/256 and add an exact binder/runtime/CTAS regression.

  • P1 — post-cast metadata erases fixed-scalar bounds and changes public result types (pkg/sql/plan/function/func_builtin.go:859, consumed by pkg/sql/plan/function/list_builtIn.go:357). GetFunctionByName invokes return callbacks with implicit-cast target types; builtInConcatCheck replaces each fixed scalar with default VARCHAR(65535). Consequently, CREATE TABLE t AS SELECT CONCAT(CAST(1 AS SIGNED), CAST(2 AS SIGNED)) AS c; now derives TEXT(0) from 65535 + 65535, although the formatted upper bound is 40 bytes and the pre-PR result was VARCHAR. This silently changes CTAS/client metadata and indexability. The same loss of pre-cast type information affects the newly bounded CONCAT_WS/MAKE_SET/EXPORT_SET/ELT/QUOTE paths. Please preserve the original type-derived bounds (or use precise cast widths) and cover binder plus CTAS metadata.

I inspected the full PR diff and the binder → overload resolution → runtime/protocol/CTAS paths. All 27 checks are green, but they do not cover these two counterexamples.

@aptend aptend 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-review completed on exact head 184cad9. I re-read the complete review/thread history, checked the full diff, and audited the two-commit delta from my previous reviewed head 69f2eb6.

Both prior blockers are genuinely closed:

  • DECIMAL(M,M) now reserves the leading zero as well as sign and decimal point for decimal64/128/256; the -0.99 DECIMAL(2,2) binder/CTAS case declares VARBINARY(5).
  • Fixed scalar implicit VARCHAR casts now retain conservative formatted bounds, so CONCAT(int64,int64) remains VARCHAR(40), QUOTE(int64) remains VARCHAR(42), and the same mechanism covers CONCAT_WS/MAKE_SET/EXPORT_SET/ELT.

I also rechecked the approved design invariant across overload resolution, runtime writes, protocol metadata, CTAS/catalog persistence, binary/text promotion, invalid UTF-8 sizing, and allocation rollback. Focused exact-head tests passed for function, planner, parser, vector, frontend protocol, and v4.0.6 upgrade packages; go vet passed for the same touched packages. The only exact-head CI failure is the unrelated race in pkg/logservice TestTickerForTaskSchedule; SCA, coverage, build, BVT, and the remaining applicable checks passed. I found no blocking issue in the PR changes.

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

Reviewed exact head 6a92469 against merge-base b23beee.

P1 — preflight REGEXP_REPLACE before materializing an expanding result

pkg/sql/plan/function/list_builtIn.go:3078 now derives an expanding result domain, but pkg/sql/plan/function/func_builtin_regexp.go:609 calls regularReplace, and its occurrence=0 path at func_builtin_regexp.go:832 executes regexp.ReplaceAllLiteralString before any result-size or MPool admission; only afterward does line 613 append/account the completed string. With VARCHAR(40000) columns s and r containing 40,000 a/b bytes, REGEXP_REPLACE(s, a, r) tries to build about 1.6 GB from roughly 80 KB of inputs before the intended 64 MiB result limit can reject it, so one legal query can bypass query memory accounting and OOM the CN. The new low-MPool test at pkg/sql/plan/function/func_builtin_test.go:1232 covers only ordinary REPLACE, so all 28 checks miss this path. Please calculate/check the regex output bound and reserve the destination before construction, then add a low-MPool REGEXP_REPLACE regression.

@ck89119

ck89119 commented Sep 1, 2026

Copy link
Copy Markdown
Contributor Author

Thanks for the detailed REGEXP_REPLACE review. We re-checked the issue ownership and agreed that the runtime work had crossed the intended boundary between #27218 and #27217.

I reset this PR branch to 6a924695bd, the commit immediately before 5ddd9dff39, and force-updated the branch. This removes the REGEXP_REPLACE runtime preflight/match-iteration/direct-writer changes introduced in the later commits.

The ownership split is now:

The Q3/OOM findings and the runtime regression cases from this review should therefore be fixed and validated as part of #27217 rather than expanding #27218 further.

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

审查完成(base fb2868c,head d704843)。我复核了完整 PR diff、调用链与测试,并读取了我上轮 review、review threads 和 PR conversation。作者对上轮 REGEXP_REPLACE P1 的范围拆分说明已收到;但下列 P1 在当前 head 仍然存在,因此不能批准。

P1 — 在放宽 REGEXP_REPLACE 结果域后,扩张结果仍会在任何 MPool/结果大小准入之前于 Go heap 完整物化。

pkg/sql/plan/function/list_builtIn.go:3078 现在通过 replacementStringReturnType(..., true) 将扩张的合法 VARCHAR 输入结果声明为 TEXT;但执行闭环没有相应的 admission。当前 pkg/sql/plan/function/func_builtin_regexp.go:609 先调用 regularReplace,其中 func_builtin_regexp.go:816 收集全部匹配,832 再执行 regexp.ReplaceAllLiteralString;直到 613 才尝试 rs.AppendBytes。因此向量/MPool 的失败发生在完整结果已经生成之后,无法约束 Go heap。

可复现场景:以两个 VARCHAR(40000) 列分别提供 40,000 个 a 和 40,000 个 b,执行 REGEXP_REPLACE(s, a, r)。零宽界以外的普通逐字节匹配就会先构造约 1.6 GB 的字符串;64 MiB MPool 无法阻止该堆分配,CN 可以在返回可处理的内存错误前 OOM。现有低 MPool 覆盖没有触达 REGEXP_REPLACE。

请在保留该扩张结果域前,把 output-size/memory admission 放到匹配结果物化之前,并避免完整 Go string/全量匹配索引;或者撤回本 PR 对 REGEXP_REPLACE 的扩张域变更。请加入上述低 MPool 扩张回归,以及零宽匹配控制组。

@ck89119

ck89119 commented Sep 1, 2026

Copy link
Copy Markdown
Contributor Author

Addressed in e30c9b8641 by taking the second option from this review: this PR no longer expands the REGEXP_REPLACE result domain.

All three overloads now use the original source-derived VARCHAR return metadata again, and the focused result-domain test was updated accordingly. Therefore #27218 does not make the unadmitted expanding REGEXP runtime path newly reachable.

As agreed in the ownership split, output-size admission, match-memory accounting, direct writing, zero-width handling, and expanded/TEXT REGEXP runtime support remain owned by #27217 and should land there as one complete runtime change.

Validation passed:

  • ./pkg/sql/plan/function
  • ./pkg/sql/plan
  • targeted golangci-lint (0 issues)
  • git diff --check

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

Request changes on exact head e30c9b8641efb8d29835baa2437c458d1714a974 against merge-base fb2868cd974d11695dc6b8c72a7d46d10ec36232.

P1: the latest commit avoids the REGEXP_REPLACE allocation problem by restoring source-derived metadata, but that violates this PR's core result-domain invariant instead of solving it. The exact test now requires regexp_replace(VARCHAR(2), VARCHAR(1), VARCHAR(2)) to return VARCHAR(2). A concrete legal value is REGEXP_REPLACE('aa', 'a', 'bb') = 'bbbb', four bytes, so the declared domain cannot contain the runtime value. Protocol metadata and CTAS can again under-declare, reject, or truncate a legal result.

Issue #27218 explicitly includes REGEXP_REPLACE where applicable and requires expanding results plus allocation/accounting closure; the PR body likewise claims that expanding string functions and REGEXP admission are aligned. Issue #27217 owns REGEXP operand/source compatibility, not this independent output-domain/memory invariant, so deferring the runtime work there does not make a too-small static type safe.

Keep REGEXP_REPLACE on an unknown/expanding TEXT domain and preflight or stream its output before materialization, with low-MPool and zero-width-match controls, or explicitly remove it from this PR's claimed #27218 closure and leave the issue open for a separately linked result-domain fix. As submitted, the code, test, design, issue, and PR body contradict one another despite green CI.

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

审查完成:当前 head e30c9b8641efb8d29835baa2437c458d1714a974,PR merge-base fb2868cd974d11695dc6b8c72a7d46d10ec36232。我复核了完整 PR diff、相关 binder → overload → runtime/protocol/CTAS 调用链、测试、我上轮 review、review threads 与 PR conversation。作者对上轮 REGEXP_REPLACE 内存问题的范围拆分回复已收到;但下面 P1 在当前 head 仍存在,因此请求修改。

P1 — REGEXP_REPLACE 的声明结果域不能包含合法运行时结果

pkg/sql/plan/function/list_builtIn.go:3078(三个 overload 同样位于 3088、3098)现在调用 derivedStringReturnType(parameters, 0, types.T_varchar),只保留 source 的 VARCHAR 宽度;新增测试还在 pkg/sql/plan/function/string_result_domain_test.go:292 固定要求 VARCHAR(2), VARCHAR(1), VARCHAR(2) 返回 VARCHAR(2)。但合法输入 REGEXP_REPLACE('aa', 'a', 'bb') 的值为 'bbbb',长度为 4,无法落在该声明域中。结果是 expression/protocol/CTAS 元数据可把合法值声明为过小的 VARCHAR(2),从而在下游存储、客户端或严格宽度路径上拒绝、截断或错误规划该结果。

撤回扩张域避免了上轮指出的未准入物化路径,但不能使过小的静态类型安全。请要么为 REGEXP_REPLACE 恢复可容纳扩张结果的域并同时完成物化前内存准入/零宽匹配闭环,要么将此函数及其相关声明从本 PR 的结果域承诺中明确移除;并补充上述运行时 + binder/CTAS 元数据反例。

@ck89119

ck89119 commented Sep 2, 2026

Copy link
Copy Markdown
Contributor Author

Addressed in 5a10234338 by explicitly removing REGEXP from this PR’s result-domain closure, as suggested by both reviews.

This is now a complete scope removal rather than retaining an unsafe source-width assertion:

  • removed the REGEXP-specific branch from replacementStringReturnType;
  • removed the zero-width REGEXP helper test;
  • removed the regexp_replace resolver/result-domain test;
  • removed REGEXP_REPLACE and REGEXP_SUBSTR claims from the design document;
  • updated the PR body to remove REGEXP admission claims and explicitly state that REGEXP result-domain expansion plus pre-materialization admission remains open for a separately linked complete fix.

The existing upstream REGEXP_REPLACE implementation and metadata are therefore untouched by this PR. The legal expansion example and its low-MPool/zero-width controls should be covered together in that follow-up, rather than splitting an unsafe metadata change from the required runtime closure.

Validation passed:

  • ./pkg/sql/plan/function
  • ./pkg/sql/plan
  • targeted golangci-lint (0 issues)
  • git diff --check

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

审查完成(base c46d897e9645b80178568ef0783dd8e99e527222,head 5a10234338e2f07514de44f4274355b4845b9d8b)。我已复核完整 PR diff、binder → overload → runtime → protocol/CTAS 调用链、定向测试,以及我上轮 review、review threads 和 PR conversation。作者已明确移除我上轮 REGEXP 结果域/内存 P1 的范围;但以下 P1 在当前 head 仍存在,因此请求修改。

P1 — EXPORT_SET 新声明的 BLOB 结果域缺少物化前的结果大小与 MPool 准入。

pkg/sql/plan/function/list_builtIn.go:270-296 将 BLOB/未知宽度 operand 的 64 段输出提升为 BLOB,因而 CTAS/协议可合法消费大结果;但 runtime 的 pkg/sql/plan/function/func_binary.go:6032-6043 先收集至多 64 个片段并用 strings.Join 完整拼接,之后才调用 rs.AppendBytes。例如在 64 MiB MPool 下,EXPORT_SET(CAST(-1 AS SIGNED), CAST(REPEAT('a', 2097152) AS BLOB), '', '', 64) 会先在 Go heap 构造约 128 MiB 字符串(随后还会有 []byte 副本);MPool 和 BLOB 的 64 MiB 上限都来不及约束,CN 可在返回可处理的内存错误前 OOM。

请在拼接前执行 checked output-size/MPool admission,并直接写入已准入的 destination(或将结果流式构造);同时新增覆盖该低 MPool 扩张路径及 64 位边界的回归。

Comment thread pkg/sql/plan/function/list_builtIn.go 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.

审查完成(base c46d897e9645b80178568ef0783dd8e99e527222,head a5e96e55ca7056af5427bcfe107e376cb1a83f33)。我重新核验了完整 PR diff、result-domain 推导到 binder/overload/runtime/vector 写入及 protocol/CTAS 路径、定向回归,并读取了我上轮 review、所有 review threads 与 PR conversation。

上轮 P1 已闭环:EXPORT_SET 现在在 pkg/sql/plan/function/func_binary.go 中以 on/off 位数和 separator 先计算 checked 精确字节数;超限返回 NULL,合法值经 AppendBytesWithWriter 在写入前完成 descriptor/area/MPool 准入,直接写入目标 area,不再通过 []string/strings.Join 完整物化。对应 thread 中作者已明确回复;新增覆盖了 64 位边界和低 MPool 的 64 段扩张路径。

我未发现当前 head 仍存的 P0/P1,也没有新的 P2/P3。当前 28 个 check 均已结束(成功或中性保护项)。

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

Reviewed exact head a5e96e5 against merge base c46d897.

The change closes the complete result-domain chain: checked known/unknown width arithmetic and binary promotion feed overload selection and binder literal refinement; parser/formatter round trips preserve CHAR and CONVERT USING semantics; direct varlena writers admit descriptor and area capacity before publication and roll back failed appends; runtime REPEAT, PAD, REPLACE, INSERT, QUOTE, and EXPORT_SET sizes match their declared domains; and protocol, CTAS, DESC, information_schema, invalid UTF-8, mask, overflow, and low-MPool controls cover the consumers. REGEXP expansion remains outside this PR consistently. Exact-head substantive CI is terminal green.

I found no remaining correctness, lifecycle, memory-admission, compatibility, or metadata blocker.

@mergify

mergify Bot commented Sep 3, 2026 •

Copy link
Copy Markdown
Contributor

Merge Queue Status

  • ✅ Entered queue — 2026-09-03 01:47 UTC · Rule: main · triggered by rule Automatic queue on approval for main
  • ✅ Checks passed · in-place
  • ✅ Merged — 2026-09-03 03:15 UTC · at 20b43edbf2ddd1667ca0492c806a950b748d9e6b · squash

This pull request spent 1 hour 27 minutes 34 seconds in the queue, including 44 minutes 40 seconds running CI.

Required conditions to merge
  • #review-threads-unresolved = 0 [🛡 GitHub branch protection]
  • github-review-approved [🛡 GitHub branch protection]
  • any of [🛡 GitHub branch protection]:
    • check-success = Matrixone CI / UT Test on Ubuntu/x86
    • check-neutral = Matrixone CI / UT Test on Ubuntu/x86
    • check-skipped = Matrixone CI / UT Test on Ubuntu/x86
  • any of [🛡 GitHub branch protection]:
    • check-success = Matrixone CI / SCA Test on Linux/arm64
    • check-neutral = Matrixone CI / SCA Test on Linux/arm64
    • check-skipped = Matrixone CI / SCA Test on Linux/arm64
  • any of [🛡 GitHub branch protection]:
    • check-success = Matrixone Compose CI / multi cn e2e bvt test docker compose(PROXY)
    • check-neutral = Matrixone Compose CI / multi cn e2e bvt test docker compose(PROXY)
    • check-skipped = Matrixone Compose CI / multi cn e2e bvt test docker compose(PROXY)
  • any of [🛡 GitHub branch protection]:
    • check-success = Matrixone Utils CI / Coverage
    • check-neutral = Matrixone Utils CI / Coverage
    • check-skipped = Matrixone Utils CI / Coverage
  • any of [🛡 GitHub branch protection]:
    • check-success = Matrixone UT Coverage / UT Coverage on Ubuntu/x86
    • check-neutral = Matrixone UT Coverage / UT Coverage on Ubuntu/x86
    • check-skipped = Matrixone UT Coverage / UT Coverage on Ubuntu/x86
  • any of [🛡 GitHub branch protection]:
    • check-success = Matrixone Standlone CI / multi CN e2e BVT Test on Linux/x64(COMPOSE, PESSIMISTIC)
    • check-neutral = Matrixone Standlone CI / multi CN e2e BVT Test on Linux/x64(COMPOSE, PESSIMISTIC)
    • check-skipped = Matrixone Standlone CI / multi CN e2e BVT Test on Linux/x64(COMPOSE, PESSIMISTIC)

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 kind/documentation Improvements or additions to documentation kind/test-ci size/XXL Denotes a PR that changes 2000+ lines

Projects

None yet

Development

Successfully merging this pull request may close these issues.

6 participants