Skip to content

Commit bfaeedd

Browse files
Evalirprestwich
andauthored
fix: properly calculate deadline, use chrono for calculating timestamps (#123)
* chore: use chrono, debug * quick mafs * chore: productionize * refactor: simplify slot_still_valid * fix: convert calc debugs into span attrs * Update src/tasks/submit/task.rs --------- Co-authored-by: James <[email protected]>
1 parent 0b6779a commit bfaeedd

File tree

5 files changed

+47
-48
lines changed

5 files changed

+47
-48
lines changed

Cargo.lock

Lines changed: 1 addition & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

Cargo.toml

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -54,6 +54,7 @@ openssl = { version = "0.10", features = ["vendored"] }
5454
reqwest = { version = "0.11.24", features = ["blocking", "json"] }
5555
serde_json = "1.0"
5656
tokio = { version = "1.36.0", features = ["full", "macros", "rt-multi-thread"] }
57+
chrono = "0.4.40"
5758

5859
tokio-stream = "0.1.17"
5960
url = "2.5.4"

src/tasks/block/sim.rs

Lines changed: 13 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,7 @@ use tokio::{
2020
},
2121
task::JoinHandle,
2222
};
23-
use tracing::info;
23+
use tracing::{Instrument, info, instrument};
2424
use trevm::revm::{
2525
context::BlockEnv,
2626
database::{AlloyDB, WrapDatabaseAsync},
@@ -92,14 +92,18 @@ impl Simulator {
9292
/// # Returns
9393
///
9494
/// A `Result` containing the built block or an error.
95+
#[instrument(skip_all, fields(
96+
block_number = block_env.number,
97+
tx_count = sim_items.len(),
98+
millis_to_deadline = finish_by.duration_since(Instant::now()).as_millis()
99+
))]
95100
pub async fn handle_build(
96101
&self,
97102
constants: SignetSystemConstants,
98103
sim_items: SimCache,
99104
finish_by: Instant,
100105
block_env: BlockEnv,
101106
) -> eyre::Result<BuiltBlock> {
102-
debug!(block_number = block_env.number, tx_count = sim_items.len(), "starting block build",);
103107
let concurrency_limit = self.config.concurrency_limit();
104108

105109
// NB: Build AlloyDB from the previous block number's state, since block_env maps to the in-progress block
@@ -116,7 +120,7 @@ impl Simulator {
116120
self.config.rollup_block_gas_limit,
117121
);
118122

119-
let built_block = block_build.build().await;
123+
let built_block = block_build.build().in_current_span().await;
120124
debug!(
121125
tx_count = built_block.tx_count(),
122126
block_number = built_block.block_number(),
@@ -205,21 +209,20 @@ impl Simulator {
205209
///
206210
/// # Returns
207211
///
208-
/// An `Instant` representing the simulation deadline, as calculated by determining
209-
/// the time left in the current slot and adding that to the current timestamp in UNIX seconds.
212+
/// An `Instant` representing the simulation deadline, as calculated by
213+
/// determining the time left in the current slot and adding that to the
214+
/// current timestamp in UNIX seconds.
210215
pub fn calculate_deadline(&self) -> Instant {
211216
// Get the current timepoint within the slot.
212217
let timepoint =
213218
self.slot_calculator().current_point_within_slot().expect("host chain has started");
214219

215220
// We have the timepoint in seconds into the slot. To find out what's
216221
// remaining, we need to subtract it from the slot duration
217-
let remaining = self.slot_calculator().slot_duration() - timepoint;
218-
219-
// We add a 2500 ms buffer to account for sequencer stopping signing.
220-
let deadline =
221-
Instant::now() + Duration::from_secs(remaining) - Duration::from_millis(2500);
222+
// we also subtract 3 seconds to account for the sequencer stopping signing.
223+
let remaining = (self.slot_calculator().slot_duration() - timepoint).saturating_sub(3);
222224

225+
let deadline = Instant::now() + Duration::from_secs(remaining);
223226
deadline.max(Instant::now())
224227
}
225228

src/tasks/submit/task.rs

Lines changed: 31 additions & 35 deletions
Original file line numberDiff line numberDiff line change
@@ -37,6 +37,21 @@ macro_rules! spawn_provider_send {
3737
};
3838
}
3939

40+
macro_rules! check_slot_still_valid {
41+
($self:expr, $initial_slot:expr) => {
42+
if !$self.slot_still_valid($initial_slot) {
43+
debug!(
44+
current_slot =
45+
$self.config.slot_calculator.current_slot().expect("host chain has started"),
46+
initial_slot = $initial_slot,
47+
"slot changed before submission - skipping block"
48+
);
49+
counter!("builder.slot_missed").increment(1);
50+
return Ok(ControlFlow::Skip);
51+
}
52+
};
53+
}
54+
4055
/// Control flow for transaction submission.
4156
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
4257
pub enum ControlFlow {
@@ -130,18 +145,9 @@ impl SubmitTask {
130145
retry_limit: usize,
131146
) -> eyre::Result<ControlFlow> {
132147
let submitting_start_time = Instant::now();
133-
let now = utils::now();
134148

135149
let (expected_slot, window) = self.get_expected_slot_and_window();
136150

137-
debug!(
138-
expected_slot,
139-
start = window.start,
140-
end = window.end,
141-
now,
142-
"calculating target slot window"
143-
);
144-
145151
let mut req = bumpable.req().clone();
146152

147153
// Retry loop
@@ -151,27 +157,26 @@ impl SubmitTask {
151157
"SubmitTask::retrying_send",
152158
retries = bumpable.bump_count(),
153159
nonce = bumpable.req().nonce,
160+
expected_slot,
161+
start = window.start,
162+
end = window.end,
163+
unix_now = utils::now(),
154164
);
155165

156-
let inbound_result = match self.send_transaction(req).instrument(span.clone()).await {
157-
Ok(control_flow) => control_flow,
158-
Err(error) => {
159-
if let Some(value) = self.slot_still_valid(expected_slot) {
160-
return value;
161-
}
162-
// Log error and retry
163-
error!(%error, "error handling inbound block");
164-
ControlFlow::Retry
165-
}
166-
};
166+
// Check at the top of the loop if the slot is still valid. This
167+
// will prevent unnecessary retries if the slot has changed.
168+
check_slot_still_valid!(self, expected_slot);
167169

168-
let guard = span.entered();
170+
let inbound_result = self
171+
.send_transaction(req)
172+
.instrument(span.clone())
173+
.await
174+
.inspect_err(|e| error!(error = %e, "error sending transaction"))
175+
.unwrap_or(ControlFlow::Retry);
169176

177+
let guard = span.entered();
170178
match inbound_result {
171179
ControlFlow::Retry => {
172-
if let Some(value) = self.slot_still_valid(expected_slot) {
173-
return value;
174-
}
175180
// bump the req
176181
req = bumpable.bumped();
177182
if bumpable.bump_count() > retry_limit {
@@ -221,17 +226,8 @@ impl SubmitTask {
221226
}
222227

223228
/// Checks if a slot is still valid during submission retries.
224-
fn slot_still_valid(&self, initial_slot: usize) -> Option<Result<ControlFlow, eyre::Error>> {
225-
let current_slot =
226-
self.config.slot_calculator.current_slot().expect("host chain has started");
227-
if current_slot != initial_slot {
228-
// If the slot has changed, skip the block
229-
debug!(current_slot, initial_slot, "slot changed before submission - skipping block");
230-
counter!("builder.slot_missed").increment(1);
231-
return Some(Ok(ControlFlow::Skip));
232-
}
233-
debug!(current_slot, "slot still valid - continuing submission");
234-
None
229+
fn slot_still_valid(&self, initial_slot: usize) -> bool {
230+
initial_slot == self.config.slot_calculator.current_slot().expect("host chain has started")
235231
}
236232

237233
/// Task future for the submit task. This function runs the main loop of the task.

src/utils.rs

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -6,12 +6,10 @@ use alloy::{
66
};
77
use signet_sim::BuiltBlock;
88
use signet_zenith::BundleHelper::FillPermit2;
9-
use std::time::UNIX_EPOCH;
109

1110
/// Returns the current timestamp in seconds since the UNIX epoch.
1211
pub(crate) fn now() -> u64 {
13-
let now = std::time::SystemTime::now();
14-
now.duration_since(UNIX_EPOCH).unwrap().as_secs()
12+
chrono::Utc::now().timestamp() as u64
1513
}
1614

1715
// This function converts &[SignedFill] into [FillPermit2]

0 commit comments

Comments
 (0)