Skip to content

feat(worker): PLTF-3689 optional scheduled jobs behind OH_PROCRASTINATE_SCHEDULED_JOBS_ENABLED - #699

Closed
aivong-openhands wants to merge 5 commits into
task-queue/scheduled-jobs-child-runnerfrom
task-queue/scheduled-jobs-registration
Closed

aivong-openhands wants to merge 5 commits into
task-queue/scheduled-jobs-child-runnerfrom
task-queue/scheduled-jobs-registration

Conversation

@aivong-openhands

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

Copy link
Copy Markdown
Contributor

HUMAN:

  • A human has tested these changes.

AGENT:


Why

Docker Compose installs need the seven CronJob jobs scheduled by the worker, while SaaS, Replicated and Helm keep their Kubernetes CronJobs. This PR makes worker scheduling opt-in with OH_PROCRASTINATE_SCHEDULED_JOBS_ENABLED (default false), and then only for the jobs enabled one by one, so nothing changes for any install that doesn't set it. With the flag off, the worker registers no scheduled task and still takes jobs only from default.

With the flag on, the worker also takes jobs from the scheduled_jobs queue, the queue whose stalled jobs housekeeping already ends as failed instead of requeueing (#694). A worker that cannot run these tasks therefore never fetches them (#690).

Summary

  • OH_PROCRASTINATE_SCHEDULED_JOBS_ENABLED accepts true/1/false/0 in any case; unset or empty is false, anything else stops the worker at startup. Per job, OH_JOB_<JOB>__ENABLED (default false), __SCHEDULE, __BACKOFF_LIMIT and __ACTIVE_DEADLINE_SECONDS default to the chart's schedules and limits. Any other OH_JOB_<JOB>__<NAME> reaches only that job's child, as <NAME>; an OH_JOB_ variable that names no job is a startup error.
  • Each enabled job is a periodic task scheduled_jobs:<job> on the scheduled_jobs queue, with lock and queueing_lock scheduled_jobs:<job>: at most one run waiting and one running, as the CronJobs' concurrencyPolicy: Forbid does. The task runs the job's module with run_child_job, checks before each attempt that housekeeping has not ended the job, and logs scheduled_jobs.failed (error), scheduled_jobs.superseded (warning) or scheduled_jobs.succeeded.
  • budget_maintenance and maintenance_tasks get MAINTENANCE_TASK_CLAIM_LEASE_SECONDS = the longer of their deadlines + 300 s, as the claim code expects. worker.started logs the flag, the queues and the enabled jobs.
  • A second SIGTERM or SIGINT calls stop_all_children. procrastinate handles the first signal (stop taking jobs, wait for running ones) and then restores the handler installed before it started; without one, the second signal killed the worker at once and left running jobs' child processes behind. Those jobs now end as failed once their children are gone.

Issue Number

PLTF-3689 (OHE-3417).

How to Test

uv run --group test pytest tests/unit/app_server/test_worker_scheduled_jobs.py \
  tests/unit/app_server/test_worker_queues.py \
  tests/unit/app_server/test_worker_child_job.py \
  tests/unit/app_server/test_worker_housekeeping.py
# Docker is needed for the test Postgres

test_worker_scheduled_jobs.py covers flag parsing; no job running unless enabled; chart defaults and per-job overrides; invalid settings and unknown job names as errors; settings isolation between children; the lease with default and overridden deadlines; task names, queue, locks and crons; worker startup with the flag off (only default, no scheduled tasks, even with a job enabled), on (both queues, logged) and invalid (stops before the worker starts). On this test's Postgres, a real worker runs a registered job's module with its settings and records succeeded, a second defer is refused by the queueing lock, and a failing module ends failed with scheduled_jobs.failed; a job already ended by housekeeping starts no child. 72 passed across the four files.

Two tests were checked against deliberate breakages: passing every OH_JOB_ setting to every child fails the isolation test, and registering scheduled jobs with the flag off fails the flag-off startup test.

Video/Screenshots

N/A. No UI change.

Type

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

Notes

Stacked on #698 (the child-process runner). Kubernetes deployment values keep the flag unset; this PR changes no chart. Enabling a job against a database whose CronJobs still run it makes two schedulers run the same job: stop the other scheduler first. The maintenance and GitLab claim fixes (#691, #692) and the Resend overlap fix (#693) should be deployed before those jobs are enabled. The Compose service itself is separate work.

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


Enterprise server image for this PR:

ghcr.io/openhands/enterprise-server:sha-7ae186c

@github-actions

github-actions Bot commented Oct 8, 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
  scheduled_jobs.py
Project Total  

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

@aivong-openhands

Copy link
Copy Markdown
Contributor Author

Mutation review

Method: hand-written mutants were applied one at a time to the code this PR adds (worker/scheduled_jobs.py and the worker/__main__.py startup change; the base branch's child runner was not mutated). After each mutant, tests/unit/app_server/test_worker_scheduled_jobs.py and tests/unit/app_server/test_worker_queues.py were run. Baseline: 35 passed.

Controls (the PR's central claims)

Mutant Result
C1: flag defaults to true when unset ❌ caught
C2: flag off still registers jobs and consumes scheduled_jobs ❌ caught
C3: OH_JOB_<JOB>__ENABLED ignored, so disabled jobs are registered ❌ caught

Other mutants caught: invalid flag value treated as false; case-sensitive parsing; scheduled_jobs consumed with the flag off; worker.started logs the static queue list; a procrastinate retry= added; lock removed; queueing_lock given a different name; lease from either budget deadline alone; lease set on non-maintenance jobs; per-job schedule ignored at registration; failure logged but not re-raised; still_current always true; flag parsed only after the worker opens its connection.

The suite works because the startup tests run the real worker_main.run() and assert the exact queues list given to run_worker_async and logged on worker.started. The registration test compares the whole (queue, lock, queueing_lock) map and the cron map with ==. The lease test gives the disabled job a different deadline, so neither single-deadline shortcut passes. The Postgres tests run a real worker, so a retry strategy or a swallowed failure changes the stored job status.

Survivors

Mutant Result
M11: task passes backoff_limit=0 to run_child_job instead of the configured value ✅ 35 passed
M12: task passes deadline_seconds=1800 to run_child_job instead of the configured value ✅ 35 passed
M15: scheduled_jobs.succeeded / scheduled_jobs.superseded branches swapped ✅ 35 passed
M18: _RESERVED = {'ENABLED'}, so SCHEDULE, BACKOFF_LIMIT and ACTIVE_DEADLINE_SECONDS reach the child ✅ 35 passed
M19: whitespace-only flag value raises instead of reading as false ✅ 35 passed
M20: empty __BACKOFF_LIMIT / __ACTIVE_DEADLINE_SECONDS raises instead of using the default ✅ 35 passed

M11, M12, M15: the settled limits never reach the child runner under test

test_schedule_deadline_and_backoff_can_be_set_per_job checks that configure() reads the overrides into ScheduledJob. But no test checks that _runner passes them on to run_child_job. The Postgres probe job uses backoff_limit=0 and a 30 s deadline, and its module exits at once, so a hard-coded value gives the same result. In production, M12 lets a hung install_gitlab_webhooks (300 s deadline) run for 30 minutes and hold its lock that long. M11 turns off the retries that the chart's backoffLimit: 3 gives. M15 logs a job that housekeeping superseded as a success at INFO level, so the scheduled_jobs.superseded warning never fires.

A fake run_child_job pins all three:

@pytest.mark.parametrize('superseded, message', [
    (False, 'scheduled_jobs.succeeded'),
    (True, 'scheduled_jobs.superseded'),
])
async def test_the_task_hands_the_jobs_settings_to_the_child_runner(
    monkeypatch, caplog, superseded, message
):
    calls = []

    async def fake_run_child_job(module, **kwargs):
        calls.append((module, kwargs))
        return SimpleNamespace(superseded=superseded, attempts=2)

    monkeypatch.setattr(scheduled_jobs_module, 'run_child_job', fake_run_child_job)
    logger: logging.Logger | None = scheduled_jobs_module._logger
    while logger is not None:
        monkeypatch.setattr(logger, 'propagate', True)
        logger = logger.parent
    [item] = configure(
        {
            'OH_JOB_RESEND_SYNC__ENABLED': 'true',
            'OH_JOB_RESEND_SYNC__ACTIVE_DEADLINE_SECONDS': '120',
            'OH_JOB_RESEND_SYNC__BACKOFF_LIMIT': '5',
        }
    )
    app = App(connector=InMemoryConnector())
    register_scheduled_jobs(app, [item])
    context = SimpleNamespace(job=SimpleNamespace(id=7), app=None)

    with caplog.at_level(logging.INFO):
        await app.tasks['scheduled_jobs:resend_sync'].func(context, timestamp=0)

    [(module, kwargs)] = calls
    assert module == 'sync.resend_keycloak'
    assert (kwargs['deadline_seconds'], kwargs['backoff_limit']) == (120, 5)
    assert kwargs['env'] == item.env
    [record] = [
        r for r in caplog.records if r.getMessage().startswith('scheduled_jobs.')
    ]
    assert (record.getMessage(), record.attempts) == (message, 2)

Verified: passes on this branch unmodified; fails with M11, M12 and M15 each applied.

M18: reserved settings leak into the child environment

test_a_jobs_settings_reach_only_its_own_child asserts that ENABLED does not reach the child, but the other three reserved names are never set in that test. The module docstring says that reserved names "set the job itself". If they leak, a child module that reads a generic SCHEDULE or BACKOFF_LIMIT variable gets the worker's settings.

def test_the_reserved_job_settings_never_reach_the_child():
    [item] = configure(
        {
            'OH_JOB_RESEND_SYNC__ENABLED': 'true',
            'OH_JOB_RESEND_SYNC__SCHEDULE': '0 4 * * *',
            'OH_JOB_RESEND_SYNC__BACKOFF_LIMIT': '1',
            'OH_JOB_RESEND_SYNC__ACTIVE_DEADLINE_SECONDS': '60',
        }
    )
    assert not {'SCHEDULE', 'BACKOFF_LIMIT', 'ACTIVE_DEADLINE_SECONDS'} & set(item.env)

Verified: passes on this branch unmodified; fails with M18 applied.

M19, M20: blank values

parse_bool and _int both .strip() before they check for empty, so a blank value (for example from a Compose .env file) means "use the default". Nothing pins this. If the strip is removed, a whitespace-only flag (M19) or an empty limit such as OH_JOB_<JOB>__BACKOFF_LIMIT= (M20) stops the worker at startup.

def test_blank_values_fall_back_to_the_defaults():
    assert scheduled_jobs_enabled({FLAG: '   '}) is False
    [item] = configure(
        {
            'OH_JOB_MAINTENANCE_TASKS__ENABLED': 'true',
            'OH_JOB_MAINTENANCE_TASKS__BACKOFF_LIMIT': '',
            'OH_JOB_MAINTENANCE_TASKS__ACTIVE_DEADLINE_SECONDS': ' ',
        }
    )
    assert (item.job.deadline_seconds, item.job.backoff_limit) == (1800, 3)

Verified: passes on this branch unmodified; fails with M19 and with M20 applied.

No hangs and no equivalent mutants.

This comment was generated by an AI assistant on behalf of the user.

@aivong-openhands

Copy link
Copy Markdown
Contributor Author

The killing tests from the mutation review were added in a648a33 (test file only, no source changes).

Mutant Killing test Result
M11: hard-coded backoff_limit test_the_task_hands_the_jobs_settings_to_the_child_runner ❌ caught
M12: hard-coded deadline_seconds test_the_task_hands_the_jobs_settings_to_the_child_runner ❌ caught
M15: succeeded/superseded branches swapped test_the_task_hands_the_jobs_settings_to_the_child_runner (parametrized over superseded) ❌ caught
M18: reserved settings reach the child env test_the_reserved_job_settings_never_reach_the_child ❌ caught
M19: whitespace-only flag raises test_blank_values_fall_back_to_the_defaults ❌ caught
M20: empty integer setting raises test_blank_values_fall_back_to_the_defaults ❌ caught

The unmodified branch passes: test_worker_scheduled_jobs.py + test_worker_queues.py now run 39 passed (35 before). ruff check and ruff format --check are clean on the changed file.

This comment was generated by an AI assistant 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. The change is small and opt-in, and it reuses the existing child runner, housekeeping and procrastinate's periodic and queueing-lock machinery. The tests check real behavior.

Material finding

A malformed cron schedule passes validation and then stops the running worker (inline comment on scheduled_jobs.py). This contradicts the PR's claim that invalid settings stop the worker at startup.

Checked, no issue

  • With the flag off, no tasks are registered and only default is consumed.
  • Each child gets the worker's base env plus only its own OH_JOB_<JOB>__* settings. The OH_JOB_ prefixes cannot overlap, because each ends in __.
  • lock and queueing_lock give at most one run waiting and one running. Procrastinate's defer_jobs skips on AlreadyEnqueued, and housekeeping fails stalled scheduled_jobs jobs.
  • MAINTENANCE_TASK_CLAIM_LEASE_SECONDS is not read on main yet. The PR notes say #691 and #692 must land before those jobs are enabled, so I treat this as deployment ordering and not a defect.
  • CI: build, lint, title and version checks pass on this head. Python tests and budget regressions were still pending when I looked.
  • I could not run the tests myself because there is no Docker daemon for the test Postgres.

[RISK ASSESSMENT]

[Overall PR] ⚠️ Risk Assessment: 🟡 MEDIUM. It adds scheduling inside the worker process, with child-process execution and procrastinate locking. The blast radius is small because it is off by default and touches no chart. Reviewers should focus on overlap with existing CronJobs, since the flag cannot stop another scheduler, and on the merge order with #691, #692 and #693.

Verdict: COMMENT. This would be an approve once the cron validation is tightened, which is a one-line fix plus a test. It is not blocking.

Key insight: the config layer validates its own settings, but procrastinate parses cron expressions later, inside the running worker. Any setting procrastinate checks lazily needs the same validation up front.

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.

@aivong-openhands

Copy link
Copy Markdown
Contributor Author

Addressed the review feedback in 482e9f2.

  • Cron validation: _settle in scheduled_jobs.py now validates schedules with croniter.is_valid(), the same parser procrastinate uses. A malformed expression such as foo bar baz qux quux is now rejected at configuration time with a ScheduledJobsConfigError, instead of stopping the running worker later.
  • Tests: added foo bar baz qux quux and 61 * * * * to the invalid-setting test cases.
  • Verification: I could not run the full pytest suite locally because the repo dependencies (for example litellm) are not installed here. I checked configure() directly: the invalid schedules raise ScheduledJobsConfigError, and all default schedules still validate. Please rely on CI for the full test run.

The inline thread is resolved.

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

@aivong-openhands

Copy link
Copy Markdown
Contributor Author

Local validation — real worker running scheduled jobs

What this checks: with OH_PROCRASTINATE_SCHEDULED_JOBS_ENABLED=true, the worker runs each enabled job's existing module as a child process: on schedule, within its deadline, without blocking the worker, and without leaving the child behind when the worker stops.

Setup: the real worker (python -m openhands.app_server.worker) at 1f542f8, which includes #698 at cf8fed0, against a local Postgres 16 database at alembic 177. The children are the real job modules: sync.clean_app_conversation_start_tasks, and sync.resend_keycloak pointed at a local fake Resend API (RESEND_API_URL) that can hang its requests. Jobs are scheduled every minute through OH_JOB_<JOB>__SCHEDULE.

Scenario Result
app_conversation_start_task_clean enabled worker.started logs queues ["default", "scheduled_jobs"] and jobs ["app_conversation_start_task_clean"]. The job ends succeeded; the child logs Deleted 0 app_conversation_start_task rows older than 1 day(s).
resend_sync hangs on Resend, ACTIVE_DEADLINE_SECONDS=15, BACKOFF_LIMIT=0 At the deadline the child and its process group are stopped (0 processes left), with no retry. The job ends failed; scheduled_jobs.failed with ChildJobDeadlineExceeded.
Worker heartbeat while that child blocks procrastinate_workers.last_heartbeat advances every 10 s.
resend_sync exits 1 (RESEND_AUDIENCE_ID unset); the job is set failed during the 10 s backoff, as housekeeping would scheduled_jobs.superseded (attempts 1); no further attempt starts; the status stays failed.
First SIGTERM to the worker while a child hangs The worker stops taking jobs and waits; the child keeps running.
Second SIGTERM worker.forced_stop; the child is stopped (exit -15), 0 processes left in its group. The job ends failed; scheduled_jobs.failed with ChildJobStopped. The worker exits.

uv run --group test pytest tests/unit/app_server/test_worker_scheduled_jobs.py tests/unit/app_server/test_worker_queues.py tests/unit/app_server/test_worker_child_job.py tests/unit/app_server/test_worker_housekeeping.py: 72 passed.

aivong-openhands and others added 3 commits October 15, 2026 21:18
…TE_SCHEDULED_JOBS_ENABLED

With the flag true (default false), the worker registers each CronJob job
enabled with OH_JOB_<JOB>__ENABLED as a periodic task
scheduled_jobs:<job> on the scheduled_jobs queue, with lock and
queueing_lock scheduled_jobs:<job>, and also consumes that queue. Each
task runs the job's module through run_child_job. OH_JOB_<JOB>__<NAME>
settings reach only that job's child; the maintenance claim lease follows
the longer budget deadline. worker.started logs the flag, queues and jobs.
…roniter

Procrastinate parses cron lazily inside the running worker, where a bad expression stops the whole worker. Reject it at configuration time.

Co-authored-by: openhands <openhands@all-hands.dev>
@aivong-openhands
aivong-openhands force-pushed the task-queue/scheduled-jobs-registration branch from 1f542f8 to 7eb7480 Compare October 15, 2026 21:23
openhands-agent and others added 2 commits October 15, 2026 21:29
Co-authored-by: openhands <openhands@all-hands.dev>
…IGINT

procrastinate handles the first signal and then restores the handler that
was installed before it started. With none, the second signal killed the
worker at once and left each running scheduled job's child process
running. The worker now installs a handler that calls stop_all_children,
so those jobs end as failed once their children are gone.
@aivong-openhands
aivong-openhands force-pushed the task-queue/scheduled-jobs-registration branch from 7eb7480 to 7ae186c Compare October 15, 2026 21:30

Copy link
Copy Markdown
Contributor Author

I am closing this PR together with #698. Procrastinate already gives us what this stack builds. I will open a new, smaller PR that uses periodic and the other native procrastinate features.

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

aivong-openhands added a commit that referenced this pull request Oct 19, 2026
…#874)

* feat(worker): PLTF-3689 schedule the CronJob jobs with procrastinate 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>

* chore(worker): tighten scheduled-jobs comments

Co-authored-by: openhands <openhands@all-hands.dev>

* fix(worker): PLTF-3689 don't retry scheduled jobs

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>

* test(worker): PLTF-3689 pin scheduled job wiring per mutation review

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

* docs(worker): PLTF-3689 note stalled-run overlap in scheduled job comment

Co-authored-by: openhands <openhands@all-hands.dev>

---------

Co-authored-by: openhands <openhands@all-hands.dev>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

type: feat A new feature

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants