Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Beat [2/4]: implement blockbeat #8894

Merged
merged 19 commits into from
Nov 21, 2024
Merged

Conversation

yyforyongyu
Copy link
Member

@yyforyongyu yyforyongyu commented Jul 4, 2024

Depends on #8893.

NOTE: itest is fixed in the final PR #9260

This PR introduces a minimal version of the new service Blockbeat as described in #7952, to handle block synchronization among different subsystems.

During startup, blockbeat consumers are registered in the BlockbeatDispatcher, a subservice that's responsible for dispatching new blockbeats to its consumers and waiting for its consumers to finish processing the blocks. If any of the consumers fail to process the block under 30s, or encounter an error during block processing, the system will shut down as it's critical to handle blocks.

This PR focuses on implementing blockbeat Consumer interface for ChainArb, UtxoSweeper and TxPublisher, the following PR focuses on finalizing blockbeat processing in ChainArb's subservices - ChannelArbitrator, chainWatcher, and ContractResolver.

Overview

The flow of the blockbeat process is shown below, whenever a new block arrives, it goes through the waterfall like this,

  1. blockbeat dispatcher receives a new block epoch and makes a blockbeat, and sends it to its consumers sequentially.
  2. ChainArb receives the blockbeat, processes it and signals back when done.
  3. UtxoSweeper receives the blockbeat, processes it and signals back when done.
  4. TxPublisher receives the blockbeat, processes it and signals back when done.
  5. This new block is now considered processed by the blockbeat dispatcher.
sequenceDiagram
		autonumber
		participant bb as BlockBeat
		participant cc as ChainArb
		participant us as UtxoSweeper
		participant tp as TxPublisher
		
		note left of bb: 0. received block x,<br>dispatching...
		
    note over bb,cc: 1. send block x to ChainArb,<br>wait for its done signal
		bb->>cc: block x
		rect rgba(165, 0, 85, 0.8)
      critical signal processed
        cc->>bb: processed block
      option Process error or timeout
        bb->>bb: error and exit
      end
    end

    note over bb,us: 2. send block x to UtxoSweeper, wait for its done signal
		bb->>us: block x
		rect rgba(165, 0, 85, 0.8)
      critical signal processed
        us->>bb: processed block
      option Process error or timeout
        bb->>bb: error and exit
      end
    end

    note over bb,tp: 3. send block x to TxPublisher, wait for its done signal
		bb->>tp: block x
		rect rgba(165, 0, 85, 0.8)
      critical signal processed
        tp->>bb: processed block
      option Process error or timeout
        bb->>bb: error and exit
      end
    end
Loading

TODO

  • add unit tests for new code
  • add readme

@yyforyongyu yyforyongyu added this to the v0.18.2 milestone Jul 4, 2024
@yyforyongyu yyforyongyu self-assigned this Jul 4, 2024
Copy link
Contributor

coderabbitai bot commented Jul 4, 2024

Important

Review skipped

Auto reviews are limited to specific labels.

🏷️ Labels to auto review (1)
  • llm-review

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.

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


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>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • 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 testing code 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 gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

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 using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • 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/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

@guggero guggero self-requested a review July 9, 2024 14:49
@yyforyongyu yyforyongyu force-pushed the yy-prepare-blockbeat branch from a0393a0 to 9d6f8e7 Compare July 11, 2024 09:46
@saubyk saubyk requested a review from ellemouton July 11, 2024 15:18
Copy link
Collaborator

@guggero guggero left a comment

Choose a reason for hiding this comment

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

Did a first pass to load context.
The sweeper commits towards the end seem to make sense, but I'm missing all the review context from the sweeper PR saga to make a good judgement call.

But I really like the concept of the block beat! This should help us quite a bit in synchronizing all subsystems.

I assume a follow-up PR that refactors all subsystems to use this will come once this lands?

chainio/README.md Show resolved Hide resolved
chainio/log.go Show resolved Hide resolved
chainio/log.go Outdated Show resolved Hide resolved
chainio/blockbeat.go Outdated Show resolved Hide resolved
chainio/blockbeat.go Outdated Show resolved Hide resolved
chainio/dispatcher.go Show resolved Hide resolved
chainio/interface.go Outdated Show resolved Hide resolved
contractcourt/channel_arbitrator.go Outdated Show resolved Hide resolved
log.go Outdated Show resolved Hide resolved
@saubyk saubyk added the P1 MUST be fixed or reviewed label Jul 15, 2024
@yyforyongyu yyforyongyu force-pushed the yy-prepare-blockbeat branch 2 times, most recently from 16e2353 to 7183080 Compare July 15, 2024 18:02
Copy link
Collaborator

@ellemouton ellemouton left a comment

Choose a reason for hiding this comment

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

Really liking this! Left some questions so long (pretty much all just questions for my understanding). Gonna need another round to really grok things

chainio/interface.go Outdated Show resolved Hide resolved
chainio/interface.go Outdated Show resolved Hide resolved
chainio/interface.go Show resolved Hide resolved
chainio/dispatcher.go Outdated Show resolved Hide resolved
chainio/dispatcher.go Show resolved Hide resolved
chainio/dispatcher.go Show resolved Hide resolved
chainio/interface.go Outdated Show resolved Hide resolved
chainio/blockbeat.go Outdated Show resolved Hide resolved
chainio/blockbeat.go Outdated Show resolved Hide resolved
chainio/interface.go Outdated Show resolved Hide resolved
@yyforyongyu yyforyongyu force-pushed the yy-prepare-blockbeat branch 2 times, most recently from 755c7f3 to 9ec032a Compare July 18, 2024 07:32
@yyforyongyu yyforyongyu changed the title Beat [2/3]: implement blockbeat Beat [2/4]: implement blockbeat Jul 18, 2024
@saubyk saubyk modified the milestones: v0.18.3, v0.19.0 Jul 18, 2024
Copy link
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.

A couple high-level concerns:

  • The timeout might be too short, causing complete node shutdown under transient load when previously recovery would have been possible.
  • TxPublisher should receive beats before UtxoSweeper, as discussed previously.

chainio/blockbeat.go Outdated Show resolved Hide resolved
chainio/interface.go Outdated Show resolved Hide resolved
chainio/blockbeat.go Outdated Show resolved Hide resolved
c.Unlock()

// Iterate all the copied channels and send the blockbeat to them.
err := beat.DispatchConcurrent(channels)
Copy link
Collaborator

Choose a reason for hiding this comment

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

I worry about timeouts in extreme cases here. handleBlockbeat has 30 seconds to complete, but every single channel arbitrator needs to process the block in that time. If there's thousands of channels, how long does it actually take to dispatch?

Copy link
Member Author

Choose a reason for hiding this comment

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

if there's no force close it takes microseconds otherwise it's milliseconds.

@yyforyongyu yyforyongyu force-pushed the yy-blockbeat branch 2 times, most recently from 7b05026 to d76a26e Compare October 15, 2024 09:18
@lightninglabs-deploy
Copy link

@yyforyongyu, remember to re-request review from reviewers when ready

Copy link
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.

I think it very close, we still need to decide on the following:

  1. Will we add ctx where possible and also have the benefit of structured logging where possible
  2. Maybe fix the lingering processBlock goroutine maybe via a errGroup with a timeout ctx ?=> was not taking the buffered errorChan into account

chainio/README.md Outdated Show resolved Hide resolved
chainio/README.md Outdated Show resolved Hide resolved
// NOTE: The consumer must try its best to NOT return an error. If an
// error is returned from processing the block, it means the subsystem
// cannot react to onchain state changes and lnd will shutdown.
ProcessBlock(b Blockbeat) error
Copy link
Collaborator

Choose a reason for hiding this comment

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

So the change in design however will keep piling up the goroutines now when we timeout for whatever reason. So if the consumer does not report in 60 sec one time this goroutine will linger around forever until the consumer closes.

}

// Create a customized logger for the blockbeat.
logPrefix := fmt.Sprintf("Height[%6d]:", b.Height())
Copy link
Collaborator

Choose a reason for hiding this comment

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

I think we should go with structured logging from the beginning, this might also faciliated the structure and we do not need a logger object in the blockbeat.


errChan := make(chan error, 1)
go func() {
errChan <- c.ProcessBlock(b)
Copy link
Collaborator

Choose a reason for hiding this comment

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

An argument for the ctx is also structured logging.

return fmt.Errorf("%s got err in ProcessBlock: %w", c.Name(),
err)

case <-time.After(timeout):
Copy link
Collaborator

Choose a reason for hiding this comment

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

I don't think that is a good idea to call the timeout here rather than cancelling a context, because then to spawned goroutine might linger around if it does not return in time.

Copy link
Collaborator

Choose a reason for hiding this comment

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

Ok I misunderstood, the errorChan is buffered so there is no way the spawned ProcessBlock worker get's stuck in case we prematurely exit because of a timeout.

Copy link
Collaborator

Choose a reason for hiding this comment

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

yeah - ideally we want everything to be attached to the overall LND parent context in some way so that a cancel cancel things like this.

but i think implementing this in a contained way is easier said than done. I think we may need a big LND overhall that makes sure that the same parent context is shared by all subprocesses before we can do this properly

// Otherwise, when living in the same queue, the subsystems are notified of the
// new blocks sequentially, which means it's critical to understand the
// relationship of these systems to properly handle the order.
type BlockbeatDispatcher struct {
Copy link
Collaborator

Choose a reason for hiding this comment

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

you mean that the NotifyBlockProcessed should be a callback when calling processblock ? I think that makes sense.

chainio/dispatcher.go Show resolved Hide resolved
sweep/sweeper.go Show resolved Hide resolved
Copy link
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 🎊

As discussed via other means, the structured logging will not be part of this series and needs a greater change for the whole LND design.

Copy link
Collaborator

@ellemouton ellemouton left a comment

Choose a reason for hiding this comment

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

Really great work & fantastic commit structure 🥇

chainio/README.md Outdated Show resolved Hide resolved
// NOTE: The consumer must try its best to NOT return an error. If an
// error is returned from processing the block, it means the subsystem
// cannot react to onchain state changes and lnd will shutdown.
ProcessBlock(b Blockbeat) error
Copy link
Collaborator

Choose a reason for hiding this comment

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

Are you suggesting we should have the ability to cancel the state change made from calling the methods of a subsystem?

we can have this discussion offline too cause i dont think we need to do this in this pr.
But yes: i think any API interface method should take a context so that if the caller is quiting, then the method they are calling into doesnt just hang while it is busy.

}

// Create a customized logger for the blockbeat.
logPrefix := fmt.Sprintf("Height[%6d]:", b.Height())
Copy link
Collaborator

Choose a reason for hiding this comment

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

it's tricky cause we need to do proper context usage first which is hard to contain to just a single system...

}

// Create a customized logger for the blockbeat.
logPrefix := fmt.Sprintf("Height[%6d]:", b.Height())
Copy link
Collaborator

Choose a reason for hiding this comment

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

does it mean we don't need the prefix logger anymore

yeah we can eventually remove the prefix logger. I think we just need to get used to the k=v pairs at the end & of the log line that we can filter on instead of the prefix. Prefix i think should just be the subsystem.

chainio/dispatcher.go Show resolved Hide resolved
return fmt.Errorf("%s got err in ProcessBlock: %w", c.Name(),
err)

case <-time.After(timeout):
Copy link
Collaborator

Choose a reason for hiding this comment

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

yeah - ideally we want everything to be attached to the overall LND parent context in some way so that a cancel cancel things like this.

but i think implementing this in a contained way is easier said than done. I think we may need a big LND overhall that makes sure that the same parent context is shared by all subprocesses before we can do this properly

// Otherwise, when living in the same queue, the subsystems are notified of the
// new blocks sequentially, which means it's critical to understand the
// relationship of these systems to properly handle the order.
type BlockbeatDispatcher struct {
Copy link
Collaborator

Choose a reason for hiding this comment

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

yeah, could be a Processed method on BlockBeat

yyforyongyu and others added 19 commits November 21, 2024 21:00
This commit inits the package `chainio` and defines the interface
`Blockbeat` and `Consumer`. The `Consumer` must be implemented by other
subsystems if it requires block epoch subscription.
In this commit, a minimal implementation of `Blockbeat` is added to
synchronize block heights, which will be used in `ChainArb`, `Sweeper`,
and `TxPublisher` so blocks are processed sequentially among them.
This commit adds two methods to handle dispatching beats. These are
exported methods so other systems can send beats to their managed
subinstances.
This commit adds a blockbeat dispatcher which handles sending new blocks
to all subscribed consumers.
This commit implements `Consumer` on `TxPublisher`, `UtxoSweeper`,
`ChainArbitrator` and `ChannelArbitrator`.
This commit removes the independent block subscriptions in `UtxoSweeper`
and `TxPublisher`. These subsystems now listen to the `BlockbeatChan`
for new blocks.
This commit removes the hack introduced in #4851. Previously we had this
issue because the chain notifier was stopped before the sweeper, which
was changed a while back and we now always stop the chain notifier last.
In addition, since we no longer subscribe to the block epoch chan
directly, this issue can no longer happen.
The sweeper can handle the waiting so there's no need to wait for blocks
inside the resolvers. By offering the inputs prior to their mature
heights also guarantees the inputs with the same deadline are
aggregated.
This commit removes the block subscriptions used in `ChainArbitrator`
and replaced them with the blockbeat managed by `BlockbeatDispatcher`.
This commit removes the block subscriptions used in `ChannelArbitrator`,
replaced them with the blockbeat managed by `BlockbeatDispatcher`.
This `immediate` flag was added as a hack so during a restart, the
pending resolvers would offer the inputs to the sweeper and ask it to
sweep them immediately. This is no longer need due to `blockbeat`, as
now during restart, a block is always sent to all subsystems via the
flow `ChainArb` -> `ChannelArb` -> resolvers -> sweeper. Thus, when
there are pending inputs offered, they will be processed by the sweeper
immediately.
To avoid calling GetBestBlock again.
This is needed so the consumers have an initial state about the current
block.
In this commit we start to break up the starting process into smaller
pieces, which is needed in the following commit to initialize blockbeat
consumers.
Refactor the `Start` method to fix the linter error:
```
contractcourt/chain_arbitrator.go:568: Function 'Start' is too long (242 > 200) (funlen)
```
@yyforyongyu yyforyongyu merged commit 7295ae3 into yy-feature-blockbeat Nov 21, 2024
15 of 18 checks passed
@yyforyongyu yyforyongyu deleted the yy-blockbeat branch November 21, 2024 14:41
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
no-itest P1 MUST be fixed or reviewed utxo sweeping
Projects
Status: Done
Development

Successfully merging this pull request may close these issues.

7 participants