Skip to content

fix(usage): take node_user_usages FK locks in node order to stop MySQL 1213 deadlocks - #1278

Merged
ImMohammad20000 merged 2 commits into
PasarGuard:devfrom
JavadMoqaddam:fix/1277-node-major-usage-lock-order
Nov 29, 2026
Merged

ImMohammad20000 merged 2 commits into
PasarGuard:devfrom
JavadMoqaddam:fix/1277-node-major-usage-lock-order

Conversation

@JavadMoqaddam

@JavadMoqaddam JavadMoqaddam commented Nov 28, 2026 •

Copy link
Copy Markdown

Fixes #1277

Problem

On large MySQL installs the panel hits recurring InnoDB deadlock 1213 (~5-10/hour with no special traffic) between two writers inside the usage recorder:

  1. The batched per-user history upsert (INSERT IGNORE INTO node_user_usages ... VALUES (...), up to 1000 rows). node_user_usages.node_id is a foreign key to nodes.id, so InnoDB takes a shared lock on every referenced nodes row — in VALUES order.
  2. The node traffic accumulator (UPDATE nodes SET uplink = uplink + N ...), executed per node in ascending nodes.id order.

The deadlock dumps (3 in 12 minutes, full record in #1277) show the cycle: the INSERT holding S on nodes.id = 45 and waiting for S on nodes.id = 1, while the UPDATE holds X on id = 1 and waits for id = 45.

Root cause

_write_node_user_usage_params sorted the rows user-major:

upsert_params.sort(key=lambda item: (item["uid"], item["node_id"]))

With uid as the leading key, the node_ids inside the VALUES list are scattered ((user 329, node 45), (user 2317, node 1), ...), so the FK parent locks are taken in a different order than the traffic UPDATE takes its exclusive locks — exactly the deadlock the "consistent lock order" comment intended to prevent.

Fix

Sort node-major so both writers walk nodes in the same ascending direction:

upsert_params.sort(key=lambda item: (item["node_id"] or 0, item["uid"]))

The or 0 guard is needed because node_id is nullable (Mapped[int | None], ondelete="CASCADE" rows for deleted nodes).

Test

test_history_rows_are_sorted_node_major_for_fk_lock_order feeds a mixed batch (nodes 45, 1, 19 and a None node, in scrambled user order) through _write_node_user_usage_params with safe_execute stubbed, and asserts the statement that reaches the database carries rows in ascending node_id order: (None, 2), (1, 2317), (19, 5), (45, 329). With the old sort the same input comes out user-major, so the test fails on main.

Checklist

  • I read CONTRIBUTING.md
  • Tests pass locally (uv run pytest tests/test_record_usages.py tests/test_usage_rollup.py tests/test_node_usage_logs_load.py → 76 passed, 1 skipped; ruff check clean)
  • The change is limited to the deadlock path; no behaviour, schema or API change

Summary by CodeRabbit

  • Bug Fixes
    • Node-user usage history is now recorded in a consistent order: by node first, with entries that have no node listed first and users ordered within each node. This makes the sequence of recorded usage rows more predictable.

…L 1213 deadlocks

The per-user history upsert sorted rows by (uid, node_id), so the multi-row
VALUES list took its foreign-key shared locks on nodes.id in scattered order
and deadlocked against the node traffic UPDATE, which walks nodes ascending.
Sort node-major instead. See PasarGuard#1277.
@coderabbitai

coderabbitai Bot commented Nov 28, 2026 •

Copy link
Copy Markdown
Contributor

Explain Change →

Important

Review skipped

Auto reviews are disabled on base/target branches other than the default branch.

Please check the settings in the CodeRabbit UI or the .coderabbit.yaml file in this repository. To trigger a single review, invoke the @coderabbitai review command.

Run configuration

  • Source mode: Auto
  • Repository: Unavailable
  • Branch: Unavailable
  • File: No configuration file from this repository applied
  • Commit: Unavailable
  • Layers: Organization UI
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: 090bdfd3-d063-441a-987f-f828064b4fd3

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

Use the checkbox below for a quick retry:

  • Trigger review

No actionable comments were generated in the recent review.

Walkthrough

The node-user usage upsert now sorts rows by ascending node ID, then user ID. A test checks that MySQL history rows follow this order, with null node IDs first.

Changes

Node-user usage lock ordering

Layer / File(s) Summary
Sort usage rows and verify MySQL order
app/jobs/record_usages.py, tests/test_record_usages.py
The upsert parameters are sorted by node ID, then user ID. A test checks the MySQL history row order, including null node IDs first.

Estimated code review effort: 2 (Simple) | ~10 minutes

Change: Bug fix · Severity of issue fixed: Medium

Possibly related issues

Suggested labels: Backend

Suggested reviewers: x0sina, immohammad20000

Merge Risk: Minimal · previous review a7f4c

This change reorders the per-user usage-history writes so they lock node rows in the same ascending order as the node traffic updates, which reduces MySQL deadlocks. The reviewed code shows no step that undoes the ordering, and the new test covers it. No merge-blocking risk was found.

Pre-merge checks: Passed 4

Check name Status Explanation
Description Check Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check Passed The title names the main change: node_user_usages foreign-key locks are taken in node order to stop MySQL 1213 deadlocks. The raw summary and PR objectives both describe a sort change in _write_node_u…
Linked Issues check Passed Directly linked issue #1277 requires both writers to take nodes row locks in the same ascending node-major order. The PR changes the sort in _write_node_user_usage_params (app/jobs/record_usages.py) f…
Out of Scope Changes check Passed The changes are limited to the sort key and its explanatory comments in app/jobs/record_usages.py and one regression test in tests/test_record_usages.py (plus the asyncio import the test uses). The so…
Full details: Title check

Explanation

The title names the main change: node_user_usages foreign-key locks are taken in node order to stop MySQL 1213 deadlocks. The raw summary and PR objectives both describe a sort change in _write_node_user_usage_params from uid-then-node_id to node_id-then-uid, which matches the title. The title is 85 characters, so it is slightly long, but it is specific and clear.

Full details: Linked Issues check

Explanation

Directly linked issue #1277 requires both writers to take nodes row locks in the same ascending node-major order. The PR changes the sort in _write_node_user_usage_params (app/jobs/record_usages.py) from (uid, node_id) to (node_id or 0, uid), so the node_user_usages upsert VALUES rows are ordered by ascending node_id. This matches the order used by the node traffic UPDATE (sorted(node_totals.items())), as described in #1277. The or 0 guard handles nullable node_id. A new test, test_history_rows_are_sorted_node_major_for_fk_lock_order in tests/test_record_usages.py, asserts the ascending node_id order for a mixed batch including None, and the PR reports it fails on the old sort. Limitation: the repository diff tool could not read the changed blobs, so the code and test evidence comes from the PR summary, the PR description, and the AI-generated change summary, not from a direct source read. The fix does not drop the foreign key, which #1277 does not require. The MySQL retry/drop impact in #1277 is background only.

Full details: Out of Scope Changes check

Explanation

The changes are limited to the sort key and its explanatory comments in app/jobs/record_usages.py and one regression test in tests/test_record_usages.py (plus the asyncio import the test uses). The sort change implements the #1277 objective directly. The test supports that objective. The PR reports no schema, API, or behavior change beyond the write order. No unrelated changes appear in the reported summary. Limitation: the file diff could not be read directly, so this verdict relies on the change summary and PR description.

Finishing Touches

Generate unit tests (beta)

Error creating Unit Test PR.

  • Create a new PR
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

Share

A rabbit sorts the rows in line,
By node, then user, neat and fine.
Null hops first, then numbers climb,
The test checks order every time.
The usage batch now follows through.

Recent review info

Run configuration

  • Source mode: Auto
  • Repository: Unavailable
  • Branch: Unavailable
  • File: No configuration file from this repository applied
  • Commit: Unavailable
  • Layers: Organization UI
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: 36d43b8d-ce65-4598-9a7e-6ffcb7f958de
Commits

Reviewing files that changed from the base of the PR and between 2b75db1 and a7f4c97.

Files selected for processing: 2

  • app/jobs/record_usages.py
  • tests/test_record_usages.py

Included review availability: This review used your included allowance. Your plan provides up to 8 included reviews per hour; 7 remain after this review.

@JavadMoqaddam

JavadMoqaddam commented Nov 28, 2026 •

Copy link
Copy Markdown
Author

Simulation on real MySQL — the deadlock reproduces, and this PR removes it

Environment: MySQL 9.7.4 (Docker, same version as the production server), transaction_isolation=REPEATABLE-READ, innodb_print_all_deadlocks=ON. The schema was rebuilt from the production dump (mysqldump --no-data, 34 tables) with scaled data: 15 nodes, 3,000 users, 500 usage rows.

Method: two concurrent transactions mirroring the real panel path:

  • A — multi-row INSERT IGNORE INTO node_user_usages … VALUES (…); InnoDB takes a shared (S) lock on the nodes.id foreign-key parent for each row, in the order of the VALUES list.
  • B — one UPDATE nodes SET uplink=uplink+? … WHERE id=? per node, ascending (the same sorted(node_totals.items()) used in record_usages.py).

The actual VALUES order was taken from the code itself (calling _write_node_user_usage_params("mysql", rows) with safe_execute monkeypatched):

branch node order in VALUES
main [None, 3, 5, 1] (uid-major)
this PR [None, 1, 3, 5] (node-major, ascending)

Results:

scenario main this PR
natural concurrent run (40 iterations) 32 deadlocks 0
forced, deterministic lock order (5 iterations) 5 deadlocks 0

The server-side counter agrees: 37 Transactions deadlock detected dumps in the error log = 32 + 5.

Real MySQL 9.7.4 dump on main (last block, trimmed):

 *** (1) TRANSACTION:
INSERT IGNORE INTO node_user_usages (created_at,user_id,node_id,used_traffic)
  VALUES ('...',5,3,1),('...',329,5,1),('...',2317,1,1)
RECORD LOCKS … index PRIMARY of table `nodes` … lock mode S locks rec but not gap
RECORD LOCKS … index PRIMARY of table `nodes` … lock mode S locks rec but not gap waiting
 *** (2) TRANSACTION:
UPDATE nodes SET uplink=uplink+7, downlink=downlink+11 WHERE id=3
RECORD LOCKS … index PRIMARY of table `nodes` … lock_mode X locks rec but not gap
RECORD LOCKS … index PRIMARY of table `nodes` … lock_mode X locks rec but not gap waiting
*** WE ROLL BACK TRANSACTION (2)

This is the same shape as the production dump (#1277): the foreign-key S lock from the INSERT side, the X lock from the counter-update side, on the same table and page, taken in opposite order.

Tests on this branch: tests/test_record_usages.py → 45 passed, 1 skipped.

The harness is a small two-transaction pymysql script; I can paste it here if you want to rerun it.

@JavadMoqaddam
JavadMoqaddam changed the base branch from main to dev November 28, 2026 11:10
@ImMohammad20000

Copy link
Copy Markdown
Contributor

@JavadMoqaddam fix formater error

@JavadMoqaddam

Copy link
Copy Markdown
Author

@ImMohammad20000 Fixed — the formatter error came from the base branch, not from these PRs; all are updated and just need a CI re-run.

@coderabbitai

coderabbitai Bot commented Nov 29, 2026

Copy link
Copy Markdown
Contributor

Note

Unit test generation is a beta feature. Expect some limitations and changes as we gather feedback and continue to improve it.


Generating unit tests... This may take up to 20 minutes.

@coderabbitai

coderabbitai Bot commented Nov 29, 2026

Copy link
Copy Markdown
Contributor

CodeRabbit can't publish this change from a fork. Run this command from a branch in the target repository.

@ImMohammad20000
ImMohammad20000 merged commit abbe544 into PasarGuard:dev Nov 29, 2026
14 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Bug]: MySQL 1213 deadlock between the node-user usage upsert and the node traffic UPDATE (FK locks taken in user-id order, not node-id order)

2 participants