"""ORM models for the background job queue. Tables: - musehub_background_jobs: Durable job queue — web process enqueues, worker process executes """ from __future__ import annotations from datetime import datetime, timezone from sqlalchemy import DateTime, ForeignKey, Index, Integer, String, Text from sqlalchemy.orm import Mapped, mapped_column from sqlalchemy.dialects.postgresql import JSONB from musehub.db.database import Base from musehub.types.json_types import JSONObject, JSONValue # JSONValue needed for ForwardRef resolution in Mapped[] def _utc_now() -> datetime: return datetime.now(tz=timezone.utc) class MusehubBackgroundJob(Base): """A durable background job enqueued by the web process and processed by the worker. The web process (uvicorn) never executes job logic directly — it only inserts a row here. A separate worker process polls this table, claims rows with ``FOR UPDATE SKIP LOCKED``, and runs the work outside the web server's memory space so a crash in the worker cannot affect request handling. Supported job_type values: ``intel.code`` — rebuild code intelligence for a repo. payload: {"head": ""} ``intel.structural`` — compute cross-domain structural intelligence. payload: {"head": ""} ``gc`` — prune commits and snapshots unreachable from any branch. payload: {} Status lifecycle: pending → running → done → failed (attempt < max_attempts) └→ pending (retried by worker after transient failure) """ __tablename__ = "musehub_background_jobs" __table_args__ = ( Index("ix_musehub_background_jobs_status_created", "status", "created_at"), ) job_id: Mapped[str] = mapped_column(String(128), primary_key=True) repo_id: Mapped[str] = mapped_column( String(128), ForeignKey("musehub_repos.repo_id", ondelete="CASCADE"), nullable=False, index=True, ) job_type: Mapped[str] = mapped_column(String(64), nullable=False) payload: Mapped[JSONObject] = mapped_column(JSONB, nullable=False, default=dict) status: Mapped[str] = mapped_column(String(16), nullable=False, default="pending", server_default="pending", index=True) created_at: Mapped[datetime] = mapped_column( DateTime(timezone=True), nullable=False, default=_utc_now ) claimed_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True), nullable=True) done_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True), nullable=True) attempt: Mapped[int] = mapped_column(Integer, nullable=False, default=0) error: Mapped[str | None] = mapped_column(Text, nullable=True) quarantine_reason: Mapped[str | None] = mapped_column(Text, nullable=True)