"""Run records: one row per agent run, tenant-scoped, mirrors the LangGraph thread.""" from __future__ import annotations import uuid from datetime import datetime from sqlalchemy import DateTime, Float, String, Text, func, select from sqlalchemy.dialects.postgresql import JSONB, UUID from sqlalchemy.ext.asyncio import AsyncSession from sqlalchemy.orm import Mapped, mapped_column from core.db.base import Base, TenantMixin, new_id class Run(TenantMixin, Base): __tablename__ = "runs" id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True), primary_key=True, default=new_id) thread_id: Mapped[str] = mapped_column(String(200), unique=True, nullable=False) event: Mapped[dict] = mapped_column(JSONB, nullable=False) graph_version: Mapped[str] = mapped_column(String(64), nullable=False) graph_nodes: Mapped[list] = mapped_column(JSONB, nullable=False) # running | waiting_approval | completed | rejected | failed | unsupported status: Mapped[str] = mapped_column(String(30), nullable=False, default="running") intent: Mapped[str | None] = mapped_column(String(200), nullable=True) cost_usd: Mapped[float] = mapped_column(Float, nullable=False, default=0.0) output: Mapped[str | None] = mapped_column(Text, nullable=True) error: Mapped[str | None] = mapped_column(Text, nullable=True) started_at: Mapped[datetime] = mapped_column( DateTime(timezone=True), server_default=func.now(), nullable=False ) ended_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True), nullable=True) async def run_cost(session: AsyncSession, run_id: uuid.UUID) -> float: """Gateway hook for the per-run cost circuit breaker.""" v = (await session.execute(select(Run.cost_usd).where(Run.id == run_id))).scalar_one_or_none() return float(v or 0.0) async def run_source(session: AsyncSession, run_id: uuid.UUID) -> str | None: """Gateway hook (Phase 15, ADR-0009 G7): the source of the event that started the run (``cron`` for schedule-triggered runs, which get a per-run batch allowance).""" v = ( await session.execute(select(Run.event["source"].astext).where(Run.id == run_id)) ).scalar_one_or_none() return None if v is None else str(v)