strata-python 0.2.2__py3-none-any.whl → 0.2.4__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,101 @@
1
+ """When a failed task should run again, and after how long.
2
+
3
+ Taken from the strata-360 pipeline's retry rules, the most worked-out of the apps' copies: a programming error never
4
+ retries (it fails the same way every time and hides the bug), an outside failure backs off exponentially, and an
5
+ attempt that made progress before it failed resets the count, so a long job that dies near the end of each of many
6
+ nights is not given up on after five of them. The durable queue (`tasks.queue`), the HTTP client and tubes' fetcher
7
+ share it.
8
+
9
+ try:
10
+ work()
11
+ except Exception as e:
12
+ decision = next_state(job.attempts, e, progressed=job.progress_moved, retries=5)
13
+ if decision.state == "retry": requeue(job, after_s=decision.after_s, attempts=decision.attempts)
14
+ else: fail(job, decision.error)
15
+ """
16
+
17
+ from __future__ import annotations
18
+
19
+ import random
20
+ from collections.abc import Callable
21
+ from dataclasses import dataclass
22
+ from typing import Literal
23
+
24
+ PROGRAMMING_ERRORS: tuple[type[BaseException], ...] = (
25
+ AttributeError,
26
+ AssertionError,
27
+ ImportError,
28
+ NameError,
29
+ NotImplementedError,
30
+ RecursionError,
31
+ SyntaxError,
32
+ TypeError,
33
+ )
34
+ """Errors in the code itself: running it again gives the same error, so they fail at once."""
35
+
36
+
37
+ class RetryLater(Exception):
38
+ """Raised by a task that knows it should run again later (a 429 with Retry-After, a file still being written).
39
+ It counts as an attempt; `after_s` replaces the computed backoff."""
40
+
41
+ def __init__(self, reason: str = "retry later", *, after_s: float | None = None) -> None:
42
+ super().__init__(reason)
43
+ self.after_s = after_s
44
+
45
+
46
+ def backoff_s(
47
+ attempts: int,
48
+ *,
49
+ base_s: float = 30.0,
50
+ cap_s: float = 3600.0,
51
+ jitter: float = 0.1,
52
+ rng: Callable[[], float] = random.random,
53
+ ) -> float:
54
+ """The pause before attempt `attempts + 1`: `base_s`, doubling per attempt, at most `cap_s`, spread by
55
+ ±`jitter` so tasks that failed together do not all come back in the same second."""
56
+ pause = min(base_s * 2 ** max(attempts - 1, 0), cap_s)
57
+ return max(pause * (1 + jitter * (2 * rng() - 1)), 0.0)
58
+
59
+
60
+ @dataclass(frozen=True)
61
+ class Decision:
62
+ """What to do with a failed attempt: `retry` after `after_s` with `attempts` counted so far, or `failed`."""
63
+
64
+ state: Literal["retry", "failed"]
65
+ attempts: int
66
+ after_s: float | None
67
+ error: str
68
+
69
+
70
+ def describe(error: BaseException) -> str:
71
+ """One line for a failure: the type and the message (`TimeoutError: read timed out`)."""
72
+ text = str(error)
73
+ return f"{type(error).__name__}: {text}" if text else type(error).__name__
74
+
75
+
76
+ def next_state(
77
+ attempts: int,
78
+ error: BaseException,
79
+ *,
80
+ progressed: bool = False,
81
+ retries: int = 5,
82
+ retryable: Callable[[BaseException], bool] | None = None,
83
+ base_s: float = 30.0,
84
+ cap_s: float = 3600.0,
85
+ rng: Callable[[], float] = random.random,
86
+ ) -> Decision:
87
+ """Decide after a failed attempt. `attempts` is how many had failed before this one; `progressed` says this one
88
+ got further than the last (it then counts as the first failure again); `retries` is how many failures in a row
89
+ are allowed before giving up; `retryable` can refuse an error class the task knows is permanent (a 404)."""
90
+ message = describe(error)
91
+ if isinstance(error, PROGRAMMING_ERRORS):
92
+ return Decision("failed", attempts + 1, None, message)
93
+ count = 1 if progressed else attempts + 1
94
+ if isinstance(error, RetryLater):
95
+ if count > retries:
96
+ return Decision("failed", count, None, message)
97
+ after = error.after_s if error.after_s is not None else backoff_s(count, base_s=base_s, cap_s=cap_s, rng=rng)
98
+ return Decision("retry", count, after, message)
99
+ if (retryable is not None and not retryable(error)) or count > retries:
100
+ return Decision("failed", count, None, message)
101
+ return Decision("retry", count, backoff_s(count, base_s=base_s, cap_s=cap_s, rng=rng), message)
@@ -0,0 +1,188 @@
1
+ """Long work in its own process that outlives the server, with its state in a file anyone can read.
2
+
3
+ strata-360 starts its renders, backups and stitches with `subprocess.Popen` (16 places), keeps their pids in fifteen
4
+ `*_JOBS` dicts and finds them again after a restart through `status.json` files written by five copies of
5
+ `write_status`. `StatusFile` is the file: atomic writes, the writer's pid, and a `read` that knows whether that pid is
6
+ still alive. `Detached` starts the process (outside the server's session, so restarting the server does not kill it),
7
+ writes the file, and stops it with its children.
8
+
9
+ RENDER = Detached(cmd=[*cli_command("strata360"), "render", project], status=f"{project}/render.status.json",
10
+ log=f"{project}/render.log")
11
+ RENDER.start(project=project) # Conflict when one is already running for that file
12
+ RENDER.read() # {"state": "running", "pid": ..., "alive": True, ...}
13
+
14
+ # in the child, which finds its file in STRATA_STATUS_FILE:
15
+ status = StatusFile.from_env()
16
+ status.update(progress={"done": 3, "total": 40})
17
+ status.update(state="done", output=path) # update merges; write replaces the file
18
+
19
+ States: whatever the writer says (`running`, `done`, `failed`, `stopped`), except that a file saying `running` whose
20
+ pid is gone reads as `died`: the process ended without saying so (killed, crashed, the machine rebooted)."""
21
+
22
+ from __future__ import annotations
23
+
24
+ import contextlib
25
+ import datetime
26
+ import json
27
+ import os
28
+ import subprocess
29
+ import tempfile
30
+ from collections.abc import Generator, Mapping, Sequence
31
+ from typing import Any, cast
32
+
33
+ from strata_python import oslib
34
+ from strata_python.tasks.flight import Conflict
35
+
36
+ ENV = "STRATA_STATUS_FILE"
37
+ Json = dict[str, Any]
38
+
39
+
40
+ def write_json_atomic(path: str, data: object) -> None:
41
+ """Write JSON so a reader sees the old file or the new one, never half of either."""
42
+ folder = os.path.dirname(os.path.abspath(path))
43
+ os.makedirs(folder, exist_ok=True)
44
+ fd, tmp = tempfile.mkstemp(dir=folder, prefix=".status.", suffix=".tmp")
45
+ try:
46
+ with os.fdopen(fd, "w", encoding="utf8") as f:
47
+ json.dump(data, f, indent=1, default=str)
48
+ os.replace(tmp, path)
49
+ except BaseException:
50
+ with contextlib.suppress(OSError):
51
+ os.unlink(tmp)
52
+ raise
53
+
54
+
55
+ class StatusFile:
56
+ def __init__(self, path: str) -> None:
57
+ self.path = path
58
+
59
+ @classmethod
60
+ def from_env(cls) -> StatusFile:
61
+ """The file a `Detached` parent named in `STRATA_STATUS_FILE`."""
62
+ path = os.environ.get(ENV)
63
+ if not path:
64
+ raise RuntimeError(f"{ENV} is not set: this process was not started by Detached")
65
+ return cls(path)
66
+
67
+ @contextlib.contextmanager
68
+ def locked(self) -> Generator[None]:
69
+ """Hold the file's lock (`<path>.lock`, across processes): `write` and `update` take it, so a merge never
70
+ loses another writer's fields. Not re-entrant: inside it, write the file with `write_json_atomic`."""
71
+ os.makedirs(os.path.dirname(os.path.abspath(self.path)), exist_ok=True)
72
+ with open(self.path + ".lock", "a+") as f, oslib.file_lock(f):
73
+ yield
74
+
75
+ def write(self, state: str, **fields: Any) -> Json:
76
+ """Replace the file: `state`, this process's pid (unless given), the time, and `fields`."""
77
+ data: Json = {"state": state, "pid": os.getpid(), "at": _now(), **fields}
78
+ with self.locked():
79
+ write_json_atomic(self.path, data)
80
+ return data
81
+
82
+ def update(self, **fields: Any) -> Json:
83
+ """Merge `fields` into the file as it is (the state and pid stay unless given)."""
84
+ with self.locked():
85
+ data: Json = {**(self._load() or {}), **fields, "at": _now()}
86
+ data.setdefault("pid", os.getpid())
87
+ write_json_atomic(self.path, data)
88
+ return data
89
+
90
+ def _load(self) -> Json | None:
91
+ try:
92
+ with open(self.path, encoding="utf8") as f:
93
+ d = json.load(f)
94
+ except (OSError, ValueError):
95
+ return None
96
+ return cast("Json", d) if isinstance(d, dict) else None
97
+
98
+ def read(self) -> Json | None:
99
+ """The file with `alive` added (is its pid running?), and `running` read as `died` when it is not; None when
100
+ there is no file."""
101
+ d = self._load()
102
+ if d is None:
103
+ return None
104
+ d["alive"] = oslib.pid_alive(d.get("pid"))
105
+ if d.get("state") == "running" and not d["alive"]:
106
+ d["state"] = "died"
107
+ return d
108
+
109
+ def running(self) -> bool:
110
+ d = self.read()
111
+ return d is not None and d.get("state") == "running"
112
+
113
+
114
+ def _now() -> str:
115
+ return datetime.datetime.now(datetime.UTC).isoformat()
116
+
117
+
118
+ class Detached:
119
+ """A command run as its own process, tracked through a `StatusFile`. The child gets the file's path in
120
+ `STRATA_STATUS_FILE` and writes its own progress and end state there; its output goes to `log` (appended)."""
121
+
122
+ def __init__(
123
+ self,
124
+ cmd: Sequence[str],
125
+ status: StatusFile | str,
126
+ log: str,
127
+ *,
128
+ env: Mapping[str, str] | None = None,
129
+ cwd: str | None = None,
130
+ ) -> None:
131
+ self.cmd = [str(c) for c in cmd]
132
+ self.status = status if isinstance(status, StatusFile) else StatusFile(status)
133
+ self.log = log
134
+ self.env = env
135
+ self.cwd = cwd
136
+ self._proc: subprocess.Popen[bytes] | None = None
137
+
138
+ def running(self) -> bool:
139
+ """Is the process still running? (A child of this server that has exited is reaped here, so it does not
140
+ linger as a zombie that would still look alive.)"""
141
+ if self._proc is not None and self._proc.poll() is not None:
142
+ self._proc = None
143
+ return self.status.running()
144
+
145
+ def read(self) -> Json | None:
146
+ self.running()
147
+ return self.status.read()
148
+
149
+ def start(self, **fields: Any) -> int:
150
+ """Start the command and return its pid; `Conflict` when the status file says one is still running."""
151
+ if self.running():
152
+ raise Conflict(f"{' '.join(self.cmd[:3])} is already running", self.status.read())
153
+ os.makedirs(os.path.dirname(os.path.abspath(self.log)), exist_ok=True)
154
+ env = {**os.environ, **(self.env or {}), ENV: os.path.abspath(self.status.path)}
155
+ detach = oslib.detached_kwargs()
156
+ # The file is written under its lock, taken before the child exists: a child that reports (or finishes) at
157
+ # once waits for it, so its update lands on top of this one instead of under it.
158
+ with self.status.locked(), open(self.log, "ab") as out:
159
+ proc: subprocess.Popen[bytes] = subprocess.Popen( # noqa: S603 - the app's own command
160
+ self.cmd,
161
+ stdin=subprocess.DEVNULL,
162
+ stdout=out,
163
+ stderr=subprocess.STDOUT,
164
+ env=env,
165
+ cwd=self.cwd,
166
+ start_new_session=bool(detach.get("start_new_session", False)),
167
+ creationflags=int(detach.get("creationflags", 0)),
168
+ )
169
+ data = {"state": "running", "pid": proc.pid, "at": _now(), "cmd": self.cmd, "log": self.log, **fields}
170
+ write_json_atomic(self.status.path, data)
171
+ self._proc = proc
172
+ return proc.pid
173
+
174
+ def stop(self, timeout: float = 10.0) -> bool:
175
+ """Stop the process and everything it started; True when one was running. The file then says `stopped`."""
176
+ d = self.status.read()
177
+ if d is None or d.get("state") != "running":
178
+ return False
179
+ oslib.kill_tree(int(d["pid"]))
180
+ if self._proc is not None:
181
+ try:
182
+ self._proc.wait(timeout)
183
+ except subprocess.TimeoutExpired:
184
+ oslib.kill_tree(int(d["pid"]), 9)
185
+ self._proc.wait(timeout)
186
+ self._proc = None
187
+ self.status.update(state="stopped")
188
+ return True
@@ -0,0 +1,85 @@
1
+ """Run a function every so often on a daemon thread: the backup sweep, the prefetch loop, the GPU poller.
2
+
3
+ Five apps wrote this loop by hand (`while not stop.wait(every): fn()`), and most of them let one exception end the
4
+ loop for the rest of the server's life. A `Ticker` catches it, hands it to `on_error` (by default the log) and keeps
5
+ going, and stops promptly: `stop()` wakes the wait instead of sleeping out the interval.
6
+
7
+ with Ticker(300, sweep, name="sweep"): # or .start() at startup and .stop() at shutdown
8
+ serve(app)
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ import logging
14
+ import threading
15
+ from collections.abc import Callable
16
+ from types import TracebackType
17
+
18
+ log = logging.getLogger(__name__)
19
+
20
+
21
+ class Ticker:
22
+ def __init__(
23
+ self,
24
+ every_s: float,
25
+ fn: Callable[[], object],
26
+ *,
27
+ name: str,
28
+ on_error: Callable[[BaseException], None] | None = None,
29
+ immediately: bool = False,
30
+ ) -> None:
31
+ """`immediately` runs `fn` once at start instead of after the first interval."""
32
+ self.every_s = every_s
33
+ self.fn = fn
34
+ self.name = name
35
+ self.on_error = on_error
36
+ self.immediately = immediately
37
+ self.ticks = 0 # runs completed, failed ones included
38
+ self.last_error: BaseException | None = None
39
+ self._stop = threading.Event()
40
+ self._thread: threading.Thread | None = None
41
+
42
+ def _tick(self) -> None:
43
+ try:
44
+ self.fn()
45
+ self.last_error = None
46
+ except Exception as e:
47
+ self.last_error = e
48
+ if self.on_error is not None:
49
+ self.on_error(e)
50
+ else:
51
+ log.exception("%s failed; trying again in %s s", self.name, self.every_s)
52
+ finally:
53
+ self.ticks += 1
54
+
55
+ def _loop(self) -> None:
56
+ if self.immediately and not self._stop.is_set():
57
+ self._tick()
58
+ while not self._stop.wait(self.every_s):
59
+ self._tick()
60
+
61
+ def start(self) -> Ticker:
62
+ if self._thread is not None and self._thread.is_alive():
63
+ return self
64
+ self._stop.clear()
65
+ self._thread = threading.Thread(target=self._loop, name=self.name, daemon=True)
66
+ self._thread.start()
67
+ return self
68
+
69
+ def stop(self, timeout: float | None = 10.0) -> None:
70
+ """Stop after the run in progress, if any; waits up to `timeout` for it."""
71
+ self._stop.set()
72
+ if self._thread is not None:
73
+ self._thread.join(timeout)
74
+
75
+ @property
76
+ def running(self) -> bool:
77
+ return self._thread is not None and self._thread.is_alive()
78
+
79
+ def __enter__(self) -> Ticker:
80
+ return self.start()
81
+
82
+ def __exit__(
83
+ self, exc_type: type[BaseException] | None, exc: BaseException | None, tb: TracebackType | None
84
+ ) -> None:
85
+ self.stop()
strata_python/testing.py CHANGED
@@ -15,6 +15,8 @@ Testing policy).
15
15
  FakeRun `subprocess.run` / `check_output`; `.returns` maps a command-line substring to stdout, `.code` fails
16
16
  Sleeper `time.sleep` that returns at once and records `.delays`
17
17
  run_cli an argparse `main(argv)` in this process -> CliResult; run_module the same as a real `python -m`
18
+ FakeModels a stand-in strata-models service (jobs, leases, registry) for `strata_python.clients.models`; served
19
+ by the `fake_models` fixture. MODELS_RESULTS holds one reply per role in the service's shapes.
18
20
  """
19
21
 
20
22
  from __future__ import annotations
@@ -255,3 +257,165 @@ def run_module(
255
257
  if check and p.returncode:
256
258
  raise AssertionError(f"python -m {module} exited {p.returncode}:\n{result.out}")
257
259
  return result
260
+
261
+
262
+ # --- a stand-in strata-models ---------------------------------------------------------------------------------------
263
+
264
+ Json = dict[str, Any]
265
+ Result = Json | Callable[[Json], Json]
266
+
267
+ MODELS_RESULTS: dict[str, Json] = {
268
+ "ocr": {
269
+ "width": 1200, "height": 1800, "text": "CHAPTER I\nIt was a dark night.",
270
+ "lines": [
271
+ {"text": "CHAPTER I", "box": [100, 80, 300, 40], "conf": 96.5, "block": 1,
272
+ "words": [{"text": "CHAPTER", "box": [100, 80, 200, 40], "conf": 97.0}, {"text": "I", "box": [320, 80, 20, 40], "conf": 96.0}]},
273
+ {"text": "It was a dark night.", "box": [100, 160, 600, 30], "conf": 91.2, "block": 2, "words": []},
274
+ ],
275
+ "engine": "tesseract 5.5", "lang": "eng", "psm": 3, "clean": [], "seconds": 1.2, "model": "tesseract", "pdf": "/out/p.pdf",
276
+ },
277
+ "transcribe": {
278
+ "language": "en", "language_probability": 0.99, "duration": 3.5,
279
+ "segments": [{"start": 0.0, "end": 1.5, "text": " Hello", "avg_logprob": -0.2, "no_speech_prob": 0.01,
280
+ "words": [{"start": 0.0, "end": 1.5, "word": " Hello", "probability": 0.9}]},
281
+ {"start": 1.5, "end": 3.5, "text": " world.", "avg_logprob": -0.3, "no_speech_prob": 0.02}],
282
+ },
283
+ "faces": {"width": 640, "height": 480, "faces": [{"bbox": [1, 2, 30, 40], "kps": [[5, 6]] * 5, "det_score": 0.87, "embedding": [0.1] * 4, "pose": [1, 2, 3]}, {"bbox": [9, 9, 20, 20]}]},
284
+ "speak": {"path": "/out/s.wav", "duration_s": 2.5, "sample_rate": 24000, "seconds": 0.8, "engine": "kokoro", "voice": "af_heart", "seed": 1, "speech_s": 2.1},
285
+ "vision-language": {"text": '{"scene": "beach"}', "json": {"scene": "beach"}, "tokens_in": 812, "tokens_out": 9, "seconds": 1.4, "model": "qwen3.5-9b-vl", "peak_vram_mb": 7100},
286
+ "image-generate": {"path": "/out/g.png", "width": 1024, "height": 768, "seed": 1234, "steps": 4, "seconds": 9.5, "peak_vram_mb": 9000, "model": "flux3-klein"},
287
+ "image-embed": {"images": [[0.6, 0.8]], "texts": [[1.0, 0.0], [0.0, 1.0]], "dim": 2},
288
+ "face-kind": {"faces": [{"real": True, "kind": "person", "probs": {"person": 0.97, "statue": 0.03}}, {"real": False, "kind": "statue", "probs": {}}], "head": "trained head.npz"},
289
+ "denoise-audio": {"path": "/out/c.wav", "duration_s": 4.0, "sample_rate": 48000, "seconds": 0.7, "engine": "dfn3", "model": "deepfilternet3", "lufs_in": -31.2, "lufs_out": -14.0, "removed_db": 6.5},
290
+ "audio-quality": {"dnsmos": {"sig": 3.4, "bak": 3.9, "ovrl": 3.0}, "squim": {"stoi": 0.93, "pesq": 2.8, "si_sdr": 14.2}, "duration_s": 4.0},
291
+ "video-enhance": {
292
+ "path": "/out/v.mp4", "width": 1440, "height": 1080, "fps": 50.0, "frames": 400, "seconds": 61.0, "engine": "ffmpeg", "model": "video-lanczos",
293
+ "crops": [{"id": "face", "label": "Gran", "box": [100, 50, 80, 80], "path": "/out/v-face.mp4", "stills": ["/out/v-face-3.png"]}],
294
+ "stills": ["/out/v-1.png"], "enhance_s": 40.0, "quality": {"ssim": 0.91, "skipped": "no numpy"},
295
+ },
296
+ } # fmt: skip
297
+ """One reply per role in the service's own shapes (taken from its runtimes), so `Shape.from_json` reads each one."""
298
+ for _role in ("transcribe-fast",):
299
+ MODELS_RESULTS[_role] = MODELS_RESULTS["transcribe"]
300
+ for _role in ("text", "judge-text", "judge-vision", "judge-audio"):
301
+ MODELS_RESULTS[_role] = MODELS_RESULTS["vision-language"]
302
+
303
+
304
+ class FakeModels:
305
+ """A stand-in strata-models service for an app's tests, over real HTTP: the `fake_models` fixture serves `.app` on
306
+ a loopback port and points `STRATA_MODELS_URL` at it, so the app's own calls through `strata_python.clients.models`
307
+ run unchanged. The job and lease endpoints follow the service's steps (queued, running, then done or failed;
308
+ long-poll `?wait=` is accepted and answered at once), so a test sees what the app does with each outcome.
309
+
310
+ fake_models.results["ocr"] = {...} # or a function of the job's params
311
+ fake_models.fail("CUDA out of memory") # the next job fails (fail(..., role="faces"): the next faces job)
312
+ fake_models.busy = True # leases stay queued: the GPU is someone else's
313
+ fake_models.down = True # every request is a 503
314
+ assert fake_models.jobs[0]["params"]["lang"] == "eng"
315
+
316
+ `running_polls` is how many polls a job answers `running` before it finishes (default 1, as the real service
317
+ usually is when the first poll arrives). A role with no result is refused with a 422, as the service refuses a role
318
+ it does not know. The registry answers each role's model from `.models` (role -> model name)."""
319
+
320
+ def __init__(self, results: Mapping[str, Result] | None = None, *, running_polls: int = 1) -> None:
321
+ from fastapi import FastAPI, HTTPException, Request # here, so importing the fakes does not load FastAPI
322
+
323
+ self.results: dict[str, Result] = dict(MODELS_RESULTS if results is None else results)
324
+ self.models: dict[str, str] = {}
325
+ self.running_polls = running_polls
326
+ self.jobs: list[Json] = [] # every job submitted, in order, as the service stored it
327
+ self.leases: list[Json] = []
328
+ self.heartbeats: list[int] = []
329
+ self.released: list[int] = []
330
+ self.busy = False
331
+ self.refuse = False # a lease request ends at once, without the GPU
332
+ self.down = False
333
+ self._failures: list[tuple[str | None, str]] = []
334
+ self._polls: dict[int, int] = {}
335
+ app = FastAPI()
336
+ self.app = app
337
+
338
+ @app.middleware("http")
339
+ async def unavailable(request: Request, call_next: Callable[[Request], Any]) -> Any: # pyright: ignore[reportUnusedFunction]
340
+ if self.down:
341
+ from fastapi.responses import JSONResponse
342
+
343
+ return JSONResponse({"detail": "starting"}, status_code=503)
344
+ return await call_next(request)
345
+
346
+ @app.get("/api/health")
347
+ def health() -> Json: # pyright: ignore[reportUnusedFunction]
348
+ return {"ok": True, "version": "0-fake", "gpu": None}
349
+
350
+ @app.get("/api/registry")
351
+ def registry() -> Json: # pyright: ignore[reportUnusedFunction]
352
+ return {"roles": [{"key": r, "model": self.models.get(r, f"fake-{r}")} for r in self.results]}
353
+
354
+ @app.post("/api/jobs")
355
+ def submit(body: Json) -> Json: # pyright: ignore[reportUnusedFunction]
356
+ role = str(body.get("role"))
357
+ if role not in self.results:
358
+ raise HTTPException(422, f"unknown role {role!r}")
359
+ job: Json = {**body, "id": len(self.jobs) + 1, "status": "queued", "result": None, "error": None}
360
+ self.jobs.append(job)
361
+ return dict(job)
362
+
363
+ @app.get("/api/jobs/{job_id}")
364
+ def poll(job_id: int, wait: float = 0) -> Json: # pyright: ignore[reportUnusedFunction]
365
+ job = self._job(job_id, HTTPException)
366
+ if job["status"] in ("queued", "running"):
367
+ n = self._polls[job_id] = self._polls.get(job_id, 0) + 1
368
+ if n <= self.running_polls:
369
+ job["status"] = "running"
370
+ else:
371
+ self._finish(job)
372
+ return dict(job)
373
+
374
+ @app.post("/api/leases")
375
+ def lease(body: Json) -> Json: # pyright: ignore[reportUnusedFunction]
376
+ row: Json = {**body, "id": len(self.leases) + 1, "status": "cancelled" if self.refuse else "queued"}
377
+ self.leases.append(row)
378
+ return dict(row)
379
+
380
+ @app.get("/api/leases/{lease_id}")
381
+ def lease_poll(lease_id: int, wait: float = 0) -> Json: # pyright: ignore[reportUnusedFunction]
382
+ row = self._lease(lease_id, HTTPException)
383
+ if row["status"] == "queued" and not self.busy:
384
+ row["status"] = "running"
385
+ return dict(row)
386
+
387
+ @app.post("/api/leases/{lease_id}/heartbeat")
388
+ def beat(lease_id: int) -> Json: # pyright: ignore[reportUnusedFunction]
389
+ self._lease(lease_id, HTTPException)
390
+ self.heartbeats.append(lease_id)
391
+ return {"ok": True}
392
+
393
+ @app.delete("/api/leases/{lease_id}")
394
+ def release(lease_id: int) -> Json: # pyright: ignore[reportUnusedFunction]
395
+ self._lease(lease_id, HTTPException)["status"] = "done"
396
+ self.released.append(lease_id)
397
+ return {"ok": True}
398
+
399
+ def fail(self, error: str = "the model failed", *, role: str | None = None) -> FakeModels:
400
+ """The next job (of `role`, when given) fails with `error`. Calls queue up: each failure is used once."""
401
+ self._failures.append((role, error))
402
+ return self
403
+
404
+ def _finish(self, job: Json) -> None:
405
+ for i, (role, error) in enumerate(self._failures):
406
+ if role is None or role == job["role"]:
407
+ del self._failures[i]
408
+ job.update(status="failed", error=error)
409
+ return
410
+ result = self.results[job["role"]]
411
+ job.update(status="done", result=result(dict(job["params"] or {})) if callable(result) else result)
412
+
413
+ def _job(self, job_id: int, error: Callable[[int, str], Exception]) -> Json:
414
+ if not 1 <= job_id <= len(self.jobs):
415
+ raise error(404, f"no job {job_id}")
416
+ return self.jobs[job_id - 1]
417
+
418
+ def _lease(self, lease_id: int, error: Callable[[int, str], Exception]) -> Json:
419
+ if not 1 <= lease_id <= len(self.leases):
420
+ raise error(404, f"no lease {lease_id}")
421
+ return self.leases[lease_id - 1]