Skip to content

fix(scheduler): a restart keeps following the runs that were in flight (#4410) - #4807

Open
dolho wants to merge 1 commit into
devfrom
fix/4410-scheduler-restart-inflight
Open

dolho wants to merge 1 commit into
devfrom
fix/4410-scheduler-restart-inflight

Conversation

@dolho

@dolho dolho commented Nov 27, 2026

Copy link
Copy Markdown
Contributor

Summary

The scheduler follows each run it starts with an in-process poll task. That task publishes the completion event and applies retry (RETRY-001) and validation (VALIDATE-001). Shutdown cancelled the task and boot recovered pending retries and reminders only, so a run in flight across a restart got none of the three.

Change

  • _spawn_poll records the run in the Redis hash scheduler:followed_executions (execution id → agent name and poll budget) before the poll starts.
  • A poll that ends on its own removes its entry. A poll cancelled by shutdown, or lost to a kill, leaves it.
  • initialize() calls _recover_followed_executions(), which starts a poll again for every recorded run. A run that reached its terminal while the scheduler was down is handled on the poll's first read.
  • The same step also reads running / queued rows a cron fire or a retry created (get_inflight_scheduled_executions()). This covers a lost Redis record and the first boot after this change.
  • A row already pending_retry is dropped from the record: its retry is decided and _recover_pending_retries() owns it.

Choices a reviewer may want to question

  • The record is in Redis, not in a new column. It needed no migration on either track. The database read covers runs still going if the record is lost; what is lost with it is only a run that both ended during the downtime and had its record wiped.
  • The database fallback takes schedule and retry rows only. Nothing says the scheduler was following a manual, webhook, reminder or validation row, and following a validation row would give it a retry it never had. Those triggers are still recovered through the Redis record when the scheduler was following them.
  • A recovered poll gets its full budget again, not the remainder.
  • A duplicate completion event is possible if the process dies between a poll finishing its work and removing its entry. Retry and validation are not duplicated in that window: retry is guarded by pending_retry, validation by validation_execution_id.

Tests

tests/unit/test_4410_scheduler_restart_follows_inflight.py, 20 tests. Two SchedulerService objects over one SQLite database and one Redis hash stand for the restart; the real poll loop, retry decision and validation decision run.

Eight single-change reverts of the fix each turn at least one test red: no boot recovery, entry removed on cancel, no record written, pending_retry handled again, entry never removed, fallback trigger set changed, no database fallback, fallback poll budget dropped.

Run locally: the new file plus tests/scheduler_tests/ and four scheduler unit files, 407 passed. The full suites were left to CI.

Not done: no restart of a live scheduler container against a real agent.

Fixes #4410

🤖 Generated with Claude Code

#4410)

The poll task that follows a scheduled run lives in the scheduler process.
It publishes the completion event and applies retry and validation.
Shutdown cancelled it and boot recovered pending retries and reminders
only, so a run in flight across a restart got none of the three.

The scheduler now records each run it follows in a Redis hash. A poll
that ends on its own removes its entry; one cancelled by shutdown or lost
to a kill leaves it. At boot every recorded run is followed again, which
also covers a run that ended while the scheduler was down. Running and
queued rows a cron fire or a retry created are read from the database as
well, for a lost record and for the first boot after this change.

Fixes #4410

Co-Authored-By: Claude Fable 5.2 <[email protected]>
@webmixgamer

Copy link
Copy Markdown
Contributor

/review + /validate-pr: APPROVE (head d3ed331f3)

No blocking findings. The record, the boot recovery and the database fallback do what #4410 asks, and each line of them is pinned by a test.

Scope: clean. Two scheduler files (+143/-1), one new test file, the scheduler feature flow, one registry entry. No schema change, no new dependency, no image change. Lane B.

Acceptance criteria (#4410)

Criterion Status Evidence
After a restart, running executions that carry a schedule_id get their post-terminal handling Done _recover_followed_executions (src/scheduler/service.py), called from initialize(); the Redis record plus get_inflight_scheduled_executions
A test restarts the scheduler mid-run and asserts the retry or validation still fires Done test_a_run_that_fails_while_the_scheduler_is_down_is_still_retried, ..._succeeds_..._is_still_validated, test_a_run_still_going_at_boot_is_followed_to_its_end, test_boot_runs_the_recovery (through the real initialize())

Execution coverage

changed symbol executed by live consumer verdict
_spawn_poll writes the record (_record_followed) the restart tests, test_a_poll_that_ends_on_its_own_forgets_the_run _call_backend_execute_task and the #2514 branch of _dispatch_and_record_outcome executed; M3 red
_on_poll_done (kept on cancel, removed otherwise) test_a_poll_cancelled_by_shutdown_keeps_the_run, test_a_poll_that_ends_on_its_own_forgets_the_run the task's done callback executed; M2, M5 red
_recover_followed_executions every restart test initialize() pinned through the real initialize(); M1 red
a pending_retry row is dropped test_a_run_whose_retry_is_already_decided_is_not_handled_twice the recovery loop executed; M4 red
the record wins over the database row test_the_poll_budget_and_agent_survive_the_restart, test_an_unreadable_record_still_follows_the_run the recovery merge executed; M6 red
get_inflight_scheduled_executions (src/scheduler/database.py) the fallback tests, on a real SQLite file the recovery executed; M7, M10 red
the two inner fences (a failed Redis read, a failed database read) none the recovery not executed (I2)

No test asserts source text. The harness is two SchedulerService objects over one SQLite file and one shared hash, with the real poll loop, retry decision and validation decision.

Fix mutation. With src/ at the merge-base 9ddef927e the test module does not import (the record's key does not exist), so all 20 tests fail. Single-line mutations at the head:

mutation result
M1 boot does not run the recovery 1 failed
M2 a cancelled poll forgets the run 5 failed
M3 no record is written 6 failed
M4 a pending_retry row is followed again 1 failed
M5 a finished poll never forgets the run 1 failed
M6 the database row overrides the record 2 failed
M7 no database fallback 2 failed
M8 a failed Redis read aborts the recovery 0 failed
M9 a failed database read aborts the recovery 0 failed
M10 the fallback also takes manual rows 2 failed

Run locally.

  • The new file at the head: 20 passed, also under CI's seed with xdist.
  • tests/scheduler_tests/ at the head and on a merge with dev ea04de240: 235 passed. No workflow runs that directory, so this is the only run it gets; the new file is in tests/unit/, where CI does run it.
  • The new query on PostgreSQL: run by hand against a local database (the tests use SQLite); it parses and returns.
  • Merge with dev ea04de240: no conflict, and no commit on dev since the merge-base touches the scheduler.

Pinned guards. 323 guard files derived at the head (the new file is one of them), CI's flags and seed: 13,427 passed, 98 red (24 failed, 74 errors). They are the same 98 test ids that are red on this machine on dev (real-app driver and pin tests that need packages missing here). CI's regression diff is green on this head.

Checked by reading.

  • One poll per run: the recovery merges the two sources by execution id and runs once, before any new fire; the scheduler is single-instance (docs/memory/architecture/execution.md).
  • A second retry cannot happen: schedule_retry sets pending_retry, clear_retry_scheduled only clears the time, nothing in the scheduler moves the row out of that status, and the recovery drops it.
  • A repeated completion event costs nothing today: I found no reader of the scheduler:events channel under src/ (only the scheduler publishes to it).
  • The scheduler's Redis user may use hashes under any key (+@hash, ~* in the three compose files).
  • initialize() runs inside start(), so there is a running loop for the recovered polls.

Critical

None.

Informational

I1. A second validation is possible while the first is still running (7/10)
The body says validation is guarded by validation_execution_id. The backend writes that link only after the validation turn has finished (services/validation_service.py, step 6); the trigger itself returns at once. So a successful run followed again before its first validation ends would be validated twice. It needs the record to outlive the trigger: a kill between the trigger call and the removal of the entry, or a failed hdel. Narrow, and no change is asked for here; the sentence in the body and the flow is a little stronger than the code.

I2. The two inner fences have no test (8/10)
M8 and M9: "a failed Redis read still follows the database rows" and "a failed database read still follows the recorded runs" are each one except, and narrowing either leaves all 20 tests green. One test each would pin them.

I3. The record is written after the backend accepts the dispatch (6/10)
A scheduler that dies during the dispatch call leaves a running row with no record. The database fallback picks it up when a cron fire or a retry created it, and not for manual or reminder. Those rows were not followed after a restart before this PR either, so this is a limit to state, or to close by recording before the dispatch.

I4. No live restart (the body says so)
Not exercised anywhere: a real Redis, the PostgreSQL adapter under the new read (beyond the hand run above), and a real stop of the process. Worth one live check before the next release cut.

Clean categories

  • SQL and data safety: one read, bound parameters, plain ANSI (it goes through the ? to %s adapter on PostgreSQL); no schema change.
  • Concurrency: covered above (one poll per run, no second retry).
  • Auth boundaries, credentials: no route; the record holds an execution id, an agent name and a number.
  • Error handling: every Redis call is fenced and fails open (the run is still followed in this process); a recovery error cannot stop boot (test_a_failing_recovery_does_not_stop_boot).
  • Enum completeness: no new status or trigger; the fallback's trigger set is pinned both ways (M10).
  • Invariants Setup improvements #5 and feat: SMARTS trading pipeline with Telegram notifications and Miro visualization #13: no agent-server twin, no router changed.

/validate-pr summary

Category Status Notes
Commit messages ✅ one, conventional
Base branch, size ✅ dev; 5 files (+552/-1)
Closing keyword ✅ Fixes #4410
Journey Impact ✅ check_journey_impact.py exit 0 (none declared)
Requirements ➖ bug fix
Feature flows ✅ scheduler-service.md has the new section
Security greps, file modes, host paths ✅ nothing found
Packaging, config vars, audit rows ➖ no new directory, env var or gated write handler
Structural review ✅ this report
Test adequacy ✅ restart-survival tests for a background service; two small gaps (I2)
Cross-surface drift ✅ nothing printed
Merge gate ✅ Tier 1 18 pass, 6 skipped on this head, regression diff included; dev-ci success
Product fit ➖ no user or operator surface path touched

Summary

  • Critical: 0
  • Informational: 4, none needs a change before merge
  • Scope: clean

🤖 Generated with Claude Code

@webmixgamer webmixgamer left a comment

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.

Approving d3ed331f3: no critical findings. The /review + /validate-pr report is in the comment above; its four notes need no change before merge.

@dolho

dolho commented Nov 27, 2026

Copy link
Copy Markdown
Contributor Author

Live check on a local instance (PostgreSQL)

The scheduler container ran this branch's src/scheduler (copied into the existing image; the dependency list is unchanged, and a full image rebuild failed on network).

  1. Created a schedule with validation on and triggered it. While the run was running, the Redis hash scheduler:followed_executions held its id.
  2. docker restart trinity-scheduler mid-run. The old process logged Background poll ... cancelled (shutdown); the new one logged Following 1 in-flight execution(s) again after restart.
  3. 50 seconds later the agent finished. The scheduler logged Background poll: execution ... succeeded and Triggering validation. A validation run was created and the original row ended business_status=validated.
  4. The Redis hash was empty at the end.

Not exercised live: the retry branch, the database fallback (the Redis record was present), and a cron fire (this was a manual trigger).

🤖 Generated with Claude Code

This branch has not been deployed

No deployments
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