Repository navigation
cron: persist last_fired, append output to daily memory, post to channels - #79
Conversation
…nels
The cron scheduler used to be best-effort: a 2-minute look-back
window meant any downtime longer than that silently skipped jobs
(and restarts within the window double-fired them), and the unit's
docstring promised "write output to the memory store for the cron
session, and optionally post to a channel" — neither of which was
actually wired. Both are fixed here.
src/pkg/cron/PasClaw.Cron.State.pas
TCronState: load / save / GetLastFired / SetLastFired backed by
<home>/workspace/cron/state.json. Format is
{ "entries": [ { "id": "...", "last_fired": <unix-s> }, ... ] }
because TJsonObject doesn't expose key enumeration (an
array-of-objects shape uses ChildArray + ItemObject which are
already on the abstraction). Writes are atomic via temp + rename
so a crash mid-save leaves the previous state intact.
src/pkg/cron/PasClaw.Cron.Sinks.pas
AppendCronToDaily(Id, Skill, Output) appends a dated section to
workspace/memory/<today>.md so the FTS5 memory index picks it up
and BuildMemorySection auto-injects it on subsequent turns. Output
is truncated to MAX_CRON_OUTPUT_TO_MEMORY (2 KB) to keep daily
notes readable; the full string still goes to the gateway log.
PostCronToChannel(Kind, Target, Text) dispatches to the existing
outbound adapters (TDiscordWebhook, TSlackWebhook, TTeamsWebhook,
TGenericWebhook, TLinePush, TWhatsAppPush). Webhook-style kinds
take the URL as Target; LINE and WhatsApp pull their credentials
from the same env vars `pasclaw post` uses ($PASCLAW_LINE_TOKEN,
$PASCLAW_WHATSAPP_TOKEN, $PASCLAW_WHATSAPP_PHONE_ID). Each
failure logs warn and returns False so a Slack outage doesn't
block the memory write and vice versa.
src/pkg/cron/PasClaw.Cron.Scheduler.pas
RunOnce now anchors NextFireAfter on the persisted last-fired time
(or Now-60s for a brand-new entry — so a freshly-added cron
doesn't backfire for every minute of history). If a fire was
missed, NextFireAfter returns the earliest missed slot and we fire
exactly once; subsequent ticks catch up the rest. last_fired is
persisted regardless of skill success so a permanently-failing
job doesn't retry on every tick forever — fix the skill, the
next due slot fires.
After a successful fire RunOnce calls AppendCronToDaily and, if
the entry has a ChannelKind, PostCronToChannel.
src/pkg/config/PasClaw.Config.pas
TCronEntry gains ChannelKind + ChannelTarget. CronToJSON only emits
the new fields when non-empty so existing config.json files round-
trip byte-identical; the parser defaults both to '' so older
config.json reads as channel-disabled.
src/cmd/PasClaw.Cmd.Cron.pas
`pasclaw cron add` accepts an optional `--channel <kind>:<target>`
arg anywhere after the required positional args. Help text grows
the list of valid kinds. ColonPos <= 1 means "no kind before the
colon" — error out instead of silently storing a malformed entry.
src/pasclaw/PasClaw.dproj
DCCReference entries for the two new units.
README.md
Cron section gains channel-add examples and a paragraph explaining
the persistence + memory-write + channel-post behavior so users
know cron isn't best-effort anymore.
Verified locally:
make builds clean under FPC 3.2.2.
Standalone state smoke (7 cases: empty load, set, overwrite, save,
round-trip via a fresh instance) — all pass.
`pasclaw cron` help shows --channel; pre-existing
list/add/disable/enable/remove byte-identical otherwise.
https://claude.ai/code/session_01TBcLtmpj7dqA5tyFbGnQon
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 1d95035cc4
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
|
|
||
| { Persist last-fired regardless of skill success — we don't want | ||
| a permanently-failing job to retry on every tick forever. } | ||
| State.SetLastFired(Entry.Id, DateTimeToUnix(Now_)); |
There was a problem hiding this comment.
Record the fired slot instead of current time
When the scheduler has been down long enough to miss multiple scheduled slots, this stores Now_ as last_fired after running only the earliest missed Next slot. On the next tick NextFireAfter starts from the current time rather than from that fired slot, so all intervening missed runs are skipped instead of being caught up one per tick; e.g. an hourly job last fired yesterday will run once and then jump to today, dropping the rest of yesterday's slots.
Useful? React with 👍 / 👎.
| if FileExists(FPath) then DeleteFile(FPath); | ||
| if not RenameFile(Tmp, FPath) then |
There was a problem hiding this comment.
Preserve the old state until the replacement is installed
If the process crashes after DeleteFile(FPath) or if RenameFile fails after the delete, the existing state.json is lost and the next scheduler startup treats every cron entry as never fired. That can re-fire or skip jobs incorrectly after exactly the crash/failure scenario this state file is meant to survive; the replacement should be installed without removing the only durable copy first.
Useful? React with 👍 / 👎.
Two P2s on PR #79, both material: P2 #1: SetLastFired(DateTimeToUnix(Now_)) after firing the earliest missed slot means the next tick's NextFireAfter starts from "now" and walks forward to a FUTURE slot, silently dropping every intervening missed slot. Stamp the SLOT we just handled (Next) instead — now subsequent ticks find the next missed slot and fire it, one per tick, until caught up. This is the behaviour the PR description claimed in the first place. P2 #2: Save sequence was WriteFileText(Tmp); DeleteFile(FPath); RenameFile(Tmp,FPath); which opens a window where a crash (or rename failure) leaves neither FPath nor a recoverable copy — exactly the failure mode the state file was supposed to survive. Fix with a backup-file dance that keeps a known-good copy at every point: 1. WriteFileText(Tmp) 2. Clear stale .bak from a prior aborted save 3. RenameFile(FPath -> .bak) (skip if no current state) 4. RenameFile(Tmp -> FPath) 5. DeleteFile(.bak) If step 4 fails, restore .bak so the previous state survives. Load checks for .bak when FPath is missing and recovers from it, then promotes it back to the primary path so a future clean Save doesn't have to handle the .bak existing. No IFDEFs needed; works the same on POSIX rename (atomic) and Windows RenameFile (which fails on existing destination — the .bak clear in step 2 avoids that). Standalone recovery smoke covers the new paths: - normal save leaves no .bak (success path cleanup) - second save still no .bak (dance idempotent) - state.json absent + .bak present → Load recovers AND promotes - stale .bak from aborted save → cleared on next Save - round-trip survives the dance with the latest value 11 assertions, all pass. https://claude.ai/code/session_01TBcLtmpj7dqA5tyFbGnQon
The cron scheduler used to be best-effort: a 2-minute look-back window meant any downtime longer than that silently skipped jobs (and restarts within the window could double-fire them), and the unit's docstring promised "write output to the memory store for the cron session, and optionally post to a channel" — neither of which was actually wired. Both fixed here.
What landed
PasClaw.Cron.State—last_firedpersistenceTCronStateloads/saves a per-id map at$PASCLAW_HOME/workspace/cron/state.json:{ "entries": [ { "id": "daily-summary", "last_fired": 1700009999 }, { "id": "ping-discord", "last_fired": 1700010500 } ] }Atomic writes via temp + rename — a crash mid-save leaves the previous state intact rather than producing half-written JSON. Array-of-objects shape because
TJsonObjectdoesn't expose key enumeration; sticking withChildArray + ItemObjectkeeps it on the cross-target abstraction.PasClaw.Cron.Sinks— memory write + channel postAppendCronToDaily(Id, Skill, Output)workspace/memory/<today>.mdso the FTS5 memory index picks it up andBuildMemorySectionauto-injects it on subsequent turns. Truncated to 2 KB; the full string still goes to the gateway log.PostCronToChannel(Kind, Target, Text)TDiscordWebhook,TSlackWebhook,TTeamsWebhook,TGenericWebhook,TLinePush,TWhatsAppPush. Webhook-style kinds use the URL asTarget; LINE and WhatsApp pull their credentials from the same env varspasclaw postuses.Each failure logs warn and returns False so a Slack outage doesn't block the memory write and vice versa.
PasClaw.Cron.Scheduler— wired togetherRunOncenow anchorsNextFireAfteron the persisted last-fired time (orNow - 60sfor a brand-new entry — so a freshly-added cron doesn't backfire for every minute of history). If a fire was missed,NextFireAfterreturns the earliest missed slot and we fire exactly once; subsequent ticks catch up the rest.last_firedis persisted regardless of skill success so a permanently-failing job doesn't retry on every tick forever — fix the skill, the next due slot fires.After a successful fire
RunOncecallsAppendCronToDailyand, if the entry has aChannelKind,PostCronToChannel.TCronEntry+ CLICronToJSONonly emits the new fields when non-empty so existingconfig.jsonfiles round-trip byte-identical; the parser defaults both to''so older configs read as channel-disabled.Help text grows the list of valid kinds (
discord/slack/teams/webhook/line/whatsapp). Malformed--channelvalues (missing:separator) error out instead of silently storing a broken entry.Verification
make— clean build under FPC 3.2.2.pasclaw cronhelp shows--channel. Pre-existinglist / add / disable / enable / removebyte-identical otherwise.pasclaw --helpunchanged.Notable trade-offs
last_firedis per cron id, not per (id, slot). If you rename a cron, the new id starts cold (correct) but the old state file entry sticks around forever (small leak; cleaned by hand).https://claude.ai/code/session_01TBcLtmpj7dqA5tyFbGnQon
Generated by Claude Code