pingcap / pingcap/tidb

stale read does not work with autocommit=0 correctly

Open
#62,384 4 comments 0 reactions 0 assignees View on GitHub
affects-6.5 affects-7.1 affects-7.5 affects-8.1 affects-8.5 report/customer severity/moderate sig/transaction type/bug
Dominant language
Go
Stars
40.5k
Forks
6.2k
PR merge metrics
PR metrics pending

Description

## Bug Report

Please answer these questions before submitting your issue. Thanks!

### 1. Minimal reproduce step (Required)

```
# tx_read_consistency.py
import pymysql
import threading
import time
import random

# Update these for your environment
MYSQL_CONFIG = {
'host': 'XXX',
'user': 'XXX',
'password': 'XXX',
'password': 'XXX',
'database': 'XXX'
}

def writer(stop_event):
conn = pymysql.connect(**MYSQL_CONFIG)
try:
while not stop_event.is_set():
val = f"{time.time()}_{random.randint(1000,9999)}"
with conn.cursor() as cur:
cur.execute("BEGIN")
cur.execute("UPDATE test SET val=%s WHERE id='A'", (val,))
cur.execute("UPDATE test SET val=%s WHERE id='B'", (val,))
conn.commit()
time.sleep(0.001) # control write QPS
finally:
conn.close()

def reader(stop_event):
conn = pymysql.connect(**MYSQL_CONFIG)
conn.cursor().execute("set @@tidb_read_staleness='-1'")
conn.cursor().execute("SET SESSION transaction_isolation = 'REPEATABLE-READ';")

try:
for _ in range(4000):
with conn.cursor() as cur:
# cur.execute("BEGIN");
cur.execute("SET autocommit=0");
cur.execute("SELECT val FROM test WHERE id='A'")
a_val = cur.fetchone()[0]
cur.execute("SELECT val FROM test WHERE id='B'")
b_val = cur.fetchone()[0]
conn.rollback()
cur.execute("SET autocommit = 1")
if a_val != b_val:
print(f"Inconsistency detected! A={a_val}, B={b_val}")
time.sleep(0.001) # 1 ms
if stop_event.is_set():
break
finally:
conn.close()

def setup_table():
conn = pymysql.connect(**MYSQL_CONFIG)
try:
with conn.cursor() as cur:
cur.execute("""
CREATE TABLE IF NOT EXISTS test (
id VARCHAR(10) PRIMARY KEY,
val VARCHAR(255)
)
""")
cur.execute("INSERT IGNORE INTO test (id, val) VALUES ('A', 'init'), ('B', 'init')")
conn.commit()
finally:
conn.close()

def main():
setup_table()
stop_event = threading.Event()
w = threading.Thread(target=writer, args=(stop_event,))
w.start()
try:
reader(stop_event)
finally:
stop_event.set()
w.join()

if __name__ == "__main__":
main()
```

### 2. What did you expect to see? (Required)

test success

### 3. What did you see instead (Required)

```
$ python3 tx_read_consistency.py
Inconsistency detected! A=1752257549.970934_4578, B=1752257550.0265982_1605
Inconsistency detected! A=1752257550.3712847_5745, B=1752257550.4241014_9275
Inconsistency detected! A=1752257550.4241014_9275, B=1752257550.4758112_3534
Inconsistency detected! A=1752257551.1683047_6359, B=1752257551.223222_6973
```

### 4. What is your TiDB version? (Required)

v8.5.1

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.