Repository navigation
feat: scheduled tasks — Phase 2a ScheduleService + EvSchedule* events (#232) - #237
Conversation
…232, phase 2a) Foundation chunk for the scheduled-tasks wire surface: - contracts/proto/mecatl/v1/schedule.proto — new ScheduleService (10 RPCs: Create/Get/List/Update/Delete/FireNow/Pause/Resume/GetFire/ListFires) + messages mirroring engine/port/schedule.go value objects. - harness.proto — Event.schedule (field 15) + SchedulePayload (the client-visible scheduler lifecycle projection, colocated with Event to break the import cycle). - engine/session/event.go — EvScheduleFired/Skipped/Failed consts + SchedulePayload + Event.Schedule field (string-passthrough, no enum). - internal/adapter/server/mapper.go — toProtoSchedule + the toProto arm. - engine/api/session.txt regenerated (api-compat gate); engine/CHANGELOG.md Added entry. Co-Authored-By: Juan Osorio Ortiz <[email protected]>
…edule emit (#232, phase 2a) - engine/port/schedule.go: ListFires (list companion to LoadFire) + SetEnabled (the pause/resume primitive — Save preserves State on overwrite so it cannot mutate Enabled). - memschedulestore/jsonlstore/redisstore: ListFires + SetEnabled; conformance subtests for both. - internal/adapter/scheduler: fireClaimed factored out of fireOne (shared by tick loop + FireNow); FireNow (manual trigger: singleton check → Claim → fireClaimed, FAILED_PRECONDITION on overlap); EmitScheduleEvent callback on Config (nil-safe; scheduler pkg stays EventSink-free); EvSchedule fired/skipped/ failed emitted from fireClaimed/fireOne/FireNow; exported LoadLocation. - internal/adapter/server/schedule.go: Service.scheduleStore() accessor (memoised type-assertion); CreateSchedule create-seam (TriggerSpec.Validate, cronparse NextFire, Singleton=true default, read-leaning-mode rejection, MinInterval floor); Update/Delete/Get/List/GetFire/ListFires/Pause/Resume/FireNow wrappers. - errors.go/grpc.go/http.go: ErrNoScheduleStore (Unimplemented), ErrScheduleDisabled/ErrFireNowOverlap (FailedPrecondition); toStatus/writeServiceError arms + port.ErrScheduleNotFound (NotFound)/ErrScheduleUnsupported (Unimplemented). - internal/app/build.go: startScheduler wires EmitScheduleEvent → svc.EmitScheduleEvent. Co-Authored-By: Juan Osorio Ortiz <[email protected]>
… phase 2a)
- internal/adapter/server/grpc_schedule.go: ScheduleServer (embeds
UnimplementedScheduleServiceServer for require_unimplemented_servers) +
NewScheduleServer constructor; all 10 RPC handlers (Create/Get/List/Update/
Delete/FireNow/Pause/Resume/GetFire/ListFires); protoToScheduleSpec +
scheduleToProto/scheduleStateToProto/scheduleFireToProto mappers reusing
the existing content/mode/limits mapper primitives.
- internal/adapter/server/http.go: 10 RESTful routes under /v1/schedules...
(POST create, GET list, GET/PUT/DELETE {name}, POST {name}/fire|pause|resume,
GET {name}/fires + {name}/fires/{id}); scheduleSpecBody feeds the single
protoToScheduleSpec chokepoint; ErrNoScheduleStore→501.
- cmd/mecated/main.go, cmd/mecak8s/serve.go, cmd/mecatui/embed/embed.go:
RegisterScheduleServiceServer beside RegisterHarnessServiceServer + the
ScheduleService health status.
Co-Authored-By: Juan Osorio Ortiz <[email protected]>
- engine/port/schedule.go: ClaimNow (FireNow primitive — Claim minus the NextFireAt<=now due-check; fences on LastFireAt==now for at-most-once that is crash-recoverable: a later ClaimNow at a new now proceeds). - memschedulestore/jsonlstore/redisstore: ClaimNow (redis via a claimNowScript Lua variant); conformance 'claim now bypasses due-check' subtest. - internal/adapter/scheduler: FireNow uses ClaimNow; fireOne keeps Claim. - internal/adapter/server/schedule_e2e_test.go: offline e2e (Create cron/one-shot, bad cron→InvalidArgument, past one-shot→InvalidArgument, List, Get, Pause/Resume, FireNow→GetFire→ListFires, Delete idempotent, no-scheduler→Unimplemented). - docs: architecture.md (ScheduleService API surface), usage.md (RPCs+REST+curl), PRODUCTION-READINESS.md (Phase 2a shipped), 0027-cloud-native.md (Phase 5 re-audit List 1 rows 30-31 + List 2 row 21), IMPLEMENTATION-NOTES.md; llms.txt regen. - engine/api/port.txt regen (ClaimNow + ListFires + SetEnabled); CHANGELOG entries. Co-Authored-By: Juan Osorio Ortiz <[email protected]>
…led, singleton update, Redis atomicity, FireNow serialization (#232) - M1: ErrScheduleExhausted (FailedPrecondition/412) for FireNow on a fired one-shot (was 500/Internal); gRPC handler-level test. - S2: ErrFireNowOverlap 412 on BOTH surfaces (was 409 on HTTP). - S3: applyScheduleDefaults shared by Create+Update (PUT omitting singleton no longer silently disables the guard). - S4: fireClaimed emits EvScheduleFailed on StopError (not just Go errors); TestFireNowStopErrorEmitsFailed pins the nil-fireErr path. - S5: Redis SetEnabled atomic (Lua script, no EXISTS+HSET TOCTOU). - S6: per-schedule-name mutex serializes concurrent FireNow + tick-loop fireOne on the same schedule (closes the singleton TOCTOU). - S1: correct EvSchedule* docs — durable-log-only for v1 (pull via GetFire/ListFires; skipped fires are operator-diag-only; live broadcast deferred) across event.go, schedule.go, 0027-cloud-native.md, architecture.md, harness.proto. - S7: HTTP handler test + EventLog EvSchedule assertion + cross-primitive Claim/ClaimNow at-most-once conformance subtest. Co-Authored-By: Juan Osorio Ortiz <[email protected]>
…cron parse-once, docs, coverage (#232) Addresses the mechanical findings from the PR #237 review (the three decision-bearing findings — non-leader stand-down boot, singleton=false handling, FireNow cross-replica at-most-once — are raised as PR comments, not changed here): - Distinct ErrSchedulerNotRunning (FailedPrecondition/412): FireNow now distinguishes "no ScheduleStore" (ErrNoScheduleStore/501) from "store present but no in-process scheduler" instead of a misleading 501. - CreateSchedule parses the cron once: validateScheduleSpec returns the next-fire from the same parse that validates the grammar; CreateSchedule reuses it (UpdateSchedule discards it). Validation semantics unchanged. - schedule.proto: reworded the schedule.* event doc to match v1 delivery (durable-log-only via GetFire/ListFires, not client-visible); documented created_at as server-stamped/output-only. Regenerated contracts/gen. - ADR 0027 (cloud-native): inventoried Scheduler.fireMu (List 1) as a bounded, un-pruned per-schedule-name mutex. - Tests: F-1 regression (TestMakeFireFuncReleasesSessionLease — proves the fire's session lease is released so a lease-backed singleton does not wedge) + renewLeader/declareLeaderLost coverage (0%->70%/100%). Incidental: fixed a genuine pre-existing data race the new renewer tests exposed — Start wrote tickCtx/tickCancel/tickDone unguarded while the renewer's declareLeaderLost read tickCancel concurrently; all now guarded by the existing s.mu (verified under -race). Orthogonal to the excluded design decisions. Note: llms.txt regen (task docs:llms) is pending — network-blocked here; the ADR edit added no new links/headings so likely a no-op, but unverified. Co-Authored-By: Claude Opus 4.8 <[email protected]>
jhrozek
left a comment
There was a problem hiding this comment.
Re-review after the merged Phase 1. The mechanical findings from this pass are already addressed in the latest fixup (3456edaa: distinct ErrSchedulerNotRunning/412, cron parsed once, proto/ADR docs, the missing F-1 lease-release regression test, and renewLeader/declareLeaderLost coverage — plus an incidental fix for a real tickCtx/tickCancel data race the new renewer tests exposed).
Three findings remain that each need a design decision rather than a mechanical fix — two are inline below; the third (HIGH) is here because it lives in already-merged code and can't take a line comment:
[HIGH] Non-leader replicas fail to boot — multi-replica scheduling is broken. internal/adapter/scheduler/scheduler.go Start (~L305-313): its doc says it "returns nil on ErrLeaseHeld (a peer is the leader — this replica stands down)", but the code return errs on ErrLeaseHeld, TestStandDownOnLeaseHeld enshrines that, and internal/app/build.go startScheduler treats any Start error as fatal → Build fails. So in the exact deployment the leader-lease exists for (mecak8s, N replicas, lease backend, --scheduler), the first replica wins the lease and boots; every other replica crash-loops. The doc, code, and test disagree, and composition makes it fatal. (Shipped in #211 — the doc reads correctly, so it slipped review; CI misses it because the k8s e2e doesn't run N replicas with a scheduler lease.)
Decision: (a) minimal — Start returns nil on ErrLeaseHeld (stand down, don't tick, keep serving), flip the test, keep only genuine-infra errors fatal; but a stood-down replica then never re-acquires, so if the leader dies scheduling stops until a restart (leader = SPOF). Or (b) also add a periodic re-acquire loop so a survivor takes over when the leader's lease lapses. (a) unblocks multi-replica boot now; (b) is what leader election really implies. Worth a tracking issue against main regardless, since it's shipped.
None of the three are blocking the mechanical fixup; they're the design calls to make before the multi-replica story is trusted.
| // unconditionally (the conservative default), and a future wire field | ||
| // (singleton_optional / a pointer) will carry the explicit-override | ||
| // semantics. Documented honestly here. | ||
| spec.Singleton = true |
There was a problem hiding this comment.
[MEDIUM — decision] singleton=false is silently ignored.
The proto exposes bool singleton = 13 and the gRPC handler reads it (in.GetSingleton()), but applyScheduleDefaults + the always-false scheduleSingletonExplicit stub force Singleton=true here unconditionally. So a client that explicitly sends singleton=false gets it overridden with no error — a non-singleton schedule is impossible to express, and the wire field is accepted-then-discarded. (proto3's bare bool has no presence, which is the root cause.)
This also means every schedule is now a singleton, so every schedule depends on the fire-session lease-release fix (makeFireFunc's defer CloseSession) — which is exactly what 3456edaa's new TestMakeFireFuncReleasesSessionLease now covers.
Decision: is non-singleton a v1 capability? If yes → optional bool singleton (proto3 presence) + honor false. If no → reject singleton=false with a clear InvalidArgument, or at least document the field as forced-true in v1 (today it's silently dropped, which is the worst option).
| // loop). ErrScheduleNotFound here means the slot was disabled/exhausted or a | ||
| // concurrent Claim/ClaimNow at the same now already advanced it (the | ||
| // at-most-once fence held). | ||
| claimed, err := s.cfg.Store.ClaimNow(ctx, name, now, nextFire) |
There was a problem hiding this comment.
[MEDIUM — decision] FireNow's cross-replica at-most-once is weaker than the tick loop's.
ClaimNow drops the due-check and fences only on LastFireAt == now, which is weaker than Claim's durable NextFireAt-advance fence (every replica sees the advance). The fireMu per-name mutex that serialises this is per-process. So once non-leader replicas actually serve (i.e. after the stand-down boot fix in the review summary), two concurrent FireNow RPCs on different replicas for a singleton schedule can both pass the singleton trial-lease (both probing the prior, finished session) within the Load→ClaimNow window and both fire — a cross-replica double-fire on a "fire now" the PR frames as at-most-once.
Decision: strict cross-replica fence (e.g. the singleton trial-lease should acquire a deterministic per-schedule "fire-in-progress" id rather than the prior session id, so concurrent FireNows contend on the same lease; or reject a ClaimNow within a short LastFireAt window) — vs. accept it and document FireNow as best-effort-once (defensible: FireNow is a manual/rare trigger, and the per-process mutex covers the common single-replica case). Fine to defer to a follow-up if you go the doc route.
…nc semantics, fireMu inventory (#237) - schedule.proto: correct the schedule.* events comment from 'CLIENT-VISIBLE' to 'DURABLE-LOG-ONLY for v1' (pull-only via GetFire/ListFires; live broadcast is a future phase per ADR 0059 decision #8). The implementation was always log-only; the proto header contradicted it. - docs/usage.md: fix the broken curl example (unescaped apostrophe in 'today's' terminated the single-quoted shell string). Document FireNow as SYNCHRONOUS-TO-TERMINAL (it blocks until the run completes; the docs implied async polling). Note the client/proxy timeout requirement. - docs/adr/0027-cloud-native.md: add List 1 row 32 for the scheduler per-schedule-name fireMu mutex map (outlives-a-call in-memory resource; the AGENTS.md inventory discipline required it). Growth bounded by authenticated- caller schedule-name cardinality; lock-before-Load is load-bearing for the TOCTOU fence. Regenerated contracts/gen via task generate. Co-Authored-By: Juan Osorio Ortiz <[email protected]>
3456eda to
0371e91
Compare
…cron parse-once, docs, coverage (#232) Addresses the mechanical findings from the PR #237 review (the three decision-bearing findings — non-leader stand-down boot, singleton=false handling, FireNow cross-replica at-most-once — are raised as PR comments, not changed here): - Distinct ErrSchedulerNotRunning (FailedPrecondition/412): FireNow now distinguishes "no ScheduleStore" (ErrNoScheduleStore/501) from "store present but no in-process scheduler" instead of a misleading 501. - CreateSchedule parses the cron once: validateScheduleSpec returns the next-fire from the same parse that validates the grammar; CreateSchedule reuses it (UpdateSchedule discards it). Validation semantics unchanged. - schedule.proto: reworded the schedule.* event doc to match v1 delivery (durable-log-only via GetFire/ListFires, not client-visible); documented created_at as server-stamped/output-only. Regenerated contracts/gen. - ADR 0027 (cloud-native): inventoried Scheduler.fireMu (List 1) as a bounded, un-pruned per-schedule-name mutex. - Tests: F-1 regression (TestMakeFireFuncReleasesSessionLease — proves the fire's session lease is released so a lease-backed singleton does not wedge) + renewLeader/declareLeaderLost coverage (0%->70%/100%). Incidental: fixed a genuine pre-existing data race the new renewer tests exposed — Start wrote tickCtx/tickCancel/tickDone unguarded while the renewer's declareLeaderLost read tickCancel concurrently; all now guarded by the existing s.mu (verified under -race). Orthogonal to the excluded design decisions. Note: llms.txt regen (task docs:llms) is pending — network-blocked here; the ADR edit added no new links/headings so likely a no-op, but unverified. Co-Authored-By: Claude Opus 4.8 <[email protected]> (cherry picked from commit 3456eda)
|
Re-applied the mechanical review fixes as |
…nc semantics, fireMu inventory (#237) - schedule.proto: correct the schedule.* events comment from 'CLIENT-VISIBLE' to 'DURABLE-LOG-ONLY for v1' (pull-only via GetFire/ListFires; live broadcast is a future phase per ADR 0059 decision #8). The implementation was always log-only; the proto header contradicted it. - docs/usage.md: fix the broken curl example (unescaped apostrophe in 'today's' terminated the single-quoted shell string). Document FireNow as SYNCHRONOUS-TO-TERMINAL (it blocks until the run completes; the docs implied async polling). Note the client/proxy timeout requirement. - docs/adr/0027-cloud-native.md: add List 1 row 32 for the scheduler per-schedule-name fireMu mutex map (outlives-a-call in-memory resource; the AGENTS.md inventory discipline required it). Growth bounded by authenticated- caller schedule-name cardinality; lock-before-Load is load-bearing for the TOCTOU fence. Regenerated contracts/gen via task generate. Co-Authored-By: Juan Osorio Ortiz <[email protected]>
Summary
Implements Phase 2a of the scheduled-tasks feature (#189): the gRPC/HTTP
ScheduleServicewire surface over the Phase-1port.ScheduleStore, plus theEvSchedule*scheduler-lifecycle events.Phase 1 (PR #211) landed the durable foundation:
port.ScheduleStore+ mem/jsonl/redis adapters + the tick loop + leader-lease +FireFuncseam +--scheduler*flags. This PR exposes that registry over the wire so clients can manage schedules programmatically.Closes #232. Part of #189 (the umbrella). Design rationale frozen in ADR 0059.
What landed (5 commits)
06fbb52contracts/proto/mecatl/v1/schedule.proto(newScheduleService— 10 RPCs: Create/Get/List/Update/Delete/FireNow/Pause/Resume/GetFire/ListFires + messages mirroringport.Schedule*).harness.protoEvent field 15 (SchedulePayload, colocated to break the import cycle).engine/session/event.go—EvScheduleFired/Skipped/Failed(string-passthrough, no proto enum) +SchedulePayload+Event.Schedulefield.mapper.go—toProtoSchedule. api-compat gate.8a1ca6binternal/adapter/server/schedule.go—Service.scheduleStore()accessor +CreateSchedule(validateTriggerSpecXOR,cronparse.NextFire,Singleton=truedefault, read-leaning-mode rejection,MinIntervalfloor) + Update/Delete/Get/List/GetFire/ListFires/Pause/Resume/FireNow.port.ScheduleStore.ListFires+SetEnabled(the pause/resume primitive —Savepreserves State so it can't mutateEnabled).scheduler.fireClaimedfactored out offireOne(shared by tick loop + FireNow).FireNow(manual trigger: singleton check →ClaimNow→fireClaimed).EmitScheduleEventcallback onscheduler.Config(nil-safe; scheduler pkg stays EventSink-free).5f743a1grpc_schedule.go—ScheduleServer(embedsUnimplementedScheduleServiceServer) + all 10 handlers + proto↔port mappers.http.go— 10 RESTful routes under/v1/schedules....cmd/mecated/mecak8s/mecatui/embed—RegisterScheduleServiceServer.0344bd8port.ScheduleStore.ClaimNow(FireNow primitive — Claim minus theNextFireAt<=nowdue-check; fences onLastFireAt==nowfor at-most-once that is crash-recoverable). Conformanceclaim now bypasses due-checksubtest.schedule_e2e_test.go— offline e2e (Create cron/one-shot, bad-cron→InvalidArgument, past-one-shot→InvalidArgument, List, Get, Pause/Resume, FireNow→GetFire→ListFires, Delete idempotent, no-scheduler→Unimplemented). Docs: architecture.md, usage.md, PRODUCTION-READINESS.md, 0027-cloud-native.md (Phase 5 re-audit rows), IMPLEMENTATION-NOTES.md.5463109ErrScheduleExhausted(was 500/Internal → 412/FailedPrecondition).ErrFireNowOverlap412 on both surfaces.applyScheduleDefaultsshared by Create+Update (PUT omitting singleton no longer disables the guard).fireClaimedemitsEvScheduleFailedonStopError(not just Go errors). RedisSetEnabledatomic (Lua). Per-schedule-name mutex serializes concurrent FireNow + tick-loop fireOne (closes singleton TOCTOU). EvSchedule* docs corrected to durable-log-only for v1. HTTP handler test + EventLog assertion + cross-primitive Claim/ClaimNow conformance subtest.The 10 RPCs
CreateScheduleRequest{spec}→CreateScheduleResponse{schedule}POST /v1/schedulesGetScheduleRequest{name}→GetScheduleResponse{schedule}GET /v1/schedules/{name}ListSchedulesRequest{}→ListSchedulesResponse{schedules}GET /v1/schedulesUpdateScheduleRequest{spec}→UpdateScheduleResponse{schedule}PUT /v1/schedules/{name}DeleteScheduleRequest{name}→DeleteScheduleResponse{}DELETE /v1/schedules/{name}FireNowRequest{name}→FireNowResponse{fire_id, session_id}POST /v1/schedules/{name}/firePauseScheduleRequest{name}→PauseScheduleResponse{}POST /v1/schedules/{name}/pauseResumeScheduleRequest{name}→ResumeScheduleResponse{}POST /v1/schedules/{name}/resumeGetFireRequest{fire_id}→GetFireResponse{fire}GET /v1/schedules/{name}/fires/{id}ListFiresRequest{schedule_name}→ListFiresResponse{fires}GET /v1/schedules/{name}/firesEvSchedule* events
EvScheduleFired/EvScheduleSkipped/EvScheduleFailed— string-passthrough (no proto enum), emitted from composition (the scheduler) at fire time, NOT the loop. v1 delivery is durable-log-only: fired/failed events land in the fire session'sEventLog(pull viaGetFire/ListFires); skipped fires (no session) are operator-diag-only. A live broadcast stream is a future phase (matches ADR 0059 decision #8, "pull-only delivery v1").New port methods (api-compat gate, Added/minor)
port.ScheduleStore.ListFires(ctx, scheduleName) ([]ScheduleFire, error)— the list companion toLoadFire.port.ScheduleStore.SetEnabled(ctx, name, enabled) error— the pause/resume primitive (Savepreserves State on overwrite so it cannot mutateEnabled).port.ScheduleStore.ClaimNow(ctx, name, now, nextFire) (Schedule, error)— the FireNow primitive (Claimminus the due-check; fences onLastFireAt==nowfor at-most-once that is crash-recoverable).All three have conformance subtests across memschedulestore / jsonlstore / redisstore.
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 (new port methods + event types inengine/api/*.txt+engine/CHANGELOG.md)task generate—contracts/gen/regeneratedtask docs—llms.txtregenerated,matlatl check . --strict0 broken links/citations (137 docs, 1323 references)go run ./cmd/mecademo— full offline session (regression)internal/adapter/server/schedule_e2e_test.go) — Create (cron+one-shot, bad-cron, past-one-shot) → List → Get → Pause/Resume → FireNow → GetFire → ListFires → Delete, over jsonlstore + mockllm. HTTP handler test overhttptest. No-scheduler-wired → Unimplemented/501.Layering
engine/agentNEVER importsport.ScheduleStoreor any scheduler type. The RPC handlers, create-seam, cron validation, EvSchedule emission, and FireNow path all live in composition (internal/adapter/server+internal/adapter/scheduler+internal/app). The new events are inengine/session(domain) but emitted only from composition. The scheduler pkg staysEventSink-free (the emit callback is a plainfunc(session.SchedulePayload)).What's NOT in this PR (tracked follow-ups)
settings.yamlschedules:block (operator-tier) + CLI management + metricsmecatui/scheduleslash command + overlaysched--GC retention, NL→cron, carried-context, webhook triggers, driverScheduleStoreServiceCo-Authored-By
Juan Osorio Ortiz [email protected]