Spaces:
Running

File size: 6,509 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
"""Event worker: ``python -m core.worker [--executor-id ID]``.



Launches DBOS (durable dispatch queue + cron jobs) with the agent runtime and the Postgres

checkpointer, then runs until SIGINT/SIGTERM. Run several for throughput: DBOS spreads the

queue across them and the per-tenant limit holds globally. Give each a stable

``--executor-id`` (e.g. the pod name) so a restarted worker recovers its own in-flight

workflows. Uses a selector event loop (psycopg async cannot run on Windows' Proactor loop).



Phase 18: without ``--executor-id`` the id comes from ``WP_WORKER_EXECUTOR_ID``, then the

platform's stable replica id (``FLY_MACHINE_ID`` on Fly.io, ``RAILWAY_REPLICA_ID`` on

Railway). All workers sharing one DBOS system database must run identical code (DBOS checks

the application version). On SIGTERM the worker drains in-flight runs at their next step

boundary, then stops DBOS (``docs/deployment.md``, "Graceful deploys").

"""

from __future__ import annotations

import argparse
import asyncio
import contextlib
import functools
import logging
import os
import selectors
import signal
from collections.abc import Callable
from typing import Any

log = logging.getLogger(__name__)

PLATFORM_REPLICA_ENV = ("FLY_MACHINE_ID", "RAILWAY_REPLICA_ID")


def resolve_executor_id(cli_value: str | None, env: dict[str, str] | None = None) -> str | None:
    env = dict(os.environ) if env is None else env
    if cli_value:
        return cli_value
    if env.get("WP_WORKER_EXECUTOR_ID"):
        return env["WP_WORKER_EXECUTOR_ID"]
    for name in PLATFORM_REPLICA_ENV:
        if env.get(name):
            return f"worker-{env[name]}"
    return None


def install_stop_handlers(

    loop: asyncio.AbstractEventLoop, stop: asyncio.Event

) -> Callable[[], None]:
    """SIGINT/SIGTERM set ``stop``. Uses the loop's handlers where supported (POSIX) and

    ``signal.signal`` otherwise (Windows). Returns a function restoring the previous state."""
    restore: list[Callable[[], object]] = []
    for sig in (signal.SIGINT, signal.SIGTERM):
        try:
            loop.add_signal_handler(sig, stop.set)
            restore.append(functools.partial(loop.remove_signal_handler, sig))
        except (NotImplementedError, RuntimeError, ValueError):
            with contextlib.suppress(ValueError, OSError):  # not the main thread
                previous = signal.getsignal(sig)
                signal.signal(sig, lambda *_: loop.call_soon_threadsafe(stop.set))
                restore.append(functools.partial(signal.signal, sig, previous))

    def _restore() -> None:
        for fn in restore:
            with contextlib.suppress(Exception):
                fn()

    return _restore


async def wait_then_drain(stop: asyncio.Event, runtime: Any, shutdown: Callable[[], None]) -> None:
    """Block until ``stop``; then drain in-flight runs and stop the durable worker."""
    try:
        await stop.wait()
    finally:
        if runtime is not None:
            runtime.request_drain("shutdown")
            log.info("draining in-flight agent runs")
        shutdown()


async def run(executor_id: str | None) -> None:
    from core.agent.checkpoint import open_checkpointer
    from core.channels import delivery
    from core.channels.outbox import pack_outboxes
    from core.config import get_settings
    from core.db.session import Database
    from core.events import workers
    from core.packs.loader import discover_packs
    from core.services import build_services

    s = get_settings()
    executor_id = executor_id or s.worker_executor_id
    db = Database()
    owner_db = Database(s.owner_database_url)
    stop = asyncio.Event()
    restore = install_stop_handlers(asyncio.get_running_loop(), stop)
    try:
        async with open_checkpointer(s.database_url) as cp:
            svc = build_services(db, discover_packs(), checkpointer=cp)
            # Phase 7: outbox delivery + inbox polling (DBOS cron jobs in core.channels.jobs).
            delivery.bind(
                delivery.DeliveryWorker(db, owner_db, pack_outboxes(svc.packs), settings=s)
            )
            # Phase 15: OTel export (no-op unless configured) + the alert sweep's monitor.
            from core.observability import alerts
            from core.observability.tracing import setup_tracing

            setup_tracing(s)
            alerts.bind(alerts.AlertMonitor(db, owner_db, settings=s))
            await workers.launch(workers.EventWorker(svc, owner_db, s), executor_id=executor_id)
            log.info("worker running (executor %s)", executor_id)
            await wait_then_drain(stop, svc.runtime, workers.shutdown)
    finally:
        restore()
        await owner_db.dispose()
        await db.dispose()


def check() -> int:
    """Container health probe (``python -m core.worker --check``): the DBOS system database

    and the app database answer. Exit 0 when healthy."""
    import psycopg
    from sqlalchemy.engine import make_url

    from core.config import get_settings
    from core.events.workers import system_database_url

    s = get_settings()
    app = make_url(s.database_url).set(drivername="postgresql")
    try:
        for url in (system_database_url(s), app.render_as_string(hide_password=False)):
            with psycopg.connect(url, connect_timeout=5) as conn:
                conn.execute("SELECT 1")
    except Exception as exc:  # report, never raise: this is a probe
        print(f"unhealthy: {type(exc).__name__}")
        return 1
    return 0


def main() -> None:
    p = argparse.ArgumentParser(prog="workpilot-worker")
    p.add_argument("--executor-id", default=None)
    p.add_argument("--check", action="store_true", help="health probe, then exit")
    a = p.parse_args()
    if a.check:
        raise SystemExit(check())
    from core.config import get_settings
    from core.ops.preflight import production_problems

    problems = production_problems(get_settings())
    if problems:
        raise SystemExit("refusing to start (WP_ENV=production): " + "; ".join(problems))
    logging.basicConfig(level=logging.INFO)
    with contextlib.suppress(KeyboardInterrupt):
        asyncio.run(
            run(resolve_executor_id(a.executor_id)),
            loop_factory=lambda: asyncio.SelectorEventLoop(selectors.DefaultSelector()),
        )


if __name__ == "__main__":
    main()