Repository navigation
feat: scheduled tasks v2 finish — Create form, NL→cron, sched-- GC, one-shot retry, carried context (#189, #236) - #256
Conversation
… to cron (#236) Wave 1 of the scheduled-tasks v2 finish (#189 + #236). - cmd/mecatui/schedparse: a small stdlib-only NL-to-cron compiler (~10 regex patterns: "every 30 minutes" to star/30 cron, "daily at 9am", "every weekday at 9am", "next monday 3pm" one-shot, "in 2 hours" one-shot, "tomorrow at noon" one-shot). NOT a full NLP engine; unmatched input falls back to raw cron. - cmd/mecatui/ui/schedule.go: a scheduleCreate sub-view (peer of inspect/confirm) with fields for name, prompt, trigger (cron OR NL), workspace, and a mutating toggle. The c action key opens it; tab/arrows cycle focus; enter submits via CreateScheduleCmd. The trigger field runs schedparse.Compile first, falling back to raw cron. - Tests: form open/submit/cancel, NL trigger compilation, validation. - Docs: PRODUCTION-READINESS.md flips Phase 3b to shipped; tui.md adds the Create form and NL trigger documentation.
Wave 2 of the scheduled-tasks v2 finish (#189 + #236). Lands ADR 0059 decision #7 Phase-2 caveat: fire sessions now carry a sched-- prefixed id (minted via a WithSessionID override on CreateSessionWithProfile) and are GC'd on their own retention schedule distinct from normal session retention. - internal/adapter/server/service.go: CreateSessionOption variadic options pattern (WithSessionID). Zero opts is byte-identical to the old signature; all existing callers compile unchanged. Override validates non-empty + no collision with a live session. - internal/app/scheduler_fire.go: makeFireFunc pre-mints the sched-- id via newFireID and passes it as the session-id override. Success path carries the sched-- id as both fire ID and session ID (decision #7). - internal/app/childgc.go: scheduleFireRetention GC family. A new scheduleFireSessionPrefixes partition (sched--) so per-fire sessions are swept by the schedule-fire age pass, NOT the main or child pass. sweepScheduleFires (peer of sweepMain: oldest-first, live-skip). - internal/app/build.go: Config.ScheduleFireRetention; cmd/mecated + cmd/mecak8s: --schedule-fire-retention flag (default 7d when scheduling is on; 0 = disabled). - Tests: session-id override unit tests; GC partition invariants; e2e asserts the fire session id starts with sched--. - Docs: ADR 0059 Phase-2 update note; PRODUCTION-READINESS, architecture, implementation-notes, usage updated; llms.txt regenerated.
…236) Wave 3 of the scheduled-tasks v2 finish (#189 + #236). Two opt-in ScheduleSpec fields that address ADR 0059 consequences: One-shot crash-loss retry: - engine/port/schedule.go: ScheduleSpec.OneShotRetry + OneShotMaxRetries, ScheduleState.OneShotRetryCount, the optional ScheduleOneShotReArmer interface (type-asserted on the store, like PrunableStore — not a ScheduleStore method, so existing implementers stay compliant). Rejected on cron triggers (a cron self-heals via misfire). - internal/adapter/scheduler/scheduler.go: maybeReArmOneShots scans for disabled one-shots with OneShotRetry=true whose prior fire crashed (LastFireSessionID==pending or LoadFire returns StopError) and re-arms them up to OneShotMaxRetries via ReArmOneShot (atomic re-enable + NextFireAt advance + retry-count increment). - All three store adapters implement ReArmOneShot; conformance suite has the atomicity sub-test. Carried-context toggle: - engine/port/schedule.go: ScheduleSpec.CarryContext (default false = fresh per fire, unchanged). - internal/app/scheduler_fire.go: when CarryContext is true, the fire path loads the prior fire's session and renders its conversation as a FENCED untrusted preamble (via agent.FenceUntrusted + NeutraliseFraming), prepended to the fire's prompt. NOT seeded history — carried context is untrusted (a prior fire may have been prompt-injected) and must not become live instructions. A re-armed one-shot does NOT carry context on the retry. API-compat gate: task api:update + engine/CHANGELOG.md (Added = minor). Proto: task generate (new optional fields on ScheduleSpec/ScheduleState). Tests: 5 re-arm tests (pending crash, StopError, no-retry, budget exhausted, no-interface degradation); 3 carried-context tests (fence rendering, forged-fence neutralisation, disabled-by-default). Docs: ADR 0059 Phase-2 amendment notes; PRODUCTION-READINESS, architecture, implementation-notes, usage updated; llms.txt regenerated.
jhrozek
left a comment
There was a problem hiding this comment.
PR #256 review — scheduled tasks v2 finish (3 waves)
Reviewed as three independent waves (one review agent per commit). Summary of findings below; details inline.
Verdicts
| Wave | Commit | Verdict | Key issue |
|---|---|---|---|
| 1 — TUI Create form + NL→cron | 5a5af50d |
REQUEST CHANGES | Create failures silently dropped (no user feedback) |
| 2 — sched-- GC retention | 87998a8b |
REQUEST CHANGES | TOCTOU + no-op collision check on shared-engine fast path |
| 3 — one-shot retry + carried context | 1ceeb752 |
REQUEST CHANGES | Re-arm scan skipped when no schedule is due (stall in quiet deployments) |
What passed clean
- Carried-context security fencing (Wave 3):
FenceUntrusted+NeutraliseFramingcorrectly applied; prior fire conversation can't become live instructions; re-armed one-shots don't carry context. ✓ - API-compat gate (Wave 3):
port.txt+CHANGELOG.mdreflect new exports as Added/minor;ScheduleOneShotReArmeris optional/type-asserted. ✓ - Re-arm atomicity (Wave 3): mutex (mem/jsonl), EVAL script (redis), conformance suite under
-race. ✓ - Layering (all waves): no domain package imports adapters/os/proto/gRPC. ✓
- Backward compat of
CreateSessionOptionvariadic pattern (Wave 2): zero opts is byte-identical. ✓ - No secret-scrubbing or permission-boundary regressions. ✓
Priority order for fixes
- Re-arm stall (Wave 3) — one-line move + test
- Collision check TOCTOU + fast-path no-op (Wave 2) — move check into registration lock
- Silent Create failure + test (Wave 1) — small, localized
- Minor/nit items as time allows
Note:
llms.txtappears unchanged despitedocs/tui.md+PRODUCTION-READINESS.mdedits — CI docs job may fail. Runtask docs:llms.
| // nothing of re-arm — it only fires what Claim advanced). A store that does | ||
| // not implement ScheduleOneShotReArmer degrades to at-most-once | ||
| // (byte-identical pre-Phase-2). | ||
| s.maybeReArmOneShots(ctx, now) |
There was a problem hiding this comment.
Major — re-arm stall in quiet deployments.
maybeReArmOneShots is called here at line 559, after the len(due) == 0 early return at line 520. This means: on any tick where nothing is due, the crashed-one-shot re-arm scan never runs. In a quiet deployment whose only schedules are one-shots, a crashed one-shot that needs re-arming will sit disabled indefinitely until some OTHER schedule happens to become due — a chicken-and-egg stall.
The tests only pass because they seed a "sparker" cron to force len(due) > 0. In production, a one-shot-only setup has no such sparker.
Fix: Move this call before the len(due) == 0 early return:
| s.maybeReArmOneShots(ctx, now) | |
| // One-shot crash-loss re-arm runs on EVERY tick, not only when work is due — | |
| // a quiet one-shot-only deployment must still re-arm a crashed one-shot even | |
| // when nothing is currently due (ADR 0059 Phase 2). | |
| s.maybeReArmOneShots(ctx, now) |
And add a test that exercises re-arm on a tick with zero due schedules (no sparker).
| // e.g. paused). Not a re-arm candidate. | ||
| return false | ||
| } | ||
| fire, err := s.cfg.Store.LoadFire(context.Background(), string(sched.State.LastFireSessionID)) |
There was a problem hiding this comment.
Minor — LoadFire uses context.Background() instead of the tick ctx.
Every other store call in the tick loop uses the passed ctx (or gctx). Using context.Background() here is unbounded — if the store backend hangs on LoadFire, a Stop() (which cancels the tick ctx) cannot interrupt this probe, so the re-arm scan (and thus tickOnce) can block past shutdown.
The isPriorFireLive path explicitly bounds its probe with singletonTrialTimeout for the same reason. This probe should be similarly bounded.
Fix: Thread the tick ctx through shouldReArmOneShot, or wrap the probe in a bounded context.WithTimeout.
| if opts.id != "" { | ||
| s.mu.Lock() | ||
| _, collision := s.sessionEngines[opts.id] | ||
| s.mu.Unlock() |
There was a problem hiding this comment.
Major — TOCTOU in the WithSessionID collision check.
The collision check acquires s.mu, reads sessionEngines[opts.id], and releases the lock at line 997 before the session is actually registered (registration happens at line 1062 under a separate lock acquisition, with the potentially-slow MCP-connecting factory call at line 1033 in between).
Two concurrent CreateSessionWithProfile calls with the same WithSessionID can both pass this check and both proceed. On the per-session path, both register under the same key (the second overwrites the first's sessionEngine, leaking its closeFn).
The comment at line 991-992 ("The collision check is under the SAME lock as the later registration so it races cleanly") is false — they are different lock acquisitions.
The scheduler's newFireID random suffix makes scheduler-vs-scheduler collision astronomically unlikely, but WithSessionID is a general API and the safety claim is incorrect.
Fix: Move the collision check INTO the registration lock at line 1051 — do the _, collision := s.sessionEngines[opts.id] check atomically with the insert at line 1062. At minimum, correct the misleading comment.
| sess := session.New(s.cfg.NewID(), mode, workspace, limits, s.cfg.Now()) | ||
| sess := session.New(mintID(), mode, workspace, limits, s.cfg.Now()) | ||
| setSessionLabels(sess, sel, profile) | ||
| if err := s.cfg.Store.Save(ctx, sess); err != nil { |
There was a problem hiding this comment.
Major — collision check is a no-op on the shared-engine fast path.
When !needPerSession (line 1005 — empty selector, default profile, workspace == DefaultWorkspace, a common schedule configuration), the session is saved to the store here at line 1012 but never enters sessionEngines. So the sessionEngines[opts.id] collision check at line 996 sees nothing even for a session that was just created and persisted under that id.
The test TestCreateSessionWithSessionIDCollisionRejected only exercises the per-session path (it sets a non-zero ProviderSelector to force needPerSession). A collision against a shared-engine session goes undetected.
This is the same root cause as the TOCTOU above. Fix: Reserve the id under s.mu regardless of path (e.g., a placeholder in sessionEngines or a dedicated reservedIDs set), or check the store via Load which is heavier but correct.
| // Return to the panel; the ScheduleMsg reducer appends the new row. | ||
| m.schedule.view = schedulePanel | ||
| m.schedule.form = scheduleForm{} | ||
| return m, client.CreateScheduleCmd(m.deps.Ctx, m.deps.Sched, spec), true |
There was a problem hiding this comment.
Blocker — Create failure silently dropped (no user feedback).
This CreateScheduleCmd returns a client.ScheduleMsg. But the ScheduleMsg handler in updateScheduleMsg (around line 519-521) does this on error:
case client.ScheduleMsg:
if msg.Err != nil {
return m, nil, true // ← error silently discarded
}ScheduleActionMsg at line 554 correctly sets m.schedule.actionErr = msg.Err.Error(), but ScheduleMsg does not. When the server rejects a bad cron expression, duplicate name, or any other validation error, the user sees the form close and the panel return — but the schedule was never created, with no error indicator.
Fix: In the ScheduleMsg error handler, surface the error (consistent with ScheduleActionMsg):
if msg.Err != nil {
m.schedule.actionErr = msg.Err.Error()
return m, nil, true
}Also: schedule_test.go only exercises the success path — add a test that sets a server error and asserts it surfaces.
| b.WriteString("\n") | ||
| } | ||
| // Clamp to the rune budget. | ||
| if b.Len() > carriedContextMaxRunes { |
There was a problem hiding this comment.
Minor — byte vs rune budget check inconsistency.
The in-loop early-exit at line 276 uses b.Len() (bytes), but carriedContextMaxRunes (line 221) is semantically a rune count and the final clamp at line 285 (clampRunes) counts runes. For multi-byte content (e.g., UTF-8 text from a prior fire in a non-ASCII language) this lets the loop overshoot the intended budget by up to one message before the final rune-based clamp corrects it.
Not a security issue (the final clamp + fence still bound the output), just an imprecise bound. Fix: Compare rune count, or just rely on the final clampRunes and drop the in-loop check.
| // It is pre-minted on the fire path (ADR 0059 decision #7 Phase-2) and passed | ||
| // as the WithSessionID override to CreateSessionWithProfile, so the fire's | ||
| // persisted session carries the "sched--" prefix the GC retention sweep | ||
| // (ScheduleFireRetention) partitions on — and the fire id IS the session id. |
There was a problem hiding this comment.
Nit — newFireID embeds the schedule name unsanitized.
newFireID formats "sched--<name>-<UTC compact>-<randhex>" and schedule names are only validated for non-empty. A name with /, spaces, or newlines lands in the session id. The store's safeName neutralizes path traversal (no security hole), and the GC decodes the real id back from the snapshot (partition holds), but a name like "nightly\n" would produce a multi-line fire id in logs/LastFireSessionID.
Fix: Either sanitize the name in newFireID (collapse control/slash runes) or add a charset constraint to validateScheduleSpec.
| // Schedule-fire (top-level "sched--") sweep (ADR 0059 decision #7 Phase-2). | ||
| // A disabled schedule-fire policy makes this a no-op, so a "sched--" session | ||
| // is never touched unless the operator turned the schedule-fire pass on. | ||
| fireDeleted := g.sweepScheduleFires(ctx, fires, &errs) |
There was a problem hiding this comment.
Minor — sweepScheduleFires has no count cap, unlike sweepMain.
sweepMain has both an age pass AND a mainMaxTotal count cap (issue #79) to bound the head — a burst of sessions within the retention window can't grow the store without limit. sweepScheduleFires (line 215) has only the age pass.
A cron firing every minute → 10,080 sessions/week at 7d retention. The age horizon bounds the tail but not the head. This is a product decision, not a bug, but worth confirming it's intentional. A --schedule-fire-retention-max-total flag (peer of --main-retention-max-total) would be the symmetric completion, or document the omission as a Phase-2 deferral in the ADR.
Resolves the CHANGES_REQUESTED review on the scheduled-tasks v2 finish,
plus the follow-on review panel's confirmed findings.
Reviewer findings:
- scheduler: run the one-shot crash-loss re-arm scan on EVERY tick, before
the len(due)==0 early return, so a quiet one-shot-only deployment (no due
cron to "spark" the tick) still re-arms a crashed one-shot; bound the
LoadFire probe with the tick ctx (singletonTrialTimeout) instead of
context.Background().
- mecatui: surface a failed schedule Create (bad cron / duplicate name /
validation error) via actionErr instead of silently closing the form.
- server: fix the WithSessionID collision check — a reservedIDs in-flight
set + a store Load probe close the TOCTOU and the shared-engine fast-path
no-op; reject WithSessionID("") per its documented contract.
- scheduler_fire: rune-accurate carried-context budget; sanitize the
schedule name embedded in the fire/session id (control/slash/space runes).
- childgc: add the symmetric --schedule-fire-retention-max-total count cap
(peer of --main-retention-max-total) so a high-frequency cron cannot grow
the store's head unbounded within the age horizon.
Review-panel findings:
- childgc: collapse sweepFamily/sweepMain/sweepScheduleFires into one
sweepPartition helper (the hand-copied cap pass was the drift class the
extraction prevents); modernize the comparator to slices.SortStableFunc.
- server: guard CreateSchedule against a duplicate name (Save is upsert-by-
name; a Create must not silently clobber an existing task).
- tests: de-vacuum the carried-context rune-budget test (lower-bound
assertion), add a concurrent-create TOCTOU test under -race, add a
Load-probe infra-fault propagation test, add a duplicate-name test.
- accurate "already in use" collision message; align actionErr terminal
sanitization across both sinks; de-reference ephemeral review comments.
task build / lint / test (root + engine + engine-standalone) / api:check /
docs all green; go run ./cmd/mecademo prints a full offline session.
Co-Authored-By: Claude Opus 4.8 <[email protected]>
Claude-Session: https://claude.ai/code/session_01B4zezZnJF9NyFf7KYxu6E9
|
Thanks for the thorough review, @jhrozek. All findings addressed in 6bf8aa1, plus a follow-on review panel that caught a couple of extra items. Details below. Review findingsWave 3 — one-shot retry / carried context
Wave 2 —
Wave 1 — TUI Create form
Extra items from the review panel
|
jhrozek
left a comment
There was a problem hiding this comment.
All 8 findings from my prior review addressed in 6bf8aa1 — verified independently against the code (not just the summary) plus go test -race on every touched package (scheduler, server, app, mecatui/ui): all green.
- Re-arm stall,
LoadFireunbounded ctx, byte/rune budget mismatch, unsanitized fire-ID name (Wave 3) - TOCTOU + shared-engine-fast-path collision no-op (Wave 2 Majors)
sweepScheduleFiresmissing count cap (Wave 2)- TUI Create-failure silently dropped (Wave 1 blocker)
Spot-checked the 4 extra items from your own review panel (sweepPartition dedup, vacuous-test fix, duplicate-name rejection, empty-WithSessionID rejection) — all present and reasonable.
Approving.
Resolves the CHANGES_REQUESTED review on the scheduled-tasks v2 finish,
plus the follow-on review panel's confirmed findings.
Reviewer findings:
- scheduler: run the one-shot crash-loss re-arm scan on EVERY tick, before
the len(due)==0 early return, so a quiet one-shot-only deployment (no due
cron to "spark" the tick) still re-arms a crashed one-shot; bound the
LoadFire probe with the tick ctx (singletonTrialTimeout) instead of
context.Background().
- mecatui: surface a failed schedule Create (bad cron / duplicate name /
validation error) via actionErr instead of silently closing the form.
- server: fix the WithSessionID collision check — a reservedIDs in-flight
set + a store Load probe close the TOCTOU and the shared-engine fast-path
no-op; reject WithSessionID("") per its documented contract.
- scheduler_fire: rune-accurate carried-context budget; sanitize the
schedule name embedded in the fire/session id (control/slash/space runes).
- childgc: add the symmetric --schedule-fire-retention-max-total count cap
(peer of --main-retention-max-total) so a high-frequency cron cannot grow
the store's head unbounded within the age horizon.
Review-panel findings:
- childgc: collapse sweepFamily/sweepMain/sweepScheduleFires into one
sweepPartition helper (the hand-copied cap pass was the drift class the
extraction prevents); modernize the comparator to slices.SortStableFunc.
- server: guard CreateSchedule against a duplicate name (Save is upsert-by-
name; a Create must not silently clobber an existing task).
- tests: de-vacuum the carried-context rune-budget test (lower-bound
assertion), add a concurrent-create TOCTOU test under -race, add a
Load-probe infra-fault propagation test, add a duplicate-name test.
- accurate "already in use" collision message; align actionErr terminal
sanitization across both sinks; de-reference ephemeral review comments.
task build / lint / test (root + engine + engine-standalone) / api:check /
docs all green; go run ./cmd/mecademo prints a full offline session.
Co-Authored-By: Claude Opus 4.8 <[email protected]>
Claude-Session: https://claude.ai/code/session_01B4zezZnJF9NyFf7KYxu6E9
Summary
Finishes the scheduled-tasks feature (#189 + #236). All v1 phases (#231–235) shipped previously; this PR lands the remaining v2 items from #236 and closes the umbrella.
What's in this PR
Three dev-pipeline waves, one commit per wave:
Wave 1 — mecatui in-overlay Create form + NL→cron (Phase 3b)
cmd/mecatui/schedparse— a small stdlib-only NL→cron compiler (~10 regex patterns: "every 30 minutes", "daily at 9am", "every weekday at 9am", "next monday 3pm", "in 2 hours", "tomorrow at noon"). NOT a full NLP engine; unmatched input falls back to raw cron.cmd/mecatui/ui/schedule.go— ascheduleCreatesub-view (peer of inspect/confirm) with fields for name, prompt, trigger (cron OR NL), workspace, and a mutating toggle. Thecaction key opens it; tab/↑↓ cycle focus; enter submits viaCreateScheduleCmd.⛔ Phase 3bPRODUCTION-READINESS row to ✅ shipped.Wave 2 —
sched--GC retention familyinternal/adapter/server/service.go—CreateSessionOptionvariadic options pattern (WithSessionID). Zero opts is byte-identical; all existing callers compile unchanged.internal/app/scheduler_fire.go—makeFireFuncpre-mints thesched--id vianewFireIDand passes it as the session-id override. Success path carries thesched--id as both fire ID and session ID (ADR 0059 decision ACP: accept client-provided streaming-HTTP MCP servers #7 Phase-2 caveat, now landed).internal/app/childgc.go—scheduleFireRetentionGC family. A newsched--prefix partition so per-fire sessions are swept by the schedule-fire age pass, NOT the main or child pass.--schedule-fire-retentionflag (default 7d; 0 = disabled).sched--.Wave 3 — One-shot crash-loss retry + carried-context toggle
ScheduleSpec.OneShotRetry+OneShotMaxRetries+ScheduleState.OneShotRetryCount+ optionalScheduleOneShotReArmerinterface): an opt-in at-least-once retry for one-shots that cannot tolerate the at-most-once crash-loss trade-off. The tick loop re-arms a crashed one-shot (prior fire ended inStopErrororLastFireSessionID == PendingFireSessionID) up toOneShotMaxRetriesvia the atomicReArmOneShot. Rejected on cron triggers.ScheduleSpec.CarryContext): an opt-in toggle that renders the prior fire's conversation as a FENCED untrusted preamble (viaagent.FenceUntrusted+NeutraliseFraming), prepended to the fire's prompt. NOT seeded history — carried context is untrusted (a prior fire may have been prompt-injected) and must not become live instructions. A re-armed one-shot does NOT carry context on the retry.task api:update+engine/CHANGELOG.md(Added = minor). Proto:task generate.What's NOT in this PR (spun to focused follow-up issues)
The remaining #236 v2 items are each genuinely full features that would produce shallow implementations if rushed:
ScheduleStoreService— a mechanical mirror of the existing driver stores, but deferred to keep this PR reviewable.context_from-style chaining — depends on carried-context (shipped here); thin layer but deserves its own design.These will be filed as focused follow-up issues.
Verification
task build✅task lint✅ (0 issues)task test✅ (full offline suite, root + engine module + engine-standalone)task api:check✅task docs:check✅ (0 broken links/anchors/orphans)go run ./cmd/mecademo✅ (full offline session)Closes #236. Closes #189.