diff --git a/pkgs/id/crates/id-caps/src/account_quota.rs b/pkgs/id/crates/id-caps/src/account_quota.rs index 1f79f9a474..5a42da850a 100644 --- a/pkgs/id/crates/id-caps/src/account_quota.rs +++ b/pkgs/id/crates/id-caps/src/account_quota.rs @@ -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}; diff --git a/pkgs/id/crates/id-worlds/src/sandbox.rs b/pkgs/id/crates/id-worlds/src/sandbox.rs index e5cb2aed2e..096e0f9073 100644 --- a/pkgs/id/crates/id-worlds/src/sandbox.rs +++ b/pkgs/id/crates/id-worlds/src/sandbox.rs @@ -355,6 +355,9 @@ impl Sandbox { seed, limits: self.limits, metrics, + fuel_rate: None, + #[cfg(test)] + fuel_now: None, trap_fuel: None, store, memory, @@ -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, + /// 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, /// Fuel a trapped call had spent, captured before the diagnostic getters /// refill the store; taken by [`Self::settle`]. trap_fuel: Option, @@ -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 @@ -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()?; // 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); @@ -813,6 +883,14 @@ impl WorldInstance { fn snapshot_via_trait(&mut self) -> Option { 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 { @@ -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::() + .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() { + 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, + // 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::() + .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::() + .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); + 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::() + .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 [ diff --git a/pkgs/id/crates/id-worlds/src/world/actor.rs b/pkgs/id/crates/id-worlds/src/world/actor.rs index 8e9d19327a..b4f574689f 100644 --- a/pkgs/id/crates/id-worlds/src/world/actor.rs +++ b/pkgs/id/crates/id-worlds/src/world/actor.rs @@ -547,6 +547,19 @@ pub(crate) enum WorldCommand { }, } +/// Whether `error` is a fuel-rate admission refusal (#1067): the +/// program never ran, so the actor stays healthy and the input may +/// be retried once the account's window rolls. Every other program +/// error is a guest failure and poisons the program. +/// +/// Checked before any `.context(...)` is applied: the bare program +/// error carries the refusal at its outermost layer. +fn is_fuel_rate_refusal(error: &anyhow::Error) -> bool { + error + .downcast_ref::() + .is_some() +} + /// Trim `journal` behind a verified snapshot of `program`. `Ok(false)` means /// the program cannot snapshot. pub(crate) fn compact_journal( @@ -634,6 +647,19 @@ pub(crate) struct WorldActor { pub(crate) active_subs: BTreeSet, /// Request ids already executed, so `wants` states intent, not polling. pub(crate) handled_requests: BTreeSet, + /// Capability results whose delivery was refused at the account's + /// fuel rate (#1067): the side effect already ran, so the result + /// event waits here — never re-executed — until the window rolls + /// and `retry_pending_results` delivers it. Actor lifetime only, + /// like `handled_requests`: a restart falls back to the existing + /// restarted-refusal path for the same id. + pub(crate) pending_results: std::collections::VecDeque, + /// Earliest actor-clock instant a fuel-refused delivery may be + /// retried (#1067): one full window past the refusal, which is + /// guaranteed to land in a fresh budget window — the refused + /// window started no later than the refusal. `None` while no + /// refusal is outstanding. + pub(crate) fuel_retry_not_before: Option, /// Forms registered by `form.present`; actor-lifetime only, so a restart /// invalidates outstanding UI submissions instead of replaying stale input. pub(crate) pending_forms: BTreeMap, @@ -879,6 +905,14 @@ impl WorldActor { } let deliverable = self.program_healthy && !self.storage_failed; let clock = self.core.clock(); + let now_instant = clock.now_instant(); + // A fuel-rate refusal backs delivery off until one full window + // past the refusal (#1067): the budget's window started no + // later than the refusal, so that instant is guaranteed to + // land in a fresh window. + let fuel_backoff = self + .fuel_retry_not_before + .filter(|deadline| *deadline > now_instant); self.ticks .values() .min() @@ -887,11 +921,16 @@ impl WorldActor { .chain(next_schedule_wake( &self.core.schedules, clock.now_ms(), - clock.now_instant(), + now_instant, deliverable, + fuel_backoff, )) .chain(self.loc_watches.values().min().copied()) .chain(self.provider_broker.next_deadline()) + // A queued capability result needs a wake at the retry + // deadline too, or the loop would sleep past the rollover + // with a result still waiting (#1067). + .chain(fuel_backoff.filter(|_| !self.pending_results.is_empty())) .min() } @@ -1406,8 +1445,19 @@ impl WorldActor { }) } Err(error) => { - self.program_healthy = false; - Err(error.context("world program rejected input")) + if is_fuel_rate_refusal(&error) { + // Recoverable admission refusal + // (#1067): the program never ran + // and stays healthy; the same + // input can succeed once the + // account's window rolls. + Err(error.context( + "world program refused input at its fuel rate", + )) + } else { + self.program_healthy = false; + Err(error.context("world program rejected input")) + } } } } @@ -1453,8 +1503,19 @@ impl WorldActor { self.republished(records.unwrap_or_default(), event.sequence); }), Err(error) => { - self.program_healthy = false; - Err(error.context("world program rejected entity input")) + if is_fuel_rate_refusal(&error) { + // Recoverable admission refusal + // (#1067): the program never ran + // and stays healthy; the same + // input can succeed once the + // account's window rolls. + Err(error.context( + "world program refused entity input at its fuel rate", + )) + } else { + self.program_healthy = false; + Err(error.context("world program rejected entity input")) + } } } } @@ -4088,6 +4149,8 @@ impl WorldActor { presence: HashMap::new(), active_subs: BTreeSet::new(), handled_requests: BTreeSet::new(), + pending_results: std::collections::VecDeque::new(), + fuel_retry_not_before: None, pending_forms: BTreeMap::new(), denied_subs: BTreeSet::new(), ticks: BTreeMap::new(), diff --git a/pkgs/id/crates/id-worlds/src/world/actor/execution.rs b/pkgs/id/crates/id-worlds/src/world/actor/execution.rs index 2f57ccad14..0a5f43acc4 100644 --- a/pkgs/id/crates/id-worlds/src/world/actor/execution.rs +++ b/pkgs/id/crates/id-worlds/src/world/actor/execution.rs @@ -213,8 +213,21 @@ impl WorldActor { }); } Err(error) => { - self.program_healthy = false; - failed = Some((reply, error.context("world program rejected input"))); + if super::is_fuel_rate_refusal(&error) { + // Recoverable admission refusal (#1067): the + // program never ran and stays healthy, so the + // failing input is answered with the refusal and + // the inputs after it go through the single + // path, where the same refusal — not an + // unavailable program — answers them too. + failed = Some(( + reply, + error.context("world program refused input at its fuel rate"), + )); + } else { + self.program_healthy = false; + failed = Some((reply, error.context("world program rejected input"))); + } break; } } @@ -682,13 +695,37 @@ impl WorldActor { publish_records(&self.records_sender, sequence, records); } +/// What one host-event delivery did (#1067). A bare `bool` conflates the +/// recoverable case with every other drop, which is exactly how a +/// fuel-refused capability result used to be lost: only `FuelRefused` +/// guarantees the program never ran, so only it may be retried. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(super) enum DeliveryOutcome { + /// The program ran the event and it was journaled. + Delivered, + /// The account's fuel-rate window is exhausted: the program never + /// ran and stays healthy, so the event may be retried once the + /// window rolls. + FuelRefused, + /// Any other drop: the program is unhealthy, storage failed, the + /// event was too large, or the program rejected it. + Failed, +} + +impl DeliveryOutcome { + /// Whether the event reached the program and was journaled. + pub(super) const fn delivered(self) -> bool { + matches!(self, Self::Delivered) + } +} + +impl WorldActor { /// Deliver a host-originated event to the program: journal it first is /// impossible (the program must accept it for the journal to be true), so /// the order is update, then journal, exactly like participant input. - /// Returns whether the program accepted the event and it was journaled. /// A read-only replica never delivers: host events are authoritative /// program effects and must not originate from a replica. - pub(super) async fn deliver(&mut self, text: String) -> bool { + pub(super) async fn deliver(&mut self, text: String) -> DeliveryOutcome { self.deliver_system(text, None).await } @@ -698,7 +735,7 @@ impl WorldActor { &mut self, text: String, participant_id: Option, - ) -> bool { + ) -> DeliveryOutcome { self.deliver_system(text, participant_id).await } @@ -706,16 +743,16 @@ impl WorldActor { &mut self, text: String, participant_id: Option, - ) -> bool { + ) -> DeliveryOutcome { if self.read_only { - return false; + return DeliveryOutcome::Failed; } if !self.program_healthy || self.storage_failed { - return false; + return DeliveryOutcome::Failed; } if text.len() > crate::world_caps::MAX_EVENT_BYTES { tracing::error!("world event exceeds the delivery bound; dropped"); - return false; + return DeliveryOutcome::Failed; } let event = WorldEvent { sequence: 0, @@ -723,9 +760,17 @@ impl WorldActor { kind: WorldEventKind::System { event: text }, }; if let Err(error) = self.program.update(&event) { + if super::is_fuel_rate_refusal(&error) { + // Recoverable admission refusal (#1067): the program + // never ran and stays healthy; this host event is + // dropped and the next tick or capability result is + // delivered as usual once the window rolls. + tracing::warn!("world program refused a host event at its fuel rate: {error:#}"); + return DeliveryOutcome::FuelRefused; + } self.program_healthy = false; tracing::error!("world program rejected a host event: {error:#}"); - return false; + return DeliveryOutcome::Failed; } match program_records(self.program.as_mut()) { Ok(records) => { @@ -735,7 +780,7 @@ impl WorldActor { Err(error) => { self.program_healthy = false; tracing::error!("world program records failed: {error:#}"); - return false; + return DeliveryOutcome::Failed; } } let journaled = self @@ -751,7 +796,70 @@ impl WorldActor { self.core.since_checkpoint = self.core.since_checkpoint.saturating_add(1); } let _ = self.view_changed.send(self.core.sequence); - journaled + if journaled { + DeliveryOutcome::Delivered + } else { + DeliveryOutcome::Failed + } + } + + /// Record that a delivery was refused at the account's fuel rate + /// (#1067): no refused delivery is retried before one full window + /// past now, which is guaranteed to land in a fresh budget window + /// — the refused window started no later than the refusal. The + /// actor clock's instant face shares the wall clock's domain + /// (`SystemClock::now_instant` is `Instant::now()`; a manual clock + /// is anchored to it at construction), so this bound holds on + /// either clock. + fn note_fuel_refusal(&mut self) { + self.fuel_retry_not_before = Some( + self.core.clock().now_instant() + id_caps::account_quota::FUEL_RATE_WINDOW, + ); + } + + /// Deliver a capability result, or queue it when the account's fuel + /// rate refuses it (#1067, Codex review on #12557): the side effect + /// already ran, so the result event must not be re-executed — it + /// waits in `pending_results` until the window rolls, when + /// [`Self::retry_pending_results`] delivers it. Any other failure + /// drops the event, as a host event is dropped today: only a fuel + /// refusal guarantees the program never ran. + async fn deliver_result(&mut self, event: String) { + if let DeliveryOutcome::FuelRefused = self.deliver(event.clone()).await { + self.note_fuel_refusal(); + self.pending_results.push_back(event); + } + } + + /// Retry queued capability results once the fuel-rate window has + /// rolled (#1067). Stops at the first refusal — the rest stay + /// queued behind it, in order — and drops a result any other + /// failure discards. A result is delivered at most once: the + /// program never ran on a refused attempt, so a retry cannot + /// duplicate it. + async fn retry_pending_results(&mut self) { + if self.pending_results.is_empty() + || !self.program_healthy + || self.storage_failed + || self + .fuel_retry_not_before + .is_some_and(|deadline| self.core.clock().now_instant() < deadline) + { + return; + } + while let Some(event) = self.pending_results.pop_front() { + match self.deliver(event.clone()).await { + DeliveryOutcome::Delivered | DeliveryOutcome::Failed => {} + DeliveryOutcome::FuelRefused => { + self.note_fuel_refusal(); + self.pending_results.push_front(event); + break; + } + } + } + if self.pending_results.is_empty() { + self.fuel_retry_not_before = None; + } } /// Pending forms intentionally are not durable. On reopen, tell a program @@ -782,6 +890,10 @@ impl WorldActor { if self.read_only || !self.holds_live_do_lease() { return; } + // Capability results a fuel-rate refusal queued (see + // `deliver_result`) go first, so the program reacts to them + // in this same pass. + self.retry_pending_results().await; for _ in 0..64 { if !self.program_healthy || self.storage_failed { break; @@ -858,7 +970,7 @@ impl WorldActor { &request.id, Err(CapError::actor_denied_with("restarted")), ); - self.deliver(refusal).await; + self.deliver_result(refusal).await; continue; } if crate::world_caps::PROVIDER_REGISTRY @@ -876,13 +988,13 @@ impl WorldActor { Ok(()) => {} Err(error) => { let refusal = crate::world_caps::result_event(&request.id, Err(error)); - self.deliver(refusal).await; + self.deliver_result(refusal).await; } } continue; } let outcome = self.execute(&request); - self.deliver(crate::world_caps::result_event(&request.id, outcome)) + self.deliver_result(crate::world_caps::result_event(&request.id, outcome)) .await; } } @@ -943,7 +1055,7 @@ impl WorldActor { &completion.guest_request_id, completion.outcome, ); - self.deliver(event).await; + self.deliver_result(event).await; } self.after_change().await; } @@ -1127,11 +1239,21 @@ impl WorldActor { /// fire is delivered as a tick is, and its schedule is consumed only after /// that delivery is journaled. A refused fire, or one that could not be /// journaled, leaves its schedule pending, so the next run delivers it. - /// A read-only replica never fires: schedules are writer authority. + /// A fuel-rate refusal backs the next attempt off until the window + /// rolls (see `fuel_retry_not_before`): without the backoff the run + /// loop would retry the same refused fire on every pass until + /// rollover. A read-only replica never fires: schedules are writer + /// authority. pub(crate) async fn fire_schedules(&mut self) { if self.read_only || !self.holds_live_do_lease() { return; } + if self + .fuel_retry_not_before + .is_some_and(|deadline| self.core.clock().now_instant() < deadline) + { + return; + } let now = self.core.clock().now_ms(); let mut due: Vec<(u64, String)> = self .core @@ -1148,7 +1270,14 @@ impl WorldActor { continue; }; let delivered = match &schedule.target { - None => self.deliver(schedule_fired_event(&id, late)).await, + None => match self.deliver(schedule_fired_event(&id, late)).await { + DeliveryOutcome::Delivered => true, + DeliveryOutcome::FuelRefused => { + self.note_fuel_refusal(); + false + } + DeliveryOutcome::Failed => false, + }, Some(target) => { // Cross-world (#1355 part 2): consent is re-checked at // fire time — a grant revoked or an isolation change @@ -1565,7 +1694,9 @@ impl WorldActor { self.acting = participant_id; self.acting_session = participant_id.and(session_id); ensure!( - self.deliver_form_result(event, participant_id).await, + self.deliver_form_result(event, participant_id) + .await + .delivered(), "form.result event was not delivered" ); if valid { @@ -1857,6 +1988,7 @@ impl WorldActor { if !self .deliver(schedule_fired_event_from(id, late, Some(source))) .await + .delivered() { return false; } @@ -2114,7 +2246,7 @@ impl WorldActor { "portal delivery fenced: {error}" ))); } - if !self.deliver(event).await { + if !self.deliver(event).await.delivered() { return Err(PortalSendError::Unavailable( "target program did not accept the portal message".to_owned(), )); diff --git a/pkgs/id/crates/id-worlds/src/world/handle.rs b/pkgs/id/crates/id-worlds/src/world/handle.rs index 7c2cf68a05..fc5213dbc2 100644 --- a/pkgs/id/crates/id-worlds/src/world/handle.rs +++ b/pkgs/id/crates/id-worlds/src/world/handle.rs @@ -314,6 +314,8 @@ impl WorldHandle { presence, active_subs: BTreeSet::new(), handled_requests: BTreeSet::new(), + pending_results: std::collections::VecDeque::new(), + fuel_retry_not_before: None, pending_forms: BTreeMap::new(), denied_subs: BTreeSet::new(), ticks: BTreeMap::new(), diff --git a/pkgs/id/crates/id-worlds/src/world/mod.rs b/pkgs/id/crates/id-worlds/src/world/mod.rs index 4579a29aba..6eaed0aae7 100644 --- a/pkgs/id/crates/id-worlds/src/world/mod.rs +++ b/pkgs/id/crates/id-worlds/src/world/mod.rs @@ -1554,6 +1554,11 @@ pub(crate) fn schedule_fired_event_from(id: &str, late: bool, source: Option<&st /// waits while the program cannot take a fire (`deliverable` is false): a due /// schedule that cannot be delivered would otherwise wake the loop without end. /// +/// A due schedule whose fire was refused at the account's fuel rate waits +/// until `not_before` instead (#1067): without this the loop retries the same +/// refused fire, scans schedules and warns on every pass until rollover. A +/// schedule that is not due yet keeps its own wake. +/// /// The deadline is anchored to `now_instant` (the injected clock's monotonic /// face), so a manual clock advancing `now_ms` past a schedule also advances /// this deadline. @@ -1562,13 +1567,19 @@ pub(crate) fn next_schedule_wake( now_ms: u64, now_instant: std::time::Instant, deliverable: bool, + not_before: Option, ) -> Option { if !deliverable { return None; } let earliest = schedules.values().map(|schedule| schedule.at_ms).min()?; let wait = std::time::Duration::from_millis(earliest.saturating_sub(now_ms)); - Some(now_instant + wait) + let wake = now_instant + wait; + Some(if wait.is_zero() { + not_before.filter(|deadline| *deadline > wake).unwrap_or(wake) + } else { + wake + }) } /// The newest `count` chat lines in `events`, oldest first, each carrying its diff --git a/pkgs/id/crates/id-worlds/src/world/tests.rs b/pkgs/id/crates/id-worlds/src/world/tests.rs index 1a2dbf6bd0..3c95b8555f 100644 --- a/pkgs/id/crates/id-worlds/src/world/tests.rs +++ b/pkgs/id/crates/id-worlds/src/world/tests.rs @@ -2903,6 +2903,61 @@ mod tests { (handle, token) } + /// A fuel-rate admission refusal is recoverable at the actor level + /// (#1067, Codex review on #12557): exhausting the budget must not + /// mark the program unhealthy, so the same input succeeds once the + /// window rolls instead of requiring a program replacement. + #[tokio::test] + async fn a_fuel_rate_refusal_keeps_the_actor_healthy() { + use crate::sandbox::{Sandbox, SandboxLimits}; + + // The same echo program as the sandbox tests: `plaza_update` + // returns the participant id and never traps. + const ECHO: &str = r#" + (module + (memory (export "memory") 1 1) + (data (i32.const 32) "hello") + (func (export "plaza_alloc") (param i32) (result i32) (i32.const 0)) + (func (export "plaza_free") (param i32 i32)) + (func (export "plaza_init") (param i64) (result i32) (i32.const 0)) + (func (export "plaza_update") (param i32 i32 i32 i32) (result i32) + local.get 0) + (func (export "plaza_view") (param i32) (result i32) + (i32.const 32)) + (func (export "plaza_out_len") (result i32) (i32.const 5))) + "#; + let limits = SandboxLimits { + fuel: 10_000, + ..SandboxLimits::default() + }; + let wasm = wat::parse_str(ECHO).unwrap(); + let runner = Sandbox::compile(&wasm, limits).unwrap(); + let mut program = runner.instantiate(123).unwrap(); + // One allowance exactly fills the account's window. + program.set_fuel_rate_budget(id_caps::account_quota::FuelRateBudget::new(limits.fuel)); + let core = WorldCore::new("fuel-rate", WorldLimits::default()).unwrap(); + let world = WorldHandle::spawn_with_program(core, Box::new(program)); + let (_, token) = world.issue("ann", WorldScopes::GUEST).await.unwrap(); + world.input(token.clone(), b"event".to_vec()).await.unwrap(); + // The next input is refused at admission — but the actor stays + // healthy: the error names the fuel rate, not an unavailable + // program. + let refusal = world + .input(token.clone(), b"event".to_vec()) + .await + .unwrap_err() + .to_string(); + assert!(refusal.contains("fuel rate"), "{refusal}"); + assert!( + !refusal.contains("unavailable after a previous failure"), + "{refusal}" + ); + // Once the window rolls, the same input succeeds: the refusal + // did not poison the program. + tokio::time::sleep(Duration::from_millis(1100)).await; + world.input(token, b"event".to_vec()).await.unwrap(); + } + #[tokio::test] async fn an_ungranted_request_is_refused_and_counted() { let (world, token) = caps_world_sync(false).await; @@ -9563,6 +9618,8 @@ mod isolation_tests { mod schedule_tests { use super::*; use crate::world::*; + use std::sync::atomic::{AtomicUsize, Ordering}; + use std::time::Duration; fn world(retained_events: usize) -> WorldCore { WorldCore::new( @@ -9787,6 +9844,14 @@ mod schedule_tests { fn batch_actor( id: &str, bounds: CapabilityBounds, + ) -> (WorldActor, JoinCapability, BatchJournal) { + batch_actor_with(id, bounds, Box::new(BatchProgram)) + } + + fn batch_actor_with( + id: &str, + bounds: CapabilityBounds, + program: Box, ) -> (WorldActor, JoinCapability, BatchJournal) { let journal = BatchJournal::for_world(id); let mut core = WorldCore::new(id, WorldLimits::default()).unwrap(); @@ -9795,11 +9860,7 @@ mod schedule_tests { .unwrap(); let issued = core.issued_entry(ann.id).unwrap(); journal.entries.lock().unwrap().push(issued); - let actor = WorldActor::for_test( - core, - Box::new(BatchProgram), - Some(Box::new(journal.clone())), - ); + let actor = WorldActor::for_test(core, program, Some(Box::new(journal.clone()))); (actor, token, journal) } @@ -9875,6 +9936,361 @@ mod schedule_tests { assert!(!actor.program_healthy); } + /// A program that refuses the input `limited` at the account's + /// fuel rate and accepts everything else (#1067). + struct FuelLimitedBatchProgram; + + impl WorldProgram for FuelLimitedBatchProgram { + fn update(&mut self, event: &WorldEvent) -> Result<()> { + if let WorldEventKind::Input(input) = &event.kind { + if input == b"limited" { + return Err(anyhow::Error::new( + id_caps::account_quota::FuelRateRefusal { + limit_per_second: 10_000, + charged_in_window: 10_000, + requested_fuel: 10_000, + }, + )); + } + } + Ok(()) + } + } + + // #1067 oracle: a fuel-rate refusal inside a batch is recoverable - + // the staged prefix commits, the refused input is answered with the + // refusal, and the input after it goes through the single path, where + // the still-healthy program accepts it instead of refusing it as + // unavailable. + #[tokio::test] + async fn a_fuel_rate_refusal_in_a_batch_keeps_the_actor_healthy() { + let (mut actor, token, journal) = batch_actor_with( + "batch-fuel-rate", + CapabilityBounds::default(), + Box::new(FuelLimitedBatchProgram), + ); + let results = batch_replies(&mut actor, &token, &[b"one", b"limited", b"two"]).await; + assert!(results[0].is_ok(), "{:?}", results[0]); + let refused = format!("{:#}", results[1].as_ref().unwrap_err()); + assert!(refused.contains("fuel rate"), "{refused}"); + assert!( + !refused.contains("unavailable after a previous failure"), + "{refused}" + ); + assert!(results[2].is_ok(), "{:?}", results[2]); + assert!(actor.program_healthy); + assert_eq!(journal.committed().len(), 2); + assert_eq!(*journal.batches.lock().unwrap(), vec![1]); + } + + /// A program that refuses host (system) events at the account's + /// fuel rate and accepts everything else (#1067). + struct FuelLimitedSystemProgram; + + impl WorldProgram for FuelLimitedSystemProgram { + fn update(&mut self, event: &WorldEvent) -> Result<()> { + if let WorldEventKind::System { .. } = &event.kind { + return Err(anyhow::Error::new( + id_caps::account_quota::FuelRateRefusal { + limit_per_second: 10_000, + charged_in_window: 10_000, + requested_fuel: 10_000, + }, + )); + } + Ok(()) + } + } + + // #1067 oracle: a fuel-rate refusal of a host event is + // recoverable — a refused schedule fire leaves the schedule + // pending and the program healthy, and the next participant + // input still succeeds. + #[tokio::test] + async fn a_fuel_rate_refusal_of_a_host_event_keeps_the_actor_healthy() { + let journal = Recorded::for_world("system-fuel-rate"); + let clock: Arc = Arc::new(ManualClock::new(EPOCH_MS)); + let mut core = WorldCore::new_with_clock( + "system-fuel-rate", + WorldLimits::default(), + clock.clone(), + ) + .unwrap(); + let (ann, token) = core + .issue_capability("ann", WorldScopes::GUEST, CapabilityBounds::default()) + .unwrap(); + let issued = core.issued_entry(ann.id).unwrap(); + super::tests::push_bumped(&mut journal.0.lock().unwrap(), &issued); + let mut actor = WorldActor::for_test( + core, + Box::new(FuelLimitedSystemProgram), + Some(Box::new(journal.clone())), + ); + actor.core.schedules.insert("tick".to_owned(), PendingSchedule::one_shot(EPOCH_MS)); + actor.fire_schedules().await; + assert!(actor.program_healthy); + assert!(actor.core.schedules.contains_key("tick")); + let results = batch_replies(&mut actor, &token, &[b"after"]).await; + assert!(results[0].is_ok(), "{:?}", results[0]); + } + + /// A program for the #1067 fuel-window tests: it asks for one + /// `time.now` result, records every result and schedule fire it + /// receives, and refuses system events at the account's fuel rate + /// while the manual clock is before `refuse_until_ms` — so the + /// test drives the rollover by advancing the clock, not the wall. + /// The attempt counters are shared with the test, so a refused + /// delivery that must not have been attempted is observable. + struct FuelWindowProgram { + clock: Arc, + refuse_until_ms: u64, + requests: Vec, + answered: BTreeSet, + results: BTreeMap, + result_deliveries: Arc, + fire_attempts: Arc, + fires: Vec, + } + + impl FuelWindowProgram { + fn fuel_refusal() -> anyhow::Error { + anyhow::Error::new(id_caps::account_quota::FuelRateRefusal { + limit_per_second: 10_000, + charged_in_window: 10_000, + requested_fuel: 10_000, + }) + } + } + + impl WorldProgram for FuelWindowProgram { + fn update(&mut self, event: &WorldEvent) -> Result<()> { + match &event.kind { + WorldEventKind::Input(bytes) => { + let document: serde_json::Value = serde_json::from_slice(bytes)?; + self.requests = document["requests"].as_array().cloned().unwrap_or_default(); + } + WorldEventKind::EntityInput { input, .. } => { + let document: serde_json::Value = serde_json::from_slice(input)?; + self.requests = document["requests"].as_array().cloned().unwrap_or_default(); + } + WorldEventKind::System { event: text } => { + let Ok(value) = serde_json::from_str::(text) else { + return Ok(()); + }; + let refused = self.clock.now_ms() < self.refuse_until_ms; + match value["cap"].as_str() { + Some("result") => { + if refused { + return Err(Self::fuel_refusal()); + } + if let Some(id) = value["id"].as_str() { + self.answered.insert(id.to_owned()); + self.results.insert(id.to_owned(), value.clone()); + self.result_deliveries.fetch_add(1, Ordering::SeqCst); + } + } + Some("schedule") => { + self.fire_attempts.fetch_add(1, Ordering::SeqCst); + if refused { + return Err(Self::fuel_refusal()); + } + self.fires.push(value.clone()); + } + _ => {} + } + } + WorldEventKind::Chat(_) | WorldEventKind::ProgramInstalled { .. } => {} + } + Ok(()) + } + + fn wants(&mut self) -> Result> { + let pending: Vec<&serde_json::Value> = self + .requests + .iter() + .filter(|request| { + !request["id"] + .as_str() + .is_some_and(|id| self.answered.contains(id)) + }) + .collect(); + Ok(Some( + serde_json::json!({"v": 1, "requests": pending}).to_string(), + )) + } + + fn records(&mut self) -> Result> { + Ok(Some( + serde_json::json!({"fired": self.fires, "results": self.results}).to_string(), + )) + } + } + + /// A `FuelWindowProgram` actor on a manual clock, with `time.now` + /// granted and one participant. Mirrors the + /// `FuelLimitedSystemProgram` setup above; the test drives + /// [`WorldActor::handle`], [`WorldActor::after_change`] and + /// [`WorldActor::fire_schedules`] directly. + #[allow(clippy::type_complexity)] + fn fuel_window_actor( + id: &str, + refuse_until_ms: u64, + ) -> ( + WorldActor, + Arc, + JoinCapability, + Recorded, + Arc, + Arc, + ) { + let journal = Recorded::for_world(id); + let clock: Arc = Arc::new(ManualClock::new(EPOCH_MS)); + let mut core = + WorldCore::new_with_clock(id, WorldLimits::default(), clock.clone()).unwrap(); + core.ledger + .set_granted(BTreeSet::from(["time.now".to_owned()])); + let (ann, token) = core + .issue_capability("ann", WorldScopes::GUEST, CapabilityBounds::default()) + .unwrap(); + let issued = core.issued_entry(ann.id).unwrap(); + super::tests::push_bumped(&mut journal.0.lock().unwrap(), &issued); + let result_deliveries = Arc::new(AtomicUsize::new(0)); + let fire_attempts = Arc::new(AtomicUsize::new(0)); + let program = FuelWindowProgram { + clock: clock.clone(), + refuse_until_ms, + requests: Vec::new(), + answered: BTreeSet::new(), + results: BTreeMap::new(), + result_deliveries: result_deliveries.clone(), + fire_attempts: fire_attempts.clone(), + fires: Vec::new(), + }; + let actor = WorldActor::for_test(core, Box::new(program), Some(Box::new(journal.clone()))); + ( + actor, + clock, + token, + journal, + result_deliveries, + fire_attempts, + ) + } + + /// How many capability results for request `id` the journal + /// delivered to the program: the exactly-once oracle for a + /// fuel-refused result. + fn journaled_results(journal: &Recorded, id: &str) -> usize { + journal + .entries() + .into_iter() + .filter(|entry| match entry { + JournalEntry::System { event } => match &event.kind { + WorldEventKind::System { event: text } => { + serde_json::from_str::(text) + .is_ok_and(|value| { + value["cap"] == "result" && value["id"] == id + }) + } + _ => false, + }, + _ => false, + }) + .count() + } + + // #1067 oracle (Codex review on #12557): a capability result + // whose delivery is refused at the fuel rate is queued, not + // lost — the side effect already ran, so the result must not be + // re-executed — and is delivered exactly once after the window + // rolls, without another attempt before then. + #[tokio::test] + async fn a_fuel_refused_capability_result_is_queued_and_retried_after_rollover() { + let (mut actor, clock, token, journal, result_deliveries, _) = + fuel_window_actor("fuel-result", EPOCH_MS + 1_000); + ask( + &mut actor, + &token, + serde_json::json!({"requests": [ + {"id": "now-1", "cap": "time.now"}, + ]}), + ) + .await; + // The request executed — its id is handled — but the program + // never saw the result: it waits in the queue instead. + assert!(actor.program_healthy); + assert!(actor.handled_requests.contains("now-1")); + assert_eq!(actor.pending_results.len(), 1); + assert_eq!(result_deliveries.load(Ordering::SeqCst), 0); + assert_eq!(journaled_results(&journal, "now-1"), 0); + // No retry before the window rolls, however often the actor + // settles: the queue is not a hot loop. + actor.after_change().await; + clock.advance(500); + actor.after_change().await; + assert_eq!(actor.pending_results.len(), 1); + assert_eq!(result_deliveries.load(Ordering::SeqCst), 0); + // Past the rollover the queued result is delivered, exactly + // once, and the program answers with it — no re-execution, no + // duplicate on a further settle. + clock.advance(600); + actor.after_change().await; + assert_eq!(result_deliveries.load(Ordering::SeqCst), 1); + assert!(actor.pending_results.is_empty()); + assert!(actor.fuel_retry_not_before.is_none()); + let result = schedule_result(&actor, "now-1").expect("the result arrived"); + assert_eq!(result["ok"], true, "{result}"); + assert_eq!(journaled_results(&journal, "now-1"), 1); + actor.after_change().await; + assert_eq!(result_deliveries.load(Ordering::SeqCst), 1); + assert_eq!(journaled_results(&journal, "now-1"), 1); + } + + // #1067 oracle (Codex review on #12557): a schedule fire refused + // at the fuel rate backs off until the window rolls instead of + // waking the loop now — no retry is attempted before the retry + // deadline — and the same occurrence then fires exactly once. + #[tokio::test] + async fn a_fuel_refused_schedule_fire_backs_off_until_rollover() { + let (mut actor, clock, _token, _journal, _, fire_attempts) = + fuel_window_actor("fuel-schedule", EPOCH_MS + 1_500); + actor + .core + .schedules + .insert("tick".to_owned(), PendingSchedule::one_shot(EPOCH_MS)); + // Before any refusal the overdue schedule wakes the loop now. + assert_eq!(actor.next_deadline(), Some(clock.now_instant())); + actor.fire_schedules().await; + assert!(actor.program_healthy); + assert!(actor.core.schedules.contains_key("tick")); + assert_eq!(fire_attempts.load(Ordering::SeqCst), 1); + // The refusal backs the next attempt off a full window. + assert_eq!( + actor.next_deadline(), + Some(clock.now_instant() + Duration::from_secs(1)) + ); + // A second fire without advancing the clock attempts nothing. + actor.fire_schedules().await; + assert_eq!(fire_attempts.load(Ordering::SeqCst), 1); + assert!(actor.core.schedules.contains_key("tick")); + // At the retry deadline the fire is attempted again — refused + // again while the window is still closed — and backs off + // another full window. + clock.advance(1_000); + actor.fire_schedules().await; + assert_eq!(fire_attempts.load(Ordering::SeqCst), 2); + assert_eq!( + actor.next_deadline(), + Some(clock.now_instant() + Duration::from_secs(1)) + ); + // Once the window rolls, the same occurrence fires exactly once. + clock.advance(1_000); + actor.fire_schedules().await; + assert_eq!(fire_attempts.load(Ordering::SeqCst), 3); + assert!(!actor.core.schedules.contains_key("tick")); + assert_eq!(schedule_fires(&actor).len(), 1); + } + // #8239 oracle: staged spends count against the uses limit before // commit - a batch of three from a participant with two uses left // admits exactly two, and the third is refused at prepare time with @@ -11049,16 +11465,50 @@ mod schedule_tests { let mut schedules = BTreeMap::new(); schedules.insert("a".to_owned(), PendingSchedule::one_shot(2_000)); let now = std::time::Instant::now(); - assert!(next_schedule_wake(&schedules, 1_000, now, true).is_some()); + assert!(next_schedule_wake(&schedules, 1_000, now, true, None).is_some()); assert!( - next_schedule_wake(&schedules, 3_000, now, true).is_some(), + next_schedule_wake(&schedules, 3_000, now, true, None).is_some(), "an overdue schedule wakes the loop now" ); assert!( - next_schedule_wake(&schedules, 3_000, now, false).is_none(), + next_schedule_wake(&schedules, 3_000, now, false, None).is_none(), "a program that refuses fires never wakes the loop for one" ); - assert!(next_schedule_wake(&BTreeMap::new(), 1_000, now, true).is_none()); + assert!(next_schedule_wake(&BTreeMap::new(), 1_000, now, true, None).is_none()); + // #1067: a due schedule whose fire was refused at the fuel rate + // waits until the retry deadline instead of waking the loop now. + assert_eq!( + next_schedule_wake( + &schedules, + 3_000, + now, + true, + Some(now + Duration::from_secs(1)) + ), + Some(now + Duration::from_secs(1)), + ); + // A schedule that is not due yet keeps its own wake, and a + // spent retry deadline holds nothing back. + assert_eq!( + next_schedule_wake( + &schedules, + 1_000, + now, + true, + Some(now + Duration::from_secs(1)) + ), + Some(now + Duration::from_millis(1_000)), + ); + assert_eq!( + next_schedule_wake( + &schedules, + 3_000, + now, + true, + Some(now - Duration::from_secs(1)) + ), + Some(now), + ); } #[test]