Skip to content

[Bug]: executable comments /*!NNNNN*/ always run - no version gate in the MySQL dialect lexer #31056

Closed

Description

@iamlinjunhong

Branch Name: main

Commit ID: 6fb6531

Other Environment Information

  • Hardware parameters: Apple Silicon (arm64), 10 cores
  • OS type: macOS (darwin), Go 1.27.1
  • Others: MatrixOne single-node mo-service (LOG/TN/CN in one process) built from the commit above, default launch topology with all ports shifted (LOOM_TEST_PORT_OFFSET); the server advertises itself as MySQL 8.0.30 (= version 80030) in the handshake; control server: MySQL 8.0.46 (80046); client: mysql CLI

Actual Behavior

Executable comments (/*!NNNNN body */) have NO version gate in the MySQL dialect - the body is parsed and executed for ANY version number:

  • /*!99999 SELECT 42 */; -> MatrixOne executes the body and returns row 42. MySQL 8.0.46: OK, empty result (99999 > 80046, body skipped as a plain comment).
  • SELECT /*!99999 6 */; -> MatrixOne returns 6. MySQL: ERROR 1064 near '' at line 1 (body dropped, select list is empty).
  • SELECT /*!80047 6 */; -> MatrixOne returns 6. MySQL 8.0.46: ERROR 1064 near '' (80047 > 80046 -> skip; 80047 > MatrixOne's own advertised 80030, so the skip applies to it too).
  • SELECT 2 /*!999999999 */; -> MatrixOne: ERROR 1064 near "9999 */" - the version reader consumes exactly 5 digits and leaks the remaining 9999 */ into the statement token stream. MySQL: returns 2 (version digits never leak; the comment is skipped wholesale).

Expected Behavior

MySQL semantics: the version embedded in /*!NNNNN ... */ is compared with the server's own version. If NNNNN <= server version the body is parsed as SQL; otherwise the ENTIRE comment (including all version digits and the closing */) is skipped like a plain comment. MatrixOne advertises 8.0.30 in its handshake, therefore:

  • 99999 -> skip; 80047 -> skip;
  • 80030 or lower matching forms -> execute;
  • version digit sequences of any length are consumed inside the comment scan and may never leak into the statement (SELECT 2 /*!999999999 */ must yield 2).

Steps to Reproduce

Pure unit repro, no server needed - full test source (verified FAILING on commit 6fb6531):

package parsers

import (
	"context"
	"testing"

	"github.com/matrixorigin/matrixone/pkg/sql/parsers/dialect"
	"github.com/matrixorigin/matrixone/pkg/sql/parsers/tree"
)

func TestReportAExecutableCommentVersionGate(t *testing.T) {
	ctx := context.Background()

	// 99999 > any server version: the body must be skipped => empty statement.
	stmts, err := Parse(ctx, dialect.MYSQL, "/*!99999 select 42 */;", 1)
	if err != nil {
		t.Fatalf("parse failed: %v", err)
	}
	if len(stmts) != 0 {
		t.Errorf("A1: version 99999 can never match, so the body must be dropped; MatrixOne still built %d statement(s), first is %T", len(stmts), stmts[0])
		if sel, ok := stmts[0].(*tree.Select); ok {
			t.Logf("A1: *tree.Select inner field type: %T", sel.Select)
		}
	}

	// After dropping, nothing remains => MySQL returns ERROR 1064 near ''.
	if _, err := Parse(ctx, dialect.MYSQL, "select /*!99999 6 */", 1); err == nil {
		t.Errorf("A2: select-list content gated behind version 99999 was executed; MySQL skips it and errors near ''")
	}

	// Overlong version numbers are capped by MySQL, the whole comment is
	// skipped, so the outer statement must still parse.
	if _, err := Parse(ctx, dialect.MYSQL, "select 2 /*!999999999 */", 1); err != nil {
		t.Errorf("A3: legal MySQL statement rejected due to the 5-digit-only version reader, got: %v", err)
	}

	// Regression guard: a version that does match MO's advertised 80030 must
	// still run the body.
	if _, err := Parse(ctx, dialect.MYSQL, "select /*!80030 6 */", 1); err != nil {
		t.Errorf("A4: matching-version executable comment must still parse: %v", err)
	}
}

Run:

go test ./pkg/sql/parsers -run '^TestReportAExecutableCommentVersionGate$' -count=1 -v

Current output: A1 (1 statement built from a 99999-gated body), A2 (select /*!99999 6 */ parsed OK), A3 (select 2 /*!999999999 */ rejected) - see evidence. A4 is a regression guard that passes today and must keep passing after the fix.

SQL-level, against a running server:

  1. mysql ... -e "/*!99999 SELECT 42 */;" -> returns 42 (expected: OK, no rows).
  2. mysql ... -e "SELECT /*!99999 6 */;" -> returns 6 (expected ERROR 1064 near '').
  3. mysql ... -e "SELECT 2 /*!999999999 */;" -> ERROR 1064 near "9999 */" (expected: 2).
  4. Same statements on a real MySQL 8.0.46 -> empty OK / ERROR near '' / 2 (full outputs in evidence).

Additional information

  • Root cause (scanner, MySQL dialect): on seeing /*! the scanner calls readVersion() (pkg/sql/parsers/dialect/mysql/scanner.go:309) which only VALIDATES that 5 digit characters exist and consumes them (scanner.go:439-451: for i := 0; i < 5; i++ { if !isDigit(s.cur()) { return false }; s.inc() }; return true). The parsed value is NEVER compared with any server version - the scanner has no version notion at all, so the gating decision ("execute body vs treat whole comment as plain comment") is never made.
  • Two divergence classes result: (1) gated bodies always execute - statements wrapped in a beyond-any-version guard that MySQL clients expect to be ignored are silently run; (2) version numbers longer than 5 digits leak their leftover digits into the token stream, turning perfectly legal MySQL statements into syntax errors.
  • Related but separate: issue [Bug]: statement split cuts inside executable comments, valid /*!50000 select 1; select 2 */ fails #30154 / PR fix(parser): preserve executable comments across statement splits #30177 fixed executable-comment handling in SplitSqlByStatement (statement splits cutting INSIDE comments); they do not touch version gating, which remains unimplemented. A live helper ExtractMysqlComment (scanner.go:762-782) already extracts (version, innerSQL) and tolerates 6-digit version runs, but nothing in the scan path calls it; the commented-out scanMySQLSpecificComment (scanner.go:736-759) shows the originally intended mechanism that was never wired up.
  • Recommended fix: in readVersion (or its callers) parse the whole digit run (not just the first 5 chars), compare against the server's advertised MySQL-compatible version (8.0.30 -> 80030, ideally sourced from the same constant the frontend uses in the handshake), and on mismatch skip to the matching */ as a plain comment. Keep /*!80030 ... */ executing (regression guard A4).
Full reproduction, exactly as Loom ran it
Run on commit 6fb6531432 (single command, no server needed):
  go test ./pkg/sql/parsers -run '^TestReportAExecutableCommentVersionGate$' -count=1 -v
Current build: FAIL (A1/A2/A3 fire; A4 regression guard passes) - bug reproduced.

Full test file source:
```
package parsers

import (
	"context"
	"testing"

	"github.com/matrixorigin/matrixone/pkg/sql/parsers/dialect"
	"github.com/matrixorigin/matrixone/pkg/sql/parsers/tree"
)

func TestReportAExecutableCommentVersionGate(t *testing.T) {
	ctx := context.Background()

	// 99999 > any server version: the body must be skipped => empty statement.
	stmts, err := Parse(ctx, dialect.MYSQL, "/*!99999 select 42 */;", 1)
	if err != nil {
		t.Fatalf("parse failed: %v", err)
	}
	if len(stmts) != 0 {
		t.Errorf("A1: version 99999 can never match, so the body must be dropped; MatrixOne still built %d statement(s), first is %T", len(stmts), stmts[0])
		if sel, ok := stmts[0].(*tree.Select); ok {
			t.Logf("A1: *tree.Select inner field type: %T", sel.Select)
		}
	}

	// After dropping, nothing remains => MySQL returns ERROR 1064 near ''.
	if _, err := Parse(ctx, dialect.MYSQL, "select /*!99999 6 */", 1); err == nil {
		t.Errorf("A2: select-list content gated behind version 99999 was executed; MySQL skips it and errors near ''")
	}

	// Overlong version numbers are capped by MySQL, the whole comment is
	// skipped, so the outer statement must still parse.
	if _, err := Parse(ctx, dialect.MYSQL, "select 2 /*!999999999 */", 1); err != nil {
		t.Errorf("A3: legal MySQL statement rejected due to the 5-digit-only version reader, got: %v", err)
	}

	// Regression guard: a version that does match MO's advertised 80030 must
	// still run the body.
	if _, err := Parse(ctx, dialect.MYSQL, "select /*!80030 6 */", 1); err != nil {
		t.Errorf("A4: matching-version executable comment must still parse: %v", err)
	}
}
```

SQL-level check of the same behavior against a server (mysql CLI):
  mysql --protocol=TCP -h 127.0.0.1 -P <port> -u root --default-character-set=utf8mb4 --force -e "/*!99999 SELECT 42 */; SELECT /*!99999 6 */; SELECT 2 /*!999999999 */;"
MatrixOne: row 42 / row 6 / ERROR 1064 near "9999 */". Real MySQL 8.0.46: empty OK / ERROR 1064 near '' / row 2.

Found by Loom bug hunt (module: sql-parser; tests: unit, black-box; severity: S1)

Activity

  1. added
    kind/bug
    severity/s1
    on Oct 24, 2026
  2. XuPeng-SH commented on Nov 1, 2026

    @XuPeng-SH
    Contributor

    QA handoff (not acceptance): PR #31168 has merged into main at 9860cb0c6ddb12273393724ac59bbb83c4268996 on 2026-11-01. The scanner now consumes the complete immediate ASCII version-digit run with bounded arithmetic and gates executable comments against the fixed MySQL compatibility baseline 80030. Future bodies are skipped as complete block comments; matching/lower/unversioned bodies retain execution. The default handshake shares the compatibility version constants; a custom display prefix does not change the SQL baseline.

    Evidence reviewed: the merged 14-file change, this issue's full discussion (no prior comments), and PR discussion/reviews. The previous request for BVT coverage was completed. The author reports real frontend COM_QUERY checks and two 20/20 mo-tester executable-comment runs, plus scoped vet/lint/build checks. The independent PR review reports focused parser/scanner, cancellation/work-budget, numeric-oracle and frontend checks. These are remote author/reviewer reports, not tests executed by this handoff run; some evidence predates the final merge. No current applicable verified counterexample or unfinished development follow-up was found.

    Please verify on the merged main SHA: future 99999/80031/80047 guards; matching 80030/lower/unversioned controls; overlong and leading-zero digit runs without token leakage; ignored SET statements without session-mode side effects; multi-statement splitting/continuation, bind numbering, malformed/unterminated comments and connection recovery. Preserve the documented boundary: 1–4 digit guards remain invalid; whole-run handling of nonstandard long guards is an intentional extension, and nested-comment support is unchanged. Include ordinary-query/parser performance controls if relevant; earlier short scanner/SQL benchmarks do not establish end-to-end regression absence.

    This round did not run local tests, full race/BVT or multi-CN/performance validation. Reassigning to Ariznawlll for QA verification, not declaring the issue passed or requesting a 4.2 backport.

  3. Ariznawlll commented on Nov 2, 2026

    @Ariznawlll
    Collaborator

    结论

    测试通过。MySQL 风格可执行注释按兼容版本门控,未来版本的内容不会执行,匹配和低版本内容仍可执行。

    关键证据

    • 版本和环境:官方 main@d24f446e1e94a58c329d422519f7aad621cdcd05,修复 fix(parser): gate executable comments by MySQL version #31168 的 merge 9860cb0c6ddb12273393724ac59bbb83c4268996 为祖先;本地隔离单 CN / TN / LogService,服务 git_version() 与二进制构建 SHA 一致,vcs.modified=false。
    • Happy Path:真实 SQL 3/3 验证 80030、较低版本及无版本注释内容执行;高版本独立语句不返回行,超长版本号被整体跳过,外层 SELECT 2 正常返回 2;前导零版本处理及多语句 SELECT 1; ...; SELECT 2 保持顺序。预处理语句中被忽略注释里的 ? 不占参数位置,正常绑定得到 7。
    • Unhappy Path:99999、80031、80047 导致空 SELECT 列表、1–4 位版本号和未终止注释均按预期报 1064;每次报错后同一连接可执行 SELECT 42。未来版本注释中的 SET sql_mode 被跳过,前后会话模式完全一致。parser / scanner 的版本门控、分句、工作量限制及相关边界测试在 -race -count=3 下通过。
    • 回归:MOTR #298 新增实服 SQL 回归,MOTR runner 3/3;离线 CI通过,该 CI 不等同于执行了此实服 SQL。

    待解决点

    • 本轮未做多 CN、生产负载及端到端性能基准;1–4 位版本号保持不支持,嵌套注释语义不在此修复范围。
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

kind/bugseverity/s1

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions