strata-python 0.2.7__py3-none-any.whl → 0.2.8__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.
@@ -142,6 +142,42 @@ def run(
142
142
  return wait(int(submit(role, params, app, priority, model)["id"]), timeout)
143
143
 
144
144
 
145
+ @dataclass(frozen=True)
146
+ class Provenance:
147
+ """What a run job's output was made with, from its row: the model key, its load options as the job ran (the
148
+ service's models.toml options merged with the job's own) and `settings_hash`, which changes when the model's
149
+ runtime, file or options do even under the same key. Key a cache on (model, settings_hash). The options and hash
150
+ are None on rows from a service older than the one that records them."""
151
+
152
+ model: str | None
153
+ options: Json | None
154
+ settings_hash: str | None
155
+ job_id: int
156
+
157
+ @classmethod
158
+ def from_job(cls, job: Json) -> Provenance:
159
+ options = job.get("options")
160
+ return cls(
161
+ _opt_str(job, "model"), cast("Json", options) if isinstance(options, dict) else None,
162
+ _opt_str(job, "settings_hash"), int(job["id"]),
163
+ ) # fmt: skip
164
+
165
+
166
+ def run_with_provenance(
167
+ role: str,
168
+ params: Mapping[str, Any] | None,
169
+ app: str,
170
+ priority: Priority = "normal",
171
+ model: str | None = None,
172
+ timeout: float | None = None,
173
+ ) -> tuple[Json, Provenance]:
174
+ """`run`, plus what the result was made with (`Provenance`): for an app that stores each result with its model
175
+ and settings, and keys its cache on them."""
176
+ job_id = int(submit(role, params, app, priority, model)["id"])
177
+ result = wait(job_id, timeout)
178
+ return result, Provenance.from_job(_call("GET", f"/api/jobs/{job_id}"))
179
+
180
+
145
181
  ROLES = (
146
182
  "faces",
147
183
  "face-kind",
@@ -338,6 +374,24 @@ def role_model(role: str) -> str | None:
338
374
  return next((cast("str", r["model"]) for r in roles if r["key"] == role), None)
339
375
 
340
376
 
377
+ @dataclass(frozen=True)
378
+ class RoleSettings:
379
+ """The model that serves a role now and its `settings_hash` (see `Provenance`); the hash is None from a service
380
+ older than the one that reports it."""
381
+
382
+ model: str
383
+ settings_hash: str | None
384
+
385
+
386
+ def role_settings(role: str) -> RoleSettings | None:
387
+ """`role_model` with the settings hash: a cache keyed on both is made again when the role's model changes, and
388
+ also when that model's options change under the same key (a threshold in the service's models.toml). None for an
389
+ unknown role."""
390
+ roles = cast("list[Json]", _call("GET", "/api/registry").get("roles", []))
391
+ r = next((r for r in roles if r["key"] == role), None)
392
+ return None if r is None else RoleSettings(str(r["model"]), _opt_str(r, "settings_hash"))
393
+
394
+
341
395
  class Lease:
342
396
  """A held lease: `.id`, `.job` (the row when granted). Heartbeats run on a daemon thread until `release()`."""
343
397
 
strata_python/testing.py CHANGED
@@ -34,7 +34,7 @@ from collections.abc import Callable, Mapping, Sequence
34
34
  from dataclasses import dataclass, field
35
35
  from email.message import Message
36
36
  from pathlib import Path
37
- from typing import Any, ClassVar
37
+ from typing import Any, ClassVar, cast
38
38
 
39
39
  Body = bytes | str | Any # bytes and str are sent as they are; anything else as JSON
40
40
 
@@ -328,13 +328,17 @@ class FakeModels:
328
328
 
329
329
  `running_polls` is how many polls a job answers `running` before it finishes (default 1, as the real service
330
330
  usually is when the first poll arrives). A role with no result is refused with a 422, as the service refuses a role
331
- it does not know. The registry answers each role's model from `.models` (role -> model name)."""
331
+ it does not know. The registry answers each role's model from `.models` (role -> model name). A job records the
332
+ settings it ran with when it starts, as the service does: `options` (`.options[role]`, the role's load options,
333
+ merged with the job's own) and `settings_hash` (a hash of the model and those options, also on the registry's roles),
334
+ so changing `.options` mid-test shows what an app's cache does when the service's settings change."""
332
335
 
333
336
  def __init__(self, results: Mapping[str, Result] | None = None, *, running_polls: int = 1) -> None:
334
337
  from fastapi import FastAPI, HTTPException, Request # here, so importing the fakes does not load FastAPI
335
338
 
336
339
  self.results: dict[str, Result] = dict(MODELS_RESULTS if results is None else results)
337
340
  self.models: dict[str, str] = {}
341
+ self.options: dict[str, Json] = {} # role -> the model's load options (the service's models.toml)
338
342
  self.running_polls = running_polls
339
343
  self.jobs: list[Json] = [] # every job submitted, in order, as the service stored it
340
344
  self.leases: list[Json] = []
@@ -345,6 +349,7 @@ class FakeModels:
345
349
  self.down = False
346
350
  self._failures: list[tuple[str | None, str]] = []
347
351
  self._polls: dict[int, int] = {}
352
+ self._asked: dict[int, Json] = {} # job id -> the load options its submit asked for
348
353
  app = FastAPI()
349
354
  self.app = app
350
355
 
@@ -362,14 +367,25 @@ class FakeModels:
362
367
 
363
368
  @app.get("/api/registry")
364
369
  def registry() -> Json: # pyright: ignore[reportUnusedFunction]
365
- return {"roles": [{"key": r, "model": self.models.get(r, f"fake-{r}")} for r in self.results]}
370
+ return {
371
+ "roles": [{"key": r, "model": self._model(r), "settings_hash": self._hash(r)} for r in self.results]
372
+ }
366
373
 
367
374
  @app.post("/api/jobs")
368
375
  def submit(body: Json) -> Json: # pyright: ignore[reportUnusedFunction]
369
376
  role = str(body.get("role"))
370
377
  if role not in self.results:
371
378
  raise HTTPException(422, f"unknown role {role!r}")
372
- job: Json = {**body, "id": len(self.jobs) + 1, "status": "queued", "result": None, "error": None}
379
+ job: Json = {
380
+ **body,
381
+ "id": len(self.jobs) + 1,
382
+ "status": "queued",
383
+ "result": None,
384
+ "error": None,
385
+ "options": None, # what it runs with, recorded when it starts; the variant asked for is kept apart
386
+ "settings_hash": None,
387
+ }
388
+ self._asked[job["id"]] = cast("Json", body.get("options") or {})
373
389
  self.jobs.append(job)
374
390
  return dict(job)
375
391
 
@@ -378,6 +394,8 @@ class FakeModels:
378
394
  job = self._job(job_id, HTTPException)
379
395
  if job["status"] in ("queued", "running"):
380
396
  n = self._polls[job_id] = self._polls.get(job_id, 0) + 1
397
+ if job["status"] == "queued":
398
+ self._start(job)
381
399
  if n <= self.running_polls:
382
400
  job["status"] = "running"
383
401
  else:
@@ -414,6 +432,24 @@ class FakeModels:
414
432
  self._failures.append((role, error))
415
433
  return self
416
434
 
435
+ def _model(self, role: str, model: object = None) -> str:
436
+ return str(model) if model else self.models.get(role, f"fake-{role}")
437
+
438
+ def _hash(self, role: str, model: object = None, asked: Json | None = None) -> str:
439
+ import hashlib
440
+
441
+ options = {**self.options.get(role, {}), **(asked or {})}
442
+ text = json.dumps([self._model(role, model), options], sort_keys=True, default=str)
443
+ return hashlib.sha256(text.encode()).hexdigest()[:12]
444
+
445
+ def _start(self, job: Json) -> None:
446
+ role, asked = str(job["role"]), self._asked.get(int(job["id"]), {})
447
+ job.update(
448
+ model=self._model(role, job.get("model")),
449
+ options={**self.options.get(role, {}), **asked},
450
+ settings_hash=self._hash(role, job.get("model"), asked),
451
+ )
452
+
417
453
  def _finish(self, job: Json) -> None:
418
454
  for i, (role, error) in enumerate(self._failures):
419
455
  if role is None or role == job["role"]:
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: strata-python
3
- Version: 0.2.7
3
+ Version: 0.2.8
4
4
  Summary: Common code for Python web server apps: OS helpers, settings, FastAPI serving, CLI commands, test fixtures and the strata-check gate
5
5
  Project-URL: Homepage, https://github.com/jburnhams/strata-python
6
6
  Project-URL: Source, https://github.com/jburnhams/strata-python
@@ -64,7 +64,7 @@ Common code for the strata Python web server apps (FastAPI + CLI), the Python co
64
64
  | `strata_python.mediatime` | Exact time for media: `rational` seconds (Fraction), `Rate` (`frame_at`, `time_of`, `snap`), half-open `Span`, and `TimeMap` from an edit's output time to its sources and back, with exact JSON |
65
65
  | `strata_python.images` (extra `[images]`) | `thumbnail(src, px, cache_dir=...)` (an upright JPEG, made once, keyed on the file, never enlarged, the app's own reader through `make=`), `open_upright`, `flatten` (alpha and 16-bit greys to 8-bit RGB), `jpeg_bytes` |
66
66
  | `strata_python.stats` | Pairwise rankings and eval statistics in pure Python: `bradley_terry` (ties, an optional side advantage, Elo-scale `ratings()`), `intervals` (bootstrap), `head_to_head`, `votes_from(judgments)`, `wilson`, `mcnemar`, `holm` |
67
- | `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 |
67
+ | `strata_python.clients.models` | The strata-models client, standard library only: `run`, `submit`, `wait`, `role_model`, `run_with_provenance` and `role_settings` (the model and settings a result was made with, for cache keys), `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 |
68
68
  | `strata_python.http_server` / `live` | A real scripted HTTP server and a real uvicorn server on loopback, for tests that make actual requests |
69
69
  | 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` |
70
70
  | `strata_python.testing` | The fakes behind those fixtures (`FakeResponse`, `http_error`, `FakeUrlopen`, `FakePopen`, `FakeRun`, `Sleeper`) `FakeModels`, the CLI runners `run_cli(main, *args)` and `run_module("myapp", *args, src=...)`, and `assert_openapi_current(create_app, path)` |
@@ -406,6 +406,7 @@ migrations = "migrations" # the app's Alembic revisions, unchanged
406
406
 
407
407
  add_database(app, Project.load(__file__), default=lambda: local_url(SETTINGS))
408
408
 
409
+
409
410
  @app.get("/api/notes")
410
411
  def notes(db: DbSession) -> list[NoteOut]: ...
411
412
  ```
@@ -16,10 +16,10 @@ strata_python/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
16
16
  strata_python/pytest_plugin.py,sha256=BaD-XokrX1PMMj0Cqxj9IJTb6EXBp7ozQZ6SSCDumMg,7223
17
17
  strata_python/settings.py,sha256=YeQMJwyqFNX7L3bbgbwRN1hdfzBem9uWxqg_WVswT-A,18688
18
18
  strata_python/stats.py,sha256=nc6qXELpMg7eK0xjFo45M1FK7FR3q89be3VCJzExKYc,8354
19
- strata_python/testing.py,sha256=WvakeIAJtdeOrIDq32WWXfWkfBkMQ2cUU279L0Ebhs0,20888
19
+ strata_python/testing.py,sha256=GpqljUX07FuOWZaizC4wHQJvT03NdBpKi31TgZPpi80,22715
20
20
  strata_python/web.py,sha256=RkT8cR6gZ0MNYnUDMtKjAu9pIkPmdh0coxkoB5cyA9c,15252
21
21
  strata_python/clients/__init__.py,sha256=xivuysmYG7rbCGProVNvdSs-h4xVFQsuqUY6EwzuJbk,182
22
- strata_python/clients/models.py,sha256=vxnvINQ_xQRbU848BTnGyjlTcr1-bhv6GAkrCN5ZDuU,30314
22
+ strata_python/clients/models.py,sha256=sHhU1Lfw_0y3lkTQ74Q0OcOV4KjviV6Qq93V_D1mV3Y,32531
23
23
  strata_python/db/__init__.py,sha256=Vx28OmktWBhEM9gj1VxoxNuJDvdtpYoJ3-prrzoBR40,4009
24
24
  strata_python/db/__main__.py,sha256=nHCtenRtjL_Ouig4FHh60dax2oILeVdoIIKrxXEc6Ss,106
25
25
  strata_python/db/cli.py,sha256=kCNHDlFIzECtvExUGBaJ0BK4ZqesGHS7Jjnhh-gWIpI,10896
@@ -48,8 +48,8 @@ strata_python/tasks/queue.py,sha256=b4in3XnplTlapL_ECTs_WYJcittYj3iKz7q_fQ8_HDY,
48
48
  strata_python/tasks/retry.py,sha256=NztmOf3Q-rl5y3CZlfP1qcDqPT0jOiIDjMfD-MUkr5s,3995
49
49
  strata_python/tasks/status.py,sha256=cZvYghNAGJRlpVIJAtUSb5pW19UbxR6bNQU4etJMYN4,7440
50
50
  strata_python/tasks/ticker.py,sha256=V6JLWgAGV5sIGeX1vp4t35omuRvvB6AYWv_lzJAq69Y,2860
51
- strata_python-0.2.7.dist-info/METADATA,sha256=KJyNArSUBEJAYXd2P2g3qWjKkodz34nNxrdG32aWX6w,38107
52
- strata_python-0.2.7.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
53
- strata_python-0.2.7.dist-info/entry_points.txt,sha256=6RVv-uDumVQ-KY2YdvKwd5R3l6P9WQD4kPtPOKKEM-I,256
54
- strata_python-0.2.7.dist-info/licenses/LICENSE,sha256=9yVMCPoK7unONyTAiDYjMTt3MZPGJ639nWOwxyNsZGg,1066
55
- strata_python-0.2.7.dist-info/RECORD,,
51
+ strata_python-0.2.8.dist-info/METADATA,sha256=2PGi5Y3ToKWuYgyURHJju0dGXAMOXhjTEIa7w2V2v_Q,38215
52
+ strata_python-0.2.8.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
53
+ strata_python-0.2.8.dist-info/entry_points.txt,sha256=6RVv-uDumVQ-KY2YdvKwd5R3l6P9WQD4kPtPOKKEM-I,256
54
+ strata_python-0.2.8.dist-info/licenses/LICENSE,sha256=9yVMCPoK7unONyTAiDYjMTt3MZPGJ639nWOwxyNsZGg,1066
55
+ strata_python-0.2.8.dist-info/RECORD,,