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
12 changes: 7 additions & 5 deletions pkgs/id/crates/id-caps/src/account_quota.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,11 +14,13 @@
//! the per-world memory budget: a validated policy type
//! ([`AccountQuotas`]) plus a deterministic accounting ledger
//! ([`FuelRateBudget`]) with typed, recoverable refusals. Enforcement
//! wiring — charging the ledger at the invocation boundary and
//! aggregating a world's charges under its owning account at the hub —
//! is the next slice; nothing here performs I/O or reads a clock, so
//! the accounting is fully determined by the charges and timestamps
//! its caller supplies.
//! wiring charges the ledger at the invocation boundary: since slice
//! 2 the sandbox's `WorldInstance` (in `id-worlds`) admits each update
//! against an installed budget, priced at the invocation's fuel
//! allowance. Aggregating one budget across all of an account's
//! worlds at the hub is the remaining slice. Nothing here performs
//! I/O or reads a clock, so the accounting is fully determined by the
//! charges and timestamps its caller supplies.

use std::time::{Duration, Instant};

Expand Down
278 changes: 277 additions & 1 deletion pkgs/id/crates/id-worlds/src/sandbox.rs
Original file line number Diff line number Diff line change
Expand Up @@ -355,6 +355,9 @@ impl Sandbox {
seed,
limits: self.limits,
metrics,
fuel_rate: None,
#[cfg(test)]
fuel_now: None,
trap_fuel: None,
store,
memory,
Expand Down Expand Up @@ -383,6 +386,19 @@ pub struct WorldInstance {
seed: u64,
limits: SandboxLimits,
metrics: CallMetrics,
/// The owning account's fuel-rate budget (#1067, F12.10), when the
/// host installed one for this world. Every [`Self::update`]
/// admission charges it the invocation's fuel allowance; `None` —
/// every host that has not wired account quotas yet — leaves
/// invocation admission exactly as it was before F12.10.
fuel_rate: Option<id_caps::account_quota::FuelRateBudget>,
/// Test-only admission clock (#1067): when set,
/// [`Self::charge_fuel_rate`] charges at this instant instead of
/// `Instant::now()`, so admission tests can pin the budget's
/// window — or step it by hand — instead of racing the wall
/// clock. `None` everywhere except tests that set it.
#[cfg(test)]
fuel_now: Option<std::time::Instant>,
/// Fuel a trapped call had spent, captured before the diagnostic getters
/// refill the store; taken by [`Self::settle`].
trap_fuel: Option<u64>,
Expand Down Expand Up @@ -425,6 +441,55 @@ impl WorldInstance {
&self.metrics
}

/// Install the owning account's fuel-rate budget (#1067, F12.10).
///
/// From the next [`Self::update`] on, every invocation admission
/// charges this budget the invocation's fuel allowance, and an
/// account at its rate has its updates refused until the budget's
/// window rolls. Installing replaces any budget already installed;
/// the replaced budget's accounting is discarded with it. Hosts
/// that never call this leave the instance uncharged, exactly as
/// before F12.10.
pub fn set_fuel_rate_budget(&mut self, budget: id_caps::account_quota::FuelRateBudget) {
self.fuel_rate = Some(budget);
}

/// The installed fuel-rate budget, if any (#1067). For reporting:
/// its counters say what the account was charged at admission,
/// which is deliberately not the metered consumption in
/// [`Self::metrics`].
pub const fn fuel_rate_budget(&self) -> Option<&id_caps::account_quota::FuelRateBudget> {
self.fuel_rate.as_ref()
}

/// Charge this invocation's fuel allowance against the owning
/// account's rate budget (#1067), when one is installed.
///
/// Admission control, priced at the allowance: the store is about
/// to be handed `limits.fuel`, so that is what the account is
/// charged — before the guest runs, so a refusal means the
/// invocation never happens and nothing is metered. A refusal is
/// recoverable: it does not poison the instance, and the same
/// call can succeed once the budget's window rolls.
///
/// # Errors
///
/// The budget's
/// [`FuelRateRefusal`](id_caps::account_quota::FuelRateRefusal)
/// when the account is at its rate for the current window.
fn charge_fuel_rate(&mut self) -> Result<()> {
if let Some(budget) = &mut self.fuel_rate {
// Tests pin `fuel_now` (#1067); production always reads
// the wall clock.
#[cfg(test)]
let now = self.fuel_now.unwrap_or_else(std::time::Instant::now);
#[cfg(not(test))]
let now = std::time::Instant::now();
budget.try_charge(now, self.limits.fuel)?;
}
Ok(())
}

/// Fuel the most recent `call` spent; zero if it has not run.
pub const fn last_fuel(&self, call: GuestCall) -> u64 {
self.metrics.get(call).fuel_last
Expand All @@ -441,13 +506,18 @@ impl WorldInstance {
}

/// Apply one event from `participant`. The model pointer is committed
/// only if guest update succeeds.
/// only if guest update succeeds. When the owning account has a
/// fuel-rate budget installed (#1067), admission charges it and a
/// refusal runs nothing — but only after the message-size check:
/// an oversized event never runs, so it must not consume the
/// account's execution budget.
pub fn update(&mut self, participant: u64, event: &[u8]) -> Result<()> {
ensure!(
!self.poisoned,
"world guest is poisoned after a previous failure"
);
self.check_message_size(event)?;
self.charge_fuel_rate()?;
Comment thread
dezren39 marked this conversation as resolved.
Resolved
// The world's participant limit keeps IDs far below i32::MAX; clamp
// defensively so a hostile caller can never wrap the guest argument.
let participant = i32::try_from(participant).unwrap_or(i32::MAX);
Expand Down Expand Up @@ -813,6 +883,14 @@ impl WorldInstance {
fn snapshot_via_trait(&mut self) -> Option<String> {
crate::world::WorldProgram::snapshot(self).unwrap()
}

/// Pin the admission clock (#1067): [`Self::charge_fuel_rate`]
/// charges at `now` until this is called again, so a test can
/// hold the budget's window still — or step it past a rollover —
/// without sleeping or racing the wall clock.
pub fn set_fuel_now_for_test(&mut self, now: std::time::Instant) {
self.fuel_now = Some(now);
}
}

impl crate::world::WorldProgram for WorldInstance {
Expand Down Expand Up @@ -936,6 +1014,204 @@ mod tests {
assert_eq!(world.view().unwrap(), b"hello");
}

#[test]
fn an_account_at_its_fuel_rate_refuses_the_next_update() {
let limits = SandboxLimits {
fuel: 10_000,
..SandboxLimits::default()
};
let runner = compile(ECHO, limits).unwrap();
let mut world = runner.instantiate(123).unwrap();
// One invocation's allowance exactly fills the account's window.
world.set_fuel_rate_budget(id_caps::account_quota::FuelRateBudget::new(limits.fuel));
world.update(1, b"event").unwrap();
let refusal = world
.update(1, b"event")
.unwrap_err()
.downcast::<id_caps::account_quota::FuelRateRefusal>()
.unwrap();
assert_eq!(refusal.limit_per_second, limits.fuel);
assert_eq!(refusal.charged_in_window, limits.fuel);
assert_eq!(refusal.requested_fuel, limits.fuel);
// The refused invocation never ran: only one update is metered.
assert_eq!(world.metrics().get(GuestCall::Update).calls, 1);
// A refusal is recoverable, not poisoning: reads still serve.
assert_eq!(world.view().unwrap(), b"hello");
}

#[test]
fn a_fuel_rate_budget_accounts_each_admitted_allowance() {
Comment thread
dezren39 marked this conversation as resolved.
Resolved
let limits = SandboxLimits {
fuel: 10_000,
..SandboxLimits::default()
};
let runner = compile(ECHO, limits).unwrap();
let mut world = runner.instantiate(123).unwrap();
world.set_fuel_rate_budget(id_caps::account_quota::FuelRateBudget::new(limits.fuel * 3));
for _ in 0..3 {
world.update(1, b"event").unwrap();
}
assert!(world.update(1, b"event").is_err());
let budget = world.fuel_rate_budget().unwrap();
assert_eq!(budget.total_charged(), limits.fuel * 3);
assert_eq!(budget.charged_in_window(), limits.fuel * 3);
assert_eq!(budget.refusal_count(), 1);
}

#[test]
fn an_oversized_event_does_not_consume_the_fuel_budget() {
let limits = SandboxLimits {
fuel: 10_000,
..SandboxLimits::default()
};
let runner = compile(ECHO, limits).unwrap();
let mut world = runner.instantiate(123).unwrap();
// One allowance exactly fills the account's window.
world.set_fuel_rate_budget(id_caps::account_quota::FuelRateBudget::new(limits.fuel));
let oversized = vec![b'e'; limits.message_bytes + 1];
assert!(world.update(1, &oversized).is_err());
// The rejected non-invocation charged nothing: the next
// valid event still fits the window.
world.update(1, b"event").unwrap();
let budget = world.fuel_rate_budget().unwrap();
assert_eq!(budget.total_charged(), limits.fuel);
assert_eq!(budget.refusal_count(), 0);
}

/// Property coverage for the admission accounting invariants
/// (Codex review on #12557): generated allowance, quota, event
/// size, and admission/refusal sequences, checked against an
/// explicit accounting oracle — bounded charges, and refused
/// calls that neither execute nor alter invocation metrics nor
/// poison the instance. The examples above stay as smoke
/// coverage.
mod admission_property {
use super::*;
use proptest::prelude::*;

/// The oracle: what the ledger and the invocation metrics
/// must say after each event. The admission clock is pinned
/// for the whole case (see below), so no window rolls
/// mid-case and the window charge is just the sum of
/// admitted allowances; the case then steps the clock by
/// hand to cover a rollover deterministically.
#[derive(Debug, Default)]
struct Oracle {
charged: u64,
refusals: u64,
calls: u64,
}

proptest! {
#[test]
fn admission_accounting_matches_its_oracle(
(fuel, budget_limit) in (10_000u64..=100_000u64)
.prop_flat_map(|fuel| (Just(fuel), 0..=fuel * 5)),
ops in prop::collection::vec(
prop_oneof![
8 => 0..=1024usize,
Comment thread
dezren39 marked this conversation as resolved.
Resolved
// Past the 1 MiB message ceiling: rejected
// before admission, so it must charge nothing.
2 => (1024 * 1024 + 1usize)..=(1024 * 1024 + 512usize),
],
0..=32,
),
) {
let limits = SandboxLimits {
fuel,
..SandboxLimits::default()
};
let runner = compile(ECHO, limits).unwrap();
let mut world = runner.instantiate(123).unwrap();
world.set_fuel_rate_budget(
id_caps::account_quota::FuelRateBudget::new(budget_limit),
);
// Pin the admission clock (#1067): the budget's
// window can only roll when this case steps it, never
// because the test process was descheduled mid-case.
let fuel_now = std::time::Instant::now();
world.set_fuel_now_for_test(fuel_now);
let mut oracle = Oracle::default();
for len in ops {
let event = vec![b'e'; len];
let result = world.update(1, &event);
if len > limits.message_bytes {
// Oversized: rejected before admission, so
// neither the budget nor the metrics move.
prop_assert!(result.is_err());
prop_assert!(
result
.unwrap_err()
.downcast_ref::<id_caps::account_quota::FuelRateRefusal>()
.is_none(),
"an oversized event is a size rejection, not a fuel refusal"
);
} else if oracle
.charged
.checked_add(fuel)
.is_none_or(|total| total > budget_limit)
{
// Refused whole at admission: the guest
// never ran, so nothing is metered.
let refusal = result
.unwrap_err()
.downcast::<id_caps::account_quota::FuelRateRefusal>()
.unwrap();
prop_assert_eq!(refusal.charged_in_window, oracle.charged);
prop_assert_eq!(refusal.requested_fuel, fuel);
oracle.refusals += 1;
} else {
prop_assert!(result.is_ok());
oracle.charged += fuel;
oracle.calls += 1;
}
// Bounded charges, exact refusal accounting, and
// metrics that count admitted invocations only —
// after every operation.
let budget = world.fuel_rate_budget().unwrap();
prop_assert_eq!(budget.total_charged(), oracle.charged);
prop_assert_eq!(budget.charged_in_window(), oracle.charged);
Comment thread
dezren39 marked this conversation as resolved.
Resolved
prop_assert_eq!(budget.refusal_count(), oracle.refusals);
prop_assert_eq!(world.metrics().get(GuestCall::Update).calls, oracle.calls);
// A refusal never poisons the instance: reads
// still serve. (The view's bytes are not pinned
// here: the echo fixture's allocator returns 0,
// so an event longer than 32 bytes overwrites
// its "hello" data — that is the fixture, not
// poisoning.)
prop_assert!(world.view().is_ok());
}
// Step the pinned clock past the window (#1067): the
// ledger restarts from zero, so an allowance that
// fits the limit is admitted fresh, and one larger
// than the limit is still refused — now with an
// empty window behind it.
world.set_fuel_now_for_test(fuel_now + std::time::Duration::from_secs(2));
let rolled = world.update(1, &[]);
if fuel <= budget_limit {
prop_assert!(rolled.is_ok());
prop_assert_eq!(
world.fuel_rate_budget().unwrap().charged_in_window(),
fuel
);
} else {
prop_assert!(rolled.is_err());
prop_assert!(
rolled
.unwrap_err()
.downcast_ref::<id_caps::account_quota::FuelRateRefusal>()
.is_some(),
"a fresh window still refuses an allowance larger than the limit"
);
prop_assert_eq!(
world.fuel_rate_budget().unwrap().charged_in_window(),
0
);
}
}
}
}

#[test]
fn checked_in_roc_examples_export_abi_version_one() {
for wasm in [
Expand Down
Loading