Skip to content

feat(core): append-only automation ledger — claim, fold, recovery (#578) - #605

Merged
ajianaz merged 4 commits into
developfrom
feat/ledger-core
Nov 11, 2026
Merged

ajianaz merged 4 commits into
developfrom
feat/ledger-core

Conversation

@ajianaz

@ajianaz ajianaz commented Nov 11, 2026 •

Copy link
Copy Markdown
Contributor

What

Second half of the automation ledger core (#578): crates/tole-core/src/ledger.rs, the append-only JSONL ledger the scheduler (#579) will run on — records, a pure fold, and ready / claim / block / settle / deliver / recover / record_hook. Pure and deterministic: now is passed in, liveness is an injected predicate, bytes go through a LedgerStore trait; no clock reads, threads, sleeps or locks inside.

Builds on #604 (the cron parser, merged); develop has been merged into this branch (merge commit, no force push), so the diff is the ledger only.

Why

Closes #578 together with #604 (epic #577). It makes the two Hermes failure classes structurally impossible (design docs/automation-design.md §2):

Changes

  • crates/tole-core/src/ledger.rs (new)
    • Records, one versioned JSON object per line ({"v":1,"kind":...}), unix seconds: job (core fields + a flattened host-owned map for feat(cron): tole cron CLI, cron tick, serve ticker, agent and script modes #579's name/prompt/mode/allow/budget; reserved keys refused), fire (fire_id, job_id, scheduled_for, claimed_at, lease), done (ok|error|cancelled|budget|awaiting_approval|interrupted, session_id, reason, usage), delivery (sent|failed|skipped, numbered attempts), missed (scheduled_for..last, count, reason), blocked ([a-z0-9_] reason code + detail), hook_seen.
    • Fold (LedgerState): later job with the same id supersedes; pause/resume/remove are new job records; first fire per (job_id, scheduled_for) and first done per fire win; everything else is keyed so re-appending a record is a no-op. Unknown kind → skipped and counted (forward compatibility); a known kind with a newer v → hard error (refuse to guess, like storage.rs); a torn or unparseable final line → discarded; a corrupt middle line → error with its byte offset.
    • claim: appends the missed range first, refuses an occurrence that is already claimed or accounted (AlreadyClaimed / AlreadyAccounted), appends fire, then re-reads and returns LostRace unless its own fire is the first in log order — so even two ticks that race past the host lock cannot both run. fire_id = <job>@<scheduled_for>/<pid>.<start_time>.
    • Catch-up: skip (default) runs only an occurrence at most 60 s late; one runs the latest occurrence if within grace_minutes (≤ one week). Older owed occurrences are superseded, too-late ones late. A job's at is when that version takes effect: only occurrences strictly after it are owed (so a resume does not replay the pause), and @every counts from it.
    • Re-saving an active job (edit, pause or removal) first appends whatever the previous version still owed up to the new at as a missed range with reason edited, computed under the previous schedule; an occurrence only seconds old at the edit is recorded the same way (visible, never silent). A paused or removed previous version owed nothing, so resume is unchanged. (Fix from review: before this, an edit silently erased owed occurrences.)
    • Validated on save (put_job): schedule (via feat(core): in-tree cron and @every schedule parser (#578) #604, including never-firing expressions), id charset, grace_minutes, time zone (only UTC/absent until feat(cron): explicit per-job time zones with pluggable sources #580; the timezone field is already in the format), reserved host keys.
    • Host contract (module docs): the host holds an exclusive lock around each mutating call (milliseconds, never around execution); mutating calls truncate a torn tail before appending (as storage.rs does on open), read-only open/refresh never truncate. Reads are incremental (read_from(offset)), so a tick costs only the new bytes.
    • MemoryStore (shared-buffer, for tests and embedders). No file adapter here: the session storage helpers are session-file specific (header, seq, writer lock), so a ledger file adapter would duplicate them; it lands with the host in feat(cron): tole cron CLI, cron tick, serve ticker, agent and script modes #579.
  • crates/tole-core/src/lib.rs: pub mod ledger; (one line).
  • crates/tole-core/tests/ledger_core.rs (new): lifecycle, concurrency, catch-up, edit accounting, pause/resume/remove, validation, recovery, forward-compat/torn tail, hooks, properties and crash injection (below).
  • crates/tole-core/tests/perf_threshold.rs + docs/perf.md: ledger fold/ready gate and numbers.
  • README.md status line and docs/epics.md Track E: ledger core landed; CLI and file adapter follow in feat(cron): tole cron CLI, cron tick, serve ticker, agent and script modes #579.

Testing

  • Crash injection (crash_at_every_append_boundary_loses_nothing_and_fires_once): a faulty store wraps the in-memory log and kills the writer at every append of a full tick (missed → fire → done → delivery) in three modes — nothing written, half a line written (torn), whole line written but no ack — 15 cases. A new process then runs recover + two fresh ready/claim/settle/deliver ticks. Asserted every time: every log line parses (torn tail repaired); no occurrence lost (each is exactly one of fired / missed, and the next occurrence runs); none fired twice (one fire line per occurrence); every fire settled exactly once; a done written before the crash keeps its status (never overwritten); a failed delivery leaves done.status = ok; no dangling claim.
  • Properties (seeded xorshift, no new dependency): fold is order-independent over 200 random record sets under shuffling and idempotent when the whole log is re-appended; 40 rounds × 200 random interleaved operations of three ledger instances on one store (stale Dues, settles, refreshes) never produce a double claim, and every fire line in the log is a won claim; a racing store that slips a competitor's fire in front of ours yields LostRace and only the winner is pending.
  • Edit accounting (review finding, red → green): editing_an_active_job_records_what_it_still_owed reproduces the review case (daily 0 9 * * * created day 0 08:00, host down until day 3 09:30, prompt edited a minute before the tick): the missed count must equal the no-edit control (4). On 782268a it was RED (no silent skip: left 0, right 4) and edit_accounting_uses_the_previous_version_only was RED too (left 0); with the fix both green. The second test also checks that editing a fresh job records nothing, that a schedule change accounts the old schedule (hourly → @daily: 3 occurrences), and that pausing an active job records what it owed while resuming records nothing more.
  • Teeth (broken-variant evidence):
    • Double claim: removing the claim/accounted checks in claim and the first-claim-wins rule in the fold → 5 tests red (claim_settle_deliver_lifecycle, claim_that_loses_a_race_past_the_lock_is_refused, fold_keeps_first_done_and_first_claim, concurrent_ticks_cannot_double_claim, random_interleaved_ticks_never_double_claim); restored → 13/13 green (before the 2 edit tests were added).
    • Done overwritten: removing the first-done-wins rule in the fold and the AlreadySettled pre-check in settle → 2 tests red (claim_settle_deliver_lifecycle, fold_keeps_first_done_and_first_claim); restored → 13/13 green.
  • Performance (ledger_fold_and_ready_under_budget, documented in docs/perf.md): fold of 100k records (10k jobs + 30k × fire/done/delivery) ~1.2–1.3 s in the unoptimized test build, ~220 ms in release (≈2.2 µs/record; 200k records ≈ 510 ms, linear); ready over 10k jobs ~16 ms unoptimized, ~6–8 ms release. Gate: fold < 30 s, ready < 2 s — ~20× over the unoptimized observation, meant to catch complexity regressions, not to race.
  • Binary size (cargo build --release -p tole-cli, Linux x86_64): origin/develop 64cca14 = 15,152,168 bytes; this branch (before the develop merge) = 15,152,296 bytes (+128 bytes; the CLI does not call the ledger yet, feat(cron): tole cron CLI, cron tick, serve ticker, agent and script modes #579 will).
  • On head 2aa22e8: cargo fmt --all — clean; cargo clippy --workspace --all-targets -- -D warnings — clean; cargo test --workspace — 1342 passed, 0 failed (ledger_core 15/15); cargo test -p tole-core --no-default-features — 450 passed, 0 failed; cora review --no-llm --base origin/develop (cora 0.20.0, deterministic rules) — no issues found. Perf after the fix: fold 1.33 s unoptimized, ready 17 ms (unchanged).

Known limits, by design for this phase: a done of awaiting_approval is terminal here; resuming an approved run (#581) will need an additive record kind rather than a second done. Retry policy after interrupted (retry_once) belongs to the host (#579). hook_seen exclusivity relies on the host lock (the run it triggers still goes through claim). hook_seen entries never expire, so the fold and memory grow with every webhook delivery; retention belongs with log rotation (open question 3 of docs/automation-design.md).

Part of the automation ledger core: 5-field cron with the Vixie/cronie
day-of-month/day-of-week rule, macros and @every durations, with
next-occurrence math and owed-occurrence spans. UTC only; zones follow
in #580. Malformed and never-firing expressions are rejected with a
precise reason. Property-tested against a minute-walking oracle.
Records job/fire/done/delivery/missed/blocked/hook_seen as versioned
JSONL lines; state is a pure fold. A fire is claimed before execution
and re-checked after the append, the first done per fire is final,
delivery never touches the run status, every skipped occurrence becomes
a missed record, and recover() interrupts only fires whose pid/start-time
lease is dead. Includes crash injection at every append boundary,
fold properties and a 100k-record perf gate.
@github-actions

github-actions Bot commented Nov 11, 2026 •

Copy link
Copy Markdown

🔍 Cora AI Code Review

✅ No issues found. Code looks good!


Review powered by cora-code · BYOK · MIT

)

put_job floors the owed window at the new version's at, so occurrences
the previous active version still owed vanished on an edit, pause or
removal. They are now appended first as a missed range with the new
reason edited, computed under the previous schedule. Resuming a paused
job still owes nothing for the paused period.
@ajianaz
ajianaz merged commit 13766c5 into develop Nov 11, 2026
19 of 20 checks passed
@ajianaz
ajianaz deleted the feat/ledger-core branch November 20, 2026 08:36
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

feat(core): append-only ledger core — claim, fold, recovery and cron parser

2 participants