Repository navigation
feat: MySQL SQLSTATEs, opt-in txn-fatal errors (mo_rollback_txn_on_error), and typed mo.sql errors - #27611
Conversation
…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 reviews are paused for this user.Troubleshooting steps vary by plan Learn more → On a Teams plan? Using GitHub Enterprise Server, GitLab Self-Managed, or Bitbucket Data Center? |
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.
CI update on
|
XuPeng-SH
left a comment
There was a problem hiding this comment.
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 errnow fails with an unknown binary op because the RHS is not astarlark.Container.err == "<the old message>"is always false becausemo.errorandstringare 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
left a comment
There was a problem hiding this comment.
Deep review of exact head 964cc4726dda6699c6e7bb9c9fbbe6944a5e4630.
Three blocking correctness/compatibility issues remain:
mo_rollback_txn_on_error=1only affects errors that reachrollbackTxnFunc; parse and other pre-execution failures bypass it. In a temporary embedded-cluster test on one connection, I enabled the setting, ranBEGIN; INSERT INTO t VALUES (1);, sent malformedselec 1, thenCOMMIT; the row count was1, not0.- The replacement
mo.erroris 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" % errstill works, so I did not count formatting as a failure.) - The structured-error conversion is incomplete: some error exits still return a raw Starlark string, so
.codeworks 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.
…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.
|
Both reviews were right on every point. Fixed in 1.
|
| 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
left a comment
There was a problem hiding this comment.
Deep review of exact head bf6092cc51a42a446f30c02df486e5173b2fe0d3.
Two blocking correctness gaps remain in the strict transaction mode.
-
rollbackWholeTxnOnPreExecutionErrordoes not actually force a whole-transaction rollback. It callsTxnHandler.Rollback(execCtx)without settingexecCtx.txnOpt.byRollback. In an active explicit transaction,TxnHandler.rollbacktherefore falls through toWorkspace.RollbackLastStatementunlessneedToFinishTransactionAtStatementEnd(execCtx)happens to be true. A parse error has no executable statement, so this is the statement-rollback branch, notrollbackUnsafe. 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 asrollbackTxnFunc. -
The claimed convergence point is no longer complete on this exact head.
ExecRequestcan return client-visible errors before callingdoComQuery, includingcaptureRewritePolicyforCOM_QUERY, rewrite/JSON-hint validation forCOM_STMT_PREPARE, and binary execute parsing/cursor validation forCOM_STMT_EXECUTE. None reaches the new defer, so an opted-in active transaction survives those errors.captureRewritePolicyis 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-doComQuerystatement 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.
What type of PR is this?
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:
SQLExceptionsubclass from the SQLSTATE class, so a duplicate key never arrived asSQLIntegrityConstraintViolationException— only as a plainSQLException.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 usedMySQLDefaultSqlStatewhere MySQL defines a specific SQLSTATE; all 29 now use MySQL's:ErrDuplicateEntryErrNoSuchTableErrBadDBErrOutOfRangeErrDivByZeroErrSyntaxError/ErrParseError…and 23 more, all derived from MO's own MySQL table rather than hand-picked.
TestSqlStateMatchesMySQLkeeps the two from drifting again. It has one deliberate exception: SQLSTATE class01is 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 oldErrBadDBvalue and is updated.Verified on a live server:
2.
mo_rollback_txn_on_errorA failed statement rolls back the statement, not the transaction — MySQL's behaviour, and still MO's default:
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:
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.
moerrcodes are banded:0..99Ok signals,100..101Info,200..201Warning, and every real error at or aboveErrStart(20100). The newError.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.GetSessionSysVaranswersniloutside its small allowlist, so a background session never opts in even when it is set globally — with a test to pin that.3.
mo.sqlreturns a structured errorStarlark has no exceptions, so the
momodule returns[result, ok]withokNoneon success.okwaserr.Error()— a bare string — so a procedure could only match on message text:The value now carries its codes:
err.code1062(0when the failure is not a moerr)err.sqlstate"23000"err.messagestr(err),"x: " + err,err + " y"bool(err)Trueerr == NoneFalseon failure,Trueon successout_param = errEverything 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
pkg/common/moerrTestSqlStateMatchesMySQLpkg/common/moerrTestDuplicateEntrySqlStatepkg/frontendTestSessionRollsBackTxnOnErrorpkg/frontendTestStaticRollbackSetIsInfrastructureOnlypkg/common/moerrTestIsRealErrorErrStartpkg/frontendTestWarningsNeverRollBackTxnpkg/frontendTestBackgroundSessionNeverRollsBackWholeTxnpessimistic_transaction/rollback_txn_on_errorprocedure/starlark_sql_errorerr.code/err.sqlstate/err.message,dir(err), truthiness, concatenation,Noneon success, and the OUT-parameter form still yielding the messagepkg/common/moerrandpkg/frontendpass; both new BVT cases pass in compare mode; theproceduresuite 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 existingsp_ins2_sumgolden instarlark_sql.resultrecords exactly that failure rather than the intended behaviour. The new case therefore uses conditional expressions instead ofif/elseblocks, and says so in a comment. Fixing mo-tester is the better answer but it lives in another repository.