Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
65 changes: 60 additions & 5 deletions crates/core/src/host/scheduler.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ use crate::db::relational_db::RelationalDB;
use crate::host::module_host::{CallProcedureParams, ModuleInfo};
use crate::host::wasm_common::module_host_actor::{InstanceCommon, WasmInstance};
use crate::host::{InvalidProcedureArguments, InvalidReducerArguments, NoSuchModule};
use crate::worker_metrics::WORKER_METRICS;
use anyhow::anyhow;
use core::time::Duration;
use futures::{FutureExt, StreamExt};
Expand Down Expand Up @@ -190,6 +191,9 @@ const MAX_SCHEDULE_DELAY: Duration = Duration::from_millis(
(1 << (6 * 6)) - 1,
);

/// Record when a scheduled function starts more than this long after it was due.
const RECORD_SCHEDULED_FUNCTION_DELAY_THRESHOLD: Duration = Duration::from_millis(50);

#[derive(thiserror::Error, Debug)]
pub enum ScheduleError {
#[error("Unable to schedule with long delay at {0:?}")]
Expand Down Expand Up @@ -447,8 +451,9 @@ struct Reschedule {
enum ScheduledProcedureStep {
Done(CallScheduledFunctionResult, bool),
Procedure {
params: CallProcedureParams,
params: Box<CallProcedureParams>,
reschedule: Option<Reschedule>,
delay: Option<(Arc<str>, Duration)>,
},
}

Expand All @@ -465,9 +470,17 @@ pub(super) async fn call_scheduled_procedure(
// even though it has been already moved during `delete_scheduled_function_row` call.
match next_step {
ScheduledProcedureStep::Done(result, trapped) => (result, trapped),
ScheduledProcedureStep::Procedure { params, reschedule } => {
ScheduledProcedureStep::Procedure {
params,
reschedule,
delay,
} => {
if let Some((function_name, delay)) = delay.as_ref() {
record_scheduled_function_delay(module_info, function_name, *delay);
}

// Execute the procedure. See above for commentary on `catch_unwind()`.
let result = panic::AssertUnwindSafe(inst_common.call_procedure(params, inst))
let result = panic::AssertUnwindSafe(inst_common.call_procedure(*params, inst))
.catch_unwind()
.await;

Expand Down Expand Up @@ -504,6 +517,7 @@ fn prepare_scheduled_procedure_call(
inst: &mut impl WasmInstance,
) -> ScheduledProcedureStep {
let ScheduledFunctionParams(item) = params;
let delay = scheduled_function_delay_for_item(&item);
let id = scheduled_item_id(&item);
let db = &**module_info.relational_db();
let tx = db.begin_mut_tx(IsolationLevel::Serializable, Workload::Internal);
Expand All @@ -530,7 +544,11 @@ fn prepare_scheduled_procedure_call(
let reschedule = id.and_then(|id| {
delete_scheduled_function_row(module_info, db, id, Some(tx), (timestamp, instant), inst_common, inst)
});
ScheduledProcedureStep::Procedure { params, reschedule }
ScheduledProcedureStep::Procedure {
params: Box::new(params),
reschedule,
delay,
}
}

fn call_scheduled_reducer_until_done(
Expand All @@ -540,6 +558,7 @@ fn call_scheduled_reducer_until_done(
inst: &mut impl WasmInstance,
) -> (CallScheduledFunctionResult, bool) {
let ScheduledFunctionParams(item) = params;
let delay = scheduled_function_delay_for_item(&item);
let id = scheduled_item_id(&item);
let db = &**module_info.relational_db();
let tx = db.begin_mut_tx(IsolationLevel::Serializable, Workload::Internal);
Expand All @@ -561,7 +580,12 @@ fn call_scheduled_reducer_until_done(
}
};

call_scheduled_reducer_with_tx(module_info, db, id, tx, (timestamp, instant), params, inst_common, inst)
let result =
call_scheduled_reducer_with_tx(module_info, db, id, tx, (timestamp, instant), params, inst_common, inst);
if let Some((function_name, delay)) = delay.as_ref() {
record_scheduled_function_delay(module_info, function_name, *delay);
Comment on lines +583 to +586

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

It looks like record_scheduled_function_delay calls Timestamp::now(), in this case after call_scheduled_reducer_with_tx has already returned. This appears to mean that we'll measure and report the delay plus the reducer's execution time. It also appears that the params already include params.timestamp, the invocation time reported to the reducer. Can we just use that timestamp to report the delay?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

record_scheduled_function_delay does not call Timestamp::now(). scheduled_function_delay_for_item does that which is called correctly before calling reducer.

I think, I can do better with naming.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Oh, I see. I'd still prefer to use the same timestamp to compute delay as gets passed to the reducer.

}
result
}

fn scheduled_item_id(item: &QueueItem) -> Option<ScheduledFunctionId> {
Expand All @@ -571,6 +595,37 @@ fn scheduled_item_id(item: &QueueItem) -> Option<ScheduledFunctionId> {
}
}

fn scheduled_function_delay_for_item(item: &QueueItem) -> Option<(Arc<str>, Duration)> {
match item {
QueueItem::Id { function_name, at, .. } => {
Some((function_name.clone(), scheduled_function_delay(Timestamp::now(), *at)))
}
QueueItem::VolatileNonatomicImmediate { .. } => None,
}
}

fn record_scheduled_function_delay(module_info: &ModuleInfo, function_name: &str, delay: Duration) {
if delay <= RECORD_SCHEDULED_FUNCTION_DELAY_THRESHOLD {
return;
}
WORKER_METRICS
.scheduled_function_delay
.with_label_values(&module_info.database_identity, function_name)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Can we cache this with_label_values call someplace rather than calling with_label_values on every report? And also, can we clean it up with remove_label_values, either when dropping whatever holds it, or in fn remove_database_gauges in crates/core/src/host/host_controller.rs?

.observe(delay.as_secs_f64());
Comment on lines +608 to +614

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Why not observe every function in the metric?

@Shubham8287 Shubham8287 Jul 29, 2026

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

I didn't because of perfomance reasons with with_label_value (as it will lead to drift itself) but maybe we can do if we cache it.


log::warn!(
"scheduled function `{}` for database {} is delayed by {:.3}s, exceeding the {:.3}s threshold",
function_name,
module_info.database_identity,
delay.as_secs_f64(),
RECORD_SCHEDULED_FUNCTION_DELAY_THRESHOLD.as_secs_f64(),
);
}

fn scheduled_function_delay(actual: Timestamp, requested: Timestamp) -> Duration {
actual.duration_since(requested).unwrap_or(Duration::ZERO)
}

#[allow(clippy::too_many_arguments)]
fn call_scheduled_reducer_with_tx(
module_info: &ModuleInfo,
Expand Down
6 changes: 6 additions & 0 deletions crates/core/src/worker_metrics/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -534,6 +534,12 @@ metrics_group!(
#[buckets(100e-6, 500e-6, 0.001, 0.005, 0.01, 0.05, 0.1, 0.5, 1, 5, 10)]
pub reducer_wait_time: HistogramVec,

#[name = spacetime_scheduled_function_delay_seconds]
#[help = "The amount of time (in seconds) between when a scheduled function was due and when the scheduler began invoking it"]
#[labels(db: Identity, function: str)]
#[buckets(0.001, 0.005, 0.01, 0.05, 0.1, 0.5, 1, 5, 10, 30, 60, 300)]
pub scheduled_function_delay: HistogramVec,

#[name = spacetime_worker_wasm_instance_errors_total]
#[help = "The number of fatal WASM instance errors, such as reducer panics."]
#[labels(database_identity: Identity, module_hash: Hash, reducer_symbol: str)]
Expand Down
Loading