Skip to content

fix(schedule): warm followers before leadership handoff - #312

Closed
loks0n wants to merge 5 commits into
mainfrom
codex/schedule-warm-followers
Closed

loks0n wants to merge 5 commits into
mainfrom
codex/schedule-warm-followers

Conversation

@loks0n

@loks0n loks0n commented Sep 21, 2026 •

Copy link
Copy Markdown
Contributor

A replacement scheduler currently waits for leadership before loading its source. If loading takes several minutes, a surge rollout still stops dispatch during takeover and can exceed the recovery window.

Reconcile on every replica before attempting leadership, keeping followers prepared while the leader dispatches. Add isReady() for completed initial loading (using the existing reconciliation cursor), leave the claim untouched when initial loading fails, and rebase a follower's pending discovery coverage against the predecessor's committed source view so takeover does not replay changes already delivered.

Document how applications can use readiness with a shared Redis store, graceful shutdown, and a surge rollout. The application still needs to expose readiness, monitor dispatch progress separately, and wire termination signals. Readiness stays true after initialization even if a later refresh fails, matching the existing last-good-view behavior. Delivery remains at-least-once; follower reads add source load, and slow reconciliation still pauses an active leader's own loop. Kubernetes rollout behavior needs an application-level staging drill; this PR tests the library handoff only.

Validation:

  • bin/monorepo check schedule --fix: Pint, PHPStan, and Rector passed.
  • bin/monorepo test schedule: 100 unit tests / 256 assertions and 10 real-Redis tests / 96 assertions passed.
  • bin/monorepo validate and vale packages/schedule/README.md passed.
  • New Redis regression drives two scheduler loops with Fibers and a deterministic clock through a six-minute follower load, continued leader delivery, follower refresh, and graceful handoff. Existing tests cover lease-expiry takeover and concurrent process contention.
  • Observed the regression fail with the original loop because the follower never became ready. Removing only the takeover rebase also fails, with an extra replayed occurrence.

A takeover regression also proves a late-discovered one-shot is recovered when the predecessor advanced coverage using an older source view. This failed with the simplified clear-only rebase and passes when takeover recomputes coverage from the retained effective timestamp.

Pending backdated replacements retain their coverage across takeover until committed. A regression covers the missed replacement one-shot, and failed-initialization coverage verifies another scheduler can deliver against the shared store without asserting claim representation.

@loks0n loks0n self-assigned this Sep 21, 2026
@github-actions

github-actions Bot commented Sep 21, 2026 •

Copy link
Copy Markdown

Benchmark results

schedule — dispatch and reconcile at scale (4 cores, 10000 schedules: 30% cron / 70% interval, 30 ticks)

stage scale p50 ms max ms
reconcile: full snapshot, cold (every row made) 10000 rows 54.94 54.94
reconcile: full snapshot, warm (version diff) 10000 rows 1.57 3.79
tick + commit (one minute of coverage) 10000 schedules 48.60 62.68
cron next occurrence: leap-day expression 1000 windows 136.30 136.30

115680 occurrences dispatched, 3856 per tick average. Selecting one minute of coverage spends 0.081% of the 60s tick interval.

Shared CI runners — treat absolute numbers as rough, compare modes within a run. Commit d3500f2.

@greptile-apps

greptile-apps Bot commented Sep 21, 2026 •

Copy link
Copy Markdown
Contributor

RetriggerConfidence Score: 4/5

The PR is not yet safe to merge because the outstanding takeover path can replay replacement occurrences already committed by the predecessor.

Fix All in Claude CodeFindings

  1. P1 Takeover replays replacements ▶
Fix with agent prompt
### Issue 1
packages/schedule/src/Scheduler.php:undefined-780
When both replicas load the same replacement before handoff, the follower keeps `replaced=true` even after the leader dispatches and commits that replacement. During takeover, this makes the follower ignore the predecessor's committed `syncedUntil` and restore coverage from `activeFrom`, so it can deliver the replacement's occurrences again. The rebase must distinguish replacements already covered by the predecessor from replacements seen only by the follower.

---

For each issue above, determine whether it is valid and should be fixed. If so, fix it directly.

Summary

Adds follower-side schedule warming and readiness reporting so replacement replicas can reconcile before attempting leadership.

  • Reorders the scheduler loop to reconcile before election and prevents an unsuccessful initial load from claiming or advancing shared coverage.
  • Retains effective-time and replacement metadata to rebase discovery coverage during takeover.
  • Adds readiness, reconciliation, and Redis handoff regressions.
  • Documents Redis-backed rolling replacements, graceful shutdown, source-load costs, at-least-once delivery, and replacement replay risk.
sequenceDiagram
    participant L as Current leader
    participant S as Schedule source
    participant R as Shared Redis store
    participant F as Warm follower
    L->>S: Reconcile
    L->>R: Hold claim and commit coverage
    L-->>L: Dispatch occurrences
    F->>S: Reconcile before election
    F-->>F: Report ready after initial load
    L->>R: Release or lose claim
    F->>R: Acquire claim and read committed source view
    F-->>F: Rebase pending discovery coverage
    F-->>F: Resume dispatch
Loading

Reviews (5) · Last reviewed commit: "docs(schedule): clarify replacement repl..."

Comment thread packages/schedule/src/Scheduler.php Resolved
Comment thread packages/schedule/src/Scheduler.php Resolved
Comment thread packages/schedule/src/Scheduler.php Resolved
if ($syncedUntil !== null) {
$seen = $this->moment($syncedUntil);
foreach ($this->entries as &$entry) {
$entry['coverFrom'] = $this->coverFrom($entry['activeFrom'], $seen, $entry['replaced']);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Takeover replays replacements

When both replicas load the same replacement before handoff, the follower keeps replaced=true even after the leader dispatches and commits that replacement. During takeover, this makes the follower ignore the predecessor's committed syncedUntil and restore coverage from activeFrom, so it can deliver the replacement's occurrences again. The rebase must distinguish replacements already covered by the predecessor from replacements seen only by the follower.

Knowledge Base Used: Scheduling and email delivery

Prompt To Fix With AI
This is a comment left during a code review.
Path: packages/schedule/src/Scheduler.php
Line: 780

Comment:
**Takeover replays replacements**

When both replicas load the same replacement before handoff, the follower keeps `replaced=true` even after the leader dispatches and commits that replacement. During takeover, this makes the follower ignore the predecessor's committed `syncedUntil` and restore coverage from `activeFrom`, so it can deliver the replacement's occurrences again. The rebase must distinguish replacements already covered by the predecessor from replacements seen only by the follower.

**Knowledge Base Used:** [Scheduling and email delivery](https://app.greptile.com/appwrite/-/custom-context/knowledge-base/utopia-php/monorepo/-/docs/scheduling-email-delivery.md)

---

For each issue above, determine whether it is valid and should be fixed. If so, fix it directly.

Fix in Claude Code Fix in Codex

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The replay is reproducible, but treating it as a merge-blocking correctness defect requires a stronger guarantee than this library provides. Scheduler and Occurrence::key() explicitly promise at-least-once delivery across handoff, not exactly-once delivery.

I ran the same two-scheduler reproduction twice: both load v1 at 03:00:30, then read at 03:01:00 around a backdated v2 update (active from 03:00:20, due 03:00:45). The follower sees v2 in both runs; the leader sees v1 in one run and v2 in the other. Snapshot reads starting at the same time need not observe the same side of an update.

Both runs produce exactly the same shared claim: coveredUntil=03:01:00 and syncedUntil=03:01:00 (same token and expiry too). In the first run the leader delivers nothing; in the second it delivers [email protected]. After lease expiry the follower delivers that same key in both runs, then commits and does not replay on the next tick.

The successor therefore cannot distinguish these cases from the shared watermark. Suppressing the second run's duplicate also suppresses the first run's required recovery. Retaining pending replacement coverage deliberately favors duplicates over silent loss, consistent with the existing contract. Distinguishing them would need durable per-definition coverage or a stronger source revision protocol, a separate API/storage change outside this rollout fix.

Documented this specific handoff limitation in 7bd8cd2. Keeping the conservative behavior; consumers use the stable occurrence key for deduplication. Please reassess the P1 against the at-least-once contract.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You're right. Given the explicit at-least-once contract, this is not a merge-blocking correctness defect. The two executions are observationally indistinguishable from the shared claim, so suppressing the replay would also risk suppressing the only delivery; retaining pending replacement coverage is the correct conservative choice. The replay is an expected handoff limitation, and Occurrence::key() gives consumers the intended deduplication mechanism. With the limitation documented, I withdraw the P1.

@ChiragAgg5k

Copy link
Copy Markdown
Member

packages/schedule now lives in appwrite/appwrite; ported as appwrite/appwrite#13913. Thanks!

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.

2 participants