From 74702ffa40d7a9cc2e3547f5bc5ec471ffb70b86 Mon Sep 17 00:00:00 2001 From: openhands Date: Mon, 19 Oct 2026 15:58:51 +0000 Subject: [PATCH 1/5] 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_ is true. Replaces the child-process approach of #698 and #699. Co-authored-by: openhands --- openhands/app_server/worker/__main__.py | 20 +- openhands/app_server/worker/app.py | 6 + openhands/app_server/worker/scheduled_jobs.py | 125 +++++++++++ run_budget_maintenance.py | 8 +- .../app_server/test_worker_scheduled_jobs.py | 203 ++++++++++++++++++ 5 files changed, 358 insertions(+), 4 deletions(-) create mode 100644 openhands/app_server/worker/scheduled_jobs.py create mode 100644 tests/unit/app_server/test_worker_scheduled_jobs.py diff --git a/openhands/app_server/worker/__main__.py b/openhands/app_server/worker/__main__.py index 5c665579c3..f1a6c3dd7c 100644 --- a/openhands/app_server/worker/__main__.py +++ b/openhands/app_server/worker/__main__.py @@ -17,10 +17,22 @@ from openhands.app_server.utils.logger import openhands_logger # noqa: E402 from openhands.app_server.worker.app import QUEUES, WorkerConfig, app # noqa: E402 from openhands.app_server.worker.database import build_connector # noqa: E402 +from openhands.app_server.worker.housekeeping import SCHEDULED_JOBS_QUEUE # noqa: E402 +from openhands.app_server.worker.scheduled_jobs import ( # noqa: E402 + NAMESPACE, + scheduled_jobs_blueprint, +) async def run() -> None: config: WorkerConfig = from_env(WorkerConfig, 'OH_WORKER') + scheduled = config.scheduled_jobs.enabled() + queues = list(QUEUES) + if scheduled: + app.add_tasks_from( + scheduled_jobs_blueprint(config.scheduled_jobs), namespace=NAMESPACE + ) + queues.append(SCHEDULED_JOBS_QUEUE) connector = build_connector( get_global_config().db_session, # One connection per running job, plus the worker's own queries. @@ -30,9 +42,13 @@ async def run() -> None: async with app.open_async(): openhands_logger.info( 'worker.started', - extra={'concurrency': config.concurrency, 'queues': QUEUES}, + extra={ + 'concurrency': config.concurrency, + 'queues': queues, + 'scheduled_jobs': scheduled, + }, ) - await app.run_worker_async(concurrency=config.concurrency, queues=QUEUES) + await app.run_worker_async(concurrency=config.concurrency, queues=queues) def main() -> None: diff --git a/openhands/app_server/worker/app.py b/openhands/app_server/worker/app.py index ff8e8ec124..727d777c6f 100644 --- a/openhands/app_server/worker/app.py +++ b/openhands/app_server/worker/app.py @@ -5,6 +5,7 @@ from openhands.app_server.sandbox.lifecycle.tasks import lifecycle from openhands.app_server.worker.housekeeping import housekeeping +from openhands.app_server.worker.scheduled_jobs import ScheduledJobsConfig class WorkerConfig(BaseModel): @@ -13,6 +14,11 @@ class WorkerConfig(BaseModel): concurrency: int = Field( default=10, description='How many jobs the worker runs at once.' ) + scheduled_jobs: ScheduledJobsConfig = Field( + default_factory=ScheduledJobsConfig, + description='The CronJob jobs this worker schedules, from ' + '``OH_WORKER_SCHEDULED_JOBS_``.', + ) # procrastinate binds each task to the one app its blueprint is added to, so diff --git a/openhands/app_server/worker/scheduled_jobs.py b/openhands/app_server/worker/scheduled_jobs.py new file mode 100644 index 0000000000..eb4a54e584 --- /dev/null +++ b/openhands/app_server/worker/scheduled_jobs.py @@ -0,0 +1,125 @@ +"""The Kubernetes CronJobs' jobs, as periodic worker tasks. + +For installs without CronJobs, such as Docker Compose. Every job is off until +enabled with ``OH_WORKER_SCHEDULED_JOBS_=true``. Never enable a job on a +database where its CronJob still runs: the two schedules would overlap. + +Schedules, retries and time limits match the OpenHands-Cloud chart's CronJobs. +""" + +import asyncio +from collections.abc import Callable +from typing import Any + +from procrastinate import Blueprint, RetryStrategy +from pydantic import BaseModel + +from openhands.app_server.worker.housekeeping import SCHEDULED_JOBS_QUEUE + +NAMESPACE = 'scheduled_jobs' + +# The CronJobs' backoffLimit, and roughly their pod backoff. +RETRY = RetryStrategy(max_attempts=3, wait=10) + +# The CronJobs' activeDeadlineSeconds, set only on the two budget jobs. +DEADLINE_SECONDS = 1800 + + +class ScheduledJobsConfig(BaseModel): + """Which jobs the worker schedules; all off by default.""" + + budget_maintenance: bool = False + maintenance_tasks: bool = False + app_conversation_start_task_clean: bool = False + proactive_convo_clean: bool = False + resend_sync: bool = False + install_gitlab_webhooks: bool = False + enrich_user_interaction: bool = False + + def enabled(self) -> list[str]: + return [name for name, on in self.model_dump().items() if on] + + +# Each job imports its module when it runs, so the worker loads the job code +# only for the jobs it schedules. + + +async def budget_maintenance(timestamp: int) -> None: + import run_budget_maintenance + + async with asyncio.timeout(DEADLINE_SECONDS): + await run_budget_maintenance.run() + + +async def maintenance_tasks(timestamp: int) -> None: + import run_maintenance_tasks + + async with asyncio.timeout(DEADLINE_SECONDS): + await run_maintenance_tasks.main() + + +async def app_conversation_start_task_clean(timestamp: int) -> None: + from sync import clean_app_conversation_start_tasks + + await clean_app_conversation_start_tasks.main() + + +async def proactive_convo_clean(timestamp: int) -> None: + from sync import clean_proactive_convo_table + + await clean_proactive_convo_table.main() + + +def resend_sync(timestamp: int) -> None: + # Fully synchronous, so procrastinate runs it in a thread. + from sync import resend_keycloak + + resend_keycloak.sync_users_to_resend() + + +async def install_gitlab_webhooks(timestamp: int) -> None: + from sync.install_gitlab_webhooks import VerifyWebhookStatus + + await VerifyWebhookStatus().install_webhooks() + + +async def enrich_user_interaction(timestamp: int) -> None: + from sync import enrich_user_interaction_data + + await enrich_user_interaction_data.main() + + +SCHEDULES: dict[str, tuple[Callable[..., Any], str]] = { + 'budget_maintenance': (budget_maintenance, '*/15 * * * *'), + 'maintenance_tasks': (maintenance_tasks, '0 6 * * *'), + 'app_conversation_start_task_clean': ( + app_conversation_start_task_clean, + '0 3 * * *', + ), + 'proactive_convo_clean': (proactive_convo_clean, '0 2 * * *'), + 'resend_sync': (resend_sync, '0 1 * * *'), + 'install_gitlab_webhooks': (install_gitlab_webhooks, '* * * * *'), + 'enrich_user_interaction': (enrich_user_interaction, '*/10 * * * *'), +} + + +def scheduled_jobs_blueprint(config: ScheduledJobsConfig) -> Blueprint: + """A periodic task for each enabled job. + + ``lock`` and ``queueing_lock`` allow one run waiting and one running, as the + CronJobs' ``concurrencyPolicy: Forbid`` does. + """ + blueprint = Blueprint() + for name in config.enabled(): + func, cron = SCHEDULES[name] + lock = f'{NAMESPACE}:{name}' + task = blueprint.task( + func, + name=name, + queue=SCHEDULED_JOBS_QUEUE, + lock=lock, + queueing_lock=lock, + retry=RETRY, + ) + blueprint.periodic(cron=cron)(task) + return blueprint diff --git a/run_budget_maintenance.py b/run_budget_maintenance.py index 6e5c4704f0..20920ecc92 100644 --- a/run_budget_maintenance.py +++ b/run_budget_maintenance.py @@ -81,7 +81,7 @@ def enqueue_budget_tasks(batch_size: int = BATCH_SIZE) -> int: return len(org_ids) -def main() -> None: +async def run() -> None: # Guard against LiteLLM's interactive device login on this headless entrypoint # (OpenHands/enterprise#565); run_maintenance_tasks.main() installs it too, but # this keeps the protection local to the entrypoint and is idempotent. @@ -97,7 +97,11 @@ def main() -> None: else: logger.info('No org budget settings found; skipping maintenance enqueue') - asyncio.run(run_maintenance_tasks.main()) + await run_maintenance_tasks.main() + + +def main() -> None: + asyncio.run(run()) if __name__ == '__main__': diff --git a/tests/unit/app_server/test_worker_scheduled_jobs.py b/tests/unit/app_server/test_worker_scheduled_jobs.py new file mode 100644 index 0000000000..3dac308f16 --- /dev/null +++ b/tests/unit/app_server/test_worker_scheduled_jobs.py @@ -0,0 +1,203 @@ +"""The CronJob jobs as periodic worker tasks, run by a real worker on this test's Postgres.""" + +import logging +import time + +import psycopg +import pytest +from procrastinate import App, PsycopgConnector + +from openhands.agent_server.env_parser import from_env +from openhands.app_server.utils.logger import openhands_logger +from openhands.app_server.worker import __main__ as worker_main +from openhands.app_server.worker import scheduled_jobs +from openhands.app_server.worker.app import WorkerConfig, app +from openhands.app_server.worker.housekeeping import SCHEDULED_JOBS_QUEUE +from openhands.app_server.worker.scheduled_jobs import ( + NAMESPACE, + ScheduledJobsConfig, + scheduled_jobs_blueprint, +) + +# The OpenHands-Cloud chart's CronJob schedules. +CHART_SCHEDULES = { + 'budget_maintenance': '*/15 * * * *', + 'maintenance_tasks': '0 6 * * *', + 'app_conversation_start_task_clean': '0 3 * * *', + 'proactive_convo_clean': '0 2 * * *', + 'resend_sync': '0 1 * * *', + 'install_gitlab_webhooks': '* * * * *', + 'enrich_user_interaction': '*/10 * * * *', +} +ALL_ON = ScheduledJobsConfig(**dict.fromkeys(CHART_SCHEDULES, True)) + + +def test_every_job_is_off_unless_enabled(monkeypatch): + assert from_env(WorkerConfig, 'OH_WORKER').scheduled_jobs.enabled() == [] + + monkeypatch.setenv('OH_WORKER_SCHEDULED_JOBS_RESEND_SYNC', 'true') + monkeypatch.setenv('OH_WORKER_SCHEDULED_JOBS_BUDGET_MAINTENANCE', '1') + monkeypatch.setenv('OH_WORKER_SCHEDULED_JOBS_MAINTENANCE_TASKS', 'false') + + config = from_env(WorkerConfig, 'OH_WORKER').scheduled_jobs + assert config.enabled() == ['budget_maintenance', 'resend_sync'] + + +def test_only_enabled_jobs_are_scheduled(): + blueprint = scheduled_jobs_blueprint(ScheduledJobsConfig(resend_sync=True)) + + assert list(blueprint.tasks) == ['resend_sync'] + assert scheduled_jobs_blueprint(ScheduledJobsConfig()).tasks == {} + + +def test_each_job_keeps_its_cronjobs_schedule_overlap_policy_and_retries(): + blueprint = scheduled_jobs_blueprint(ALL_ON) + + schedules = {task.name: cron for (task, cron) in _periodic(blueprint).items()} + assert schedules == CHART_SCHEDULES + for name, task in blueprint.tasks.items(): + assert task.queue == SCHEDULED_JOBS_QUEUE + assert task.lock == task.queueing_lock == f'{NAMESPACE}:{name}' + assert task.retry_strategy.max_attempts == 3 + + +def _periodic(blueprint) -> dict: + return { + periodic.task: periodic.cron + for periodic in blueprint.periodic_registry.periodic_tasks.values() + } + + +@pytest.fixture +def restore_app(): + """Undo the tasks ``worker_main.run`` adds to the process-wide app.""" + tasks = dict(app.tasks) + periodic = dict(app.periodic_registry.periodic_tasks) + yield + app.tasks.clear() + app.tasks.update(tasks) + app.periodic_registry.periodic_tasks.clear() + app.periodic_registry.periodic_tasks.update(periodic) + + +@pytest.mark.usefixtures('app_db_session', 'restore_app') +async def test_worker_takes_scheduled_jobs_only_once_one_is_enabled( + monkeypatch, caplog +): + started_with: dict = {} + + async def run_worker_async(**kwargs): + # The real call runs until the process is stopped. + started_with.update(kwargs) + + monkeypatch.setattr(app, 'run_worker_async', run_worker_async) + monkeypatch.setattr(openhands_logger, 'propagate', True) + monkeypatch.setenv('OH_WORKER_SCHEDULED_JOBS_RESEND_SYNC', 'true') + + with caplog.at_level(logging.INFO, logger=openhands_logger.name): + await worker_main.run() + + assert started_with['queues'] == ['default', SCHEDULED_JOBS_QUEUE] + assert f'{NAMESPACE}:resend_sync' in app.tasks + assert not any( + name.startswith(f'{NAMESPACE}:') and name != f'{NAMESPACE}:resend_sync' + for name in app.tasks + ) + [started] = [r for r in caplog.records if r.getMessage() == 'worker.started'] + assert started.scheduled_jobs == ['resend_sync'] + + +@pytest.fixture +def conninfo(test_database) -> dict: + server = test_database.server + return { + 'host': server.host, + 'port': server.port, + 'user': server.user, + 'password': server.password, + 'dbname': test_database.name, + } + + +@pytest.fixture +async def worker_app(conninfo, app_db_session): + worker_app = App( + connector=PsycopgConnector(kwargs=conninfo, min_size=1, max_size=3) + ) + worker_app.add_tasks_from(scheduled_jobs_blueprint(ALL_ON), namespace=NAMESPACE) + async with worker_app.open_async(): + yield worker_app + + +def _sql(conninfo: dict, query: str, *params) -> list[tuple]: + with psycopg.connect(**conninfo, autocommit=True) as connection: + cursor = connection.execute(query, params) + return cursor.fetchall() if cursor.description else [] + + +async def _run_job(worker_app: App, conninfo: dict, name: str) -> tuple[str, int]: + """Run one job to its end on a real worker; its status and attempts after.""" + job_id = await worker_app.configure_task(f'{NAMESPACE}:{name}').defer_async( + timestamp=0 + ) + await worker_app.run_worker_async( + queues=[SCHEDULED_JOBS_QUEUE], wait=False, concurrency=1 + ) + [(status, attempts)] = _sql( + conninfo, + 'SELECT status, attempts FROM procrastinate_jobs WHERE id = %s', + job_id, + ) + return status, attempts + + +async def test_a_job_runs_its_existing_code_in_the_worker(worker_app, conninfo): + _sql( + conninfo, + 'INSERT INTO app_conversation_start_task (id, created_by_user_id, request, created_at) ' + "VALUES (gen_random_uuid(), 'user', '{}', now() - interval '2 days'), " + "(gen_random_uuid(), 'user', '{}', now())", + ) + + status, _ = await _run_job( + worker_app, conninfo, 'app_conversation_start_task_clean' + ) + + assert status == 'succeeded' + # Only the row older than a day is gone. + assert _sql(conninfo, 'SELECT count(*) FROM app_conversation_start_task') == [(1,)] + + +async def test_a_sync_job_that_exits_is_retried_and_the_worker_survives( + worker_app, conninfo, monkeypatch +): + from sync import resend_keycloak + + # The job calls sys.exit(1) without its API key, as its CronJob pod did. + monkeypatch.setattr(resend_keycloak, 'RESEND_API_KEY', None) + + status, attempts = await _run_job(worker_app, conninfo, 'resend_sync') + + assert (status, attempts) == ('todo', 1) + # The worker is still usable after the job's SystemExit. + status, _ = await _run_job(worker_app, conninfo, 'proactive_convo_clean') + assert status == 'succeeded' + + +@pytest.mark.parametrize('name', ['budget_maintenance', 'maintenance_tasks']) +async def test_a_budget_job_is_stopped_at_its_deadline( + worker_app, conninfo, monkeypatch, name +): + monkeypatch.setattr(scheduled_jobs, 'DEADLINE_SECONDS', 1) + # The run waits out a task's delay after processing it. + _sql( + conninfo, + 'INSERT INTO maintenance_tasks (status, processor_type, processor_json, delay) ' + "VALUES ('PENDING', 'not.a.processor', '{}', 600)", + ) + + started = time.monotonic() + status, attempts = await _run_job(worker_app, conninfo, name) + + assert time.monotonic() - started < 30 + assert (status, attempts) == ('todo', 1) From cc6e9d6a3996e11ceb48a752d1421b34a11dfc54 Mon Sep 17 00:00:00 2001 From: openhands Date: Mon, 19 Oct 2026 16:31:01 +0000 Subject: [PATCH 2/5] chore(worker): tighten scheduled-jobs comments Co-authored-by: openhands --- openhands/app_server/worker/scheduled_jobs.py | 19 +++++++++---------- .../app_server/test_worker_scheduled_jobs.py | 5 +++-- 2 files changed, 12 insertions(+), 12 deletions(-) diff --git a/openhands/app_server/worker/scheduled_jobs.py b/openhands/app_server/worker/scheduled_jobs.py index eb4a54e584..ad7d94cb0a 100644 --- a/openhands/app_server/worker/scheduled_jobs.py +++ b/openhands/app_server/worker/scheduled_jobs.py @@ -2,7 +2,7 @@ For installs without CronJobs, such as Docker Compose. Every job is off until enabled with ``OH_WORKER_SCHEDULED_JOBS_=true``. Never enable a job on a -database where its CronJob still runs: the two schedules would overlap. +database where its CronJob still runs, or both will run it. Schedules, retries and time limits match the OpenHands-Cloud chart's CronJobs. """ @@ -26,7 +26,7 @@ class ScheduledJobsConfig(BaseModel): - """Which jobs the worker schedules; all off by default.""" + """Which jobs the worker schedules.""" budget_maintenance: bool = False maintenance_tasks: bool = False @@ -40,8 +40,8 @@ def enabled(self) -> list[str]: return [name for name, on in self.model_dump().items() if on] -# Each job imports its module when it runs, so the worker loads the job code -# only for the jobs it schedules. +# Each job imports its module when it runs: some modules build API clients or +# read their settings at import, which a worker not scheduling that job shouldn't do. async def budget_maintenance(timestamp: int) -> None: @@ -71,7 +71,8 @@ async def proactive_convo_clean(timestamp: int) -> None: def resend_sync(timestamp: int) -> None: - # Fully synchronous, so procrastinate runs it in a thread. + # A plain def, so procrastinate runs it in a thread where its blocking calls + # can't stall the other jobs. from sync import resend_keycloak resend_keycloak.sync_users_to_resend() @@ -104,14 +105,12 @@ async def enrich_user_interaction(timestamp: int) -> None: def scheduled_jobs_blueprint(config: ScheduledJobsConfig) -> Blueprint: - """A periodic task for each enabled job. - - ``lock`` and ``queueing_lock`` allow one run waiting and one running, as the - CronJobs' ``concurrencyPolicy: Forbid`` does. - """ + """A periodic task for each enabled job.""" blueprint = Blueprint() for name in config.enabled(): func, cron = SCHEDULES[name] + # Runs never overlap, as under the CronJobs' concurrencyPolicy: Forbid, but + # one run that comes due meanwhile waits instead of being skipped. lock = f'{NAMESPACE}:{name}' task = blueprint.task( func, diff --git a/tests/unit/app_server/test_worker_scheduled_jobs.py b/tests/unit/app_server/test_worker_scheduled_jobs.py index 3dac308f16..1ac82579fd 100644 --- a/tests/unit/app_server/test_worker_scheduled_jobs.py +++ b/tests/unit/app_server/test_worker_scheduled_jobs.py @@ -136,7 +136,7 @@ def _sql(conninfo: dict, query: str, *params) -> list[tuple]: async def _run_job(worker_app: App, conninfo: dict, name: str) -> tuple[str, int]: - """Run one job to its end on a real worker; its status and attempts after.""" + """Run one job to its end on a real worker and return its status and attempts.""" job_id = await worker_app.configure_task(f'{NAMESPACE}:{name}').defer_async( timestamp=0 ) @@ -189,7 +189,8 @@ async def test_a_budget_job_is_stopped_at_its_deadline( worker_app, conninfo, monkeypatch, name ): monkeypatch.setattr(scheduled_jobs, 'DEADLINE_SECONDS', 1) - # The run waits out a task's delay after processing it. + # run_maintenance_tasks sleeps for a task's delay after processing it, so this + # row keeps the job running past its deadline. _sql( conninfo, 'INSERT INTO maintenance_tasks (status, processor_type, processor_json, delay) ' From bc47c0408d7e6385bde165212f241b955fbb8389 Mon Sep 17 00:00:00 2001 From: openhands Date: Mon, 19 Oct 2026 17:09:32 +0000 Subject: [PATCH 3/5] 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/app_server/worker/scheduled_jobs.py | 13 ++-- .../app_server/test_worker_scheduled_jobs.py | 68 ++++++++++++++++--- 2 files changed, 66 insertions(+), 15 deletions(-) diff --git a/openhands/app_server/worker/scheduled_jobs.py b/openhands/app_server/worker/scheduled_jobs.py index ad7d94cb0a..ca2dda8260 100644 --- a/openhands/app_server/worker/scheduled_jobs.py +++ b/openhands/app_server/worker/scheduled_jobs.py @@ -4,23 +4,21 @@ enabled with ``OH_WORKER_SCHEDULED_JOBS_=true``. Never enable a job on a database where its CronJob still runs, or both will run it. -Schedules, retries and time limits match the OpenHands-Cloud chart's CronJobs. +Schedules and time limits match the OpenHands-Cloud chart's CronJobs. A failed +run isn't retried; the next scheduled run is the retry. """ import asyncio from collections.abc import Callable from typing import Any -from procrastinate import Blueprint, RetryStrategy +from procrastinate import Blueprint from pydantic import BaseModel from openhands.app_server.worker.housekeeping import SCHEDULED_JOBS_QUEUE NAMESPACE = 'scheduled_jobs' -# The CronJobs' backoffLimit, and roughly their pod backoff. -RETRY = RetryStrategy(max_attempts=3, wait=10) - # The CronJobs' activeDeadlineSeconds, set only on the two budget jobs. DEADLINE_SECONDS = 1800 @@ -110,7 +108,9 @@ def scheduled_jobs_blueprint(config: ScheduledJobsConfig) -> Blueprint: for name in config.enabled(): func, cron = SCHEDULES[name] # Runs never overlap, as under the CronJobs' concurrencyPolicy: Forbid, but - # one run that comes due meanwhile waits instead of being skipped. + # one run that comes due meanwhile waits instead of being skipped. No + # retry=: a retry returns the failed run to todo, which that waiting run's + # queueing lock forbids, so the failed run would stay doing and hold lock. lock = f'{NAMESPACE}:{name}' task = blueprint.task( func, @@ -118,7 +118,6 @@ def scheduled_jobs_blueprint(config: ScheduledJobsConfig) -> Blueprint: queue=SCHEDULED_JOBS_QUEUE, lock=lock, queueing_lock=lock, - retry=RETRY, ) blueprint.periodic(cron=cron)(task) return blueprint diff --git a/tests/unit/app_server/test_worker_scheduled_jobs.py b/tests/unit/app_server/test_worker_scheduled_jobs.py index 1ac82579fd..009ee11f73 100644 --- a/tests/unit/app_server/test_worker_scheduled_jobs.py +++ b/tests/unit/app_server/test_worker_scheduled_jobs.py @@ -1,5 +1,7 @@ """The CronJob jobs as periodic worker tasks, run by a real worker on this test's Postgres.""" +import asyncio +import contextlib import logging import time @@ -50,7 +52,7 @@ def test_only_enabled_jobs_are_scheduled(): assert scheduled_jobs_blueprint(ScheduledJobsConfig()).tasks == {} -def test_each_job_keeps_its_cronjobs_schedule_overlap_policy_and_retries(): +def test_each_job_keeps_its_cronjobs_schedule_and_overlap_policy(): blueprint = scheduled_jobs_blueprint(ALL_ON) schedules = {task.name: cron for (task, cron) in _periodic(blueprint).items()} @@ -58,7 +60,7 @@ def test_each_job_keeps_its_cronjobs_schedule_overlap_policy_and_retries(): for name, task in blueprint.tasks.items(): assert task.queue == SCHEDULED_JOBS_QUEUE assert task.lock == task.queueing_lock == f'{NAMESPACE}:{name}' - assert task.retry_strategy.max_attempts == 3 + assert task.retry_strategy is None def _periodic(blueprint) -> dict: @@ -119,16 +121,22 @@ def conninfo(test_database) -> dict: } -@pytest.fixture -async def worker_app(conninfo, app_db_session): +@contextlib.asynccontextmanager +async def _open_worker_app(conninfo: dict, config: ScheduledJobsConfig): worker_app = App( connector=PsycopgConnector(kwargs=conninfo, min_size=1, max_size=3) ) - worker_app.add_tasks_from(scheduled_jobs_blueprint(ALL_ON), namespace=NAMESPACE) + worker_app.add_tasks_from(scheduled_jobs_blueprint(config), namespace=NAMESPACE) async with worker_app.open_async(): yield worker_app +@pytest.fixture +async def worker_app(conninfo, app_db_session): + async with _open_worker_app(conninfo, ALL_ON) as worker_app: + yield worker_app + + def _sql(conninfo: dict, query: str, *params) -> list[tuple]: with psycopg.connect(**conninfo, autocommit=True) as connection: cursor = connection.execute(query, params) @@ -168,7 +176,7 @@ async def test_a_job_runs_its_existing_code_in_the_worker(worker_app, conninfo): assert _sql(conninfo, 'SELECT count(*) FROM app_conversation_start_task') == [(1,)] -async def test_a_sync_job_that_exits_is_retried_and_the_worker_survives( +async def test_a_sync_job_that_exits_fails_and_the_worker_survives( worker_app, conninfo, monkeypatch ): from sync import resend_keycloak @@ -178,7 +186,7 @@ async def test_a_sync_job_that_exits_is_retried_and_the_worker_survives( status, attempts = await _run_job(worker_app, conninfo, 'resend_sync') - assert (status, attempts) == ('todo', 1) + assert (status, attempts) == ('failed', 1) # The worker is still usable after the job's SystemExit. status, _ = await _run_job(worker_app, conninfo, 'proactive_convo_clean') assert status == 'succeeded' @@ -201,4 +209,48 @@ async def test_a_budget_job_is_stopped_at_its_deadline( status, attempts = await _run_job(worker_app, conninfo, name) assert time.monotonic() - started < 30 - assert (status, attempts) == ('todo', 1) + assert (status, attempts) == ('failed', 1) + + +async def _wait_for(conninfo: dict, job_id: int, statuses: set[str]) -> str: + for _ in range(200): + [(status,)] = _sql( + conninfo, 'SELECT status FROM procrastinate_jobs WHERE id = %s', job_id + ) + if status in statuses: + return status + await asyncio.sleep(0.1) + return status + + +@pytest.mark.usefixtures('app_db_session') +async def test_a_run_that_fails_while_the_next_waits_lets_the_next_start( + conninfo, monkeypatch +): + monkeypatch.setattr(scheduled_jobs, 'DEADLINE_SECONDS', 1) + # The first run claims this row and sleeps past its deadline. The second finds + # the row claimed, so it has nothing to do and succeeds. + _sql( + conninfo, + 'INSERT INTO maintenance_tasks (status, processor_type, processor_json, delay) ' + "VALUES ('PENDING', 'not.a.processor', '{}', 600)", + ) + config = ScheduledJobsConfig(maintenance_tasks=True) + async with _open_worker_app(conninfo, config) as worker_app: + task = worker_app.configure_task(f'{NAMESPACE}:maintenance_tasks') + first = await task.defer_async(timestamp=0) + worker = asyncio.create_task( + worker_app.run_worker_async(queues=[SCHEDULED_JOBS_QUEUE], concurrency=2) + ) + try: + assert await _wait_for(conninfo, first, {'doing'}) == 'doing' + second = await task.defer_async(timestamp=1) + + assert await _wait_for(conninfo, first, {'failed'}) == 'failed' + assert await _wait_for(conninfo, second, {'succeeded', 'failed'}) == ( + 'succeeded' + ) + finally: + worker.cancel() + with contextlib.suppress(asyncio.CancelledError): + await worker From 90c6c7d3b676141fe97ee2fbc4cd8c7dee24fe92 Mon Sep 17 00:00:00 2001 From: openhands Date: Mon, 19 Oct 2026 18:49:10 +0000 Subject: [PATCH 4/5] 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 --- .../app_server/test_worker_scheduled_jobs.py | 118 +++++++++++++++--- 1 file changed, 98 insertions(+), 20 deletions(-) diff --git a/tests/unit/app_server/test_worker_scheduled_jobs.py b/tests/unit/app_server/test_worker_scheduled_jobs.py index 009ee11f73..9df67bfa8f 100644 --- a/tests/unit/app_server/test_worker_scheduled_jobs.py +++ b/tests/unit/app_server/test_worker_scheduled_jobs.py @@ -9,6 +9,7 @@ import pytest from procrastinate import App, PsycopgConnector +import run_budget_maintenance from openhands.agent_server.env_parser import from_env from openhands.app_server.utils.logger import openhands_logger from openhands.app_server.worker import __main__ as worker_main @@ -33,6 +34,20 @@ } ALL_ON = ScheduledJobsConfig(**dict.fromkeys(CHART_SCHEDULES, True)) +# 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', +} + +# A lost deadline would otherwise hang the suite on the planted delay=600 row. +pytestmark = pytest.mark.timeout(60) + def test_every_job_is_off_unless_enabled(monkeypatch): assert from_env(WorkerConfig, 'OH_WORKER').scheduled_jobs.enabled() == [] @@ -109,6 +124,33 @@ async def run_worker_async(**kwargs): assert started.scheduled_jobs == ['resend_sync'] +@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'] + + +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] + + @pytest.fixture def conninfo(test_database) -> dict: server = test_database.server @@ -123,6 +165,7 @@ def conninfo(test_database) -> dict: @contextlib.asynccontextmanager async def _open_worker_app(conninfo: dict, config: ScheduledJobsConfig): + """Only ``config``'s jobs, so no other job's periodic run comes due mid-test.""" worker_app = App( connector=PsycopgConnector(kwargs=conninfo, min_size=1, max_size=3) ) @@ -131,12 +174,6 @@ async def _open_worker_app(conninfo: dict, config: ScheduledJobsConfig): yield worker_app -@pytest.fixture -async def worker_app(conninfo, app_db_session): - async with _open_worker_app(conninfo, ALL_ON) as worker_app: - yield worker_app - - def _sql(conninfo: dict, query: str, *params) -> list[tuple]: with psycopg.connect(**conninfo, autocommit=True) as connection: cursor = connection.execute(query, params) @@ -159,7 +196,8 @@ async def _run_job(worker_app: App, conninfo: dict, name: str) -> tuple[str, int return status, attempts -async def test_a_job_runs_its_existing_code_in_the_worker(worker_app, conninfo): +@pytest.mark.usefixtures('app_db_session') +async def test_a_job_runs_its_existing_code_in_the_worker(conninfo): _sql( conninfo, 'INSERT INTO app_conversation_start_task (id, created_by_user_id, request, created_at) ' @@ -167,35 +205,39 @@ async def test_a_job_runs_its_existing_code_in_the_worker(worker_app, conninfo): "(gen_random_uuid(), 'user', '{}', now())", ) - status, _ = await _run_job( - worker_app, conninfo, 'app_conversation_start_task_clean' - ) + config = ScheduledJobsConfig(app_conversation_start_task_clean=True) + async with _open_worker_app(conninfo, config) as worker_app: + status, _ = await _run_job( + worker_app, conninfo, 'app_conversation_start_task_clean' + ) assert status == 'succeeded' # Only the row older than a day is gone. assert _sql(conninfo, 'SELECT count(*) FROM app_conversation_start_task') == [(1,)] +@pytest.mark.usefixtures('app_db_session') async def test_a_sync_job_that_exits_fails_and_the_worker_survives( - worker_app, conninfo, monkeypatch + conninfo, monkeypatch ): from sync import resend_keycloak # The job calls sys.exit(1) without its API key, as its CronJob pod did. monkeypatch.setattr(resend_keycloak, 'RESEND_API_KEY', None) - status, attempts = await _run_job(worker_app, conninfo, 'resend_sync') + config = ScheduledJobsConfig(resend_sync=True, proactive_convo_clean=True) + async with _open_worker_app(conninfo, config) as worker_app: + status, attempts = await _run_job(worker_app, conninfo, 'resend_sync') - assert (status, attempts) == ('failed', 1) - # The worker is still usable after the job's SystemExit. - status, _ = await _run_job(worker_app, conninfo, 'proactive_convo_clean') - assert status == 'succeeded' + assert (status, attempts) == ('failed', 1) + # The worker is still usable after the job's SystemExit. + status, _ = await _run_job(worker_app, conninfo, 'proactive_convo_clean') + assert status == 'succeeded' +@pytest.mark.usefixtures('app_db_session') @pytest.mark.parametrize('name', ['budget_maintenance', 'maintenance_tasks']) -async def test_a_budget_job_is_stopped_at_its_deadline( - worker_app, conninfo, monkeypatch, name -): +async def test_a_budget_job_is_stopped_at_its_deadline(conninfo, monkeypatch, name): monkeypatch.setattr(scheduled_jobs, 'DEADLINE_SECONDS', 1) # run_maintenance_tasks sleeps for a task's delay after processing it, so this # row keeps the job running past its deadline. @@ -206,12 +248,48 @@ async def test_a_budget_job_is_stopped_at_its_deadline( ) started = time.monotonic() - status, attempts = await _run_job(worker_app, conninfo, name) + async with _open_worker_app( + conninfo, ScheduledJobsConfig(**{name: True}) + ) as worker_app: + status, attempts = await _run_job(worker_app, conninfo, name) assert time.monotonic() - started < 30 assert (status, attempts) == ('failed', 1) +@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) + + 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'} + + async def _wait_for(conninfo: dict, job_id: int, statuses: set[str]) -> str: for _ in range(200): [(status,)] = _sql( From d525fb9758b62d35d1c4dd50db2c2428d78cc07a Mon Sep 17 00:00:00 2001 From: openhands Date: Mon, 19 Oct 2026 20:17:15 +0000 Subject: [PATCH 5/5] docs(worker): PLTF-3689 note stalled-run overlap in scheduled job comment Co-authored-by: openhands --- openhands/app_server/worker/scheduled_jobs.py | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/openhands/app_server/worker/scheduled_jobs.py b/openhands/app_server/worker/scheduled_jobs.py index ca2dda8260..6b8f818a67 100644 --- a/openhands/app_server/worker/scheduled_jobs.py +++ b/openhands/app_server/worker/scheduled_jobs.py @@ -107,9 +107,11 @@ def scheduled_jobs_blueprint(config: ScheduledJobsConfig) -> Blueprint: blueprint = Blueprint() for name in config.enabled(): func, cron = SCHEDULES[name] - # Runs never overlap, as under the CronJobs' concurrencyPolicy: Forbid, but - # one run that comes due meanwhile waits instead of being skipped. No - # retry=: a retry returns the failed run to todo, which that waiting run's + # Runs don't overlap, as under the CronJobs' concurrencyPolicy: Forbid, but + # one run that comes due meanwhile waits instead of being skipped. The + # exception is a run that housekeeping ends as stalled while its worker is + # still alive: it keeps going beside the next run, so jobs must tolerate that. + # No retry=: a retry returns the failed run to todo, which that waiting run's # queueing lock forbids, so the failed run would stay doing and hold lock. lock = f'{NAMESPACE}:{name}' task = blueprint.task(