Bug #80373 auto-increment max triggering incorrect error
Submitted: 15 Feb 2016 13:47 Modified: 17 Feb 2016 11:00
Reporter: Steven Hartland Email Updates:
Status: Duplicate Impact on me:
None 
Category:MySQL Server: Errors Severity:S2 (Serious)
Version: OS:Any
Assigned to: CPU Architecture:Any
Tags: Auto-increment, ON DUPLICATE KEY

[15 Feb 2016 13:47] Steven Hartland
Description:
When inserting into a table which has reached its max auto-increment value the error returned is:
[Err] 1062 - Duplicate entry '2147483647' for key 'PRIMARY'

This prevents on duplicate key statements from operating correctly, possibly resulting in data loss.

Instead it would make more sense for an auto-increment failure to be specific e.g.
[Err] 1467 - Failed to read auto-increment value from storage engine

How to repeat:
Create a table with the max auto-increment value set to its max e.g.
CREATE TABLE `xxx_test` (
  `test` int(11) NOT NULL AUTO_INCREMENT,
  `val` varchar(255) DEFAULT NULL,
  `updated` datetime DEFAULT NULL ON UPDATE CURRENT_TIMESTAMP,
  PRIMARY KEY (`test`),
  UNIQUE KEY `unq_val` (`val`)
) ENGINE=InnoDB AUTO_INCREMENT=2147483646 DEFAULT CHARSET=latin1;

Try to insert into said table two rows:
INSERT INTO `xxx_test` (`val`, `updated`)
VALUES ('value1', NOW())
ON DUPLICATE KEY UPDATE `updated` = VALUES(`updated`);
# id = 2147483646

INSERT INTO `xxx_test` (`val`, `updated`)
VALUES ('value2', NOW())
ON DUPLICATE KEY UPDATE `updated` = VALUES(`updated`);
# id = 2147483647

Now a row which should trigger an update of the id = 2147483646, val = value1 row:
INSERT INTO `xxx_test` (`val`, `updated`)
VALUES ('value1', NOW())
ON DUPLICATE KEY UPDATE `updated` = VALUES(`updated`);

Instead of updating the row with id = 2147483646, val = 'value1' it tries to update the row with id = 2147483647, val = 'value2' due to the auto-increment failure, resulting in the confusing error:
[Err] 1062 - Duplicate entry 'value1' for key 'unq_val'

If the following is run:
INSERT INTO `xxx_test` (`val`, `updated`)
VALUES ('value3', NOW())
ON DUPLICATE KEY UPDATE `updated` = VALUES(`updated`);
we get:
# Affected rows: 2
# Time: 0.012s

This again is incorrect as it should have inserted a new row but didn't due to the auto-increment failure and hence it updated the row with id = 2147483647 losing that data.

Suggested fix:
Failure to increment the auto-increment value should always return an error specific to that case e.g.
[Err] 1467 - Failed to read auto-increment value from storage engine

Preventing it from being treated as a duplicate key error, which can cause data loss.
[17 Feb 2016 8:51] MySQL Verification Team
Hello Steven,

Thank you for the report.
This is most likely duplicate of Bug #66566/Bug #76463.

Thanks,
Umesh
[17 Feb 2016 11:00] Steven Hartland
Yes they are related but in combination with ON DUPLICATE KEY you can also get data loss / corruption so its a more serious issue than those bugs indicate.