Skip to content

fix variables - #26762

Merged
mergify[bot] merged 59 commits into
matrixorigin:mainfrom
daviszhen:0806-fix-var
Aug 19, 2026
Merged

mergify[bot] merged 59 commits into
matrixorigin:mainfrom
daviszhen:0806-fix-var

Conversation

@daviszhen

@daviszhen daviszhen commented Aug 6, 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 #25123

#24492

What this PR does / why we need it:

  • 支持未赋值用户变量读取返回 NULL,不再报 “user variable does not exist”。

  • 支持 SELECT ... INTO @var,包括多变量赋值、空结果不覆盖旧值、多行结果报错。

  • 修复用户变量数值表达式:

    • SET @A = 1, @b = 2;
    • SELECT @A + @b;
    • 现在返回 3.0,不再报 TEXT TEXT 类型错误。
  • 修复 prepared statement 参数数值上下文:

    • prepare ps_count from 'select ? + ? as sum_val';
    • execute ps_count using @c1, @c2;
    • 现在可正常返回 3.0。
  • 补充了 planner 单测和 BVT case:

    • pkg/sql/plan/user_variable_numeric_test.go
    • test/distributed/cases/expression/mysql_compat_user_variables.sql
    • test/distributed/cases/expression/mysql_compat_user_variables.result

@daviszhen
daviszhen requested a review from a user August 6, 2026 11:17
@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 →

@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 the complete diff from merge-base 6798bd63884c3fb363589565f925fd16f94eccbe to head 2b290fc5f5c05f3be1105316f42a4c82df23b04b, including parser generation, frontend compile/execute paths, prepared reuse, planner binding, and tests. Requesting changes for two P1 correctness issues; one P2 performance issue is also recorded inline. No P0 or P3 findings.

Comment thread pkg/frontend/status_stmt.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.

Request changes on exact head 2b290fc5f5c05f3be1105316f42a4c82df23b04b.

I independently traced the parser → planner → frontend/status execution paths and found three blocking correctness gaps:

  1. SELECT ... INTO @vars validates expression/variable cardinality only after receiving a non-empty batch. select 1 where false into @a, @b therefore succeeds and leaves the variables untouched, while MySQL 8.4 rejects it with error 1222 regardless of row count. I reproduced the silent success through MatrixOne's embedded SQL path; the structural check must be independent of runtime result cardinality.
  2. The background execution path installs and fills selectIntoUserVariables, but executeStatusStmtInBack only calls runner.Run and never calls apply. Stored-procedure SQL uses this path, so SELECT ... INTO @var can report success without assigning the variable.
  3. Capture keeps only []any and assignment calls SetUserDefinedVar, which hard-codes IsBin=false. Binary-string metadata from the result vector is therefore lost. Later prepared execution (EXECUTE ... USING @v) consults ResolveVariableIsBin, so values assigned by this new syntax can change type/lookup semantics compared with the existing SET path.

There is also an avoidable unhappy-path cost: the collector detects a second row but does not stop execution, and reports the error only after the entire query has completed. Large inputs continue scanning and transporting rows after the outcome is already known.

Focused parser, planner, frontend, and collector tests pass, but they do not cover these execution/metadata/zero-row boundaries. The zero-row counterexample fails against this head exactly because MatrixOne returns nil error.

@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 the exact head. Requesting changes for three P1 correctness gaps. First, pkg/frontend/select_into_user_variables.go:61 returns before validating expression and variable arity for a zero-row result, so SELECT 1 WHERE FALSE INTO @A,@b silently succeeds. Validate structural arity independently of runtime batches. Second, line 91 stores only the extracted value and loses the source vector binary flag; preserve per-column IsBin metadata and use the binary-aware setter because EXECUTE USING depends on it. Third, the background and stored-procedure path installs the collector but executeStatusStmtInBack never calls apply, so SELECT INTO reports success without assigning variables. Also return the too-many-rows error as soon as rowCount exceeds one instead of scanning the remaining result.

@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-reviewed updated exact head 2f31e8830f1cd5e27851914226b3a0601a4f10f4. The previous 0/1/N-row cardinality defect is fixed: warnings are now generated at actual remote execution and carried back in the terminal envelope. One new resource-safety blocker remains.

[P1] Bound remote warning retention; one warning per row currently grows outside the query memory budget.

remoteWarningCollector.AppendWarningDiagnostic appends every row-level warning to an unbounded Go slice (pkg/sql/compile/remote_warnings.go:34-51). The collector lives for the whole remote fragment. At terminal, SnapshotWarnings copies the entire slice (:54-60), and setTerminalAnalysis then retains it again in the envelope and JSON-marshals all entries (remoterunServer.go:389-391,1187-1195).

A remote scan of N invalid text values therefore retains O(N) warning structs/messages on the Go heap until terminal, outside the process mpool limit. Large N can OOM the CN; before that, the unbounded terminal JSON can exceed practical RPC/message limits. This is newly introduced by moving diagnostics to the actual row execution boundary. The initiating frontend session is bounded by its diagnostic storage policy (default 64); applying that bound only after transport is too late.

Please separate total warning count from bounded retained diagnostics at the remote collector/protocol boundary, honor the session/engine storage limit, and merge totals plus the capped SHOW WARNINGS records across descendant fragments. Add a high-cardinality test proving retained memory/message size is bounded while 0/1/N warning-count semantics remain correct.

Unhappy-path audit results:

  • Q1: collector ownership reaches one terminal snapshot; client duplicate terminal merge is guarded by terminalSeen.
  • Q2: no new wait/deadlock edge found; success and error terminals both carry the envelope.
  • Q3: failed as above—no capacity, truncation, aggregation, or earlier release exists before terminal.

Validation on the exact head passed:

  • focused remote warning execution/forwarding tests under -race -count=3
  • complete pkg/sql/compile package via the CGo wrapper
  • diff check and remote CI 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 on exact head 22b2e96.

The previous resource-safety blocker is closed. Remote warning collection now separates the total count from bounded retained diagnostics, caps each fragment before terminal JSON construction, merges descendant totals without recounting retained records, and applies the aggregate through the session/back-session sinks. I rechecked success/error terminal envelopes, duplicate-terminal protection, multi-fragment accumulation, frontend warning-count saturation, retained SHOW WARNINGS ordering, and the earlier user-variable execution paths; no remaining blocker found.

Validation passed on the exact head: full pkg/sql/compile and pkg/frontend tests; focused collector/terminal/frontend race tests; repeated high-cardinality retention and total-count tests; go build; go vet; and diff hygiene.

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

Deep re-review of exact head 22b2e96d759b58b61c2f533542688a9c78befceb, incorporating the full review history. The latest commit closes the prior unbounded-retention blocker: remote fragments now separate total warning count from bounded retained diagnostics, propagate descendant totals, and merge them into the frontend session. The earlier SELECT-INTO ownership/type/cache fixes also remain intact. One P1 cardinality blocker remains.

[P1] Make warnings for a folded user-variable coercion follow logical output-row cardinality, not physical batch fragmentation.

foldVarExprsInExprInPlace turns @s into a constant before remote execution. For SELECT @s + 0 FROM t, the cast therefore receives a const input vector. strToFloatWithProc calls appendNumericCoercionWarning while iterating that physical const vector, so it appends once even when the result vector represents multiple evaluated rows. This exact head already contains the minimal witness in TestRemoteNumericCastWarningAppearsAtExecution: the input and result both have two rows, but line 112 explicitly asserts only one warning.

I changed only that oracle from 1 to 2 in the isolated exact-head worktree and ran the focused test under the required CGo wrapper. It failed with: should have 2 item(s), but has 1. After restoring the file, the original focused compile warning tests and focused frontend diagnostic/SELECT-INTO tests pass.

This violates the PR's own Matrix D4 contract (“one warning per evaluated row”) and makes the observable warning count depend on batching: one two-row batch produces one warning, while two one-row batches can produce two. Please account for the logical evaluation cardinality when the coercion source is const, and retain a metamorphic regression proving identical counts for the same 0/1/N logical rows under different batch layouts.

@daviszhen

Copy link
Copy Markdown
Contributor Author

Deep re-review of exact head 22b2e96d759b58b61c2f533542688a9c78befceb, incorporating the full review history. The latest commit closes the prior unbounded-retention blocker: remote fragments now separate total warning count from bounded retained diagnostics, propagate descendant totals, and merge them into the frontend session. The earlier SELECT-INTO ownership/type/cache fixes also remain intact. One P1 cardinality blocker remains.

[P1] Make warnings for a folded user-variable coercion follow logical output-row cardinality, not physical batch fragmentation.

foldVarExprsInExprInPlace turns @s into a constant before remote execution. For SELECT @s + 0 FROM t, the cast therefore receives a const input vector. strToFloatWithProc calls appendNumericCoercionWarning while iterating that physical const vector, so it appends once even when the result vector represents multiple evaluated rows. This exact head already contains the minimal witness in TestRemoteNumericCastWarningAppearsAtExecution: the input and result both have two rows, but line 112 explicitly asserts only one warning.

I changed only that oracle from 1 to 2 in the isolated exact-head worktree and ran the focused test under the required CGo wrapper. It failed with: should have 2 item(s), but has 1. After restoring the file, the original focused compile warning tests and focused frontend diagnostic/SELECT-INTO tests pass.

This violates the PR's own Matrix D4 contract (“one warning per evaluated row”) and makes the observable warning count depend on batching: one two-row batch produces one warning, while two one-row batches can produce two. Please account for the logical evaluation cardinality when the coercion source is const, and retain a metamorphic regression proving identical counts for the same 0/1/N logical rows under different batch layouts.

  • 提交:89d065e569
  • 对字符串→数值转换禁止常量折叠,确保每个逻辑输出行都执行转换并生成 warning。
  • 新增单批 [2]、拆批 [1,1]、空批 [0] 回归测试,warning 数量稳定为 2/2/0。
  • focused compile/colexec 测试、race 测试、go vet、git diff --check 均通过。

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

Deep re-reviewed the exact current head with the complete review history. The last blocker is closed: string-to-numeric function executors are kept non-folded, so a folded user-variable source is still converted once per logical output row. The new metamorphic regression covers one two-row batch, two one-row batches, and an empty batch, preserving 2/2/0 warning counts independently of physical batching. I also rechecked the bounded remote-warning collector/terminal propagation and the earlier SELECT-INTO ownership, cache, type, prepared-value, and diagnostic closures. Current CI is terminal with no failures. No remaining blocking issue found.

@daviszhen

Copy link
Copy Markdown
Contributor Author

@mergify queue

@mergify

mergify Bot commented Aug 19, 2026 •

Copy link
Copy Markdown
Contributor

Merge Queue Status

  • ✅ Entered queue — 2026-08-19 04:59 UTC · Rule: main · triggered by @daviszhen with the @mergifyio queue command
  • ✅ Checks skipped · PR is already up-to-date
  • ✅ Merged — 2026-08-19 04:59 UTC · at 2cd2ed6cf91cce96690624f242cd0d2cd8e37097 · squash

This pull request spent 40 seconds in the queue, including 2 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)

@daviszhen

Copy link
Copy Markdown
Contributor Author

@mergify refresh

@mergify

mergify Bot commented Aug 19, 2026

Copy link
Copy Markdown
Contributor

refresh

✅ Pull request refreshed

@daviszhen

Copy link
Copy Markdown
Contributor Author

@Mergifyio queue

@mergify

mergify Bot commented Aug 19, 2026

Copy link
Copy Markdown
Contributor

queue

☑️ Command queue ignored because it is already running from a previous command.

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/XXL Denotes a PR that changes 2000+ lines

Projects

None yet

Development

Successfully merging this pull request may close these issues.

7 participants