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,236 @@
1
+ """Queue jobs in long-lived processes of their own: what `Worker(isolate=True)` (the default) runs them in.
2
+
3
+ strata-listory runs each job in a child process in its own process group (its `start_job`, `watch_supervisor`,
4
+ `kill_job`), because a thread can only be asked to stop: a cancel, a timeout or a server shutdown then ends the job
5
+ and every tool it started (an ffmpeg, a model run) at once, a crash or a leak dies with the job instead of the server,
6
+ and the parent dying takes the job with it (the lifeline in `oslib.start_supervised`). This is that, for every app,
7
+ without listory's cost of a new interpreter per job: each `Worker` slot keeps one `JobProcess`, which imports the
8
+ app's handlers and opens its database once and then runs job after job, so a quick job costs a pipe round trip and
9
+ a read of its row. Only a kill (cancel, timeout, stop, or a job that took the process down) costs a new process,
10
+ and `max_jobs` replaces a process after that many jobs, for code that leaks.
11
+
12
+ The parent claims a job and writes `{"id", "token", "handler"}` as one line on the child's stdin; the child imports
13
+ the handler by name (`module:qualname`, so it must be a module-level function), runs it with progress going straight
14
+ to the job's row, and answers with one line: the result, or the error's type and message, which the parent rebuilds
15
+ so the retry rules (`tasks.retry`) treat it as they would in-process. The answers travel on the child's original
16
+ stdout; its fd 1 is pointed at stderr, so what handlers and their tools print goes to the server's log, not into
17
+ the protocol. stdin closing (the parent died) ends the process group at once, even mid-job.
18
+
19
+ In the child `job.stopping` stays False: the parent kills the process instead of asking."""
20
+
21
+ from __future__ import annotations
22
+
23
+ import builtins
24
+ import importlib
25
+ import json
26
+ import os
27
+ import queue as queue_mod
28
+ import subprocess
29
+ import sys
30
+ import threading
31
+ from collections.abc import Callable
32
+ from typing import IO, Any, cast
33
+
34
+ from sqlalchemy import MetaData, create_engine
35
+
36
+ from strata_python import oslib
37
+ from strata_python.tasks.progress import ProgressReporter, reporting
38
+ from strata_python.tasks.retry import RetryLater
39
+
40
+ ENV = "STRATA_JOB"
41
+ # Starts every answer. On Windows a tool the handler starts inherits the process's real stdout handle (moving fd 1
42
+ # does not move it), so other lines can reach the parent on the same pipe: those go on to the log.
43
+ MARK = "\x02strata-job:" # not \x1c-\x1e: str.splitlines breaks lines there
44
+ Json = dict[str, Any]
45
+
46
+
47
+ def handler_spec(fn: Any) -> str:
48
+ """The name a child imports `fn` by; ValueError when it cannot (a lambda, a closure, a method, `__main__`)."""
49
+ spec = f"{getattr(fn, '__module__', '')}:{getattr(fn, '__qualname__', '')}"
50
+ try:
51
+ found = resolve(spec)
52
+ except (ImportError, AttributeError, ValueError):
53
+ found = None
54
+ if found is not fn or spec.startswith("__main__:"):
55
+ raise ValueError(
56
+ f"handler {spec} cannot be imported by name in a job process: make it a module-level function, "
57
+ "or run this kind in the server's process with Worker(isolate=False)"
58
+ )
59
+ return spec
60
+
61
+
62
+ def resolve(spec: str) -> Any:
63
+ module, _, name = spec.partition(":")
64
+ if not module or not name or "<" in name:
65
+ raise ValueError(f"not a module:function name: {spec}")
66
+ obj: Any = importlib.import_module(module)
67
+ for part in name.split("."):
68
+ obj = getattr(obj, part)
69
+ return obj
70
+
71
+
72
+ def error_outcome(e: BaseException) -> Json:
73
+ """An error as the parent rebuilds it: its type's name, the builtin class it derives from, and its message."""
74
+ base = next(c for c in type(e).__mro__ if c.__module__ == "builtins")
75
+ message = str(e.args[0]) if len(e.args) == 1 else str(e) # KeyError('x') round-trips as 'x', not "'x'"
76
+ out: Json = {"ok": False, "type": type(e).__name__, "base": base.__name__, "message": message}
77
+ if isinstance(e, RetryLater):
78
+ out["retry_later"] = True
79
+ out["after_s"] = e.after_s
80
+ return out
81
+
82
+
83
+ def rebuild_error(d: Json) -> BaseException:
84
+ """The exception a child reported, as near the original as the parent can make it: the same builtin class (so a
85
+ TypeError is still a programming error and fails at once), under the same name (so the job's error reads the
86
+ same), else a RuntimeError of that name."""
87
+ message = str(d.get("message", ""))
88
+ if d.get("retry_later"):
89
+ return RetryLater(message, after_s=d.get("after_s"))
90
+ name = str(d.get("type") or "RuntimeError")
91
+ base = getattr(builtins, str(d.get("base")), None)
92
+ if not (isinstance(base, type) and issubclass(base, Exception)):
93
+ base = RuntimeError
94
+ for cls in (base if base.__name__ == name else type(name, (base,), {}), type(name, (RuntimeError,), {})):
95
+ try:
96
+ return cast("BaseException", cls(message))
97
+ except Exception: # noqa: S112 - a class whose constructor needs more arguments: try the next one
98
+ continue
99
+ return RuntimeError(message) # pragma: no cover - RuntimeError's subclass always takes a message
100
+
101
+
102
+ def route(line: str, answers: queue_mod.Queue[str | None], log: IO[str]) -> None:
103
+ """An answer to `answers`; anything else on the pipe (a tool's output) to `log`."""
104
+ if line.startswith(MARK):
105
+ answers.put(line[len(MARK) :])
106
+ else:
107
+ log.write(line)
108
+ log.flush()
109
+
110
+
111
+ def run_one(queue: Any, cmd: Json, handlers: dict[str, Any]) -> Json:
112
+ """Run the attempt `cmd` names and say what happened. `handlers` caches the imported functions."""
113
+ job = queue.get(int(cmd["id"]))
114
+ if job is None or job.state != "running" or job.token != cmd["token"]:
115
+ return {"gone": True} # recovered and claimed again before it got here: nothing to run or record
116
+ try:
117
+ name = str(cmd["handler"])
118
+ handler = handlers.get(name) or handlers.setdefault(name, resolve(name))
119
+ with reporting(ProgressReporter(lambda p: queue.report(job, p))):
120
+ result = handler(job)
121
+ return {"ok": True, "result": json.loads(json.dumps(result, default=str))}
122
+ except Exception as e: # the job's failure is its outcome; the parent decides what it means
123
+ return error_outcome(e)
124
+
125
+
126
+ def main(
127
+ commands: IO[str] | None = None,
128
+ replies: IO[str] | None = None,
129
+ on_eof: Callable[[], object] = oslib.terminate_own_group,
130
+ ) -> int:
131
+ """The job process: run each job named on stdin until it closes. `commands`, `replies` and `on_eof` are for
132
+ running it in a test's own process."""
133
+ spec = cast("Json", json.loads(os.environ.pop(ENV)))
134
+ os.environ.pop(oslib.SUPERVISED_ENV, None) # the lifeline is watched here; the job's own children are not
135
+ if replies is None:
136
+ # print() and the tools a handler runs write to the server's log, never into the answers
137
+ replies = os.fdopen(oslib.stdout_to_stderr(), "w", encoding="utf8", buffering=1)
138
+ # Commands arrive on a private fd: what the handler's tools inherit as stdin is empty (see stdin_from_devnull).
139
+ lines: IO[str] = open(oslib.stdin_from_devnull(), encoding="utf8") if commands is None else commands # noqa: SIM115
140
+ if spec.get("lower_priority"):
141
+ oslib.lower_priority(io=True)
142
+ from strata_python.tasks.queue import Queue, jobs_table # here, not at import: queue imports this module
143
+
144
+ engine = create_engine(str(spec["url"]))
145
+ if engine.dialect.name == "sqlite":
146
+ from strata_python.db.engine import sqlite_pragmas
147
+
148
+ sqlite_pragmas(engine)
149
+ queue = Queue(engine, jobs_table(MetaData(schema=spec.get("schema")), str(spec["table"])))
150
+ inbox: queue_mod.Queue[str | None] = queue_mod.Queue()
151
+
152
+ def read() -> None: # a thread, so the parent closing the pipe is seen while a job runs, not after it
153
+ for line in lines:
154
+ inbox.put(line)
155
+ inbox.put(None)
156
+ on_eof()
157
+
158
+ threading.Thread(target=read, name="strata-job-commands", daemon=True).start()
159
+ handlers: dict[str, Any] = {}
160
+ try:
161
+ while (line := inbox.get()) is not None:
162
+ replies.write(MARK + json.dumps(run_one(queue, cast("Json", json.loads(line)), handlers)) + "\n")
163
+ replies.flush()
164
+ finally:
165
+ engine.dispose()
166
+ return 0
167
+
168
+
169
+ class JobProcess:
170
+ """The parent's end of one job process: started on first use, reused for each job, replaced after a kill."""
171
+
172
+ def __init__(self, spec: Json, *, max_jobs: int | None = None) -> None:
173
+ self.spec = spec
174
+ self.max_jobs = max_jobs
175
+ self.proc: subprocess.Popen[str] | None = None
176
+ self.jobs = 0 # run by the current process
177
+ self.started = 0 # processes started, for the overhead test and the status page
178
+ self._answers: queue_mod.Queue[str | None] = queue_mod.Queue()
179
+
180
+ def ensure(self) -> subprocess.Popen[str]:
181
+ if self.proc is not None and self.proc.poll() is None and (self.max_jobs is None or self.jobs < self.max_jobs):
182
+ return self.proc
183
+ self.close()
184
+ env = {
185
+ **os.environ,
186
+ ENV: json.dumps(self.spec), # the environment, not argv: the URL can hold a password
187
+ "PYTHONPATH": os.pathsep.join(p for p in sys.path if p), # so it imports what this process can
188
+ }
189
+ proc = oslib.start_supervised([sys.executable, "-m", "strata_python.tasks.child"], env=env, text=True)
190
+ answers: queue_mod.Queue[str | None] = queue_mod.Queue()
191
+ out = proc.stdout
192
+ assert out is not None # noqa: S101 - start_supervised(text=True) pipes stdout
193
+
194
+ def read() -> None:
195
+ for line in out:
196
+ route(line, answers, sys.stderr)
197
+ answers.put(None)
198
+
199
+ threading.Thread(target=read, name="strata-job-answers", daemon=True).start()
200
+ self.proc, self._answers, self.jobs = proc, answers, 0
201
+ self.started += 1
202
+ return proc
203
+
204
+ def run(self, cmd: Json, should_stop: Callable[[], str]) -> tuple[Json | None, str]:
205
+ """Send one job and wait for its answer. Returns (answer, "") or, when `should_stop()` names a reason
206
+ first, (None, reason) with the process killed; (None, "") when the process died without answering."""
207
+ proc = self.ensure()
208
+ assert proc.stdin is not None # noqa: S101 - start_supervised pipes stdin
209
+ try:
210
+ proc.stdin.write(json.dumps(cmd) + "\n")
211
+ proc.stdin.flush()
212
+ except OSError:
213
+ self.close()
214
+ return None, ""
215
+ self.jobs += 1
216
+ while True:
217
+ if reason := should_stop():
218
+ self.close()
219
+ return None, reason
220
+ try:
221
+ line = self._answers.get(timeout=0.05)
222
+ except queue_mod.Empty:
223
+ continue
224
+ if line is None:
225
+ self.close() # it died mid-job; what it started goes with its group
226
+ return None, ""
227
+ return cast("Json", json.loads(line)), ""
228
+
229
+ def close(self) -> None:
230
+ if self.proc is not None:
231
+ oslib.kill_group(self.proc)
232
+ self.proc = None
233
+
234
+
235
+ if __name__ == "__main__":
236
+ sys.exit(main())
@@ -0,0 +1,146 @@
1
+ """One run at a time per key, in a background thread of this process: the "start a scan of this folder" button.
2
+
3
+ strata-stills kept a `jobs` dict, a `batches` dict and `fullres._jobs`, strata-360 fifteen `*_JOBS` dicts, each with
4
+ its own lock, its own "already running" check and its own stop flag. `SingleFlight` is that once: a second start of a
5
+ running key raises `Conflict` (which `web.add_error_handlers` answers as 409), `stop` asks the run to end at its next
6
+ check, and the last run of each key stays readable for the status endpoint.
7
+
8
+ SCANS: SingleFlight[str] = SingleFlight("scan")
9
+
10
+ def scan(flight: Flight[str]) -> int:
11
+ for i, f in enumerate(files):
12
+ if flight.stopping: return i
13
+ report_progress(i, len(files), f"{i} of {len(files)}")
14
+ return len(files)
15
+
16
+ SCANS.start(folder, scan) # in the route; Conflict -> 409 if that folder is already being scanned
17
+ SCANS.get(folder) # Flight: state, progress, result or error, times
18
+
19
+ The thread is a daemon: a run in progress dies with the server. Work that must outlive a restart is a `Detached`
20
+ process or a job on the durable queue."""
21
+
22
+ from __future__ import annotations
23
+
24
+ import datetime
25
+ import logging
26
+ import threading
27
+ from collections.abc import Callable, Hashable
28
+ from dataclasses import dataclass, field
29
+ from typing import Any, Generic, Literal, TypeVar
30
+
31
+ from strata_python.contracts import Progress
32
+ from strata_python.tasks.progress import ProgressReporter, reporting
33
+ from strata_python.tasks.retry import describe
34
+
35
+ K = TypeVar("K", bound=Hashable)
36
+ FlightState = Literal["running", "done", "failed", "stopped"]
37
+ log = logging.getLogger(__name__)
38
+
39
+
40
+ class Conflict(RuntimeError):
41
+ """That run is already going. `.payload` is what is running, for the 409's body."""
42
+
43
+ def __init__(self, message: str, payload: Any = None) -> None:
44
+ super().__init__(message)
45
+ self.payload = payload
46
+
47
+
48
+ def _now() -> datetime.datetime:
49
+ return datetime.datetime.now(datetime.UTC)
50
+
51
+
52
+ @dataclass
53
+ class Flight(Generic[K]):
54
+ """One run of a key. The run's function reads `.stopping`; everyone else reads the rest."""
55
+
56
+ key: K
57
+ name: str
58
+ state: FlightState = "running"
59
+ started_at: datetime.datetime = field(default_factory=_now)
60
+ finished_at: datetime.datetime | None = None
61
+ progress: Progress | None = None
62
+ result: Any = None
63
+ error: str | None = None
64
+ stop_event: threading.Event = field(default_factory=threading.Event, repr=False)
65
+ thread: threading.Thread | None = field(default=None, repr=False)
66
+
67
+ @property
68
+ def stopping(self) -> bool:
69
+ """Has someone asked this run to stop? Check it between steps and return."""
70
+ return self.stop_event.is_set()
71
+
72
+ @property
73
+ def running(self) -> bool:
74
+ return self.state == "running"
75
+
76
+ def join(self, timeout: float | None = None) -> bool:
77
+ """Wait for the run to end; True when it has."""
78
+ if self.thread is not None:
79
+ self.thread.join(timeout)
80
+ return not self.running
81
+
82
+ def as_json(self) -> dict[str, Any]:
83
+ """The run as a status endpoint answers it."""
84
+ return {
85
+ "key": self.key,
86
+ "state": self.state,
87
+ "started_at": self.started_at.isoformat(),
88
+ "finished_at": self.finished_at.isoformat() if self.finished_at else None,
89
+ "progress": None if self.progress is None else self.progress.model_dump(mode="json"),
90
+ "error": self.error,
91
+ }
92
+
93
+
94
+ class SingleFlight(Generic[K]):
95
+ def __init__(self, name: str) -> None:
96
+ self.name = name
97
+ self._flights: dict[K, Flight[K]] = {}
98
+ self._lock = threading.Lock()
99
+
100
+ def start(self, key: K, fn: Callable[[Flight[K]], Any]) -> Flight[K]:
101
+ """Run `fn(flight)` in a new thread unless `key` is already running (then `Conflict`). Progress reported
102
+ inside it (`report_progress`) lands on `flight.progress` at once: it is memory, not worth throttling."""
103
+ with self._lock:
104
+ old = self._flights.get(key)
105
+ if old is not None and old.running:
106
+ raise Conflict(f"{self.name} {key} is already running", old.as_json())
107
+ flight: Flight[K] = Flight(key, self.name)
108
+ self._flights[key] = flight
109
+
110
+ def write(p: Progress) -> None:
111
+ flight.progress = p
112
+
113
+ def run() -> None:
114
+ try:
115
+ with reporting(ProgressReporter(write, min_interval_s=0)):
116
+ flight.result = fn(flight)
117
+ flight.state = "stopped" if flight.stopping else "done"
118
+ except Exception as e: # the run's failure is its state; the server goes on
119
+ flight.error = describe(e)
120
+ flight.state = "failed"
121
+ log.exception("%s %s failed", self.name, key)
122
+ finally:
123
+ flight.finished_at = _now()
124
+
125
+ flight.thread = threading.Thread(target=run, name=f"{self.name}:{key}", daemon=True)
126
+ flight.thread.start()
127
+ return flight
128
+
129
+ def stop(self, key: K) -> bool:
130
+ """Ask `key`'s run to stop; True when one was running. It ends at its next check of `.stopping`."""
131
+ flight = self._flights.get(key)
132
+ if flight is None or not flight.running:
133
+ return False
134
+ flight.stop_event.set()
135
+ return True
136
+
137
+ def get(self, key: K) -> Flight[K] | None:
138
+ """The current or last run of `key`."""
139
+ return self._flights.get(key)
140
+
141
+ def running(self, key: K) -> bool:
142
+ flight = self._flights.get(key)
143
+ return flight is not None and flight.running
144
+
145
+ def all(self) -> dict[K, Flight[K]]:
146
+ return dict(self._flights)
@@ -0,0 +1,92 @@
1
+ """Progress from deep inside a task, without passing a callback down every call.
2
+
3
+ A handler calls `report_progress(done, total, text)` wherever it is; the task runner (a `SingleFlight`, the durable
4
+ queue, or the app's own loop) binds a `ProgressReporter` around the call, which writes at most once a second (listory's
5
+ rule: a progress write per page of a 900-page book would be most of the job's database traffic) but always writes a
6
+ stage change and the last step. Outside any runner `report_progress` does nothing, so the same function runs from a
7
+ test or a CLI.
8
+
9
+ with reporting(ProgressReporter(lambda p: store.set_progress(job_id, p))):
10
+ handler(...) # anywhere inside: report_progress(3, 40, "Page 3 of 40")
11
+ """
12
+
13
+ from __future__ import annotations
14
+
15
+ import contextlib
16
+ import contextvars
17
+ import datetime
18
+ import threading
19
+ import time
20
+ from collections.abc import Callable, Generator
21
+
22
+ from strata_python.contracts import Progress
23
+
24
+ _current: contextvars.ContextVar[ProgressReporter | None] = contextvars.ContextVar("strata_progress", default=None)
25
+
26
+
27
+ class ProgressReporter:
28
+ """Throttled progress writes. `write` gets a `Progress`; it is called from the task's own thread."""
29
+
30
+ def __init__(
31
+ self,
32
+ write: Callable[[Progress], None],
33
+ *,
34
+ min_interval_s: float = 1.0,
35
+ clock: Callable[[], float] = time.monotonic,
36
+ now: Callable[[], datetime.datetime] = lambda: datetime.datetime.now(datetime.UTC),
37
+ ) -> None:
38
+ self._write = write
39
+ self.min_interval_s = min_interval_s
40
+ self._clock = clock
41
+ self._now = now
42
+ self._last_at: float | None = None
43
+ self._last_stage: str | None = None
44
+ self._pending: Progress | None = None
45
+ self.latest: Progress | None = None
46
+ self._lock = threading.Lock()
47
+
48
+ def report(self, done: float, total: float | None = None, text: str = "", stage: str | None = None) -> bool:
49
+ """Record a step; True when it was written now. A step that is not written is kept, and `flush` writes it."""
50
+ p = Progress(done=done, total=total, text=text, stage=stage, at=self._now())
51
+ with self._lock:
52
+ self.latest = p
53
+ t = self._clock()
54
+ due = (
55
+ self._last_at is None
56
+ or t - self._last_at >= self.min_interval_s
57
+ or stage != self._last_stage
58
+ or (total is not None and done >= total)
59
+ )
60
+ if not due:
61
+ self._pending = p
62
+ return False
63
+ self._last_at, self._last_stage, self._pending = t, stage, None
64
+ self._write(p)
65
+ return True
66
+
67
+ def flush(self) -> None:
68
+ """Write the last step if it was held back (call when the task ends, so its final state is stored)."""
69
+ with self._lock:
70
+ p, self._pending = self._pending, None
71
+ if p is not None:
72
+ self._last_at = self._clock()
73
+ if p is not None:
74
+ self._write(p)
75
+
76
+
77
+ @contextlib.contextmanager
78
+ def reporting(reporter: ProgressReporter) -> Generator[ProgressReporter]:
79
+ """Bind `reporter` for the block (this thread and context only), flushing it at the end."""
80
+ token = _current.set(reporter)
81
+ try:
82
+ yield reporter
83
+ finally:
84
+ _current.reset(token)
85
+ reporter.flush()
86
+
87
+
88
+ def report_progress(done: float, total: float | None = None, text: str = "", stage: str | None = None) -> None:
89
+ """Report progress to the runner of the current task; nothing happens outside one."""
90
+ r = _current.get()
91
+ if r is not None:
92
+ r.report(done, total, text, stage)