Files
Library/docs/roadmap/subsystems/Scheduler.md
T

182 lines
12 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# Scheduler timers, calendar jobs and persistence plan
Status: NEW subsystem; all feature work PLANNED. Baseline:
`f1f9ba375b22abf1adcc7c550ec21ac20895c0a4`, inspected 2026-11-24.
No current Scheduler source directory is part of this baseline. NEW proposed roots:
`include/Void/Scheduler`, `src/Scheduler`, `tests/standalone/Scheduler`.
Requirements R-009, R-011, R-014–R-016 apply. Follow
[architecture](../ARCHITECTURE.md) C-02–C-05, C-08, C-10 and C-12.
## Baseline and subsystem boundary
[Fsm Engine](../../../include/Void/Fsm/Detail/Engine.hpp) already has local timer IDs,
event-wait deadlines and a worker; [Engine.cpp](../../../src/Fsm/Engine.cpp) implements
them. [Async Executor](../../../include/Void/Async/Executor.hpp) provides manual
progress, while [Time Stopwatch](../../../include/Void/Time/Stopwatch.hpp) uses a
steady clock. None supplies durable jobs, calendar recurrence or persisted occurrence
acknowledgement. These paths were coverage-checked and relevant timer/executor source
read directly. [Fsm event](../../../tests/standalone/Fsm/Events.cpp) and
[executor](../../../tests/standalone/Async/Executor.cpp) fixtures are reuse anchors;
there is no existing Scheduler test target.
[Time](../modules/Time.md) owns injected clocks and civil/calendar conversions;
[Async](../modules/Async.md) owns timer-wait completion, scopes and OperationOptions;
[Scheduler](Scheduler.md) owns job definitions, occurrence admission and dispatch;
[Fsm](../modules/Fsm.md) owns workflow execution. Scheduler does not become Async's
timer backend dependency. In-memory scheduling is usable without Storage/Runtime;
durability is an explicit [Storage](Storage.md) adapter, with
[Sqlite](../modules/Sqlite.md) an independently specified optional implementation of
the same persistence port. It is never a hidden substitute for native Storage.
## NEW APIs and recurrence policies
Illustrative contracts, not delivered declarations:
```cpp
namespace Void::Scheduler {
struct OccurrenceId {
JobId job; std::uint64_t revision; std::uint64_t sequence;
};
enum class Misfire { skip, coalesce_latest, catch_up_bounded };
enum class Overlap { forbid, queue_one, allow_bounded };
struct JobSpec {
JobId id; std::uint64_t revision;
Schedule schedule; // once, fixed-delay/rate, calendar
HandlerId handler; std::vector<std::byte> payload;
Misfire misfire; Overlap overlap; RetryPolicy retry;
};
// add(spec, options) -> Task<Result<JobRevision>>;
// remove(job, options) -> Task<Result<void>>;
// handler(OccurrenceId, payload, Async::OperationOptions) -> Task<Result<void>>;
// close_and_join(options) -> Task<Result<ShutdownReport>>;
}
```
Async OperationOptions is the only operation cancellation/deadline type. JobSpec has
separate persistent scheduling/retry policy, not a persisted std::stop_token. Time's
injected clock drives a monotonic min-heap ordered by due time then occurrence sequence.
Callbacks run on the injected executor outside heap/store locks. A root scope owns
all dispatcher/handler children and their shutdown.
One-shot delay uses monotonic time in memory; durable one-shot stores an intended UTC
instant plus its occurrence sequence. Fixed-rate recurrence advances from intended
schedule time, not completion time; fixed-delay advances only after a completion record
commits. Civil schedules store a timezone ID, timezone-data version policy and intended
local slot, with Time resolving it to UTC. Default DST gap policy skips nonexistent
local slots; fold policy chooses the first occurrence only. Explicit twice-fold policy
includes the fold index in the persisted slot identity. Unknown zone or unavailable
required timezone data is a configuration error, never silent UTC fallback.
Initial calendar grammar is five fields (minute/hour/day/month/weekday) with explicit
lists/ranges/steps; day and weekday constraints both apply. This is a documented
cron-like grammar, not a claim of compatibility with every cron implementation.
Seconds, arbitrary scripts and natural-language schedules are later named extensions.
Default misfire coalesces to the latest due occurrence; catch_up_bounded admits at most
100 missed occurrences per job per recovery pass, preserving remaining cursor state.
Default overlap forbids concurrent execution for one job; queue_one retains the latest
pending slot. allow_bounded requires an explicit per-job concurrency cap.
## Durable state machine and at-least-once delivery
Initial persistent mode has one scheduler process owning the store namespace through
an exclusive local ownership lock. A second process fails startup; there is no implied
cross-host lease/election. Job envelopes contain format version, handler identity,
payload schema, revision and recurrence policy. Occurrence records contain ID, intended
slot/UTC time, pending/running/completed/dead status, attempt number, next retry instant
and bounded diagnostic category. Store adapter operations are atomic conditional batches.
1. In one durable batch, create due occurrence records with unique IDs and advance the
job's materialization cursor. Reserve occurrence capacity before moving the cursor.
OccurrenceId sequence is allocated in that transaction; retries retain the same ID.
A unique `(job, revision, civil-slot, fold)` index prevents duplicate materialization
after wall-clock rollback. ID is never generated from current wall time alone.
2. Atomically mark pending → running with attempt identity, then dispatch only after
that record is durably acknowledged. Queue saturation keeps it pending; it does not
falsely mark delivery complete. Handler admission options cover queue wait and run.
3. Handler success writes completed durably before releasing durable occurrence state.
Failure writes a retry/dead transition. Exponential backoff defaults 1 second to
5 minutes, multiplier 2, injected full-jitter RNG, maximum five attempts. Stop during
host shutdown preserves pending/running recovery intent and does not consume a retry
merely because the process is stopping.
4. After crash/restart, running records without a terminal acknowledgement return to
pending with the same OccurrenceId. The handler may already have applied its effect.
This is at-least-once execution, including successful effects whose acknowledgement
was lost. Expose `unknown_outcome` for failed/lost persistence acknowledgement and
inspect before automatic retry when the store outcome is unknown.
Exactly-once external effects are not promised. A handler passes OccurrenceId as an
idempotency key, or atomically commits its application mutation and dedup record in
the same Storage transaction/batch where supported. Network calls/email/process launches
need downstream idempotency or compensation. A scheduler completion record alone cannot
make those effects transactional. Storage mutation and scheduler applied state may share
a batch only through an explicitly supported common-store adapter, never by assuming
two unrelated databases commit atomically.
Editing a job increments revision; old running occurrences retain their handler/payload
snapshot and policy. Default update atomically records an old-revision invalidation
watermark with the new revision. This logically cancels unstarted old occurrences;
bounded background batches reclaim them without exceeding the 1 MiB batch cap. Claim
checks that watermark in the same conditional batch as pending → running, so an edit
cannot race a stale dispatch. Remove records a job tombstone, closes new admission,
requests stop for active handlers and optionally joins; a remove timeout does not claim
active effects were undone. Calendar timezone-data changes require explicit reschedule policy and keep
already materialized slot identities. Large wall-clock jumps trigger bounded rescan;
monotonic handler deadlines do not jump with the civil clock.
## Bounds, shutdown and backend decisions
Defaults: 10,000 job definitions, 100,000 retained occurrence records, 64 KiB payload,
16 MiB aggregate loaded payloads, 256 ready dispatches, 32 active handlers, one active
handler/job, 100 catch-up slots/job/pass, 64 retries processed/turn and 1 MiB durable
batch. Count running records against retention. Completed history retention is seven
days within the count cap; when pending/running state fills the cap, reject new jobs
and pause materialization without advancing cursors. Do not delete unacknowledged work.
Dead records require explicit operator acknowledgement/export before pruning by policy.
Heap entries are lightweight IDs; payloads load under a separate byte budget. Persist
next-due indices to avoid loading the entire store on each tick. Bound per-turn work
and yield to other Async tasks. Errors distinguish invalid rule, unsupported timezone,
overload, persistence failure, unknown outcome, handler failure and cancellation.
Observation hooks report lag, duplicate attempts, retry/dead counts and retention pressure
without labels per arbitrary job ID by default.
Shutdown stops materialization/dispatch, requests handler stop and joins the root scope
before closing persistence. A deadline produces incomplete shutdown with live owner IDs;
it never abandons frames or erases running records. Native heap/calendar composition is
selected over an external scheduling framework. Distributed dispatch is P4 only: a
Coordination/Replication adapter must provide committed ownership epochs/fencing and
deduplication; local lock semantics are not stretched into distributed correctness.
## Ordered implementation backlog
All rows are PLANNED.
| ID | Phase / depends on | Intended scope | Acceptance / recommended role |
| --- | --- | --- | --- |
| S-SCHEDULER-01 | P1 / Async scopes/timers and Time clock gates | In-memory heap, one-shot/fixed schedules, explicit admission and joined handlers | Fake-clock tests prove ordering, overlap bounds and cancellation without sleeps / sol_implementer |
| S-SCHEDULER-02 | P2 / S-SCHEDULER-01; Time calendar gate | Calendar grammar, DST/misfire/catch-up and stable occurrence identities | Gap/fold/backward/forward clock cases yield documented slot IDs with bounded work / sol_implementer |
| S-SCHEDULER-03 | P2 / S-SCHEDULER-02; Storage durable conditional-batch gate | Persistence port, versioned records, exclusive ownership, recovery cursor and attempts | Crash at every acknowledgement boundary neither loses admitted occurrence nor claims exactly-once effects / astra_implementer |
| S-SCHEDULER-04 | P3 / S-SCHEDULER-03; Fsm checkpoint/Runtime gates | Workflow handler adapter, updates/removal, retention and operator inspection | Restart retries same ID; failed revision update leaves old policy intact; cap pauses without cursor loss / astra_implementer |
| S-SCHEDULER-05 | P4 / S-SCHEDULER-04; Coordination/Replication fencing gates | Separate distributed ownership/dispatch adapter | Partitioned former owner cannot commit current ownership work; duplicates remain explicitly deduplicated / astra_implementer |
## Validation, performance and migration
CURRENT aggregate regression command for reused modules:
`ctest --test-dir /tmp/voidlibrary-discovery-f1f9ba3 --output-on-failure --timeout 60`;
not rerun here. PROPOSED Scheduler checks need NEW targets and persistence fixtures:
crash after cursor/claim/effect/completion sync, lost success reply, corrupted record,
disk full, duplicate handler callback, delayed cancellation, full retention, job edit
during running attempt, DST fold/gap, timezone revision, wall-clock reversal, and
coalescing millions of missed slots under the per-pass cap. Use Time injection and
crash subprocesses; do not infer persistence from in-memory tests.
Measure dispatch-lag and durable-admission p50/p95/p99, jobs/second, recovery throughput,
allocations, peak RSS/CPU, store size and build cost under [PERFORMANCE](../PERFORMANCE.md).
No measurements ran here. There is no old Scheduler API to preserve; retain Fsm's
local timer adapters while adopting Async clocks. Persisted formats receive explicit
version readers and offline validate/upgrade tooling before incompatible changes.
Keep original store/checkpoint until upgraded validation succeeds; rollback after new
handler effects follows application idempotency/compensation, not record deletion.
See [MIGRATION](../MIGRATION.md), [VALIDATION](../VALIDATION.md),
[DEPENDENCIES](../DEPENDENCIES.md) and [DELIVERY](../DELIVERY.md).