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,716 @@
1
+ """A durable job queue in the app's own database (SQLite or the shared Postgres), with workers in this process.
2
+ Needs the db extra (`strata-python[db]`).
3
+
4
+ Seven apps had seven job systems. This one takes the schema and claim loop from strata-listory's `JobQueue` (the most
5
+ used), rewritten on SQLAlchemy Core so it runs on both backends; the API style of the strata-models store (an
6
+ injectable clock, a claim that is one conditional UPDATE, cursor paging, `recover`, `prune`, a deterministic `step`
7
+ for tests); and the retry rules of `tasks.retry`.
8
+
9
+ # models.py: the table is part of the app's models, so its migrations create it
10
+ from strata_python.tasks.queue import jobs_table
11
+ JOBS = jobs_table(Base.metadata)
12
+
13
+ # the app
14
+ QUEUE = Queue(engine, JOBS)
15
+ jid = QUEUE.enqueue("ocr", {"page": 3}, domain="book:12", dedupe=True, resources=["gpu"])
16
+
17
+ def ocr(job: Job) -> dict:
18
+ for i, line in enumerate(lines):
19
+ if job.stopping: return {"lines": i} # cancelled, timed out or shutting down
20
+ report_progress(i, len(lines), f"line {i}")
21
+ return {"lines": len(lines)}
22
+
23
+ WORKER = Worker(QUEUE, {"ocr": ocr}, concurrency=2).start() # a process per job; stop() at shutdown
24
+ QUEUE.page(state="running") # Page[Task] for the API
25
+ QUEUE.cancel(jid)
26
+
27
+ What a job gets:
28
+ - **Retry**: a failure goes through `tasks.retry.next_state`: a programming error fails at once, anything else runs
29
+ again after a backoff, up to `retries` failures in a row; an attempt that got further than the last (its progress
30
+ `done` grew) counts as the first failure again. `RetryLater(after_s=...)` names its own pause.
31
+ - **Crash recovery**: a running job whose worker died (its pid is gone on this host, or no heartbeat for
32
+ `stale_s`) is failed with `WorkerLost` by `recover()` (which `Worker.start` runs) and so retried like any failure.
33
+ Each claim gets its own token and every write an attempt makes names it, so a worker that was only slow, and whose
34
+ job has since been claimed again, finds its writes ignored and its heartbeat telling it to stop.
35
+ - **Dedupe**: `dedupe=True` returns the id of a queued or running job with the same kind, domain and options instead
36
+ of adding another (best effort: two enqueues in the same instant from two processes can both add one).
37
+ - **Resources**: a job is not claimed while a running job holds one of its `resources` (the GPU, a book's folder).
38
+ Claims are serialised (a lock in this process, a transaction-scoped advisory lock on Postgres, the write lock on
39
+ SQLite), so two workers, in this process or another, never start two jobs that share a resource.
40
+ - **Cancel and timeout**: `cancel` ends a queued job at once and stops a running one; a job past its `timeout_s` is
41
+ stopped and fails with TimeoutError (so it retries). A `Worker` runs each job in its own process group by default
42
+ (`tasks.child`), so stopping kills the job and the tools it started; with `isolate=False` (and in `run`/`step`) it
43
+ is cooperative: the handler sees `job.stopping` and returns, and one that never checks runs to the end.
44
+ - **on_fail**: `Queue(on_fail=...)` is called with the connection, the job and the error inside the transaction that
45
+ fails it for good, for the app's cascade (listory marks the book's other jobs).
46
+
47
+ Times are float epoch seconds in the table (the same on both backends) and aware datetimes in `Task`.
48
+ """
49
+
50
+ from __future__ import annotations
51
+
52
+ import contextlib
53
+ import hashlib
54
+ import json
55
+ import logging
56
+ import os
57
+ import socket
58
+ import threading
59
+ import time
60
+ import uuid
61
+ from collections.abc import Callable, Generator, Mapping, Sequence
62
+ from dataclasses import dataclass, field
63
+ from typing import Any, cast
64
+
65
+ from sqlalchemy import (
66
+ Boolean,
67
+ Column,
68
+ Float,
69
+ Index,
70
+ Integer,
71
+ MetaData,
72
+ String,
73
+ Table,
74
+ Text,
75
+ and_,
76
+ delete,
77
+ func,
78
+ or_,
79
+ select,
80
+ text,
81
+ update,
82
+ )
83
+ from sqlalchemy.engine import Connection, Engine, Row
84
+
85
+ from strata_python import oslib
86
+ from strata_python.contracts import FINISHED, Page, Progress, Task, utc
87
+ from strata_python.tasks import child
88
+ from strata_python.tasks.progress import ProgressReporter, reporting
89
+ from strata_python.tasks.retry import Decision, next_state
90
+
91
+ ACTIVE = ("queued", "running")
92
+ Json = dict[str, Any]
93
+ Handler = Callable[["Job"], Any]
94
+ log = logging.getLogger(__name__)
95
+
96
+
97
+ class WorkerLost(RuntimeError):
98
+ """The worker running a job stopped without finishing it (crashed, killed, or the machine went down)."""
99
+
100
+
101
+ class JobCancelled(RuntimeError):
102
+ """Raised by `Queue.check(job)` when a running job has been asked to stop."""
103
+
104
+
105
+ def jobs_table(metadata: MetaData, name: str = "jobs") -> Table:
106
+ """The queue's table in the app's MetaData (its naming convention names the keys and indexes)."""
107
+ return Table(
108
+ name,
109
+ metadata,
110
+ Column("id", Integer, primary_key=True, autoincrement=True),
111
+ Column("kind", String(100), nullable=False),
112
+ Column("domain", String(500), nullable=True), # what the job is about in the app's terms: "book:12"
113
+ Column("options", Text, nullable=False, default="{}"), # JSON
114
+ Column("dedupe", String(64), nullable=True), # sha256 of kind, domain and options, when asked for
115
+ Column("resources", Text, nullable=False, default="[]"), # JSON list of names
116
+ Column("state", String(20), nullable=False),
117
+ Column("priority", Integer, nullable=False, default=0),
118
+ Column("attempts", Integer, nullable=False, default=0),
119
+ Column("run_after", Float, nullable=True),
120
+ Column("timeout_s", Float, nullable=True),
121
+ Column("created_at", Float, nullable=False),
122
+ Column("started_at", Float, nullable=True),
123
+ Column("finished_at", Float, nullable=True),
124
+ Column("heartbeat_at", Float, nullable=True),
125
+ Column("owner", String(200), nullable=True), # host:pid of the worker running it
126
+ Column("owner_pid", Integer, nullable=True),
127
+ # A new token per claim: every update an attempt makes names it, so a worker whose job was recovered and
128
+ # claimed again elsewhere cannot write over the new attempt.
129
+ Column("claim_token", String(32), nullable=True),
130
+ Column("cancel_requested", Boolean, nullable=False, default=False),
131
+ Column("error", Text, nullable=True),
132
+ Column("result", Text, nullable=True), # JSON
133
+ Column("progress", Text, nullable=True), # JSON: a Progress
134
+ Index(f"ix_{name}_claim", "state", "priority", "id"),
135
+ Index(f"ix_{name}_dedupe", "dedupe"),
136
+ Index(f"ix_{name}_domain", "domain"),
137
+ )
138
+
139
+
140
+ def _loads(raw: str | None) -> Any:
141
+ return None if raw is None else json.loads(raw)
142
+
143
+
144
+ @dataclass
145
+ class Job:
146
+ """A job as a handler sees it. `stopping` turns true when it is cancelled, times out or the worker stops."""
147
+
148
+ id: int
149
+ kind: str
150
+ domain: str | None
151
+ options: Json
152
+ state: str
153
+ priority: int
154
+ attempts: int
155
+ resources: list[str]
156
+ created_at: float
157
+ started_at: float | None
158
+ finished_at: float | None
159
+ run_after: float | None
160
+ timeout_s: float | None
161
+ error: str | None
162
+ result: Any
163
+ progress: Progress | None
164
+ cancel_requested: bool
165
+ token: str | None = None
166
+ stop_event: threading.Event = field(default_factory=threading.Event, repr=False)
167
+
168
+ @classmethod
169
+ def from_row(cls, r: Row[Any]) -> Job:
170
+ p = _loads(r.progress)
171
+ return cls(
172
+ id=int(r.id),
173
+ kind=str(r.kind),
174
+ domain=r.domain,
175
+ options=cast("Json", _loads(r.options) or {}),
176
+ state=str(r.state),
177
+ priority=int(r.priority),
178
+ attempts=int(r.attempts),
179
+ resources=cast("list[str]", _loads(r.resources) or []),
180
+ created_at=float(r.created_at),
181
+ started_at=r.started_at,
182
+ finished_at=r.finished_at,
183
+ run_after=r.run_after,
184
+ timeout_s=r.timeout_s,
185
+ error=r.error,
186
+ result=_loads(r.result),
187
+ progress=None if p is None else Progress.model_validate(p),
188
+ cancel_requested=bool(r.cancel_requested),
189
+ token=r.claim_token,
190
+ )
191
+
192
+ @property
193
+ def stopping(self) -> bool:
194
+ return self.cancel_requested or self.stop_event.is_set()
195
+
196
+ def to_task(self) -> Task:
197
+ created = utc(self.created_at)
198
+ assert created is not None # noqa: S101 - created_at is NOT NULL
199
+ return Task(
200
+ id=self.id,
201
+ kind=self.kind,
202
+ state=cast("Any", self.state),
203
+ created_at=created,
204
+ started_at=utc(self.started_at),
205
+ finished_at=utc(self.finished_at),
206
+ error=self.error,
207
+ result=self.result,
208
+ progress=self.progress,
209
+ attempts=self.attempts,
210
+ domain=self.domain,
211
+ )
212
+
213
+
214
+ def dedupe_key(kind: str, domain: str | None, options: Mapping[str, Any]) -> str:
215
+ return hashlib.sha256(json.dumps([kind, domain, options], sort_keys=True, default=str).encode()).hexdigest()
216
+
217
+
218
+ class Queue:
219
+ def __init__(
220
+ self,
221
+ engine: Engine,
222
+ table: Table,
223
+ *,
224
+ clock: Callable[[], float] = time.time,
225
+ owner: str | None = None,
226
+ retries: int = 5,
227
+ base_s: float = 30.0,
228
+ cap_s: float = 3600.0,
229
+ on_fail: Callable[[Connection, Job, str], None] | None = None,
230
+ batch: int = 200,
231
+ ) -> None:
232
+ self.engine = engine
233
+ self.t = table
234
+ self.clock = clock
235
+ self.host = socket.gethostname()
236
+ self.owner = owner or f"{self.host}:{os.getpid()}"
237
+ self.retries = retries
238
+ self.base_s = base_s
239
+ self.cap_s = cap_s
240
+ self.on_fail = on_fail
241
+ self.batch = batch
242
+ self._claim_lock = threading.Lock()
243
+
244
+ # --- adding and reading ------------------------------------------------------------------------------------------
245
+
246
+ def enqueue(
247
+ self,
248
+ kind: str,
249
+ options: Mapping[str, Any] | None = None,
250
+ *,
251
+ domain: str | None = None,
252
+ priority: int = 0,
253
+ resources: Sequence[str] = (),
254
+ dedupe: bool = False,
255
+ delay_s: float | None = None,
256
+ timeout_s: float | None = None,
257
+ ) -> int:
258
+ """Add a job and return its id (or, with `dedupe`, the id of the same job already queued or running).
259
+ Higher `priority` runs first; `delay_s` holds it back that long."""
260
+ opts = dict(options or {})
261
+ key = dedupe_key(kind, domain, opts) if dedupe else None
262
+ t = self.t
263
+ with self.engine.begin() as c:
264
+ if key is not None:
265
+ found = c.execute(select(t.c.id).where(t.c.dedupe == key, t.c.state.in_(ACTIVE)).limit(1)).first()
266
+ if found is not None:
267
+ return int(found.id)
268
+ now = self.clock()
269
+ res = c.execute(
270
+ t.insert().values(
271
+ kind=kind,
272
+ domain=domain,
273
+ options=json.dumps(opts),
274
+ dedupe=key,
275
+ resources=json.dumps(sorted(set(resources))),
276
+ state="queued",
277
+ priority=priority,
278
+ attempts=0,
279
+ run_after=None if delay_s is None else now + delay_s,
280
+ timeout_s=timeout_s,
281
+ created_at=now,
282
+ cancel_requested=False,
283
+ )
284
+ )
285
+ pk = res.inserted_primary_key
286
+ assert pk is not None # noqa: S101 - an insert always has one
287
+ return int(pk[0])
288
+
289
+ def get(self, job_id: int) -> Job | None:
290
+ with self.engine.connect() as c:
291
+ r = c.execute(select(self.t).where(self.t.c.id == job_id)).first()
292
+ return None if r is None else Job.from_row(r)
293
+
294
+ def page(
295
+ self,
296
+ *,
297
+ state: str | Sequence[str] | None = None,
298
+ kind: str | None = None,
299
+ domain: str | None = None,
300
+ after: str | None = None,
301
+ limit: int = 50,
302
+ ) -> Page[Task]:
303
+ """Jobs newest first, `limit` at a time; pass the page's `next` back as `after` for the next page."""
304
+ t = self.t
305
+ q = select(t).order_by(t.c.id.desc()).limit(limit + 1)
306
+ if state is not None:
307
+ q = q.where(t.c.state.in_([state] if isinstance(state, str) else list(state)))
308
+ if kind is not None:
309
+ q = q.where(t.c.kind == kind)
310
+ if domain is not None:
311
+ q = q.where(t.c.domain == domain)
312
+ if after:
313
+ q = q.where(t.c.id < int(after))
314
+ with self.engine.connect() as c:
315
+ rows = c.execute(q).all()
316
+ jobs = [Job.from_row(r) for r in rows[:limit]]
317
+ more = len(rows) > limit
318
+ return Page[Task](items=[j.to_task() for j in jobs], next=str(jobs[-1].id) if more and jobs else None)
319
+
320
+ def counts(self) -> dict[str, int]:
321
+ """How many jobs are in each state."""
322
+ with self.engine.connect() as c:
323
+ rows = c.execute(select(self.t.c.state, func.count()).group_by(self.t.c.state)).all()
324
+ return {str(s): int(n) for s, n in rows}
325
+
326
+ # --- claiming and running ----------------------------------------------------------------------------------------
327
+
328
+ @contextlib.contextmanager
329
+ def _serialised(self) -> Generator[Connection]:
330
+ """One claim at a time: a lock in this process and, on Postgres, an advisory lock for this table that
331
+ other processes wait on too (released when the transaction ends)."""
332
+ with self._claim_lock, self.engine.begin() as c:
333
+ if c.dialect.name == "postgresql":
334
+ lock_id = int(hashlib.sha256(f"strata-queue:{self.t.fullname}".encode()).hexdigest()[:15], 16)
335
+ c.execute(text("SELECT pg_advisory_xact_lock(:k)"), {"k": lock_id})
336
+ elif c.dialect.name == "sqlite":
337
+ # A write that changes nothing takes SQLite's write lock for the rest of the transaction, so another
338
+ # process (or another Queue on the same file) waits here, before it reads which resources are held.
339
+ c.execute(update(self.t).where(text("0")).values(state=self.t.c.state))
340
+ yield c
341
+
342
+ def claim(self, kinds: Sequence[str] | None = None) -> Job | None:
343
+ """Take the next job this worker may run (highest priority, then oldest; not before its `run_after`; none of
344
+ its resources held by a running job) and mark it running. None when there is nothing to do. Candidates are read
345
+ `batch` at a time, in claim order, so jobs waiting on a held resource never hide the ones behind them."""
346
+ t = self.t
347
+ now = self.clock()
348
+ with self._serialised() as c:
349
+ held: set[str] = set()
350
+ for (raw,) in c.execute(select(t.c.resources).where(t.c.state == "running")).all():
351
+ held.update(cast("list[str]", json.loads(raw)))
352
+ base = (
353
+ select(t)
354
+ .where(t.c.state == "queued", or_(t.c.run_after.is_(None), t.c.run_after <= now))
355
+ .order_by(t.c.priority.desc(), t.c.id)
356
+ .limit(self.batch)
357
+ )
358
+ if kinds is not None:
359
+ base = base.where(t.c.kind.in_(list(kinds)))
360
+ q = base
361
+ while rows := c.execute(q).all():
362
+ for r in rows:
363
+ if held & set(cast("list[str]", json.loads(r.resources))):
364
+ continue
365
+ token = uuid.uuid4().hex
366
+ done = c.execute(
367
+ update(t)
368
+ .where(t.c.id == r.id, t.c.state == "queued")
369
+ .values(
370
+ state="running",
371
+ started_at=now,
372
+ heartbeat_at=now,
373
+ owner=self.owner,
374
+ owner_pid=os.getpid(),
375
+ cancel_requested=False,
376
+ claim_token=token,
377
+ )
378
+ )
379
+ if done.rowcount == 1:
380
+ return Job.from_row(c.execute(select(t).where(t.c.id == r.id)).one())
381
+ last = rows[-1] # the next batch starts after the last one read (priority desc, then id)
382
+ q = base.where(or_(t.c.priority < last.priority, and_(t.c.priority == last.priority, t.c.id > last.id)))
383
+ return None
384
+
385
+ def _mine(self, job: Job) -> Any:
386
+ """The row of this attempt of `job`: still running, under the claim this worker made."""
387
+ return and_(self.t.c.id == job.id, self.t.c.state == "running", self.t.c.claim_token == job.token)
388
+
389
+ def heartbeat(self, job: Job) -> bool:
390
+ """Mark the job alive and pick up a cancel request; False when it should stop."""
391
+ t = self.t
392
+ with self.engine.begin() as c:
393
+ c.execute(update(t).where(self._mine(job)).values(heartbeat_at=self.clock()))
394
+ r = c.execute(select(t.c.cancel_requested, t.c.state, t.c.claim_token).where(t.c.id == job.id)).first()
395
+ if r is None or r.state != "running" or r.claim_token != job.token or r.cancel_requested:
396
+ job.cancel_requested = True
397
+ return not job.stopping
398
+
399
+ def report(self, job: Job, progress: Progress) -> None:
400
+ """Store the job's progress (and count it as a heartbeat)."""
401
+ t = self.t
402
+ with self.engine.begin() as c:
403
+ c.execute(
404
+ update(t).where(self._mine(job)).values(progress=progress.model_dump_json(), heartbeat_at=self.clock())
405
+ )
406
+ job.progress = progress
407
+
408
+ def check(self, job: Job) -> None:
409
+ """Raise `JobCancelled` if the job has been asked to stop (for handlers that prefer an exception)."""
410
+ if job.stopping:
411
+ raise JobCancelled(f"job {job.id} was asked to stop")
412
+
413
+ def finish(self, job: Job, result: Any = None) -> None:
414
+ """The job is done (or `cancelled`, when it stopped because it was asked to)."""
415
+ t = self.t
416
+ state = "cancelled" if job.cancel_requested else "done"
417
+ with self.engine.begin() as c:
418
+ c.execute(
419
+ update(t)
420
+ .where(self._mine(job))
421
+ .values(state=state, finished_at=self.clock(), result=json.dumps(result, default=str), error=None)
422
+ )
423
+ job.state = state
424
+
425
+ def fail(
426
+ self,
427
+ job: Job,
428
+ error: BaseException,
429
+ *,
430
+ progressed: bool = False,
431
+ retryable: Callable[[BaseException], bool] | None = None,
432
+ ) -> Decision:
433
+ """Record a failed attempt: queued again after its backoff, or failed for good (then `on_fail` runs)."""
434
+ t = self.t
435
+ d = next_state(
436
+ job.attempts,
437
+ error,
438
+ progressed=progressed,
439
+ retries=self.retries,
440
+ retryable=retryable,
441
+ base_s=self.base_s,
442
+ cap_s=self.cap_s,
443
+ )
444
+ if job.cancel_requested and not isinstance(error, TimeoutError):
445
+ d = Decision("failed", d.attempts, None, d.error) # a cancelled job is not run again
446
+ now = self.clock()
447
+ with self.engine.begin() as c:
448
+ if d.state == "retry":
449
+ values: Json = {
450
+ "state": "queued",
451
+ "run_after": now + (d.after_s or 0),
452
+ "owner": None,
453
+ "owner_pid": None,
454
+ "heartbeat_at": None,
455
+ "claim_token": None,
456
+ }
457
+ else:
458
+ values = {"state": "cancelled" if job.cancel_requested else "failed", "finished_at": now}
459
+ done = c.execute(update(t).where(self._mine(job)).values(attempts=d.attempts, error=d.error, **values))
460
+ if done.rowcount == 0: # this attempt was recovered (and maybe claimed again): nothing of it to record
461
+ return d
462
+ if d.state == "failed" and self.on_fail is not None:
463
+ self.on_fail(c, job, d.error)
464
+ job.state, job.attempts, job.error = str(values["state"]), d.attempts, d.error
465
+ return d
466
+
467
+ def cancel(self, job_id: int) -> str | None:
468
+ """Cancel a queued job at once, or ask a running one to stop. Returns the job's state after, None if unknown."""
469
+ t = self.t
470
+ with self.engine.begin() as c:
471
+ c.execute(
472
+ update(t)
473
+ .where(t.c.id == job_id, t.c.state == "queued")
474
+ .values(state="cancelled", finished_at=self.clock())
475
+ )
476
+ c.execute(update(t).where(t.c.id == job_id, t.c.state == "running").values(cancel_requested=True))
477
+ r = c.execute(select(t.c.state).where(t.c.id == job_id)).first()
478
+ return None if r is None else str(r.state)
479
+
480
+ def retry(self, job_id: int) -> bool:
481
+ """Run a failed or cancelled job again, from a clean count (a person asked for it)."""
482
+ t = self.t
483
+ with self.engine.begin() as c:
484
+ done = c.execute(
485
+ update(t)
486
+ .where(t.c.id == job_id, t.c.state.in_(("failed", "cancelled")))
487
+ .values(state="queued", attempts=0, run_after=None, finished_at=None, cancel_requested=False)
488
+ )
489
+ return done.rowcount == 1
490
+
491
+ # --- housekeeping ------------------------------------------------------------------------------------------------
492
+
493
+ def recover(self, *, stale_s: float = 300.0) -> list[int]:
494
+ """Fail (and so retry) running jobs whose worker is gone: its process is not alive on this host, or it has
495
+ not sent a heartbeat for `stale_s`. Returns their ids. `Worker.start` runs it."""
496
+ t = self.t
497
+ now = self.clock()
498
+ with self.engine.connect() as c:
499
+ rows = c.execute(select(t).where(t.c.state == "running")).all()
500
+ lost: list[int] = []
501
+ for r in rows:
502
+ mine = r.owner is not None and str(r.owner).rsplit(":", 1)[0] == self.host
503
+ dead = mine and r.owner_pid is not None and not oslib.pid_alive(r.owner_pid)
504
+ stale = r.heartbeat_at is None or now - float(r.heartbeat_at) > stale_s
505
+ if dead or stale:
506
+ self.fail(Job.from_row(r), WorkerLost(f"worker {r.owner} stopped while running it"))
507
+ lost.append(int(r.id))
508
+ return lost
509
+
510
+ def prune(self, *, older_than_s: float) -> int:
511
+ """Delete finished jobs that ended more than `older_than_s` ago; returns how many."""
512
+ t = self.t
513
+ cutoff = self.clock() - older_than_s
514
+ with self.engine.begin() as c:
515
+ done = c.execute(delete(t).where(and_(t.c.state.in_(sorted(FINISHED)), t.c.finished_at < cutoff)))
516
+ return int(done.rowcount)
517
+
518
+ def run(self, job: Job, handler: Handler) -> Job:
519
+ """Run `handler(job)` for a claimed job and record the outcome. Progress it reports is stored at most once a
520
+ second; a failure is retried or failed by the rules above."""
521
+ before = job.progress.done if job.progress is not None else 0.0
522
+ started = time.monotonic()
523
+ try:
524
+ with reporting(ProgressReporter(lambda p: self.report(job, p))):
525
+ result = handler(job)
526
+ except Exception as e:
527
+ now = job.progress.done if job.progress is not None else 0.0
528
+ self.fail(job, e, progressed=now > before)
529
+ return job
530
+ if job.cancel_requested:
531
+ self.finish(job, result) # stopped because it was asked to: cancelled, with what it had done
532
+ elif job.timeout_s is not None and time.monotonic() - started > job.timeout_s:
533
+ now = job.progress.done if job.progress is not None else 0.0
534
+ self.fail(job, TimeoutError(f"took longer than {job.timeout_s:g} s"), progressed=now > before)
535
+ elif job.stop_event.is_set():
536
+ self.release(job) # the worker is shutting down: the job runs again, from the start, next time
537
+ else:
538
+ self.finish(job, result)
539
+ return job
540
+
541
+ def release(self, job: Job) -> None:
542
+ """Put a running job back in the queue without counting an attempt (its worker is stopping)."""
543
+ t = self.t
544
+ with self.engine.begin() as c:
545
+ c.execute(
546
+ update(t)
547
+ .where(self._mine(job))
548
+ .values(
549
+ state="queued", owner=None, owner_pid=None, heartbeat_at=None, started_at=None, claim_token=None
550
+ )
551
+ )
552
+ job.state = "queued"
553
+
554
+ def step(self, handlers: Mapping[str, Handler]) -> Job | None:
555
+ """Claim one job of a kind in `handlers` and run it here, now: a deterministic run loop for tests and CLIs."""
556
+ job = self.claim(list(handlers))
557
+ return None if job is None else self.run(job, handlers[job.kind])
558
+
559
+
560
+ class Worker:
561
+ """Threads that claim and run jobs until stopped. Each running job gets a heartbeat every `heartbeat_s`, which also
562
+ picks up a cancel request and asks a job past its timeout to stop.
563
+
564
+ `isolate=True` (the default) runs jobs in job processes of their own (`tasks.child`), one per thread and kept
565
+ between jobs, so a quick job costs milliseconds: a cancel, a timeout or `stop` kills the process and every tool it
566
+ started at once (the next job gets a fresh one), a crash or a leak dies with it, and it dies with the server.
567
+ `max_jobs` replaces a process after that many jobs. The handlers must be module-level functions (the process
568
+ imports them by name); `isolate=False` runs them on this process's threads and asks them to stop through
569
+ `job.stopping`. `lower_priority=True` runs the job processes at idle CPU and disk priority."""
570
+
571
+ def __init__(
572
+ self,
573
+ queue: Queue,
574
+ handlers: Mapping[str, Handler],
575
+ *,
576
+ concurrency: int = 1,
577
+ poll_s: float = 1.0,
578
+ heartbeat_s: float = 10.0,
579
+ stale_s: float = 300.0,
580
+ isolate: bool = True,
581
+ lower_priority: bool = False,
582
+ max_jobs: int | None = None,
583
+ ) -> None:
584
+ self.queue = queue
585
+ self.handlers = dict(handlers)
586
+ self.isolate = isolate
587
+ self.lower_priority = lower_priority
588
+ self.max_jobs = max_jobs
589
+ self.slots: list[child.JobProcess] = [] # one job process per thread, kept between jobs
590
+ # Checked now, so a handler a child could not import fails at start-up, not in the first job.
591
+ self._specs = {k: child.handler_spec(fn) for k, fn in self.handlers.items()} if isolate else {}
592
+ self.concurrency = concurrency
593
+ self.poll_s = poll_s
594
+ self.heartbeat_s = heartbeat_s
595
+ self.stale_s = stale_s
596
+ self._stop = threading.Event()
597
+ self._threads: list[threading.Thread] = []
598
+ self._running: dict[int, Job] = {}
599
+ self._lock = threading.Lock()
600
+ self.ran = 0 # jobs this worker has run, failed ones included
601
+
602
+ def start(self) -> Worker:
603
+ self.queue.recover(stale_s=self.stale_s)
604
+ self._stop.clear()
605
+ self._threads = [
606
+ threading.Thread(target=self._loop, name=f"strata-worker-{i}", daemon=True) for i in range(self.concurrency)
607
+ ]
608
+ self._threads.append(threading.Thread(target=self._beat, name="strata-worker-heartbeat", daemon=True))
609
+ for th in self._threads:
610
+ th.start()
611
+ return self
612
+
613
+ def stop(self, timeout: float = 30.0) -> None:
614
+ """Ask running jobs to stop, then wait up to `timeout` for the threads. A job still running at the end is
615
+ recovered by the next `start` (its heartbeat goes stale, or its pid is gone)."""
616
+ self._stop.set()
617
+ with self._lock:
618
+ for job in self._running.values():
619
+ job.stop_event.set()
620
+ deadline = time.monotonic() + timeout
621
+ for th in self._threads:
622
+ th.join(max(deadline - time.monotonic(), 0))
623
+
624
+ def _loop(self) -> None:
625
+ slot = None
626
+ if self.isolate:
627
+ slot = child.JobProcess(self._process_spec(), max_jobs=self.max_jobs)
628
+ with self._lock:
629
+ self.slots.append(slot)
630
+ slot.ensure() # started now, so the first job does not wait for imports
631
+ try:
632
+ self._claim_and_run(slot)
633
+ finally:
634
+ if slot is not None:
635
+ slot.close()
636
+
637
+ def _claim_and_run(self, slot: child.JobProcess | None) -> None:
638
+ while not self._stop.is_set():
639
+ job = self.queue.claim(list(self.handlers))
640
+ if job is None:
641
+ self._stop.wait(self.poll_s)
642
+ continue
643
+ with self._lock:
644
+ self._running[job.id] = job
645
+ try:
646
+ if slot is not None:
647
+ self._run_isolated(job, slot)
648
+ else:
649
+ self.queue.run(job, self.handlers[job.kind])
650
+ except Exception as e: # the worker's own failure (a lost database, a bad answer): fail the job, go on
651
+ log.exception("job %s (%s) could not be run", job.id, job.kind)
652
+ with contextlib.suppress(Exception):
653
+ self.queue.fail(job, e)
654
+ if slot is not None:
655
+ slot.close()
656
+ finally:
657
+ with self._lock:
658
+ self._running.pop(job.id, None)
659
+ self.ran += 1
660
+
661
+ def _beat(self) -> None:
662
+ while not self._stop.wait(self.heartbeat_s):
663
+ with self._lock:
664
+ jobs = list(self._running.values())
665
+ for job in jobs:
666
+ with contextlib.suppress(Exception): # a missed beat is retried next time; recover() allows stale_s
667
+ self.queue.heartbeat(job)
668
+ if (
669
+ job.timeout_s is not None
670
+ and job.started_at is not None
671
+ and self.queue.clock() - job.started_at > job.timeout_s
672
+ ):
673
+ job.stop_event.set()
674
+
675
+ def _process_spec(self) -> Json:
676
+ q = self.queue
677
+ return {
678
+ "url": q.engine.url.render_as_string(hide_password=False),
679
+ "table": q.t.name,
680
+ "schema": q.t.schema,
681
+ "lower_priority": self.lower_priority,
682
+ }
683
+
684
+ def _run_isolated(self, job: Job, slot: child.JobProcess) -> None:
685
+ """Run a claimed job in this slot's job process and record what happened (see `tasks.child`)."""
686
+ q = self.queue
687
+ before = job.progress.done if job.progress is not None else 0.0
688
+ started = time.monotonic()
689
+
690
+ def should_stop() -> str:
691
+ if job.cancel_requested:
692
+ return "cancel"
693
+ if job.timeout_s is not None and time.monotonic() - started > job.timeout_s:
694
+ return "timeout"
695
+ return "stop" if job.stop_event.is_set() else ""
696
+
697
+ cmd = {"id": job.id, "token": job.token, "handler": self._specs[job.kind]}
698
+ outcome, ended = slot.run(cmd, should_stop)
699
+ if outcome is not None and outcome.get("gone"):
700
+ return # this attempt was recovered before the process got to it: nothing of it to record
701
+ fresh = q.get(job.id) # the process wrote progress to the row: read it back for `progressed`
702
+ if fresh is not None and fresh.token == job.token:
703
+ job.progress = fresh.progress
704
+ progressed = (job.progress.done if job.progress is not None else 0.0) > before
705
+ if ended == "cancel":
706
+ q.finish(job, None) # recorded as cancelled, since it was asked to stop
707
+ elif ended == "timeout":
708
+ q.fail(job, TimeoutError(f"took longer than {job.timeout_s:g} s"), progressed=progressed)
709
+ elif ended == "stop":
710
+ q.release(job) # the worker is shutting down: the job runs again, from the start, next time
711
+ elif outcome is None:
712
+ q.fail(job, WorkerLost("its job process exited before it finished"), progressed=progressed)
713
+ elif outcome.get("ok"):
714
+ q.finish(job, outcome.get("result"))
715
+ else:
716
+ q.fail(job, child.rebuild_error(outcome), progressed=progressed)