Source code for s365b.jobs.liveness

"""Whether a job run is really still running.

A run reports progress every few seconds (see :mod:`s365b.jobs.progress`).
A run that has gone quiet belongs to a worker that stopped (restart,
crash, out of memory): it will never finish, so it is marked interrupted
rather than shown as running forever. Work it committed is kept, and the
next run continues from its last checkpoint.
"""

from __future__ import annotations

import asyncio
import contextlib
from collections.abc import AsyncIterator
from datetime import UTC, datetime, timedelta

from sqlalchemy import select
from sqlalchemy.ext.asyncio import AsyncSession

from s365b.db.models import JobRun, RunKind, RunStatus
from s365b.db.session import Database

# A live run reports at least this often (progress is saved every ~3 s;
# Graph throttling waits are at most 2 minutes and do not block saving).
[docs] LIVE_WITHIN = timedelta(minutes=2)
# Quiet this long: the worker is gone.
[docs] STALE_AFTER = timedelta(minutes=10)
[docs] INTERRUPTED = ( "Interrupted: the worker stopped during this run (restart or crash). What was stored is" " kept; the next run continues from there." )
[docs] INTERRUPTED_RESTORE = ( "Interrupted: the worker stopped during this restore (restart or crash). What was restored" " before that stays restored." )
[docs] HEARTBEAT_EVERY = timedelta(seconds=30)
@contextlib.asynccontextmanager
[docs] async def heartbeat( db: Database, run_id: int, every: timedelta = HEARTBEAT_EVERY ) -> AsyncIterator[None]: """Keep a run marked live while work without progress reports runs. For runs that have no progress to show (retention): only the ``updated_at`` of their progress is refreshed. Args: db: Database. run_id: The running run. every: How often. """ async def beat() -> None: """Refresh the run's heartbeat until it stops running or this is cancelled.""" while True: await asyncio.sleep(every.total_seconds()) async with db.session() as s: run = await s.get(JobRun, run_id) if run is None or run.status is not RunStatus.RUNNING: return run.progress = {**(run.progress or {}), "updated_at": datetime.now(UTC).isoformat()} task = asyncio.create_task(beat()) try: yield finally: task.cancel() with contextlib.suppress(asyncio.CancelledError): await task
[docs] def last_heartbeat(run: JobRun) -> datetime | None: """When the run last reported progress (or started, if it never did). Args: run: The run. Returns: The time, or ``None`` if it has not started. """ updated = (run.progress or {}).get("updated_at") if updated: try: return datetime.fromisoformat(updated) except ValueError: pass return run.started_at
[docs] def is_live(run: JobRun, now: datetime | None = None) -> bool: """Whether a running run has reported progress recently. Args: run: The run. now: Current time. Returns: True if it is running and was heard from within :data:`LIVE_WITHIN`. """ beat = last_heartbeat(run) now = now or datetime.now(UTC) return run.status is RunStatus.RUNNING and beat is not None and now - beat < LIVE_WITHIN
[docs] async def live_run(s: AsyncSession, job_id: int, *, other_than: int | None = None) -> JobRun | None: """Return a live run of a job, if there is one. Args: s: Database session. job_id: The job. other_than: A run to ignore (the caller's own). Returns: The live run, or ``None``. """ stmt = select(JobRun).where(JobRun.job_fk == job_id, JobRun.status == RunStatus.RUNNING) if other_than is not None: stmt = stmt.where(JobRun.id != other_than) for run in (await s.execute(stmt)).scalars(): if is_live(run): return run return None
[docs] async def reap_stale_runs(db: Database, now: datetime | None = None) -> list[int]: """Mark runs whose worker is gone as failed. Args: db: Database. now: Current time. Returns: IDs of the runs marked. """ now = now or datetime.now(UTC) reaped = [] async with db.session() as s: runs = ( ( await s.execute( select(JobRun).where(JobRun.status == RunStatus.RUNNING).with_for_update() ) ) .scalars() .all() ) for run in runs: beat = last_heartbeat(run) if beat is None or now - beat > STALE_AFTER: run.status = RunStatus.FAILED run.finished_at = now run.error = INTERRUPTED_RESTORE if run.kind is RunKind.RESTORE else INTERRUPTED run.progress = dict(run.progress or {}) | {"phase": "done", "active": []} reaped.append(run.id) return reaped