Skip to content

fix: implement ROW_COUNT() affected-row semantics - #25750

Merged
mergify[bot] merged 27 commits into
matrixorigin:mainfrom
ck89119:issue-24767-main
Jul 17, 2026
Merged

mergify[bot] merged 27 commits into
matrixorigin:mainfrom
ck89119:issue-24767-main

Conversation

@ck89119

@ck89119 ck89119 commented Jul 15, 2026

Copy link
Copy Markdown
Contributor

What type of PR is this?

  • BUG

Which issue(s) this PR fixes:

issue #24767

What this PR does / why we need it:

ROW_COUNT() was an unimplemented stub that always returned 0. This PR tracks the previous statement affected-row state across the frontend session, process, prepared-statement paths, and remote CN execution, then evaluates ROW_COUNT() at execution time.

It follows the expected semantics:

  • affected rows after DML and LOAD DATA;
  • -1 after result-set or failed statements;
  • 0 after statements that affect no rows.

It also preserves the state across protocol-only commands and rejects truncated temporal binary parameters without panicking.

Tests cover the function, session/process state, protobuf round trips, frontend protocol paths, prepared statements, multi-statements, REPLACE, ODKU, and LOAD DATA.

Validation:

  • make
  • go test ./pkg/sql/plan/function ./pkg/vm/process ./pkg/frontend ./pkg/pb/pipeline
  • targeted go test -race for the new session/process state tests

ck89119 and others added 16 commits June 2, 2026 12:34
ROW_COUNT() was an unimplemented stub that always returned 0. Track the
previous statement's affected rows on the session and process (mirroring
last_insert_id) and have the ROW_COUNT() builtin read it, following MySQL
semantics: affected rows for DML, -1 after a result-set statement, and 0
after DDL.

Add unit tests at the process/function/frontend layers and a BVT case.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
Address review on the initial ROW_COUNT() fix:

- Record the affected-rows value once per statement at the execution point
  (executeStmtWithResponse), updating both the process and the session,
  instead of in per-responder code. This fixes ROW_COUNT() inside a
  multi-statement COM_QUERY (all statements reuse one proc) and keeps the
  binary-protocol execute path correct.
- Drop the now-redundant per-responder writebacks.
- BVT: replace the existing-key REPLACE case (MO returns 1, MySQL 2) with a
  new-key REPLACE so the golden no longer encodes non-MySQL semantics.
- Add TestRecordLastAffectedRows.

ROW_COUNT() inside stored procedures / after CALL (background NullResp path)
is tracked separately in matrixorigin#24783.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
recordLastAffectedRows only runs after a statement succeeds, so when the
previous statement failed (parse / compile / execution error) ROW_COUNT()
kept returning the last successful statement's value. MySQL returns -1 after
a failed statement.

Set the ROW_COUNT() state to -1 on every error path of the main
COM_QUERY / COM_STMT_EXECUTE flow via a deferred handler in doComQuery,
covering parse, compile and execution errors.

Extend the BVT with a failed-DML case.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
Two follow-up fixes from review:

1. Mark the row_count() overload as volatile + realTimeRelated, mirroring
   last_insert_id. Without these flags constant folding froze the value into
   the prepared plan at PREPARE time, so `prepare s from 'select row_count()'`
   returned the affected rows captured at prepare time instead of the live
   session state at EXECUTE time.

2. When parseStmtExecute fails (malformed execute packet, missing prepared
   statement, binary param decode error) the request returns before reaching
   doComQuery, so its error defer never ran and the next ROW_COUNT() leaked the
   previous successful DML value. Reset the ROW_COUNT() state to -1 on that
   path too. Extracted the shared reset into markRowCountFailed.

Tests: frontend unit test for markRowCountFailed; BVT prepared-statement case
verifying EXECUTE-time evaluation.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
…r paths

Follow-up fixes from review:

1. ProcessInfo did not carry AffectedRows, so when an expression that reads
   ROW_COUNT() (e.g. `select row_count() from <table>` whose projection is
   pushed down to a TableScan) is shipped to a remote CN, the codec-built proc
   started at the default 0 instead of the previous statement's affected rows.
   Added affected_rows to the ProcessInfo proto message and carry/restore it in
   BuildProcessInfo / Decode.

2. COM_STMT_CLOSE / COM_STMT_RESET returned an error response for a missing
   prepared statement before reaching doComQuery, so the next ROW_COUNT() leaked
   the previous value. Reset it to -1 on those paths too, matching the
   COM_STMT_EXECUTE parse-failure fix.

Tests: pipeline.ProcessInfo Marshal/Unmarshal round-trip for AffectedRows
(including the -1 sentinel).

Co-Authored-By: Claude Opus 4.8 <[email protected]>
…ard short packets

Follow-up fixes from review:

1. The main remote-run path does not go through process_codec.Decode(); it
   rebuilds the proc via generateProcessHelper / newCompile in remoterunServer.go,
   which did not carry AffectedRows. So row_count() pushed down to a remote
   TableScan/Projection still read the default 0. Carry affected_rows through
   processHelper and call proc.SetAffectedRows on the rebuilt remote proc.

2. The affected_rows field was hand-added to pipeline.pb.go last round but the
   embedded FileDescriptor was stale, so Descriptor()/reflection saw the old
   schema. Regenerated pipeline.pb.go (gogofast) so the descriptor matches.

3. COM_STMT_CLOSE / COM_STMT_RESET read the statement id without a length check,
   panicking on a short packet (recovered later, but ROW_COUNT() kept its old
   value). Guard the packet length and reset ROW_COUNT() to -1 on a malformed
   packet instead.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
recordLastAffectedRows() only preserved AffectRows for the Insert/Update/Delete/
Replace/Load AST whitelist and stored 0 for everything else. That discarded the
real affected-row count of successful status statements outside the whitelist,
e.g. `CREATE TABLE ... AS SELECT` and status-returning `SELECT ... INTO ...`,
which run through status_stmt.go with a real runResult.AffectRows. The following
`SELECT ROW_COUNT()` then wrongly reported 0.

Key the recorded value off the statement's output type instead:
  - OUTPUT_RESULT_ROW -> -1
  - OUTPUT_STATUS     -> runResult.AffectRows (DDL/no-op status carry 0)
  - otherwise         -> 0

Removed the now-unused isRowCountDML helper. Added a status-select unit case and
a `create table ... as select` BVT case (reports 6, previously 0).

Co-Authored-By: Claude Opus 4.8 <[email protected]>
ParseExecuteData() validated the declared length byte of TIME/DATE/DATETIME/
TIMESTAMP binary parameters but not that the payload was actually present. The
readTime/readDate/readDateTime/readTimestamp helpers then index the buffer at
fixed offsets, so a truncated packet panicked during parsing (recovered later)
and skipped the parse-failure path that sets ROW_COUNT() to -1.

Guard each temporal case with `pos+int(length) > len(data)` so a truncated
payload returns a malformed-packet error, which flows through the normal
COM_STMT_EXECUTE failure handling (markRowCountFailed -> -1).

Co-Authored-By: Claude Opus 4.8 <[email protected]>
COM_FIELD_LIST is routed through doComQuery as InternalCmdFieldList, whose
StmtKind() is OUTPUT_STATUS. Since recordLastAffectedRows runs after every
successful statement, an OUTPUT_STATUS statement with no runResult recorded 0,
so `INSERT ...; <COM_FIELD_LIST>; SELECT ROW_COUNT()` wrongly returned 0 instead
of the insert's affected-row count.

InternalCmdFieldList is a protocol-only metadata helper, not a user SQL
statement, so skip it in recordLastAffectedRows and leave the preceding
statement's ROW_COUNT() state untouched.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
Two issues found in multi-statement / protocol handling:

1. SELECT ... INTO ... (export) discarded the RunResult from runner.Run(0) in
   status_stmt.go, and the multi-statement COM_QUERY loop never cleared
   execCtx.runResult between statements (it is only reset on Close()). So in
   `UPDATE ...; SELECT ... INTO OUTFILE ...; SELECT ROW_COUNT();` the export
   statement inherited the UPDATE's affected rows for both ROW_COUNT() and its
   OK packet. The export branch now keeps its own runResult, and the loop clears
   execCtx.runResult before each statement so a statement that does not set it
   no longer inherits a stale value.

2. COM_STMT_CLOSE / COM_STMT_RESET are rewritten to DEALLOCATE/RESET PREPARE and
   run through doComQuery, so a successful close/reset recorded 0 and clobbered
   the preceding statement's ROW_COUNT(). These are protocol-only side effects;
   save and restore the ROW_COUNT() state around the rewritten query on success
   (a genuine failure still leaves the -1 marking in place).

Tests: TestRestoreRowCount; verified the multi-statement export case with
go-sql-driver multiStatements=true (returns the export's own count, not the
previous UPDATE's). ROW_COUNT() after CALL/stored procedures remains tracked in
 matrixorigin#24783.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
Add BVT coverage for two more affected-rows paths the implementation touches:
- INSERT ... ON DUPLICATE KEY UPDATE that inserts a new row -> 1
- LOAD DATA INFILE -> number of imported rows (4)

Note: REPLACE-over-existing and ON DUPLICATE KEY UPDATE's update/no-op cases are
intentionally not added. MatrixOne's executor counts net rows written to the
target table once (REPLACE-conflict=1, ODKU update=1, ODKU no-op=1) rather than
MySQL's client-protocol convention (2/2/0); see build_dml_util.go addAffectedRows.
That is an executor-level affected-rows semantic, independent of ROW_COUNT(), so
the golden does not encode the non-MySQL values.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
# Conflicts:
#	pkg/pb/pipeline/pipeline.pb.go
Pin ROW_COUNT() for the high-value duplicate-key paths a reviewer asked about:
REPLACE that collides with an existing key, and INSERT ... ON DUPLICATE KEY
UPDATE that hits an existing row (real change and no-op).

These lock MatrixOne's current values (all 1): MatrixOne counts the net rows
written to the target table once, whereas MySQL reports 2 for REPLACE-over-
existing and ODKU update, and 0 for an ODKU no-op. That affected-rows divergence
is an executor-level semantic (not ROW_COUNT() plumbing) and is tracked
separately in matrixorigin#24907; the case comments call this out.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
@ck89119
ck89119 requested review from XuPeng-SH and aunjgr as code owners July 15, 2026 07:01
@ck89119
ck89119 requested a review from a user July 15, 2026 07:01
@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 →

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

Re-reviewed current head 005872a8a with a full protocol/state/remote/migration unhappy-path audit. The four previous blockers are resolved: FIELD_LIST and unsupported commands set -1, every COM_STMT_CLOSE path preserves the prior value, and fresh sessions initialize session/process state to -1. SEND_LONG_DATA and truncated binary temporal packets also have explicit failure handling.

The state propagation is closed end-to-end (Session -> Process -> remote ProcessInfo -> receiver, and source CN -> proxy -> target Session), including signed -1 round trips. Q1-Q3 audit found no new resource, wait-termination, or unbounded-accumulation risk.

Local verification passed: go test for frontend/process/function/pipeline/compile/proxy, targeted go test -race, go vet for all affected Go packages, and git diff --check. CI still has jobs in progress but no failures at review time.

@mergify

mergify Bot commented Jul 17, 2026 •

Copy link
Copy Markdown
Contributor

Merge Queue Status

  • ✅ Entered queue — 2026-07-17 03:22 UTC · Rule: main · triggered by rule Automatic queue on approval for main
  • ✅ Checks passed · in-place
  • ✅ Merged — 2026-07-17 04:51 UTC · at 3a8a036c0dae5528de50a2111cb98afbd5ef4e39 · squash

This pull request spent 1 hour 29 minutes 45 seconds in the queue, including 58 minutes 43 seconds running CI.

Required conditions to merge
  • #review-threads-unresolved = 0 [🛡 GitHub branch protection]
  • github-review-approved [🛡 GitHub branch protection]
  • github-review-decision = APPROVED [🛡 GitHub branch protection]
  • any of [🛡 GitHub branch protection]:
    • check-success = Matrixone Compose CI / multi cn e2e bvt test docker compose(PESSIMISTIC)
    • check-neutral = Matrixone Compose CI / multi cn e2e bvt test docker compose(PESSIMISTIC)
    • check-skipped = Matrixone Compose CI / multi cn e2e bvt test docker compose(PESSIMISTIC)
  • any of [🛡 GitHub branch protection]:
    • check-success = Matrixone Standlone CI / Multi-CN e2e BVT Test on Linux/x64(LAUNCH, PROXY)
    • check-neutral = Matrixone Standlone CI / Multi-CN e2e BVT Test on Linux/x64(LAUNCH, PROXY)
    • check-skipped = Matrixone Standlone CI / Multi-CN e2e BVT Test on Linux/x64(LAUNCH, PROXY)
  • any of [🛡 GitHub branch protection]:
    • check-success = Matrixone Standlone CI / e2e BVT Test on Linux/x64(LAUNCH, PESSIMISTIC)
    • check-neutral = Matrixone Standlone CI / e2e BVT Test on Linux/x64(LAUNCH, PESSIMISTIC)
    • check-skipped = Matrixone Standlone CI / e2e BVT Test on Linux/x64(LAUNCH, PESSIMISTIC)
  • 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 Utils CI / Coverage
    • check-neutral = Matrixone Utils CI / Coverage
    • check-skipped = Matrixone Utils CI / Coverage
  • 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

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/L Denotes a PR that changes [500,999] lines

Projects

None yet

Development

Successfully merging this pull request may close these issues.

6 participants