Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ dependencies = [
"browsergym-core==0.13.3", # integrate browsergym-core as the browsing interface
"cloud-sql-python-connector==1.20.1",
"coredis==4.24.0",
"croniter==6.2.4",
"ddtrace==4.8.2", # pin to avoid yanked version 3.12.4
"deprecated==1.3.1",
"deprecation==2.1.0",
Expand Down
Empty file added server/task_queue/__init__.py
Empty file.
75 changes: 75 additions & 0 deletions server/task_queue/app.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
"""Build the Procrastinate app for one worker role."""

from __future__ import annotations

from datetime import UTC, datetime, timedelta

import croniter # type: ignore[import-untyped]
from procrastinate import App, PsycopgConnector

from server.task_queue.config import Settings
from server.task_queue.jobs import JOBS, ScheduledJob
from server.task_queue.tasks import register_tasks

# Enough occurrences to see the longest gap of any schedule that repeats within
# a year, without walking a year of minutes for a minutely one.
_GAP_SAMPLE_OCCURRENCES = 1000


def longest_gap(schedule: str) -> timedelta:
"""Longest interval between consecutive occurrences of a cron schedule."""
start = datetime(2026, 1, 1, tzinfo=UTC)
horizon = start + timedelta(days=366)
it = croniter.croniter(schedule, start)
previous = it.get_next(datetime)
gap = timedelta(0)
for _ in range(_GAP_SAMPLE_OCCURRENCES):
current = it.get_next(datetime)
gap = max(gap, current - previous)
if current > horizon:
break
previous = current
return gap


def scheduled_jobs(settings: Settings) -> list[tuple[ScheduledJob, str]]:
"""The jobs this worker schedules, with the cron expression each uses."""
if not settings.scheduling_enabled:
return []
return [
(job, settings.cron_overrides.get(job.name, job.default_schedule))
for job in JOBS
if job.role == settings.role and job.name in settings.enabled_jobs
]


def build_app(settings: Settings) -> App:
app = App(
connector=PsycopgConnector(
conninfo=settings.conninfo,
min_size=1,
max_size=settings.concurrency + 3,
timeout=settings.pool_timeout,
),
periodic_defaults={'max_delay': settings.max_delay.total_seconds()},
)
register_tasks(app)

for job, schedule in scheduled_jobs(settings):
if not croniter.croniter.is_valid(schedule):
raise ValueError(f'{job.name}: invalid cron schedule {schedule!r}')
gap = longest_gap(schedule)
if gap >= settings.max_delay:
# An occurrence missed at startup would be dropped before any task
# code runs, and nothing downstream could recover it.
raise ValueError(
f'{job.name}: schedule {schedule!r} can leave {gap} between runs, '
f'which is not covered by max_delay {settings.max_delay}'
)
app.periodic_registry.register_task(
task=app.tasks[job.task_name],
cron=schedule,
periodic_id=job.name,
configure_kwargs={},
)
return app
133 changes: 133 additions & 0 deletions server/task_queue/config.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,133 @@
"""Environment-derived settings for the task queue worker.

Everything is read once into a frozen ``Settings``, so tests build settings
directly instead of patching the environment.
"""

from __future__ import annotations

import enum
import os
from dataclasses import dataclass, field
from datetime import timedelta

from psycopg.conninfo import make_conninfo

from openhands.db.ssl import normalize_db_ssl_mode


class Role(str, enum.Enum):
"""Which periodic registrations a worker attaches, and which queue it consumes.

Every worker defines every task; only the matching role schedules them.
Procrastinate's periodic deferrer reads the whole periodic registry and
ignores which queues the worker consumes, so without this an ops worker
would schedule business jobs.
"""

BUSINESS = 'business'
OPS = 'ops'

@property
def queue(self) -> str:
return self.value


# Every attempt a Class A job gets, first run included. Procrastinate counts
# retries, so its RetryStrategy is configured with MAX_ATTEMPTS - 1.
MAX_ATTEMPTS = 3

# A discarded occurrence cannot be recovered downstream, so the deferrer's
# catch-up window has to exceed the longest schedule interval in scope (daily).
DEFAULT_MAX_DELAY = timedelta(hours=26)


def env_flag(name: str, default: str = '0') -> bool:
return os.getenv(name, default).strip().lower() in ('1', 'true')


def _positive_int(name: str, default: int) -> int:
value = int(os.getenv(name, str(default)))
if value <= 0:
raise ValueError(f'{name} must be positive, got {value}')
return value


def conninfo_from_env() -> str:
"""libpq connection string for the worker's psycopg pool.

Uses the app's ``DB_*`` variables. The Cloud SQL connector path
(``GCP_DB_INSTANCE``) hands SQLAlchemy a connection factory, which a psycopg
pool cannot use, so it is refused rather than silently bypassed.
"""
if os.getenv('GCP_DB_INSTANCE'):
raise RuntimeError(
'The task queue worker does not support the Cloud SQL connector '
'(GCP_DB_INSTANCE). Configure DB_HOST instead.'
)
host = os.getenv('DB_HOST')
if not host:
raise RuntimeError('No database configured. Set DB_HOST.')

params: dict[str, str | int] = dict(
host=host,
port=int(os.getenv('DB_PORT', '5432')),
dbname=os.getenv('DB_NAME', 'openhands'),
user=os.getenv('DB_USER', 'postgres'),
password=os.getenv('DB_PASS', 'postgres'),
application_name=f'task-queue-{os.getenv("TASK_QUEUE_ROLE", "worker")}',
connect_timeout=10,
# Detect a dead peer on an established socket: a server-side timeout
# cannot unblock a client read on a black-holed connection.
keepalives=1,
keepalives_idle=30,
keepalives_interval=10,
keepalives_count=3,
tcp_user_timeout=60_000,
)
ssl_mode = normalize_db_ssl_mode(os.getenv('DB_SSL_MODE') or os.getenv('PGSSLMODE'))
if ssl_mode:
params['sslmode'] = ssl_mode
return make_conninfo(**params)


@dataclass(frozen=True)
class Settings:
role: Role
conninfo: str = field(repr=False)
scheduling_enabled: bool = False
enabled_jobs: frozenset[str] = frozenset()
cron_overrides: dict[str, str] = field(default_factory=dict)
max_delay: timedelta = DEFAULT_MAX_DELAY
concurrency: int = 1
update_heartbeat_interval: float = 10.0
stalled_worker_timeout: float = 30.0
fetch_job_polling_interval: float = 5.0
pool_timeout: float = 30.0
listen_notify: bool = True

@classmethod
def from_env(cls) -> Settings:
from server.task_queue.jobs import JOBS

return cls(
role=Role(os.environ['TASK_QUEUE_ROLE'].strip().lower()),
conninfo=conninfo_from_env(),
scheduling_enabled=env_flag('TASK_QUEUE_SCHEDULING_ENABLED'),
enabled_jobs=frozenset(
job.name for job in JOBS if env_flag(job.enabled_env)
),
cron_overrides={
job.name: os.environ[job.schedule_env].strip()
for job in JOBS
if os.getenv(job.schedule_env, '').strip()
},
max_delay=timedelta(
seconds=_positive_int(
'TASK_QUEUE_MAX_DELAY_SECONDS',
int(DEFAULT_MAX_DELAY.total_seconds()),
)
),
concurrency=_positive_int('TASK_QUEUE_CONCURRENCY', 1),
listen_notify=env_flag('TASK_QUEUE_LISTEN_NOTIFY', '1'),
)
79 changes: 79 additions & 0 deletions server/task_queue/jobs.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
"""The scheduled jobs the task queue runs, formerly Kubernetes CronJobs.

Each job calls its existing ``main()`` unchanged. The module is imported only
when the job runs, because some of them build external clients at import
(enrichment needs GitHub App credentials) and a disabled job must not require
its configuration.
"""

from __future__ import annotations

import importlib
from collections.abc import Awaitable, Callable
from dataclasses import dataclass

from server.task_queue.config import Role


@dataclass(frozen=True)
class ScheduledJob:
name: str
role: Role
default_schedule: str
module: str
# Skip an occurrence when a newer one of the same job is already queued,
# running or done. True only for scans where a later run covers everything
# an earlier one would have done.
skip_superseded: bool

@property
def task_name(self) -> str:
return f'scheduled:{self.name}'

@property
def lock(self) -> str:
"""Execution lock: at most one occurrence of the job runs at a time.

Never a queueing_lock. Procrastinate keeps ``queueing_lock`` when it
re-queues a retry, and the queueing-lock index is unique over ``todo``
jobs, so a retry would collide with the next queued occurrence.
"""
return self.task_name

@property
def enabled_env(self) -> str:
return f'TASK_QUEUE_{self.name.upper()}_ENABLED'

@property
def schedule_env(self) -> str:
return f'TASK_QUEUE_{self.name.upper()}_SCHEDULE'

def load(self) -> Callable[[], Awaitable[None]]:
return importlib.import_module(self.module).main


JOBS: tuple[ScheduledJob, ...] = (
ScheduledJob(
name='clean_app_conversation_start_tasks',
role=Role.BUSINESS,
default_schedule='0 3 * * *',
module='sync.clean_app_conversation_start_tasks',
skip_superseded=True,
),
ScheduledJob(
name='clean_proactive_convo_table',
role=Role.BUSINESS,
default_schedule='0 2 * * *',
module='sync.clean_proactive_convo_table',
skip_superseded=True,
),
ScheduledJob(
name='enrich_user_interaction_data',
role=Role.BUSINESS,
default_schedule='*/10 * * * *',
module='sync.enrich_user_interaction_data',
skip_superseded=False,
),
)

JOBS_BY_NAME = {job.name: job for job in JOBS}
Loading
Loading