Skip to content

feat: MySQL SQLSTATEs, opt-in txn-fatal errors (mo_rollback_txn_on_error), and typed mo.sql errors - #27611

Merged
fengttt merged 16 commits into
matrixorigin:mainfrom
fengttt:feat-dupkey-sqlstate-txn
Aug 27, 2026
Merged

fengttt merged 16 commits into
matrixorigin:mainfrom
fengttt:feat-dupkey-sqlstate-txn

Conversation

@fengttt

@fengttt fengttt commented Aug 25, 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 #27610

What this PR does / why we need it:

Three changes to how a constraint violation is reported and what it does to an open transaction.

1. SQLSTATE now matches MySQL

MO reported a duplicate key as error 1062 with SQLSTATE HY000. MySQL pairs 1062 with 23000, the integrity-constraint-violation class, and clients route on that class:

  • JDBC picks the SQLException subclass from the SQLSTATE class, so a duplicate key never arrived as SQLIntegrityConstraintViolationException — only as a plain SQLException.
  • Anything classifying errors by SQLSTATE class saw "general error" for every constraint violation.

MO already carries MySQL's own table in pkg/common/moerr/mysql_error_define.go, so the fix is to stop ignoring it. 29 errors used MySQLDefaultSqlState where MySQL defines a specific SQLSTATE; all 29 now use MySQL's:

error MySQL code was now
ErrDuplicateEntry 1062 HY000 23000
ErrNoSuchTable 1146 HY000 42S02
ErrBadDB 1049 HY000 42000
ErrOutOfRange 1264 HY000 22003
ErrDivByZero 1365 HY000 22012
ErrSyntaxError / ErrParseError 1064 / 1149 HY000 42000

…and 23 more, all derived from MO's own MySQL table rather than hand-picked.

TestSqlStateMatchesMySQL keeps the two from drifting again. It has one deliberate exception: SQLSTATE class 01 is the warning class, which MySQL attaches to a warning and never to an ERR packet — a client reads class 01 as "succeeded, with a warning". ErrWarnDataTruncated (MySQL 1265, SQLSTATE 01000) is delivered by MO as an error, so copying the warning SQLSTATE would misreport it; HY000 stays there and the test documents why.

Nothing inside MO branches on SQLSTATE — it is only forwarded to the wire (protocol.go, util.go) — so this changes what clients see and nothing else. One existing test asserted the old ErrBadDB value and is updated.

Verified on a live server:

ERROR 1062 (23000): Duplicate entry '1' for key 'a'
ERROR 1146 (42S02): SQL parser error: table "nosuchtable" does not exist
ERROR 1049 (42000): Unknown database nosuchdb

2. mo_rollback_txn_on_error

A failed statement rolls back the statement, not the transaction — MySQL's behaviour, and still MO's default:

BEGIN;
INSERT INTO t VALUES (20, 'twenty');
INSERT INTO t VALUES (1, 'dup');       -- ERROR 1062 (23000)
INSERT INTO t VALUES (21, 'twentyone');
COMMIT;                                -- 20 and 21 both commit

That is the default for almost every error. Of the ~240 codes MO defines, only twelve abort a transaction, and all twelve are infrastructure failures after which it cannot continue anyway (errCodeRollbackWholeTxn): CN rolling restart, deadlock, the lock-table/lock-conflict codes, two lock timeouts, unknown transaction state, and three backend-connection failures. A duplicate key is not special — a syntax error, a bad type conversion and a missing table behave identically.

Some applications treat any failed statement as fatal to their unit of work:

SET mo_rollback_txn_on_error = 1;

With it on, any error rolls back the whole transaction, including work done before the failure. Session and global scope, dynamic, boolean, default 0.

Only errors, never warnings. moerr codes are banded: 0..99 Ok signals, 100..101 Info, 200..201 Warning, and every real error at or above ErrStart (20100). The new Error.IsRealError() is that boundary and the setting gates on it, so a warning — which travels as the same type — can never discard a transaction. In practice no SQL statement currently reaches the frontend with a warning-coded result (an over-long value is a real error in strict mode and is accepted silently in non-strict mode), so the exemption is defensive and is asserted in Go rather than BVT.

Why a session variable and not the static set. Every member of that set is an infrastructure failure. Moving data errors into it would change the default away from MySQL for everyone, and would apply to background and internal executors too, where an error can be benign. The second risk is handled structurally rather than by convention: the variable has global scope, but backSession.GetSessionSysVar answers nil outside its small allowlist, so a background session never opts in even when it is set globally — with a test to pin that.

3. mo.sql returns a structured error

Starlark has no exceptions, so the mo module returns [result, ok] with ok None on success. ok was err.Error() — a bare string — so a procedure could only match on message text:

if err != None and "Duplicate entry" in err:      # brittle

The value now carries its codes:

rs, err = mo.sql("insert into t values (1, 'dup')")
if err != None and err.code == 1062:              # the error CLASS
    ...
expression value
err.code MySQL error number, e.g. 1062 (0 when the failure is not a moerr)
err.sqlstate "23000"
err.message the message text
str(err), "x: " + err, err + " y" the message
bool(err) True
err == None False on failure, True on success
out_param = err the message string

Everything a procedure could already do with the value keeps working, so this is additive rather than breaking.

Design notes: docs/design/duplicate_key_error_semantics.md.

Tests

Level What it proves
pkg/common/moerr TestSqlStateMatchesMySQL every error carrying a MySQL error number reports MySQL's SQLSTATE; warning class excluded, with the reason recorded
pkg/common/moerr TestDuplicateEntrySqlState 1062 / 23000 specifically
pkg/frontend TestSessionRollsBackTxnOnError the opt-in is per session, applies to any real error (six kinds driven), and is off by default
pkg/frontend TestStaticRollbackSetIsInfrastructureOnly data errors stay out of the infrastructure set, while a genuine infrastructure error still ends the transaction
pkg/common/moerr TestIsRealError the Ok / Info / Warning / error bands and that the boundary is exactly ErrStart
pkg/frontend TestWarningsNeverRollBackTxn a warning or info never rolls back a transaction even with the setting on, while a real error does
pkg/frontend TestBackgroundSessionNeverRollsBackWholeTxn a background session cannot inherit the setting, even globally
BVT pessimistic_transaction/rollback_txn_on_error end to end: the default keeps the transaction for a duplicate key and for an unrelated error; opted in, a duplicate key, an unknown column, a bad type and a missing table each discard it including earlier work; global scope is inherited by a new session but not the setting one
BVT procedure/starlark_sql_error err.code / err.sqlstate / err.message, dir(err), truthiness, concatenation, None on success, and the OUT-parameter form still yielding the message

pkg/common/moerr and pkg/frontend pass; both new BVT cases pass in compare mode; the procedure suite is 211/211.

One thing found along the way

mo-tester strips leading whitespace from each line of a case, and Starlark is indentation-sensitive, so an indented procedure body reaches the server dedented and fails with got identifier, want indent. The existing sp_ins2_sum golden in starlark_sql.result records exactly that failure rather than the intended behaviour. The new case therefore uses conditional expressions instead of if/else blocks, and says so in a comment. Fixing mo-tester is the better answer but it lives in another repository.

…mo.sql errors

Three changes to how a constraint violation is reported and what it does.

1. SQLSTATE now matches MySQL. MO sent error 1062 with SQLSTATE HY000;
   MySQL pairs 1062 with 23000, the integrity-constraint class, and clients
   route on that class -- JDBC picks the SQLException subclass from it, so a
   duplicate key never arrived as SQLIntegrityConstraintViolationException.
   MO already carried MySQL's own table in mysql_error_define.go, so the fix
   is to stop ignoring it: 29 errors that used MySQLDefaultSqlState where
   MySQL defines a specific SQLSTATE now use MySQL's (1146 -> 42S02,
   1049 -> 42000, 1264 -> 22003, 1064 -> 42000, and so on).

   TestSqlStateMatchesMySQL keeps the two tables from drifting again. It
   deliberately excludes SQLSTATE class 01, the WARNING class: MySQL attaches
   it to a warning, never to an ERR packet, and a client reads class 01 as
   "succeeded, with a warning", so copying it onto ErrWarnDataTruncated would
   misreport that error. HY000 stays there.

   Nothing inside MO branches on SQLSTATE -- it is only forwarded to the wire
   -- so this changes what clients see and nothing else. One test asserted
   the old value for ErrBadDB and is updated.

2. mo_rollback_txn_on_duplicate_key (session/global, dynamic, default 0).
   A duplicate key rolls back the failing statement and leaves the
   transaction open, which is MySQL's behaviour and stays MO's default. A
   session that treats a constraint violation as fatal to its unit of work
   can now opt into rolling back the whole transaction, including work done
   before the failure.

   It is consulted beside errCodeRollbackWholeTxn rather than added to it.
   Every member of that set is an infrastructure failure -- deadlock, lock
   timeout, backend gone -- after which a transaction cannot continue. A
   duplicate key is a data error: putting it there would change the default
   away from MySQL for everyone and would also apply to background and
   internal executors, where a duplicate key can be benign and would destroy
   an enclosing transaction. The opt-in is scoped to ErrDuplicateEntry, so an
   unrelated statement error still rolls back only the statement.

3. mo.sql returns a structured error. Starlark has no exceptions, so the mo
   module returns [result, ok] with ok None on success; ok was a bare string,
   so a procedure could only match on message text. It now carries err.code
   (the MySQL number), err.sqlstate and err.message, while still behaving as
   the message string everywhere it already did: it is truthy, concatenates
   with strings on either side, prints as the message, and converts to the
   message when assigned to an OUT parameter. Additive, not breaking.

Design notes: docs/design/duplicate_key_error_semantics.md.

Verified on a live server: 1062 now reports 23000 (and 1146/1049 report
42S02/42000); the default keeps a transaction alive across a duplicate key
while the variable ON discards it including the earlier row; and a procedure
reads err.code == 1062 and still gets the message from concatenation and from
an OUT parameter.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_016qdL5akNrbUfXfqjC659n6
@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 →

fengttt and others added 2 commits August 26, 2026 14:50
Two CI failures on aed9409, both real.

SCA: pkg/frontend/util_test.go was not gofmt'd -- adding a comment line
above `want1` changed the alignment of the `want` key in the same struct
literal. `make static-check` now passes locally (exit 0, no findings),
which is the same command CI runs.

BVT: function/foreign_exttab expects sql_tvf to surface a remote error
verbatim, and that text embeds the remote server's SQLSTATE:

  Error 1146 (HY000): SQL parser error: table "no_such" does not exist

Since ErrNoSuchTable now reports MySQL's 42S02, so does the embedded
text. The golden is updated to the string CI observed. It is the only
live expectation in the whole BVT corpus that contains a SQLSTATE -- the
other 38 HY000 occurrences are all `--ERROR ...` comments in .sql files,
which mo-tester does not compare.

The third failure, Utils CI / Coverage, was a cascade: "coverage merge
skipped because at least one required producer was skipped or failed",
caused by the BVT job above.

pkg/sql/plan/... also run: only the pre-existing timezone-dependent
TestBuildCreateOrReplaceViewRejectsRecursiveDefinition/future_AS_OF_timestamp
fails, and no SQLSTATE assertion anywhere broke -- the HY000 expectations
in build_test.go, query_builder_test.go and func_builtin_regexp_test.go
all cover errors outside the 29 that changed.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_016qdL5akNrbUfXfqjC659n6
The BVT compared dir(err) against the exact list ["code","message","sqlstate"],
which the AttrNames fix changes: the string methods are reachable, so they are
listed. Pinning the whole list also made the assertion useless -- the real one
ran past the varchar(300) column and was truncated mid-list.

It now asserts the two properties that matter and neither more nor less: the
value's OWN fields are still exactly code/message/sqlstate, and a string method
is both listed and callable on it (err.startswith("Duplicate entry")), which is
the compatibility the delegation exists to keep.

procedure/ 210/210, pessimistic_transaction/rollback_txn_on_error 73/73.
@fengttt

fengttt commented Aug 27, 2026

Copy link
Copy Markdown
Contributor Author

CI update on 2a3a861 → fixed in 964cc47

The coverage gate passed — Matrixone Utils CI / Coverage green, and UT Coverage on Ubuntu/x86 green. That failure is closed.

Two other jobs failed, neither from this PR:

SCA on Linux/arm64 — main was broken

pkg/lockservice/txn_test.go:310:9: ineffectual assignment to opts (ineffassign)

That file is byte-identical to main here (this PR touches no lockservice file); it arrived via the main merge, from c7f75e4704 fix(lock): stabilize bulk DML locking. Reproduced locally with golangci-lint --default=none -E ineffassign ./pkg/lockservice/..., so every PR merging main in that window failed SCA the same way.

Already fixed upstream by 63f16ffc7a test(lock): strengthen bulk lock regression checks (#27727) — and with the better of the two possible fixes: it asserts opts.Granularity rather than discarding the value with _. I merged latest main; ineffassign on that package is now clean locally.

UT — TestSendCommitDeadlineReturnsTxnUnknown/Commit

pkg/txn/rpc/sender_test.go:844, a 100 ms context deadline against an RPC that deliberately never replies. Its sibling subtest CommitAutoIncrEpochFence passed in the same run.

Not reachable from this PR, and I checked rather than assumed: the assertion is moerr.IsMoErrCode(err, moerr.ErrTxnUnknown), which compares the error code, while this PR changes only SQLSTATE strings in MysqlErrorMsgRefer plus adds IsRealError — no code constant is touched, and ErrTxnUnknown is not in the diff at all. Locally it passes -count=20.

Note this is a different test from the two that failed on the previous head (pkg/tests/partition), which also passed locally at -count=3. Two unrelated timing-sensitive tests failing across two runs points at the runners, not at a common cause in this diff.

Head is now 964cc47 with latest main merged. Please re-run.

@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 at 964cc4726dda6699c6e7bb9c9fbbe6944a5e4630.

Blocking compatibility regression in sqlError: the design says this is additive and even shows the existing expression "Duplicate entry" in err, but the new value only implements Value, HasAttrs, and HasBinary, with Binary handling + only. It is no longer a Starlark string/container/sequence. Consequently:

  • "Duplicate entry" in err now fails with an unknown binary op because the RHS is not a starlark.Container.
  • err == "<the old message>" is always false because mo.error and string are different Starlark types.
  • len(err), indexing/slicing, iteration, and string % formatting no longer work.

This is directly reachable by existing procedures, not a theoretical API concern. TestSQLErrorStaysAString calls selected Go methods directly and therefore misses the old language-level operations. Please either preserve the complete prior string contract and add evaluated Starlark/BVT regressions for containment, equality, len/index/slice/iteration/formatting, or explicitly design and approve a breaking migration.

Also resolve the scope mismatch: the stated feature is typed mo.sql errors, while this patch changes the error value returned by every mo.* builtin (jq, quote, getvar, setvar, and LLM calls), multiplying the compatibility surface.

This PR changes public SQLSTATE behavior, transaction-abort policy, and the stored-procedure API. The bundled design has no independent approval evidence yet; please obtain design approval after the compatibility contract is corrected.

@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 review of exact head 964cc4726dda6699c6e7bb9c9fbbe6944a5e4630.

Three blocking correctness/compatibility issues remain:

  1. mo_rollback_txn_on_error=1 only affects errors that reach rollbackTxnFunc; parse and other pre-execution failures bypass it. In a temporary embedded-cluster test on one connection, I enabled the setting, ran BEGIN; INSERT INTO t VALUES (1);, sent malformed selec 1, then COMMIT; the row count was 1, not 0.
  2. The replacement mo.error is not actually backward-compatible with the former Starlark string. Evaluated Starlark counterexamples show containment, equality, len, indexing, slicing, and iteration either fail or change result. ("%s" % err still works, so I did not count formatting as a failure.)
  3. The structured-error conversion is incomplete: some error exits still return a raw Starlark string, so .code works or throws depending on which failure branch produced the value.

Validation with the required thirdparties/CGO setup: full go test ./pkg/common/moerr ./pkg/frontend, focused race tests for the new moerr/frontend paths, and go vet ./pkg/common/moerr ./pkg/frontend ./pkg/tests/issues pass. The two temporary counterexample tests were removed and the exact-head worktree is clean.

Comment thread pkg/frontend/txn.go Resolved
Comment thread pkg/frontend/starlark_interpreter.go Resolved
Comment thread pkg/frontend/starlark_interpreter.go Resolved
…ilures

Two blocking reviews, both right. Verified each before acting.

1. The typed mo.error was NOT backward compatible. Evaluating real Starlark
   against it and against the string it replaced shows `"x" in err`,
   `err == msg`, `len(err)`, `err[0]`, `err[0:9]`, `sorted([err, s])` and
   `hash(err)` all break or change result. My earlier test called Go methods
   directly and could not see any of it, because those are language
   operations resolved on the CONCRETE type.

   Making the value a complete superset is not possible. Reporting
   Type() == "string" recovers equality and containment but makes
   `str(err)` / `"%s" % err` return the quoted form, and makes
   `sorted([err, "x"])` PANIC on an interface conversion inside the
   interpreter. An honest type avoids the panic but leaves equality, hashing,
   ordering and dict-interchange different.

   So the value goes back to being exactly what it was -- a plain
   starlark.String -- and the codes live beside it, in mo.errno() and
   mo.sqlstate(), reporting the most recent mo.* failure. Every failable
   builtin clears the record on entry, so a stale class is never reported;
   reading does not consume it, so a procedure can have both. This also drops
   the scope creep the review flagged: jq/quote/getvar/setvar and the LLM
   calls return precisely what they always did.

   The compatibility claim is now tested at the language level:
   TestBuiltinFailureIsStillAPlainString evaluates containment, equality,
   ordering, len, indexing, slicing, hashing, formatting and the string
   methods against a failing builtin's ok value and the equivalent string, and
   requires both to agree. BVT does the same through a stored procedure.

2. mo_rollback_txn_on_error missed failures that never reach the executor.
   Reproduced the reported counterexample: with the setting on,
   `BEGIN; INSERT ...; selec 1; COMMIT;` committed the row, because a parse
   error returns from doComQuery long before finishTxnFunc. Applied at the
   defer where every COM_QUERY error path converges; a statement that already
   rolled back leaves no active transaction, so this adds no double work.
   Now 0 rows with the setting on, 1 with it off.

   Also confirmed inert at the default: a transaction still survives both a
   parse error and a duplicate key when the setting is 0.

3. Two builtin exits still returned a raw string while the rest returned the
   typed value, so the codes were available or not depending on which branch
   failed. Moot now that every exit returns a string, and consistent because
   every exit also records the codes.
@fengttt

fengttt commented Aug 27, 2026

Copy link
Copy Markdown
Contributor Author

Both reviews were right on every point. Fixed in c4fafe13ee. Thank you — the compatibility finding in particular was a real defect my tests were structurally incapable of catching.

1. mo.error was not backward compatible — the value is a plain string again

I reproduced it by evaluating real Starlark against the new value and against the string it replaced:

expression old string mo.error
"Duplicate entry" in err True ERROR unknown binary op: string in mo.error
err == MSG / err != MSG True / False False / True
len(err) 31 ERROR
err[0], err[0:9] "D", "Duplicate" ERROR
sorted([err, "AAA"]) works ERROR
hash(err), {err: 1}[MSG] works ERROR / not found

You were also right about why my tests missed it: TestSQLErrorStaysAString called Go methods, and every operation above is resolved by the interpreter on the concrete type, never by name.

Making it a complete superset is not achievable, which I established rather than assumed. Reporting Type() == "string" does recover equality, containment, len and slicing — because sameType compares Type() strings — but it then makes str(err) and "%s" % err return the quoted form (those type-assert String and otherwise fall back to the repr), and it makes sorted([err, "x"]) panic:

panic: interface conversion: starlark.Value is *frontend.sqlError, not starlark.String

An honest Type() avoids the panic but leaves equality, hashing, ordering and dict-interchange different. Neither is a superset, and a panic inside a stored procedure is not a trade worth making.

So the ok value is exactly what it always was — a plain starlark.String — and the codes live beside it:

rs, err = mo.sql("insert into t values (1, 'dup')")
if err != None and mo.errno() == 1062:
    ...

mo.errno() / mo.sqlstate() report the most recent mo.* failure. Every failable builtin clears the record on entry, so a stale class is never reported; reading does not consume it, so a procedure can have both.

This also removes the scope creep you flagged: jq, quote, getvar, setvar and the LLM calls now return precisely what they always did. The compatibility surface of this PR is zero.

The claim is now tested the way you asked — at the language level. TestBuiltinFailureIsStillAPlainString evaluates containment, equality, ordering, len, indexing, slicing, hashing, formatting and the string methods against a failing builtin's ok value and against the equivalent plain string, and requires both to agree. The BVT does the same through a real stored procedure.

2. Pre-execution failures bypassed the setting

Reproduced your counterexample exactly, and it now behaves:

set mo_rollback_txn_on_error = 1;
begin; insert into t values (1); selec 1; commit;
select count(*) from t;   -- was 1, now 0

set mo_rollback_txn_on_error = 0;   -- MySQL behaviour preserved
begin; insert into t values (2); selec 1; commit;
select count(*) from t;   -- 1

A parse error returns from doComQuery long before finishTxnFunc, which is where the setting was honoured. It is now applied at the defer where every COM_QUERY error path converges; a statement that already rolled back leaves no active transaction, so the second site adds no double work. Both cases are BVT-covered now, along with an unknown-table rejection.

I also verified the default path is untouched: with the setting at 0, a transaction still survives both a parse error and a duplicate key.

3. Inconsistent error exits

Correct — two exits still returned a raw string while the rest returned the typed value, so .code was available or not depending on which branch failed. Moot now that every exit returns a string, and consistent because every exit also records the codes.

On design approval

The design doc section is rewritten to match: it documents mo.errno()/mo.sqlstate(), and records why the codes are not on the error value, with the table of which operations are concrete-type-dispatched and the panic that rules out the alternative — so the next person does not retry it. It also documents the two places the transaction setting is applied and why both are needed. Ready for your review of that as the settled contract.

The changed-line coverage gate failed at 66.67%. Two new pieces had no test
reaching them: the doComQuery rollback defer, and the parts of the starlark
module that need a session. Measured the same way locally, the diff goes from
72.34% to 90.43%, with mysql_cmd_executor.go at 100%.

The rollback decision moved out of the defer into
rollbackWholeTxnOnPreExecutionError, which is worth doing on its own terms: it
runs on EVERY COM_QUERY error, including the ones finishTxnFunc already
handled, so its guards are the interesting part and they were untestable
inline. TestPreExecutionRollbackIsGuarded pins them -- not opted in,
autocommit, opted in but no active transaction (the state a statement that
already rolled back leaves behind, which is what stops the two call sites
doubling up), a warning, and a nil error.

For starlark: the accessors are now proven reachable from a procedure through
buildModule, proven to reject arguments (accepting one silently would make
`mo.errno(err)` look meaningful), and proven to record codes for failures
DEEPER than argument unpacking -- an exec failure through a mock
BackgroundExec, a variable lookup, and a value conversion -- since otherwise
mo.errno() would answer only for the shallowest failures.

That test also caught a pre-existing bug it was written to exclude: mo.setvar
was registered as starlark.NewBuiltin("mo.getvar", si.moSetVar), so every
error raised inside setvar named getvar as the culprit. No golden captured it.

The nine lines still uncovered are result-set and LLM failure exits that need
a live backend; CI merges the BVT profile, which reaches them.
/pkg/fulltext2 listed @epegeric, which is not a GitHub account (the API 404s),
so that path effectively had one fewer owner than it looked like. The account
is @cpegeric (Eric Lam).

@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 of exact head bf6092cc51a42a446f30c02df486e5173b2fe0d3.

Two blocking correctness gaps remain in the strict transaction mode.

  1. rollbackWholeTxnOnPreExecutionError does not actually force a whole-transaction rollback. It calls TxnHandler.Rollback(execCtx) without setting execCtx.txnOpt.byRollback. In an active explicit transaction, TxnHandler.rollback therefore falls through to Workspace.RollbackLastStatement unless needToFinishTransactionAtStatementEnd(execCtx) happens to be true. A parse error has no executable statement, so this is the statement-rollback branch, not rollbackUnsafe. The current BVT has exactly one successful insert before each parse error and then immediately commits; rolling back only that last insert produces the same final row count and masks the bug. Add at least two successful statements before the error and assert both are gone, assert the transaction is no longer active, and assert a later statement cannot continue the old transaction. The helper needs to use the same explicit whole-rollback signal/path as rollbackTxnFunc.

  2. The claimed convergence point is no longer complete on this exact head. ExecRequest can return client-visible errors before calling doComQuery, including captureRewritePolicy for COM_QUERY, rewrite/JSON-hint validation for COM_STMT_PREPARE, and binary execute parsing/cursor validation for COM_STMT_EXECUTE. None reaches the new defer, so an opted-in active transaction survives those errors. captureRewritePolicy is particularly direct: it is part of processing a COM_QUERY, yet contradicts the design statement that every COM_QUERY error converges on this defer. Please put the strict rollback at a command-level error boundary (with warning/nil/inactive guards), or explicitly handle and regress every pre-doComQuery statement failure.

The SQLSTATE mapping and restored plain-string Starlark compatibility look sound in this revision. The SQLSTATE unit tests pass locally. The focused frontend test binary built but could not run in this worktree because the local libmo.dylib runtime dependency is absent; CI is green, and the blockers above follow from the exact control flow rather than a CI failure.

This branch was previously deployed

1 inactive deployment
ci — a75b5b49 Deployed Aug 27, 2026 by fengttt via Matrixone Utils CI / Coverage #48866
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

kind/api-change kind/bug Something isn't working kind/feature size/XL Denotes a PR that changes [1000, 1999] lines

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants