Repository navigation
feat(worker): PLTF-3689 run the CronJob jobs as periodic worker tasks - #874
Conversation
Coverage reportClick to see where and how coverage changed
This report was generated by python-coverage-comment-action |
||||||||||||||||||||||||||||||||||||
Co-authored-by: openhands <openhands@all-hands.dev>
This comment was marked as outdated.
This comment was marked as outdated.
aivong-openhands
left a comment
There was a problem hiding this comment.
Taste rating: acceptable. The design fits the existing worker: scheduled jobs go on the queue that housekeeping already handles, every job is off by default, and the modules are imported lazily. One material defect remains in how retries interact with the queueing lock.
🟠 Retrying a run while its next run is waiting leaves the job stuck until the worker restarts
Each task has lock == queueing_lock and retry=RETRY (scheduled_jobs.py:118-121). By design, a run that comes due while the previous run is doing is inserted as todo (L112-113). If the running job then fails, procrastinate's _persist_job_status calls retry_job → procrastinate_retry_job_v2, which sets it back to todo. That collides with procrastinate_jobs_queueing_lock_idx_v1 (unique on queueing_lock WHERE status = 'todo'), so UniqueViolation is raised inside the job's asyncio task and nobody handles it. As a result:
- the failed run stays
doingand keeps holdinglock; - the waiting run can't be fetched, because
procrastinate_fetch_job_v2skips any job whose lock has adoingjob; - every later tick gets
AlreadyEnqueued; retry_stalled_jobsdoesn't recover it, because the worker is still sending heartbeats.
The job stops running until the worker process is restarted.
This is the normal outcome for budget_maintenance, not a rare one. Its 1800 s deadline is longer than its */15 schedule, so whenever it hits the deadline, a later run is already waiting. The same thing happens to install_gitlab_webhooks (* * * * *) after a failed run longer than 60 s, and to enrich_user_interaction (*/10) after a failed run longer than 10 min. housekeeping.retry_stalled_jobs already catches this UniqueViolation for its own retries; the worker's retry path doesn't.
I reproduced it against procrastinate 3.10.0 on Postgres 16 using this PR's task options (lock=queueing_lock, RetryStrategy(max_attempts=3)). I deferred run A; while A was doing, I deferred run B; then A raised TimeoutError:
procrastinate.exceptions.UniqueViolation (from manager.retry_job_by_id_async)
while A runs: [(1, 'doing', 0), (2, 'todo', 0)]
after A failed + 5s: [(1, 'doing', 0), (2, 'todo', 0)]
next tick: AlreadyEnqueued
The validation run and test_a_budget_job_is_stopped_at_its_deadline both queued a single run by hand, so neither covered this path.
Smallest fix: remove retry= and let the next tick act as the retry, which is how _end_stalled_scheduled_job already treats scheduled jobs. If backoffLimit parity matters, the retry has to give up when a newer run with the same queueing_lock is already todo. A regression test should defer a second run while the first is doing, make the first fail, and assert that the second run starts.
PR template
Why / Summary / Issue Number / How to Test / Video / Type are all present. ✅
[RISK ASSESSMENT]
[Overall PR]
This adds a new scheduler for seven background jobs, including the budget-enforcement jobs. It is opt-in, so Kubernetes installs are unaffected. Its correctness depends on procrastinate's lock and retry semantics, and the defect above sits exactly there. Reviewers should focus on the lock/queueing_lock/retry interaction and on whether a run that hits its deadline should be retried at all.
Verdict: Needs changes before merge, because of the stuck-job defect above. (This is posted as COMMENT because it's the author's own PR.)
Key insight: In procrastinate, queueing_lock allows only one todo row per lock, and a retry turns the failed row back into todo. Any task that combines queueing_lock with retry can therefore collide with its own next run.
Improve this review? If feedback seems incorrect or irrelevant, update the repository's
.agents/skills/custom-codereview-guide.md(with the/codereviewtrigger), then re-request review. The reviewer reads the guide from the PR head.Resolve with AI? Install the iterate skill and run
/iterate.Was this review helpful? React with 👍 or 👎.
This review was generated by an AI agent (OpenHands) on behalf of the user.
A retry returns the failed run to todo, which collides with the next run already waiting under the same queueing lock. The UniqueViolation left the failed run doing and holding its lock, so the job stopped until the worker restarted. The next scheduled run is now the retry. Co-authored-by: openhands <openhands@all-hands.dev>
Validation: Kubernetes default-disabled scheduling pathTested Result: pass for Kubernetes compatibility. With worker scheduling flags unset, existing Kubernetes CronJobs remained active and completed jobs.
This comment was drafted by an AI agent (OpenHands) on behalf of @aivong-openhands. |
Validation: the seven jobs on a real workerTested Result: pass. Each enabled job ran its existing code on the worker at its schedule. Runs did not overlap. A failed run, including one stopped at the budget deadline, ended Setup
What I checked
This comment was drafted by an AI agent on behalf of the user. |
Mutation review:
|
| Mutant | Result |
|---|---|
C1: put retry=3 back on the scheduled tasks |
❌ caught |
C2: worker never appends SCHEDULED_JOBS_QUEUE |
❌ caught |
C3: drop lock= (runs can overlap) |
❌ caught |
C4: budget_maintenance schedule */15 → */30 |
❌ caught |
The suite pins the scheduling contract well. It compares every job's schedule, lock and queueing lock against a separate copy of the chart values, and it asserts retry_strategy is None. The fail-while-the-next-run-waits test drives a real worker into the exact lock state the no-retry decision guards against, so it is the test that proves that decision is right.
Survivors
| Mutant | Result |
|---|---|
M1: budget_maintenance calls run_maintenance_tasks.main() and skips enqueue_budget_tasks() |
✅ 9 passed |
M2: enrich_user_interaction job body → pass |
✅ 9 passed |
M3: install_gitlab_webhooks imports sync.install_gitlab_webhook (a module that doesn't exist) |
✅ 9 passed |
M4: proactive_convo_clean job body → pass |
✅ 9 passed |
M5: resend_sync becomes async def, so its blocking calls run on the event loop |
✅ 9 passed |
M6: run_budget_maintenance.main() calls run() without asyncio.run |
✅ 9 passed |
M7: worker takes scheduled_jobs even when no job is enabled |
✅ 9 passed |
M8: maintenance_tasks loses its asyncio.timeout |
⏳ hung (suite timed out) |
1. Five of the seven jobs never call their entrypoint in a test (M1–M5)
Only app_conversation_start_task_clean is checked for doing its work. proactive_convo_clean only has its status checked, and install_gitlab_webhooks and enrich_user_interaction never run. The imports happen inside the jobs, so a typo in a module path (M3) shows up only at the first scheduled run after deploy. That run fails, and because there's no retry, every later run fails the same way, with nothing louder than an error log. M1 is the worst case: the budget job reports succeeded every 15 minutes but never queues any budget tasks. M5 reverses the deliberate plain def on resend_sync. Its blocking Resend calls would then stall the loop for the other jobs and the heartbeat.
One parametrized test kills all five. It swaps each job's CronJob entrypoint for a recorder and runs the job on a real worker. I used a stand-in only because the real entrypoints call GitLab, GitHub, Resend and LiteLLM. The worker, the job wrapper, the lazy import and the dispatch to a thread are all real. The recorder also logs whether it ran on the event loop, which is what catches M5:
# Each job's CronJob entrypoint; resend_sync's is sync and must run off the loop.
ENTRYPOINTS = {
'budget_maintenance': 'run_budget_maintenance.run',
'maintenance_tasks': 'run_maintenance_tasks.main',
'app_conversation_start_task_clean': 'sync.clean_app_conversation_start_tasks.main',
'proactive_convo_clean': 'sync.clean_proactive_convo_table.main',
'resend_sync': 'sync.resend_keycloak.sync_users_to_resend',
'install_gitlab_webhooks': 'sync.install_gitlab_webhooks.VerifyWebhookStatus.install_webhooks',
'enrich_user_interaction': 'sync.enrich_user_interaction_data.main',
}
@pytest.mark.usefixtures('app_db_session')
@pytest.mark.parametrize('name', ENTRYPOINTS)
async def test_each_job_runs_its_cronjobs_entrypoint(conninfo, monkeypatch, name):
# enrich_user_interaction_data builds a GitHub App client at import.
monkeypatch.setattr(
'integrations.github.data_collector.GitHubDataCollector', object
)
ran_on: list[str] = []
def record(*args):
try:
asyncio.get_running_loop()
ran_on.append('event loop')
except RuntimeError:
ran_on.append('thread')
async def async_record(*args):
record()
entrypoint = record if name == 'resend_sync' else async_record
monkeypatch.setattr(ENTRYPOINTS[name], entrypoint)
# Only this job, so no other job's periodic run can reach the entrypoint.
async with _open_worker_app(
conninfo, ScheduledJobsConfig(**{name: True})
) as worker_app:
status, _ = await _run_job(worker_app, conninfo, name)
assert status == 'succeeded'
# Its own periodic run may come due too, so it can run more than once.
assert ran_on
assert set(ran_on) == {'thread' if name == 'resend_sync' else 'event loop'}Verified: all 7 cases pass on the PR branch. M1, M2, M3, M4 and M5 each fail exactly one case: the one for the job they break.
2. The CronJob entrypoint isn't covered (M6)
run_budget_maintenance.main() is what every Kubernetes install runs, and this PR changes it. Nothing in this suite calls it, and test_run_budget_maintenance.py only checks the AST for delay=0. If main() stopped awaiting run(), the budget CronJob would exit 0 and do nothing.
import run_budget_maintenance
def test_budget_cronjob_entrypoint_still_runs_the_job(monkeypatch):
ran = []
async def run():
ran.append(True)
monkeypatch.setattr(run_budget_maintenance, 'run', run)
run_budget_maintenance.main()
assert ran == [True]Verified: passes on the PR branch and fails under M6. It would also fit in tests/unit/test_run_budget_maintenance.py.
3. Losing a deadline hangs CI instead of failing it (M8)
With the asyncio.timeout removed from maintenance_tasks, the deadline test waits for the planted delay=600 row. The < 30 s assertion only runs after that, and the cleanup in the fail-while-waiting test blocks on the same sleep. The suite failed only when my 150 s outer timeout killed it. pytest-timeout is already a dev dependency:
pytestmark = pytest.mark.timeout(60)Verified: the full file runs in about 11 s on the PR branch. Under M8, the two affected tests now fail at 60 s each instead of hanging.
4. The "only once one is enabled" negative case (M7)
test_worker_takes_scheduled_jobs_only_once_one_is_enabled only covers the enabled case. If the guard moved, every Kubernetes worker would start taking scheduled_jobs with none of its tasks registered, which is the TaskNotFound situation the QUEUES comment exists to prevent.
@pytest.mark.usefixtures('app_db_session', 'restore_app')
async def test_worker_skips_scheduled_jobs_queue_when_none_is_enabled(monkeypatch):
started_with: dict = {}
async def run_worker_async(**kwargs):
started_with.update(kwargs)
monkeypatch.setattr(app, 'run_worker_async', run_worker_async)
await worker_main.run()
assert started_with['queues'] == ['default']Verified: passes on the PR branch and fails under M7.
With all four additions the file has 18 tests, and all 12 mutants (controls and candidates) are killed. Each candidate is killed by the test written for it.
Not a test gap
_run_jobon theALL_ONworker_appalso runs every periodic job that is due at that moment, becauserun_worker_async(wait=False)runs the periodic deferrer. While writing the fix, a realenrich_user_interactionrun with a wall-clocktimestampshowed up inside a test. Soinstall_gitlab_webhooksruns its real code during every_run_job, andbudget_maintenancedoes too in part of each 15-minute window. The current tests pass anyway, but what they run depends on the clock. Giving each test a worker app with only the jobs it needs, as the fix above does, avoids that.
This comment was generated by an AI assistant on behalf of the user.
- Run every job on a real worker with its CronJob entrypoint recorded, so a wrong or missing entrypoint call, a bad lazy import or resend_sync on the event loop fails (M1-M5). - Cover run_budget_maintenance.main() still running the job (M6). - Cover the worker skipping scheduled_jobs when no job is enabled (M7). - Time out each test at 60 s so a lost deadline fails instead of hanging (M8). - Give each worker test only the jobs it runs, so other jobs' periodic runs don't depend on the clock. Co-authored-by: openhands <openhands@all-hands.dev>
|
Reply to the mutation review. All four proposed tests are in, along with the not-a-test-gap point, in 90c6c7d. That commit changes only Findings
Test result
Re-verification per mutantI applied each mutant to the source on top of 90c6c7d, ran the full file, and reverted. No source changes are left behind.
The controls are still caught after the move to per-test worker apps. C1 ( This comment was created by an AI agent (OpenHands) on behalf of the user. |
aivong-openhands
left a comment
There was a problem hiding this comment.
Taste rating: good. I found nothing material. The change does what the description says, and I checked the claims below against procrastinate 3.10.0 in the venv and the OpenHands-Cloud chart on main.
What I verified
- Schedules and time limits match the chart. All seven
schedulevalues and the 1800 sactiveDeadlineSecondsonbudgetMaintenanceandmaintenanceTasksmatchcharts/openhands/values.yaml. The other five CronJobs have no deadline. croniter reads float timestamps as UTC whatever the processTZis, which fits the UTC schedules. - Overlap. The periodic deferrer calls
task.configure(), which falls back to the task's ownlock,queueing_lockandqueue.procrastinate_fetch_job_v2won't fetch a job while another job with the same lock isdoing.procrastinate_jobs_queueing_lock_idx_v1allows onetodorow per lock, so one run waits and later ticks getAlreadyEnqueued.procrastinate_periodic_defersdedups ticks across replicas and restarts. - No retry. With
retry_strategy=None,_persist_job_statuscallsfinish_job(FAILED), which releases both locks, so the earlier stuck-in-doingdefect is gone. - Sync vs. async.
_process_jobwraps the job inexcept BaseException. SoSystemExitfromrun_maintenance_tasks.main()(async, on the loop) or fromresend_keycloak(sync, in an asgiref thread) fails the job without reachingTask.__stepor stopping the worker.asyncio.timeoutcancels the job task,TimeoutErrorcomes out of the timeout block, and the job endsfailed. - Kubernetes installs that set nothing.
enabled()is[], so no task is added, the queues stay['default'](test_worker_queues.pystill pins this), andscheduled_jobs.pyimports no job module at load.run_budget_maintenance.main()is still the sync entrypoint the CronJob runs. - Tests.
test_worker_scheduled_jobs.py,test_worker_queues.pyandtest_worker_housekeeping.pypass locally: 29 passed on real Postgres. When I checked,Python Tests on LinuxandBudget regressionswere still running on90c6c7d.
Stall behaviour. I checked this on a real worker. The PR's Notes say housekeeping "ends that job as failed rather than running it twice". That's true for a dead worker. For a live worker that only missed heartbeats, the two runs overlap; see the inline comment. The jobs already tolerate this through their claim leases and idempotent writes, so it doesn't block the merge, but the comment and the Notes overstate the guarantee.
One operational caveat, not a code defect. Every enabled job shares the one scheduled_jobs queue. If two worker replicas on one database enable different jobs, a replica can fetch a job it has no task for and fail it with TaskNotFound. Keep OH_WORKER_SCHEDULED_JOBS_* the same on every replica, for example in the Compose docs when this gets wired up.
[RISK ASSESSMENT]
Verdict: Fine to merge once the current-head CI finishes green. The inline comment is a non-blocking correction to the docs.
Key insight: lock + queueing_lock + no retry makes procrastinate behave like concurrencyPolicy: Forbid with a queue depth of one. The only way out of it is housekeeping marking a run failed from outside, and that doesn't stop the run's coroutine.
Improve this review? If feedback seems incorrect or irrelevant, update the repository's
.agents/skills/custom-codereview-guide.md(with the/codereviewtrigger), then re-request review. The reviewer reads the guide from the PR head.Resolve with AI? Install the iterate skill and run
/iterate.Was this review helpful? React with 👍 or 👎.
This review was created by an AI agent (OpenHands) on behalf of the user.
…ment Co-authored-by: openhands <openhands@all-hands.dev>
|
🚀 Released in 1.73.0. |
HUMAN:
AGENT:
Why
Docker Compose installs have no Kubernetes CronJobs, so the seven jobs those CronJobs run need another scheduler. This PR runs each one on the procrastinate worker as a periodic task that calls the job's existing code, with the CronJob's schedule, overlap policy and time limit. Every job is off unless enabled, so Kubernetes installs, which set nothing, keep running their CronJobs.
Summary
scheduled_jobsqueue at its OpenHands-Cloud chart schedule. One run can wait and one can run, as withconcurrencyPolicy: Forbid. A failed run isn't retried; the next scheduled run is the retry. A procrastinate retry would put the failed run back totodo, which the waiting run's queueing lock forbids, so the failed run would staydoingand hold its lock until the worker restarted.budget_maintenanceandmaintenance_tasksstop after 1800 s, their chartactiveDeadlineSeconds.OH_WORKER_SCHEDULED_JOBS_<JOB>=trueis set. The worker takes thescheduled_jobsqueue only when at least one job is on, and itsworker.startedlog lists the enabled jobs.run_budget_maintenancegains an asyncrun()for the worker to await. Itsmain()still serves the CronJob.Issue Number
None.
How to Test
CI runs
tests/unit/app_server/test_worker_scheduled_jobs.py. It checks every job against its chart schedule and locks, and on a real worker against the test Postgres it runs a job's existing code, survives the syncresend_syncexiting in its thread, stops the two budget jobs at their deadline, and starts the waiting run when a run fails while that run is queued. That last test fails withretry=put back: the first run staysdoing. It also runs each job on a real worker and checks that it calls its CronJob entrypoint, withresend_syncoff the event loop. It checks thatrun_budget_maintenance.main()still runs the job and that the worker skipsscheduled_jobswhen no job is on. Each test times out at 60 s, so a lost deadline fails instead of hanging.Video/Screenshots
N/A. No UI change.
Type
Notes
backoffLimit: 3. A run stopped at its deadline isn't retried, as withactiveDeadlineSeconds.OH_WORKER_SCHEDULED_JOBS_*flags on every worker replica that shares a database. All enabled jobs share thescheduled_jobsqueue, so a replica could fetch a job it has no task for and fail it withTaskNotFound.This PR was created by an AI agent (OpenHands) on behalf of @aivong-openhands.
@aivong-openhands can click here to continue refining the PR
Enterprise server image for this PR: