strata-python 0.2.0__py3-none-any.whl → 0.2.2__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.
Files changed (36) hide show
  1. strata_python/__init__.py +2 -1
  2. strata_python/cli.py +99 -20
  3. strata_python/clients/__init__.py +2 -0
  4. strata_python/clients/models.py +780 -0
  5. strata_python/db/__init__.py +116 -0
  6. strata_python/db/__main__.py +5 -0
  7. strata_python/db/_alembic/env.py +24 -0
  8. strata_python/db/_alembic/script.py.mako +28 -0
  9. strata_python/db/cli.py +199 -0
  10. strata_python/db/config.py +85 -0
  11. strata_python/db/engine.py +53 -0
  12. strata_python/db/guard.py +159 -0
  13. strata_python/db/migrations.py +243 -0
  14. strata_python/db/models.py +62 -0
  15. strata_python/db/project.py +98 -0
  16. strata_python/db/pytest_plugin.py +205 -0
  17. strata_python/db/scratch.py +143 -0
  18. strata_python/db/settings.py +63 -0
  19. strata_python/db/testing.py +43 -0
  20. strata_python/db/testserver.py +205 -0
  21. strata_python/oslib.py +44 -5
  22. strata_python/pages/__init__.py +21 -0
  23. strata_python/pages/model.py +241 -0
  24. strata_python/pages/render.py +273 -0
  25. strata_python/public_check.py +54 -8
  26. strata_python/pytest_plugin.py +70 -1
  27. strata_python/settings.py +243 -42
  28. strata_python/testing.py +257 -0
  29. strata_python/web.py +15 -6
  30. strata_python-0.2.2.dist-info/METADATA +334 -0
  31. strata_python-0.2.2.dist-info/RECORD +38 -0
  32. {strata_python-0.2.0.dist-info → strata_python-0.2.2.dist-info}/entry_points.txt +2 -0
  33. strata_python-0.2.0.dist-info/METADATA +0 -82
  34. strata_python-0.2.0.dist-info/RECORD +0 -16
  35. {strata_python-0.2.0.dist-info → strata_python-0.2.2.dist-info}/WHEEL +0 -0
  36. {strata_python-0.2.0.dist-info → strata_python-0.2.2.dist-info}/licenses/LICENSE +0 -0
@@ -0,0 +1,257 @@
1
+ """Shared test helpers for the strata apps: scripted stand-ins for the outside world and CLI runners.
2
+
3
+ Every app carried its own `tests/utils/fakes.py` (five drifted copies of the same code) and the same `cli` fixtures; they
4
+ live here once. The pytest plugin exposes the fakes as fixtures (`fake_urlopen`, `fake_popen`, `fake_run`, `no_sleep`),
5
+ so most tests never import this module; import it for `http_error`, `FakeResponse` and the CLI runners.
6
+
7
+ The fakes are a last resort for quick unit tests of many cases at a true external edge (a web API, an external
8
+ program). Prefer the real thing: the `http_server` fixture for HTTP, the actual program for subprocesses (AGENTS.md,
9
+ Testing policy).
10
+
11
+ FakeResponse what `urlopen` returns: `.read()`, `.status`, `.headers`, a context manager
12
+ FakeUrlopen a FIFO of scripted replies (bodies, FakeResponses, exceptions); `.calls` records each request
13
+ http_error an `HTTPError` with a JSON (or bytes) body, to queue as a reply
14
+ FakePopen `subprocess.Popen` that starts nothing; `.instances` lists every one made, `.returncode` is settable
15
+ FakeRun `subprocess.run` / `check_output`; `.returns` maps a command-line substring to stdout, `.code` fails
16
+ Sleeper `time.sleep` that returns at once and records `.delays`
17
+ run_cli an argparse `main(argv)` in this process -> CliResult; run_module the same as a real `python -m`
18
+ """
19
+
20
+ from __future__ import annotations
21
+
22
+ import contextlib
23
+ import io
24
+ import json
25
+ import os
26
+ import subprocess
27
+ import sys
28
+ import urllib.error
29
+ import urllib.request
30
+ from collections.abc import Callable, Mapping, Sequence
31
+ from dataclasses import dataclass, field
32
+ from email.message import Message
33
+ from pathlib import Path
34
+ from typing import Any, ClassVar
35
+
36
+ Body = bytes | str | Any # bytes and str are sent as they are; anything else as JSON
37
+
38
+
39
+ def _encode(body: Body) -> bytes:
40
+ if isinstance(body, bytes):
41
+ return body
42
+ if isinstance(body, str):
43
+ return body.encode()
44
+ return json.dumps(body).encode()
45
+
46
+
47
+ def _maybe_json(data: object) -> object:
48
+ """A request body as the test wants to assert on it: parsed JSON when it is JSON, else as sent."""
49
+ if not isinstance(data, (bytes, str)):
50
+ return data
51
+ try:
52
+ return json.loads(data)
53
+ except ValueError:
54
+ return data
55
+
56
+
57
+ class FakeResponse:
58
+ """What `urllib.request.urlopen` returns. `body` is bytes, str or anything JSON-serialisable."""
59
+
60
+ def __init__(self, body: Body = b"", status: int = 200, headers: Mapping[str, str] | None = None) -> None:
61
+ self.body = _encode(body)
62
+ self._stream = io.BytesIO(
63
+ self.body
64
+ ) # reads consume it, so a chunked read loop reaches EOF as on a real response
65
+ self.status = status
66
+ self.headers: dict[str, str] = dict(headers or {})
67
+
68
+ def read(self, n: int = -1) -> bytes:
69
+ return self._stream.read(n)
70
+
71
+ def getcode(self) -> int:
72
+ return self.status
73
+
74
+ def __enter__(self) -> FakeResponse:
75
+ return self
76
+
77
+ def __exit__(self, *exc: object) -> bool:
78
+ return False
79
+
80
+
81
+ def http_error(code: int, body: Body = None, url: str = "http://fake") -> urllib.error.HTTPError:
82
+ """An `HTTPError` whose `.read()` gives `body` (JSON unless bytes; `{}` when None). Queue it as a reply."""
83
+ return urllib.error.HTTPError(url, code, "error", Message(), io.BytesIO(_encode({} if body is None else body)))
84
+
85
+
86
+ @dataclass
87
+ class Call:
88
+ """One request `FakeUrlopen` was asked to make. `call["url"]` works too, as in the apps' old copies."""
89
+
90
+ url: str
91
+ method: str | None
92
+ timeout: float | None
93
+ headers: dict[str, str] # names lower-cased
94
+ body: object # parsed JSON when it is JSON
95
+
96
+ def __getitem__(self, key: str) -> object:
97
+ return getattr(self, key)
98
+
99
+
100
+ class FakeUrlopen:
101
+ """A scripted `urlopen`. Queue replies in order, run the code, then assert on `.calls`:
102
+
103
+ fake_urlopen.reply(http_error(429), {"ok": 1}) # the retry sees a 429, then a body
104
+
105
+ A reply is a body, a `FakeResponse` or an exception (raised). A request with nothing queued fails the test rather
106
+ than reaching the network."""
107
+
108
+ def __init__(self) -> None:
109
+ self.replies: list[object] = []
110
+ self.calls: list[Call] = []
111
+
112
+ def reply(self, *items: object) -> FakeUrlopen:
113
+ self.replies.extend(items)
114
+ return self
115
+
116
+ def __call__(
117
+ self, req: str | urllib.request.Request, data: bytes | None = None, timeout: float | None = None, **kw: object
118
+ ) -> FakeResponse:
119
+ if isinstance(req, str):
120
+ call = Call(req, None, timeout, {}, _maybe_json(data))
121
+ else:
122
+ headers = {k.lower(): v for k, v in req.header_items()}
123
+ call = Call(req.full_url, req.get_method(), timeout, headers, _maybe_json(req.data))
124
+ self.calls.append(call)
125
+ if not self.replies:
126
+ raise AssertionError(f"unexpected HTTP request to {call.url} (no reply queued)")
127
+ reply = self.replies.pop(0)
128
+ if isinstance(reply, BaseException):
129
+ raise reply
130
+ return reply if isinstance(reply, FakeResponse) else FakeResponse(reply)
131
+
132
+
133
+ class FakePopen:
134
+ """Stands in for `subprocess.Popen`: records the command and keyword arguments, never starts anything.
135
+
136
+ The `fake_popen` fixture hands each test its own subclass, so `.instances` starts empty and never leaks between
137
+ tests. A test finishes a process by setting `fake_popen.instances[-1].returncode = 0`. File objects passed as
138
+ stdin/stdout/stderr are recorded by name, not kept: holding them open would stop a test deleting its folder on
139
+ Windows."""
140
+
141
+ instances: ClassVar[list[FakePopen]] = []
142
+
143
+ def __init__(self, cmd: Sequence[object], **kw: object) -> None:
144
+ self.cmd = [str(c) for c in cmd]
145
+ self.kw = {k: getattr(v, "name", v) if hasattr(v, "fileno") else v for k, v in kw.items()}
146
+ self.pid = 4242 + len(type(self).instances)
147
+ self.returncode: int | None = None
148
+ type(self).instances.append(self)
149
+
150
+ @classmethod
151
+ def fresh(cls) -> type[FakePopen]:
152
+ """A subclass with its own empty `.instances`."""
153
+ return type("FakePopen", (cls,), {"instances": []})
154
+
155
+ def poll(self) -> int | None:
156
+ return self.returncode
157
+
158
+ def wait(self, timeout: float | None = None) -> int:
159
+ return 0 if self.returncode is None else self.returncode
160
+
161
+ def terminate(self) -> None:
162
+ self.returncode = -15
163
+
164
+ def kill(self) -> None:
165
+ self.returncode = -9
166
+
167
+ def __enter__(self) -> FakePopen:
168
+ return self
169
+
170
+ def __exit__(self, *exc: object) -> bool:
171
+ return False
172
+
173
+
174
+ class FakeRun:
175
+ """Stands in for `subprocess.run` and `check_output`: `.calls` holds each command as a list of strings;
176
+ `.returns["ffprobe"] = b"..."` gives the stdout of any command whose line contains that text (default `b""`,
177
+ returned as the test set it, bytes or str); `.code = 1` makes every command fail (raising only with `check=True`,
178
+ as `subprocess.run` does; `check_output` always checks)."""
179
+
180
+ def __init__(self) -> None:
181
+ self.calls: list[list[str]] = []
182
+ self.returns: dict[str, bytes | str] = {}
183
+ self.code = 0
184
+
185
+ def _out(self, cmd: Sequence[object]) -> bytes | str:
186
+ line = " ".join(map(str, cmd))
187
+ return next((v for k, v in self.returns.items() if k in line), b"")
188
+
189
+ def __call__(self, cmd: Sequence[object], *a: object, **kw: object) -> subprocess.CompletedProcess[Any]:
190
+ self.calls.append([str(c) for c in cmd])
191
+ out = self._out(cmd)
192
+ if self.code and kw.get("check"):
193
+ raise subprocess.CalledProcessError(self.code, self.calls[-1], out)
194
+ return subprocess.CompletedProcess(self.calls[-1], self.code, out, b"")
195
+
196
+ def check_output(self, cmd: Sequence[object], *a: object, **kw: object) -> bytes | str:
197
+ self.calls.append([str(c) for c in cmd])
198
+ out = self._out(cmd)
199
+ if self.code:
200
+ raise subprocess.CalledProcessError(self.code, self.calls[-1], out)
201
+ return out
202
+
203
+
204
+ @dataclass
205
+ class Sleeper:
206
+ """`time.sleep` that returns at once; `.delays` records what was asked, so a test can assert on a backoff."""
207
+
208
+ delays: list[float] = field(default_factory=lambda: [])
209
+
210
+ def __call__(self, seconds: float) -> None:
211
+ self.delays.append(seconds)
212
+
213
+
214
+ @dataclass
215
+ class CliResult:
216
+ stdout: str
217
+ stderr: str
218
+ code: int
219
+
220
+ @property
221
+ def out(self) -> str:
222
+ return self.stdout + self.stderr
223
+
224
+
225
+ def run_cli(main: Callable[[list[str]], int | None], *args: object, check: bool = True) -> CliResult:
226
+ """Run an argparse-style `main(argv)` in this process, capturing its output and exit code (a `SystemExit` counts).
227
+ Raises AssertionError with the output on a non-zero exit unless `check=False`."""
228
+ out, err = io.StringIO(), io.StringIO()
229
+ code = 0
230
+ with contextlib.redirect_stdout(out), contextlib.redirect_stderr(err):
231
+ try:
232
+ code = main([str(a) for a in args]) or 0
233
+ except SystemExit as e:
234
+ code = e.code if isinstance(e.code, int) else (1 if e.code else 0)
235
+ if isinstance(e.code, str):
236
+ err.write(e.code + "\n")
237
+ result = CliResult(out.getvalue(), err.getvalue(), code)
238
+ if check and code:
239
+ raise AssertionError(f"{' '.join(map(str, args))} exited {code}:\n{result.out}")
240
+ return result
241
+
242
+
243
+ def run_module(
244
+ module: str, *args: object, src: str | Path | None = None, check: bool = True, timeout: float = 300
245
+ ) -> CliResult:
246
+ """The same through a real `python -m module` process, for entry-point smoke tests and anything that must not
247
+ share this process's state. `src` is put on PYTHONPATH (an app's `src` folder when it is not installed)."""
248
+ env = dict(os.environ, PYTHONWARNINGS="ignore")
249
+ if src is not None:
250
+ env["PYTHONPATH"] = os.pathsep.join([str(src), *filter(None, [os.environ.get("PYTHONPATH")])])
251
+ p = subprocess.run( # noqa: S603 - the interpreter running the tests, on the app's own module
252
+ [sys.executable, "-m", module, *map(str, args)], capture_output=True, text=True, env=env, timeout=timeout
253
+ )
254
+ result = CliResult(p.stdout, p.stderr, p.returncode)
255
+ if check and p.returncode:
256
+ raise AssertionError(f"python -m {module} exited {p.returncode}:\n{result.out}")
257
+ return result
strata_python/web.py CHANGED
@@ -10,7 +10,7 @@ assets are relative (Vite `base: './'`)."""
10
10
 
11
11
  import argparse
12
12
  import os
13
- from collections.abc import Sequence
13
+ from collections.abc import Callable, Mapping, Sequence
14
14
 
15
15
  import uvicorn
16
16
  from fastapi import FastAPI, HTTPException
@@ -36,8 +36,17 @@ def static_file(static: str, path: str) -> str | None:
36
36
  return full if os.path.dirname(full) == root and os.path.isfile(full) else None
37
37
 
38
38
 
39
- def base_app(title: str, version: str, settings: Settings | None = None, *, docs: bool = True) -> FastAPI:
40
- """A FastAPI app with `GET /api/health` and, given settings, `GET`/`PUT /api/settings` (a PUT with an unknown key or a value that fails validation is a 400 and changes nothing)."""
39
+ def base_app(
40
+ title: str,
41
+ version: str,
42
+ settings: Settings | None = None,
43
+ *,
44
+ docs: bool = True,
45
+ health: Callable[[], Mapping[str, object]] | None = None,
46
+ ) -> FastAPI:
47
+ """A FastAPI app with `GET /api/health` and, given settings, `GET`/`PUT /api/settings` (a PUT with an unknown key or a value that fails validation is a 400 and changes nothing).
48
+ `health` adds the app's own fields to the health response after `ok` and `version` (strata-models' `gpu`); it is called on every request, so keep it cheap,
49
+ and it may set `ok` to false for a service that is up but cannot do its work."""
41
50
  app = FastAPI(
42
51
  title=title,
43
52
  docs_url="/api/docs" if docs else None,
@@ -46,16 +55,16 @@ def base_app(title: str, version: str, settings: Settings | None = None, *, docs
46
55
 
47
56
  @app.get("/api/health")
48
57
  def get_health() -> dict[str, object]: # pyright: ignore[reportUnusedFunction]
49
- return {"ok": True, "version": version}
58
+ return {"ok": True, "version": version, **(health() if health else {})}
50
59
 
51
60
  if settings is not None:
52
61
 
53
62
  @app.get("/api/settings")
54
- def get_settings() -> dict[str, str]: # pyright: ignore[reportUnusedFunction]
63
+ def get_settings() -> dict[str, str | list[str]]: # pyright: ignore[reportUnusedFunction]
55
64
  return settings.all()
56
65
 
57
66
  @app.put("/api/settings")
58
- def put_settings(changes: dict[str, str | None]) -> dict[str, str]: # pyright: ignore[reportUnusedFunction]
67
+ def put_settings(changes: dict[str, str | list[str] | None]) -> dict[str, str | list[str]]: # pyright: ignore[reportUnusedFunction]
59
68
  try:
60
69
  settings.save(changes)
61
70
  except (KeyError, ValueError) as e:
@@ -0,0 +1,334 @@
1
+ Metadata-Version: 2.5
2
+ Name: strata-python
3
+ Version: 0.2.2
4
+ Summary: Common code for Python web server apps: OS helpers, settings, FastAPI serving, CLI commands, test fixtures and the strata-check gate
5
+ Project-URL: Homepage, https://github.com/jburnhams/strata-python
6
+ Project-URL: Source, https://github.com/jburnhams/strata-python
7
+ Project-URL: Changelog, https://github.com/jburnhams/strata-python/blob/main/CHANGELOG.md
8
+ Author: jburnhams
9
+ License-Expression: MIT
10
+ License-File: LICENSE
11
+ Keywords: cli,fastapi,pytest,settings
12
+ Classifier: Development Status :: 4 - Beta
13
+ Classifier: Framework :: FastAPI
14
+ Classifier: Framework :: Pytest
15
+ Classifier: Operating System :: OS Independent
16
+ Classifier: Programming Language :: Python :: 3
17
+ Classifier: Programming Language :: Python :: 3.11
18
+ Classifier: Programming Language :: Python :: 3.12
19
+ Classifier: Programming Language :: Python :: 3.13
20
+ Classifier: Typing :: Typed
21
+ Requires-Python: >=3.11
22
+ Requires-Dist: fastapi<1,>=0.115
23
+ Requires-Dist: pydantic<3,>=2.9
24
+ Requires-Dist: pytest<10,>=8
25
+ Requires-Dist: tzdata; sys_platform == 'win32'
26
+ Requires-Dist: uvicorn<1,>=0.32
27
+ Provides-Extra: db
28
+ Requires-Dist: alembic<2,>=1.13; extra == 'db'
29
+ Requires-Dist: psycopg[binary]<4,>=3.2; extra == 'db'
30
+ Requires-Dist: sqlalchemy<3,>=2.0; extra == 'db'
31
+ Provides-Extra: dev
32
+ Requires-Dist: httpx<1,>=0.27; extra == 'dev'
33
+ Requires-Dist: pyright<2,>=1.1.400; extra == 'dev'
34
+ Requires-Dist: pytest-cov<8,>=5; extra == 'dev'
35
+ Requires-Dist: pytest-randomly<6,>=3; extra == 'dev'
36
+ Requires-Dist: pytest-timeout<3,>=2; extra == 'dev'
37
+ Requires-Dist: pytest-xdist<4,>=3; extra == 'dev'
38
+ Requires-Dist: ruff<0.18,>=0.17; extra == 'dev'
39
+ Requires-Dist: ty<0.1,>=0.0.99; extra == 'dev'
40
+ Provides-Extra: pdf
41
+ Requires-Dist: pillow<14,>=10; extra == 'pdf'
42
+ Requires-Dist: pypdfium2<6,>=4.30; extra == 'pdf'
43
+ Requires-Dist: reportlab<6,>=4.2; extra == 'pdf'
44
+ Description-Content-Type: text/markdown
45
+
46
+ # strata-python
47
+
48
+ Common code for the strata Python web server apps (FastAPI + CLI), the Python counterpart of [strata-react](https://github.com/jburnhams/strata-react). Every app made from [python-app-template](https://github.com/jburnhams/python-app-template) used to carry its own drifting copy of these modules; they live here once. It is opinionated and built for those apps rather than as a general-purpose library, but it is public, MIT-licensed and on PyPI.
49
+
50
+ | Module | What it gives an app |
51
+ |---|---|
52
+ | `strata_python.oslib` | Cross-platform file locks, process liveness (`pid_alive`), `kill_tree`, `lower_priority`, `venv_python`, `cli_command(module)` |
53
+ | `strata_python.settings` | `Settings` / `Setting` / `ListSetting`: one JSON file in `~/.<app>` with `<APP>_*` environment overrides, validation (`absolute_path`, `non_empty`, `number_between`, `whole_between`, `iso_date`, `boolean`), typed getters, atomic saves, and `bind(store)` to keep them elsewhere (`strata_python.db.settings.TableStore`) |
54
+ | `strata_python.web` | `base_app` (health with the app's own fields + settings routes), `add_web` (built web app or stand-in page at every non-API path), `with_base` (reverse-proxy-safe `<base href>`), `static_file` (path-safe), `serve` |
55
+ | `strata_python.cli` | `add_doctor` (imports, labels, optional modules and the app's own `Check`s), `add_set`, `add_serve` for the app's argparse subcommands |
56
+ | `strata_python.clients.models` | The strata-models client, standard library only: `run`, `submit`, `wait`, `role_model`, `gpu_lease`, a shortcut for every role the service runs (`faces`, `face_kind`, `transcribe`, `ocr`, `speak`, `denoise_audio`, `audio_quality`, `generate_image`, `embed`, `enhance_video`, and `ask` for the language models) and a typed result for each |
57
+ | `strata_python.http_server` / `live` | A real scripted HTTP server and a real uvicorn server on loopback, for tests that make actual requests |
58
+ | pytest plugin | Loaded automatically: hermetic home and data folders (`strata_env` adds the app's own variables), a no-network guard, `http_server` and `live_app`, the `fake_urlopen`, `fake_popen`, `fake_run` and `no_sleep` fixtures, and the `integration` marker on everything under `tests/integration` |
59
+ | `strata_python.testing` | The fakes behind those fixtures (`FakeResponse`, `http_error`, `FakeUrlopen`, `FakePopen`, `FakeRun`, `Sleeper`) and the CLI runners `run_cli(main, *args)` and `run_module("myapp", *args, src=...)` |
60
+ | `strata_python.db` (extra `[db]`) | The shared database: `connect("myapp")` (the app's schema of one shared Postgres, or a SQLite path), a declarative base with the shared `NAMING_CONVENTION` for typed models, Alembic migrations with no per-app `env.py`, the live-database guard, the `strata-db` command, and the `db_*` fixtures (SQLite by default, a throwaway Postgres with `--pg`) |
61
+ | `strata_python.pages` (extra `[pdf]`) | A scanned page described as blocks, lines, styled spans and figures in scan pixels, drawn as a PDF with real embedded fonts (`render`), and read back as pixels at the scan's dpi (`rasterise`) and as text (`read_text`): for rebuilding scanned books, and for scoring a rebuild with the renderer that prints it |
62
+ | `strata-check` | The one gate: lockfile, ruff, `ruff format`, pyright strict, ty, unit tests with coverage |
63
+ | `strata-public-check` | Fails on email addresses, private IPv4 addresses, home-folder paths and the regexes in `STRATA_PUBLIC_DENY` in a tree, sdist or wheel; run before anything public is published. Silence a false positive with `[tool.strata-public-check] exclude = ["web/package-lock.json"]` (or `--exclude`), or `strata-public-check: ignore` on the line (never applies to `STRATA_PUBLIC_DENY`) |
64
+
65
+ ## Move an app onto it
66
+
67
+ The goal: an app keeps only its plumbing and business logic, and everything else comes from here. Work through the steps in order, one commit each, running `scripts/check` after every step. Each step says what to delete, so the app gets smaller as it goes. What changed in each release, and how to upgrade, is in [CHANGELOG.md](CHANGELOG.md).
68
+
69
+ ### 1. Depend on the release
70
+
71
+ ```toml
72
+ # pyproject.toml
73
+ [project]
74
+ dependencies = [
75
+ "strata-python>=0.2,<0.3", # brings FastAPI, uvicorn, pydantic and pytest; while 0.x, cap below the next minor
76
+ # ... only what is the app's own: torch, opencv, yt-dlp ...
77
+ ]
78
+
79
+ [dependency-groups]
80
+ dev = ["strata-python[dev]"] # ruff, pyright, ty, httpx and the pytest plugins, at the versions strata-check expects
81
+ ```
82
+
83
+ Delete from the app's own lists everything strata-python already brings (fastapi, uvicorn, pydantic, pytest, ruff, pyright, ty, pytest-cov, pytest-xdist, pytest-randomly, pytest-timeout, httpx) and any `[tool.uv.sources] strata-python = { git = ... }` entry, then run `uv lock`. To try an unreleased commit, put a `git` source with `rev = "<sha>"` back for the moment.
84
+
85
+ The shared versions are decided here: strata-python sets a minimum (what its CI tested) and a cap (the next release that may break) for each, and its own dependabot keeps them current. Each app still has its own `uv.lock`, so one dependabot PR a week per app is the floor; make it one, not one per package:
86
+
87
+ ```yaml
88
+ # .github/dependabot.yml in the app
89
+ version: 2
90
+ updates:
91
+ - package-ecosystem: uv
92
+ directory: /
93
+ schedule: { interval: weekly }
94
+ groups: { python: { patterns: ["*"] } } # strata-python and everything else in one PR
95
+ - package-ecosystem: github-actions
96
+ directory: /
97
+ schedule: { interval: monthly }
98
+ groups: { actions: { patterns: ["*"] } }
99
+ ```
100
+
101
+ Security updates still arrive on their own as soon as they are published; keep them on.
102
+
103
+ ### 2. The gate
104
+
105
+ `scripts/check` becomes one line, and the app's own `scripts/check.py` goes:
106
+
107
+ ```bash
108
+ #!/bin/bash
109
+ DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
110
+ cd "$DIR/.." && exec uv run --locked strata-check "$@"
111
+ ```
112
+
113
+ It runs the lockfile check, ruff, `ruff format`, pyright strict, ty and the unit tests with coverage. `--fast` skips the tests and `--fix` applies safe ruff fixes. An optional `[tool.strata-check]` sets `paths` (default `src`, `tests`, `scripts`) and `tests` (default `tests/unit`). CI calls the same script. A public app also runs `uv run strata-public-check . dist/*` in CI, with `STRATA_PUBLIC_DENY` as a repository secret.
114
+
115
+ ### 3. Settings
116
+
117
+ Replace the app's `settings.py` (its key list, getters, file handling and environment lookups) with a declaration:
118
+
119
+ ```python
120
+ from strata_python.settings import ListSetting, Setting, Settings, absolute_path, non_empty, whole_between
121
+
122
+ SETTINGS = Settings(
123
+ "myapp", # ~/.myapp/settings.json, moved with MYAPP_HOME
124
+ [
125
+ Setting("data_dir", default=lambda: "/srv/myapp", normalise=absolute_path),
126
+ Setting("greeting", default="Hello", normalise=non_empty),
127
+ Setting("workers", default="2", normalise=whole_between(1, 16)),
128
+ ListSetting("source_roots", item=absolute_path, env="MYAPP_SOURCES"), # MYAPP_SOURCES split on os.pathsep
129
+ ],
130
+ prefix="MYAPP", # only if the app already runs with other variable names
131
+ )
132
+
133
+ SETTINGS.get("greeting") # MYAPP_GREETING, else the file, else the default
134
+ SETTINGS.save({"greeting": "Hi"}) # validated and written atomically; None resets to the default
135
+ SETTINGS.folder("data_dir") # the value as a folder, created if missing
136
+ ```
137
+
138
+ Values are canonical strings, and lists of them. Normalisers for the common kinds give one spelling each: `number_between(lo, hi)`, `whole_between(lo, hi)`, `iso_date(allow_blank=True)` and `boolean`, read back with `get_float`, `get_int` and `get_bool`. A `ListSetting` is a JSON list in the file (a string there is split, so a hand edit works), split on `sep` in the environment (`os.pathsep` by default, `sep=","` for names), with `item` normalising each entry. `get_list` returns it, and `all()` and `GET /api/settings` return it as JSON. `get` and `set` show it joined, and `save` takes a list or a joined string.
139
+
140
+ To keep the values in the app's database instead of the file, add the table to the models and bind at service start, after the migrations. The file's values are copied in the first time, and the CLI and tests without a database keep using the file:
141
+
142
+ ```python
143
+ from strata_python.db.settings import TableStore, settings_table
144
+
145
+ SETTINGS_TABLE = settings_table(Base.metadata) # in models.py, so the migrations create it
146
+ SETTINGS.bind(TableStore(engine, SETTINGS_TABLE)) # any object with load() and update(changes) is a store
147
+ ```
148
+
149
+ ### 4. The server
150
+
151
+ ```python
152
+ from strata_python import web
153
+
154
+
155
+ def create_app():
156
+ app = web.base_app("myapp", __version__, SETTINGS) # GET /api/health, GET and PUT /api/settings, /api/docs
157
+ # ... the app's own /api routes ...
158
+ web.add_web(app, STATIC_DIR, LANDING_HTML) # last: /assets, top-level files, and index.html at every other path
159
+ return app
160
+ ```
161
+
162
+ Delete the app's own `/api/health` and `/api/settings` routes, its `/assets` mount, SPA fallback, `with_base` and `static_file` copies and its `uvicorn.run` wrapper. `web.serve(app, argv, default_port=...)` replaces the last of these. For health fields of the app's own, pass `health=lambda: {"gpu": gpu_name()}`: they follow `ok` and `version`, and may set `ok` to false. It runs on every request, so keep it cheap.
163
+
164
+ ### 5. The CLI
165
+
166
+ ```python
167
+ import argparse
168
+
169
+ from strata_python import cli, web
170
+
171
+
172
+ def main(argv=None):
173
+ parser = argparse.ArgumentParser(prog="myapp")
174
+ sub = parser.add_subparsers(dest="cmd", required=True)
175
+ cli.add_doctor(sub, "myapp", __version__, ("fastapi", "uvicorn")) # versions, and whether each import works
176
+ cli.add_set(sub, SETTINGS) # myapp set KEY [VALUE|default]
177
+ cli.add_serve(
178
+ sub, lambda host, port: web.serve(create_app(), ["--host", host, "--port", str(port)]), default_port=8000
179
+ )
180
+ # ... the app's own subcommands, each with set_defaults(fn=...) ...
181
+ args = parser.parse_args(argv)
182
+ return args.fn(args)
183
+ ```
184
+
185
+ Delete the hand-written `doctor`, `set` and `serve` subparsers. Each app's port belongs in its deploy units, not in this library.
186
+
187
+ A doctor that needs more than imports takes labels, optional modules, checks and its own hint, and prints every app's rows in the same columns:
188
+
189
+ ```python
190
+ cli.add_doctor(
191
+ sub,
192
+ "myapp",
193
+ __version__,
194
+ ("fastapi", ("rawpy (DNG decoding)", "rawpy"), cli.Module("ultralytics", optional=True)),
195
+ checks=[cli.Check("ffmpeg", cli.program("ffmpeg", "apt install ffmpeg")), cli.Check("gpu", gpu_check)],
196
+ hint="uv sync (scripts/setup_env)",
197
+ )
198
+ ```
199
+
200
+ A check returns `(status, text)` with status `ok`, `missing`, `slow` (works, but not as it should; never fails) or `broken`, and an exception counts as `broken`. Doctor exits 1 when a required module or check is missing or broken. A check that may be missing without that being a fault is `Check(..., optional=True)`.
201
+
202
+ ### 5b. The strata-models client (apps that use the model service)
203
+
204
+ Drop the `strata-models-client` path or git dependency and change the import. The functions, their arguments and the exceptions are the same:
205
+
206
+ ```python
207
+ from strata_python.clients import models as sm # was: import strata_models_client as sm
208
+
209
+ page = sm.OcrPage.from_json(sm.ocr("/path/page.png", app="strata-scan")) # typed: page.lines[0].words[0].box
210
+ talk = sm.Transcript.from_json(sm.transcribe("/path/talk.wav", app="strata-360"))
211
+ with sm.gpu_lease("strata-stills", vram_gb=4):
212
+ run_my_own_cuda_code()
213
+ ```
214
+
215
+ The shortcuts still return the service's JSON, so existing code keeps working, and the result classes keep all of it in `.raw`. There is one shortcut for every role the service runs (`sm.ROLES`): `faces`, `face_kind`, `transcribe` (also `role="transcribe-fast"`), `ocr`, `speak`, `denoise_audio`, `audio_quality`, `generate_image`, `embed` and `enhance_video`, plus `ask` for the language-model roles (`vision-language`, `text`, and the judges). Each has a result class (`Answer`, `GeneratedImage`, `Embeddings`, `FaceKinds`, `CleanAudio`, `AudioQuality`, `EnhancedVideo` and the four above). The roles `models.toml` lists without a runtime yet (sound-events, speaker-embedding, detect-people, upscale, denoise, nsfw) have none: `run(role, params, app)` reaches them once the service serves them.
216
+
217
+ ### 6. OS helpers
218
+
219
+ Delete the app's `oslib.py` and import from `strata_python.oslib`: `file_lock(f)`, `pid_alive(pid)`, `kill_tree(pid, sig)`, `lower_priority(nice, io=False)` (`io=True` for idle disk priority too; drop the app's `ionice` helper), `venv_python(venv)` and `cli_command(module)`. `cli_command` now takes the module name (`cli_command("myapp")`). Local `alive(pid)`, `_alive` and `lower_priority()` copies go too. Helpers this library does not have yet (process-group supervision, load average) stay in the app until they move here, and the app's file says so.
220
+
221
+ ### 7. Tests
222
+
223
+ The pytest plugin loads itself once strata-python is installed. Configure it in `pyproject.toml`:
224
+
225
+ ```toml
226
+ [tool.pytest.ini_options]
227
+ strata_env_prefix = "MYAPP" # MYAPP_HOME and MYAPP_DATA point into a fresh folder for every test
228
+ strata_tuning_vars = ["MYAPP_WORKERS"] # removed for every test: what a developer sets to try things
229
+ strata_env = [ # set for every test; {env} is that folder
230
+ "MYAPP_SWEEP_SECONDS=0",
231
+ "MYAPP_PROJECTS={env}/projects",
232
+ ]
233
+ ```
234
+
235
+ Then delete these from the app:
236
+
237
+ - `tests/utils/fakes.py`, or keep only the doubles that are the app's own (a fake model, a fake yt-dlp).
238
+ - The `fake_urlopen`, `fake_popen` and `fake_run` fixtures, and any `no_sleep`.
239
+ - `pytest_collection_modifyitems`, which added the `integration` marker. The plugin registers the marker and adds it under `tests/integration`.
240
+ - The `isolated_env` (or `isolated_home`) and `no_network` fixtures. The app's extra variables move to `strata_env`. Keep a small autouse fixture only for what is not a variable, such as patching a module default.
241
+ - The integration `cli` and `cli_subprocess` fixtures. They become short fixtures in `tests/integration/conftest.py`:
242
+
243
+ ```python
244
+ from pathlib import Path
245
+
246
+ import pytest
247
+
248
+ from strata_python.testing import run_cli, run_module
249
+
250
+ SRC = str(Path(__file__).parents[2] / "src")
251
+
252
+
253
+ @pytest.fixture
254
+ def cli():
255
+ from myapp import cli as app_cli
256
+
257
+ return lambda *args, check=True: run_cli(app_cli.main, *args, check=check)
258
+
259
+
260
+ @pytest.fixture
261
+ def cli_subprocess(isolated_env):
262
+ return lambda *args, check=True: run_module("myapp", *args, src=SRC, check=check)
263
+ ```
264
+
265
+ What every test gets:
266
+
267
+ | Fixture | Use it for |
268
+ |---|---|
269
+ | `isolated_env` (autouse) | Home, app home and data in a fresh folder, tuning variables removed, `strata_env` set. Returns the folder |
270
+ | `no_network` (autouse) | An outbound connection fails the test; loopback is fine |
271
+ | `http_server` | **First choice for HTTP**: a real server on loopback. `http_server.route("GET", "/items/1", {"id": 1})`, `once=True` for a sequence, then `http_server.requests`. A request no route answered fails the test |
272
+ | `live_app` | `with live_app(create_app()) as base:` runs the app on a real port for a client under test |
273
+ | `fake_urlopen` | Many quick cases at a web API's edge: `fake_urlopen.reply(http_error(429), {"ok": 1})`, then `fake_urlopen.calls[0].url`, `.method`, `.headers["user-agent"]`, `.body` (parsed JSON) |
274
+ | `fake_popen` | Code that starts a long-running process: nothing starts; `fake_popen.instances[-1].cmd` and `.kw`; set `.returncode = 0` to finish it |
275
+ | `fake_run` | Code that runs a program: `fake_run.returns["ffprobe"] = b"..."`, `fake_run.code = 1`, then `fake_run.calls` |
276
+ | `no_sleep` | Retries and backoff without waiting: `no_sleep.delays` |
277
+
278
+ `strata_python.testing` holds the classes behind them (`FakeResponse`, `http_error`, `FakeUrlopen`, `FakePopen`, `FakeRun`, `Sleeper`) for a test that needs one directly. Prefer the real thing: `http_server` over `fake_urlopen`, the actual program over `fake_run`. A fake is for a true external edge where speed matters.
279
+
280
+ ### 8. Database (apps with one)
281
+
282
+ Replaces the git-pinned database package, with the same behaviour under new names.
283
+
284
+ ```toml
285
+ # pyproject.toml
286
+ dependencies = ["strata-python[db]>=0.2,<0.3"] # SQLAlchemy 2, Alembic, psycopg 3
287
+
288
+ [tool.strata-db] # was the old package's own table: rename it, the keys are the same
289
+ app = "myapp" # owner role and schema (lower case, digits, _)
290
+ models = "myapp.models:Base"
291
+ migrations = "migrations" # the app's Alembic revisions, unchanged
292
+ # engine = "postgres" # only for an app that uses Postgres-only features
293
+ ```
294
+
295
+ - Imports: the old package's names come from `strata_python.db` (`connect`, `session`, `NAMING_CONVENTION`, `Project`, `upgrade`, `drift`, `check_migrations`, `LiveDatabaseRefused`); the standard tests from `strata_python.db.testing`. The naming convention is byte-identical, so existing revisions and databases do not drift.
296
+ - Models: write the base class out, not `Base = make_base()`, which ty rejects as a base (`unsupported-base`) and so fails the gate:
297
+
298
+ ```python
299
+ from sqlalchemy import MetaData
300
+ from sqlalchemy.orm import DeclarativeBase, MappedAsDataclass
301
+ from strata_python.db import NAMING_CONVENTION
302
+
303
+
304
+ class Base(MappedAsDataclass, DeclarativeBase):
305
+ metadata = MetaData(naming_convention=NAMING_CONVENTION)
306
+ ```
307
+ - Environment: `STRATA_DB_LIVE=1` in the service unit (next to the old variable until every app has moved), and `STRATA_DB_DATABASE` naming the shared database. It has no built-in name any more, because that name is the owner's and this package is public; set it once where the services get their environment. `STRATA_DB_URL` and `<APP>_DATABASE_URL` work as before. Tests and CI: `STRATA_DB_TEST_ADMIN_URL`, `STRATA_DB_TEST=postgres`.
308
+ - Commands: `strata-db revision -m "..."`, `strata-db check`, `strata-db migrate --live`, `strata-db current --live`, `strata-db new-app`, `strata-db init` (or `python -m strata_python.db`).
309
+ - At service start (only there): `Project.load(__file__).upgrade(connect("myapp"))`.
310
+ - Tests: the plugin is registered with every install and does nothing until the extra is installed and the project has `[tool.strata-db]` (or `strata_db = true` in `[tool.pytest.ini_options]`; `strata_db = false` turns it off). So an app can take a 0.2.x release before it moves its database, even with the old database package still installed. Then `db_session`, `db_engine`, `db_url` (a URL for code that builds its own engine), `db_env` (points the app's own `connect("myapp")` at the test database; make it autouse in `conftest.py` for an app that connects by itself), `db_backend`, `db_project`. Migrations run once into a template and each test gets a copy, so a test costs a file copy. `pytest --pg` (or `--strata-pg`, which no other plugin can take) runs the same tests on a private Postgres the run starts for itself (needs the PostgreSQL server binaries), or on `STRATA_DB_TEST_ADMIN_URL`. Add the standard tests once:
311
+
312
+ ```python
313
+ # tests/unit/test_database.py
314
+ from strata_python.db.testing import test_migrations, test_schema_matches_models # noqa: F401
315
+ ```
316
+
317
+ Never build a test schema with `Base.metadata.create_all()`: the tests would pass with broken migrations. And never write a guard of your own: under pytest every psycopg connection to a database that is not a throwaway `strata_db_*` one fails with `LiveDatabaseRefused`, in the test process and its subprocesses.
318
+ - CI: run the tests with `--pg` as well for an app that deploys on Postgres, since SQLite hides Postgres-only behaviour (types, defaults, locking). The fixtures need the PostgreSQL server binaries on the runner (`sudo apt-get install -y postgresql` if they are missing; this repo's `ci.yml` shows the step), or `STRATA_DB_TEST_ADMIN_URL` pointing at a service container.
319
+
320
+ Delete: the git source for the old package, its `[tool.*]` table, any home-made "unset the URL" or "block the database" fixture, and any `create_all()` in tests.
321
+
322
+ ### Done when
323
+
324
+ - `grep -rn "def fake_urlopen\|def no_network\|def isolated_env\|pytest_collection_modifyitems\|class FakeRun\|uvicorn.run\|/api/health" src tests` finds nothing the app still needs.
325
+ - The app has no `oslib.py`, `settings.py` with file handling, `fakes.py` copy or `scripts/check.py`.
326
+ - `scripts/check` and the integration tests pass, and the app's changelog names the strata-python version it moved to.
327
+
328
+ ### Keep it current
329
+
330
+ Read the `Unreleased` section and each new version in [CHANGELOG.md](CHANGELOG.md) when dependabot raises a bump. A `### Breaking` line ends with what to change. When the app finds code it shares with another app, it belongs here: open a PR on this repo instead of copying it.
331
+
332
+ ## Develop
333
+
334
+ `uv sync`, then `scripts/check` (add `--fast` to skip the tests, `--fix` for safe ruff fixes). Integration tests (`uv run pytest tests/integration`) run the gate on a tiny project, `serve` in a separate process and `strata-db` as a command. The database tests use a throwaway Postgres: the private server needs the PostgreSQL server binaries on the machine (initdb refuses to run as root), or point `STRATA_DB_TEST_ADMIN_URL` at a throwaway server. Read [AGENTS.md](AGENTS.md) before changing anything; every change gets a [CHANGELOG.md](CHANGELOG.md) line for the apps and a [DEVLOG.md](DEVLOG.md) entry for us. Merging to main releases: `release.yml` bumps the version through its own PR, tags it and creates the GitHub release, and `pypi-publish.yml` uploads it to PyPI.