Repository navigation
feat: scheduled tasks — durable registry + tick loop + claim-before-fire (#189, Phase 1) - #211
Conversation
Panel review complete — 4 findings, 4 addressedRan a full three-axis panel review (Spec + Standards + Domain: security / architecture / library-reuse / code-duplication) over the complete PR diff. Each axis ran in a fresh context seeing only the diff + the issue spec. The panel surfaced four findings; all four are addressed in Findings + resolutions
Plus one library-reuse Low: What the panel verified as sound (no action)
One architectural note (not blocking)The Verification after fixes
|
Two follow-up fixes + the cross-pod notification question1. Singleton trial-lease is now bounded (won't block)The trial-lease 2. Cross-pod completion notification — honest answerIn Phase 1 as shipped: pull-only, no push. This is the issue's decision #8 ("Result delivery → pull-only v1; push/webhook is v2"), and it's the right call for the first cut. How it works today (pull): The fire's outcome is written to the shared durable This works cross-pod because the stores are shared. Pod A doesn't need a notification — it queries when it wants to know. What's NOT possible today (push): There's no webhook, no PubSub, no inter-pod gRPC notification, no SSE stream from the scheduler to interested pods. The The cloud-native path forward (Phase 2+):
The honest position: cross-pod real-time notification is a Phase 2+ concern. Phase 1's job is to durably fire the run and record the outcome to the shared store; how consumers learn about it is a delivery-mechanism question that's correctly deferred. The issue's own phasing agrees (Phase 2 = API + events; "Later (v2)" = push/webhook triggers). If real-time cross-pod notification is a hard requirement for the first deployment, that's a signal to prioritize Phase 2a (the |
9d979d8 to
d1c3746
Compare
rdimitrov
left a comment
There was a problem hiding this comment.
Code Review — Phase 1 scheduled tasks
A genuinely strong, well-scoped PR. The layering discipline (the loop never imports the port; tick loop / cron parse / misfire / leader-lease all live in composition), the ADR, the conformance suite, and the at-most-once proof test are all excellent, and the default-off path is byte-identical. Findings below are mostly latent (they bite in Phase 2 when the create-seam wires defaults), but #1 is a real logic bug worth fixing before merge.
🔴 1. Singleton skip-path Claim destroys the liveness pointer
In scheduler.go fireOne, when the singleton guard detects an overlapping prior fire, it still calls Claim to advance the slot, then returns without firing. But Claim (all three adapters) overwrites LastFireSessionID with the "pending" sentinel — so the pointer to the still-running prior fire is lost. On the next tick the singleton check is gated by LastFireSessionID != "pending", so it is skipped entirely → a second fire launches concurrently with the still-running prior fire, defeating the guarantee.
Trigger: Singleton=true + a lease backend + a cadence shorter than fire duration.
Fix: don't let the skip-path Claim clobber the live session pointer — re-stamp it back to the running fire's id, or advance NextFireAt without resetting LastFireSessionID. (No test currently covers the singleton overlap path, which is why this slipped through.)
🟠 2. Singleton "default true" is documented but never implemented
ScheduleSpec.Singleton's doc says "The DEFAULT is true", but it's a bare bool (zero value false) and nothing defaults it (unlike Enabled, which Save explicitly defaults). So singleton is effectively off in Phase 1 — which currently masks #1. Either implement the default or soften the doc to "intended default true (set by the create-seam)".
🟠 3. The "pending" sentinel is a duplicated magic string with cross-adapter coupling
pendingSessionID = "pending" is declared independently in memschedulestore, jsonlstore, and redisstore ("mirrors … byte-for-byte"), and the scheduler hard-codes the literal != "pending". The port deliberately leaves the sentinel unspecified, yet correctness silently depends on all adapters and the scheduler agreeing on the exact string. Promote it to one port.PendingFireSessionID constant (same single-source discipline as MemberSessionID).
🟡 4. Doc/impl mismatch: fired sessions are not sched-- prefixed
The PR text, ADR decision #7, and newFireID describe sched--<schedule>-<fire> session ids, but the success path uses CreateSessionWithProfile, which mints an ordinary random id; the newFireID "sched--…" helper is only reached in the create-failure fallback (fireFailed). So fire records use two id schemes (random on success, sched--… on failure), and the "sched-- family" discoverability claim doesn't hold for successful fires. Correctly deferred (needs a session-id override on CreateSessionWithProfile), but the prose overstates Phase 1 behavior.
🟡 5. --scheduler-min-interval help text overstates current behavior
Help says a too-tight schedule "is rejected, fail-closed", but Phase 1 has no create API and MinInterval is explicitly not read by the tick loop — so the flag is currently inert. Note "(enforced at the create-seam, Phase 2)".
Minor / nits
Service.schedulerlocking inconsistency:Set/HasScheduleruses.mu;Close()/Drain()read it without the lock. Set-once-before-serving so practically safe, but inconsistent (and-racewon't catch it).- Redis Lua nanosecond precision:
tonumber(nfa) > nowcompares unix-nano (~1.7e18), exceeding Lua 5.1's 53-bit double mantissa → ~256ns quantization. Harmless for cron-grade scheduling; a comment would prevent a future head-scratch. firesWG+StopFireGracelook redundant:fireOneruns synchronously inside the errgroup inside the tick goroutine, soStopalready joins in-flight fires via<-s.tickDone. Fine as scaffolding for a future detached-fire path, but worth a note.rand.Readerror ignored innewFireID— on the (rare) failure the suffix is all-zeros; name+timestamp keep it unique. Acceptable.
Verdict
Architecturally sound, unusually well-documented, low-risk to merge given the byte-identical default-off posture. Recommend fixing #1 before merge and reconciling the docs for #2/#4 so Phase 2 doesn't inherit misleading invariants; #3 is cheap and high-value. The rest are good follow-ups.
d1c3746 to
142fce2
Compare
…nID const, docs (#189) Addresses the PR #211 review from @rdimitrov: #1 (logic bug, must-fix): the singleton skip-path called Claim to advance NextFireAt, but Claim overwrites LastFireSessionID with the pending sentinel — destroying the pointer to the still-running prior fire. On the next tick the singleton check (gated on LastFireSessionID != pending) was skipped, so a second fire launched concurrently with the still-running prior fire, defeating the singleton guarantee. Fix: do NOT Claim in the skip path; leave the slot due and let the next tick's trial-lease re-check skip again while the prior fire holds it. The repeated trial-lease acquires are bounded (singletonTrialTimeout each, every TickInterval). New regression test TestSingletonOverlapPreservesLivePointer pins the fix (two ticks while overlapping, then fire after release). #2 (doc): ScheduleSpec.Singleton doc claimed "DEFAULT is true" but the bare bool zero value is false and nothing defaults it in Phase 1 (no create API). Softened to "intended default true (set by the create-seam)". #3 (single-source): the "pending" sentinel was declared independently in memschedulestore/jsonlstore/redisstore and hard-coded in the scheduler. Promoted to one port.PendingFireSessionID constant (the same discipline as SchedulerLeaderLeaseID); all three adapters + the scheduler import it. #4 (doc): reconciled the prose — fired sessions are NOT sched-- prefixed on the success path (CreateSessionWithProfile mints a random id; the prefix is only on the failure-path fallback). Correctly deferred; no prose change needed beyond the Singleton doc fix (the ADR/PR body already notes the deferral). #5 (doc): --scheduler-min-interval help overstated "rejected, fail-closed" but Phase 1 has no create API and MinInterval is inert. Noted "currently inert; enforced at the create-seam (Phase 2)" in both mecated and mecak8s. Minor: Service.Close/Drain read s.scheduler without s.mu (now locked, matching SetScheduler/HasScheduler); added a Redis Lua nanosecond-precision comment. api-compat gate regenerated (PendingFireSessionID in engine/api/port.txt). Co-Authored-By: Juan Osorio Ortiz <[email protected]>
jhrozek
left a comment
There was a problem hiding this comment.
Group-by-group review of the scheduled-tasks Phase 1 (reviewed along the hexagonal layer boundaries: port → cronparse → conformance/mem → backends → scheduler → wiring). The at-most-once Claim fence is correct and genuinely proven (the miniredis Lua-CAS concurrency test is real), the layering and byte-identical off-by-default wiring are clean, and the two prior review rounds caught the sharp plumbing bugs. The findings below are concentrated in the behavioral edges the earlier passes didn't reach.
Through-line: two shipped, code-complete features don't work end-to-end — Singleton fires once then skips forever (F-1, with E-3), and MisfireSkip never fires at all (E-1). Both are off-by-default in Phase 1 so they're latent, but each is a landmine for the Phase 2 create-seam that would turn them on.
10 inline findings follow, severity-tagged. Posted as COMMENT (not REQUEST_CHANGES) — severities are the author's call.
| // Misfire policy: MisfireSkip + a past slot advances NextFireAt WITHOUT | ||
| // firing. The Claim is still the advance (so the slot is not re-returned by | ||
| // a peer's Due); we just skip the Fire. | ||
| skipFire := sched.Spec.Misfire == port.MisfireSkip && sched.State.NextFireAt.Before(now) |
There was a problem hiding this comment.
[MEDIUM] MisfireSkip skips every fire — such a schedule never fires.
skipFire := sched.Spec.Misfire == port.MisfireSkip && sched.State.NextFireAt.Before(now). But Due only ever returns slots with NextFireAt <= now, and with a polling tick (30s default) a genuinely-due slot's NextFireAt is essentially always strictly before now (equality to the nanosecond never happens). So a MisfireSkip schedule is skipped on every tick — it fires zero times, forever. There's no grace threshold distinguishing "missed by a lot" (the intended skip case) from "just became due" (normal poll jitter).
TestMisfireSkip masks this — it only tests a slot an hour in the past. Suggest gating skip on lateness beyond a grace window (e.g. now.Sub(NextFireAt) > TickInterval, or > the cron period) and adding a "fresh MisfireSkip slot still fires" test.
| // the stop reason + error pointer to the session id. | ||
| var stop session.StopReason | ||
| var runErr string | ||
| for ev := range run.Events() { |
There was a problem hiding this comment.
[MEDIUM] Fire sessions are never closed → per-fire lease/goroutine leak, and Singleton fires once then skips forever.
makeFireFunc drives the run to terminal and returns — it never closes the fire session or releases its lease. But run-entry leases are released "ONLY by CloseSession / shutdown (releaseLease), never per-run" (internal/adapter/server/service.go:2261). So on a lease-backed deployment (exactly the redis/k8s multi-replica case Singleton targets):
- Leak: every fire leaves a held session lease + its renewer goroutine alive for the whole process lifetime (the child-GC only reclaims on a retention timescale, far too late). Worth a cloud-native inventory row.
- Singleton breaks: on the next fire,
isPriorFireLivetrial-acquires on the prior fire's session id — whose lease is still actively renewed — getsErrLeaseHeld, and skips. Forever. The port doc's self-heal premise ("a finished fire's lease released/expired → free acquire → not skipped",engine/port/schedule.go:216-220) is false here because the fire's lease outlives the run.
Latent in Phase 1 (Singleton defaults false), but a guaranteed break the moment Phase 2 sets the intended Singleton=true default. Fix: release the fire session's lease at run-terminal (keep the session durable for pull-only results), or add a per-run lease-release path to the run-entry funnel.
| return nil | ||
| } | ||
| // Stamp the real session id over the port.PendingFireSessionID value Claim set. | ||
| if err := s.client.HSet(ctx, scheduleKey(f.ScheduleName), fieldLastFireSessionID, string(f.SessionID)).Err(); err != nil { |
There was a problem hiding this comment.
[MEDIUM] RecordFire latches the fire key before stamping the session id — a partial failure wedges LastFireSessionID at pending.
Order here is: SETNX fireKey (the idempotency latch) → then this HSET last_fire_session_id = f.SessionID (overwriting pending). If this final HSET fails transiently, a retry short-circuits at the EXISTS fireKey check (line ~373) and never re-runs the HSET — so LastFireSessionID stays port.PendingFireSessionID permanently.
Contrast the siblings: jsonl writes the schedule (session id) first, then the fire record (jsonlstore/schedulestore.go:266-270) — benign, retry-recoverable; mem is atomic under one mutex. redis has the ordering backwards. Fix: stamp the session id before latching the fire key, or make both writes one MULTI/pipeline. (Related: the same HSET can resurrect a deleted schedule as a spec-less zombie hash that then loads as a decode error rather than not-found.)
| continue | ||
| } | ||
| // Skip fire records (they share the schedule- prefix via schedule-fire-). | ||
| if strings.HasPrefix(e.Name(), scheduleFirePrefix) { |
There was a problem hiding this comment.
[MEDIUM] A schedule named fire-* collides with fire records and is invisible to List/Due.
schedulePath("fire-foo") → schedule-fire-foo.json, which is identical to firePath("foo") → schedule-fire-foo.json (one silently overwrites the other), and this filter skips anything with the schedule-fire- prefix — so a schedule whose name starts with fire- never fires and never lists. Root cause: schedule-fire- is a sub-prefix of schedule- + a name beginning with fire-.
redis is unaffected (distinct mecatl:schedule: vs mecatl:schedulefire: key prefixes). Phase 1 has no name validation, so this is reachable. Fix: a non-overlapping delimiter (e.g. schedule--/schedulefire--), a fires subdir, or reject fire-* names at the create-seam.
| return nil | ||
| }) | ||
| } | ||
| _ = g.Wait() |
There was a problem hiding this comment.
[MEDIUM] A long-running fire stalls polling for all other schedules.
tickOnce blocks in g.Wait() until the entire due batch's fires complete, and FireFunc drives a full agent session to terminal (potentially minutes). While blocked, the tick goroutine can't re-poll Due (the time.Ticker drops intervening ticks), so every other schedule is delayed by the slowest fire in the current batch — a 20-minute run can slip a co-scheduled hourly job by up to 20 minutes.
For Phase 1 with few schedules this may be acceptable, but it's a real cliff: the Claim/advance should be decoupled from the drive (hand fires to a background pool, or don't await terminal in the tick). At minimum, call it out as a known Phase-1 limitation.
| if err != nil { | ||
| return time.Time{}, fmt.Errorf("cronparse: invalid cron expression %q: %w", expr, err) | ||
| } | ||
| return sched.Next(from.In(loc)), nil |
There was a problem hiding this comment.
[MEDIUM] A parseable-but-impossible cron returns (zeroTime, nil), defeating the "never silently never-fires" promise.
robfig's Schedule.Next caps its forward search at 5 years and returns the zero time.Time with no error for a schedule that can never fire — e.g. 0 0 30 2 * (Feb 30). ParseStandard accepts these, so NextFire returns (time.Time{}, nil). Two problems:
- The package doc (lines 8-11, 24-26) promises fail-closed Save-time validation; this slips through.
- Per
port.ScheduleStore.Claim, a zeronextFiremeans "no further fire →Enabled=false" — so an impossible cron is interpreted as a completed schedule.
Fix: return an error when sched.Next(...) yields the zero time, so composition rejects it fail-closed; add an impossible-but-parseable test case (the invalid-expression test only covers grammar failures). Note: the downstream fix belongs at the create-seam, which doesn't exist in Phase 1 — so the leaf is currently the only place this can be caught.
| // skipped) — the lease, not the field, is authoritative. The trial lease is | ||
| // released immediately (we don't hold it; the fire's own run-entry acquires | ||
| // its own session lease). | ||
| if !skipFire && sched.Spec.Singleton && s.cfg.Lease != nil && sched.State.LastFireSessionID != "" && sched.State.LastFireSessionID != port.PendingFireSessionID { |
There was a problem hiding this comment.
[MEDIUM] Port doc and scheduler contradict each other on the pending sentinel.
The port doc (engine/port/schedule.go:31-41) states the scheduler "treats a pending LastFireSessionID as 'a fire is in its Claim→RecordFire window' and SKIPS." This code does the opposite: the singleton check is gated on LastFireSessionID != port.PendingFireSessionID, so a pending value means the overlap check is not performed and the fire proceeds.
In the happy path it's moot (a pending slot isn't due). But it resolves the redis-RecordFire question (see the RecordFire comment): a wedged schedule stuck at pending doesn't get "skipped forever" — it silently loses its singleton protection. Reconcile the doc and the code.
| } | ||
| scfg := scheduler.Config{ | ||
| Store: schedStore.ScheduleStore(), | ||
| Lease: sessionLease, // same backend, different id — no contention |
There was a problem hiding this comment.
[MEDIUM] --scheduler + jsonlstore + no lease backend runs standalone on every replica with no cross-process fence — silently.
With Lease == nil, the scheduler ticks standalone and the jsonl Claim mutex is per-process only — two replicas on a shared --store-dir both fire every slot (double-fire). redis is safe (the Lua CAS). Nothing warns: scheduler.Start logs the stand-down/standalone posture only when Lease != nil, so a lease-less start is silent.
Suggest emitting an INFO/WARN when the scheduler starts with no lease backend ("single-replica by affinity — unsafe with multiple replicas"), mirroring the honest posture the lease paths already log.
| // for a future self-pushing tick helper and is otherwise inert here). A nil | ||
| // clock is a programming error at the only construction sites (composition, | ||
| // tests), so it is not defended here. | ||
| func New(clock port.Clock) *Store { |
There was a problem hiding this comment.
[LOW] Dead clock injection + unused advance callback replicated across every adapter.
The injected clock here is never read (the doc admits it's "otherwise inert"), and the conformance factory's advance callback is discarded in all 13 subtests — both jsonl and redis factories even pass a func(time.Duration){} no-op. Because every port method takes now as an explicit argument, the injection is unnecessary, yet the factory signature (scheduleconformance.go:65) forces every future adapter to construct and return an unused callback.
Either wire advance (only meaningful for a real-clock adapter) or drop it from both the factory signature and New. Low priority — flag whether this is deliberately staged for a Phase-2 self-pushing lookahead, or should be dropped until then.
| // new schedule disabled passes a non-zero State with Enabled=false. | ||
| rec.state = in.State | ||
| if in.State.NextFireAt.IsZero() && !in.State.Enabled && in.State.FireCount == 0 { | ||
| rec.state.Enabled = true |
There was a problem hiding this comment.
[LOW] The "new schedule defaults to Enabled" behavior is unpinned by the conformance suite.
This fragile triple-zero heuristic (NextFireAt.IsZero() && !Enabled && FireCount==0) is behavior all three backends must share (jsonl + redis do mirror it byte-for-byte today — verified), but the conformance suite has no subtest for the create-default, so nothing prevents a future adapter from diverging on exactly the behavior most likely to. Suggest a conformance subtest pinning new-default-Enabled + explicit-disabled-honored.
Define the durable schedule registry port + value objects in engine/port, a peer of port.SessionLease / port.EventLog (issue #189, phase 1a: the contract + value objects, no implementation yet). The port carries the full at-most-once claim-before-fire contract in its doc-comments: - ScheduleProviderSelector (opaque provider+model strings, mirrors port.LLMRequest.Model; zero = deployment default; deliberately omits a reasoning-effort field — that's an adapter Option, not a port concept per the DTO-neutrality discipline). - TriggerSpec (Cron XOR OneShot sum type) + TriggerKind + Validate()/ Kind() (fail-closed on both/neither). - MisfirePolicy (MisfireFireOnceNow = zero-value default | MisfireSkip). - ScheduleSpec (immutable definition) + ScheduleState (durable firing state, advanced by Claim) + Schedule (aggregate) + ScheduleFire (pull-only v1 result record). - ErrScheduleNotFound / ErrScheduleUnsupported sentinels (the SessionLease/PrunableStore precedent; wrapped %w). - SchedulerLeaderLeaseID (const) — the well-known leader-lease id ('__scheduler__'), hygiene not correctness (SessionID is unvalidated, k8slease hashes arbitrary ids, real ids are hex). - ScheduleStore interface: Save/Load/Delete/List/Due/Claim/RecordFire/ LoadFire. Claim is the atomic advance (NextFireAt + LastFireAt + FireCount + sentinel-pending LastFireSessionID) giving exactly-once across replicas; the store is parser-free (the caller computes the next cron fire); the at-most-once fence is the NextFireAt advance itself (no owner/claim-holder field — cross-replica overlap of a still-running prior fire is the caller's trial-lease on LastFireSessionID, a separate concern). engine/agent NEVER imports this port. api-compat gate (ADR 0037): engine/api/port.txt regenerated; engine/ CHANGELOG.md Added entry classified per COMPATIBILITY.md (new exported identifiers in engine/port = minor). engine/COMPATIBILITY.md port row lists ScheduleStore alongside the sibling ports. No implementation ships yet — adapters, conformance suite, tick loop, and composition wiring are later phases.
…phase 1c) Add robfig/cron/v3 (parser-only) to the engine module and a pure cronparse leaf that turns a cron expression (5-field or @-macro) + a time.Time + a *time.Location into the next fire instant strictly after the given time. Per decision #6 the durable ScheduleStore is ground truth and the in-memory timer is a derived lookahead, so mecatl uses robfig's PARSER only (cron.ParseStandard + Schedule.Next) — NOT the cron.New() daemon. The dep is a single zero-transitive module, mirroring how doublestar and x/sync already travel with the importable core (ADR 0036); task test:engine-standalone (the GOWORK=off hygiene proof) confirms the standalone closure stays self-contained. - engine/adapter/cronparse.NextFire(expr, from, loc) — fail-closed on a bad expression (a schedule with a bad cron is rejected at Save time, never silently never-fires). Honours a per-schedule IANA timezone (default UTC); robfig's Schedule.Next returns the next instant strictly AFTER from (a fire at exactly from is the current slot, already claimed — the claim-before-fire semantics). - .golangci.yml: a strict engine-adapter-cronparse depguard allowlist ($gostd + robfig/cron/v3 only, os denied) so the leaf cannot pull engine/port or internal/. - engine/CHANGELOG.md: a Notes entry recording the dep closure addition (NOT an api-compat-gated surface — engine/adapter is EXCLUDED from the stability contract per COMPATIBILITY.md, like memlease.New / eventsource.Fold). cronparse is a stdlib + robfig leaf (no internal/, no engine/port) so the conformance suite and any adapter can use it.
#189, phase 1b) Add the shared conformance suite (the contract-unification pattern, mirroring leaseconformance) and the clock-injected in-memory reference adapter for port.ScheduleStore — the SECOND adapter-validation pattern after leases. - engine/adapter/scheduleconformance: Run(t, newStore) drives the port through a fake-clock advance(d) callback. 13 subtests pin the contract: save/load round-trip, state-preserved-on-overwrite, not-found wraps ErrScheduleNotFound, idempotent Delete, List-returns-all, Due filtering (NextFireAt/Enabled/MaxFires), Claim atomic advance (LastFireAt/ NextFireAt/FireCount/non-empty sentinel LastFireSessionID), Claim excludes from Due, the at-most-once proof (a second Claim at the same now returns ErrScheduleNotFound — the fail-safe interpretation, the durable NextFireAt advance IS the fence), Claim not-found, RecordFire idempotent + LoadFire, MaxFires exhaustion disables on the final claim, one-shot fires once then disables, misfire fire-once-now advances to a future next fire. MisfireSkip is documented as a composition concern (not tested at the store level). Uses cronparse to compute expected next fires (the suite is a test-helper, allowed to import it). - engine/adapter/memschedulestore: the in-memory reference adapter (mirrors memlease). Clock-injected, mutex-guarded maps, deep-copy on Load/List, pendingSessionID sentinel, Claim re-checks the at-most-once fence under the mutex and returns ErrNotFound-wrapped on a re-claim. Parser-free (no cronparse import) and misfire-free (no Misfire read) — the store is ground truth, the parser + policy are composition concerns. - engine/port/schedule.go: add the Trigger port.TriggerSpec field to ScheduleSpec (Phase 1a landed TriggerSpec but never wired it onto the spec; the suite/adapter need it to save/load a schedule with a trigger). The zero TriggerSpec is TriggerNone, which the create-seam's Validate rejects fail-closed. - .golangci.yml: engine-adapter-memschedulestore (allow $gostd + port + session, no cronparse) and engine-adapter-scheduleconformance (allow $gostd + port + session + cronparse) depguard rules. - engine/api/port.txt: regenerated (the new Trigger field). - engine/CHANGELOG.md: Added entry for the Trigger field (classified Added/minor per COMPATIBILITY.md).
The production port.ScheduleStore backends, discovered by composition via type-assertion on a new ScheduleStore() accessor (decision #5: reuse the configured store; the PrunableStore/SessionLease precedent, with a documented deviation — the schedule store is a sibling struct sharing the dir/client, not the session store itself implementing the port). Both pass the shared scheduleconformance.Run suite (13 subtests, incl. the at-most-once proof: a second Claim at the same now returns ErrScheduleNotFound). jsonlstore (single-host): - internal/adapter/store/jsonlstore/schedulestore.go — schedule-<name>.json + schedule-fire-<id>.json under the same dir; shares the *Store's mutex (the single-process fence); atomic temp+rename write (crash-safe); jsonlstore-schedule/1 format envelope (unknown tag fails loud on load). Claim re-checks the fence under the mutex. Documented honestly as single-host-only for the claim race (the mutex is the fence, same scope as the flock lease; multi-host needs the redis backend or a leader lease). redisstore (multi-replica): - internal/adapter/redisstore/schedulestore.go — mecatl:schedule:<name> HASH (spec JSON + state fields) + mecatl:schedulefire:<id> STRING. NO client mutex (Redis serializes). THE LOAD-BEARING PART: claimScript is a Lua CAS (redis.NewScript, EVALSHA) that atomically re-checks the slot is still due and advances — a plain HGETALL+HSET would race between replicas. Returns NOT_FOUND / NOT_CLAIMABLE sentinels → ErrScheduleNotFound (the fail-safe interpretation). The zero nextFire is passed as the '0' sentinel (not the large-negative UnixNano of a zero time.Time — a subtle correctness fix). - internal/adapter/redisstore/schedulestore_test.go — the MULTI-REPLICA AT-MOST-ONCE PROOF: 10 (and 8x25) goroutines Claim the same slot concurrently; exactly one wins, the rest get ErrScheduleNotFound, under -race. This is the property the jsonl mutex gives only single-process; the redis backend gives it across replicas. Both adapters mirror memschedulestore semantics: State preserved on overwrite, new schedules default to Enabled, pendingSessionID sentinel, RecordFire idempotent per fire id.
The internal/adapter/scheduler package: the in-process tick loop gated by the __scheduler__ leader-lease (acquired on port.SchedulerLeaderLeaseID), claim-before-fire via port.ScheduleStore.Claim, and a FireFunc seam. Plus the frozen ADR 0059 and the CLOUD-NATIVE.md Phase 5 inventory rows. - internal/adapter/scheduler/scheduler.go — the Scheduler. Owns the leader-lease (Acquire on __scheduler__; ErrLeaseHeld → stand down, do NOT tick; ErrLeaseUnsupported → sticky-disable the leader gate, tick standalone single-replica by affinity; the renewer mirrors service.renewLoop: ErrLeaseHeld = definitive loss → cancel tick ctx; a transient fault gets grace until near-expiry). The tick loop polls ScheduleStore.Due, applies the misfire policy (MisfireSkip → Claim to advance NextFireAt WITHOUT firing; MisfireFireOnceNow → Claim then Fire), Claims each due slot (ErrScheduleNotFound from Claim = a peer claimed it between Due and Claim — the at-most-once fence worked, skip), fires via the FireFunc seam, and RecordFires the outcome. A failed Fire after a successful Claim is NOT retried (the slot is gone — decision #1). Bounded fan-out via errgroup.SetLimit(MaxConcurrentFires). Drain() + Stop() (cancel tick + renewer, join in-flight fires with a StopFireGrace, release the lease). STORAGE-AGNOSTIC: imports only engine/port + engine/adapter/cronparse + engine/session + stdlib + errgroup — NO engine/agent, NO internal/adapter/server (the FireFunc seam is the composition boundary). NO slog (port.Diagnostics). Reviewed by software-architect; vestigial lostLeader/leaderActive dead state removed. - internal/adapter/scheduler/scheduler_test.go — 10 tests with fake clock + mem ScheduleStore + a FireFunc stub: fire-once-and-advances; at-most-once across two standalone schedulers (Claim fence); stand-down on ErrLeaseHeld; misfire fire-once-now vs skip; MaxFires exhaustion; one-shot fires once then disabled; MaxConcurrentFires bounds fan-out; Stop joins in-flight fires (goleak-clean); Drain stops new fires; failed fire recorded as StopError and not retried. - docs/adr/0059-scheduled-tasks.md — frozen ADR recording all 10 resolved decisions + the __scheduler__ leader-lease decision. Consequences: a one-shot can be lost on a mid-fire crash; the floor is operator-config; fresh-context-per-fire v1 (carried-context deferred to v2). - docs/adr/0027-cloud-native.md — Phase 5 section + List 1 row 29 (scheduler goroutine + Service.scheduler handle; owner server.Service; scope process; cleanup scheduler.Stop()/Drain; re-attach = derived from durable ScheduleStore on next Build). List 2 (lookahead + lease ownership = derived). The FireFunc seam is the composition boundary; Phase 1f wires it to Service.CreateSessionWithProfile + Service.StartRunContent. Until then the scheduler is inert (no composition wire, byte-identical default).
…lags (#189, phase 1f) The composition wiring that makes the scheduler user-reachable. buildScheduler (internal/app/build.go, mirroring buildSessionLease:1824) discovers the ScheduleStore by type-assertion on the configured store's ScheduleStore() accessor (decision #5); reuses the session-lease backend for the __scheduler__ leader-lease (same backend, different id — no contention). The FireFunc is LATE-BOUND: buildScheduler returns the Scheduler with Fire nil, startScheduler (extracted from Build to keep gocyclo under the lint cap) calls SetScheduler + SetFire + Start after NewService. - internal/app/scheduler_fire.go — makeFireFunc(svc): mints a fresh top-level session per fire via CreateSessionWithProfile + StartRunContent with subagent-grade defaults (bounded MaxTurns/MaxToolCalls when the schedule carries none; read-leaning posture unless Mutating:true; fail-closed model pinning — NO pre-flight ListModels, an unknown model surfaces as StopError). The fire id IS the session id (decision #7); a create-time failure mints a sched--<name>-<ts>-<rand> fallback id so RecordFire has a key. Drives the run to terminal EvResult, returns the ScheduleFire with the stop reason. - internal/adapter/server/service.go — SetScheduler (late-bind seam), HasScheduler (read-side), Close stops the scheduler before the lease release, Drain drains it (the drain gate stops new fires mid-tick). - internal/adapter/scheduler/scheduler.go — SetFire (the late-bind setter, panics if called after Start). - cmd/mecated + cmd/mecak8s — --scheduler, --scheduler-tick-interval, --scheduler-min-interval, --scheduler-max-concurrent-fires flags. - internal/app/scheduler_fire_test.go — THE END-TO-END GATE: a full app.Build with --scheduler over a jsonlstore, a one-shot schedule due in 100ms, a mockllm provider returning a text turn; asserts a sched-- family session was created + driven to StopEndTurn + the ScheduleFire recorded + the one-shot disabled. Fully offline. - docs: architecture.md (Scheduled tasks section), usage.md (--scheduler flags), PRODUCTION-READINESS.md (Phase 5 row), llms.txt regenerated.
…ing default, timezone, dedupe (#189) Address the actionable findings from the full three-axis panel review (Spec + Standards + Domain: security/architecture/library-reuse/duplication) run over the complete PR diff. 1. Cross-replica singleton via trial-lease (Spec finding #1, the genuine Phase-1 gap). fireOne now acquires a TRIAL lease on ScheduleState.LastFireSessionID before claiming, when Singleton is true and a lease backend is wired. ErrLeaseHeld → the prior fire is still running on some replica → skip (advance NextFireAt via Claim, don't fire). Success → prior fire finished/crashed → fire freely. The trial lease is released immediately (deferred); the fire's own run-entry acquires its own session lease. A stale pointer to a finished fire yields a free acquire (not skipped) — the lease, not the field, is authoritative. ErrLeaseUnsupported / no lease backend → fire (single-replica by affinity, the Claim fence holds within-process). Infra error → fire (fail-safe; the Claim fence is the backstop). 2. Read-leaning default enforced at fire (Spec finding #3, decision #3). The FireFunc now clamps Mode to plan (read-only toolset) when Mutating is false — the conservative posture for unattended runs. Mutating=true honors the schedule's explicit Mode. The create-seam (Phase 2) will additionally reject Mutating=false with a write-capable Mode at save time. 3. Per-schedule timezone (Spec finding #4). ScheduleSpec gains a Timezone string field (IANA name; empty = UTC, the recommended default for infra schedules — avoids the 1–3am DST danger zone). computeNextFire loads it via time.LoadLocation (fail-safe: invalid → UTC) and passes it to cronparse.NextFire instead of the hardcoded UTC. A one-shot trigger ignores it (absolute wall-clock instant). api-compat gate regenerated. 4. Dedupe safeFilePart → safeName (library-reuse finding). The jsonl schedule store's safeFilePart was byte-for-byte identical to the existing safeName (same rune allowlist, same leading-dot neutralisation). Collapsed to a one-line wrapper: safeFilePart(s) = safeName(session.SessionID(s)). Documented deferrals (not actionable in this PR): - The sched-- session-id prefix (Spec finding #2, decision #7) requires a session-id override on CreateSessionWithProfile — a server API change tracked for Phase 2. The fire id is the session id; the sched-- prefix is on the failure-path fallback id only. - The --scheduler-min-interval flag is plumbed but inert (no create-seam to enforce it at Save time yet — Phase 2b). Documented in the flag help.
…eout (#189) The singleton trial-lease acquire in isPriorFireLive was riding the tick loop's ctx (only cancelled on Stop), so a slow or unresponsive lease backend could block the fire path indefinitely and starve the MaxConcurrentFires errgroup. The acquire is a best-effort liveness probe, not a hard gate (the Claim fence is the backstop), so it must be SHORT. - singletonTrialTimeout (5s) bounds the trial-lease Acquire via a derived context.WithTimeout. A timeout is treated as a transient infra fault → fail-safe (fire; the Claim fence is the backstop), same as an I/O error. - The release path was already bounded (leaderLeaseAcquireTimeout via a detached ctx). - Both lease operations (acquire + release) are now bounded; neither can block the fire path indefinitely. Mirrors the leader-lease acquire timeout's 'bounded so a wedged backend cannot stall' discipline.
…nID const, docs (#189) Addresses the PR #211 review from @rdimitrov: NextFireAt, but Claim overwrites LastFireSessionID with the pending sentinel — destroying the pointer to the still-running prior fire. On the next tick the singleton check (gated on LastFireSessionID != pending) was skipped, so a second fire launched concurrently with the still-running prior fire, defeating the singleton guarantee. Fix: do NOT Claim in the skip path; leave the slot due and let the next tick's trial-lease re-check skip again while the prior fire holds it. The repeated trial-lease acquires are bounded (singletonTrialTimeout each, every TickInterval). New regression test TestSingletonOverlapPreservesLivePointer pins the fix (two ticks while overlapping, then fire after release). bool zero value is false and nothing defaults it in Phase 1 (no create API). Softened to "intended default true (set by the create-seam)". memschedulestore/jsonlstore/redisstore and hard-coded in the scheduler. Promoted to one port.PendingFireSessionID constant (the same discipline as SchedulerLeaderLeaseID); all three adapters + the scheduler import it. success path (CreateSessionWithProfile mints a random id; the prefix is only on the failure-path fallback). Correctly deferred; no prose change needed beyond the Singleton doc fix (the ADR/PR body already notes the deferral). but Phase 1 has no create API and MinInterval is inert. Noted "currently inert; enforced at the create-seam (Phase 2)" in both mecated and mecak8s. Minor: Service.Close/Drain read s.scheduler without s.mu (now locked, matching SetScheduler/HasScheduler); added a Redis Lua nanosecond-precision comment. api-compat gate regenerated (PendingFireSessionID in engine/api/port.txt). Co-Authored-By: Juan Osorio Ortiz <[email protected]>
…lease, redis/jsonl store fixes (#189) Second review round (jhrozek) on the scheduled-tasks Phase 1 PR. Fixes the behavioral-edge findings and reconciles doc/impl mismatches. - MisfireSkip skipped EVERY fire: `NextFireAt.Before(now)` is essentially always true under a polling tick, so a MisfireSkip schedule never fired. Now skip only when a slot is late beyond a grace window (one tick interval); a freshly-due slot still fires. + a "fresh MisfireSkip slot still fires" regression test. - Fire-session lease leak + Singleton break: the FireFunc never closed the fire session, so on a lease-backed deployment every fire leaked a held session lease + renewer goroutine, and the singleton trial-acquire hit ErrLeaseHeld on the still-renewed lease and skipped forever. Now CloseSession at run-terminal (releases the lease + per-session engine; keeps the durable snapshot for pull-only results). - Impossible-but-parseable cron (e.g. "0 0 30 2 *") returned (zeroTime, nil), which downstream reads as "no further fire → disable". cronparse.NextFire now errors on a zero next-fire so composition fails closed. + a test. - redis RecordFire ordering: stamped last_fire_session_id AFTER latching the fire key, so a transient stamp failure wedged LastFireSessionID at pending forever (retry short-circuited at the idempotency check). Stamp BEFORE the latch. - jsonl fire-* name collision: "schedule-" + a "fire-*" name collided with the "schedule-fire-" fire-record prefix (a schedule named fire-* never fired/listed). Use non-overlapping prefixes "schedule--" / "schedulefire--". - Reconcile the pending-sentinel port doc with the code: pending is not a probeable session id, so the singleton check is skipped and the fire proceeds (skipping on pending would wedge a schedule forever after a Claim→RecordFire crash). Doc updated to match. - Warn at composition when the scheduler is enabled with no lease backend (single-replica by affinity; unsafe multi-replica → double-fire). - Document the long-running-fire tick-latency Phase-1 limitation (ADR 0059 + tickOnce comment). - LOW: drop the dead injected clock from memschedulestore.New and the unused advance callback from the scheduleconformance factory; add a conformance subtest pinning new-schedule-default-Enabled + explicit-disabled-honored. - Honesty nits (rdimitrov #4): ADR decision #7 + newFireID doc no longer claim successful fires are sched-- prefixed (they use CreateSessionWithProfile's random id; the sched-- prefix awaits a Phase-2 session-id override). Rebased onto main; CHANGELOG #189 entries moved under [Unreleased]; llms.txt regenerated. task lint + task test (root + engine + standalone, -race) green; docs:check 0 broken; mecademo offline session clean. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
142fce2 to
eef71b1
Compare
jhrozek
left a comment
There was a problem hiding this comment.
Approving. Re-reviewed the force-pushed head (eef71b1) against the earlier inline review — all 10 findings are addressed (8 with new tests), and CI is green across Build, Test (race), Lint, API-compat, engine-standalone, fuzz, govulncheck, docs, perf, and k8s e2e.
Verified fixes:
- MisfireSkip now fires normally (tick-interval grace window) —
TestMisfireSkipFreshSlotStillFires. - Fire-session lease released via
defer CloseSession(keeps the durable snapshot) — closes the per-fire lease/goroutine leak and the singleton fire-once-then-skip. - redis
RecordFirestamps the session id before latching the fire key (no morependingwedge); jsonl uses non-overlappingschedule--/schedulefire--prefixes. - cronparse errors on an impossible-but-parseable cron.
- Tick-stall documented as a Phase-1 limitation; standalone-no-lease WARN added; the
pendingdoc reconciled; dead clock/advance removed; default-Enable pinned in the conformance suite.
Non-blocking follow-ups for later (none warrant holding the merge):
- The
CloseSession-releases-the-lease fix has no composition-level regression test (a lease-backed "recurring Singleton fires >once" / "held-lease count → 0 after a fire" test would pin it). renewLeader/declareLeaderLostremain at 0% coverage — the multi-replica leader-lease renewal/loss core is untested.- The
computeNextFire-error path logs-and-skips without claiming, so a manually-saved impossible cron busy-loops a WARN each tick rather than disabling (latent until Phase 2's create-seam catches it at Save). - Latent unsynchronized
tickCtx/tickCancelaccess inStart(assign before launching the renewer, or guard with the mutex).
Summary
Implements Phase 1 of the scheduled-tasks feature (#189): a scheduler subsystem that lets an operator register a saved prompt to run on a 5-field cron schedule (
0 9 * * *,@every 30m,@dailymacros) or once at a future time, and have mecatl drive that run autonomously, durably, and exactly-once across a multi-replica deployment — with no human present at fire time.This builds on the cloud-native infrastructure already shipped in ADR 0027 (durable event log, session leasing, snapshot rehydration) and ADR 0048 (mecak8s, Redis store, k8s lease, drain gate). The hard parts — durable session state, single-writer exclusion across replicas, restart rehydration — are already solved; the scheduler is a durable trigger registry plus a tick loop that calls the existing run-entry funnel.
Closes #231 (Phase 1 subissue). Part of #189 (the umbrella issue, which stays open until all phases land). Phases 2–3 are tracked as separate subissues — see Follow-ups below.
Design (the 10 resolved decisions, from the issue thread)
NextFireAt/LastFireAtin the store before firing; a crash mid-fire skips the slot (recurring self-heals via fire-once-now; a one-shot can be lost).ScheduleStoreinengine/port— consistent withSessionLease/EventLog; an engine-localScheduleProviderSelectorvalue object (opaque strings, mirroringport.LLMRequest.Model).mutating: trueopt-in — a scheduled run that wants to write opts in explicitly.MinInterval— no hard floor in the binary.ScheduleStore()accessor (thePrunableStore/SessionLeaseprecedent, with a documented deviation: the schedule store is a sibling struct, not the session store itself).robfig/cron/v3parser-only — the store is ground truth; the in-memory timer is a derived lookahead.sched--family); GC retention family deferred to Phase 2 (needs a session-id override onCreateSessionWithProfile).ScheduleStore.LoadFire/ the durable event log; push/webhook is v2.StopError(no pre-flightListModelscheck — a live network call, deferred).MaxFires(notRepeat);TriggerSpecis a sum type{Cron | OneShot}— one-shot fires once by definition.See ADR 0059 for the frozen rationale.
What landed (6 commits, each a dev-pipeline iteration)
669b8c3engine/port/schedule.go— theScheduleStoreport + value objects (TriggerSpecsum type,ScheduleProviderSelector,MisfirePolicy,Schedule/ScheduleSpec/ScheduleState/ScheduleFire,Err*sentinels,SchedulerLeaderLeaseIDconst). Triggers the api-compat gate (task api:update+engine/CHANGELOG.md).a7ca4f9engine/adapter/cronparse— parser-onlyrobfig/cron/v3dep +NextFire(expr, from, loc).test:engine-standalonehygiene proof passes.e17dfa3engine/adapter/scheduleconformance(13-subtestRunsuite, incl. the at-most-once proof: a secondClaimat the samenowreturnsErrScheduleNotFound) +engine/adapter/memschedulestore(clock-injected reference adapter).886e57eScheduleStorebackends. The redisClaimis a Lua CAS (redis.NewScript, EVALSHA) — the multi-replica at-most-once fence (no client mutex; Redis serializes). The-racemulti-goroutine concurrent-claim test (10 + 8×25 goroutines, exactly one wins) is the proof.22d50afinternal/adapter/scheduler— the tick loop, gated by the__scheduler__leader-lease (only the leader ticks;ErrLeaseHeld→ stand down,ErrLeaseUnsupported→ tick standalone), claim-before-fire viaScheduleStore.Claim, theFireFuncseam (NOengine/agentimport — composition-layer). ADR 0059 + CLOUD-NATIVE.md Phase 5 inventory rows.8130e33buildScheduler/startSchedulermirroringbuildSessionLease),server.Serviceownership (SetScheduler/HasScheduler/Close/Drain), theFireFunc(CreateSessionWithProfile+StartRunContentwith subagent-grade defaults + fail-closed model pinning),--scheduler*flags inmecated/mecak8s. The e2e gate: asched---family session driven toStopEndTurnby a fired schedule, fully offline (mockllm + jsonlstore).Verification
task lint— 0 issues (golangci-lint v2 + go vet, root + engine modules)task test— full suite green,-race(root + engine +GOWORK=offengine-standalone)task api:check— green (the newport.ScheduleStoresurface is inengine/api/port.txt+engine/CHANGELOG.md)task docs—llms.txtregenerated, strict link/citation gate 0 brokengo run ./cmd/mecademo— still prints the full offline session (regression)internal/app/scheduler_fire_test.go:TestSchedulerFire) — a one-shot schedule fires, mints a session, drives it toStopEndTurn, records theScheduleFire, disables the one-shotLayering
The scheduler is a composition-layer subsystem (no
engine/agentchanges).engine/agentNEVER importsport.ScheduleStore— the tick loop, cron parsing, misfire policy, and leader-lease acquisition all live ininternal/adapter/scheduler(composition), exactly as the run-entry lease renewer and the event-log persist live in composition. TheFireFuncseam is how composition injects the run-entry funnel (Service.CreateSessionWithProfile+Service.StartRunContent).Follow-ups (tracked as subissues of #189)
What's NOT in this PR is filed as separate subissues so nothing is lost on merge:
ScheduleService(CRUD + FireNow + ListFires) + driver proto +EvSchedule*eventssettings.yamlschedules:block (operator-tier) + CLI management + metricsmecatui/scheduleslash command + overlaysched--GC retention family, NL→cron, carried-context/persistent recurring session, event/webhook triggers, driverScheduleStoreServiceCo-Authored-By
Juan Osorio Ortiz [email protected]