Uploaded image for project: 'MariaDB Server'
  1. MariaDB Server
  2. MDEV-42344

Online ALTER TABLE (ALGORITHM=COPY, LOCK=NONE, the default): a statement that fails in a concurrent transaction is rolled back in InnoDB, but the rows it had already logged are applied to the new table at COMMIT; committed rows get deleted

    XMLWordPrintable

Details

    Description

      Since 11.2 an ALTER TABLE that needs a table copy runs as ALGORITHM=COPY, LOCK=NONE by default, and the
      DML of other sessions is logged to an online ALTER log that the ALTER applies to the new table. When a
      statement fails inside a concurrent multi-statement transaction (duplicate key, lock wait timeout, ...),
      InnoDB rolls back the statement and the transaction goes on, but the rows events that the statement had
      already written to its online ALTER cache stay there. When the transaction commits, they are applied to
      the new table:

      • rows inserted by a failed INSERT appear in the table,
      • values written by a failed UPDATE replace the committed ones,
      • rows deleted by a failed DELETE disappear, so committed rows are lost.

      The client got an error for each of these statements, the transaction itself saw them rolled back, and
      the table is correct until the ALTER finishes. Afterwards CHECK TABLE ... EXTENDED reports OK. What is kept
      is every complete rows event of the failed statement (binlog_row_event_max_size, 64 KiB by default); a
      failing statement that changes fewer rows than fit into one event is rolled back correctly. Autocommit
      statements and transactions that end with ROLLBACK are not affected.

      How to repeat (bash and the mariadb client on the server host, database test; session A runs the ALTER,
      session C holds a row lock, session B runs the transaction):

      M="mariadb -uroot test"
      $M -e "CREATE OR REPLACE TABLE t (id INT PRIMARY KEY, u INT, v VARCHAR(100), UNIQUE KEY uk (u));
             INSERT INTO t SELECT seq, seq, CONCAT('row', seq) FROM seq_1_to_400000"
       
      # session A: an ALTER that needs a table copy (runs as ALGORITHM=COPY, LOCK=NONE by default)
      $M -e "ALTER TABLE t MODIFY u BIGINT" &
      until $M -N -e "SELECT state FROM information_schema.processlist WHERE info LIKE 'ALTER TABLE t%'" | grep -q copy; do sleep 0.1; done
       
      # session C: locks row 30000 for 10 s, so that the DELETE below gets a lock wait timeout
      $M -e "BEGIN; SELECT id FROM t WHERE id = 30000 FOR UPDATE; DO SLEEP(10); COMMIT" > /dev/null &
      until $M -N -e "SELECT COUNT(*) FROM information_schema.processlist WHERE info LIKE 'DO SLEEP%'" | grep -q 1; do sleep 0.1; done
       
      # session B: one committed change and three statements that fail and are rolled back, then COMMIT
      Q="SELECT COUNT(*) AS total_rows, SUM(id > 1000000) AS failed_insert_rows, SUM(v = 'rolled-back') AS failed_update_rows, SUM(id BETWEEN 10001 AND 30000) AS rows_10001_30000 FROM t"
      $M -f <<SQL
      SET SESSION innodb_lock_wait_timeout = 1;
      BEGIN;
      UPDATE t SET v = 'committed' WHERE id = 1;
      INSERT INTO t SELECT seq + 1000000, seq + 1000000, REPEAT('x', 90) FROM seq_1_to_3000
        UNION ALL SELECT 1, 1, 'duplicate';
      UPDATE t SET v = 'rolled-back', u = IF(id = 5000, 6000, u + 2000000) WHERE id BETWEEN 2 AND 5000;
      DELETE FROM t WHERE id BETWEEN 10001 AND 30000;
      $Q;
      COMMIT;
      SQL
      wait   # for the ALTER
      $M -e "$Q; CHECK TABLE t EXTENDED"
      

      Result on 13.2 main (ef4c7459):

      --------------
      INSERT INTO t SELECT seq + 1000000, seq + 1000000, REPEAT('x', 90) FROM seq_1_to_3000
        UNION ALL SELECT 1, 1, 'duplicate'
      --------------
       
      ERROR 1062 (23000) at line 4: Duplicate entry '1' for key 'PRIMARY'
      --------------
      UPDATE t SET v = 'rolled-back', u = IF(id = 5000, 6000, u + 2000000) WHERE id BETWEEN 2 AND 5000
      --------------
       
      ERROR 1062 (23000) at line 6: Duplicate entry '6000' for key 'uk'
      --------------
      DELETE FROM t WHERE id BETWEEN 10001 AND 30000
      --------------
       
      ERROR 1205 (HY000) at line 7: Lock wait timeout exceeded; try restarting transaction
      total_rows	failed_insert_rows	failed_update_rows	rows_10001_30000
      400000	0	0	20000
      total_rows	failed_insert_rows	failed_update_rows	rows_10001_30000
      385352	2592	4941	2760
      Table	Op	Msg_type	Msg_text
      test.t	check	status	OK
      

      The first result is the transaction's own view before COMMIT: the three failed statements are rolled back.
      The second is the table after the ALTER: 2592 of the 3000 rows of the failed INSERT are there (four rows
      events of 648 rows), 4941 rows carry the value of the failed UPDATE, and 17240 of the committed rows
      10001..30000 are gone (the failed DELETE had deleted 19999 of them before it timed out). The column type is
      BIGINT as requested. 13.0.2 gives the same numbers. Without the concurrent ALTER the table after COMMIT is
      the same as the transaction's own view (400000, 0, 0, 20000).

      The same test with only a failing INSERT ... SELECT of N rows plus one duplicate keeps 0 rows for N = 300,
      648 for N = 700, 1296 for N = 1400 and 2592 for N = 3000 (also when the failing statement is the first one
      of the transaction).

      Expected: a statement that failed and was rolled back has no effect on the table, with or without a
      concurrent ALTER; the new table contains exactly what the committed transactions wrote.

      Cause, as far as I can tell:

      online_alter_log_row() calls store_prev_position() before every row it logs, so before_stmt_pos is moved
      to the current end of the cache for each row instead of marking the start of the statement (the
      restore_prev_position() on its error path undoes the write of that one row):
      https://github.com/MariaDB/server/blob/ef4c7459b8433603b306dc46618eccae9d2b6957/sql/online_alter.cc#L190-L203
      https://github.com/MariaDB/server/blob/ef4c7459b8433603b306dc46618eccae9d2b6957/sql/online_alter.cc#L68-L71
      The rows are collected in a pending rows event, which is written to the cache when the next row would make it
      larger than binlog_row_event_max_size; after that the next row moves before_stmt_pos past it:
      https://github.com/MariaDB/server/blob/ef4c7459b8433603b306dc46618eccae9d2b6957/sql/log.cc#L8330-L8350
      On a statement rollback inside a transaction, online_alter_end_trans() calls restore_prev_position():
      https://github.com/MariaDB/server/blob/ef4c7459b8433603b306dc46618eccae9d2b6957/sql/online_alter.cc#L267-L271
      binlog_cache_data::truncate() then drops only the pending event and rewinds to before_stmt_pos, which is
      behind every complete event the failed statement had written:
      https://github.com/MariaDB/server/blob/ef4c7459b8433603b306dc46618eccae9d2b6957/sql/log_cache.h#L419-L432
      At COMMIT the cache is copied to the online ALTER log (write_cache_raw(), online_alter.cc line 261) and the
      ALTER applies those events to the new table in online_alter_read_from_binlog():
      https://github.com/MariaDB/server/blob/ef4c7459b8433603b306dc46618eccae9d2b6957/sql/sql_table.cc#L12967
      For comparison, the binary log's transaction cache sets the statement start once per statement
      (THD::binlog_set_stmt_begin()):
      https://github.com/MariaDB/server/blob/ef4c7459b8433603b306dc46618eccae9d2b6957/sql/log.cc#L7805-L7810
      A fix could keep the statement start separately (set when the statement first logs a row, and after the
      statement commit at line 275) and leave the per-row position for the error path at line 201. The code is the
      same in 11.4, 11.8, 12.3 and 13.1 (not run there).

      Workaround: run copying ALTERs with LOCK=SHARED (or set old_mode=LOCK_ALTER_TABLE_COPY); concurrent writes
      then wait for the ALTER, and the same transaction gives the correct result.

      Related: MDEV-16329 (the feature). MDEV-32126 (fixed in 11.2.2) was an assertion with transactions with
      failing statements and the binary log enabled; its fix reworked the online ALTER savepoints, and its test
      statements write two rows, which fit into one rows event and are rolled back correctly. MDEV-31624 (open):
      online ALTER fails because of intermediate DML that is later overridden (an error, not a silent change).
      MDEV-35661 (stalled): an assertion with XA. None of them covers rows of a failed statement being applied to
      the new table.

      Attachments

        Issue Links

          Activity

            People

              sanja Oleksandr Byelkin
              kehan5800 Ke Han
              Oleksandr Byelkin Oleksandr Byelkin
              Votes:
              0 Vote for this issue
              Watchers:
              3 Start watching this issue

              Dates

                Created:
                Updated:

                Time Tracking

                  Estimated:
                  Original Estimate - 0d
                  0d
                  Remaining:
                  Remaining Estimate - 1h
                  1h
                  Logged:
                  Time Spent - Not Specified
                  Not Specified

                  Git Integration

                    Error rendering 'com.xiplink.jira.git.jira_git_plugin:git-issue-webpanel'. Please contact your Jira administrators.