Properly handle execution time<->energy conversion in v8 host (#4884)

# Description of Changes

Fixes a todo.

# Expected complexity level and risk

1

# Testing

- [x] Checked that conversion ratio is sane.
This commit is contained in:
Noa
2026-04-24 19:35:23 -05:00
committed by GitHub
parent 6fc591e4d5
commit 458eac8c85
2 changed files with 13 additions and 4 deletions
+6 -2
View File
@@ -16,13 +16,17 @@ pub struct EnergyQuanta {
impl EnergyQuanta {
pub const ZERO: Self = EnergyQuanta { quanta: 0 };
// per the comment on [`FunctionBudget::DEFAULT_BUDGET`]: 1 second of wasm runtime is roughtly 2 TeV
pub const PER_EXECUTION_SEC: Self = Self::new(2_000_000_000_000);
pub const PER_EXECUTION_NANOSEC: Self = Self::new(Self::PER_EXECUTION_SEC.get() / 1_000_000_000);
#[inline]
pub fn new(quanta: u128) -> Self {
pub const fn new(quanta: u128) -> Self {
Self { quanta }
}
#[inline]
pub fn get(&self) -> u128 {
pub const fn get(&self) -> u128 {
self.quanta
}
+7 -2
View File
@@ -13,7 +13,7 @@ use core::ptr;
use core::sync::atomic::Ordering;
use core::time::Duration;
use core::{ffi::c_void, sync::atomic::AtomicBool};
use spacetimedb_client_api_messages::energy::FunctionBudget;
use spacetimedb_client_api_messages::energy::{EnergyQuanta, FunctionBudget};
use std::sync::Arc;
use v8::{Isolate, IsolateHandle};
@@ -118,7 +118,12 @@ fn budget_to_duration(_budget: FunctionBudget) -> Duration {
/// Returns [`EnergyStats`] for a reducer given its `budget`
/// and the `duration` it took to execute.
pub(super) fn energy_from_elapsed(budget: FunctionBudget, duration: Duration) -> EnergyStats {
let used = duration_to_budget(duration);
let used = duration.as_nanos() * EnergyQuanta::PER_EXECUTION_NANOSEC.get();
// in order for duration_nanos * ev_per_ns >= u64::MAX:
// duration_nanos >= u64::MAX / ev_per_ns
// duration_nanos >= (9223372036854775 ns = 106.75 days)
// so it's unlikely we'll have to worry about it
let used = FunctionBudget::new(u64::try_from(used).unwrap_or(u64::MAX));
let remaining = budget - used;
EnergyStats { budget, remaining }
}