Skip to content

feat(worker): PLTF-3689 run the CronJob jobs as periodic worker tasks - #874

Merged
aivong-openhands merged 6 commits into
mainfrom
aivong/pltf-3689-scheduled-jobs-periodic
Oct 19, 2026
Merged

aivong-openhands merged 6 commits into
mainfrom
aivong/pltf-3689-scheduled-jobs-periodic

Conversation

@aivong-openhands

@aivong-openhands aivong-openhands commented Oct 19, 2026 •

Copy link
Copy Markdown
Contributor

HUMAN:

  • A human has tested these changes.

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

  • Each job runs on the scheduled_jobs queue at its OpenHands-Cloud chart schedule. One run can wait and one can run, as with concurrencyPolicy: Forbid. A failed run isn't retried; the next scheduled run is the retry. A procrastinate retry would put the failed run back to todo, which the waiting run's queueing lock forbids, so the failed run would stay doing and hold its lock until the worker restarted. budget_maintenance and maintenance_tasks stop after 1800 s, their chart activeDeadlineSeconds.
  • A job runs only when OH_WORKER_SCHEDULED_JOBS_<JOB>=true is set. The worker takes the scheduled_jobs queue only when at least one job is on, and its worker.started log lists the enabled jobs.
  • run_budget_maintenance gains an async run() for the worker to await. Its main() 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 sync resend_sync exiting 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 with retry= put back: the first run stays doing. It also runs each job on a real worker and checks that it calls its CronJob entrypoint, with resend_sync off the event loop. It checks that run_budget_maintenance.main() still runs the job and that the worker skips scheduled_jobs when 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

  • Bug fix
  • Feature
  • Refactor
  • Breaking change
  • Docs / chore

Notes

  • Never enable a job on a database where its CronJob still runs, or both schedules will fire.
  • A failed daily job waits for the next day, where its CronJob would have retried it up to backoffLimit: 3. A run stopped at its deadline isn't retried, as with activeDeadlineSeconds.
  • The async jobs share the worker's event loop. A job that blocks the loop for more than 30 s makes the worker look stalled, and housekeeping then ends that job as failed rather than retrying it. If that worker is still alive, the job keeps running beside the next run, so jobs must tolerate overlap. The current jobs do, through their claim leases and idempotent writes.
  • Set the same OH_WORKER_SCHEDULED_JOBS_* flags on every worker replica that shares a database. All enabled jobs share the scheduled_jobs queue, so a replica could fetch a job it has no task for and fail it with TaskNotFound.

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:

ghcr.io/openhands/enterprise-server:sha-d525fb9

…periodic tasks

Each job is a periodic task that calls its existing code in the worker,
off unless OH_WORKER_SCHEDULED_JOBS_<JOB> is true. Replaces the child-process
approach of #698 and #699.

Co-authored-by: openhands <openhands@all-hands.dev>
@github-actions github-actions Bot added the type: feat A new feature label Oct 19, 2026
@github-actions

github-actions Bot commented Oct 19, 2026 •

Copy link
Copy Markdown
Contributor

Coverage report

Click to see where and how coverage changed

FileStatementsMissingCoverageCoverage
(new stmts)
Lines missing
  openhands/app_server/worker
  __main__.py
  app.py
  scheduled_jobs.py 74-76
Project Total  

This report was generated by python-coverage-comment-action

@aivong-openhands aivong-openhands changed the title feat(worker): PLTF-3689 schedule the CronJob jobs with procrastinate periodic tasks feat(worker): PLTF-3689 run the CronJob jobs as periodic worker tasks Oct 19, 2026
Co-authored-by: openhands <openhands@all-hands.dev>

This comment was marked as outdated.

@aivong-openhands aivong-openhands left a comment

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.

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 doing and keeps holding lock;
  • the waiting run can't be fetched, because procrastinate_fetch_job_v2 skips any job whose lock has a doing job;
  • every later tick gets AlreadyEnqueued;
  • retry_stalled_jobs doesn'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] ⚠️ Risk Assessment: 🟡 MEDIUM
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 /codereview trigger), 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>
@aivong-openhands

Copy link
Copy Markdown
Contributor Author

Validation: Kubernetes default-disabled scheduling path

Tested bc47c04 (enterprise-server image sha-bc47c04) in a fresh single-node embedded-cluster installation with external PostgreSQL.

Result: pass for Kubernetes compatibility. With worker scheduling flags unset, existing Kubernetes CronJobs remained active and completed jobs.

Check Observed result
Default configuration No OH_WORKER_SCHEDULED_JOBS_* environment variables in the running application container.
Existing CronJob execution Budget maintenance retained */15 * * * * with suspend=false; one observed job had status.succeeded=1. GitLab webhook installation retained * * * * * with suspend=false; three observed jobs each had status.succeeded=1.

This comment was drafted by an AI agent (OpenHands) on behalf of @aivong-openhands.

Copy link
Copy Markdown
Contributor Author

Validation: the seven jobs on a real worker

Tested bc47c04 with python -m openhands.app_server.worker against a local Postgres 16 at alembic head.

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 failed without a retry, and the run waiting behind it then started. A slow sync job did not stall the worker.

Setup

  1. Postgres 16 from make local-db, migrated to alembic head.
  2. Seed rows for the jobs to act on: one old and one new app_conversation_start_task, old and new proactive_conversation_table rows, and 4 users not yet synced to Resend.
  3. resend_sync pointed at a local stub of the Resend API through RESEND_API_URL. The stub can delay each contact create. enrich_user_interaction got a placeholder GitHub App ID and key; it found no PRs, so it made no GitHub calls.
  4. Jobs turned on with OH_WORKER_SCHEDULED_JOBS_<JOB>=true and queued by hand, with the same task, queue and locks as the periodic defer.
  5. For the deadline rows, DEADLINE_SECONDS was set to 20 before the worker started, checked in the loaded module (DEADLINE_SECONDS = 20), and a test maintenance task waited 600 s.

What I checked

Off by default ✅ No job enabled: "queues": ["default"], "scheduled_jobs": [], and no scheduled_jobs rows after a minute boundary
Schedule ✅ Only install_gitlab_webhooks (* * * * *) on: after the worker started, one run each minute at 18:01:00, 18:02:00, 18:03:00 and 18:04:00, all succeeded
Existing code, all seven ✅ All 7 queued at once on one worker, all succeeded. The old start task and the old proactive row were deleted; the new rows stayed. The stub got 4 contact creates and 4 welcome emails
No overlap ✅ resend_sync queued 3 times while it ran: the 2nd waited as todo and started after the 1st ended; the 3rd was refused with AlreadyEnqueued
Slow sync job ✅ Contact creates delayed 20 s: Job scheduled_jobs:resend_sync[39](timestamp=1) ended with status: Success, lasted 84.147 s. last_heartbeat moved every 10 s, a cleanup job queued meanwhile succeeded, and housekeeping run 65 s in did not flag it
Failed run ✅ RESEND_AUDIENCE_ID unset: SystemExit: 1, then Job scheduled_jobs:resend_sync[3](timestamp=0) ended with status: Error, lasted 0.014 s, with no to retry. The row is failed, attempts 1, and no further attempt ran in the next 40 s. A cleanup job queued afterwards succeeded
Deadline ✅ Job scheduled_jobs:maintenance_tasks[8](timestamp=0) ended with status: Error, lasted 20.054 s (TimeoutError), with no to retry. The row is failed, attempts 1, and no second attempt ran
Fails while next waits ✅ Run 1 doing when run 2 was queued as todo; run 3 was refused with AlreadyEnqueued. Run 1 ended failed at 20.003 s (17:57:47.5); run 2 started at 17:57:48.5 and succeeded, finding the stopped run's task still claimed. Nothing left in doing, no UniqueViolation in the log
Both budget jobs together ✅ budget_maintenance and maintenance_tasks at once on 20 pending tasks: each task ran exactly once, 10 per run
Event loop ✅ asyncio debug mode: longest block inside a job 0.37 s (maintenance_tasks)
SIGTERM ✅ Waiting for job to finish: worker: scheduled_jobs:maintenance_tasks[50](timestamp=300) (started 5.449 s ago), then lasted 12.272 s Success, then Stopped worker on queues default, scheduled_jobs
Killed worker ✅ A second SIGTERM ended the process with resend_sync still doing and the next run todo. After a restart, housekeeping logged scheduled_jobs.stalled for job 53 and marked it failed. The waiting run started 5 s later and succeeded
CronJob entry point ✅ python -m run_budget_maintenance exits 0

This comment was drafted by an AI agent on behalf of the user.

@aivong-openhands

Copy link
Copy Markdown
Contributor Author

Mutation review: test_worker_scheduled_jobs.py

I broke the PR's code on purpose with hand-written mutants and ran tests/unit/app_server/test_worker_scheduled_jobs.py against each one (real Postgres, at bc47c04). Baseline: 9 passed.

Controls (reverting what the PR sets up)

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_job on the ALL_ON worker_app also runs every periodic job that is due at that moment, because run_worker_async(wait=False) runs the periodic deferrer. While writing the fix, a real enrich_user_interaction run with a wall-clock timestamp showed up inside a test. So install_gitlab_webhooks runs its real code during every _run_job, and budget_maintenance does 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>
@aivong-openhands

Copy link
Copy Markdown
Contributor Author

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 tests/unit/app_server/test_worker_scheduled_jobs.py.

Findings

Finding What was done Commit
M1–M5: five jobs never call their entrypoint in a test Added test_each_job_runs_its_cronjobs_entrypoint, parametrized over a new ENTRYPOINTS dict as proposed. It swaps each job's CronJob entrypoint for a recorder, runs the job on a real worker that has only that job enabled, and asserts that resend_sync runs in a thread and every other job runs on the event loop. 90c6c7d
M6: run_budget_maintenance.main() isn't covered Added test_budget_cronjob_entrypoint_still_runs_the_job, with import run_budget_maintenance at the top of the file. 90c6c7d
M7: no negative case for the scheduled_jobs queue Added test_worker_skips_scheduled_jobs_queue_when_none_is_enabled, which asserts the queues are ['default']. 90c6c7d
M8: a lost deadline hangs CI Added pytestmark = pytest.mark.timeout(60) to the file. 90c6c7d
Not a test gap: _run_job on the ALL_ON worker app also runs whatever periodic jobs are due Removed the ALL_ON worker_app fixture. Each test that runs jobs now opens _open_worker_app with only the jobs it runs: app_conversation_start_task_clean, resend_sync + proactive_convo_clean, or the one budget job under test. install_gitlab_webhooks, enrich_user_interaction and budget_maintenance no longer run their real code depending on the clock. ALL_ON is still used by the static schedule/lock test. 90c6c7d

Test result

uv run pytest -q -p no:randomly tests/unit/app_server/test_worker_scheduled_jobs.py (real Postgres via testcontainers): 18 passed in 10.5 s. Before the change it was 9 passed. Pre-commit passes on the file (ruff, ruff format, mypy).

Re-verification per mutant

I applied each mutant to the source on top of 90c6c7d, ran the full file, and reverted. No source changes are left behind.

Mutant Result Failing test(s)
M1: budget_maintenance calls run_maintenance_tasks.main() ❌ 1 failed, 17 passed test_each_job_runs_its_cronjobs_entrypoint[budget_maintenance]
M2: enrich_user_interaction body → pass ❌ 1 failed, 17 passed …[enrich_user_interaction]
M3: imports sync.install_gitlab_webhook ❌ 1 failed, 17 passed …[install_gitlab_webhooks]
M4: proactive_convo_clean body → pass ❌ 1 failed, 17 passed …[proactive_convo_clean]
M5: resend_sync → async def ❌ 1 failed, 17 passed …[resend_sync]
M6: main() calls run() without asyncio.run ❌ 1 failed, 17 passed test_budget_cronjob_entrypoint_still_runs_the_job
M7: worker takes scheduled_jobs with no job enabled ❌ 1 failed, 17 passed test_worker_skips_scheduled_jobs_queue_when_none_is_enabled
M8: maintenance_tasks loses asyncio.timeout ❌ 2 failed, 16 passed in 124 s (60 s timeout each, no hang) test_a_budget_job_is_stopped_at_its_deadline[maintenance_tasks], test_a_run_that_fails_while_the_next_waits_lets_the_next_start

The controls are still caught after the move to per-test worker apps. C1 (retry=3) fails 5 tests, including the fail-while-the-next-waits test. C2 (no SCHEDULED_JOBS_QUEUE append), C3 (no lock=) and C4 (*/30) each fail 1 test.

This comment was created by an AI agent (OpenHands) on behalf of the user.

@aivong-openhands aivong-openhands left a comment

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.

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 schedule values and the 1800 s activeDeadlineSeconds on budgetMaintenance and maintenanceTasks match charts/openhands/values.yaml. The other five CronJobs have no deadline. croniter reads float timestamps as UTC whatever the process TZ is, which fits the UTC schedules.
  • Overlap. The periodic deferrer calls task.configure(), which falls back to the task's own lock, queueing_lock and queue. procrastinate_fetch_job_v2 won't fetch a job while another job with the same lock is doing. procrastinate_jobs_queueing_lock_idx_v1 allows one todo row per lock, so one run waits and later ticks get AlreadyEnqueued. procrastinate_periodic_defers dedups ticks across replicas and restarts.
  • No retry. With retry_strategy=None, _persist_job_status calls finish_job(FAILED), which releases both locks, so the earlier stuck-in-doing defect is gone.
  • Sync vs. async. _process_job wraps the job in except BaseException. So SystemExit from run_maintenance_tasks.main() (async, on the loop) or from resend_keycloak (sync, in an asgiref thread) fails the job without reaching Task.__step or stopping the worker. asyncio.timeout cancels the job task, TimeoutError comes out of the timeout block, and the job ends failed.
  • Kubernetes installs that set nothing. enabled() is [], so no task is added, the queues stay ['default'] (test_worker_queues.py still pins this), and scheduled_jobs.py imports 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.py and test_worker_housekeeping.py pass locally: 29 passed on real Postgres. When I checked, Python Tests on Linux and Budget regressions were still running on 90c6c7d.

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]
⚠️ Risk: 🟡 MEDIUM. This is a new scheduler for seven background jobs, including budget enforcement. It's opt-in and changes nothing for Kubernetes installs that don't set the flags. Its correctness rests on procrastinate's lock and queueing-lock semantics, which the code uses correctly.

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 /codereview trigger), 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>
@aivong-openhands
aivong-openhands merged commit 3590801 into main Oct 19, 2026
22 checks passed
@aivong-openhands
aivong-openhands deleted the aivong/pltf-3689-scheduled-jobs-periodic branch October 19, 2026 21:18
@openhands-release-bot openhands-release-bot Bot added the released: 1.73.0 Shipped in 1.73.0 label Oct 19, 2026
@openhands-release-bot

Copy link
Copy Markdown
Contributor

🚀 Released in 1.73.0.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

released: 1.73.0 Shipped in 1.73.0 type: feat A new feature

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants