Skip to content

channeldb: acquire mutexes in the same order throughout#8400

Merged
Roasbeef merged 5 commits into
lightningnetwork:masterfrom
ellemouton:deadlockFix
Jan 22, 2024
Merged

channeldb: acquire mutexes in the same order throughout#8400
Roasbeef merged 5 commits into
lightningnetwork:masterfrom
ellemouton:deadlockFix

Conversation

@ellemouton
Copy link
Copy Markdown
Collaborator

@ellemouton ellemouton commented Jan 18, 2024

In this commit, we ensure that the channeldb cacheMu mutex is only ever aquired before acquiring the main DB lock in the cases where the two locks need to be held simultaneously.

Fixes #8398

Summary by CodeRabbit

  • New Features

    • Introduced new safety mechanisms in the channel graph to enhance stability and prevent deadlocks.
  • Bug Fixes

    • Fixed a potential deadlock in channel ID filtering.
  • Tests

    • Added a stress test for the ChannelGraph API to ensure reliability under concurrent usage.
  • Documentation

    • Updated release notes with recent changes and fixes.

@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai Bot commented Jan 18, 2024

Important

Auto Review Skipped

Auto reviews are limited to the following labels: llm-review. Please add one of these labels to enable auto reviews.

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.

Walkthrough

The update introduces critical changes to the ChannelGraph structure in the channeldb package to address deadlock issues. By adding a new mutex, cacheMu, the changes ensure thread-safe operations on caches. The refactoring of the delChannelEdge method and the addition of delChannelEdgeUnsafe and markEdgeLiveUnsafe methods aim to streamline cache and database operations without locking conflicts. A new stress test in graph_test.go assesses the concurrent robustness of these modifications.

Changes

File Change Summary
channeldb/graph.go Introduced cacheMu mutex, refactored delChannelEdge to delChannelEdgeUnsafe, added markEdgeLiveUnsafe
channeldb/graph_test.go Added TestStressTestChannelGraphAPI function for deadlock testing
docs/release-notes/release-notes-0.18.0.md Documented deadlock fix in FilterKnownChanIDs and update on watchtower session handling

Assessment against linked issues

Objective Addressed Explanation
Fix potential deadlock in FilterKnownChanIDs when receiving ReplyChannelRange message (#8398) The addition of cacheMu and restructuring of locking in graph.go should resolve the deadlock issue described.

Poem

In the graph where channels flow,
Deadlocks once lurked, hidden below.
But with mutex in hand and tests underway,
The rabbit ensures the channels safely play. 🐇🔒

Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

Share

Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>.
    • Generate unit-tests for this file.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit tests for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai generate interesting stats about this repository from git and render them as a table.
    • @coderabbitai show all the console.log statements in this repository.
    • @coderabbitai read src/utils.ts and generate unit tests.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (invoked as PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger a review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai help to get help.

Additionally, you can add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.

CodeRabbit Configration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • The JSON schema for the configuration file is available here.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/coderabbit-overrides.v2.json

CodeRabbit Discord Community

Join our Discord Community to get help, request features, and share feedback.

@ellemouton ellemouton requested a review from ziggie1984 January 18, 2024 18:51
Copy link
Copy Markdown
Collaborator

@morehouse morehouse left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM

@Roasbeef Roasbeef added this to the v0.17.4 milestone Jan 18, 2024
Copy link
Copy Markdown
Collaborator

@ziggie1984 ziggie1984 left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thank you for this quick fix 🙏

I wonder if these kind of conditions can be detected by the unit-race test of the golang suite ? Are we missing a test or so ?

Comment thread channeldb/graph.go Outdated
@ellemouton
Copy link
Copy Markdown
Collaborator Author

Thanks for the idea @ziggie1984 ! Let me know what you think of the new stress test I have added

@ellemouton
Copy link
Copy Markdown
Collaborator Author

oops - race detected in new test. Will fix & comment here once it is fixed

@ellemouton ellemouton force-pushed the deadlockFix branch 3 times, most recently from 03cf965 to 1ec1c58 Compare January 19, 2024 12:58
@ellemouton
Copy link
Copy Markdown
Collaborator Author

ok - all good now @ziggie1984

@ellemouton
Copy link
Copy Markdown
Collaborator Author

@coderabbitai review

Copy link
Copy Markdown
Contributor

@coderabbitai coderabbitai Bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Review Status

Actionable comments generated: 2

Configuration used: CodeRabbit UI

Commits Files that changed from the base of the PR and between ba4021c and 1ec1c58457a574b4409db0fc51c1eedd5bb90c8a.
Files selected for processing (3)
  • channeldb/graph.go (9 hunks)
  • channeldb/graph_test.go (1 hunks)
  • docs/release-notes/release-notes-0.18.0.md (1 hunks)
Additional comments: 8
channeldb/graph.go (8)
  • 179-181: The comment on lines 179-181 explains the importance of the lock order between cacheMu and the database lock to prevent deadlocks. This is a critical piece of information for future maintainers.
  • 1337-1338: The delChannelEdgeUnsafe method is called with the correct parameters. Ensure that all calls to this method are made with the cacheMu lock already held, as per the method's contract.
  • 1592-1593: Similar to the previous comment, verify that the cacheMu lock is acquired before calling delChannelEdgeUnsafe.
  • 1736-1737: Again, ensure that the cacheMu lock is acquired before this call to delChannelEdgeUnsafe.
  • 2093-2095: The cacheMu lock is correctly acquired and deferred to be unlocked. This is in line with the new locking strategy to prevent deadlocks.
  • 2148-2148: The markEdgeLiveUnsafe method is called within a transaction. Verify that this method is always called with the cacheMu lock held.
  • 2483-2484: The comment on lines 2483-2484 clearly states the precondition for calling delChannelEdgeUnsafe. This is good for maintainability and preventing misuse of the method.
  • 3635-3636: The comment on lines 3635-3636 serves as a clear warning to maintain the correct lock acquisition order when calling markEdgeLiveUnsafe. This is crucial for avoiding deadlocks.

Comment thread docs/release-notes/release-notes-0.18.0.md Outdated
Comment thread channeldb/graph_test.go Outdated
Copy link
Copy Markdown
Member

@Roasbeef Roasbeef left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM 🦖

Comment thread channeldb/graph_test.go Outdated
Comment thread channeldb/graph.go Outdated
@saubyk
Copy link
Copy Markdown
Collaborator

saubyk commented Jan 19, 2024

Basic question:
Why are we labelling functions delChannelEdgeUnsafe and markEdgeLiveUnsafe as unsafe?

@Roasbeef
Copy link
Copy Markdown
Member

Why are we labelling functions delChannelEdgeUnsafe and markEdgeLiveUnsafe as unsafe?

The caller must hold the mutex before they call them. An alternative, would be like delChannelMustHaveMutex or something like that lol.

Copy link
Copy Markdown
Collaborator

@ziggie1984 ziggie1984 left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM ⭐️

Comment thread channeldb/graph.go Outdated
Comment thread channeldb/graph_test.go Outdated
Copy link
Copy Markdown
Member

@Roasbeef Roasbeef left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Looksl ike things are still dead-locking w/ the postgres backend:

panic: test timed out after 3h0m0s
running tests:
	TestAllowMoreAttempts (2h59m50s)
	TestDecidePaymentStatus (2h59m52s)
	TestHTLCsExtraData (2h59m53s)
	TestNeedWaitAttempts (2h59m50s)
	TestPaymentSetState (2h59m50s)
	TestPaymentStatusActions (2h59m52s)
	TestRegistrable (2h59m49s)
	TestSerializeAndDeserializeRevLog (2h59m50s)
	TestStressTestChannelGraphAPI (2h59m55s)
	TestStressTestChannelGraphAPI/0 (2h59m49s)
	TestStressTestChannelGraphAPI/5 (2h59m49s)
	TestStressTestChannelGraphAPI/8 (2h59m49s)
	TestStressTestChannelGraphAPI/9 (2h59m49s)

goroutine 149545 [running]:
testing.(*M).startAlarm.func1()
	/opt/hostedtoolcache/go/1.21.0/x64/src/testing/testing.go:2259 +0x3b9

@Roasbeef
Copy link
Copy Markdown
Member

Looks like things are still dead-locking w/ the postgres backend:

Trying to repro locally now...

Unlike the other backends, the postgres backend has an additional client-side mutex. Will see if I can get a goroutine dump.

@Roasbeef
Copy link
Copy Markdown
Member

Relevant goroutine dump: https://paste.sh/qavACXtH#5SsXOJ_rcoU0gzqHYmJNHeik

@ellemouton
Copy link
Copy Markdown
Collaborator Author

Added a final commit to fix this last deadlock @Roasbeef

With postgres, since we require an exclusive lock, we cant call kvdb.View from within kvdb.Update. Fixed this by adding an optional read tx to FetchChanInfos

@ellemouton ellemouton force-pushed the deadlockFix branch 2 times, most recently from 124b332 to 3a06075 Compare January 22, 2024 10:50
Copy link
Copy Markdown
Member

@Roasbeef Roasbeef left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM 🪃

This commit adds a test that calls many of the ChannelGraph methods
concurrently and in a random order. This test demonstrates that a
deadlock currently exists in the ChannelGraph since the test does not
complete. This is fixed in the next commit.
In this commit, we ensure that the channeldb cacheMu mutex is only ever
aquired _before_ acquiring the main DB lock in the cases where the two
locks need to be held simultaneously.

With this commit, the deadlock demonstrated in the previous commit is
now fixed.
In order to emphasise the fact that the ChannelGraph's cacheMu should be
acquired before calling the `delChannelEdge` method, we add the `Unsafe`
postfix and add a comment to alert readers.
In this commit, the FetchChanInfos ChannelGraph method is updated to
take in an optional read transaction for the case where it is called
from within another transaction.
@Roasbeef Roasbeef merged commit 41c167d into lightningnetwork:master Jan 22, 2024
@ellemouton ellemouton deleted the deadlockFix branch January 24, 2025 13:20
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[bug]: Potential Deadlock when Receiving ReplyChannelRange msg

5 participants