simple-module-background-tasks 0.0.1__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1 @@
1
+ """BackgroundTasks module — Celery + Redis task queue with admin UI."""
@@ -0,0 +1,105 @@
1
+ """Signal-handler helpers shared across :mod:`background_tasks.signals`.
2
+
3
+ Kept in a separate module so :mod:`.signals` stays under the 300-line cap.
4
+ These helpers are intentionally side-effect-free except for the DB write in
5
+ ``upsert_by_celery_id`` — signal handlers compose them.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import traceback as tb_mod
11
+ from datetime import UTC, datetime
12
+ from typing import Any
13
+
14
+ from sqlalchemy import select
15
+ from sqlalchemy.orm import Session
16
+
17
+ from background_tasks.models import TaskExecution
18
+
19
+
20
+ def now_utc() -> datetime:
21
+ return datetime.now(UTC)
22
+
23
+
24
+ def coerce_args_kwargs(args: Any, kwargs: Any) -> tuple[list[Any], dict[str, Any]]:
25
+ """Normalise Celery args/kwargs payloads to JSON-ready shapes.
26
+
27
+ Celery sometimes hands us tuples/frozensets that our JSON column can't
28
+ store; also tolerates ``None`` so a partial payload won't wedge the row.
29
+ """
30
+ safe_args: list[Any] = list(args) if args else []
31
+ safe_kwargs: dict[str, Any] = dict(kwargs) if kwargs else {}
32
+ return safe_args, safe_kwargs
33
+
34
+
35
+ def upsert_by_celery_id(
36
+ session: Session,
37
+ *,
38
+ celery_task_id: str | None,
39
+ defaults: dict[str, Any],
40
+ ) -> TaskExecution:
41
+ """Fetch the row for ``celery_task_id``, or create it from ``defaults``.
42
+
43
+ ``defaults`` must include ``task_name`` (it's NOT NULL on the table).
44
+ Handlers never race on the same row within a worker process — Celery
45
+ serialises per-task signals — so this is upsert-by-read, no advisory
46
+ locks needed.
47
+ """
48
+ row: TaskExecution | None = None
49
+ if celery_task_id:
50
+ stmt = select(TaskExecution).where(TaskExecution.celery_task_id == celery_task_id)
51
+ row = session.execute(stmt).scalar_one_or_none()
52
+ if row is None:
53
+ row = TaskExecution(celery_task_id=celery_task_id, **defaults)
54
+ session.add(row)
55
+ else:
56
+ for key, value in defaults.items():
57
+ setattr(row, key, value)
58
+ return row
59
+
60
+
61
+ def task_name_of(sender: Any, task: Any = None) -> str:
62
+ """Best-effort resolution of a task's registered name from signal args."""
63
+ return (
64
+ (isinstance(sender, str) and sender)
65
+ or getattr(task, "name", None)
66
+ or getattr(sender, "name", None)
67
+ or "unknown"
68
+ )
69
+
70
+
71
+ def task_id_from(sender: Any = None, request: Any = None) -> str | None:
72
+ """Pull the Celery task UUID out of whichever signal-arg carries it.
73
+
74
+ Celery's signals pass the task id via three different shapes depending
75
+ on the signal: ``task_id=`` kwarg, ``request.id``, or ``sender.request.id``.
76
+ Centralising the probe keeps the per-handler code boring.
77
+ """
78
+ if request is not None:
79
+ tid = getattr(request, "id", None)
80
+ if tid:
81
+ return tid
82
+ sender_request = getattr(sender, "request", None)
83
+ return getattr(sender_request, "id", None) if sender_request is not None else None
84
+
85
+
86
+ def jsonable_result(result: Any) -> dict[str, Any] | None:
87
+ """Wrap arbitrary task results in a JSON-storable shape."""
88
+ if result is None:
89
+ return None
90
+ if isinstance(result, dict):
91
+ return result
92
+ try:
93
+ return {"value": result}
94
+ except Exception:
95
+ return {"value": repr(result)}
96
+
97
+
98
+ def render_traceback(einfo: Any, exception: BaseException | None) -> str | None:
99
+ """Prefer Celery's pre-formatted traceback; fall back to the live exception."""
100
+ tb = getattr(einfo, "traceback", None)
101
+ if tb:
102
+ return str(tb)
103
+ if exception is not None:
104
+ return "".join(tb_mod.format_exception(type(exception), exception, exception.__traceback__))
105
+ return None
@@ -0,0 +1,95 @@
1
+ """Build and configure the Celery application.
2
+
3
+ Invoked from two places:
4
+
5
+ - :meth:`BackgroundTasksModule.on_startup` in the web process, so the API
6
+ can enqueue tasks via ``app.state.background_tasks.celery.send_task(...)``.
7
+ - ``scripts/run_worker.py`` at worker boot, so the worker process uses an
8
+ identical config (broker URL, signal handlers, autodiscovered tasks).
9
+
10
+ Task discovery uses :py:meth:`celery.Celery.autodiscover_tasks` with the
11
+ top-level package name of every installed module (enumerated via the
12
+ ``simple_module`` entry-point group). Any module that ships a ``tasks.py``
13
+ is picked up automatically — no framework hook, no per-module registration.
14
+ """
15
+
16
+ from __future__ import annotations
17
+
18
+ import logging
19
+ from importlib.metadata import entry_points
20
+
21
+ from celery import Celery
22
+ from celery.schedules import schedule
23
+ from simple_module_core.discovery import ENTRY_POINT_GROUP
24
+
25
+ from background_tasks.constants import (
26
+ INTERNAL_TASK_PURGE_OLD,
27
+ INTERNAL_TASK_SWEEP_STUCK,
28
+ MODULE_NAME,
29
+ )
30
+ from background_tasks.settings import BackgroundTasksSettings
31
+
32
+ logger = logging.getLogger(__name__)
33
+
34
+
35
+ def _discover_task_packages() -> list[str]:
36
+ """Return the top-level package name of every installed simple_module.
37
+
38
+ Celery's ``autodiscover_tasks`` imports ``<package>.tasks`` for each name
39
+ returned here, so any module that ships a ``tasks.py`` registers its
40
+ tasks without a per-module hook.
41
+ """
42
+ packages: set[str] = set()
43
+ for ep in entry_points(group=ENTRY_POINT_GROUP):
44
+ module_path = ep.value.split(":", 1)[0]
45
+ top_level = module_path.split(".", 1)[0]
46
+ packages.add(top_level)
47
+ return sorted(packages)
48
+
49
+
50
+ def build_celery(settings: BackgroundTasksSettings) -> Celery:
51
+ """Construct a Celery app wired to the project's Redis broker."""
52
+ celery = Celery(MODULE_NAME)
53
+
54
+ celery.conf.update(
55
+ broker_url=settings.broker_url,
56
+ result_backend=settings.result_backend,
57
+ task_default_queue=settings.task_default_queue,
58
+ # ``task_track_started`` gives us the ``STARTED`` state so
59
+ # ``task_prerun`` can flip our row to ``running``.
60
+ task_track_started=True,
61
+ # ``task_acks_late`` + ``worker_prefetch_multiplier=1`` gives us
62
+ # at-least-once semantics, which matches how the admin UI asks users
63
+ # to think about retries — duplicates beat lost work.
64
+ task_acks_late=True,
65
+ worker_prefetch_multiplier=1,
66
+ task_serializer="json",
67
+ result_serializer="json",
68
+ accept_content=["json"],
69
+ timezone="UTC",
70
+ enable_utc=True,
71
+ broker_connection_retry_on_startup=True,
72
+ beat_schedule={
73
+ "background-tasks-sweep-stuck": {
74
+ "task": INTERNAL_TASK_SWEEP_STUCK,
75
+ "schedule": schedule(settings.stuck_sweep_interval_seconds),
76
+ },
77
+ "background-tasks-purge-old": {
78
+ "task": INTERNAL_TASK_PURGE_OLD,
79
+ "schedule": schedule(settings.purge_interval_seconds),
80
+ },
81
+ },
82
+ beat_scheduler="celery.beat:PersistentScheduler",
83
+ )
84
+
85
+ # Autodiscover across every installed simple_module — a module just ships
86
+ # a `tasks.py` and the worker picks it up.
87
+ packages = _discover_task_packages()
88
+ logger.info("Celery autodiscover_tasks across: %s", packages)
89
+ celery.autodiscover_tasks(packages, related_name="tasks", force=True)
90
+
91
+ # Side-effect import: connects signal handlers to this Celery instance's
92
+ # ``celery.signals.*`` globals. Safe to import repeatedly.
93
+ from background_tasks import signals # noqa: F401
94
+
95
+ return celery
@@ -0,0 +1,75 @@
1
+ """Single source of truth for background_tasks module string literals.
2
+
3
+ Anything that would otherwise become a magic string — table names, env-var
4
+ prefixes, permission codes, route segments, page identifiers, task-status
5
+ values — lives here so models, signals, services, endpoints, tests, and
6
+ the frontend all agree on one spelling.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ from enum import StrEnum
12
+
13
+ # ── Module identity ─────────────────────────────────────────────
14
+ MODULE_NAME = "background_tasks"
15
+ MODULE_DISPLAY_NAME = "BackgroundTasks"
16
+ TABLE_PREFIX = "background_tasks_"
17
+ TABLE_TASK_EXECUTION = f"{TABLE_PREFIX}task_execution"
18
+
19
+ # ── Env / settings ──────────────────────────────────────────────
20
+ ENV_PREFIX = "SM_BG_TASKS_"
21
+
22
+ # ── Permissions ─────────────────────────────────────────────────
23
+ PERM_GROUP = "Background Tasks"
24
+ PERM_VIEW = "background_tasks.view"
25
+ PERM_MANAGE = "background_tasks.manage"
26
+
27
+ # ── Routes ──────────────────────────────────────────────────────
28
+ API_PREFIX = "/api/background_tasks"
29
+ VIEW_PREFIX = "/admin/background-tasks"
30
+ ADMIN_ROUTER_PREFIX = "/admin"
31
+
32
+ # ── Menu ────────────────────────────────────────────────────────
33
+ MENU_LABEL = "Background Tasks"
34
+ MENU_ICON = "activity"
35
+ MENU_ORDER = 80
36
+
37
+ # ── Page identifiers ────────────────────────────────────────────
38
+ # Kept as literals at the call site (see endpoints/views.py) so
39
+ # ``make doctor``'s SM003/SM004 static analysis can match pages to renders.
40
+
41
+
42
+ # ── Task statuses ───────────────────────────────────────────────
43
+ class TaskStatus(StrEnum):
44
+ """Lifecycle state of a single task execution row."""
45
+
46
+ PENDING = "pending"
47
+ RUNNING = "running"
48
+ SUCCESS = "success"
49
+ FAILED = "failed"
50
+ STUCK = "stuck"
51
+ REVOKED = "revoked"
52
+ RETRYING = "retrying"
53
+
54
+
55
+ RETRYABLE_STATUSES: frozenset[TaskStatus] = frozenset({TaskStatus.FAILED, TaskStatus.STUCK})
56
+ TERMINAL_STATUSES: frozenset[TaskStatus] = frozenset(
57
+ {TaskStatus.SUCCESS, TaskStatus.FAILED, TaskStatus.STUCK, TaskStatus.REVOKED}
58
+ )
59
+
60
+ # ── Defaults ────────────────────────────────────────────────────
61
+ DEFAULT_QUEUE = "default"
62
+ DEFAULT_BROKER_URL = "redis://localhost:6379/0"
63
+ DEFAULT_RESULT_BACKEND = "redis://localhost:6379/1"
64
+ DEFAULT_STUCK_AFTER_SECONDS = 300
65
+ DEFAULT_STUCK_SWEEP_INTERVAL_SECONDS = 60
66
+ DEFAULT_PURGE_INTERVAL_SECONDS = 60 * 60 * 24
67
+ DEFAULT_RETENTION_DAYS = 14
68
+ DEFAULT_MAX_RETRIES = 3
69
+
70
+ # ── Internal task names ─────────────────────────────────────────
71
+ INTERNAL_TASK_SWEEP_STUCK = "background_tasks.sweep_stuck_tasks"
72
+ INTERNAL_TASK_PURGE_OLD = "background_tasks.purge_old_executions"
73
+ # Harmless round-trip task; only wired into CI smoke tests and local dev —
74
+ # not scheduled, not invoked by other modules.
75
+ DEMO_ECHO_TASK = "background_tasks.demo_echo"
@@ -0,0 +1 @@
1
+ """Public contracts for the BackgroundTasks module."""
@@ -0,0 +1,26 @@
1
+ """Public events emitted by the BackgroundTasks module."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import uuid
6
+ from dataclasses import dataclass
7
+
8
+ from simple_module_core.events import Event
9
+
10
+
11
+ @dataclass
12
+ class TaskFailed(Event):
13
+ """A task transitioned to ``failed`` — subscribers may alert/log."""
14
+
15
+ task_execution_id: uuid.UUID
16
+ task_name: str
17
+ exception_type: str | None
18
+
19
+
20
+ @dataclass
21
+ class TaskRetried(Event):
22
+ """A failed/stuck task was manually retried via the admin UI."""
23
+
24
+ original_id: uuid.UUID
25
+ new_id: uuid.UUID
26
+ task_name: str
@@ -0,0 +1,66 @@
1
+ """DTOs returned by the BackgroundTasks admin API / views."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import uuid
6
+ from datetime import datetime
7
+ from typing import Any
8
+
9
+ from pydantic import ConfigDict
10
+ from sqlmodel import SQLModel
11
+
12
+ from background_tasks.constants import TaskStatus
13
+
14
+
15
+ class TaskExecutionListItem(SQLModel):
16
+ """Compact row for the admin listing table."""
17
+
18
+ model_config = ConfigDict(from_attributes=True)
19
+
20
+ id: uuid.UUID
21
+ celery_task_id: str | None = None
22
+ task_name: str
23
+ status: TaskStatus
24
+ queue: str
25
+ retries: int
26
+ worker: str | None = None
27
+ queued_at: datetime | None = None
28
+ started_at: datetime | None = None
29
+ finished_at: datetime | None = None
30
+ exception_type: str | None = None
31
+ retried_from_id: uuid.UUID | None = None
32
+
33
+
34
+ class TaskExecutionDetail(SQLModel):
35
+ """Full row for the detail page (adds args/kwargs/result/traceback)."""
36
+
37
+ model_config = ConfigDict(from_attributes=True)
38
+
39
+ id: uuid.UUID
40
+ celery_task_id: str | None = None
41
+ task_name: str
42
+ status: TaskStatus
43
+ queue: str
44
+ args: list[Any] = []
45
+ kwargs: dict[str, Any] = {}
46
+ result: dict[str, Any] | None = None
47
+ traceback: str | None = None
48
+ exception_type: str | None = None
49
+ worker: str | None = None
50
+ retries: int = 0
51
+ retried_from_id: uuid.UUID | None = None
52
+ queued_at: datetime | None = None
53
+ started_at: datetime | None = None
54
+ finished_at: datetime | None = None
55
+ heartbeat_at: datetime | None = None
56
+
57
+
58
+ class TaskExecutionListResponse(SQLModel):
59
+ """Paginated response shape used by both the API and Inertia views."""
60
+
61
+ items: list[TaskExecutionListItem]
62
+ total: int
63
+ page: int
64
+ per_page: int
65
+ status: TaskStatus | None = None
66
+ task_name: str | None = None
@@ -0,0 +1,19 @@
1
+ """FastAPI dependencies for the BackgroundTasks module."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from fastapi import Depends, Request
6
+ from simple_module_core.events import EventBus
7
+ from simple_module_db.deps import get_db
8
+ from sqlalchemy.ext.asyncio import AsyncSession
9
+
10
+ from background_tasks.service import BackgroundTaskService
11
+
12
+
13
+ async def get_background_task_service(
14
+ request: Request,
15
+ db: AsyncSession = Depends(get_db),
16
+ ) -> BackgroundTaskService:
17
+ services = request.app.state.background_tasks
18
+ bus: EventBus = request.app.state.sm.event_bus
19
+ return BackgroundTaskService(db=db, celery=services.celery, event_bus=bus)
File without changes
@@ -0,0 +1,62 @@
1
+ """Admin REST endpoints for BackgroundTasks."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import uuid
6
+
7
+ from fastapi import APIRouter, Depends, HTTPException, Query
8
+ from simple_module_hosting.permissions import RequiresPermission
9
+
10
+ from background_tasks.constants import (
11
+ ADMIN_ROUTER_PREFIX,
12
+ MODULE_NAME,
13
+ PERM_MANAGE,
14
+ PERM_VIEW,
15
+ TaskStatus,
16
+ )
17
+ from background_tasks.contracts.schemas import (
18
+ TaskExecutionDetail,
19
+ TaskExecutionListResponse,
20
+ )
21
+ from background_tasks.deps import get_background_task_service
22
+ from background_tasks.service import BackgroundTaskService
23
+
24
+ router = APIRouter(
25
+ prefix=ADMIN_ROUTER_PREFIX,
26
+ dependencies=[Depends(RequiresPermission(PERM_VIEW))],
27
+ tags=[f"{MODULE_NAME}-admin"],
28
+ )
29
+
30
+
31
+ @router.get("/executions", response_model=TaskExecutionListResponse)
32
+ async def list_executions(
33
+ status: TaskStatus | None = Query(default=None),
34
+ task_name: str | None = Query(default=None),
35
+ page: int = Query(default=1, ge=1),
36
+ per_page: int = Query(default=20, ge=1, le=200),
37
+ service: BackgroundTaskService = Depends(get_background_task_service),
38
+ ) -> TaskExecutionListResponse:
39
+ return await service.list(status=status, task_name=task_name, page=page, per_page=per_page)
40
+
41
+
42
+ @router.get("/executions/{execution_id}", response_model=TaskExecutionDetail)
43
+ async def get_execution(
44
+ execution_id: uuid.UUID,
45
+ service: BackgroundTaskService = Depends(get_background_task_service),
46
+ ) -> TaskExecutionDetail:
47
+ detail = await service.get(execution_id)
48
+ if detail is None:
49
+ raise HTTPException(status_code=404, detail="Task execution not found")
50
+ return detail
51
+
52
+
53
+ @router.post(
54
+ "/executions/{execution_id}/retry",
55
+ response_model=TaskExecutionDetail,
56
+ dependencies=[Depends(RequiresPermission(PERM_MANAGE))],
57
+ )
58
+ async def retry_execution(
59
+ execution_id: uuid.UUID,
60
+ service: BackgroundTaskService = Depends(get_background_task_service),
61
+ ) -> TaskExecutionDetail:
62
+ return await service.retry(execution_id)
@@ -0,0 +1,71 @@
1
+ """Inertia view endpoints for the BackgroundTasks admin UI."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import uuid
6
+
7
+ from fastapi import APIRouter, Depends, HTTPException, Query
8
+ from inertia import InertiaResponse
9
+ from simple_module_hosting.inertia_deps import InertiaDep
10
+ from simple_module_hosting.permissions import RequiresPermission
11
+
12
+ from background_tasks.constants import (
13
+ PERM_VIEW,
14
+ TaskStatus,
15
+ )
16
+ from background_tasks.deps import get_background_task_service
17
+ from background_tasks.service import BackgroundTaskService
18
+
19
+ router = APIRouter(dependencies=[Depends(RequiresPermission(PERM_VIEW))])
20
+
21
+ PER_PAGE = 20
22
+
23
+
24
+ @router.get("/", response_model=None)
25
+ async def index(
26
+ inertia: InertiaDep,
27
+ status: TaskStatus | None = Query(default=None),
28
+ task_name: str = Query(default="", alias="q"),
29
+ page: int = Query(default=1, ge=1),
30
+ service: BackgroundTaskService = Depends(get_background_task_service),
31
+ ) -> InertiaResponse:
32
+ response = await service.list(
33
+ status=status,
34
+ task_name=task_name or None,
35
+ page=page,
36
+ per_page=PER_PAGE,
37
+ )
38
+ return await inertia.render(
39
+ "BackgroundTasks/Index",
40
+ {
41
+ "executions": [i.model_dump(mode="json") for i in response.items],
42
+ "pagination": {
43
+ "page": response.page,
44
+ "per_page": response.per_page,
45
+ "total": response.total,
46
+ },
47
+ "filters": {
48
+ "status": status.value if status else "",
49
+ "task_name": task_name,
50
+ },
51
+ },
52
+ )
53
+
54
+
55
+ @router.get("/{execution_id}", response_model=None)
56
+ async def detail(
57
+ execution_id: str,
58
+ inertia: InertiaDep,
59
+ service: BackgroundTaskService = Depends(get_background_task_service),
60
+ ) -> InertiaResponse:
61
+ try:
62
+ eid = uuid.UUID(execution_id)
63
+ except ValueError as exc:
64
+ raise HTTPException(status_code=404) from exc
65
+ row = await service.get(eid)
66
+ if row is None:
67
+ raise HTTPException(status_code=404)
68
+ return await inertia.render(
69
+ "BackgroundTasks/Detail",
70
+ {"execution": row.model_dump(mode="json")},
71
+ )
@@ -0,0 +1,57 @@
1
+ {
2
+ "index": {
3
+ "title": "Background Tasks",
4
+ "description": "Monitor task executions and retry failed or stuck jobs.",
5
+ "search_placeholder": "Search by task name…",
6
+ "count_one": "{count} task",
7
+ "count_other": "{count} tasks",
8
+ "empty_title": "No task executions yet",
9
+ "empty_description": "Tasks appear here as soon as modules enqueue work.",
10
+ "no_match": "No tasks match \"{query}\""
11
+ },
12
+ "filters": {
13
+ "status_label": "Status",
14
+ "status_all": "All statuses"
15
+ },
16
+ "status": {
17
+ "pending": "Pending",
18
+ "running": "Running",
19
+ "success": "Success",
20
+ "failed": "Failed",
21
+ "stuck": "Stuck",
22
+ "revoked": "Revoked",
23
+ "retrying": "Retrying"
24
+ },
25
+ "table": {
26
+ "task": "Task",
27
+ "status": "Status",
28
+ "queue": "Queue",
29
+ "queued_at": "Queued",
30
+ "duration": "Duration",
31
+ "worker": "Worker",
32
+ "actions": "Actions",
33
+ "view": "View",
34
+ "retry": "Retry"
35
+ },
36
+ "detail": {
37
+ "title": "Task execution",
38
+ "back_button": "Back to tasks",
39
+ "args": "Arguments",
40
+ "kwargs": "Keyword arguments",
41
+ "result": "Result",
42
+ "traceback": "Traceback",
43
+ "meta": "Details",
44
+ "retried_from": "Retried from",
45
+ "no_traceback": "No traceback recorded."
46
+ },
47
+ "retry_dialog": {
48
+ "title": "Retry this task?",
49
+ "description": "A new task execution will be enqueued with the same arguments. The original row is kept for history.",
50
+ "cancel": "Cancel",
51
+ "confirm": "Retry task"
52
+ },
53
+ "toasts": {
54
+ "retried": "Task \"{name}\" re-enqueued",
55
+ "retry_failed": "Failed to retry task"
56
+ }
57
+ }
@@ -0,0 +1,86 @@
1
+ """SQLModel tables for the BackgroundTasks module."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import uuid
6
+ from datetime import datetime
7
+ from typing import Any
8
+
9
+ from simple_module_db.base import create_module_base
10
+ from simple_module_db.mixins import AuditMixin
11
+ from sqlalchemy import JSON, Column, Index, String
12
+ from sqlmodel import Field
13
+
14
+ from background_tasks.constants import (
15
+ DEFAULT_QUEUE,
16
+ MODULE_NAME,
17
+ TABLE_TASK_EXECUTION,
18
+ TaskStatus,
19
+ )
20
+
21
+ # Provider is auto-detected from SM_DATABASE_URL (falls back to SQLite).
22
+ # On PostgreSQL this gives the module its own `background_tasks` schema; on
23
+ # SQLite all modules share one schema, so __tablename__ is prefixed for
24
+ # isolation.
25
+ Base = create_module_base(MODULE_NAME)
26
+
27
+
28
+ class TaskExecution(Base, AuditMixin, table=True): # ty: ignore[unsupported-base]
29
+ """Persistent record of a single Celery task execution.
30
+
31
+ We keep our own row (separate from Celery's volatile result backend)
32
+ because the admin UI needs stable history, retried-from chains, and a
33
+ "stuck since" timestamp that Celery's state machine doesn't model.
34
+ """
35
+
36
+ __tablename__ = TABLE_TASK_EXECUTION
37
+
38
+ id: uuid.UUID = Field(default_factory=uuid.uuid4, primary_key=True)
39
+
40
+ # Celery's own UUID for the running task. Nullable because we create the
41
+ # row *before* enqueue in the retry flow, then stamp it on send.
42
+ celery_task_id: str | None = Field(default=None, index=True, max_length=64)
43
+
44
+ task_name: str = Field(index=True, max_length=255)
45
+ # Stored as a plain string (the enum's ``value``) rather than a native
46
+ # SQL ENUM so autogenerate produces a VARCHAR column and Postgres
47
+ # doesn't own a ``taskstatus`` type that we'd need a separate migration
48
+ # to evolve.
49
+ status: TaskStatus = Field(
50
+ default=TaskStatus.PENDING,
51
+ sa_column=Column(String(20), index=True, nullable=False, default=TaskStatus.PENDING.value),
52
+ )
53
+ queue: str = Field(default=DEFAULT_QUEUE, max_length=64)
54
+
55
+ args: list[Any] = Field(default_factory=list, sa_column=Column(JSON))
56
+ kwargs: dict[str, Any] = Field(default_factory=dict, sa_column=Column(JSON))
57
+ result: dict[str, Any] | None = Field(default=None, sa_column=Column(JSON))
58
+
59
+ traceback: str | None = None
60
+ exception_type: str | None = Field(default=None, max_length=255)
61
+
62
+ worker: str | None = Field(default=None, max_length=255)
63
+ retries: int = 0
64
+
65
+ # Self-reference so the UI can show "retried from <original>" chains.
66
+ retried_from_id: uuid.UUID | None = Field(
67
+ default=None,
68
+ foreign_key=f"{TABLE_TASK_EXECUTION}.id",
69
+ index=True,
70
+ )
71
+
72
+ queued_at: datetime | None = None
73
+ started_at: datetime | None = None
74
+ finished_at: datetime | None = None
75
+ # Heartbeat is refreshed on every signal that touches a running task.
76
+ # `stuck_after_seconds` older than ``now`` ⇒ `sweep_stuck_tasks` flips
77
+ # the row to `stuck`.
78
+ heartbeat_at: datetime | None = None
79
+
80
+ __table_args__ = (
81
+ Index(
82
+ "ix_background_tasks_task_execution_status_queued",
83
+ "status",
84
+ "queued_at",
85
+ ),
86
+ )