KDOC 668: 中断して残ったMySQLのトランザクションはスレッドをkillして終わらせる

この文書のステータス

  • 作成
    • 2026-10-17 貴島
  • レビュー
    • 2026-10-17 貴島

概要

MySQL で、テストの実行を途中で止めると、次の実行は Lock wait timeout exceeded で失敗することがある。止めたテストのトランザクションは終わらずに残り、行のロックを持ち続けている。

ERROR 1205 (HY000): Lock wait timeout exceeded; try restarting transaction

ふつうは、クライアントの接続が切れるとセッションが終わり、コミットしていないトランザクションはロールバックされる。

If a session that has autocommit disabled ends without explicitly committing the final transaction, MySQL rolls back that transaction.

MySQL 8.4 Reference Manual - autocommit, Commit, and Rollback

BEGIN や START TRANSACTION で始めたトランザクションも、終わるまでは autocommit が無効になっているので、この場合に当てはまる。

With START TRANSACTION, autocommit remains disabled until you end the transaction with COMMIT or ROLLBACK.

MySQL 8.4 Reference Manual - START TRANSACTION, COMMIT, and ROLLBACK Statements

残るのは、セッションが終わっていないときである。テストのプロセスが接続を開いたまま生き残っていたり、重いクエリの実行中で、サーバーがクライアントの切断にまだ気づいていなかったりすると、トランザクションとロックが残る。

残ったトランザクションは、 information_schema.INNODB_TRX で、それを持っているスレッドの番号と開始時刻を引ける。

The INNODB_TRX table provides information about every transaction currently executing inside InnoDB, including whether the transaction is waiting for a lock, when the transaction started, and the SQL statement the transaction is executing, if any.

MySQL 8.4 Reference Manual - The INFORMATION_SCHEMA INNODB_TRX Table

その番号を KILL に渡して接続を切ると、セッションが終わり、トランザクションはロールバックされる。更新は元に戻り、次回の実行は通るようになる。

SELECT trx_mysql_thread_id, trx_started FROM information_schema.INNODB_TRX ORDER BY trx_started;
KILL 11; -- 上で見つけた trx_mysql_thread_id

関連

なし。