Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

ADR 0022 — Scheduler link: broker-side schedules that drive equipment

Status: accepted · 2026-10-29, built (proposed 2026-10-28; owner decisions in that conversation: the link writes to equipment itself, retries until confirmed, respects a manual change until the next transition; confirmation may come from another data path). Built as a portable App (ADR 0023): crates/wyrm-schedule, links/scheduler; user guide docs/scheduler.md. The text below states the behaviour as built: where the build differs from the proposal, the plan’s rulings (numbered, from the plan docs/superpowers/plans/2026-10-29-scheduler-link.md) say why.

Context

The owner needs a scheduler that controls equipment from the broker when the site has no connection upstream: people (explorer) and AI (the agent link, through actions) create schedules; the broker turns devices on and off by them, offline, for months. Dataflows may edit schedules later; that needs other changes and is not part of this work.

The reference is DSA dslink-dart-localschedule (2.0.4, analysed 2026-10-28). Kept: a schedule with a default value and events; event priority 1 (highest) … 9, 0 = none; special days that block other events; Add/Edit/Remove/Import/Export; current, next value and time. Not kept, because they are its defects:

  • windows across midnight, the hour or the week wrap break after the first occurrence; day 29–31 and Feb 29 roll over into the next month;
  • edits through writable child nodes are not saved; a restart loses them;
  • next shows the next event start, not the next transition (a return to default is missed);
  • timers do not follow wall-clock steps; DST shifts window ends; time zone = host zone, stored times have no offset;
  • a 1 Hz countdown node per schedule (N updates per second at idle);
  • restart and import are O(n² log n); the whole state file is rewritten on every edit;
  • it never writes to equipment (consumers bind its value).

Goals

  1. Correct state at any instant, from the definition alone: after a restart, a power cut or a clock step the link computes “now” and acts; it does not replay missed transitions.
  2. Writes to equipment, confirmed, with retries, visible state per target, audit.
  3. A manual change after a confirmed write wins until the next transition.
  4. An action API people and AI can use safely: validated parameters, stable ids, errors that say what is wrong, a preview of what will happen (get_events).
  5. Zero messages between transitions at idle; one timer for all schedules.
  6. One evaluation core for every way the link runs.

Non-goals

  • iCal/Outlook/Google import or remote calendars (not how schedules arrive).
  • Dataflows editing schedules (later, separate change).
  • Targets on other sites or under sys/** (no upstream needed offline; same rule as flow set, owner decision 8).

Anti-goals (a failure even if it works)

  • A missed or wrong transition after a restart, a clock step or a DST change.
  • An edit accepted but not on disk.
  • Fighting a person who changed a device by hand.
  • Load at idle that grows with the number of schedules.

Decision

Model (crate wyrm-schedule, no I/O, no async)

  • Schedule: id (key segment), display, tz (IANA name, stored explicitly; without one, add_schedule takes the link param default_tz), default (Value), events, targets, enabled.
  • Default zone (ruling 3): a WASM app cannot read the host’s zone, so the zone of a schedule added without tz (and of a DSA import) is the app param default_tz (IANA name, default UTC). The embedded scheduler gets the system zone from wyrmd (jiff::tz::TimeZone::system().iana_name(), else UTC); packages use their params. Zones come from the tz database bundled in wyrm-schedule (jiff, tzdb-bundle-always); a native build may read the host’s newer database first.
  • Event: id (stable, generated e<n>, never reused in a schedule), display, value, priority (0–9, integer, validated), special (bool), start and end as local wall-clock date-times in the schedule’s zone (the first occurrence’s window), and recurrence.
  • Recurrence: an RRULE subset — FREQ (HOURLY|DAILY|WEEKLY|MONTHLY|YEARLY), INTERVAL (1 … 1 000), COUNT (≤ 10 000) or UNTIL (a local time; not both), BYDAY (weekdays; with MONTHLY and YEARLY an ordinal within the month, e.g. 1MO, -1FR), BYMONTHDAY (1…31, −1 = last), BYMONTH. None = one-off. Canonical text order: FREQ, INTERVAL, COUNT|UNTIL, BYMONTH, BYMONTHDAY, BYDAY. BY* parts: with HOURLY and DAILY they filter; WEEKLY expands BYDAY within the week (Monday first); MONTHLY expands BYMONTHDAY and BYDAY (both given: their intersection); YEARLY expands BYMONTH (default the start’s month), then BYMONTHDAY/BYDAY within each month; BYMONTH (and BYMONTHDAY with WEEKLY) filter otherwise (ruling R5). At most 100 events per schedule. The caps are constants of wyrm-schedule, which validates them; the link re-exports them (ruling R1). DSA’s Single/Hourly/…/Yearly import as FREQ with INTERVAL=1. A moment event (DSA “Add Moment Event”) is an event with start == end: the value is written once at that instant; there is no window and no return to default from it.
  • Occurrence arithmetic is in local wall time, then mapped to UTC: each occurrence’s start and end are computed as local date-times (day 31 in a month without it is skipped, not rolled over; BYMONTHDAY=-1 gives the last day), then each end of the window is mapped to an instant with the zone’s rules. A local time in the spring-forward gap moves to the first instant after the gap; in the fall-back overlap it takes the first (earlier) instant. Windows keep their wall-clock length (08:00–17:00 stays 08:00–17:00 on a DST day). A window may cross midnight or the period boundary.
  • Moment events obey the same precedence: a moment fires (writes its value) only if no window of higher precedence is active at that instant; after it, current keeps the moment’s value (source: Moment(id, t)) until the next transition. A moment missed while the link was down is not replayed (goal 1). Ruling 8: state_at is the window state only (Default or Event) and never returns a past moment; next_transition returns moments as transitions (Source::Moment); the link holds a moment’s state until the next transition. Ruling R17: that held moment survives a restart: the link keeps it in the store (h/<s>, put in the transition event, deleted when the next transition replaces it) and a loaded schedule is evaluated with it (the moment while it is still the state, else the window state). This is not a replay: a moment missed while the link was down still does not fire.
  • Precedence at an instant: if any special event has an occurrence that touches that local day, only special events count for the whole local day (midnight to midnight in the schedule’s zone; this is the DSA promise, which DSA did not keep). Among active events: higher priority wins (1 > 2 > … > 9 > 0); on equal priority, the later-starting occurrence wins; on equal start, the lower event id wins. No active event → default. The result is defined for any number of overlaps.
  • Core API:
    • state_at(def, t) -> State { value, source: Default | Event(id, occurrence_start) | Moment(id, at) }
    • next_transition(def, t) -> Option<(Instant, State)> — the first instant after t where state_at changes (an event start, an event end, a day boundary under a special day, a moment).
    • occurrences(def, from, to, limit) -> Vec<Occurrence> for the timeline: every event’s occurrences that touch the range, precedence not applied; a moment exactly at from is included (ruling R6).
    • Bounded work: scanning stops at the horizon of next_transition (366 days ahead, then “none”). COUNT is resolved once, when a schedule is compiled, and walks at most 400 years. Ruling R18: for an enabled schedule with “none”, the link wakes again 365 days on and evaluates it, so a transition further ahead still fires.
    • Values (the default, event values, a target’s map/feedback_map) hold finite numbers only: NaN and ±infinity are refused, also inside arrays and maps. A BYDAY ordinal is 1…5 (or −1…−5) with MONTHLY and YEARLY: it counts within a month.
    • Instants are i64 microseconds since the Unix epoch, UTC. The crate reads no clock and no OS zone and builds for wasm32-unknown-unknown.
  • One timer for all schedules: a min-heap of each schedule’s next transition, and of the targets’ retries and confirm timeouts (no timer per target); one Host::set_timer for the earliest; on on_timer, compute state_at(now) for due schedules, write their targets, arm the next.
  • Wall-clock steps: the one timer fires at least every 30 s and compares now_us (wall clock) with the elapsed monotonic time (set_timer is monotonic, ADR 0023); a step of more than 2 s (either way) re-evaluates every schedule at “now” and rebuilds the heap (retries and confirm timeouts are put back). This also covers a host resumed from sleep. Every event (also an action, a value, a reply) checks the clock before it arms the timer, so a backward step seen there is not lost.
  • Host bounds (ruling 5): the host allows 1 000 commands per event and fails the event (and restarts the instance) over that. Every event of the app spends at most 800 commands and at most 500 ms of wall time on batched work (ruling R7): start declares the root and loads the definitions, then declares and evaluates schedules in batches; a timer burst handles due wakes in batches; leftover work goes on in 0 ms timer events. A continuation more than 30 s late counts as a clock step: the link goes to state_at(now) and does not replay the lag (ruling R11). Writes beyond 50 in flight wait in a FIFO queue drained by on_reply. While schedules are still loading, import and the target actions answer busy.
  • Node budget (ruling 1, R8): the host bounds a link at 10 000 nodes; the app counts its nodes and refuses an add over 9 500 with resource_exhausted, so the host never fails the event. A schedule takes 6 nodes (the folder, current, default, enabled, events, targets), plus one per event and one per target: 1 000 schedules × 2 events × 1 target = 9 000.
  • What a transition is: a change of state_at (value or source occurrence), an edit or import that changes the current state, enabled turned on, or a change of a target. A re-evaluation after a clock step that finds the same state is not a transition.
  • Restart: load, evaluate every schedule at “now” (with its held moment, R17). A target whose stored record says it was confirmed or overridden for this same state (value and source occurrence) and whose valid_until is still ahead is left alone; the others are written: an ack target at once, a read_back/feedback target after it waits 2 s for a first sample of its confirm key (a sample that already shows the value confirms without a write). So a manual change survives a restart inside the same window. Ruling R19: a record carries valid_until, the instant of the next transition after its state (the R18 re-check when there is none); a record at or past it is stale, so an outage across a whole window does not keep an override of the state before it. An edit, a clock step or the re-check that moves the next transition puts the records again. A record without the field (an older store) is stale.
  • Bad samples: a sample that is not good confirms nothing and clears the key’s last value, so an ok reply cannot confirm on a value from before it.
  • Persistence: the host store (ADR 0023): index (the schedule ids: the store has no key listing), s/<schedule> (the definition with its targets), o/<schedule>/<target> (the last outcome (state it was for, confirmed | override, valid_until), kept only for those two) and h/<schedule> (the held moment, R17), written by store_put in the event that accepts the edit, so it is durable before the action replies. Keys at most 1 + 2 × schedules + targets: 8 031 within the node budget, below the host’s 10 000. A store that refuses a write fails the action with resource_exhausted; nothing is half-saved or declared, and the instance goes on. Embedded store 64 MiB (scheduler.store_mb), packages 16 MiB (capabilities).

Targets: writes, confirmation, override

  • A target is { point: <key under wy/<site>/downstream/>, confirm: read_back | feedback | ack, feedback?: <key>, map?: {<schedule value>: <value to write>}, feedback_map?: {<schedule value>: <value the feedback key shows>}, tolerance? }. At most 20 targets per schedule. Map keys are the schedule value as text (true, false, a number in its shortest decimal, text as it is). Through an action confirm is the enum index (0, 1, 2), in an import the text.
  • On each transition (and at start), for each enabled target: ~set the value (mapped if map). Confirmation:
    • read_back: the next ~val of the same point equals it (numbers within tolerance, default 1e-6 relative);
    • feedback: a ~val of another key equals the expected value (feedback_map may name it, else the written value) — for devices whose write register is not the one read back (Modbus coil written, status register read);
    • ack: an ok reply to the ~set is enough (no feedback path). A matching sample counts while the write waits for its reply or after an ok; none 10 s after the ok fails the write. Links publish a value only when it changes, so a key whose last sample already shows the value confirms on the ok. A target holds a subscription on its confirm key while it is enabled, not override and not ack; targets that confirm on the same key share one; at most 1 000 subscriptions (an add over that, or one the host refuses, fails with resource_exhausted or the host’s error).
  • Retry until confirmed: exponential backoff 1 s → 60 s cap, jitter ±20 % from an FNV-1a 64 hash of now_us and the target id, not rand (ruling 4); never gives up within a transition; a newer transition cancels it. Each transition gives the target a new generation: replies and wakes of an older one are ignored, and a target has one write in flight at most.
  • Override: after a target is confirmed, a ~val on its confirm point that differs from the expected value marks it override (the person wins); the link does not write it again until the next transition. In ack mode there is no feedback, so no override is detected.
  • Per-target state in the tree: the target node’s value is its state, pending | writing | confirmed | retrying | override | disabled; last_error, last_write (time), attempts are attributes.
  • Audit (ruling 2): the Host API has no audit call and the wyrm:app@0.1.0 WIT stays frozen. Every write is a ~set, audited by the target link’s responder (sys/audit/<target link>, subject link:<scheduler id>) as any ~set. Confirmations and overrides go to the link log at info (ids and states only, never values) and to the target node.
  • Who may point a schedule at a device (ruling 6; an owner decision, the plan’s default): the proposal had add_target check the caller’s own write on the target point from the request’s ptok. That is not possible: every token carries one grant, narrowed to the request key (wyrm_client::SigningTokens::scoped, also used by the gateway), so a request to …/scheduler/s1/~act/add_target says nothing about the caller’s rights on …/plc/fan. Targets are configuration: add_target, a target’s edit/enable/disable/remove, and import (it carries targets) are config actions, and the responder enforces the level before the app runs. Schedules and events stay at write. Who has config on the scheduler may point it at any device the scheduler can reach (embedded: all of wy/<site>/downstream; packages: their grants). The gateway’s operator role has write and cannot add targets; engineer and admin can (ruling R12). The agent link (capped at write) and upstream sites (ADR 0018, at write) can edit events but cannot add targets. The app does not read Who grants; created_by = who.subject. As with flows (decided 2026-10-21), a schedule keeps writing after its author loses rights. Amended 2026-10-31 (ADR 0029, decision 10): spec 04 0.2.10 added that claim (auth); a target now also keeps its author’s rights and writes only within them (checked when it is defined and before each write).
  • Site check (ruling 7): the app does not know its site; the host refuses a key outside the link’s site (or grants) at subscribe/set. add_target (and an import with targets) subscribes the point and the feedback key inside the action: an error refuses the target with that error, and nothing stays subscribed. The app itself checks the key’s shape (wy/<site>/downstream/<link>/<path>, no *, ~ or empty segment).
  • One writer per point: a point may be the target of one schedule only; add_target refuses a point another target of this link already writes (two schedules would see each other’s writes as overrides). A flow that also writes the point is not detected, nor a feedback key that is another target’s point; the guide says not to.
  • Rights of the writes: the embedded link signs its writes with its own key, created as a link secret by the admin (as the agent’s); links trust it as a LimitedKey at write, scoped to wy/<site>/downstream, bound to the subject link:scheduler; the key is not in sys/signing_keys. Package grants (ruling 10): a package carries no requester grants (a package cannot ask for a root); an operator grants write on each target link with sys/links/<id>/~act/grant (ADR 0013). A grant that changes restarts a running process link, because grants and the requester key reach a process only in its first hello (ruling R13); WASM links get it with the router rebuild. Without a grant, add_target fails with permission_denied and no message: the SDK strips the detail of that status (ruling R14). Ruling R21: the embedded scheduler does not trust its own key (its own LinkConfig leaves it out), so a schedule cannot write the scheduler’s own nodes in a loop. The app does not know its own link id or root, so add_target cannot refuse such a point; its writes fail with permission_denied and retry (the guide says not to). A package scheduler still trusts its own requester key under its grants, so a grant that covers its own link (an operator step) would let it write itself.

Tree and actions (all actions at write except where noted; ids are key segments)

Ruling 1 and R8: the proposal’s tree took 9+ nodes per schedule, so 1 000 schedules (this ADR’s benchmark) did not fit the host’s 10 000 nodes; and a value node cannot have children (spec 02: type only on leaves). So the schedule is a folder with attributes, and its value is the leaf current; an event is one node with its fields as attributes; a target is one node whose value is its state.

<link>/
  add_schedule {id, display?, tz?, default, enabled?}
  import {json, id?, overwrite?}  (config) -> {id}   # DSA localschedule JSON or this link's own export (ruling R9)
  <schedule>/                     folder; attrs display, tz, source (default | <event id>),
                                  next_time (RFC 3339 instant | null), next_value
    current                       the value now (read-only)
    default                       writable value; saved
    enabled                       writable bool; saved
    add_event {display?, value, start, end, recurrence?, priority?, special?}   -> {id}
    add_target {point, confirm, feedback?, map?, feedback_map?, tolerance?}  (config) -> {id}
    get_events {timerange, limit?}  (read)   -> rows {start, end, event, value, priority, special}
    export (read) -> {json}; edit {display?, tz?, default?}; remove
    events/<e>                    folder; attrs display, value, start, end, recurrence, priority, special;
                                  edit {…}, remove
    targets/<t>                   the state; attrs point, confirm, feedback, last_error, last_write,
                                  attempts, created_by; edit {…}, enable, disable, remove  (config)
  • remove of a schedule is at write and is refused while the schedule has targets (invalid_parameter, “remove its targets first”; ruling R20): targets are configuration (ruling 6), and a write caller must not drop them. import with overwrite is at config already.
  • Writable values are only default and enabled, and they are saved. enabled turned on is always a transition: the targets are written even with the same state (ruling R10). Event fields change only through edit (one validated, saved step; DSA’s unsaved writable fields are not repeated).
  • import {json, id?, overwrite?}: without id the export’s id is used, for a DSA export its name when that is a valid id, else it is refused (ruling R9). A schedule with that id is refused unless overwrite replaces it as a whole. The targets of an own export are checked as by add_target; created_by becomes the importer.
  • Every action validates fully before saving: ids, zone name, RRULE, priority range, end >= start, window not longer than its period, targets under wy/<site>/downstream/. Errors name the field and the rule.
  • get_events uses editor: daterange (spec 02 0.2.4).

Run modes (one core, three hosts)

One source, three hosts (ADR 0023):

  • Embedded in wyrmd — the default: one fixed instance at wy/<site>/downstream/scheduler, started with the router like the storage link, grants and key from wyrmd (ADR 0023, embedded built-in apps); not an operator-created driver instance. Ruling 9: scheduler joins the reserved ids of new links, and Daemon::open refuses a stored link with it, as with storage; it is not in sys/links (not a registry link) but is in the broker’s overlays (publish_overlays), so history marks show on its nodes. wyrmd.json5 scheduler: { enabled: true, store_mb: 64 } (both optional) turns it off or sizes its store; peers.downstream cannot name a site scheduler. Ruling R22: when the admin cannot save the scheduler’s keys (ensure_builtin_keys), it logs that at error and the broker runs without the scheduler; the broker start does not fail. The next router build tries again.
  • Process package scheduler-process — process::main::<Portable<Scheduler>>() (--features process), packed by wyr link pack --kind process --name scheduler-process (ADR 0021); wyrmd link scheduler runs the same app as a process link. No requester grants: an operator grants each target link (ruling 10).
  • WASM package scheduler — the same App built with --features wasm on world wyrm:app/app, store 16 MiB (capabilities); targets work as in the other modes (requests within its grants). The wyrm-schedule crate builds for wasm32-unknown-unknown (no std time; tz data compiled in). examples/packages/build.sh packs both packages.

Benchmarks and tests (in the crate and on the demo)

  • Correctness fixtures: windows across midnight, the hour, the week wrap; day 31 and Feb 29; BYDAY ordinals; three or more overlaps; special days; DST spring-forward and fall-back in Europe/Kyiv and America/New_York (window boundaries, the missing and the repeated hour); clock step forward and backward. next_transition agrees with state_at sampled every 5 minutes.
  • cargo bench -p wyrm-schedule --bench eval (Apple M4 Max, release), per call: state_at p50 0.21 µs (E = 1), 5.5 µs (E = 10), 53.7 µs (E = 100); next_transition p50 0.62–0.67 µs, 11.6 µs, 113 µs, the same for S ∈ {1, 10, 100, 1000}. E = 1000 is not measured: at most 100 events per schedule. Cold start of the evaluator (Compiled::new + state_at), 1 000 schedules × 10 events: p50 8.96 ms. occurrences over a year, 10 events (7 198 rows): p50 0.83 ms. Worst COUNT compile (100 events whose rule never matches): 17–84 ms.
  • cargo bench -p wyrm-link-scheduler --bench cold_start: the link’s cold start on SimHost, 1 000 schedules × 2 events × 1 target (9 000 nodes; the node budget forbids 10 events each at this size, ruling R3), 10 rounds, from the start of Scheduler::start, p50 / max: ack — start event 1.71 / 1.94 ms, tree complete 26.22 / 29.96 ms, last write sent 40.34 / 45.50 ms, all confirmed 40.85 / 46.03 ms; read_back — 1.67 / 1.76 ms, 25.84 / 26.53 ms, 44.27 / 45.02 ms, 44.92 / 45.74 ms, plus on a real host the 2 000 ms first-sample wait before the writes.
  • WASM package (e2e scheduler_three_modes), 200 schedules × 10 events × 1 target: start answered in 0.29 s, all 200 back in the tree in 1.7 s.
  • On the demo (examples/demo/scheduler-load.sh; Apple M4 Max, demo edge site, embedded scheduler, release build, 2026-10-29; ruling R4: measured by the controller):
    • idle samples in 60 s with 1 000 schedules: 0 (target 0 between transitions; 3 000 stored values at subscribe); the 1 000 schedules were made in 47.1 s and removed in 42.8 s (50 requests per second per caller);
    • transition latency of 100 moments, current: p50 16.0 ms, p99 23.7 ms, max 26.7 ms (target < 50 ms embedded); at the written mock point (ack target): p50 16.9 ms, p99 24.8 ms, max 27.6 ms;
    • a target on the Modbus simulator (plc1/line1/ahu1/fan) with feedback on fan_status: confirmed after 390 ms, override 973 ms after a manual write of false, written true again and confirmed at the next transition.

Left to the builder (as built)

  • Crate layout: crates/wyrm-schedule (model, rrule, occur, eval, convert, dsa) and links/scheduler (lib (schedules, events, the wake loop), targets, tree, store, wake, limits: the link’s constants, one place each). The tz library is jiff with its bundled database.
  • The own export format is wyrm-schedule/1: {format, id, display, tz, default, enabled, next_event, events: [{id, display, value, priority, special, start, end, recurrence?}], targets: [{id, point, confirm, feedback?, map?, feedback_map?, tolerance?, enabled, created_by}], next_target}. It round-trips.
  • DSA import: name → display (and the id), value → default, timeRange.sDate + sTime → start, eTime − sTime → the window length, freq 0 … 5 → once or FREQ with INTERVAL=1 and UNTIL = the date of eDate with the time of sTime; instants with Z or an offset are converted to default_tz.

Consequences

  • The link id scheduler is reserved like storage.
  • Spec 02 does not change (only existing editors and value types are used).
  • Built-in probe scenario links/probe/scenarios/scheduler.json; user guide docs/scheduler.md.
  • Open items:
    • an audit record put while the target link reconnects (a router rebuild) can be lost: records are sent once; a fix needs ack and resend (spec 01/04; owner decision);
    • rustls is pinned to =0.23.45: zenoh-link-tls 1.10.1 gives its reader and writer one TlsStream, and 0.23.46 crashes on it (ruling R16); the durable fix is upstream Zenoh or process links on QUIC (owner decision);
    • a forward clock step under 30 s while a long burst still runs replays the transitions of that span (moments too) instead of skipping them; a step over 30 s is caught;
    • targets as configuration (ruling 6), within their author’s rights since ADR 0029 (decision 10).