File size: 11,851 Bytes
23d418f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Step 9: the web app's HTTP layer (FastAPI). It serves the React app (web/dist) and:

    GET  /api/info   systems, model, today, questions left today, the not-advice notice
    POST /api/ask    {question, system, day?, history?} -> a server-sent event stream of
                     engine.events() (one JSON object per "data:" line)

    uv run python -m coveragecheck.web.api      # http://127.0.0.1:8000 (HOST/PORT env)

One process, one port: on the Hugging Face Docker Space (Step 10) the same uvicorn
serves the built frontend and the API. Guards for a public demo on a 2-core box and a
small API budget (config WEB_*): at most WEB_MAX_RUNNING questions at once (more get
HTTP 429 "busy", not a queue), WEB_DAILY_QUESTIONS per UTC day, per visitor
WEB_CLIENT_RUNNING at once and WEB_CLIENT_DAILY per day, a WEB_DEADLINE_S deadline
per question (C stops between graph nodes when its visitor leaves), and a keep-alive
comment every WEB_PING_S while a step runs.
"""

import asyncio
import json
import logging
import os
import queue
import threading
import time
from collections.abc import AsyncIterator, Callable, Iterator
from contextlib import asynccontextmanager
from datetime import UTC, date, datetime
from pathlib import Path
from typing import Literal

from fastapi import FastAPI, HTTPException, Request
from fastapi.responses import StreamingResponse
from fastapi.staticfiles import StaticFiles
from pydantic import BaseModel, ConfigDict, Field, field_validator
from starlette.exceptions import HTTPException as StarletteHTTPException

from coveragecheck import config
from coveragecheck.web.engine import NOT_ADVICE, Engine
from coveragecheck.web.followup import HistoryTurn

log = logging.getLogger(__name__)
DONE = object()  # end of a question's events, put on its queue by the worker thread
BUSY = "The demo is answering other questions right now. Please try again in a minute."
SPENT = "Today's question limit for this demo is reached. Please come back tomorrow."
LATE = "This question took too long and was stopped. Please try again."
CLIENT_SPENT = "You have asked today's maximum number of questions. Please come back tomorrow."
SERVER = "Something went wrong."


class AskRequest(BaseModel):
    """A visitor's question. day: the policy date (versions in force on it); default
    today, as the held-out run used for questions without a date. history: the earlier
    turns of the conversation (a follow-up is rewritten from the last few of them)."""

    model_config = ConfigDict(extra="forbid")
    question: str = Field(min_length=3, max_length=config.WEB_MAX_QUESTION_CHARS)
    system: Literal[config.WEB_SYSTEMS]  # type: ignore[valid-type]
    day: date | None = None
    history: list[HistoryTurn] = Field(
        default_factory=list, max_length=config.WEB_HISTORY_MAX_TURNS
    )

    @field_validator("question")
    @classmethod
    def stripped(cls, value: str) -> str:
        value = value.strip()
        if len(value) < 3:
            raise ValueError("the question is empty")
        return value

    @field_validator("day")
    @classmethod
    def plausible(cls, value: date | None) -> date | None:
        if value is not None and not date(1990, 1, 1) <= value <= date(2100, 12, 31):
            raise ValueError("the policy date must be between 1990 and 2100")
        return value


class Gate:
    """Admission for live questions: at most `running` at once and `daily` per UTC day
    in all (the API budget), and per visitor at most `client_running` at once and
    `client_daily` per day (9a audit: one visitor could hold every slot or spend the
    whole day's budget). admit(client) returns None (admitted: call release(client)
    when done) or why not; a refusal never counts against any budget."""

    def __init__(
        self,
        running: int,
        daily: int,
        today: Callable[[], date],
        client_running: int = 1,
        client_daily: int | None = None,
    ):
        self.running, self.daily, self.today = running, daily, today
        self.client_running = client_running
        self.client_daily = daily if client_daily is None else client_daily
        self.day, self.count, self.lock = None, 0, threading.Lock()
        self.busy: dict[str, int] = {}  # client -> questions running
        self.used: dict[str, int] = {}  # client -> questions today

    def roll(self) -> None:
        """A new UTC day resets the day's counts (call with the lock held)."""
        if self.day != self.today():
            self.day, self.count, self.used = self.today(), 0, {}

    def left(self) -> int:
        with self.lock:
            self.roll()
            return self.daily - self.count

    def admit(self, client: str = "") -> str | None:
        with self.lock:
            self.roll()
            if self.count >= self.daily:
                return SPENT
            if self.used.get(client, 0) >= self.client_daily:
                return CLIENT_SPENT
            running = sum(self.busy.values())
            if running >= self.running or self.busy.get(client, 0) >= self.client_running:
                return BUSY
            self.count += 1
            self.used[client] = self.used.get(client, 0) + 1
            self.busy[client] = self.busy.get(client, 0) + 1
            return None

    def release(self, client: str = "") -> None:
        with self.lock:
            self.busy[client] -= 1
            if not self.busy[client]:
                del self.busy[client]


def utc_today() -> date:
    return datetime.now(UTC).date()


def client_of(request: Request) -> str:
    """Who is asking, for the per-visitor limits: the LAST X-Forwarded-For hop (the one
    the hosting proxy adds; earlier hops are whatever the visitor sent, so trusting
    the first would let anyone pick a fresh identity per request), else the socket's
    address. Step 10: check what the Hugging Face proxy sends."""
    forwarded = request.headers.get("x-forwarded-for", "")
    hops = [h.strip() for h in forwarded.split(",") if h.strip()]
    if hops:
        return hops[-1]
    return request.client.host if request.client else ""


def sse(event: dict) -> str:
    """One server-sent event: a "data:" line of JSON and a blank line."""
    return f"data: {json.dumps(event, ensure_ascii=False)}\n\n"


def start(events: Iterator[dict], release: Callable[[], None], cancel: threading.Event):
    """Run engine.events() in a worker thread (the systems are blocking code), now; each
    event arrives on the returned queue already as server-sent-event text (an event
    that won't serialise becomes an error event, 9a audit), then DONE. Started by the
    request handler, not by the response stream, so the slot is released even if the
    visitor leaves before the stream starts (an async generator that never starts runs
    no `finally`). When `cancel` is set (the visitor left, or the deadline passed), the
    worker stops at the next event: System C then stops between graph nodes, so an
    abandoned question pays for no further LLM call (A and B are one call each and
    finish it). The slot is freed only when the worker ends."""
    inbox: queue.Queue = queue.Queue()

    def work() -> None:
        try:
            for event in events:
                if cancel.is_set():
                    break
                inbox.put(sse(event))  # an unserialisable event raises: handled below
        except Exception:  # engine.events never raises; sse() can (9a audit)
            log.exception("event stream failed")
            inbox.put(sse({"type": "error", "kind": "server", "message": SERVER}))
        finally:
            close = getattr(events, "close", None)
            if close:
                close()  # a generator stopped early: run its cleanup (closes C's graph)
            inbox.put(DONE)
            release()

    threading.Thread(target=work, daemon=True).start()
    return inbox


async def relay(
    inbox: queue.Queue, cancel: threading.Event, ping_s: float, deadline_s: float
) -> AsyncIterator[str]:
    """A worker's events, as they come. While a step runs, a comment line goes out every
    ping_s so proxies keep the connection open; past deadline_s an error event ends the
    stream. However the stream ends (done, deadline, the visitor gone), the worker is
    told to stop."""
    ends = time.monotonic() + deadline_s
    try:
        while True:
            left = ends - time.monotonic()
            if left <= 0:
                yield sse({"type": "error", "kind": "deadline", "message": LATE})
                return
            try:
                text = await asyncio.to_thread(inbox.get, True, min(ping_s, left))
            except queue.Empty:
                yield ": ping\n\n"
                continue
            if text is DONE:
                return
            yield text
    finally:
        cancel.set()


class SpaFiles(StaticFiles):
    """The built React app; an unknown path that is not an API call gets index.html, so
    the app's own routes (e.g. /architecture) survive a page reload."""

    async def get_response(self, path: str, scope):
        try:
            return await super().get_response(path, scope)
        except StarletteHTTPException as missing:  # FastAPI's HTTPException is a SUBclass
            if missing.status_code != 404 or path.startswith("api"):
                raise
            return await super().get_response("index.html", scope)


def create_app(
    load_engine: Callable[[], Engine],
    dist: Path | None,
    gate: Gate | None = None,
    ping_s: float = config.WEB_PING_S,
    deadline_s: float = config.WEB_DEADLINE_S,
) -> FastAPI:
    """The app. load_engine runs once at startup (in a thread: ~15 s of model loading);
    dist: the built frontend to serve at "/", or None (API only, e.g. under `npm run
    dev`, which proxies /api here)."""
    gate = gate or Gate(
        config.WEB_MAX_RUNNING,
        config.WEB_DAILY_QUESTIONS,
        utc_today,
        config.WEB_CLIENT_RUNNING,
        config.WEB_CLIENT_DAILY,
    )

    @asynccontextmanager
    async def lifespan(app: FastAPI):
        app.state.engine = await asyncio.to_thread(load_engine)
        yield

    app = FastAPI(title="CoverageCheck", lifespan=lifespan)

    @app.get("/api/info")
    def info() -> dict:
        return {
            "systems": list(config.WEB_SYSTEMS),
            "model": app.state.engine.model,
            "today": utc_today().isoformat(),
            "questions_left": gate.left(),
            "not_advice": NOT_ADVICE,
        }

    @app.post("/api/ask")
    def ask(body: AskRequest, request: Request) -> StreamingResponse:
        client = client_of(request)
        refused = gate.admit(client)
        if refused:
            raise HTTPException(status_code=429, detail=refused)
        day = body.day or utc_today()
        events = app.state.engine.events(body.system, body.question, day, body.history)
        cancel = threading.Event()
        inbox = start(events, lambda: gate.release(client), cancel)
        return StreamingResponse(
            relay(inbox, cancel, ping_s, deadline_s),
            media_type="text/event-stream",
            headers={"Cache-Control": "no-cache", "X-Accel-Buffering": "no"},
        )

    if dist is not None and (dist / "index.html").exists():
        app.mount("/", SpaFiles(directory=dist, html=True), name="web")
    return app


def main() -> None:
    import uvicorn

    logging.basicConfig(level=logging.INFO)
    app = create_app(Engine.load, config.WEB_DIST_DIR)
    # open streams would hold a shutdown up to the deadline; the host kills us sooner
    uvicorn.run(
        app,
        host=os.environ.get("HOST", config.WEB_HOST),
        port=int(os.environ.get("PORT", config.WEB_PORT)),
        timeout_graceful_shutdown=config.WEB_SHUTDOWN_S,
    )


if __name__ == "__main__":
    main()