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;
nextshows 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
- 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.
- Writes to equipment, confirmed, with retries, visible state per target, audit.
- A manual change after a confirmed write wins until the next transition.
- 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). - Zero messages between transitions at idle; one timer for all schedules.
- 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 flowset, 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_scheduletakes the link paramdefault_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 paramdefault_tz(IANA name, defaultUTC). The embedded scheduler gets the system zone fromwyrmd(jiff::tz::TimeZone::system().iana_name(), elseUTC); packages use their params. Zones come from the tz database bundled inwyrm-schedule(jiff,tzdb-bundle-always); a native build may read the host’s newer database first. - Event:
id(stable, generatede<n>, never reused in a schedule),display,value,priority(0–9, integer, validated),special(bool),startandendas local wall-clock date-times in the schedule’s zone (the first occurrence’s window), andrecurrence. - Recurrence: an RRULE subset —
FREQ(HOURLY|DAILY|WEEKLY|MONTHLY|YEARLY),INTERVAL(1 … 1 000),COUNT(≤ 10 000) orUNTIL(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 expandsBYDAYwithin the week (Monday first); MONTHLY expandsBYMONTHDAYandBYDAY(both given: their intersection); YEARLY expandsBYMONTH(default the start’s month), thenBYMONTHDAY/BYDAYwithin each month;BYMONTH(andBYMONTHDAYwith WEEKLY) filter otherwise (ruling R5). At most 100 events per schedule. The caps are constants ofwyrm-schedule, which validates them; the link re-exports them (ruling R1). DSA’sSingle/Hourly/…/Yearlyimport asFREQwithINTERVAL=1. A moment event (DSA “Add Moment Event”) is an event withstart == 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=-1gives 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,
currentkeeps 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_atis the window state only (DefaultorEvent) and never returns a past moment;next_transitionreturns 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 aftertwherestate_atchanges (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 atfromis included (ruling R6).- Bounded work: scanning stops at the horizon of
next_transition(366 days ahead, then “none”).COUNTis 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. ABYDAYordinal is 1…5 (or −1…−5) with MONTHLY and YEARLY: it counts within a month. - Instants are
i64microseconds since the Unix epoch, UTC. The crate reads no clock and no OS zone and builds forwasm32-unknown-unknown.
The link (links/scheduler: an App on the portable API, ADR 0023)
- 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_timerfor the earliest; onon_timer, computestate_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_timeris 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):
startdeclares 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 in0ms timer events. A continuation more than 30 s late counts as a clock step: the link goes tostate_at(now)and does not replay the lag (ruling R11). Writes beyond 50 in flight wait in a FIFO queue drained byon_reply. While schedules are still loading,importand the target actions answerbusy. - 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,enabledturned 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_untilis still ahead is left alone; the others are written: anacktarget at once, aread_back/feedbacktarget 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 carriesvalid_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
goodconfirms nothing and clears the key’s last value, so anokreply 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) andh/<schedule>(the held moment, R17), written bystore_putin the event that accepts the edit, so it is durable before the action replies. Keys at most1 + 2 × schedules + targets: 8 031 within the node budget, below the host’s 10 000. A store that refuses a write fails the action withresource_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 actionconfirmis the enum index (0, 1, 2), in an import the text. - On each transition (and at start), for each enabled target:
~setthe value (mapped ifmap). Confirmation:read_back: the next~valof the same point equals it (numbers withintolerance, default 1e-6 relative);feedback: a~valof another key equals the expected value (feedback_mapmay name it, else the written value) — for devices whose write register is not the one read back (Modbus coil written, status register read);ack: anokreply to the~setis enough (no feedback path). A matching sample counts while the write waits for its reply or after anok; none 10 s after theokfails the write. Links publish a value only when it changes, so a key whose last sample already shows the value confirms on theok. A target holds a subscription on its confirm key while it is enabled, notoverrideand notack; targets that confirm on the same key share one; at most 1 000 subscriptions (an add over that, or one the host refuses, fails withresource_exhaustedor the host’s error).
- Retry until confirmed: exponential backoff 1 s → 60 s cap, jitter ±20 % from an FNV-1a 64 hash of
now_usand the target id, notrand(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
~valon its confirm point that differs from the expected value marks itoverride(the person wins); the link does not write it again until the next transition. Inackmode 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),attemptsare attributes. - Audit (ruling 2): the
HostAPI has no audit call and thewyrm:app@0.1.0WIT stays frozen. Every write is a~set, audited by the target link’s responder (sys/audit/<target link>, subjectlink:<scheduler id>) as any~set. Confirmations and overrides go to the link log atinfo(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_targetcheck the caller’s ownwriteon the target point from the request’sptok. 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_targetsays nothing about the caller’s rights on…/plc/fan. Targets are configuration:add_target, a target’sedit/enable/disable/remove, andimport(it carries targets) areconfigactions, and the responder enforces the level before the app runs. Schedules and events stay atwrite. Who hasconfigon the scheduler may point it at any device the scheduler can reach (embedded: all ofwy/<site>/downstream; packages: their grants). The gateway’soperatorrole haswriteand cannot add targets;engineerandadmincan (ruling R12). The agent link (capped atwrite) and upstream sites (ADR 0018, atwrite) can edit events but cannot add targets. The app does not readWhogrants;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_targetrefuses 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
LimitedKeyatwrite, scoped towy/<site>/downstream, bound to the subjectlink:scheduler; the key is not insys/signing_keys. Package grants (ruling 10): a package carries norequestergrants (a package cannot ask for a root); an operator grantswriteon each target link withsys/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 firsthello(ruling R13); WASM links get it with the router rebuild. Without a grant,add_targetfails withpermission_deniedand no message: the SDK strips the detail of that status (ruling R14). Ruling R21: the embedded scheduler does not trust its own key (its ownLinkConfigleaves 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, soadd_targetcannot refuse such a point; its writes fail withpermission_deniedand 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)
removeof a schedule is atwriteand is refused while the schedule has targets (invalid_parameter, “remove its targets first”; ruling R20): targets are configuration (ruling 6), and awritecaller must not drop them.importwithoverwriteis atconfigalready.- Writable values are only
defaultandenabled, and they are saved.enabledturned on is always a transition: the targets are written even with the same state (ruling R10). Event fields change only throughedit(one validated, saved step; DSA’s unsaved writable fields are not repeated). import {json, id?, overwrite?}: withoutidthe export’s id is used, for a DSA export itsnamewhen that is a valid id, else it is refused (ruling R9). A schedule with that id is refused unlessoverwritereplaces it as a whole. The targets of an own export are checked as byadd_target;created_bybecomes the importer.- Every action validates fully before saving: ids, zone name, RRULE, priority range,
end >= start, window not longer than its period, targets underwy/<site>/downstream/. Errors name the field and the rule. get_eventsuseseditor: 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 atwy/<site>/downstream/scheduler, started with the router like the storage link, grants and key fromwyrmd(ADR 0023, embedded built-in apps); not an operator-created driver instance. Ruling 9:schedulerjoins the reserved ids of new links, andDaemon::openrefuses a stored link with it, as withstorage; it is not insys/links(not a registry link) but is in the broker’s overlays (publish_overlays), so history marks show on its nodes.wyrmd.json5scheduler: { enabled: true, store_mb: 64 }(both optional) turns it off or sizes its store;peers.downstreamcannot name a sitescheduler. Ruling R22: when the admin cannot save the scheduler’s keys (ensure_builtin_keys), it logs that aterrorand 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 bywyr link pack --kind process --name scheduler-process(ADR 0021);wyrmd link schedulerruns the same app as a process link. Norequestergrants: an operator grants each target link (ruling 10). - WASM package
scheduler— the sameAppbuilt with--features wasmon worldwyrm:app/app, store 16 MiB (capabilities); targets work as in the other modes (requests within its grants). Thewyrm-schedulecrate builds forwasm32-unknown-unknown(no std time; tz data compiled in).examples/packages/build.shpacks 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;
BYDAYordinals; three or more overlaps; special days; DST spring-forward and fall-back inEurope/KyivandAmerica/New_York(window boundaries, the missing and the repeated hour); clock step forward and backward.next_transitionagrees withstate_atsampled every 5 minutes. cargo bench -p wyrm-schedule --bench eval(Apple M4 Max, release), per call:state_atp50 0.21 µs (E = 1), 5.5 µs (E = 10), 53.7 µs (E = 100);next_transitionp50 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.occurrencesover a year, 10 events (7 198 rows): p50 0.83 ms. WorstCOUNTcompile (100 events whose rule never matches): 17–84 ms.cargo bench -p wyrm-link-scheduler --bench cold_start: the link’s cold start onSimHost, 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 ofScheduler::start, p50 / max:ack—startevent 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:startanswered 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 (acktarget): p50 16.9 ms, p99 24.8 ms, max 27.6 ms; - a target on the Modbus simulator (
plc1/line1/ahu1/fan) withfeedbackonfan_status:confirmedafter 390 ms,override973 ms after a manual write offalse, writtentrueagain andconfirmedat the next transition.
Left to the builder (as built)
- Crate layout:
crates/wyrm-schedule(model,rrule,occur,eval,convert,dsa) andlinks/scheduler(lib(schedules, events, the wake loop),targets,tree,store,wake,limits: the link’s constants, one place each). The tz library isjiffwith 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,freq0 … 5 → once orFREQwithINTERVAL=1andUNTIL= the date ofeDatewith the time ofsTime; instants withZor an offset are converted todefault_tz.
Consequences
- The link id
scheduleris reserved likestorage. - Spec 02 does not change (only existing editors and value types are used).
- Built-in probe scenario
links/probe/scenarios/scheduler.json; user guidedocs/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);
rustlsis pinned to=0.23.45:zenoh-link-tls1.10.1 gives its reader and writer oneTlsStream, 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).