You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
fix(usage): take node_user_usages FK locks in node order to stop MySQL 1213 deadlocks - #1278
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:
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.
The node traffic accumulator (UPDATE nodes SET uplink = uplink + N ...), executed per node in ascendingnodes.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:
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:
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.
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.
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.
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: 4
Check name
Status
Explanation
Description Check
Check skipped - CodeRabbit’s high-level summary is enabled.
Title check
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
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
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.
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.
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: 37Transactions 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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
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:
INSERT IGNORE INTO node_user_usages ... VALUES (...), up to 1000 rows).node_user_usages.node_idis a foreign key tonodes.id, so InnoDB takes a shared lock on every referencednodesrow — in VALUES order.UPDATE nodes SET uplink = uplink + N ...), executed per node in ascendingnodes.idorder.The deadlock dumps (3 in 12 minutes, full record in #1277) show the cycle: the INSERT holding
Sonnodes.id = 45and waiting forSonnodes.id = 1, while the UPDATE holdsXonid = 1and waits forid = 45.Root cause
_write_node_user_usage_paramssorted the rows user-major:With
uidas the leading key, thenode_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
nodesin the same ascending direction:The
or 0guard is needed becausenode_idis nullable (Mapped[int | None],ondelete="CASCADE"rows for deleted nodes).Test
test_history_rows_are_sorted_node_major_for_fk_lock_orderfeeds a mixed batch (nodes 45, 1, 19 and aNonenode, in scrambled user order) through_write_node_user_usage_paramswithsafe_executestubbed, and asserts the statement that reaches the database carries rows in ascendingnode_idorder:(None, 2), (1, 2317), (19, 5), (45, 329). With the old sort the same input comes out user-major, so the test fails onmain.Checklist
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 checkclean)Summary by CodeRabbit