"""Persistence for the event inbox and schedules. All functions take an open session; the caller decides the role (app role + tenant for tenant work, owner role for sweeps).""" from __future__ import annotations import uuid from dataclasses import dataclass from datetime import UTC, datetime, timedelta from typing import Any from zoneinfo import ZoneInfo from croniter import croniter from sqlalchemy import func, select, update from sqlalchemy.dialects.postgresql import insert from sqlalchemy.ext.asyncio import AsyncSession from core.agent.state import Event from core.events.intake import NormalizedEvent, normalize_cron from core.events.models import InboxEvent, Schedule MAX_ERROR = 4000 @dataclass(frozen=True) class Recorded: event_id: uuid.UUID duplicate: bool # Phase 11: ``workflow.run`` events recorded for workflows subscribed to this event. derived: tuple[uuid.UUID, ...] = () @dataclass(frozen=True) class Claim: event: Event run_id: uuid.UUID thread_id: str async def record(session: AsyncSession, tenant_id: uuid.UUID, ne: NormalizedEvent) -> Recorded: """Insert once per ``(tenant_id, dedupe_key)``; a duplicate returns the existing id.""" e = ne.event stmt = ( insert(InboxEvent) .values( id=uuid.uuid4(), tenant_id=tenant_id, type=e.type, source=e.source, text=e.text, trusted=e.trusted, payload=e.payload, dedupe_key=ne.dedupe_key, status="received", attempts=0, ) .on_conflict_do_nothing(constraint="uq_events_tenant_dedupe_key") .returning(InboxEvent.id) ) new_id = (await session.execute(stmt)).scalar_one_or_none() if new_id is not None: return Recorded(new_id, False, await _workflow_fan_out(session, tenant_id, new_id, e)) existing = ( await session.execute( select(InboxEvent.id).where( InboxEvent.tenant_id == tenant_id, InboxEvent.dedupe_key == ne.dedupe_key ) ) ).scalar_one() return Recorded(existing, True) async def _workflow_fan_out( session: AsyncSession, tenant_id: uuid.UUID, event_id: uuid.UUID, e: Event ) -> tuple[uuid.UUID, ...]: """Phase 11: one ``workflow.run`` event per active workflow subscribed to this event.""" from core.workflows.triggers import fan_out derived = [] for ne in await fan_out(session, tenant_id, event_id, e): rec = await record(session, tenant_id, ne) if not rec.duplicate: derived.append(rec.event_id) return tuple(derived) def to_event(row: InboxEvent) -> Event: return Event( type=row.type, source=row.source, text=row.text, payload=row.payload, trusted=row.trusted ) async def claim(session: AsyncSession, tenant_id: uuid.UUID, event_id: uuid.UUID) -> Claim | None: """``received`` -> ``processing``, fixing the run id on first claim (kept on retries, so a retried event continues the same run instead of starting a second one).""" run_id = uuid.uuid4() row = ( await session.execute( update(InboxEvent) .where(InboxEvent.id == event_id, InboxEvent.status == "received") .values( status="processing", run_id=func.coalesce(InboxEvent.run_id, run_id), thread_id=func.coalesce(InboxEvent.thread_id, f"{tenant_id}:{run_id}"), ) .returning(InboxEvent) .execution_options(synchronize_session=False) ) ).scalar_one_or_none() if row is None: return None assert row.run_id is not None and row.thread_id is not None return Claim(event=to_event(row), run_id=row.run_id, thread_id=row.thread_id) async def note_attempt(session: AsyncSession, event_id: uuid.UUID, error: str | None) -> None: await session.execute( update(InboxEvent) .where(InboxEvent.id == event_id) .values( attempts=InboxEvent.attempts + 1, last_error=error[:MAX_ERROR] if error else InboxEvent.last_error, ) ) async def finish( session: AsyncSession, event_id: uuid.UUID, *, dead: bool, error: str | None = None ) -> None: values: dict[str, Any] = {"status": "dead" if dead else "processed"} if dead: values["last_error"] = (error or "dispatch failed")[:MAX_ERROR] else: values["processed_at"] = func.now() await session.execute(update(InboxEvent).where(InboxEvent.id == event_id).values(**values)) async def requeue(session: AsyncSession, event_id: uuid.UUID) -> bool: """Manual retry of a dead-lettered event.""" row = ( await session.execute( update(InboxEvent) .where(InboxEvent.id == event_id, InboxEvent.status == "dead") .values(status="received") .returning(InboxEvent.id) ) ).scalar_one_or_none() return row is not None async def stale_received( session: AsyncSession, older_than: timedelta, limit: int = 500 ) -> list[tuple[uuid.UUID, uuid.UUID, int]]: """Owner sweep: events persisted but never dispatched (e.g. the API died between the insert and the enqueue). Returns ``(tenant_id, event_id, attempts)``; ``attempts`` is the dispatch generation, so a re-enqueue reuses the workflow id the API would have used.""" cutoff = datetime.now(UTC) - older_than rows = await session.execute( select(InboxEvent.tenant_id, InboxEvent.id, InboxEvent.attempts) .where(InboxEvent.status == "received", InboxEvent.received_at < cutoff) .order_by(InboxEvent.received_at) .limit(limit) ) return [(r.tenant_id, r.id, r.attempts) for r in rows] async def stranded_runs( session: AsyncSession, older_than: timedelta, limit: int = 100 ) -> list[tuple[uuid.UUID, uuid.UUID]]: """Owner sweep: runs still ``running`` long after they started that no event owns. Event-dispatched runs are recovered by DBOS (the dispatch workflow re-runs ``start`` with the same run id). A run started directly by ``POST /chat`` has no such owner: if the API process died mid-request it would stay ``running`` forever. Returns ``(tenant_id, run_id)``; the caller continues each one from its last checkpoint.""" from core.agent.runs import Run cutoff = datetime.now(UTC) - older_than owned = select(InboxEvent.id).where(InboxEvent.run_id == Run.id).exists() rows = await session.execute( select(Run.tenant_id, Run.id) .where(Run.status == "running", Run.started_at < cutoff, ~owned) .order_by(Run.started_at) .limit(limit) ) return [(r.tenant_id, r.id) for r in rows] # ------------------------------------------------------------------ schedules def validate_cron(cron: str, tz: str) -> None: if not croniter.is_valid(cron): raise ValueError(f"invalid cron expression {cron!r}") try: ZoneInfo(tz) except Exception as exc: raise ValueError(f"unknown timezone {tz!r}") from exc def next_fire(cron: str, tz: str, after: datetime) -> datetime: """Next slot strictly after ``after``, evaluated in the schedule's timezone, as UTC.""" local = after.astimezone(ZoneInfo(tz)) nxt: datetime = croniter(cron, local).get_next(datetime) return nxt.astimezone(UTC) async def fire_due_schedules( session: AsyncSession, now: datetime | None = None, limit: int = 500 ) -> list[tuple[uuid.UUID, uuid.UUID]]: """Owner sweep. For each enabled schedule whose slot is due, insert one event for that slot (dedupe key = schedule id + slot time) and advance ``next_run_at`` past ``now``. Missed slots are not backfilled: a worker that was down for a day fires once, not 24 times. Returns newly inserted ``(tenant_id, event_id)`` pairs.""" now = now or datetime.now(UTC) due = ( await session.execute( select(Schedule) .where( Schedule.enabled.is_(True), Schedule.next_run_at.is_not(None), Schedule.next_run_at <= now, ) .order_by(Schedule.next_run_at) .limit(limit) .with_for_update(skip_locked=True) ) ).scalars() fired: list[tuple[uuid.UUID, uuid.UUID]] = [] for sch in list(due): slot = sch.next_run_at assert slot is not None ne = normalize_cron( sch.id, slot, event_type=sch.event_type, payload=sch.payload, schedule_name=sch.name ) rec = await record(session, sch.tenant_id, ne) if not rec.duplicate: fired.append((sch.tenant_id, rec.event_id)) sch.last_run_at = slot sch.next_run_at = next_fire(sch.cron, sch.timezone, now) await session.flush() fired.extend(await _fire_due_workflow_waits(session, now)) # Phase 11 return fired async def _fire_due_workflow_waits( session: AsyncSession, now: datetime ) -> list[tuple[uuid.UUID, uuid.UUID]]: """Phase 11: workflows paused by a ``wait`` step continue as new events when due.""" from core.workflows.triggers import fire_due_waits out = [] for tenant_id, ne in await fire_due_waits(session, now): rec = await record(session, tenant_id, ne) if not rec.duplicate: out.append((tenant_id, rec.event_id)) return out