Skip to content

Commit a0e24f1

Browse files
authored
Delay logs (#730)
## 📝 Summary This PR improved debuggability regarding block build timings: - Added 5 more timestamps: /// UnfinishedBuiltBlocksInput chose this block as the best block and sent it downstream pub chosen_as_best_at: OffsetDateTime, /// Block was sent to the bidder (SlotBidder::notify_new_built_block) pub sent_to_bidder: OffsetDateTime, /// Bid received from the bidder (UnfinishedBuiltBlocksInput::seal_command) pub bid_received_at: OffsetDateTime, /// Bid sent to the sealer thread pub sent_to_sealer: OffsetDateTime, /// Sealer picked by sealer thread pub picked_by_sealer_at: OffsetDateTime, - Added new log when a block is chosen as best block. - Added a global block id to give the blocks an easy identity. - Changed trigger_to_bid_round_trip_time_us metric scale. As an extra it split in a new thread the reception of a new seal command and the presealing so we only preseal the last one. ## ✅ I have completed the following steps: * [X] Run `make lint` * [X] Run `make test` * [ ] Added tests (if applicable)
1 parent 02fe646 commit a0e24f1

File tree

13 files changed

+189
-60
lines changed

13 files changed

+189
-60
lines changed

crates/rbuilder/src/bin/run-bundle-on-prefix.rs

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,10 @@ use rbuilder::{
1111
BlockData, HistoricalDataStorage, OrdersWithTimestamp,
1212
},
1313
building::{
14-
builders::block_building_helper::{BlockBuildingHelper, BlockBuildingHelperFromProvider},
14+
builders::{
15+
block_building_helper::{BlockBuildingHelper, BlockBuildingHelperFromProvider},
16+
BuiltBlockId,
17+
},
1518
order_priority::{FullProfitInfoGetter, OrderMaxProfitPriority},
1619
BlockBuildingContext, ExecutionError, MockRootHasher, NullPartialBlockExecutionTracer,
1720
OrderPriority, ThreadBlockBuildingContext,
@@ -158,6 +161,7 @@ impl LandedBlockInfo {
158161
.into();
159162
let order_statistics = OrderStatistics::new();
160163
Ok(BlockBuildingHelperFromProvider::new(
164+
BuiltBlockId::ZERO,
161165
block_state,
162166
ctx,
163167
&mut self.local_ctx,

crates/rbuilder/src/building/builders/block_building_helper.rs

Lines changed: 21 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -11,12 +11,12 @@ use tracing::{debug, error, trace};
1111

1212
use crate::{
1313
building::{
14-
estimate_payout_gas_limit, tracers::GasUsedSimulationTracer, BlockBuildingContext,
15-
BlockSpace, BlockState, BuiltBlockTrace, BuiltBlockTraceError, CriticalCommitOrderError,
16-
EstimatePayoutGasErr, ExecutionError, ExecutionResult, FinalizeAdjustmentState,
17-
FinalizeError, FinalizeResult, FinalizeRevertStateCurrentIteration,
18-
NullPartialBlockExecutionTracer, PartialBlock, PartialBlockExecutionTracer,
19-
ThreadBlockBuildingContext,
14+
builders::BuiltBlockId, estimate_payout_gas_limit, tracers::GasUsedSimulationTracer,
15+
BlockBuildingContext, BlockSpace, BlockState, BuiltBlockTrace, BuiltBlockTraceError,
16+
CriticalCommitOrderError, EstimatePayoutGasErr, ExecutionError, ExecutionResult,
17+
FinalizeAdjustmentState, FinalizeError, FinalizeResult,
18+
FinalizeRevertStateCurrentIteration, NullPartialBlockExecutionTracer, PartialBlock,
19+
PartialBlockExecutionTracer, ThreadBlockBuildingContext,
2020
},
2121
telemetry::{self, add_block_fill_time, add_order_simulation_time},
2222
utils::{check_block_hash_reader_health, elapsed_ms, HistoricalBlockError},
@@ -75,6 +75,10 @@ pub trait BlockBuildingHelper: Send + Sync {
7575
/// BuiltBlockTrace for current state.
7676
fn built_block_trace(&self) -> &BuiltBlockTrace;
7777

78+
fn id(&self) -> BuiltBlockId {
79+
self.built_block_trace().build_block_id
80+
}
81+
7882
/// BlockBuildingContext used for building.
7983
fn building_context(&self) -> &BlockBuildingContext;
8084

@@ -97,13 +101,15 @@ pub trait BlockBuildingHelper: Send + Sync {
97101
pub struct BiddableUnfinishedBlock {
98102
pub block: Box<dyn BlockBuildingHelper>,
99103
pub true_block_value: U256,
104+
pub chosen_as_best_at: OffsetDateTime,
100105
}
101106

102107
impl Clone for BiddableUnfinishedBlock {
103108
fn clone(&self) -> Self {
104109
Self {
105110
block: self.block.box_clone(),
106111
true_block_value: self.true_block_value,
112+
chosen_as_best_at: self.chosen_as_best_at,
107113
}
108114
}
109115
}
@@ -114,8 +120,12 @@ impl BiddableUnfinishedBlock {
114120
Ok(Self {
115121
block,
116122
true_block_value,
123+
chosen_as_best_at: OffsetDateTime::now_utc(),
117124
})
118125
}
126+
pub fn id(&self) -> BuiltBlockId {
127+
self.block.id()
128+
}
119129

120130
pub fn block(&self) -> &dyn BlockBuildingHelper {
121131
self.block.as_ref()
@@ -189,7 +199,9 @@ pub struct FinalizeBlockResult {
189199
}
190200

191201
impl BlockBuildingHelperFromProvider<NullPartialBlockExecutionTracer> {
202+
#[allow(clippy::too_many_arguments)]
192203
pub fn new(
204+
built_block_id: BuiltBlockId,
193205
state_provider: Arc<dyn StateProvider>,
194206
building_ctx: BlockBuildingContext,
195207
local_ctx: &mut ThreadBlockBuildingContext,
@@ -199,6 +211,7 @@ impl BlockBuildingHelperFromProvider<NullPartialBlockExecutionTracer> {
199211
cancel_on_fatal_error: CancellationToken,
200212
) -> Result<Self, BlockBuildingHelperError> {
201213
BlockBuildingHelperFromProvider::new_with_execution_tracer(
214+
built_block_id,
202215
state_provider,
203216
building_ctx,
204217
local_ctx,
@@ -222,6 +235,7 @@ impl<
222235
/// - Estimate payout tx cost.
223236
#[allow(clippy::too_many_arguments)]
224237
pub fn new_with_execution_tracer(
238+
built_block_id: BuiltBlockId,
225239
state_provider: Arc<dyn StateProvider>,
226240
building_ctx: BlockBuildingContext,
227241
local_ctx: &mut ThreadBlockBuildingContext,
@@ -254,7 +268,7 @@ impl<
254268
partial_block.reserve_block_space(payout_tx_space);
255269
let payout_tx_gas = payout_tx_space.gas;
256270

257-
let mut built_block_trace = BuiltBlockTrace::new();
271+
let mut built_block_trace = BuiltBlockTrace::new(built_block_id);
258272
built_block_trace.available_orders_statistics = available_orders_statistics;
259273
Ok(Self {
260274
_fee_recipient_balance_start: fee_recipient_balance_start,

crates/rbuilder/src/building/builders/mock_block_building_helper.rs

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
use crate::{
22
building::{
3-
BlockBuildingContext, BuiltBlockTrace, CriticalCommitOrderError, ExecutionError,
4-
ExecutionResult, ThreadBlockBuildingContext,
3+
builders::BuiltBlockId, BlockBuildingContext, BuiltBlockTrace, CriticalCommitOrderError,
4+
ExecutionError, ExecutionResult, ThreadBlockBuildingContext,
55
},
66
live_builder::simulation::SimulatedOrderCommand,
77
provider::RootHasher,
@@ -34,7 +34,7 @@ impl MockBlockBuildingHelper {
3434
pub fn new(true_block_value: U256) -> Self {
3535
let built_block_trace = BuiltBlockTrace {
3636
true_bid_value: true_block_value,
37-
..Default::default()
37+
..BuiltBlockTrace::new(BuiltBlockId::ZERO)
3838
};
3939
Self {
4040
built_block_trace,

crates/rbuilder/src/building/builders/mod.rs

Lines changed: 40 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,14 @@ use alloy_eips::eip7594::BlobTransactionSidecarVariant;
2020
use alloy_primitives::{Address, Bytes};
2121
use rbuilder_primitives::{mev_boost::BidAdjustmentData, AccountNonce, OrderId, SimulatedOrder};
2222
use reth::primitives::SealedBlock;
23-
use std::{collections::HashMap, fmt::Debug, sync::Arc};
23+
use std::{
24+
collections::HashMap,
25+
fmt::Debug,
26+
sync::{
27+
atomic::{AtomicU64, Ordering},
28+
Arc,
29+
},
30+
};
2431
use tokio::sync::{
2532
broadcast,
2633
broadcast::error::{RecvError, TryRecvError},
@@ -44,6 +51,36 @@ pub struct Block {
4451
pub bid_adjustments: HashMap<Address, BidAdjustmentData>,
4552
}
4653

54+
/// Id to uniquely identify every block built (unique even among different algorithms).
55+
#[derive(Clone, Copy, Eq, PartialEq, Debug)]
56+
pub struct BuiltBlockId(pub u64);
57+
58+
impl BuiltBlockId {
59+
pub const ZERO: Self = Self(0);
60+
}
61+
62+
#[derive(Debug)]
63+
pub struct BuiltBlockIdSource {
64+
next_id: AtomicU64,
65+
}
66+
67+
impl BuiltBlockIdSource {
68+
pub fn new() -> Self {
69+
Self {
70+
next_id: AtomicU64::new(0),
71+
}
72+
}
73+
pub fn get_new_id(&self) -> BuiltBlockId {
74+
BuiltBlockId(self.next_id.fetch_add(1, Ordering::Relaxed))
75+
}
76+
}
77+
78+
impl Default for BuiltBlockIdSource {
79+
fn default() -> Self {
80+
Self::new()
81+
}
82+
}
83+
4784
#[derive(Debug)]
4885
pub struct LiveBuilderInput<P> {
4986
pub provider: P,
@@ -53,6 +90,7 @@ pub struct LiveBuilderInput<P> {
5390
pub builder_name: String,
5491
pub cancel: CancellationToken,
5592
pub built_block_cache: Arc<BuiltBlockCache>,
93+
pub built_block_id_source: Arc<BuiltBlockIdSource>,
5694
}
5795

5896
/// Struct that helps reading new orders/cancellations
@@ -203,6 +241,7 @@ pub struct BlockBuildingAlgorithmInput<P> {
203241
/// A cache common to several builders so they can optimize their work looking at other builders blocks.
204242
pub built_block_cache: Arc<BuiltBlockCache>,
205243
pub cancel: CancellationToken,
244+
pub built_block_id_source: Arc<BuiltBlockIdSource>,
206245
}
207246

208247
/// Algorithm to build blocks

crates/rbuilder/src/building/builders/ordering_builder.rs

Lines changed: 13 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,8 @@ use crate::{
99
building::{
1010
block_orders_from_sim_orders,
1111
builders::{
12-
block_building_helper::BlockBuildingHelper, LiveBuilderInput, OrderIntakeConsumer,
12+
block_building_helper::BlockBuildingHelper, BuiltBlockId, LiveBuilderInput,
13+
OrderIntakeConsumer,
1314
},
1415
BlockBuildingContext, ExecutionError, NullPartialBlockExecutionTracer, OrderPriority,
1516
PartialBlockExecutionTracer, PrioritizedOrderStore, SimulatedOrderSink, Sorting,
@@ -138,7 +139,11 @@ pub fn run_ordering_builder<P, OrderPriorityType>(
138139
}
139140

140141
let orders = order_intake_consumer.current_block_orders();
141-
match builder.build_block(orders, input.cancel.clone()) {
142+
match builder.build_block(
143+
orders,
144+
input.built_block_id_source.get_new_id(),
145+
input.cancel.clone(),
146+
) {
142147
Ok(block) => {
143148
if let Ok(block) = BiddableUnfinishedBlock::new(block) {
144149
input.sink.new_block(block);
@@ -184,6 +189,7 @@ where
184189
);
185190
let mut block_builder = builder.build_block_with_execution_tracer(
186191
block_orders,
192+
BuiltBlockId::ZERO,
187193
CancellationToken::new(),
188194
partial_block_execution_tracer,
189195
)?;
@@ -235,10 +241,12 @@ impl OrderingBuilderContext {
235241
pub fn build_block<OrderPriorityType: OrderPriority>(
236242
&mut self,
237243
block_orders: PrioritizedOrderStore<OrderPriorityType>,
244+
built_block_id: BuiltBlockId,
238245
cancel_block: CancellationToken,
239246
) -> eyre::Result<Box<dyn BlockBuildingHelper>> {
240247
self.build_block_with_execution_tracer(
241248
block_orders,
249+
built_block_id,
242250
cancel_block,
243251
NullPartialBlockExecutionTracer {},
244252
)
@@ -253,6 +261,7 @@ impl OrderingBuilderContext {
253261
>(
254262
&mut self,
255263
mut block_orders: PrioritizedOrderStore<OrderPriorityType>,
264+
built_block_id: BuiltBlockId,
256265
cancel_block: CancellationToken,
257266
partial_block_execution_tracer: PartialBlockExecutionTracerType,
258267
) -> eyre::Result<Box<dyn BlockBuildingHelper>> {
@@ -267,6 +276,7 @@ impl OrderingBuilderContext {
267276
self.order_attempts.clear();
268277

269278
let mut block_building_helper = BlockBuildingHelperFromProvider::new_with_execution_tracer(
279+
built_block_id,
270280
self.state.clone(),
271281
self.ctx.clone(),
272282
&mut self.local_ctx,
@@ -468,6 +478,7 @@ where
468478
builder_name: self.name.clone(),
469479
cancel: input.cancel,
470480
built_block_cache: input.built_block_cache,
481+
built_block_id_source: input.built_block_id_source,
471482
};
472483
run_ordering_builder::<P, OrderPriorityType>(live_input, &self.config);
473484
}

crates/rbuilder/src/building/builders/parallel_builder/block_building_result_assembler.rs

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,7 @@ use crate::{
1616
block_building_helper::{
1717
BiddableUnfinishedBlock, BlockBuildingHelper, BlockBuildingHelperFromProvider,
1818
},
19-
handle_building_error,
19+
handle_building_error, BuiltBlockIdSource,
2020
},
2121
BlockBuildingContext, ThreadBlockBuildingContext,
2222
},
@@ -38,6 +38,7 @@ pub struct BlockBuildingResultAssembler {
3838
best_results: Arc<BestResults>,
3939
run_id: u64,
4040
last_version: Option<u64>,
41+
built_block_id_source: Arc<BuiltBlockIdSource>,
4142
}
4243

4344
impl BlockBuildingResultAssembler {
@@ -58,6 +59,7 @@ impl BlockBuildingResultAssembler {
5859
cancellation_token: CancellationToken,
5960
builder_name: String,
6061
sink: Option<UnfinishedBuiltBlocksInput>,
62+
built_block_id_source: Arc<BuiltBlockIdSource>,
6163
) -> Self {
6264
Self {
6365
state,
@@ -70,6 +72,7 @@ impl BlockBuildingResultAssembler {
7072
best_results,
7173
run_id: 0,
7274
last_version: None,
75+
built_block_id_source,
7376
}
7477
}
7578

@@ -178,6 +181,7 @@ impl BlockBuildingResultAssembler {
178181
let build_start = Instant::now();
179182

180183
let mut block_building_helper = BlockBuildingHelperFromProvider::new(
184+
self.built_block_id_source.get_new_id(),
181185
self.state.clone(),
182186
self.ctx.clone(),
183187
&mut self.local_ctx,
@@ -251,6 +255,7 @@ impl BlockBuildingResultAssembler {
251255
orders_closed_at: OffsetDateTime,
252256
) -> eyre::Result<Box<dyn BlockBuildingHelper>> {
253257
let mut block_building_helper = BlockBuildingHelperFromProvider::new(
258+
self.built_block_id_source.get_new_id(),
254259
self.state.clone(),
255260
self.ctx.clone(),
256261
&mut self.local_ctx,

crates/rbuilder/src/building/builders/parallel_builder/mod.rs

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -32,7 +32,7 @@ use tracing::{error, trace};
3232
use crate::{
3333
building::builders::{
3434
BacktestSimulateBlockInput, Block, BlockBuildingAlgorithm, BlockBuildingAlgorithmInput,
35-
LiveBuilderInput,
35+
BuiltBlockIdSource, LiveBuilderInput,
3636
},
3737
provider::StateProviderFactory,
3838
utils::elapsed_ms,
@@ -133,6 +133,7 @@ where
133133
input.cancel.clone(),
134134
input.builder_name.clone(),
135135
Some(input.sink.clone()),
136+
input.built_block_id_source.clone(),
136137
);
137138

138139
let order_intake_consumer = OrderIntakeStore::new(input.input);
@@ -350,6 +351,7 @@ where
350351
CancellationToken::new(),
351352
String::from("backtest_builder"),
352353
None,
354+
Arc::new(BuiltBlockIdSource::new()),
353355
);
354356
let assembler_duration = assembler_start.elapsed();
355357

@@ -418,6 +420,7 @@ where
418420
builder_name: self.name.clone(),
419421
cancel: input.cancel,
420422
built_block_cache: input.built_block_cache,
423+
built_block_id_source: input.built_block_id_source,
421424
};
422425
run_parallel_builder(live_input, &self.config);
423426
}

0 commit comments

Comments
 (0)