diff --git a/.opencode/plans/phase-9-portable-platform.md b/.opencode/plans/phase-9-portable-platform.md index 7e89cd7699..c6ce9fe958 100644 --- a/.opencode/plans/phase-9-portable-platform.md +++ b/.opencode/plans/phase-9-portable-platform.md @@ -75,6 +75,7 @@ each one is useful alone and does not depend on a later one. ## Phase 10 progress - **P10.1 started in this worktree:** role-scoped invites (`spectator`, `player`, `guest`, `delegator`) over the existing scope machinery, and `id world list --json` for directory feeds. Builder/moderator roles with their own authority, and a cross-node directory feed, remain follow-ups. Record: [roles and directory](../../doc/2026-10-17T08-00-00Z_feature_world_roles_directory/2026-10-17T08-00-00Z_feature_world_roles_directory.md). +- **P10.3 started in this worktree:** scheduled events. `schedule.at` and `schedule.cancel` capability requests (JOIN scope, granted and ceiling-checked), durable in the journal, with bounds of 64 pending schedules per world, 64-byte printable ids, and a 30-day horizon. A fire is delivered to the program as a host event and never reaches joiners; recurring and cross-world schedules remain follow-ups. Record: [scheduled events](../../doc/2026-10-17T10-00-00Z_feature_scheduled_events/2026-10-17T10-00-00Z_feature_scheduled_events.md). ## Next stage diff --git a/doc/2026-10-17T10-00-00Z_feature_scheduled_events/2026-10-17T10-00-00Z_feature_scheduled_events.md b/doc/2026-10-17T10-00-00Z_feature_scheduled_events/2026-10-17T10-00-00Z_feature_scheduled_events.md new file mode 100644 index 0000000000..484330222f --- /dev/null +++ b/doc/2026-10-17T10-00-00Z_feature_scheduled_events/2026-10-17T10-00-00Z_feature_scheduled_events.md @@ -0,0 +1,108 @@ +# Scheduled events: a world can ask for one fire at a set time + +See the [Phase 9 plan](../../.opencode/plans/phase-9-portable-platform.md) (Phase 10 progress, P10.3). This record follows [roles and directory](../2026-10-17T08-00-00Z_feature_world_roles_directory/2026-10-17T08-00-00Z_feature_world_roles_directory.md) and [world capability ceilings](../2026-10-16T11-00-00Z_feature_world_capability_ceilings/2026-10-16T11-00-00Z_feature_world_capability_ceilings.md). + +## Intent + +The Phase 10 sketch asks for "a first-class `schedule` capability for tournaments and reminders, durable in the journal, delivered as ticks." Subscribed ticks are a repeating timer tied to presence: they stop when nobody is connected and carry no meaning beyond an interval. A program that needs "start round three at 20:00 UTC" or "remind me in an hour" has nothing durable to ask for. This slice adds two capability requests and a journaled set of pending fires. It does not add recurring schedules, cross-world scheduling, or any way for a participant to see the schedule. + +## Requests + +- `schedule.at` with args `{"id": "", "at": }` returns `{"id", "fires_at"}`. +- `schedule.cancel` with args `{"id": ""}` returns `{"cancelled": }`. An id that is not pending returns `false`. + +Both are ordinary capability requests. They go through the capability ledger, so they are refused and counted when the world has not granted them or its ceiling excludes them. `decide_for` checks the acting participant's scopes through `allows_effect`; the default branch requires `join`, as for `records.read`. The program learns each outcome through the existing `result` event. No wire frame changes. + +A fire reaches the program as a host event with participant 0. It is never sequenced, never sent to sessions, and never part of `events_after` or a snapshot: + +```json +{ "cap": "schedule", "event": "fired", "id": "" } +``` + +`"late":true` is added only when the schedule was already overdue when the world reopened. + +## Decisions + +1. **Schedules are world state.** They live on `WorldCore`, not in the program, and they survive a program install. A new program receives the fires of schedules the previous one pended. The install clears only what belongs to a program's own subscriptions and requests. Fires do not wait for presence, unlike ticks: a world with nobody connected still runs its tournament. + +2. **Accept, journal the delivery, then consume the schedule.** A fire runs in this order: + 1. The program's `update` accepts the fire event. A refusal marks the program unavailable, as for any event, and nothing is journaled. + 2. The event is journaled as `JournalEntry::System`, the same entry ticks use. + 3. `JournalEntry::ScheduleFired { id }` removes the schedule from the pending set. + + The brief said "journaled before delivery, the same discipline as ticks". That does not match the code. `deliver` (used by ticks, presence, and results) and the participant input path both run `update` before they journal, because the journal must hold only what the program accepted. Journaling a fire first would record a delivery the program refused, and a restart would then lose the fire. This order keeps the schedule pending until its delivery is durable. The one window is a storage failure between steps 2 and 3. Then the fire is journaled but the schedule still pending, so a restart delivers it again, with `late:true`. That is at-least-once, and the program can dedupe on `id`. + +3. **Restore never reads the clock.** Pending schedules are rebuilt from `ScheduleSet`, `ScheduleCancelled` and `ScheduleFired` entries. A replay feeds the program the `System` events that were journaled, byte for byte, so `late` is not recomputed during replay. + +4. **Late means overdue at open.** When the actor starts, it records which restored schedules are already past their `at`. Their first fire carries `late:true`. A schedule requested in this run is never late, even if its `at` was in the past, and a cancel or fire removes the id from that set. + +5. **Waiting only while deliverable.** The loop sleeps until the earliest pending `at` only while the program is healthy and storage is writable. Otherwise a due schedule that cannot be delivered would wake the loop without end. The rule is a pure function, `next_schedule_wake`, so it can be tested. + +6. **Timer deadline uses the earliest tick.** The loop previously woke at `ticks.values().next()`, which is the deadline of the smallest interval, not the earliest deadline. It now takes the minimum over all armed ticks, so an interval that was armed later cannot be delivered late. This changes tick timing and is part of this slice because the deadline expression is shared. + +7. **Refusals carry no reason on the wire.** `CapError` has a code and no message, and adding a message field would change the result frame. The program sees `bad_args`. The reason (malformed id, duplicate id, full schedule, or horizon) is in the core validation error and in a debug log. + +8. **Wildcard grants reach the new names.** `*` grants every allowed catalog name, as it has for each name added since the catalog existed. A world granted `*` can schedule unless its ceiling excludes `schedule.at`. + +9. **The checkpoint must agree with its entries.** A checkpoint carries `schedules`, and `ScheduleSet` entries precede it, as `CapsCeiling` does. Restore refuses a journal where the two disagree. A journal this writer produces never disagrees, so the check only catches corruption. + +## Bounds + +| Bound | Value | Where | +| --------------------------- | --------------------------------------------------------------------------------------------------------------- | ----------------------------------------------- | +| Pending schedules per world | 64 | `MAX_PENDING_SCHEDULES` | +| Id length | 1 to 64 bytes, printable ASCII (0x20 to 0x7e) | `validate_schedule_id`, `MAX_SCHEDULE_ID_BYTES` | +| Horizon | `at` at most 30 days past the host clock at request time; any past `at` is allowed and fires on the next wakeup | `MAX_SCHEDULE_HORIZON_DAYS` | +| Fires per wakeup | 64, earliest first | `MAX_SCHEDULE_FIRES_PER_WAKEUP` | + +A refused request leaves the pending set and the journal unchanged; the capability usage counter still records the attempt. A duplicate pending id is refused, and the existing schedule is never overwritten. The horizon and count checks run only on a new request. Restore does not re-check the horizon, because the request time is not journaled. + +## Durability + +- `ScheduleSet { id, at_ms }` is journaled when a request is accepted, before its result is delivered. +- `ScheduleCancelled { id }` is journaled before a cancel's result is returned. +- `ScheduleFired { id }` follows the fire's `System` entry (decision 2). +- A checkpoint writes one `ScheduleSet` per pending schedule, before the checkpoint entry, and carries `schedules` as `(id, at_ms)` pairs. The field is omitted when nothing is pending, so older checkpoints and their JSON are unchanged. +- The state entries do not advance `since_checkpoint`. Their `System` event does, through `deliver`, so compaction cadence still follows delivered events. + +**Forward-only.** New entries mean an older binary cannot read a journal that holds them. This is the rollback limitation tracked in issue #227. The claim has a gap, found while writing this record. `FileJournal::open` treats an unparsable final line as a torn append and truncates it. So an older binary would silently drop a schedule entry that is the last line of a journal that was not compacted. A compacted journal is safe, because the `ScheduleSet` entries sit before the checkpoint and are not last. Closing the gap means `FileJournal::open` must refuse an unparsable line that ends in a newline. That changes the torn-tail rule for every entry type, so it is a follow-up and not part of this slice. + +## Security + +- Scheduling adds no authority. It needs the `schedule.at` grant and the ceiling must allow it. A fire delivers only to the program that already holds the world's state. +- The host clock decides when a fire happens, and that decision is journaled. A replay never reads the clock. +- Bounds cap memory and journal growth per world: 64 pending, 30 days ahead, and 64-byte ids. +- Each accepted or refused request still produces a journaled `result` event, so churn (schedule, cancel, schedule) costs journal space as `chat.say` does. Compaction trims it. +- A participant can cause a schedule only by sending input that makes the program ask. That input requires the `input` scope, and the request requires `join`, as for any effect a program takes on input. + +## Follow-ups + +- Recurring schedules and a `schedule.list` request, if an app needs them. +- Cross-world scheduling. Not designed. +- A re-requested pending id, after a restart or program install, gets `bad_args` instead of its original result. The program would see an error for a schedule that is pending with the same `at`. Idempotent re-request needs a design decision. +- Refuse unparsable complete journal lines in `FileJournal::open` (see Durability), to make rollback safe for every entry type. Issue #227. +- Host events never enter the event stream, so a joiner cannot see a fire. Issue #242. +- Whether `schedule.at` should need a scope beyond `join`, for example `chat`. Not decided here. + +--- + +## 2026-10-17T12-10-00Z Update: implemented as designed, with the deviations listed + +Shipped: + +- `world_caps.rs`: `schedule.at` and `schedule.cancel` in the catalog, the bounds (`MAX_PENDING_SCHEDULES`, `MAX_SCHEDULE_ID_BYTES`, `MAX_SCHEDULE_HORIZON_DAYS`, `MAX_SCHEDULE_FIRES_PER_WAKEUP`), and `validate_schedule_id`. +- `world.rs`: the three journal entries, the checkpoint `schedules` field with its consistency check, `WorldCore::check_schedule`, the two request handlers, `fire_schedules`, `next_schedule_wake`, and the overdue-at-open set. Its tests are in `schedule_tests`. +- `world_store.rs`: a file-journal round trip for the new entries. +- `examples/roc-world/RocCap.roc`: `schedule_at_request` and `schedule_cancel_request`, checked by a compile-and-run test in `world_compile.rs`. The README lists the capabilities and builders. + +Deviations from the brief, for review: + +1. **Fire order.** The fire is accepted, then its `System` delivery is journaled, then `ScheduleFired` is journaled (decision 2). The brief's "journaled before delivery" does not describe the code: `deliver` and the participant input path both journal after the program accepts. The README and the `world_caps` module comment repeated the same wording and now match the code. +2. **Tick deadline.** The loop wakes at the minimum over armed ticks. The previous expression read the deadline of the smallest interval key (decision 6). +3. **Checkpoint consistency.** Restore refuses a checkpoint whose `schedules` disagree with the `ScheduleSet` entries before it (decision 9). +4. **Refusal reason.** The program sees `bad_args`. The reason goes to the core error and a debug log (decision 7). + +Found while testing: + +- `FileJournal::open` truncates an unparsable final line as a torn append, so an older binary can silently drop a trailing schedule entry from an uncompacted journal. Compaction protects only compacted journals (see Durability). The fix is a follow-up. +- A pending schedule survives a program install (decision 1). A re-requested pending id after an install or restart gets `bad_args` (see Follow-ups). diff --git a/pkgs/id/examples/roc-world/README.md b/pkgs/id/examples/roc-world/README.md index 2695c2ce53..cedcd4baf5 100644 --- a/pkgs/id/examples/roc-world/README.md +++ b/pkgs/id/examples/roc-world/README.md @@ -59,12 +59,20 @@ program holds and the one-shot requests it has outstanding The host answers each new request with a host event (participant 0) carrying `{"cap":"result","id":"r1","ok":true,"value":...}` or `"ok":false` with an error code, and delivers subscription events (`time.tick`, `players`) as host -events too. Every host event is journaled before delivery, so replay is -exact. A request to a capability the world has not granted is answered with -`cap_denied` — never silently. See the design doc for the catalog +events too. Every host event is journaled once the program accepts it, so +replay is exact. A request to a capability the world has not granted is +answered with `cap_denied` — never silently. See the design doc for the catalog (`time.now`, `time.tick`, `random.u64`, `players`, `players.list`, -`chat.say`, `chat.history`, `records.read`, `world.info`, and the platform modules `Key`, -`Screen`, `RocJson`, `RocGrid`, `RocCap`, `RocText`). +`chat.say`, `chat.history`, `records.read`, `schedule.at`, `schedule.cancel`, +`world.info`, and the platform modules `Key`, `Screen`, `RocJson`, `RocGrid`, +`RocCap`, `RocText`). + +`schedule.at` asks for one fire of a named schedule at a unix-millisecond time +(a time already past fires on the next wakeup; one more than 30 days ahead is refused). +In a durable world, pending schedules survive a restart, and they fire even when +nobody is connected. A fire arrives as `{"cap":"schedule","event":"fired","id":...}`, with +`"late":true` when the world reopened after the time had passed. +`schedule.cancel` drops a pending schedule and reports whether one was dropped. The platform also exposes the dependency-free `RocJson.roc` module to apps as `pf.RocJson`. Its `decode`/`encode`, object `get`, and type-specific `as_*` accessors let @@ -87,7 +95,7 @@ index arithmetic per app. `examples/roc-grid` is the checked-in example. protocol. `issue` reserves `r0`, `r1`, … ids and records each one's capability; `attach` stores the request document so `requests` can re-announce it in `wants` after replay; `chat_request`, `now_request`, `players_request`, -`world_request`, `history_request`, and `records_request` build the documents; `answered` routes a +`world_request`, `history_request`, `records_request`, `schedule_at_request`, and `schedule_cancel_request` build the documents; `answered` routes a result back to the capability that asked; `done` retires it; and `from_pending` rebuilds a session from a snapshot. `history_lines` reads the rows of a `chat.history` result. Apps stop re-deriving id counters and pending lists. diff --git a/pkgs/id/examples/roc-world/RocCap.roc b/pkgs/id/examples/roc-world/RocCap.roc index 4243740b92..519e7f6360 100644 --- a/pkgs/id/examples/roc-world/RocCap.roc +++ b/pkgs/id/examples/roc-world/RocCap.roc @@ -143,6 +143,35 @@ RocCap := { next_after : RocJson -> Str next_after = |value| string_field(value, "next_after") + ## A `schedule.at` request document: ask for one `schedule_id` fire at + ## `at_ms` (unix milliseconds). A time in the past fires on the next wakeup. + ## The server refuses ids that are empty, longer than 64 bytes, or not + ## printable ASCII; a duplicate of a pending id; and times more than 30 days + ## ahead. The result is `{"id":..,"fires_at":..}` or `bad_args`. + schedule_at_request : Str, Str, U64 -> RocJson + schedule_at_request = |id, schedule_id, at_ms| + RocJson.Object([ + { key: "id", value: RocJson.String(id) }, + { key: "cap", value: RocJson.String("schedule.at") }, + { + key: "args", + value: RocJson.Object([ + { key: "id", value: RocJson.String(schedule_id) }, + { key: "at", value: RocJson.Number(at_ms.to_str()) }, + ]), + }, + ]) + + ## A `schedule.cancel` request document. The result is `{"cancelled":bool}`: + ## `true` when a pending schedule with `schedule_id` was dropped before it fired. + schedule_cancel_request : Str, Str -> RocJson + schedule_cancel_request = |id, schedule_id| + RocJson.Object([ + { key: "id", value: RocJson.String(id) }, + { key: "cap", value: RocJson.String("schedule.cancel") }, + { key: "args", value: RocJson.Object([{ key: "id", value: RocJson.String(schedule_id) }]) }, + ]) + ## An array field of a JSON object, or `[]` when missing or not an array. list_field : RocJson, Str -> List(RocJson) list_field = |value, key| match RocJson.get(value, key) { diff --git a/pkgs/id/src/world.rs b/pkgs/id/src/world.rs index f200867c10..668c44c627 100644 --- a/pkgs/id/src/world.rs +++ b/pkgs/id/src/world.rs @@ -489,6 +489,26 @@ pub enum JournalEntry { /// The new setting. enabled: bool, }, + /// A `schedule.at` request was accepted: `id` fires once, at `at_ms` (unix + /// milliseconds). Written before the request's result is delivered. + ScheduleSet { + /// The schedule's id, unique among pending schedules. + id: String, + /// When it fires, in unix milliseconds. + at_ms: u64, + }, + /// A pending schedule was cancelled before it fired. + ScheduleCancelled { + /// The cancelled schedule's id. + id: String, + }, + /// A pending schedule fired. It follows the fire's `System` entry, which + /// the program accepted first, so the schedule is consumed only once its + /// delivery is durable. + ScheduleFired { + /// The fired schedule's id. + id: String, + }, /// The world as of `sequence`, standing in for every event up to it. Only /// ever written by compaction, directly after the participant entries. Checkpoint { @@ -508,6 +528,10 @@ pub enum JournalEntry { /// when it is the whole catalog. #[serde(default, skip_serializing_if = "Option::is_none")] caps_ceiling: Option>, + /// Pending schedules as `(id, at_ms)`. Absent when none are pending, + /// and it must match the `ScheduleSet` entries before it. + #[serde(default, skip_serializing_if = "Option::is_none")] + schedules: Option>, /// The program's own serialization of its state. snapshot: String, /// Recent events kept for reconnect catch-up. @@ -604,6 +628,32 @@ fn presence_change(text: &str) -> Option<(u64, bool)> { Some((value.get("participant")?.get("id")?.as_u64()?, joined)) } +/// The host event a program receives when schedule `id` fires. `late` is set +/// only for a schedule the journal left overdue when the world reopened. +fn schedule_fired_event(id: &str, late: bool) -> String { + let mut event = serde_json::json!({"cap": "schedule", "event": "fired", "id": id}); + if late { + event["late"] = serde_json::Value::Bool(true); + } + event.to_string() +} + +/// When the earliest pending schedule is due, as a monotonic deadline. Nothing +/// 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. +fn next_schedule_wake( + schedules: &BTreeMap, + now_ms: u64, + deliverable: bool, +) -> Option { + if !deliverable { + return None; + } + let earliest = schedules.values().min().copied()?; + let wait = std::time::Duration::from_millis(earliest.saturating_sub(now_ms)); + Some(std::time::Instant::now() + wait) +} + /// The newest `count` chat lines in `events`, oldest first, each carrying its /// sequence, participant id, and text. The retained-events buffer is itself /// bounded by the world's limits, so a request can never see unbounded history. @@ -829,6 +879,8 @@ pub struct WorldCore { /// This world's own capability ceiling. The ledger allows the intersection /// of this and the server's `limits.server_caps`. caps_ceiling: BTreeSet, + /// Pending `schedule.at` fires: id to due time, in unix milliseconds. + schedules: BTreeMap, isolation: Isolation, cross_world_write: bool, cross_world_forced: bool, @@ -880,6 +932,7 @@ impl WorldCore { active_seed: 0, ledger: crate::world_caps::CapLedger::new(BTreeSet::new(), grant_on_use), caps_ceiling: crate::world_caps::catalog_names(), + schedules: BTreeMap::new(), isolation: Isolation::default(), cross_world_write: false, cross_world_forced: false, @@ -1044,6 +1097,34 @@ impl WorldCore { } JournalEntry::FileScope { scope } => core.file_scope = scope, JournalEntry::FileWriteOverride { enabled } => core.file_write_override = enabled, + JournalEntry::ScheduleSet { id, at_ms } => { + crate::world_caps::validate_schedule_id(&id) + .context("invalid schedule id in journal")?; + ensure!( + !core.schedules.contains_key(&id), + "journal schedules {id:?} twice" + ); + ensure!( + core.schedules.len() < crate::world_caps::MAX_PENDING_SCHEDULES, + "journal holds more than {} pending schedules", + crate::world_caps::MAX_PENDING_SCHEDULES + ); + // No clock here: the due time is what the request set, and + // a restore never judges it against now. + core.schedules.insert(id, at_ms); + } + JournalEntry::ScheduleCancelled { id } => { + ensure!( + core.schedules.remove(&id).is_some(), + "journal cancels schedule {id:?}, which is not pending" + ); + } + JournalEntry::ScheduleFired { id } => { + ensure!( + core.schedules.remove(&id).is_some(), + "journal fires schedule {id:?}, which is not pending" + ); + } JournalEntry::System { event } => { ensure!( event.sequence == 0 && event.participant_id == 0, @@ -1105,6 +1186,7 @@ impl WorldCore { provenance, execution_profile, caps_ceiling, + schedules, snapshot, events, } => { @@ -1142,6 +1224,14 @@ impl WorldCore { } None => crate::world_caps::catalog_names(), }; + // The writer emits one `ScheduleSet` per pending schedule + // before the checkpoint, so the two must agree exactly. + let listed = schedules.unwrap_or_default(); + let declared: BTreeMap = listed.iter().cloned().collect(); + ensure!( + declared.len() == listed.len() && declared == core.schedules, + "journal checkpoint's pending schedules disagree with its schedule entries" + ); program = Some(RestoredProgram { module_hash, seed, @@ -1243,6 +1333,21 @@ impl WorldCore { profile: self.execution_profile, }); } + // One entry per pending schedule, before the checkpoint, mirroring the + // ceiling: an older binary cannot read `ScheduleSet` and refuses the + // journal, instead of restoring without the schedules. + for (id, at_ms) in &self.schedules { + entries.push(JournalEntry::ScheduleSet { + id: id.clone(), + at_ms: *at_ms, + }); + } + let schedules: Option> = (!self.schedules.is_empty()).then(|| { + self.schedules + .iter() + .map(|(id, at_ms)| (id.clone(), *at_ms)) + .collect() + }); entries.push(JournalEntry::Checkpoint { sequence: self.sequence, module_hash, @@ -1250,6 +1355,7 @@ impl WorldCore { provenance: self.active_module_provenance.clone(), execution_profile: Some(self.execution_profile), caps_ceiling, + schedules, snapshot, events: self.events.iter().cloned().collect(), }); @@ -1290,6 +1396,33 @@ impl WorldCore { self.commit(0, WorldEventKind::Chat(text)) } + /// Whether a `schedule.at` for `id` may be pended, given the host clock + /// `now_ms`. The error says why; the program sees only `bad_args`. + /// + /// # Errors + /// + /// A malformed id, a duplicate pending id, a full schedule, or a time past + /// the horizon. + fn check_schedule(&self, id: &str, at_ms: u64, now_ms: u64) -> Result<()> { + crate::world_caps::validate_schedule_id(id)?; + ensure!( + !self.schedules.contains_key(id), + "schedule {id:?} is already pending; cancel it before scheduling it again" + ); + ensure!( + self.schedules.len() < crate::world_caps::MAX_PENDING_SCHEDULES, + "world already has {} pending schedules", + crate::world_caps::MAX_PENDING_SCHEDULES + ); + let horizon = now_ms.saturating_add(crate::world_caps::MAX_SCHEDULE_HORIZON_MS); + ensure!( + at_ms <= horizon, + "schedule {id:?} is more than {} days past the host clock", + crate::world_caps::MAX_SCHEDULE_HORIZON_DAYS + ); + Ok(()) + } + /// Journal entry for an already-issued capability. fn issued_entry(&self, participant_id: u64) -> Option { self.capabilities @@ -2041,6 +2174,9 @@ struct WorldActor { denied_subs: BTreeSet, /// Armed tick intervals to their next fire time. ticks: BTreeMap, + /// Restored schedules already overdue when the world opened. Their first + /// fire is marked `late`; a cancel or fire removes the id. + overdue_at_open: BTreeSet, /// The participant whose input is being processed. Requests the program /// makes in response are checked against that participant's scopes. acting: Option, @@ -2050,9 +2186,9 @@ impl WorldActor { async fn run(mut self, mut receiver: mpsc::Receiver) { self.after_change().await; loop { - // Ticks sleep until their earliest deadline; with none armed this - // branch never wakes. - let deadline = self.ticks.values().next().copied(); + // Ticks and schedules sleep until their earliest deadline; with + // neither armed this branch never wakes. + let deadline = self.next_deadline(); let command = tokio::select! { command = receiver.recv() => match command { Some(command) => command, @@ -2060,6 +2196,7 @@ impl WorldActor { }, () = Self::sleep_until(deadline) => { self.fire_ticks().await; + self.fire_schedules().await; self.after_change().await; continue; } @@ -2085,6 +2222,23 @@ impl WorldActor { } } + /// The earliest moment the loop must wake: the soonest armed tick or + /// pending schedule. Schedules wait only while the program can take them. + fn next_deadline(&self) -> Option { + let deliverable = self.program_healthy && !self.storage_failed; + self.ticks + .values() + .min() + .copied() + .into_iter() + .chain(next_schedule_wake( + &self.core.schedules, + unix_ms(), + deliverable, + )) + .min() + } + fn check_storage(&self) -> Result<()> { ensure!( !self.storage_failed, @@ -2130,13 +2284,14 @@ 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. - async fn deliver(&mut self, text: String) { + /// Returns whether the program accepted the event and it was journaled. + async fn deliver(&mut self, text: String) -> bool { if !self.program_healthy || self.storage_failed { - return; + return false; } if text.len() > crate::world_caps::MAX_EVENT_BYTES { tracing::error!("world event exceeds the delivery bound; dropped"); - return; + return false; } let event = WorldEvent { sequence: 0, @@ -2146,7 +2301,7 @@ impl WorldActor { if let Err(error) = self.program.update(&event) { self.program_healthy = false; tracing::error!("world program rejected a host event: {error:#}"); - return; + return false; } match program_records(self.program.as_mut()) { Ok(records) => { @@ -2156,13 +2311,15 @@ impl WorldActor { Err(error) => { self.program_healthy = false; tracing::error!("world program records failed: {error:#}"); - return; + return false; } } - if self.persist(JournalEntry::System { event }).is_ok() { + let journaled = self.persist(JournalEntry::System { event }).is_ok(); + if journaled { self.core.since_checkpoint = self.core.since_checkpoint.saturating_add(1); } let _ = self.view_changed.send(self.core.sequence); + journaled } /// Recompute the program's `wants` and serve the delta: new subscriptions @@ -2288,6 +2445,38 @@ impl WorldActor { } } + /// Fire the schedules that are due, earliest first, at most + /// [`crate::world_caps::MAX_SCHEDULE_FIRES_PER_WAKEUP`] per wakeup. Each + /// 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. + async fn fire_schedules(&mut self) { + let now = unix_ms(); + let mut due: Vec<(u64, String)> = self + .core + .schedules + .iter() + .filter(|(_, at_ms)| **at_ms <= now) + .map(|(id, at_ms)| (*at_ms, id.clone())) + .collect(); + due.sort_unstable(); + due.truncate(crate::world_caps::MAX_SCHEDULE_FIRES_PER_WAKEUP); + for (_, id) in due { + let late = self.overdue_at_open.contains(&id); + if !self.deliver(schedule_fired_event(&id, late)).await { + break; + } + if self + .persist(JournalEntry::ScheduleFired { id: id.clone() }) + .is_err() + { + break; + } + self.core.schedules.remove(&id); + self.overdue_at_open.remove(&id); + } + } + /// Execute one capability request. Anything the world has not granted is /// an error the program sees. fn execute(&mut self, request: &Request) -> Result { @@ -2327,6 +2516,8 @@ impl WorldActor { ), })), "records.read" => self.execute_records_read(&request.args), + "schedule.at" => self.execute_schedule_at(&request.args), + "schedule.cancel" => self.execute_schedule_cancel(&request.args), _ => Err(CapError::Unknown), } } @@ -2410,6 +2601,65 @@ impl WorldActor { } } + /// `schedule.at`: pend one fire of `id` at `at` (unix ms). The schedule is + /// journaled before the result is delivered. A refused request changes + /// nothing but the usage count. + fn execute_schedule_at( + &mut self, + args: &serde_json::Value, + ) -> Result { + let id = args + .get("id") + .and_then(serde_json::Value::as_str) + .ok_or(CapError::BadArgs)?; + let at_ms = args + .get("at") + .and_then(serde_json::Value::as_u64) + .ok_or(CapError::BadArgs)?; + if let Err(error) = self.core.check_schedule(id, at_ms, unix_ms()) { + tracing::debug!("world {}: schedule refused: {error:#}", self.core.world_id); + return Err(CapError::BadArgs); + } + if self + .persist(JournalEntry::ScheduleSet { + id: id.to_owned(), + at_ms, + }) + .is_err() + { + return Err(CapError::Failed); + } + self.core.schedules.insert(id.to_owned(), at_ms); + Ok(serde_json::json!({"id": id, "fires_at": at_ms})) + } + + /// `schedule.cancel`: drop a pending schedule before it fires. `cancelled` + /// is false when nothing by that id is pending. + fn execute_schedule_cancel( + &mut self, + args: &serde_json::Value, + ) -> Result { + let id = args + .get("id") + .and_then(serde_json::Value::as_str) + .ok_or(CapError::BadArgs)?; + if crate::world_caps::validate_schedule_id(id).is_err() { + return Err(CapError::BadArgs); + } + if !self.core.schedules.contains_key(id) { + return Ok(serde_json::json!({"cancelled": false})); + } + if self + .persist(JournalEntry::ScheduleCancelled { id: id.to_owned() }) + .is_err() + { + return Err(CapError::Failed); + } + self.core.schedules.remove(id); + self.overdue_at_open.remove(id); + Ok(serde_json::json!({"cancelled": true})) + } + /// A participant opened or closed a session: presence transitions deliver /// `players` events and arm or disarm ticks. async fn handle_presence(&mut self, participant: u64, joined: bool) { @@ -3057,6 +3307,14 @@ impl WorldHandle { } }; let (records_sender, records) = watch::channel((core.sequence, Arc::new(initial))); + // Schedules the journal left pending that are already due fire late. + let now = unix_ms(); + let overdue_at_open: BTreeSet = core + .schedules + .iter() + .filter(|(_, at_ms)| **at_ms <= now) + .map(|(id, _)| id.clone()) + .collect(); let actor = WorldActor { core, program, @@ -3073,6 +3331,7 @@ impl WorldHandle { handled_requests: BTreeSet::new(), denied_subs: BTreeSet::new(), ticks: BTreeMap::new(), + overdue_at_open, acting: None, auth: crate::directory_auth::DirectoryAuth::default(), }; @@ -6640,3 +6899,660 @@ mod isolation_tests { } } } + +#[cfg(test)] +#[allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] +mod schedule_tests { + use super::*; + + fn world(retained_events: usize) -> WorldCore { + WorldCore::new( + "test-world", + WorldLimits { + retained_events, + ..WorldLimits::default() + }, + ) + .unwrap() + } + + /// A program for the schedule tests. Each input is a request document, and + /// the program asks for its requests until each one's result arrives. Its + /// records carry every schedule fire and every result, so a test reads them + /// through `WorldHandle::records`. + #[derive(Default)] + struct Scheduler { + requests: Vec, + answered: BTreeSet, + results: BTreeMap, + fires: Vec, + refuse_fires: bool, + } + + impl WorldProgram for Scheduler { + 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::System { event: text } => { + let Ok(value) = serde_json::from_str::(text) else { + return Ok(()); + }; + match value["cap"].as_str() { + Some("result") => { + if let Some(id) = value["id"].as_str() { + self.answered.insert(id.to_owned()); + self.results.insert(id.to_owned(), value.clone()); + } + } + Some("schedule") => { + if self.refuse_fires { + bail!("this program refuses schedule fires"); + } + 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 journal kept in memory, so a test can restore from what was written. + #[derive(Clone, Default)] + struct Recorded(Arc>>); + + impl Recorded { + /// A journal that starts with the header a real world writes first. + fn for_world(world_id: &str) -> Self { + let journal = Self::default(); + journal.0.lock().unwrap().push(JournalEntry::Created { + world_id: world_id.to_owned(), + version: JOURNAL_VERSION, + }); + journal + } + + fn entries(&self) -> Vec { + self.0.lock().unwrap().clone() + } + } + + impl WorldJournal for Recorded { + fn append(&mut self, entry: &JournalEntry) -> Result<()> { + self.0.lock().unwrap().push(entry.clone()); + Ok(()) + } + } + + /// A journaled world running a `Scheduler`, with one participant and the + /// given grants. + async fn scheduling_world( + id: &str, + grants: &[&str], + refuse_fires: bool, + ) -> (WorldHandle, JoinCapability, Recorded) { + let journal = Recorded::for_world(id); + let core = WorldCore::new(id, WorldLimits::default()).unwrap(); + let program = Scheduler { + refuse_fires, + ..Scheduler::default() + }; + let world = + WorldHandle::spawn_durable(core, Box::new(program), Some(Box::new(journal.clone()))); + let (_, token) = world.issue("ann", WorldScopes::GUEST).await.unwrap(); + if !grants.is_empty() { + world + .update_caps( + grants.iter().map(|grant| (*grant).to_owned()).collect(), + Vec::new(), + ) + .await + .unwrap(); + } + (world, token, journal) + } + + /// Send one request document to the program as a participant's input. + async fn ask(world: &WorldHandle, token: &JoinCapability, document: serde_json::Value) { + world + .input(token.clone(), document.to_string().into_bytes()) + .await + .unwrap(); + } + + /// The schedule fire events the program has received so far. + fn schedule_fires(world: &WorldHandle) -> Vec { + world + .records() + .1 + .get("fired") + .and_then(serde_json::Value::as_array) + .cloned() + .unwrap_or_default() + } + + /// The result event the program received for request `id`, if any. + fn schedule_result(world: &WorldHandle, id: &str) -> Option { + world + .records() + .1 + .get("results") + .and_then(|results| results.get(id)) + .cloned() + } + + /// Poll until `ready` holds, failing after three seconds. + async fn eventually(what: &str, mut ready: impl FnMut() -> bool) { + let deadline = std::time::Instant::now() + std::time::Duration::from_secs(3); + while !ready() { + assert!( + std::time::Instant::now() < deadline, + "timed out waiting for {what}" + ); + tokio::time::sleep(std::time::Duration::from_millis(10)).await; + } + } + + #[test] + fn schedule_bounds_refuse_each_violation_with_a_reason() { + let now = 1_000_000_000_000u64; + let horizon = crate::world_caps::MAX_SCHEDULE_HORIZON_MS; + let mut core = world(8); + assert!(core.check_schedule("ok", now, now).is_ok()); + assert!(core.check_schedule(&"x".repeat(64), now, now).is_ok()); + let long = "x".repeat(65); + for bad in ["", "tab\there", long.as_str()] { + let error = core.check_schedule(bad, now, now).unwrap_err(); + assert!(error.to_string().contains("schedule id"), "{error}"); + } + + core.schedules.insert("taken".to_owned(), now + 5); + let error = core.check_schedule("taken", now + 9, now).unwrap_err(); + assert!(error.to_string().contains("already pending"), "{error}"); + assert_eq!( + core.schedules["taken"], + now + 5, + "a duplicate overwrites nothing" + ); + + assert!(core.check_schedule("edge", now + horizon, now).is_ok()); + let error = core + .check_schedule("far", now + horizon + 1, now) + .unwrap_err(); + assert!(error.to_string().contains("days past"), "{error}"); + assert!(core.check_schedule("past", 0, now).is_ok()); + + let mut full = world(8); + for index in 0..crate::world_caps::MAX_PENDING_SCHEDULES - 1 { + full.schedules.insert(format!("s{index}"), now); + } + assert!(full.check_schedule("last", now, now).is_ok()); + full.schedules.insert("last".to_owned(), now); + let error = full.check_schedule("one-more", now, now).unwrap_err(); + assert!(error.to_string().contains("pending schedules"), "{error}"); + } + + #[tokio::test] + async fn an_ungranted_schedule_is_refused_and_counted() { + let (world, token, journal) = scheduling_world("sched-refused", &[], false).await; + ask( + &world, + &token, + serde_json::json!({"requests": [ + {"id": "s1", "cap": "schedule.at", "args": {"id": "nap", "at": unix_ms() + 60_000}}, + ]}), + ) + .await; + eventually("the refusal", || schedule_result(&world, "s1").is_some()).await; + assert_eq!( + schedule_result(&world, "s1").unwrap()["error"], + "cap_denied" + ); + let report = world.caps_report().await.unwrap(); + assert!(report.usage["schedule.at"].denied > 0, "{report:?}"); + world.shutdown().await.unwrap(); + assert!( + journal + .entries() + .iter() + .all(|entry| !matches!(entry, JournalEntry::ScheduleSet { .. })), + "a refused request pends nothing" + ); + } + + #[tokio::test] + async fn a_due_schedule_fires_once_and_the_program_receives_it() { + let (world, token, journal) = scheduling_world("sched-fire", &["schedule.at"], false).await; + ask( + &world, + &token, + serde_json::json!({"requests": [ + {"id": "s1", "cap": "schedule.at", "args": {"id": "now", "at": unix_ms()}}, + ]}), + ) + .await; + eventually("the fire", || !schedule_fires(&world).is_empty()).await; + tokio::time::sleep(std::time::Duration::from_millis(100)).await; + let fires = schedule_fires(&world); + assert_eq!(fires.len(), 1, "{fires:?}"); + assert_eq!(fires[0]["id"], "now"); + assert!( + fires[0].get("late").is_none(), + "a fire in this run is not late" + ); + world.shutdown().await.unwrap(); + + let entries = journal.entries(); + let fire = WorldEventKind::System { + event: schedule_fired_event("now", false), + }; + let delivered = entries + .iter() + .position(|entry| matches!(entry, JournalEntry::System { event } if event.kind == fire)) + .expect("the fire is journaled as delivered"); + let consumed = entries + .iter() + .position(|entry| matches!(entry, JournalEntry::ScheduleFired { id } if id == "now")) + .expect("the schedule is consumed"); + assert!(delivered < consumed, "the delivery is journaled first"); + assert_eq!( + entries + .iter() + .filter(|entry| matches!(entry, JournalEntry::ScheduleFired { .. })) + .count(), + 1 + ); + } + + #[tokio::test] + async fn a_cancelled_schedule_never_fires_and_an_unknown_id_says_false() { + let (world, token, _journal) = + scheduling_world("sched-cancel", &["schedule.at", "schedule.cancel"], false).await; + let at = unix_ms(); + // One pass: the cancel runs before any timer can fire the schedule. + ask( + &world, + &token, + serde_json::json!({"requests": [ + {"id": "s1", "cap": "schedule.at", "args": {"id": "soon", "at": at}}, + {"id": "c1", "cap": "schedule.cancel", "args": {"id": "soon"}}, + {"id": "c2", "cap": "schedule.cancel", "args": {"id": "ghost"}}, + ]}), + ) + .await; + eventually("the cancel results", || { + schedule_result(&world, "c2").is_some() + }) + .await; + assert_eq!( + schedule_result(&world, "s1").unwrap()["value"]["fires_at"], + at + ); + assert_eq!( + schedule_result(&world, "c1").unwrap()["value"]["cancelled"], + true + ); + assert_eq!( + schedule_result(&world, "c2").unwrap()["value"]["cancelled"], + false + ); + tokio::time::sleep(std::time::Duration::from_millis(100)).await; + assert!( + schedule_fires(&world).is_empty(), + "a cancelled schedule must not fire" + ); + world.shutdown().await.unwrap(); + } + + #[tokio::test] + async fn refused_schedule_requests_pend_nothing() { + let (world, token, journal) = + scheduling_world("sched-bad", &["schedule.at", "schedule.cancel"], false).await; + let later = unix_ms() + 3_600_000; + let far = unix_ms() + crate::world_caps::MAX_SCHEDULE_HORIZON_MS + 60_000; + let long_id = "x".repeat(65); + ask( + &world, + &token, + serde_json::json!({"requests": [ + {"id": "ok", "cap": "schedule.at", "args": {"id": "kept", "at": later}}, + {"id": "empty", "cap": "schedule.at", "args": {"id": "", "at": later}}, + {"id": "long", "cap": "schedule.at", "args": {"id": long_id, "at": later}}, + {"id": "far", "cap": "schedule.at", "args": {"id": "far", "at": far}}, + {"id": "dup", "cap": "schedule.at", "args": {"id": "kept", "at": later}}, + {"id": "missing", "cap": "schedule.at", "args": {"id": "nothing"}}, + {"id": "text", "cap": "schedule.at", "args": {"id": "t", "at": "soon"}}, + {"id": "bad-cancel", "cap": "schedule.cancel", "args": {"id": "a\nb"}}, + ]}), + ) + .await; + eventually("the last result", || { + schedule_result(&world, "bad-cancel").is_some() + }) + .await; + assert_eq!(schedule_result(&world, "ok").unwrap()["ok"], true); + for id in [ + "empty", + "long", + "far", + "dup", + "missing", + "text", + "bad-cancel", + ] { + assert_eq!( + schedule_result(&world, id).unwrap()["error"], + "bad_args", + "{id}" + ); + } + world.shutdown().await.unwrap(); + let pended: Vec = journal + .entries() + .into_iter() + .filter_map(|entry| match entry { + JournalEntry::ScheduleSet { id, .. } => Some(id), + _ => None, + }) + .collect(); + assert_eq!(pended, ["kept"], "only the accepted request is journaled"); + } + + #[tokio::test] + async fn a_fire_the_program_refuses_stays_pending_in_the_journal() { + let (world, token, journal) = + scheduling_world("sched-refuse", &["schedule.at"], true).await; + ask( + &world, + &token, + serde_json::json!({"requests": [ + {"id": "s1", "cap": "schedule.at", "args": {"id": "stuck", "at": unix_ms()}}, + ]}), + ) + .await; + eventually("the request result", || { + schedule_result(&world, "s1").is_some() + }) + .await; + tokio::time::sleep(std::time::Duration::from_millis(100)).await; + // The program is unavailable now, but the actor still answers. + assert!(world.caps_report().await.is_ok()); + world.shutdown().await.unwrap(); + + let entries = journal.entries(); + assert!( + !entries + .iter() + .any(|entry| matches!(entry, JournalEntry::ScheduleFired { .. })), + "a refused fire is not consumed" + ); + let journaled_fire = entries.iter().any(|entry| match entry { + JournalEntry::System { event } => matches!( + &event.kind, + WorldEventKind::System { event } if event.contains("\"schedule\"") + ), + _ => false, + }); + assert!(!journaled_fire, "a refused fire is not journaled"); + let restored = WorldCore::restore("sched-refuse", WorldLimits::default(), entries).unwrap(); + assert!( + restored.core.schedules.contains_key("stuck"), + "the next run delivers it" + ); + } + + #[tokio::test] + async fn a_schedule_overdue_at_restart_fires_late_on_the_first_wakeup() { + let entries = vec![ + JournalEntry::Created { + world_id: "sched-late".to_owned(), + version: JOURNAL_VERSION, + }, + JournalEntry::ScheduleSet { + id: "overdue".to_owned(), + at_ms: unix_ms() - 5_000, + }, + ]; + let restored = WorldCore::restore("sched-late", WorldLimits::default(), entries).unwrap(); + let journal = Recorded::default(); + let world = WorldHandle::spawn_durable( + restored.core, + Box::new(Scheduler::default()), + Some(Box::new(journal.clone())), + ); + eventually("the late fire", || !schedule_fires(&world).is_empty()).await; + let fires = schedule_fires(&world); + assert_eq!(fires.len(), 1, "{fires:?}"); + assert_eq!(fires[0]["id"], "overdue"); + assert_eq!(fires[0]["late"], true); + world.shutdown().await.unwrap(); + assert!( + journal.entries().iter().any( + |entry| matches!(entry, JournalEntry::ScheduleFired { id } if id == "overdue") + ) + ); + } + + #[tokio::test] + async fn a_pending_schedule_survives_a_restart_and_fires_on_time() { + let at_ms = unix_ms() + 700; + let entries = vec![ + JournalEntry::Created { + world_id: "sched-later".to_owned(), + version: JOURNAL_VERSION, + }, + JournalEntry::ScheduleSet { + id: "later".to_owned(), + at_ms, + }, + ]; + let restored = WorldCore::restore("sched-later", WorldLimits::default(), entries).unwrap(); + assert_eq!(restored.core.schedules.get("later"), Some(&at_ms)); + let world = WorldHandle::spawn_durable(restored.core, Box::new(Scheduler::default()), None); + assert!(schedule_fires(&world).is_empty(), "not due yet"); + eventually("the scheduled fire", || !schedule_fires(&world).is_empty()).await; + let fires = schedule_fires(&world); + assert_eq!(fires[0]["id"], "later"); + assert!(fires[0].get("late").is_none(), "it was not overdue at open"); + world.shutdown().await.unwrap(); + } + + #[tokio::test] + async fn replay_reproduces_the_pending_and_fired_sets() { + let (world, token, journal) = + scheduling_world("sched-replay", &["schedule.at", "schedule.cancel"], false).await; + ask( + &world, + &token, + serde_json::json!({"requests": [ + {"id": "s1", "cap": "schedule.at", "args": {"id": "keep", "at": unix_ms() + 3_600_000}}, + {"id": "s2", "cap": "schedule.at", "args": {"id": "now", "at": unix_ms()}}, + {"id": "s3", "cap": "schedule.at", "args": {"id": "gone", "at": unix_ms() + 3_600_000}}, + {"id": "c3", "cap": "schedule.cancel", "args": {"id": "gone"}}, + ]}), + ) + .await; + eventually("the fire and the cancel", || { + !schedule_fires(&world).is_empty() && schedule_result(&world, "c3").is_some() + }) + .await; + let live_fired: Vec = schedule_fires(&world) + .iter() + .filter_map(|fire| fire["id"].as_str().map(str::to_owned)) + .collect(); + world.shutdown().await.unwrap(); + + let restored = + WorldCore::restore("sched-replay", WorldLimits::default(), journal.entries()).unwrap(); + let pending: Vec = restored.core.schedules.keys().cloned().collect(); + assert_eq!(pending, ["keep"]); + let replayed_fired: Vec = restored + .replay + .iter() + .filter_map(|event| match &event.kind { + WorldEventKind::System { event } => { + serde_json::from_str::(event) + .ok() + .filter(|value| value["cap"] == "schedule") + .and_then(|value| value["id"].as_str().map(str::to_owned)) + } + _ => None, + }) + .collect(); + assert_eq!(live_fired, ["now"]); + assert_eq!(replayed_fired, live_fired); + } + + #[test] + fn a_checkpoint_keeps_pending_schedules_and_writes_their_entries() { + let now = unix_ms(); + let mut core = world(8); + core.active_module_hash = Some("h".to_owned()); + core.schedules.insert("a".to_owned(), now + 100); + core.schedules.insert("b".to_owned(), now + 200); + let entries = core.checkpoint_entries("state".to_owned()).unwrap(); + for (id, at_ms) in [("a", now + 100), ("b", now + 200)] { + let set = JournalEntry::ScheduleSet { + id: id.to_owned(), + at_ms, + }; + assert!( + entries.contains(&set), + "a compacted journal keeps the schedule {id}" + ); + } + let restored = WorldCore::restore("test-world", WorldLimits::default(), entries).unwrap(); + assert_eq!(restored.core.schedules, core.schedules); + } + + #[test] + fn a_checkpoint_that_disagrees_with_its_schedule_entries_is_refused() { + let header = || JournalEntry::Created { + world_id: "w".to_owned(), + version: JOURNAL_VERSION, + }; + let set = || JournalEntry::ScheduleSet { + id: "a".to_owned(), + at_ms: 5, + }; + let checkpoint = |schedules: Option>| JournalEntry::Checkpoint { + sequence: 0, + module_hash: "h".to_owned(), + seed: 1, + provenance: None, + execution_profile: None, + caps_ceiling: None, + schedules, + snapshot: "s".to_owned(), + events: Vec::new(), + }; + let agreed = [header(), set(), checkpoint(Some(vec![("a".to_owned(), 5)]))]; + assert!(WorldCore::restore("w", WorldLimits::default(), agreed).is_ok()); + let omitted = [header(), set(), checkpoint(None)]; + assert!(WorldCore::restore("w", WorldLimits::default(), omitted).is_err()); + let unwritten = [header(), checkpoint(Some(vec![("a".to_owned(), 5)]))]; + assert!(WorldCore::restore("w", WorldLimits::default(), unwritten).is_err()); + let duplicated = [ + header(), + set(), + checkpoint(Some(vec![("a".to_owned(), 5), ("a".to_owned(), 5)])), + ]; + assert!(WorldCore::restore("w", WorldLimits::default(), duplicated).is_err()); + } + + #[test] + fn a_schedule_entry_must_refer_to_a_pending_schedule() { + let header = || JournalEntry::Created { + world_id: "w".to_owned(), + version: JOURNAL_VERSION, + }; + let fired = [header(), JournalEntry::ScheduleFired { id: "x".to_owned() }]; + assert!(WorldCore::restore("w", WorldLimits::default(), fired).is_err()); + let cancelled = [ + header(), + JournalEntry::ScheduleCancelled { id: "x".to_owned() }, + ]; + assert!(WorldCore::restore("w", WorldLimits::default(), cancelled).is_err()); + let twice = [ + header(), + JournalEntry::ScheduleSet { + id: "x".to_owned(), + at_ms: 1, + }, + JournalEntry::ScheduleSet { + id: "x".to_owned(), + at_ms: 2, + }, + ]; + assert!(WorldCore::restore("w", WorldLimits::default(), twice).is_err()); + let malformed = [ + header(), + JournalEntry::ScheduleSet { + id: "a\nb".to_owned(), + at_ms: 1, + }, + ]; + assert!(WorldCore::restore("w", WorldLimits::default(), malformed).is_err()); + } + + #[test] + fn schedules_wake_the_loop_only_while_the_program_can_take_them() { + let mut schedules = BTreeMap::new(); + schedules.insert("a".to_owned(), 2_000u64); + assert!(next_schedule_wake(&schedules, 1_000, true).is_some()); + assert!( + next_schedule_wake(&schedules, 3_000, true).is_some(), + "an overdue schedule wakes the loop now" + ); + assert!( + next_schedule_wake(&schedules, 3_000, false).is_none(), + "a program that refuses fires never wakes the loop for one" + ); + assert!(next_schedule_wake(&BTreeMap::new(), 1_000, true).is_none()); + } + + #[test] + fn schedule_entries_keep_their_journal_tags() { + let set = serde_json::to_value(JournalEntry::ScheduleSet { + id: "a".to_owned(), + at_ms: 7, + }) + .unwrap(); + assert_eq!( + set, + serde_json::json!({"entry": "schedule_set", "id": "a", "at_ms": 7}) + ); + let cancelled = + serde_json::to_value(JournalEntry::ScheduleCancelled { id: "a".to_owned() }).unwrap(); + assert_eq!(cancelled["entry"], "schedule_cancelled"); + let fired = + serde_json::to_value(JournalEntry::ScheduleFired { id: "a".to_owned() }).unwrap(); + assert_eq!(fired["entry"], "schedule_fired"); + } +} diff --git a/pkgs/id/src/world_caps.rs b/pkgs/id/src/world_caps.rs index 748c921f71..a832ee68e1 100644 --- a/pkgs/id/src/world_caps.rs +++ b/pkgs/id/src/world_caps.rs @@ -3,8 +3,8 @@ //! A program stays a pure function. What it needs from the server is **data //! it returns** (`wants`, a pure projection of its model) and **events it //! receives** (delivered through `update` with participant id `0`, every one -//! journaled before delivery, so replay feeds the program exactly what it saw -//! the first time). +//! journaled once the program accepts it, so replay feeds the program exactly +//! what it saw the first time). //! //! ```json //! {"v":1, @@ -61,6 +61,8 @@ pub const CATALOG: &[&str] = &[ "chat.say", "chat.history", "records.read", + "schedule.at", + "schedule.cancel", "world.info", "Key", "Screen", @@ -73,6 +75,35 @@ pub const CATALOG: &[&str] = &[ /// Most chat lines one `chat.history` request may return. pub const MAX_CHAT_HISTORY_LINES: usize = 64; +/// Most schedules one world may hold pending at once. +pub const MAX_PENDING_SCHEDULES: usize = 64; +/// Longest schedule id, in bytes. Ids are printable ASCII. +pub const MAX_SCHEDULE_ID_BYTES: usize = 64; +/// How far past the host clock a schedule may be set, in days. +pub const MAX_SCHEDULE_HORIZON_DAYS: u64 = 30; +/// How far past the host clock a schedule may be set, in milliseconds. +pub const MAX_SCHEDULE_HORIZON_MS: u64 = MAX_SCHEDULE_HORIZON_DAYS * 24 * 60 * 60 * 1000; +/// Most schedules delivered in one wakeup. Any left due fire on the next. +pub const MAX_SCHEDULE_FIRES_PER_WAKEUP: usize = 64; + +/// Check a schedule id: 1 to [`MAX_SCHEDULE_ID_BYTES`] bytes, all printable +/// ASCII (space through `~`), so no control characters reach the journal. +/// +/// # Errors +/// +/// Names the rule the id breaks. +pub fn validate_schedule_id(id: &str) -> Result<()> { + ensure!( + !id.is_empty() && id.len() <= MAX_SCHEDULE_ID_BYTES, + "schedule id must be 1 to {MAX_SCHEDULE_ID_BYTES} bytes" + ); + ensure!( + id.bytes().all(|byte| (0x20..=0x7e).contains(&byte)), + "schedule id must be printable ASCII" + ); + Ok(()) +} + /// Whether `name` is a capability the server can provide. #[must_use] pub fn is_known(name: &str) -> bool { @@ -660,6 +691,8 @@ mod tests { validate_grant_names(&[ "chat.history".to_owned(), "records.read".to_owned(), + "schedule.at".to_owned(), + "schedule.cancel".to_owned(), "RocJson".to_owned(), "RocGrid".to_owned(), "RocCap".to_owned(), @@ -670,6 +703,24 @@ mod tests { assert!(error.to_string().contains("time.nwo"), "{error}"); } + #[test] + fn schedule_ids_are_bounded_printable_ascii() { + validate_schedule_id("a").unwrap(); + validate_schedule_id("round 3: start!").unwrap(); + validate_schedule_id(&"x".repeat(MAX_SCHEDULE_ID_BYTES)).unwrap(); + let long = "x".repeat(MAX_SCHEDULE_ID_BYTES + 1); + for bad in [ + "", + "a\nb", + "tab\there", + "del\u{7f}", + "caf\u{e9}", + long.as_str(), + ] { + assert!(validate_schedule_id(bad).is_err(), "{bad:?}"); + } + } + #[test] fn result_events_are_bounded_and_carry_codes() { let ok: serde_json::Value = diff --git a/pkgs/id/src/world_compile.rs b/pkgs/id/src/world_compile.rs index 9c1143988c..635a90a674 100644 --- a/pkgs/id/src/world_compile.rs +++ b/pkgs/id/src/world_compile.rs @@ -715,6 +715,91 @@ restore = |text| { session: RocCap.empty, request: text } assert_eq!(decoded_wants["requests"][1]["args"]["count"], 5); } + #[tokio::test] + async fn the_schedule_helpers_build_schedule_requests() { + let Ok(roc_bin) = which_roc() else { + eprintln!("skipping: no roc binary on PATH"); + return; + }; + let Some(platform_dir) = default_platform_dir() else { + eprintln!( + "skipping: no roc-world platform with targets/wasm32/host.wasm (run examples/roc-world/build-host.sh)" + ); + return; + }; + let compiler = Compiler::new(platform_dir, roc_bin).unwrap(); + let app = r#"app [program] { pf: platform "../roc-world/platform.roc" } + +import pf.RocCap +import pf.RocJson + +Model : { documents : List(RocJson) } + +program = { init, update, view, layout, records, wants, snapshot, restore } + +init : U64 -> Model +init = |seed| { + scheduled = RocCap.schedule_at_request("r0", "nap", seed * 1000) + cancelled = RocCap.schedule_cancel_request("r1", "nap") + { documents: [scheduled, cancelled] } +} + +update : Model, U64, Str -> Model +update = |model, _pid, _ev| model + +view : Model -> Str +view = |_model| "" + +layout : Model, U64, U64 -> Str +layout = |model, _width, _height| view(model) + +records : Model -> Str +records = |_model| "{}" + +wants : Model -> Str +wants = |model| { + encoded = List.map(model.documents, |document| match RocJson.encode(document) { + Ok(text) => text + Err(_) => "" + }) + "{\"requests\":[${Str.join_with(encoded, ",")}]}" +} + +snapshot : Model -> Str +snapshot = |_model| "" + +restore : Str -> Model +restore = |_text| { documents: [] } +"#; + let (wasm, _diagnostics, _provenance) = compile( + &CompileSpec { + files: vec![("main.roc".to_owned(), app.to_owned())], + seed: 7, + native: false, + }, + &compiler, + &["RocCap".to_owned(), "RocJson".to_owned()], + COMPILE_TIMEOUT, + ) + .await + .unwrap(); + let runner = + crate::sandbox::Sandbox::compile(&wasm, crate::sandbox::SandboxLimits::default()) + .unwrap(); + let mut world = runner.instantiate(7).unwrap(); + let wants = crate::world::WorldProgram::wants(&mut world) + .unwrap() + .unwrap(); + let decoded: serde_json::Value = serde_json::from_str(&wants).unwrap(); + assert_eq!(decoded["requests"][0]["id"], "r0"); + assert_eq!(decoded["requests"][0]["cap"], "schedule.at"); + assert_eq!(decoded["requests"][0]["args"]["id"], "nap"); + assert_eq!(decoded["requests"][0]["args"]["at"], 7000); + assert_eq!(decoded["requests"][1]["id"], "r1"); + assert_eq!(decoded["requests"][1]["cap"], "schedule.cancel"); + assert_eq!(decoded["requests"][1]["args"]["id"], "nap"); + } + #[test] fn the_platform_modules_are_staged_with_the_platform() { let from = tempfile::tempdir().unwrap(); diff --git a/pkgs/id/src/world_store.rs b/pkgs/id/src/world_store.rs index 939f08d508..3cbac4861e 100644 --- a/pkgs/id/src/world_store.rs +++ b/pkgs/id/src/world_store.rs @@ -1274,6 +1274,7 @@ mod tests { provenance: None, execution_profile: None, caps_ceiling: None, + schedules: None, snapshot: "s".to_owned(), events: Vec::new(), }); @@ -1281,6 +1282,34 @@ mod tests { assert!(error.to_string().contains("checkpoint"), "{error:#}"); } + #[test] + fn schedule_entries_survive_the_file_journal() { + let dir = TempDir::new().unwrap(); + let path = dir.path().join("journal.jsonl"); + let written = [ + JournalEntry::ScheduleSet { + id: "a".to_owned(), + at_ms: 9, + }, + JournalEntry::ScheduleCancelled { id: "a".to_owned() }, + JournalEntry::ScheduleSet { + id: "b".to_owned(), + at_ms: 10, + }, + JournalEntry::ScheduleFired { id: "b".to_owned() }, + ]; + { + // Opening a new journal writes its header first. + let (mut journal, header) = FileJournal::open(&path, "w").unwrap(); + assert_eq!(header.len(), 1); + for entry in &written { + journal.append(entry).unwrap(); + } + } + let (_, reread) = FileJournal::open(&path, "w").unwrap(); + assert_eq!(reread[1..], written); + } + #[cfg(feature = "sandbox")] #[tokio::test] async fn a_missing_module_leaves_chat_working_and_the_program_unavailable() {