strata-python 0.2.1__tar.gz → 0.2.3__tar.gz

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 (83) hide show
  1. strata_python-0.2.3/CHANGELOG.md +77 -0
  2. strata_python-0.2.3/PKG-INFO +372 -0
  3. strata_python-0.2.3/README.md +327 -0
  4. {strata_python-0.2.1 → strata_python-0.2.3}/pyproject.toml +11 -3
  5. {strata_python-0.2.1 → strata_python-0.2.3}/src/strata_python/__init__.py +5 -1
  6. strata_python-0.2.3/src/strata_python/cli.py +150 -0
  7. strata_python-0.2.3/src/strata_python/client.py +184 -0
  8. strata_python-0.2.3/src/strata_python/clients/__init__.py +2 -0
  9. strata_python-0.2.3/src/strata_python/clients/models.py +783 -0
  10. strata_python-0.2.3/src/strata_python/contracts.py +149 -0
  11. {strata_python-0.2.1 → strata_python-0.2.3}/src/strata_python/db/__init__.py +6 -3
  12. {strata_python-0.2.1 → strata_python-0.2.3}/src/strata_python/db/models.py +15 -3
  13. {strata_python-0.2.1 → strata_python-0.2.3}/src/strata_python/db/project.py +29 -16
  14. {strata_python-0.2.1 → strata_python-0.2.3}/src/strata_python/db/pytest_plugin.py +63 -9
  15. strata_python-0.2.3/src/strata_python/db/settings.py +63 -0
  16. strata_python-0.2.3/src/strata_python/oslib.py +285 -0
  17. strata_python-0.2.3/src/strata_python/pages/__init__.py +21 -0
  18. strata_python-0.2.3/src/strata_python/pages/model.py +241 -0
  19. strata_python-0.2.3/src/strata_python/pages/render.py +273 -0
  20. {strata_python-0.2.1 → strata_python-0.2.3}/src/strata_python/public_check.py +54 -8
  21. {strata_python-0.2.1 → strata_python-0.2.3}/src/strata_python/pytest_plugin.py +10 -0
  22. strata_python-0.2.3/src/strata_python/settings.py +346 -0
  23. strata_python-0.2.3/src/strata_python/tasks/__init__.py +37 -0
  24. strata_python-0.2.3/src/strata_python/tasks/child.py +236 -0
  25. strata_python-0.2.3/src/strata_python/tasks/flight.py +146 -0
  26. strata_python-0.2.3/src/strata_python/tasks/progress.py +92 -0
  27. strata_python-0.2.3/src/strata_python/tasks/queue.py +716 -0
  28. strata_python-0.2.3/src/strata_python/tasks/retry.py +101 -0
  29. strata_python-0.2.3/src/strata_python/tasks/status.py +188 -0
  30. strata_python-0.2.3/src/strata_python/tasks/ticker.py +85 -0
  31. {strata_python-0.2.1 → strata_python-0.2.3}/src/strata_python/testing.py +164 -0
  32. strata_python-0.2.3/src/strata_python/web.py +260 -0
  33. strata_python-0.2.3/tests/unit/job_handlers.py +68 -0
  34. strata_python-0.2.3/tests/unit/test_cli.py +115 -0
  35. strata_python-0.2.3/tests/unit/test_client.py +132 -0
  36. strata_python-0.2.3/tests/unit/test_clients_models.py +188 -0
  37. strata_python-0.2.3/tests/unit/test_contracts.py +47 -0
  38. {strata_python-0.2.1 → strata_python-0.2.3}/tests/unit/test_db.py +150 -0
  39. strata_python-0.2.3/tests/unit/test_oslib.py +209 -0
  40. strata_python-0.2.3/tests/unit/test_pages.py +251 -0
  41. {strata_python-0.2.1 → strata_python-0.2.3}/tests/unit/test_public_check.py +59 -0
  42. strata_python-0.2.3/tests/unit/test_queue.py +515 -0
  43. strata_python-0.2.3/tests/unit/test_settings.py +263 -0
  44. strata_python-0.2.3/tests/unit/test_tasks.py +281 -0
  45. {strata_python-0.2.1 → strata_python-0.2.3}/tests/unit/test_testing.py +35 -0
  46. strata_python-0.2.3/tests/unit/test_web.py +278 -0
  47. strata_python-0.2.1/CHANGELOG.md +0 -39
  48. strata_python-0.2.1/PKG-INFO +0 -274
  49. strata_python-0.2.1/README.md +0 -233
  50. strata_python-0.2.1/src/strata_python/cli.py +0 -71
  51. strata_python-0.2.1/src/strata_python/oslib.py +0 -117
  52. strata_python-0.2.1/src/strata_python/settings.py +0 -132
  53. strata_python-0.2.1/src/strata_python/web.py +0 -98
  54. strata_python-0.2.1/tests/unit/test_cli.py +0 -64
  55. strata_python-0.2.1/tests/unit/test_oslib.py +0 -80
  56. strata_python-0.2.1/tests/unit/test_settings.py +0 -125
  57. strata_python-0.2.1/tests/unit/test_web.py +0 -126
  58. {strata_python-0.2.1 → strata_python-0.2.3}/.gitignore +0 -0
  59. {strata_python-0.2.1 → strata_python-0.2.3}/LICENSE +0 -0
  60. {strata_python-0.2.1 → strata_python-0.2.3}/src/strata_python/check.py +0 -0
  61. {strata_python-0.2.1 → strata_python-0.2.3}/src/strata_python/db/__main__.py +0 -0
  62. {strata_python-0.2.1 → strata_python-0.2.3}/src/strata_python/db/_alembic/env.py +0 -0
  63. {strata_python-0.2.1 → strata_python-0.2.3}/src/strata_python/db/_alembic/script.py.mako +0 -0
  64. {strata_python-0.2.1 → strata_python-0.2.3}/src/strata_python/db/cli.py +0 -0
  65. {strata_python-0.2.1 → strata_python-0.2.3}/src/strata_python/db/config.py +0 -0
  66. {strata_python-0.2.1 → strata_python-0.2.3}/src/strata_python/db/engine.py +0 -0
  67. {strata_python-0.2.1 → strata_python-0.2.3}/src/strata_python/db/guard.py +0 -0
  68. {strata_python-0.2.1 → strata_python-0.2.3}/src/strata_python/db/migrations.py +0 -0
  69. {strata_python-0.2.1 → strata_python-0.2.3}/src/strata_python/db/scratch.py +0 -0
  70. {strata_python-0.2.1 → strata_python-0.2.3}/src/strata_python/db/testing.py +0 -0
  71. {strata_python-0.2.1 → strata_python-0.2.3}/src/strata_python/db/testserver.py +0 -0
  72. {strata_python-0.2.1 → strata_python-0.2.3}/src/strata_python/http_server.py +0 -0
  73. {strata_python-0.2.1 → strata_python-0.2.3}/src/strata_python/live.py +0 -0
  74. {strata_python-0.2.1 → strata_python-0.2.3}/src/strata_python/py.typed +0 -0
  75. {strata_python-0.2.1 → strata_python-0.2.3}/tests/conftest.py +0 -0
  76. {strata_python-0.2.1 → strata_python-0.2.3}/tests/integration/test_db_cli.py +0 -0
  77. {strata_python-0.2.1 → strata_python-0.2.3}/tests/integration/test_serve.py +0 -0
  78. {strata_python-0.2.1 → strata_python-0.2.3}/tests/integration/test_strata_check.py +0 -0
  79. {strata_python-0.2.1 → strata_python-0.2.3}/tests/unit/test_check.py +0 -0
  80. {strata_python-0.2.1 → strata_python-0.2.3}/tests/unit/test_http_server.py +0 -0
  81. {strata_python-0.2.1 → strata_python-0.2.3}/tests/unit/test_live.py +0 -0
  82. {strata_python-0.2.1 → strata_python-0.2.3}/tests/unit/test_package.py +0 -0
  83. {strata_python-0.2.1 → strata_python-0.2.3}/tests/unit/test_plugin.py +0 -0
@@ -0,0 +1,77 @@
1
+ # Changelog
2
+
3
+ What each release adds or changes for an app that depends on strata-python, newest first. Every breaking change says what to do in one line. Versions follow [semver](https://semver.org); while the version is 0.x a minor release may break, so depend on `strata-python>=0.N,<0.N+1`. Why each change was made is in [DEVLOG.md](DEVLOG.md).
4
+
5
+ ## Unreleased
6
+
7
+ ## 0.2.3 (2026-11-14)
8
+
9
+ ## 0.2.2 (2026-11-14)
10
+
11
+ ### Added
12
+
13
+ - `strata_python.contracts`: the shapes the apps' APIs share, as pydantic models to declare as a route's `response_model` (so `/api/openapi.json` describes them and a web app's types can be generated): `Health`, `SystemInfo` (with `Folder`, `ServiceStatus`), `ErrorBody`, `Task` with `TaskState` and `FINISHED`, `Progress`, `Page[T]` (cursor paging), `FileRef`, `Judgment`, and `utc(epoch)`. Times are aware datetimes, sent as ISO 8601.
14
+ - `strata_python.client.ServiceClient(base_url, app=...)`: the standard-library base for calling a strata service: `get`/`post`/`put`/`delete` returning parsed JSON, `Rejected` for a 4xx (`.status`, `.detail`, `.payload`) and `Unavailable` for an outage or a 5xx, reads retried with a doubling pause (POSTs never), `wait(path, done)` long-polling with `?wait=`, `health()` and `available()`, and `env_url("MYAPP_URL", default)` reading the URL on each call. `X-Strata-App` and the User-Agent name the calling app. `clients.models.Unavailable` is now a `client.Unavailable`.
15
+ - `web.add_error_handlers(app, {MyError: 423})`: the app's exceptions answered as `ErrorBody` responses (`{detail, payload}`); the defaults map `ValueError` to 400, `PermissionError` 403, `KeyError` and `FileNotFoundError` 404, `tasks.Conflict` 409, `client.Rejected` 502 and `client.Unavailable` 503. Delete the app's `guard()`.
16
+ - `web.add_system(app, version, commit=, folders=, services=, extra=)`: `GET /api/system` as a `SystemInfo` (version, commit, Python, platform, start time, each folder with its disk's free and total bytes, each service's health probed in parallel). Delete the app's own route.
17
+ - `base_app(..., commit=web.source_commit(__file__))`: `/api/health` answers `commit`, read from `.git` without running git (worktrees and packed refs included).
18
+ - `Settings.model()`: the settings as a pydantic model (`<App>Settings`), which `base_app` declares as the settings routes' response, so `/api/openapi.json` now names each setting and its type.
19
+ - `strata_python.tasks`: `next_state`, `backoff_s`, `RetryLater` and `PROGRAMMING_ERRORS` (retry rules: bugs fail at once, outside failures back off, progress resets the count); `report_progress` with `ProgressReporter` and `reporting` (throttled to one write a second, stage changes and the last step always written); `SingleFlight` and `Flight` (one in-process run per key, `Conflict` on a second start, cooperative `stopping`); `StatusFile` and `Detached` (a process outside the server's session, its state in an atomic JSON file that reads `died` when its pid is gone; the child finds the file in `STRATA_STATUS_FILE`; writes and merges hold `StatusFile.locked()` across processes, so none is lost); `Ticker` (a function every N seconds that survives its own errors and stops at once); `write_json_atomic`.
20
+ - `oslib.stdin_from_devnull()` (an empty stdin for the process and its tools; returns the old one) and `oslib.stdout_to_stderr()` (moves stdout for the process and the tools it starts, the Win32 handle too, and returns the old one). `oslib.start_supervised`, `watch_supervisor`, `terminate_own_group` and `kill_group`: listory's per-job process groups. A child started with a lifeline on its stdin ends its whole group when the parent dies; `kill_group` stops it and every tool it started. Replaces listory's `job_process`, `start_job`, `watch_supervisor`, `terminate_job_group` and `kill_job`.
21
+ - `strata_python.tasks.queue` (needs `[db]`): a durable job queue in the app's own database, SQLite or Postgres. `jobs_table(metadata)` for the app's models; `Queue(engine, table)` with `enqueue` (priority, `delay_s`, `dedupe`, `resources`, `timeout_s`, `domain`), `claim`, `heartbeat`, `report`, `finish`, `fail` (the `tasks.retry` rules; `on_fail(conn, job, error)` runs in the transaction that fails a job for good), `cancel`, `retry`, `get`, `page` (`Page[Task]`, newest first, cursor paging), `counts`, `recover` (jobs whose worker died are retried; each claim carries a token, so a slow worker whose job was claimed again cannot write over the new attempt), `prune`, and `step(handlers)` for tests; `Worker(queue, handlers, concurrency=)` runs them on threads with heartbeats, cooperative cancel and timeouts, and releases running jobs back to the queue on `stop()`. By default jobs run in a job process per worker thread (`tasks.child`), kept between jobs so a quick job costs well under a millisecond more than on a thread: cancel, timeout and `stop()` kill the job and the tools it started (the next job gets a new process), and jobs die with the server. Handlers must be module-level functions (checked when the `Worker` is made); `max_jobs=N` replaces a process after N jobs, `isolate=False` keeps handlers on threads, and `lower_priority=True` runs the processes at idle priority. Replaces an app's own queue and its job dicts that must survive a restart.
22
+ - `oslib.detached_kwargs()` (Popen arguments for a process outside this one's session or console) and `oslib.load_average()`.
23
+ - The `fake_models` fixture and `strata_python.testing.FakeModels`: a stand-in strata-models on a real loopback port with `STRATA_MODELS_URL` pointing at it, so an app's own `strata_python.clients.models` calls run in its tests without the service or a GPU. Script `fake_models.results[role]` (a reply or a function of the params; `MODELS_RESULTS` has one in the service's shape per role), `.fail(error, role=...)`, `.busy` (leases stay queued), `.down` (503s), and assert on `.jobs`, `.leases`, `.heartbeats`, `.released`. Delete the app's own stand-in.
24
+ - `strata_python.pages` and the `[pdf]` extra (ReportLab, pypdfium2, Pillow): a scanned page described as blocks, lines, styled spans and figures in scan pixels (`Page`, `Block`, `Line`, `Span`, `Figure`, JSON with `to_dict`/`from_dict`), drawn as a PDF with real, embedded fonts by `pages.render.render(page, fonts)`, and read back with `rasterise(pdf, page, dpi)` (greyscale pixels at the scan's size) and `read_text(pdf)`. A span takes a font matcher's per-word fit as it is (`x`, `baseline_y`, `size_pt`, `tracking_em`, `hscale`, `stroke_em`); small capitals are synthesised unless the face is a small-caps cut; the same input gives the same bytes. For apps that rebuild scanned books, and for scoring a rebuild against the scan with the very renderer that prints it.
25
+ - `strata_python.clients.models`: the strata-models client, standard library only, with the same functions as `strata_models_client` (`run`, `submit`, `wait`, `wait_job`, `faces`, `transcribe`, `ocr`, `speak`, `role_model`, `acquire`, `gpu_lease`, `Unavailable`, `JobFailed`), now typed, plus a shortcut for each of the other roles the service runs (`ask` for `vision-language`, `text` and the judges; `generate_image`, `embed`, `face_kind`, `denoise_audio`, `audio_quality`, `enhance_video`) and a result shape for every role (`OcrPage`, `Transcript`, `Faces`, `Speech`, `Answer`, `GeneratedImage`, `Embeddings`, `FaceKinds`, `CleanAudio`, `AudioQuality`, `EnhancedVideo`; `.from_json`, with everything the service sent in `.raw`). `ROLES` lists them. To move: replace `import strata_models_client as sm` with `from strata_python.clients import models as sm` and drop the client's path or git dependency.
26
+ - Typed settings: normalisers `number_between(lo, hi)`, `whole_between(lo, hi)`, `iso_date(allow_blank=True)` and `boolean`, and getters `get_int`, `get_float`, `get_bool`. Replace an app's own range and date normalisers and its `int(SETTINGS.get(...))` calls.
27
+ - `ListSetting(key, default=..., item=..., sep=os.pathsep, env=...)`: a list of strings, a JSON list in the file, split on `sep` in the environment, read with `get_list`. `all()`, `GET /api/settings` and `PUT /api/settings` carry it as a JSON list, and `set` shows and takes it joined. An app with a list of folders can now drop its own settings file handling.
28
+ - Settings stores: `Settings(..., store=...)` and `Settings.bind(store)` keep the values in any object with `load()` and `update(changes)`. On the first bind the JSON file's values are copied in once. `strata_python.db.settings` has the table every app shares (`settings_table(Base.metadata)`) and its `TableStore`, on SQLite and Postgres.
29
+ - `cli.add_doctor(..., checks=[...], hint="...")`: imports can be `(label, module)` pairs or `cli.Module(label, module, optional=True)`, and `cli.Check(label, fn)` rows (`fn` returns `(status, text)`; `ok`, `missing`, `slow` or `broken`) cover what an import cannot tell, with `cli.program("ffmpeg")` for a program on the PATH. Every app's rows line up the same. `cli.doctor(...)` runs the same thing directly. Replace an app's own `doctor` with these.
30
+ - `web.base_app(..., health=lambda: {...})` adds the app's own fields to `GET /api/health` after `ok` and `version`; it may set `ok` to false. Replace an app's own health route with it.
31
+ - `oslib.lower_priority(nice, io=True)` also lowers disk priority for batch jobs that read many large files: the idle I/O class on Linux (children inherit it), background mode on Windows, I/O throttling on macOS. Replace the app's own `ionice -c3 -p <pid>` helper with it.
32
+ - `strata-public-check` takes `[tool.strata-public-check] exclude = [...]` in pyproject.toml and `--exclude GLOB` to skip the built-in patterns in matching files (an sdist's copy matches too), and skips the built-in patterns on a line that says `strata-public-check: ignore`. Neither silences `STRATA_PUBLIC_DENY`.
33
+
34
+ ### Changed
35
+
36
+ - `Settings.all()` is typed `dict[str, str | list[str]]`, since a `ListSetting` is a list. It is unchanged for an app with only `Setting`s, but its type checker may now ask it to narrow a value it passes on as a `str`.
37
+ - The documented way to declare an app's models base is now the class written out (`class Base(MappedAsDataclass, DeclarativeBase): metadata = MetaData(naming_convention=NAMING_CONVENTION)`, README step 8), because ty rejects `Base = make_base()` as a base class and fails the gate. `make_base()` still works and stays for code that needs a base at run time; an app that uses it for its models should switch.
38
+
39
+ ### Fixed
40
+
41
+ - The `[pdf]` extra needs Pillow 13 (`pillow>=13,<14`): 12.x has eight published advisories, most of them in PDF parsing, and `uv audit` fails an app that locks it. Run `uv lock --upgrade-package pillow`.
42
+ - `strata-public-check` no longer reads three-part versions (`10.4.2` in package.json and package-lock.json) as private IPv4 addresses: only a whole four-part address counts. An app with a web front end can now run it in CI.
43
+ - The db pytest plugin no longer stops an app's tests from running when the old database package is installed too ("option names {'--pg'} already added"). It now switches on only for an app that uses `strata_python.db`: the db extra installed and a `[tool.strata-db]` table in pyproject.toml, or `strata_db = true` in `[tool.pytest.ini_options]` (`strata_db = false` turns it off). SQLAlchemy and Alembic brought in by another package no longer switch on its guard. Until it is on it adds no `--pg`; once on, `--pg` is ours unless another plugin has it, and `--strata-pg` always works. Drop the old database package once the app has moved to `strata_python.db`.
44
+
45
+ ## 0.2.1 (2026-11-14)
46
+
47
+ ### Added
48
+
49
+ - `strata_python.testing`: the test doubles every app copied into `tests/utils/fakes.py` (`FakeResponse`, `http_error`, `FakeUrlopen`, `FakePopen`, `FakeRun`, plus `Sleeper`), and CLI runners `run_cli(main, *args, check=True)` and `run_module(module, *args, src=..., check=True)` returning `CliResult(stdout, stderr, code)`. Delete the app's `fakes.py` and import from here.
50
+ - Plugin fixtures `fake_urlopen`, `fake_popen`, `fake_run` and `no_sleep`, so the app's conftest no longer defines them. `fake_popen` gives each test its own `.instances`. `FakeUrlopen.calls` entries are `Call` objects that still answer `call["url"]`.
51
+ - `strata_env = ["KEY=VALUE", ...]` in `[tool.pytest.ini_options]` sets the app's own variables for every test (`{env}` is the isolated folder), for what each app's `isolated_env` copy added.
52
+ - `strata-python[dev]`: ruff, pyright, ty, httpx and the pytest plugins at the versions `strata-check` is tested with. An app's dev group becomes `dev = ["strata-python[dev]"]`; delete those packages from it.
53
+ - `strata-python[db]` and `strata_python.db`: the shared-database code apps took from a git pin of the database package, now typed and released here. `connect`, `session`, `make_base` (the same naming convention, so existing revisions do not drift), `Project` from `[tool.strata-db]`, `upgrade`, `downgrade`, `drift`, `check_migrations`, `lint_revisions`, `stairway`, the live-database guard (`LiveDatabaseRefused`), scratch databases, a private throwaway Postgres for tests (now on Windows too), the `strata-db` command (`init`, `new-app`, `revision`, `migrate`, `check`, `current`; also `python -m strata_python.db`), the fixtures `db_engine`, `db_session`, `db_url`, `db_env`, `db_backend`, `db_project` with `--pg`, and the standard tests in `strata_python.db.testing`. The names are `STRATA_DB_*` (`URL`, `DATABASE`, `LIVE`, `TESTING`, `TEST`, `TEST_ADMIN_URL`, `ADMIN_URL`); throwaway databases are `strata_db_*`. To move: rename the app's table to `[tool.strata-db]`, import from `strata_python.db`, set `STRATA_DB_LIVE=1` and `STRATA_DB_DATABASE` in its service environment, and drop the git dependency (README, step 8).
54
+ - Tests under `tests/integration` get the `integration` marker automatically, and the marker is registered; delete the app's `pytest_collection_modifyitems`. Set `strata_auto_integration = false` to opt out.
55
+
56
+ ### Changed
57
+
58
+ - The shared dependencies are capped below their next release that may break (`fastapi<1`, `uvicorn<1`, `pydantic<3`, `pytest<10`), so a breaking upstream release reaches the apps through a strata-python release, not on its own.
59
+ - `FakeRun.check_output` raises `CalledProcessError` when `.code` is set, as the real `check_output` does; the apps' copies returned the output.
60
+
61
+ ## 0.2.0 (2026-11-14)
62
+
63
+ The first release on PyPI. Apps tracked a git commit before this.
64
+
65
+ ### Changed
66
+
67
+ - **Install from PyPI.** Replace the `[tool.uv.sources] strata-python = { git = ... }` entry with the dependency `strata-python>=0.2,<0.3`, then run `uv lock`.
68
+
69
+ ### Added
70
+
71
+ - `strata-public-check`: fails on email addresses, private IPv4 addresses, home-folder paths and the regexes in `STRATA_PUBLIC_DENY`, in a folder, an sdist or a wheel. Run it in a public app's CI.
72
+ - `Settings(..., prefix="MA")` names the environment variables an app already uses (from the pre-PyPI commits; listed here because no earlier release exists).
73
+ - The MIT licence.
74
+
75
+ ## Before 0.2.0 (git commits only)
76
+
77
+ `oslib`, `settings`, `web`, `cli`, `http_server`, `live`, the pytest plugin (`isolated_env`, `no_network`, `http_server`, `live_app`) and `strata-check`, taken from python-app-template.
@@ -0,0 +1,372 @@
1
+ Metadata-Version: 2.5
2
+ Name: strata-python
3
+ Version: 0.2.3
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,>=13; 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`, `detached_kwargs`, `load_average`, `start_supervised`/`watch_supervisor`/`kill_group` (a child in its own process group that dies with its parent), `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 and `commit` + typed settings routes), `add_error_handlers` (exceptions to `ErrorBody` responses), `add_system` (`GET /api/system`: folders, disks, services), `source_commit`, `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.contracts` | The shapes the apps' APIs share, as pydantic models for `response_model`: `Health`, `SystemInfo`, `ErrorBody`, `Task` (with `TaskState`), `Progress`, `Page[T]`, `FileRef`, `Judgment` |
57
+ | `strata_python.client` | `ServiceClient`, the standard-library base for calling a strata service: JSON calls, `Rejected` (4xx, with the reason and payload) and `Unavailable` (down or 5xx), retried reads, a long-poll `wait`, `available()`, and `env_url` |
58
+ | `strata_python.tasks` | Work outside a request: `next_state`/`backoff_s`/`RetryLater` (when to retry), `report_progress` and `ProgressReporter` (throttled), `SingleFlight` (one run per key, `Conflict` on a second), `StatusFile` and `Detached` (a process that outlives the server), `Ticker` (a loop that survives its errors), and with the `[db]` extra `tasks.queue` (`Queue`, `Worker`, `jobs_table`: durable jobs with retry, dedupe, resources, cancel and crash recovery) |
59
+ | `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 |
60
+ | `strata_python.http_server` / `live` | A real scripted HTTP server and a real uvicorn server on loopback, for tests that make actual requests |
61
+ | 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, `fake_models` (a stand-in strata-models), and the `integration` marker on everything under `tests/integration` |
62
+ | `strata_python.testing` | The fakes behind those fixtures (`FakeResponse`, `http_error`, `FakeUrlopen`, `FakePopen`, `FakeRun`, `Sleeper`) `FakeModels`, and the CLI runners `run_cli(main, *args)` and `run_module("myapp", *args, src=...)` |
63
+ | `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`) |
64
+ | `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 |
65
+ | `strata-check` | The one gate: lockfile, ruff, `ruff format`, pyright strict, ty, unit tests with coverage |
66
+ | `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`) |
67
+
68
+ ## Move an app onto it
69
+
70
+ 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).
71
+
72
+ ### 1. Depend on the release
73
+
74
+ ```toml
75
+ # pyproject.toml
76
+ [project]
77
+ dependencies = [
78
+ "strata-python>=0.2,<0.3", # brings FastAPI, uvicorn, pydantic and pytest; while 0.x, cap below the next minor
79
+ # ... only what is the app's own: torch, opencv, yt-dlp ...
80
+ ]
81
+
82
+ [dependency-groups]
83
+ dev = ["strata-python[dev]"] # ruff, pyright, ty, httpx and the pytest plugins, at the versions strata-check expects
84
+ ```
85
+
86
+ 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.
87
+
88
+ 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:
89
+
90
+ ```yaml
91
+ # .github/dependabot.yml in the app
92
+ version: 2
93
+ updates:
94
+ - package-ecosystem: uv
95
+ directory: /
96
+ schedule: { interval: weekly }
97
+ groups: { python: { patterns: ["*"] } } # strata-python and everything else in one PR
98
+ - package-ecosystem: github-actions
99
+ directory: /
100
+ schedule: { interval: monthly }
101
+ groups: { actions: { patterns: ["*"] } }
102
+ ```
103
+
104
+ Security updates still arrive on their own as soon as they are published; keep them on.
105
+
106
+ ### 2. The gate
107
+
108
+ `scripts/check` becomes one line, and the app's own `scripts/check.py` goes:
109
+
110
+ ```bash
111
+ #!/bin/bash
112
+ DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
113
+ cd "$DIR/.." && exec uv run --locked strata-check "$@"
114
+ ```
115
+
116
+ 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.
117
+
118
+ ### 3. Settings
119
+
120
+ Replace the app's `settings.py` (its key list, getters, file handling and environment lookups) with a declaration:
121
+
122
+ ```python
123
+ from strata_python.settings import ListSetting, Setting, Settings, absolute_path, non_empty, whole_between
124
+
125
+ SETTINGS = Settings(
126
+ "myapp", # ~/.myapp/settings.json, moved with MYAPP_HOME
127
+ [
128
+ Setting("data_dir", default=lambda: "/srv/myapp", normalise=absolute_path),
129
+ Setting("greeting", default="Hello", normalise=non_empty),
130
+ Setting("workers", default="2", normalise=whole_between(1, 16)),
131
+ ListSetting("source_roots", item=absolute_path, env="MYAPP_SOURCES"), # MYAPP_SOURCES split on os.pathsep
132
+ ],
133
+ prefix="MYAPP", # only if the app already runs with other variable names
134
+ )
135
+
136
+ SETTINGS.get("greeting") # MYAPP_GREETING, else the file, else the default
137
+ SETTINGS.save({"greeting": "Hi"}) # validated and written atomically; None resets to the default
138
+ SETTINGS.folder("data_dir") # the value as a folder, created if missing
139
+ ```
140
+
141
+ 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.
142
+
143
+ 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:
144
+
145
+ ```python
146
+ from strata_python.db.settings import TableStore, settings_table
147
+
148
+ SETTINGS_TABLE = settings_table(Base.metadata) # in models.py, so the migrations create it
149
+ SETTINGS.bind(TableStore(engine, SETTINGS_TABLE)) # any object with load() and update(changes) is a store
150
+ ```
151
+
152
+ ### 4. The server
153
+
154
+ ```python
155
+ from strata_python import web
156
+
157
+
158
+ def create_app():
159
+ app = web.base_app("myapp", __version__, SETTINGS) # GET /api/health, GET and PUT /api/settings, /api/docs
160
+ # ... the app's own /api routes ...
161
+ web.add_web(app, STATIC_DIR, LANDING_HTML) # last: /assets, top-level files, and index.html at every other path
162
+ return app
163
+ ```
164
+
165
+ Two more that replace code most servers carry:
166
+
167
+ ```python
168
+ web.add_error_handlers(app) # ValueError 400, PermissionError 403, KeyError and FileNotFoundError 404,
169
+ # tasks.Conflict 409, client.Rejected 502, client.Unavailable 503: {detail, payload}
170
+ web.add_system(app, __version__, commit=web.source_commit(__file__),
171
+ folders={"data": lambda: SETTINGS.get("data_dir")},
172
+ services={"strata-models": "http://127.0.0.1:8366"}) # GET /api/system, a SystemInfo
173
+ ```
174
+
175
+ Delete the app's `guard()` (or each route's `try/except` raising `HTTPException`), passing its own exceptions as `add_error_handlers(app, {BookLocked: 423})`, and its `/api/system` route. Give `base_app` the same `commit=` so `/api/health` says which source the server runs. Declare a route's answer with a shape from `strata_python.contracts` (`response_model=Page[Task]`) where the app already returns that shape, so the web app's types can come from `/api/openapi.json`.
176
+
177
+ 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.
178
+
179
+ ### 5. The CLI
180
+
181
+ ```python
182
+ import argparse
183
+
184
+ from strata_python import cli, web
185
+
186
+
187
+ def main(argv=None):
188
+ parser = argparse.ArgumentParser(prog="myapp")
189
+ sub = parser.add_subparsers(dest="cmd", required=True)
190
+ cli.add_doctor(sub, "myapp", __version__, ("fastapi", "uvicorn")) # versions, and whether each import works
191
+ cli.add_set(sub, SETTINGS) # myapp set KEY [VALUE|default]
192
+ cli.add_serve(
193
+ sub, lambda host, port: web.serve(create_app(), ["--host", host, "--port", str(port)]), default_port=8000
194
+ )
195
+ # ... the app's own subcommands, each with set_defaults(fn=...) ...
196
+ args = parser.parse_args(argv)
197
+ return args.fn(args)
198
+ ```
199
+
200
+ Delete the hand-written `doctor`, `set` and `serve` subparsers. Each app's port belongs in its deploy units, not in this library.
201
+
202
+ 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:
203
+
204
+ ```python
205
+ cli.add_doctor(
206
+ sub,
207
+ "myapp",
208
+ __version__,
209
+ ("fastapi", ("rawpy (DNG decoding)", "rawpy"), cli.Module("ultralytics", optional=True)),
210
+ checks=[cli.Check("ffmpeg", cli.program("ffmpeg", "apt install ffmpeg")), cli.Check("gpu", gpu_check)],
211
+ hint="uv sync (scripts/setup_env)",
212
+ )
213
+ ```
214
+
215
+ 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)`.
216
+
217
+ ### 5b. The strata-models client (apps that use the model service)
218
+
219
+ Drop the `strata-models-client` path or git dependency and change the import. The functions, their arguments and the exceptions are the same:
220
+
221
+ ```python
222
+ from strata_python.clients import models as sm # was: import strata_models_client as sm
223
+
224
+ page = sm.OcrPage.from_json(sm.ocr("/path/page.png", app="strata-scan")) # typed: page.lines[0].words[0].box
225
+ talk = sm.Transcript.from_json(sm.transcribe("/path/talk.wav", app="strata-360"))
226
+ with sm.gpu_lease("strata-stills", vram_gb=4):
227
+ run_my_own_cuda_code()
228
+ ```
229
+
230
+ 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). In tests, the `fake_models` fixture (section 7) stands in for the service, so the app's tests need neither the service nor a GPU. 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.
231
+
232
+ ### 6. OS helpers
233
+
234
+ 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. `detached_kwargs()` starts a process outside the server's session and `load_average()` replaces 360's copy. listory's `job_process`, `start_job`, `watch_supervisor`, `terminate_job_group` and `kill_job` are `start_supervised(cmd, env=)`, `watch_supervisor()`, `terminate_own_group()` and `kill_group(proc)`; with the queue's `Worker` an app needs none of them directly.
235
+
236
+ ### 6b. Background work
237
+
238
+ Replace the app's job dicts and loops with `strata_python.tasks`:
239
+
240
+ - An in-process run per key ("scan this folder") is `SingleFlight`: `FLIGHTS.start(key, fn)` raises `Conflict` (a 409 with `add_error_handlers`) when that key is running; `fn(flight)` checks `flight.stopping`; `FLIGHTS.get(key).as_json()` is the status. Delete the app's `*_JOBS` dicts, their locks and their stop flags.
241
+ - Work that must outlive a restart is `Detached(cmd, status_path, log)`: `start()`, `read()`, `stop()`. The child writes its own progress and end state with `StatusFile.from_env().update(...)`. Delete the app's `write_status` copies and its pid bookkeeping.
242
+ - A loop every N seconds is `Ticker(every_s, fn, name=...)`. Delete the hand-written `while not stop.wait(...)` threads.
243
+ - Progress from deep inside a task is `report_progress(done, total, text)`; the runner binds a `ProgressReporter` (at most one write a second). Retry rules are `next_state(attempts, error, progressed=...)`: delete the app's own backoff.
244
+ - Jobs that must survive a restart, retry and be listed are the durable queue (with the db extra). Add `JOBS = jobs_table(Base.metadata)` to the models and a revision, then:
245
+
246
+ ```python
247
+ from strata_python.tasks.queue import Job, Queue, Worker
248
+
249
+ QUEUE = Queue(engine, JOBS, on_fail=cascade) # on_fail(conn, job, error), in the failing transaction
250
+ QUEUE.enqueue("ocr", {"page": 3}, domain="book:12", dedupe=True, resources=["gpu"], timeout_s=600)
251
+ WORKER = Worker(QUEUE, {"ocr": ocr_page}, concurrency=2).start() # a job process per thread, reused; recovers dead workers' jobs
252
+ QUEUE.page(state="running", after=cursor) # Page[Task] for GET /api/jobs
253
+ QUEUE.cancel(job_id); QUEUE.retry(job_id); QUEUE.prune(older_than_s=30 * 86400)
254
+ ```
255
+
256
+ A handler is a module-level `fn(job) -> result` that reads `job.options` and reports progress. By default jobs run in job processes (`python -m strata_python.tasks.child`, one per worker thread, kept between jobs and importing the handlers by name), so a cancel, a timeout or `WORKER.stop()` kills the job and every tool it started, and jobs die with the server; a quick job costs about half a millisecond more than on a thread (3.5 ms against 2.9 ms a job on SQLite), since only a kill starts a new process. `max_jobs=N` replaces a process after N jobs, for code that leaks. The worker checks at start-up that every handler can be imported. `Worker(lower_priority=True)` runs the jobs at idle CPU and disk priority. `Worker(isolate=False)` runs handlers on the server's threads instead, where they return early when `job.stopping`. In tests, `QUEUE.step(handlers)` claims and runs one job in the test's own thread.
257
+
258
+ ### 7. Tests
259
+
260
+ The pytest plugin loads itself once strata-python is installed. Configure it in `pyproject.toml`:
261
+
262
+ ```toml
263
+ [tool.pytest.ini_options]
264
+ strata_env_prefix = "MYAPP" # MYAPP_HOME and MYAPP_DATA point into a fresh folder for every test
265
+ strata_tuning_vars = ["MYAPP_WORKERS"] # removed for every test: what a developer sets to try things
266
+ strata_env = [ # set for every test; {env} is that folder
267
+ "MYAPP_SWEEP_SECONDS=0",
268
+ "MYAPP_PROJECTS={env}/projects",
269
+ ]
270
+ ```
271
+
272
+ Then delete these from the app:
273
+
274
+ - `tests/utils/fakes.py`, or keep only the doubles that are the app's own (a fake model, a fake yt-dlp).
275
+ - The `fake_urlopen`, `fake_popen` and `fake_run` fixtures, and any `no_sleep`.
276
+ - `pytest_collection_modifyitems`, which added the `integration` marker. The plugin registers the marker and adds it under `tests/integration`.
277
+ - 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.
278
+ - The integration `cli` and `cli_subprocess` fixtures. They become short fixtures in `tests/integration/conftest.py`:
279
+
280
+ ```python
281
+ from pathlib import Path
282
+
283
+ import pytest
284
+
285
+ from strata_python.testing import run_cli, run_module
286
+
287
+ SRC = str(Path(__file__).parents[2] / "src")
288
+
289
+
290
+ @pytest.fixture
291
+ def cli():
292
+ from myapp import cli as app_cli
293
+
294
+ return lambda *args, check=True: run_cli(app_cli.main, *args, check=check)
295
+
296
+
297
+ @pytest.fixture
298
+ def cli_subprocess(isolated_env):
299
+ return lambda *args, check=True: run_module("myapp", *args, src=SRC, check=check)
300
+ ```
301
+
302
+ What every test gets:
303
+
304
+ | Fixture | Use it for |
305
+ |---|---|
306
+ | `isolated_env` (autouse) | Home, app home and data in a fresh folder, tuning variables removed, `strata_env` set. Returns the folder |
307
+ | `no_network` (autouse) | An outbound connection fails the test; loopback is fine |
308
+ | `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 |
309
+ | `live_app` | `with live_app(create_app()) as base:` runs the app on a real port for a client under test |
310
+ | `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) |
311
+ | `fake_popen` | Code that starts a long-running process: nothing starts; `fake_popen.instances[-1].cmd` and `.kw`; set `.returncode = 0` to finish it |
312
+ | `fake_run` | Code that runs a program: `fake_run.returns["ffprobe"] = b"..."`, `fake_run.code = 1`, then `fake_run.calls` |
313
+ | `no_sleep` | Retries and backoff without waiting: `no_sleep.delays` |
314
+ | `fake_models` | An app that calls strata-models: a stand-in service on a real port with `STRATA_MODELS_URL` set, so `strata_python.clients.models` runs unchanged. `fake_models.results["ocr"] = {...}` (or a function of the params), `.fail("CUDA out of memory", role="faces")`, `.busy = True` (leases wait), `.down = True` (503s), then `.jobs[0]["params"]` |
315
+
316
+ `strata_python.testing` holds the classes behind them (`FakeResponse`, `http_error`, `FakeUrlopen`, `FakePopen`, `FakeRun`, `Sleeper`, `FakeModels` and its example replies `MODELS_RESULTS`) 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.
317
+
318
+ ### 8. Database (apps with one)
319
+
320
+ Replaces the git-pinned database package, with the same behaviour under new names.
321
+
322
+ ```toml
323
+ # pyproject.toml
324
+ dependencies = ["strata-python[db]>=0.2,<0.3"] # SQLAlchemy 2, Alembic, psycopg 3
325
+
326
+ [tool.strata-db] # was the old package's own table: rename it, the keys are the same
327
+ app = "myapp" # owner role and schema (lower case, digits, _)
328
+ models = "myapp.models:Base"
329
+ migrations = "migrations" # the app's Alembic revisions, unchanged
330
+ # engine = "postgres" # only for an app that uses Postgres-only features
331
+ ```
332
+
333
+ - 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.
334
+ - Models: write the base class out, not `Base = make_base()`, which ty rejects as a base (`unsupported-base`) and so fails the gate:
335
+
336
+ ```python
337
+ from sqlalchemy import MetaData
338
+ from sqlalchemy.orm import DeclarativeBase, MappedAsDataclass
339
+ from strata_python.db import NAMING_CONVENTION
340
+
341
+
342
+ class Base(MappedAsDataclass, DeclarativeBase):
343
+ metadata = MetaData(naming_convention=NAMING_CONVENTION)
344
+ ```
345
+ - 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`.
346
+ - 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`).
347
+ - At service start (only there): `Project.load(__file__).upgrade(connect("myapp"))`.
348
+ - 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:
349
+
350
+ ```python
351
+ # tests/unit/test_database.py
352
+ from strata_python.db.testing import test_migrations, test_schema_matches_models # noqa: F401
353
+ ```
354
+
355
+ 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.
356
+ - 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.
357
+
358
+ 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.
359
+
360
+ ### Done when
361
+
362
+ - `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.
363
+ - The app has no `oslib.py`, `settings.py` with file handling, `fakes.py` copy or `scripts/check.py`.
364
+ - `scripts/check` and the integration tests pass, and the app's changelog names the strata-python version it moved to.
365
+
366
+ ### Keep it current
367
+
368
+ 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.
369
+
370
+ ## Develop
371
+
372
+ `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.