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

Structured Concurrency: Part 2 #1216

Merged
merged 22 commits into from
Oct 1, 2024
Merged

Conversation

rakanalh
Copy link
Contributor

@rakanalh rakanalh commented Sep 23, 2024

Description

Related to #1214 so this is to be merged AFTER.

This PR:

  • Primitives:
    • Introduces TaskManager: Calling spawn using the task manager would force the future-to-be-spawned to accept a cancellation token so that all tasks using the task manager are cancellable.
  • DaService:
    • Replaces tokio::spawn for each transaction queue call with a single worker.
    • Replaces an additional long running task for logging
  • Sequencer
    • Spawns tasks using TaskManager.
    • Since most tasks which are running in the sequencer are running in a single tokio task, handling ctrl-c event would be sufficient since tokio::select is going to execute the ctrl-c signal to stop all current tasks. This means that no other branch of tokio::select is going to be executed concurrently.
  • Full Node
    • Spawns tasks using TaskManager.
    • Use cancellation token to shutdown DA handler
  • Prover
    • Spawns tasks using TaskManager.
    • Use cancellation token to shutdown DA handler

Task cancellation

For tasks which are spawned by the task manager, all tasks are expected to use the cancellation_token. Most of the uses of the token would come inside the tokio::select. This means that if all futures inside this select are running in a single task, notifying the task with the cancellation token means that we have to finish processing whatever the task is currently doing in-hand and return control back to tokio::select in order for the cancellation token to be seen as cancelled and then the component currently running is stopped.

Linked Issues

Refs:

Copy link
Contributor

@kpp kpp left a comment

Choose a reason for hiding this comment

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

bitcoin-da should be updated too

@rakanalh
Copy link
Contributor Author

bitcoin-da should be updated too

bitcoin-da does not use tokio::spawn anywhere. Are there specific parts you'd like to update?

@kpp
Copy link
Contributor

kpp commented Sep 23, 2024

 172   │     pub fn spawn_da_queue(
 173   │         self: Arc<Self>,
 174   │         mut rx: UnboundedReceiver<SenderWithNotifier<TxidWrapper>>,
 175   │     ) {
 176   │         // This is a queue of inscribe requests
 177   │         tokio::task::spawn_blocking(|| {

@rakanalh
Copy link
Contributor Author

rakanalh commented Sep 23, 2024

 172   │     pub fn spawn_da_queue(
 173   │         self: Arc<Self>,
 174   │         mut rx: UnboundedReceiver<SenderWithNotifier<TxidWrapper>>,
 175   │     ) {
 176   │         // This is a queue of inscribe requests
 177   │         tokio::task::spawn_blocking(|| {

I haven't look at the code here yet and maybe it does need some refactoring. However, based on Tokio's documentation for spawn_blocking:

Be aware that tasks spawned using spawn_blocking cannot be aborted because they are not async. If you call abort on a spawn_blocking task, then this will not have any effect, and the task will continue running normally. The exception is if the task has not started running yet; in that case, calling abort may prevent the task from starting.

We might be able to pull off cancellation of a blocking task using a cancellation token... i'll look into that.

@rakanalh rakanalh force-pushed the rakanalh/structured-concurrency-pt2 branch from 0d0c449 to 4a51289 Compare September 23, 2024 21:24
@kpp
Copy link
Contributor

kpp commented Sep 23, 2024

So there are 2 things a tokio task is doing - to process get_fee_rate (can be a separate task) and to send_transaction_with_fee_rate - which is mining a tx prefix inside.

@rakanalh
Copy link
Contributor Author

So there are 2 things a tokio task is doing - to process get_fee_rate (can be a separate task) and to send_transaction_with_fee_rate - which is mining a tx prefix inside.

get_fee_rate cannot be a separate task because we're fetching the value so that we can pass it to send_transaction_with_fee_rate

@rakanalh rakanalh requested a review from kpp September 24, 2024 10:35
@rakanalh rakanalh force-pushed the rakanalh/structured-concurrency-pt2 branch from b21f310 to 667b653 Compare September 24, 2024 22:07
@rakanalh rakanalh force-pushed the rakanalh/structured-concurrency-pt2 branch from 667b653 to f6b7eef Compare September 25, 2024 10:27
@rakanalh rakanalh mentioned this pull request Sep 25, 2024
Base automatically changed from rakanalh/structured-concurrency-pt1 to nightly September 30, 2024 11:31
Copy link

codecov bot commented Sep 30, 2024

Codecov Report

Attention: Patch coverage is 80.98160% with 31 lines in your changes missing coverage. Please review.

Project coverage is 77.8%. Comparing base (68f32a2) to head (fa1deea).
Report is 1 commits behind head on nightly.

Files with missing lines Patch % Lines
crates/bitcoin-da/src/service.rs 28.5% 20 Missing ⚠️
crates/common/src/tasks/manager.rs 73.9% 6 Missing ⚠️
crates/fullnode/src/runner.rs 96.1% 2 Missing ⚠️
bin/citrea/src/rollup/bitcoin.rs 0.0% 1 Missing ⚠️
crates/fullnode/src/lib.rs 0.0% 1 Missing ⚠️
crates/prover/src/lib.rs 0.0% 1 Missing ⚠️
Additional details and impacted files
Files with missing lines Coverage Δ
crates/fullnode/src/da_block_handler.rs 74.0% <100.0%> (+<0.1%) ⬆️
crates/prover/src/da_block_handler.rs 81.2% <100.0%> (-0.2%) ⬇️
crates/prover/src/runner.rs 87.8% <100.0%> (+3.4%) ⬆️
crates/sequencer/src/sequencer.rs 91.7% <100.0%> (+1.4%) ⬆️
...ates/sovereign-sdk/adapters/mock-da/src/service.rs 95.7% <100.0%> (+<0.1%) ⬆️
bin/citrea/src/rollup/bitcoin.rs 0.0% <0.0%> (ø)
crates/fullnode/src/lib.rs 50.0% <0.0%> (ø)
crates/prover/src/lib.rs 50.0% <0.0%> (ø)
crates/fullnode/src/runner.rs 89.2% <96.1%> (+3.4%) ⬆️
crates/common/src/tasks/manager.rs 73.9% <73.9%> (ø)
... and 1 more

... and 1 file with indirect coverage changes

Copy link
Contributor

@kpp kpp left a comment

Choose a reason for hiding this comment

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

LGMT but please note my comments

Copy link
Member

@ercecan ercecan left a comment

Choose a reason for hiding this comment

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

LGTM overall but I believe l1 and l2 sync can also be managed with task manager? I would like to hear your thoughts on this

crates/bitcoin-da/src/service.rs Show resolved Hide resolved
crates/bitcoin-da/src/service.rs Outdated Show resolved Hide resolved
crates/fullnode/src/runner.rs Show resolved Hide resolved
crates/primitives/src/lib.rs Outdated Show resolved Hide resolved
@rakanalh
Copy link
Contributor Author

rakanalh commented Oct 1, 2024

Shouldn't l1_sync_worker also be spawned with task_manager?

LGTM overall but I believe l1 and l2 sync can also be managed with task manager? I would like to hear your thoughts on this

if we can also pass the cancellation_token into l2 sync, we can make sure we committed db correctly before shutting down and that would be great

The reason we don't spawn sync_l1 and sync_l2 by the task manager is because it is already managed by it's own tokio::select loop. On our cancellation request, sync_l2 for example would finish it's work before ctrl_c signal is handled if a sync task was already running. For the tasks that we spawn as separate tasks, we would use the task manager to cancel them.

So, tasks which are running outside the select loop in sequencer / full node / prover would be cancelled by task manager's cancellation token. But the ones running inside would be cancelled by the ctrl_c signal.

@rakanalh rakanalh merged commit 87e6fc8 into nightly Oct 1, 2024
13 of 14 checks passed
@rakanalh rakanalh deleted the rakanalh/structured-concurrency-pt2 branch October 1, 2024 10:26
@eyusufatik eyusufatik mentioned this pull request Oct 7, 2024
82 tasks
eyusufatik added a commit that referenced this pull request Oct 9, 2024
* Structured concurrency: Part 1 (#1214)

* Implement managed tasks for SubscriptionManager

* Fix clippy

* Add comment about trace task

* Use broadcast instead of mpsc for l2 blocks events

* Fix typo (#1246)

* Structured Concurrency: Part 2 (#1216)

* Implement managed tasks for SubscriptionManager

* Fix clippy

* Add comment about trace task

* Use broadcast instead of mpsc for l2 blocks events

* Fix spawns in DaService

* Add TaskManager

* Use task manager in sequencer

* Document TaskManager

* Handle shutdown event

* Use TaskTracker

* Add comment about using a cancellation token

* Use JoinHandles instead of TaskTracker

* Use TaskManager in fullnode and prover

* Improve bitcoin-da service

* Force spawned tasks to accept a cancellation token

* Use biased polling

* Satisfy clippy

* Address PR feedback

* Fix checks

* Pin foundry (#1253)

* Pin foundary

* Add comment

* Remove puclihs mock da block script

* Use default block time on error (#1244)

* Use default block time on error

* Constant target_block_time

* Remove import

* Dump logs and cleanup on assert failures (#1252)

* Fix estiamte gas l1 fee issue when metamask max amount is selected (#1261)

* Fix estiamte gas l1 fee issue when metamask max amount is selected

* Fix tests

* Remove unnecessary comment

* Fix hive (#1263)

* Fix configs

* Remove publish mock block from docker

* Update port for hive

* Rename config in hive

* Refactor eth estimate gas l1 fee issue (#1264)

* Refactor eth estimate gas l1 fee issue

* Nits

* Fix bug

* Refactor

* Do not ignore resources

* Fix

---------

Co-authored-by: Roman Proskuryakoff <[email protected]>

* Pruning skeleton (#1229)

* Implement managed tasks for SubscriptionManager

* Fix clippy

* Add comment about trace task

* Use broadcast instead of mpsc for l2 blocks events

* Fix spawns in DaService

* Add TaskManager

* Use task manager in sequencer

* Document TaskManager

* Handle shutdown event

* Use TaskTracker

* Add comment about using a cancellation token

* Use JoinHandles instead of TaskTracker

* Use TaskManager in fullnode and prover

* Improve bitcoin-da service

* Force spawned tasks to accept a cancellation token

* Use biased polling

* Satisfy clippy

* WIP

* Add pruning tables

* Pruning skeleton implementation

* Use pruner in nodes

* Use biased polling based on order

* WIP

* Fix how config is done

* Derive default

* Add logs

* Let the tasks finish without panicing

* Use pruning config in fullnode and prover

* Add simple run test

* Use option instead of PruningMode

* Unneccessary changes

* l2_receiver

* Cleanup prints

* Use last pruned block in calculation

* Implement pruning criteria

* Lint and add comment

* Set the last_pruned_block to up_to_block value

* Don't store config internally

* Remove from constructor

* Should not change

* Move config value

* Remove pruning from sequencer / prover

* Derive SequencerClient (#1269)

* Derive SequencerClient

* Renames

* Lint

* Improve estimate gas and create access list rpcs (#1265)

* Remove unnecessary transact_to conversion

* unwrap_or_default

* More concise block_env initialization

* Actually get highest gas limit from request and block env

* One liner set

* Allow unused

* Cleanup prepare_call_env

* Fix tests & lint

* Replace unwrap

* Set state to block in eth_call

* Consume request in prepare_call_env

* Lint

* Set state before reading config

* Remove unnecessary clone

* Replace allow unused with feature native gate

* Add sys txs to evm tests (#1255)

* modify config_push_contracts

* modify call_multiple_test

* modify tests in call_tests.rs

* moving common functions to utils.rs

* minor fixes

* updated lock files

* modify tests

---------

Co-authored-by: Esad Yusuf Atik <[email protected]>

* make prover config arg not optional (#1278)

* Pin to 27.1 (#1279)

* E2E tests using citrea-e2e (#1277)

* E2E tests using citrea-e2e

* Lint

* Set CITREA path

* With github.workspace

* Target citrea-e2e main

* Update citrea-e2e rev

* Use debug build

* Update citrea-e2e

* Prover generate input rpc (#1280)

* WIP Implement prover generate rpcg

* It compiles but stf is modified

* Context

* Fix Context: Send

* Merge fix

* Move function from common to prover

* Remove code duplicate and unnecessary log

* Add optional parameter to break commitments into groups

* Return input as string

---------

Co-authored-by: Roman Proskuryakoff <[email protected]>

* Move node configs to citrea-common (#1286)

* move node configs to a seperate crate

* fix udeps

* remove native feature

* move SequencerConfig

* move config to citrea-common

* fix use statements

* Update e2e test framework and fix tests (#1305)

* Update e2e test framework and fix tests

* Fix bug

* Update ci binary env key

* Test if new fix works

* Update bitcoincore-rpc version

* Dprint

* Try against fix prover config rev

* Target main HEAD rev

---------

Co-authored-by: jfldde <[email protected]>

* build and publish a new image for every commit to the nightly branch (#1309)

* Get fee recommendation from mempool space (#1302)

* Get fee recommendation from mempool space

* Fix bug

* Construct mempool space endpoint by network

---------

Co-authored-by: Esad Yusuf Atik <[email protected]>

* new path fix for nightly (#1310)

* Enable pending block tag in simulation endpoints (#1303)

* treat pending tag same as latest

* fix lint

* return new sealed block for pending

* handle pending tag externally

* revert enabling pending in some endpoints

* get blockenv instead of sealed block

* address review comments

* implement tests for eth_call, eth_estimateGas, eth_createAccessList pending blocks

* rename tests

---------

Co-authored-by: eyusufatik <[email protected]>

* Implement state and block overrides (#1270)

* Implement state and block overrides

* Update comment

* apply_block_overrides func

* apply_state_overrides func

* Use a single func for replacing account storage

* Clippy

* Address feedback

Use Reth's BlockOverrides with saturating_to to convert back to u64

* Test for block overrides

* Test for state overrides

* Comment tests

* Create a fresh working set

* Remove box

* remove alloy-serde

---------

Co-authored-by: eyusufatik <[email protected]>

* Use spawn_blocking for da queue (#1311)

* Fetch smart fee only if none (#1312)

* update run doc and changelog (#1315)

---------

Co-authored-by: Rakan Al-Huneiti <[email protected]>
Co-authored-by: Ahmet Yazıcı <[email protected]>
Co-authored-by: Erce Can Bektüre <[email protected]>
Co-authored-by: jfldde <[email protected]>
Co-authored-by: Erce Can Bektüre <[email protected]>
Co-authored-by: Roman Proskuryakoff <[email protected]>
Co-authored-by: Ege Okan Ünaldı <[email protected]>
Co-authored-by: Çetin <[email protected]>
eyusufatik added a commit that referenced this pull request Oct 9, 2024
* Structured concurrency: Part 1 (#1214)

* Implement managed tasks for SubscriptionManager

* Fix clippy

* Add comment about trace task

* Use broadcast instead of mpsc for l2 blocks events

* Fix typo (#1246)

* Structured Concurrency: Part 2 (#1216)

* Implement managed tasks for SubscriptionManager

* Fix clippy

* Add comment about trace task

* Use broadcast instead of mpsc for l2 blocks events

* Fix spawns in DaService

* Add TaskManager

* Use task manager in sequencer

* Document TaskManager

* Handle shutdown event

* Use TaskTracker

* Add comment about using a cancellation token

* Use JoinHandles instead of TaskTracker

* Use TaskManager in fullnode and prover

* Improve bitcoin-da service

* Force spawned tasks to accept a cancellation token

* Use biased polling

* Satisfy clippy

* Address PR feedback

* Fix checks

* Pin foundry (#1253)

* Pin foundary

* Add comment

* Remove puclihs mock da block script

* Use default block time on error (#1244)

* Use default block time on error

* Constant target_block_time

* Remove import

* Dump logs and cleanup on assert failures (#1252)

* Fix estiamte gas l1 fee issue when metamask max amount is selected (#1261)

* Fix estiamte gas l1 fee issue when metamask max amount is selected

* Fix tests

* Remove unnecessary comment

* Fix hive (#1263)

* Fix configs

* Remove publish mock block from docker

* Update port for hive

* Rename config in hive

* Refactor eth estimate gas l1 fee issue (#1264)

* Refactor eth estimate gas l1 fee issue

* Nits

* Fix bug

* Refactor

* Do not ignore resources

* Fix

---------

Co-authored-by: Roman Proskuryakoff <[email protected]>

* Pruning skeleton (#1229)

* Implement managed tasks for SubscriptionManager

* Fix clippy

* Add comment about trace task

* Use broadcast instead of mpsc for l2 blocks events

* Fix spawns in DaService

* Add TaskManager

* Use task manager in sequencer

* Document TaskManager

* Handle shutdown event

* Use TaskTracker

* Add comment about using a cancellation token

* Use JoinHandles instead of TaskTracker

* Use TaskManager in fullnode and prover

* Improve bitcoin-da service

* Force spawned tasks to accept a cancellation token

* Use biased polling

* Satisfy clippy

* WIP

* Add pruning tables

* Pruning skeleton implementation

* Use pruner in nodes

* Use biased polling based on order

* WIP

* Fix how config is done

* Derive default

* Add logs

* Let the tasks finish without panicing

* Use pruning config in fullnode and prover

* Add simple run test

* Use option instead of PruningMode

* Unneccessary changes

* l2_receiver

* Cleanup prints

* Use last pruned block in calculation

* Implement pruning criteria

* Lint and add comment

* Set the last_pruned_block to up_to_block value

* Don't store config internally

* Remove from constructor

* Should not change

* Move config value

* Remove pruning from sequencer / prover

* Derive SequencerClient (#1269)

* Derive SequencerClient

* Renames

* Lint

* Improve estimate gas and create access list rpcs (#1265)

* Remove unnecessary transact_to conversion

* unwrap_or_default

* More concise block_env initialization

* Actually get highest gas limit from request and block env

* One liner set

* Allow unused

* Cleanup prepare_call_env

* Fix tests & lint

* Replace unwrap

* Set state to block in eth_call

* Consume request in prepare_call_env

* Lint

* Set state before reading config

* Remove unnecessary clone

* Replace allow unused with feature native gate

* Add sys txs to evm tests (#1255)

* modify config_push_contracts

* modify call_multiple_test

* modify tests in call_tests.rs

* moving common functions to utils.rs

* minor fixes

* updated lock files

* modify tests

---------

Co-authored-by: Esad Yusuf Atik <[email protected]>

* make prover config arg not optional (#1278)

* Pin to 27.1 (#1279)

* E2E tests using citrea-e2e (#1277)

* E2E tests using citrea-e2e

* Lint

* Set CITREA path

* With github.workspace

* Target citrea-e2e main

* Update citrea-e2e rev

* Use debug build

* Update citrea-e2e

* Prover generate input rpc (#1280)

* WIP Implement prover generate rpcg

* It compiles but stf is modified

* Context

* Fix Context: Send

* Merge fix

* Move function from common to prover

* Remove code duplicate and unnecessary log

* Add optional parameter to break commitments into groups

* Return input as string

---------

Co-authored-by: Roman Proskuryakoff <[email protected]>

* Move node configs to citrea-common (#1286)

* move node configs to a seperate crate

* fix udeps

* remove native feature

* move SequencerConfig

* move config to citrea-common

* fix use statements

* Update e2e test framework and fix tests (#1305)

* Update e2e test framework and fix tests

* Fix bug

* Update ci binary env key

* Test if new fix works

* Update bitcoincore-rpc version

* Dprint

* Try against fix prover config rev

* Target main HEAD rev

---------

Co-authored-by: jfldde <[email protected]>

* build and publish a new image for every commit to the nightly branch (#1309)

* Get fee recommendation from mempool space (#1302)

* Get fee recommendation from mempool space

* Fix bug

* Construct mempool space endpoint by network

---------

Co-authored-by: Esad Yusuf Atik <[email protected]>

* new path fix for nightly (#1310)

* Enable pending block tag in simulation endpoints (#1303)

* treat pending tag same as latest

* fix lint

* return new sealed block for pending

* handle pending tag externally

* revert enabling pending in some endpoints

* get blockenv instead of sealed block

* address review comments

* implement tests for eth_call, eth_estimateGas, eth_createAccessList pending blocks

* rename tests

---------

Co-authored-by: eyusufatik <[email protected]>

* Implement state and block overrides (#1270)

* Implement state and block overrides

* Update comment

* apply_block_overrides func

* apply_state_overrides func

* Use a single func for replacing account storage

* Clippy

* Address feedback

Use Reth's BlockOverrides with saturating_to to convert back to u64

* Test for block overrides

* Test for state overrides

* Comment tests

* Create a fresh working set

* Remove box

* remove alloy-serde

---------

Co-authored-by: eyusufatik <[email protected]>

* Use spawn_blocking for da queue (#1311)

* Fetch smart fee only if none (#1312)

* update run doc and changelog (#1315)

---------

Co-authored-by: Rakan Al-Huneiti <[email protected]>
Co-authored-by: Ahmet Yazıcı <[email protected]>
Co-authored-by: Erce Can Bektüre <[email protected]>
Co-authored-by: jfldde <[email protected]>
Co-authored-by: Erce Can Bektüre <[email protected]>
Co-authored-by: Roman Proskuryakoff <[email protected]>
Co-authored-by: Ege Okan Ünaldı <[email protected]>
Co-authored-by: Çetin <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
4 participants