Spaces:
Running
Running
File size: 16,587 Bytes
fd5dd94 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 | """Durable event dispatch on DBOS (system database in Postgres).
Flow::
API / webhook / schedule tick
-> INSERT events (unique tenant_id + dedupe_key) one durable door
-> enqueue DBOS workflow ``wp.dispatch_event`` on queue ``wp-events``
(workflow id ``event-<id>-<attempts>``: enqueueing twice is a no-op;
partition key = tenant id: at most ``events_tenant_concurrency`` per tenant)
-> worker: claim (received -> processing, fixes run_id)
run (AgentRuntime.start(run_id=...), retried with backoff)
finish (processed) | dead-letter after ``events_max_attempts``
Every step's result is checkpointed by DBOS. If a worker dies mid-dispatch, DBOS recovers
the workflow: finished steps are not repeated, and the run step calls ``start`` with the
same ``run_id``, which continues the LangGraph thread from its last checkpoint.
Periodic jobs (DBOS cron schedules, fired by exactly one worker):
* ``wp.schedule_tick``: insert one event per due ``schedules`` slot and re-enqueue events
that were persisted but never dispatched.
* ``wp.expire_approvals``: expire overdue approvals, then resume their runs, which finish as
rejected (the gateway treats an expired approval as a rejection).
DBOS is a process-global singleton: ``launch`` once per process (the worker, or a test
session). The API never launches DBOS; it enqueues through ``DBOSDispatcher`` (a
``DBOSClient`` on the system database).
"""
from __future__ import annotations
import asyncio
import contextlib
import logging
import uuid
from dataclasses import dataclass, field
from datetime import datetime, timedelta
from typing import Any, Protocol
from dbos import DBOS, DBOSClient, DBOSConfig, EnqueueOptions
from sqlalchemy import select, update
from sqlalchemy.engine import make_url
from core.agent.runs import Run
from core.agent.runtime import AgentRuntime, RunNotFound, RunResult
from core.agent.state import Event
from core.approvals.service import ApprovalService
from core.channels.delivery import RECEIPT_EVENT_TYPES, apply_receipt_event
from core.channels.jobs import channel_schedules
from core.config import Settings, get_settings
from core.db.session import Database
from core.events import store
from core.observability.jobs import alert_schedules
from core.services import Services
log = logging.getLogger(__name__)
QUEUE = "wp-events"
DISPATCH = "wp.dispatch_event"
TICK = "wp.schedule_tick"
EXPIRE = "wp.expire_approvals"
def system_database_url(settings: Settings | None = None) -> str:
"""``WP_DBOS_SYSTEM_DATABASE_URL`` or ``<owner database>_dbos_sys`` (created by bootstrap)."""
s = settings or get_settings()
if s.dbos_system_database_url:
return s.dbos_system_database_url
url = make_url(s.owner_database_url)
url = url.set(drivername="postgresql", database=f"{url.database}_dbos_sys")
return url.render_as_string(hide_password=False)
def workflow_id(event_id: uuid.UUID | str, generation: int = 0) -> str:
"""Deterministic per (event, retry generation): enqueueing twice never runs twice."""
return f"event-{event_id}-{generation}"
def _options(tenant_id: uuid.UUID | str, wf_id: str, s: Settings) -> EnqueueOptions:
return EnqueueOptions(
workflow_name=DISPATCH,
queue_name=QUEUE,
workflow_id=wf_id,
queue_partition_key=str(tenant_id),
application_name=s.dbos_app_name,
)
# --------------------------------------------------------------------- binding
@dataclass
class EventWorker:
"""What dispatch needs in this process: the agent runtime (app role) and an owner-role
database for cross-tenant sweeps."""
services: Services
owner_db: Database
settings: Settings = field(default_factory=get_settings)
@property
def runtime(self) -> AgentRuntime:
if self.services.runtime is None:
raise RuntimeError("event worker needs services with an agent runtime")
return self.services.runtime
@property
def db(self) -> Database:
return self.services.db
_worker: EventWorker | None = None
def bind(worker: EventWorker) -> None:
global _worker
_worker = worker
def current() -> EventWorker:
if _worker is None:
raise RuntimeError("no event worker bound in this process (core.events.workers.bind)")
return _worker
# ------------------------------------------------------------------- dispatch
def _run_out(r: RunResult) -> dict[str, Any]:
return {
"run_id": str(r.run_id),
"thread_id": r.thread_id,
"status": r.status,
"intent": r.intent,
"output": r.output,
"error": r.error,
"pending": r.pending,
"actions": r.actions,
}
async def _claim(tenant_id: str, event_id: str) -> dict[str, Any] | None:
w = current()
tid = uuid.UUID(tenant_id)
async with w.db.session(tenant_id=tid) as s, s.begin():
c = await store.claim(s, tid, uuid.UUID(event_id))
if c is None:
return None
return {
"run_id": str(c.run_id),
"thread_id": c.thread_id,
"event": c.event.model_dump(mode="json"),
}
async def _run(tenant_id: str, event_id: str, run_id: str, event: dict[str, Any]) -> dict[str, Any]:
w = current()
tid, eid = uuid.UUID(tenant_id), uuid.UUID(event_id)
if event.get("type") in RECEIPT_EVENT_TYPES: # Phase 7: delivery receipts, no agent run
applied = await apply_receipt_event(
w.db, w.services.packs, tid, Event.model_validate(event)
)
async with w.db.session(tenant_id=tid) as s, s.begin():
await store.note_attempt(s, eid, None)
return {"run_id": None, "thread_id": None, "status": "completed", "intent": None,
"output": f"receipt {applied['status']}", "error": None, "pending": [],
"actions": []} # fmt: skip
try:
result = await w.runtime.start(tid, Event.model_validate(event), run_id=uuid.UUID(run_id))
except Exception as exc:
async with w.db.session(tenant_id=tid) as s, s.begin():
await store.note_attempt(s, eid, f"{type(exc).__name__}: {exc}")
raise
async with w.db.session(tenant_id=tid) as s, s.begin():
await store.note_attempt(s, eid, None)
return _run_out(result)
async def _finish(tenant_id: str, event_id: str, dead: bool, error: str | None) -> None:
w = current()
async with w.db.session(tenant_id=uuid.UUID(tenant_id)) as s, s.begin():
await store.finish(s, uuid.UUID(event_id), dead=dead, error=error)
@DBOS.workflow(name=DISPATCH)
async def dispatch_event(tenant_id: str, event_id: str) -> dict[str, Any]:
"""Resolve the event (under its tenant's RLS), start or continue its run, mark it."""
s = get_settings()
claimed = await DBOS.run_step_async({"name": "claim"}, _claim, tenant_id, event_id)
if claimed is None: # already processing/processed elsewhere, or dead
return {"event_id": event_id, "status": "skipped", "run": None}
try:
run = await DBOS.run_step_async(
{
"name": "run",
"retries_allowed": True,
"max_attempts": max(1, s.events_max_attempts),
"interval_seconds": s.events_retry_interval_s,
"backoff_rate": 2.0,
},
_run,
tenant_id,
event_id,
claimed["run_id"],
claimed["event"],
)
except Exception as exc:
errors = getattr(exc, "errors", None)
last = errors[-1] if errors else exc
error = f"{type(last).__name__}: {last}"
await DBOS.run_step_async({"name": "dead"}, _finish, tenant_id, event_id, True, error)
return {"event_id": event_id, "status": "dead", "error": error, "run": None}
await DBOS.run_step_async({"name": "processed"}, _finish, tenant_id, event_id, False, None)
return {"event_id": event_id, "status": "processed", "run": run}
async def enqueue_in_workflow(
tenant_id: uuid.UUID | str, event_id: uuid.UUID | str, generation: int = 0
) -> None:
"""Enqueue from inside a DBOS workflow or a DBOS-launched process."""
await DBOS.enqueue_workflow_with_options_async(
_options(tenant_id, workflow_id(event_id, generation), get_settings()),
str(tenant_id),
str(event_id),
)
# ------------------------------------------------------------------- periodic
async def _fire_due(at_iso: str) -> list[tuple[str, str, int]]:
w = current()
async with w.owner_db.session() as s, s.begin():
fired = await store.fire_due_schedules(s, datetime.fromisoformat(at_iso))
stale = await store.stale_received(s, timedelta(seconds=w.settings.events_stale_after_s))
out = {str(e): (str(t), str(e), 0) for t, e in fired}
for t, e, gen in stale:
out.setdefault(str(e), (str(t), str(e), gen))
return list(out.values())
@DBOS.workflow(name=TICK)
async def schedule_tick(scheduled_at: datetime, context: Any) -> None:
pending = await DBOS.run_step_async({"name": "fire_due"}, _fire_due, scheduled_at.isoformat())
for tenant_id, event_id, generation in pending:
await enqueue_in_workflow(tenant_id, event_id, generation)
async def _expire() -> list[tuple[str, str]]:
w = current()
async with w.owner_db.session() as s, s.begin():
expired = await ApprovalService().expire_pending(s)
threads = {(str(a.tenant_id), a.thread_id) for a in expired if a.thread_id}
return sorted(threads)
async def _resume(tenant_id: str, thread_id: str) -> str:
try:
r = await current().runtime.resume(uuid.UUID(tenant_id), thread_id)
except RunNotFound: # completed meanwhile, or another sweep got there first
return "not_waiting"
return r.status
async def _stranded() -> list[tuple[str, str]]:
w = current()
if w.settings.stranded_run_after_s <= 0:
return []
async with w.owner_db.session() as s:
rows = await store.stranded_runs(s, timedelta(seconds=w.settings.stranded_run_after_s))
return [(str(t), str(r)) for t, r in rows]
async def _recover(tenant_id: str, run_id: str) -> str:
"""Continue a stranded run from its last checkpoint (``start`` with an existing run id is
idempotent; tool calls replay through gateway idempotency keys)."""
w = current()
tid, rid = uuid.UUID(tenant_id), uuid.UUID(run_id)
async with w.db.session(tenant_id=tid) as s:
event = (await s.execute(select(Run.event).where(Run.id == rid))).scalar_one_or_none()
if event is None:
return "not_found"
try:
result = await w.runtime.start(tid, Event.model_validate(event), run_id=rid)
except Exception as exc: # leave a terminal state instead of retrying forever
log.warning("stranded run %s could not be recovered: %s", run_id, exc)
async with w.db.session(tenant_id=tid) as s, s.begin():
await s.execute(
update(Run)
.where(Run.id == rid, Run.status == "running")
.values(status="failed", error=f"recovery failed: {exc}"[:4000])
)
return "failed"
return result.status
@DBOS.workflow(name=EXPIRE)
async def expire_approvals(scheduled_at: datetime, context: Any) -> list[str]:
"""Expire overdue approvals (owner role, all tenants), then resume each affected run
so it finishes as rejected. Each resume is its own durable step. Then continue chat runs
stranded in ``running`` by a dead API process (``stranded_run_after_s``)."""
threads = await DBOS.run_step_async({"name": "expire"}, _expire)
out = []
for tenant_id, thread_id in threads:
status = await DBOS.run_step_async(
{"name": "resume", "retries_allowed": True, "max_attempts": 3},
_resume,
tenant_id,
thread_id,
)
out.append(status)
stranded = await DBOS.run_step_async({"name": "stranded"}, _stranded)
for tenant_id, run_id in stranded:
out.append(await DBOS.run_step_async({"name": "recover"}, _recover, tenant_id, run_id))
return out
# --------------------------------------------------------------------- launch
def dbos_config(settings: Settings, *, executor_id: str | None = None) -> DBOSConfig:
cfg: DBOSConfig = {
"name": settings.dbos_app_name,
"system_database_url": system_database_url(settings),
"log_level": "WARNING",
}
if executor_id:
cfg["executor_id"] = executor_id
return cfg
async def launch(
worker: EventWorker,
*,
executor_id: str | None = None,
consume: bool = True,
periodic: bool = True,
) -> None:
"""Bind ``worker`` and launch DBOS in the running event loop (workflows then run on this
loop, next to the async DB pools). ``consume=False`` launches without polling the event
queue (used by the crash test's subprocess)."""
s = worker.settings
bind(worker)
DBOS(config=dbos_config(s, executor_id=executor_id))
DBOS.launch()
if consume:
await DBOS.register_queue_async(
QUEUE,
partition_concurrency=s.events_tenant_concurrency,
worker_concurrency=max(s.events_worker_concurrency, s.events_tenant_concurrency),
polling_interval_sec=s.events_queue_poll_s,
on_conflict="always_update",
)
if periodic:
await DBOS.apply_schedules_async(
[
{
"schedule_name": TICK,
"workflow_fn": schedule_tick,
"schedule": s.schedule_tick_cron,
},
{
"schedule_name": EXPIRE,
"workflow_fn": expire_approvals, # type: ignore[typeddict-item] # result unused
"schedule": s.approval_sweep_cron,
},
*channel_schedules(s), # Phase 7: outbox delivery + inbox polling
*alert_schedules(s), # Phase 15: alert sweep
]
)
def shutdown(timeout_s: int = 10) -> None:
DBOS.destroy(workflow_completion_timeout_sec=timeout_s)
# ------------------------------------------------------------ API-side dispatch
class Dispatcher(Protocol):
async def enqueue(
self, tenant_id: uuid.UUID, event_id: uuid.UUID, generation: int = 0
) -> str: ...
async def result(self, wf_id: str, timeout_s: float) -> dict[str, Any] | None: ...
class DBOSDispatcher:
"""Enqueues from a process that does not run workflows (the API), via ``DBOSClient``."""
def __init__(self, settings: Settings | None = None) -> None:
self.settings = settings or get_settings()
self._client: DBOSClient | None = None
self._lock = asyncio.Lock()
async def _get(self) -> DBOSClient:
async with self._lock:
if self._client is None:
url = system_database_url(self.settings)
self._client = await asyncio.to_thread(
lambda: DBOSClient(
system_database_url=url, application_name=self.settings.dbos_app_name
)
)
return self._client
async def enqueue(self, tenant_id: uuid.UUID, event_id: uuid.UUID, generation: int = 0) -> str:
client = await self._get()
wf = workflow_id(event_id, generation)
await client.enqueue_async(
_options(tenant_id, wf, self.settings), str(tenant_id), str(event_id)
)
return wf
async def result(self, wf_id: str, timeout_s: float) -> dict[str, Any] | None:
client = await self._get()
handle: Any = await client.retrieve_workflow_async(wf_id)
try:
out: dict[str, Any] = await asyncio.wait_for(handle.get_result(), timeout_s)
except TimeoutError:
return None
return out
def close(self) -> None:
if self._client is not None:
with contextlib.suppress(Exception):
self._client.destroy()
self._client = None
|