diogosilva30 commented on issue #77497:
URL: https://github.com/apache/airflow/issues/77497#issuecomment-7104627107
I reproduced this on a throwaway MySQL 8.4.13 (`READ-COMMITTED`,
`innodb_print_all_deadlocks=ON`) with two sessions, using the real `edge_job` /
`edge_logs` definitions (same primary keys and collations).
**Setup.** 200 finished jobs of one task (one run each, `try_number=1`).
Session A takes the odd runs and session B the even runs with `SELECT ... FOR
UPDATE` (what `_purge_jobs` ends up with when two schedulers claim interleaved
rows), then each deletes its jobs one by one and handles their `edge_logs`, and
commits at the end.
**Old pattern** (`DELETE FROM edge_logs WHERE <key> AND NOT EXISTS (SELECT
... FROM edge_job WHERE <same key> AND task_instance_id != ...)`): **30 of 30
rounds deadlocked.** The report has the same shape as the production one: both
transactions are that `DELETE`; each holds `lock_mode X locks rec but not gap`
on `edge_job` `PRIMARY` and waits for `lock mode S locks rec but not gap` on
`edge_job` `PRIMARY`.
**New pattern** (plain `SELECT EXISTS(...)` for a sibling, then `DELETE FROM
edge_logs WHERE <key>` only if none): **0 of 30 rounds deadlocked**, no other
errors, and every job and `edge_logs` row was deleted.
**Sibling case** (two jobs with the same coordinates but different
`task_instance_id`, purged by two sessions that have not committed yet): with
the plain `SELECT` alone, both sessions still see the other's job and keep the
logs, so 1 `edge_logs` row is left forever. With a recheck after each session's
commit (delete the logs if no job has the coordinates any more), 0 rows are
left. #77496 does this.
Not covered: real concurrency from workers pushing logs, and the `SKIP
LOCKED` claiming order of the real executor. The test above fixes the claimed
sets.
<details><summary>Script (needs <code>pymysql</code> and
<code>cryptography</code>; MySQL on 127.0.0.1:33306, root password
<code>repro</code>, database <code>airflow_db</code>)</summary>
```python
"""Two scheduler purges on MySQL: old edge_logs DELETE with a NOT EXISTS
subquery vs plain-SELECT check."""
import sys
import threading
import uuid
import pymysql
HOST, PORT = "127.0.0.1", 33306
N_JOBS = 200
ROUNDS = int(sys.argv[1]) if len(sys.argv) > 1 else 30
def connect():
c = pymysql.connect(host=HOST, port=PORT, user="root", password="repro",
database="airflow_db", autocommit=False)
with c.cursor() as cur:
cur.execute("SET SESSION innodb_lock_wait_timeout = 10")
return c
SCHEMA = [
"DROP TABLE IF EXISTS edge_logs",
"DROP TABLE IF EXISTS edge_job",
"""CREATE TABLE edge_job (
dag_id varchar(250) CHARACTER SET utf8mb3 COLLATE utf8mb3_bin NOT NULL,
task_id varchar(250) CHARACTER SET utf8mb3 COLLATE utf8mb3_bin NOT
NULL,
run_id varchar(250) CHARACTER SET utf8mb3 COLLATE utf8mb3_bin NOT NULL,
map_index int NOT NULL DEFAULT '-1',
try_number int NOT NULL,
state varchar(20) DEFAULT NULL,
queue varchar(256) DEFAULT NULL,
concurrency_slots int DEFAULT NULL,
command varchar(2048) DEFAULT NULL,
queued_dttm timestamp(6) NULL DEFAULT NULL,
edge_worker varchar(64) DEFAULT NULL,
last_update timestamp(6) NULL DEFAULT NULL,
team_name varchar(64) DEFAULT NULL,
task_instance_id varchar(36) CHARACTER SET ascii COLLATE ascii_bin NOT
NULL DEFAULT '',
priority_weight int NOT NULL DEFAULT '1',
PRIMARY KEY
(dag_id,task_id,run_id,map_index,try_number,task_instance_id),
KEY rj_order (state,priority_weight,queued_dttm,queue)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci""",
"""CREATE TABLE edge_logs (
dag_id varchar(250) CHARACTER SET utf8mb3 COLLATE utf8mb3_bin NOT NULL,
task_id varchar(250) CHARACTER SET utf8mb3 COLLATE utf8mb3_bin NOT
NULL,
run_id varchar(250) CHARACTER SET utf8mb3 COLLATE utf8mb3_bin NOT NULL,
map_index int NOT NULL DEFAULT '-1',
try_number int NOT NULL,
log_chunk_time timestamp(6) NOT NULL,
log_chunk_data mediumtext NOT NULL,
PRIMARY KEY (dag_id,task_id,run_id,map_index,try_number,log_chunk_time)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci""",
]
RUNS = [f"scheduled__2026-11-23T10:{i // 60:02d}:{i % 60:02d}+00:00" for i
in range(N_JOBS)]
JOBS = [("dag", "task", r, -1, 1, str(uuid.UUID(int=i + 1))) for i, r in
enumerate(RUNS)]
def reset(conn):
with conn.cursor() as cur:
cur.execute("DELETE FROM edge_logs")
cur.execute("DELETE FROM edge_job")
cur.executemany(
"INSERT INTO edge_job
(dag_id,task_id,run_id,map_index,try_number,task_instance_id,state) "
"VALUES (%s,%s,%s,%s,%s,%s,'success')",
JOBS,
)
cur.executemany(
"INSERT INTO edge_logs
(dag_id,task_id,run_id,map_index,try_number,log_chunk_time,log_chunk_data) "
"VALUES (%s,%s,%s,%s,%s,NOW(6),'x')",
[j[:5] for j in JOBS],
)
conn.commit()
def purge(conn, jobs, mode, barrier, result, name):
"""What one scheduler does: lock its jobs, then delete each job and its
logs, commit at the end."""
try:
with conn.cursor() as cur:
for j in jobs: # FOR UPDATE SKIP LOCKED in the executor: each
scheduler ends up with its own rows
cur.execute(
"SELECT 1 FROM edge_job WHERE dag_id=%s AND task_id=%s
AND run_id=%s AND map_index=%s "
"AND try_number=%s AND task_instance_id=%s FOR UPDATE",
j,
)
barrier.wait(timeout=30)
for j in jobs:
cur.execute(
"DELETE FROM edge_job WHERE dag_id=%s AND task_id=%s AND
run_id=%s AND map_index=%s "
"AND try_number=%s AND task_instance_id=%s",
j,
)
key = j[:5]
if mode == "old":
cur.execute(
"DELETE FROM edge_logs WHERE dag_id=%s AND run_id=%s
AND task_id=%s AND map_index=%s "
"AND try_number=%s AND NOT (EXISTS (SELECT
edge_job.dag_id FROM edge_job WHERE "
"edge_job.dag_id=%s AND edge_job.run_id=%s AND
edge_job.task_id=%s AND "
"edge_job.map_index=%s AND edge_job.try_number=%s
AND edge_job.task_instance_id != %s))",
(key[0], key[2], key[1], key[3], key[4], key[0],
key[2], key[1], key[3], key[4], j[5]),
)
else:
cur.execute(
"SELECT EXISTS (SELECT 1 FROM edge_job WHERE
dag_id=%s AND run_id=%s AND task_id=%s "
"AND map_index=%s AND try_number=%s AND
task_instance_id != %s)",
(key[0], key[2], key[1], key[3], key[4], j[5]),
)
if not cur.fetchone()[0]:
cur.execute(
"DELETE FROM edge_logs WHERE dag_id=%s AND
run_id=%s AND task_id=%s AND map_index=%s "
"AND try_number=%s",
(key[0], key[2], key[1], key[3], key[4]),
)
conn.commit()
result[name] = "ok"
except pymysql.err.OperationalError as e:
conn.rollback()
result[name] = "deadlock" if e.args[0] == 1213 else f"error
{e.args[0]}"
except threading.BrokenBarrierError:
result[name] = "barrier"
def run(mode):
setup = connect()
deadlocks = errors = 0
for _ in range(ROUNDS):
reset(setup)
barrier = threading.Barrier(2)
result = {}
a, b = connect(), connect()
ts = [
threading.Thread(target=purge, args=(a, JOBS[0::2], mode,
barrier, result, "A")),
threading.Thread(target=purge, args=(b, JOBS[1::2], mode,
barrier, result, "B")),
]
for t in ts:
t.start()
for t in ts:
t.join()
a.close()
b.close()
if "deadlock" in result.values():
deadlocks += 1
elif any(v != "ok" for v in result.values()):
errors += 1
left = None
with setup.cursor() as cur:
cur.execute("SELECT (SELECT COUNT(*) FROM edge_job), (SELECT
COUNT(*) FROM edge_logs)")
left = cur.fetchone()
print(f"{mode:4s}: {ROUNDS} rounds, rounds with a deadlock: {deadlocks},
other errors: {errors}, "
f"rows left after last round (jobs, logs): {left}")
setup.close()
if __name__ == "__main__":
c = connect()
with c.cursor() as cur:
for stmt in SCHEMA:
cur.execute(stmt)
c.commit()
c.close()
for mode in sys.argv[2:] or ["old", "new"]:
run(mode)
```
Run with `python repro_edge_deadlock.py 30 old new`.
</details>
(Analysis prepared with Claude Code.)
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: [email protected]
For queries about this service, please contact Infrastructure at:
[email protected]