hsmmkit 0.5.0__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.
- hsmmkit/__init__.py +13 -0
- hsmmkit/cli/__init__.py +1 -0
- hsmmkit/cli/app.py +513 -0
- hsmmkit/cli/stream.py +194 -0
- hsmmkit/config/__init__.py +1 -0
- hsmmkit/config/defaults.py +13 -0
- hsmmkit/config/gates.py +39 -0
- hsmmkit/config/migrate.py +53 -0
- hsmmkit/config/schema.py +996 -0
- hsmmkit/config/yaml_io.py +67 -0
- hsmmkit/data/__init__.py +1 -0
- hsmmkit/data/batch.py +311 -0
- hsmmkit/data/calendar.py +314 -0
- hsmmkit/data/clocks.py +165 -0
- hsmmkit/data/contracts.py +543 -0
- hsmmkit/data/labels.py +150 -0
- hsmmkit/data/prepare.py +706 -0
- hsmmkit/data/provenance.py +34 -0
- hsmmkit/data/quality.py +112 -0
- hsmmkit/data/sources/__init__.py +92 -0
- hsmmkit/data/sources/base.py +247 -0
- hsmmkit/data/sources/csv.py +36 -0
- hsmmkit/data/sources/numpy.py +143 -0
- hsmmkit/data/sources/pandas.py +33 -0
- hsmmkit/data/sources/parquet.py +37 -0
- hsmmkit/data/sources/xarray.py +62 -0
- hsmmkit/data/transforms.py +129 -0
- hsmmkit/engine/__init__.py +1 -0
- hsmmkit/engine/approx.py +51 -0
- hsmmkit/engine/augmented.py +93 -0
- hsmmkit/engine/base.py +134 -0
- hsmmkit/engine/batch.py +414 -0
- hsmmkit/engine/constraints.py +173 -0
- hsmmkit/engine/criteria.py +67 -0
- hsmmkit/engine/estep.py +314 -0
- hsmmkit/engine/estep_explicit.py +260 -0
- hsmmkit/engine/expanded_hmm.py +336 -0
- hsmmkit/engine/explicit_dd.py +114 -0
- hsmmkit/engine/explicit_duration.py +721 -0
- hsmmkit/engine/ffbs.py +229 -0
- hsmmkit/engine/parallel.py +98 -0
- hsmmkit/engine/viterbi.py +85 -0
- hsmmkit/estimation/__init__.py +36 -0
- hsmmkit/estimation/compare.py +154 -0
- hsmmkit/estimation/ecm.py +106 -0
- hsmmkit/estimation/em.py +460 -0
- hsmmkit/estimation/gem.py +467 -0
- hsmmkit/estimation/gibbs.py +136 -0
- hsmmkit/estimation/init.py +578 -0
- hsmmkit/estimation/map.py +287 -0
- hsmmkit/estimation/mcmc.py +370 -0
- hsmmkit/estimation/mstep.py +304 -0
- hsmmkit/estimation/newton.py +104 -0
- hsmmkit/estimation/objective.py +232 -0
- hsmmkit/estimation/optimizers.py +195 -0
- hsmmkit/estimation/recovery.py +748 -0
- hsmmkit/estimation/recovery_ext.py +557 -0
- hsmmkit/estimation/relabel.py +85 -0
- hsmmkit/estimation/report.py +167 -0
- hsmmkit/estimation/results.py +53 -0
- hsmmkit/estimation/selftest.py +154 -0
- hsmmkit/estimation/vb.py +508 -0
- hsmmkit/evaluation/__init__.py +1 -0
- hsmmkit/evaluation/backtest.py +616 -0
- hsmmkit/evaluation/compare.py +172 -0
- hsmmkit/evaluation/metrics/__init__.py +1 -0
- hsmmkit/evaluation/metrics/clustering.py +111 -0
- hsmmkit/evaluation/metrics/labels.py +40 -0
- hsmmkit/evaluation/metrics/matching.py +103 -0
- hsmmkit/evaluation/metrics/model.py +53 -0
- hsmmkit/evaluation/metrics/predictive.py +337 -0
- hsmmkit/evaluation/metrics/registry.py +154 -0
- hsmmkit/evaluation/metrics/segmentation.py +182 -0
- hsmmkit/evaluation/padding.py +72 -0
- hsmmkit/evaluation/report.py +170 -0
- hsmmkit/evaluation/results.py +28 -0
- hsmmkit/inference/__init__.py +1 -0
- hsmmkit/inference/covariate_forecasters.py +344 -0
- hsmmkit/inference/decode.py +185 -0
- hsmmkit/inference/forecast.py +475 -0
- hsmmkit/inference/results.py +97 -0
- hsmmkit/inference/simulate.py +342 -0
- hsmmkit/interop/__init__.py +1 -0
- hsmmkit/interop/arviz.py +114 -0
- hsmmkit/interop/hmmlearn.py +163 -0
- hsmmkit/interop/pandas.py +116 -0
- hsmmkit/interop/sklearn.py +505 -0
- hsmmkit/interop/xarray.py +296 -0
- hsmmkit/model/__init__.py +1 -0
- hsmmkit/model/build.py +404 -0
- hsmmkit/model/conjugate.py +260 -0
- hsmmkit/model/dists.py +244 -0
- hsmmkit/model/duration/__init__.py +23 -0
- hsmmkit/model/duration/base.py +215 -0
- hsmmkit/model/duration/explicit.py +205 -0
- hsmmkit/model/duration/gamma.py +53 -0
- hsmmkit/model/duration/geometric.py +106 -0
- hsmmkit/model/duration/hazard.py +23 -0
- hsmmkit/model/duration/lognormal.py +56 -0
- hsmmkit/model/duration/negbin.py +115 -0
- hsmmkit/model/duration/nonparametric.py +120 -0
- hsmmkit/model/duration/per_state.py +107 -0
- hsmmkit/model/duration/poisson.py +56 -0
- hsmmkit/model/duration/weibull.py +61 -0
- hsmmkit/model/emission/__init__.py +24 -0
- hsmmkit/model/emission/_discrete.py +104 -0
- hsmmkit/model/emission/base.py +105 -0
- hsmmkit/model/emission/bernoulli.py +131 -0
- hsmmkit/model/emission/categorical.py +158 -0
- hsmmkit/model/emission/gaussian.py +754 -0
- hsmmkit/model/emission/mixture.py +387 -0
- hsmmkit/model/emission/msar.py +545 -0
- hsmmkit/model/emission/poisson.py +144 -0
- hsmmkit/model/emission/product.py +390 -0
- hsmmkit/model/emission/student_t.py +454 -0
- hsmmkit/model/lattice.py +246 -0
- hsmmkit/model/params/__init__.py +45 -0
- hsmmkit/model/params/bijectors.py +238 -0
- hsmmkit/model/params/manager.py +307 -0
- hsmmkit/model/params/priors.py +84 -0
- hsmmkit/model/params/spec.py +65 -0
- hsmmkit/model/spec.py +43 -0
- hsmmkit/model/topology.py +97 -0
- hsmmkit/model/transition.py +419 -0
- hsmmkit/online/__init__.py +24 -0
- hsmmkit/online/alerts.py +181 -0
- hsmmkit/online/buffer.py +203 -0
- hsmmkit/online/covariates.py +162 -0
- hsmmkit/online/em.py +304 -0
- hsmmkit/online/filter.py +682 -0
- hsmmkit/online/session.py +364 -0
- hsmmkit/online/state.py +240 -0
- hsmmkit/persistence/__init__.py +1 -0
- hsmmkit/persistence/results.py +495 -0
- hsmmkit/persistence/store.py +394 -0
- hsmmkit/plot/__init__.py +13 -0
- hsmmkit/plot/_common.py +56 -0
- hsmmkit/plot/diagnostics.py +176 -0
- hsmmkit/plot/durations.py +74 -0
- hsmmkit/plot/forecast.py +55 -0
- hsmmkit/plot/regimes.py +146 -0
- hsmmkit/plugins.py +311 -0
- hsmmkit/presets/__init__.py +116 -0
- hsmmkit/presets/core/counts_poisson_hazard.yaml +61 -0
- hsmmkit/presets/core/msar2_hamilton.yaml +59 -0
- hsmmkit/presets/core/segmentation_gaussian_ltr.yaml +82 -0
- hsmmkit/presets/core/two_regime_gaussian.yaml +60 -0
- hsmmkit/presets/fixtures.py +330 -0
- hsmmkit/project.py +1106 -0
- hsmmkit/py.typed +0 -0
- hsmmkit/scaffold.py +80 -0
- hsmmkit/selection/__init__.py +30 -0
- hsmmkit/selection/bootstrap.py +388 -0
- hsmmkit/selection/cv.py +301 -0
- hsmmkit/selection/grid.py +412 -0
- hsmmkit/selection/ppc.py +199 -0
- hsmmkit/selection/pseudo_residuals.py +265 -0
- hsmmkit/selection/replicate.py +57 -0
- hsmmkit/selection/splitters.py +213 -0
- hsmmkit/statespace/__init__.py +1 -0
- hsmmkit/statespace/builders.py +317 -0
- hsmmkit/statespace/factorial.py +249 -0
- hsmmkit/statespace/index.py +85 -0
- hsmmkit/statespace/transitions.py +143 -0
- hsmmkit/templates/family-plugin/common/README.md.tmpl +9 -0
- hsmmkit/templates/family-plugin/common/pyproject.toml.tmpl +19 -0
- hsmmkit/templates/family-plugin/common/src/__pkg__/__init__.py.tmpl +7 -0
- hsmmkit/templates/family-plugin/common/src/__pkg__/tests/__init__.py.tmpl +0 -0
- hsmmkit/templates/family-plugin/duration/family.py.tmpl +19 -0
- hsmmkit/templates/family-plugin/duration/test_contract.py.tmpl +14 -0
- hsmmkit/templates/family-plugin/emission/family.py.tmpl +95 -0
- hsmmkit/templates/family-plugin/emission/test_contract.py.tmpl +48 -0
- hsmmkit/testing/__init__.py +6 -0
- hsmmkit/testing/clock_contract.py +53 -0
- hsmmkit/testing/duration_contract.py +218 -0
- hsmmkit/testing/family_contract.py +339 -0
- hsmmkit/testing/metric_contract.py +157 -0
- hsmmkit/testing/source_contract.py +196 -0
- hsmmkit/utils/__init__.py +1 -0
- hsmmkit/utils/clock.py +109 -0
- hsmmkit/utils/deprecation.py +125 -0
- hsmmkit/utils/errors.py +56 -0
- hsmmkit/utils/jax_setup.py +48 -0
- hsmmkit/utils/logging.py +30 -0
- hsmmkit/utils/optional.py +25 -0
- hsmmkit/utils/rng.py +49 -0
- hsmmkit/utils/typing.py +32 -0
- hsmmkit-0.5.0.dist-info/METADATA +84 -0
- hsmmkit-0.5.0.dist-info/RECORD +192 -0
- hsmmkit-0.5.0.dist-info/WHEEL +4 -0
- hsmmkit-0.5.0.dist-info/entry_points.txt +2 -0
- hsmmkit-0.5.0.dist-info/licenses/LICENSE +190 -0
hsmmkit/cli/stream.py
ADDED
|
@@ -0,0 +1,194 @@
|
|
|
1
|
+
"""`hsmmkit stream`: CSV rows from stdin or a (growing) file -> JSONL regime probabilities and alert events.
|
|
2
|
+
|
|
3
|
+
Concept refs: Part II §14.11; Part I §5.9. One line per processed row on stdout (`t`, `time`, `filtered`,
|
|
4
|
+
`smoothed_lag`, `events`); diagnostics go to stderr so a pipe stays clean. `--state` resumes from, and
|
|
5
|
+
checkpoints into, a state directory (`online.checkpoint_every` rows, and on exit or SIGINT / SIGTERM).
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import csv
|
|
11
|
+
import json
|
|
12
|
+
import signal
|
|
13
|
+
import sys
|
|
14
|
+
import threading
|
|
15
|
+
import time
|
|
16
|
+
from pathlib import Path
|
|
17
|
+
from typing import IO, TYPE_CHECKING, Any
|
|
18
|
+
|
|
19
|
+
import typer
|
|
20
|
+
|
|
21
|
+
from hsmmkit.utils.errors import ConfigError, DataError
|
|
22
|
+
|
|
23
|
+
if TYPE_CHECKING:
|
|
24
|
+
from collections.abc import Callable
|
|
25
|
+
from contextlib import AbstractContextManager
|
|
26
|
+
|
|
27
|
+
from hsmmkit.cli.app import CliApp
|
|
28
|
+
from hsmmkit.online.session import OnlineSession
|
|
29
|
+
|
|
30
|
+
POLL_SECONDS = 0.5
|
|
31
|
+
EMIT_FIELDS = ("filtered", "smoothed", "events", "params")
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def _parse_emit(value: str) -> set[str]:
|
|
35
|
+
fields = {f.strip() for f in value.split(",") if f.strip()}
|
|
36
|
+
unknown = fields - set(EMIT_FIELDS)
|
|
37
|
+
if unknown:
|
|
38
|
+
raise ConfigError(
|
|
39
|
+
f"unknown --emit field(s) {sorted(unknown)}; allowed: {', '.join(EMIT_FIELDS)}", path="--emit"
|
|
40
|
+
)
|
|
41
|
+
return fields
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def _lines(stream: IO[str], follow: bool, stop: list[bool]) -> Any: # noqa: ANN401
|
|
45
|
+
"""Yield complete lines; with `follow` wait for more at the end of the file until `stop[0]`."""
|
|
46
|
+
buffer = ""
|
|
47
|
+
while not stop[0]:
|
|
48
|
+
chunk = stream.readline()
|
|
49
|
+
if chunk:
|
|
50
|
+
buffer += chunk
|
|
51
|
+
if buffer.endswith("\n"):
|
|
52
|
+
yield buffer.rstrip("\r\n")
|
|
53
|
+
buffer = ""
|
|
54
|
+
continue
|
|
55
|
+
if not follow:
|
|
56
|
+
break
|
|
57
|
+
time.sleep(POLL_SECONDS)
|
|
58
|
+
if buffer and not follow:
|
|
59
|
+
yield buffer.rstrip("\r\n")
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
def _emit_line(result: dict[str, Any], emit: set[str]) -> str:
|
|
63
|
+
return json.dumps(
|
|
64
|
+
{
|
|
65
|
+
"t": result["t"],
|
|
66
|
+
"time": result["time"],
|
|
67
|
+
"filtered": result["filtered"] if "filtered" in emit else None,
|
|
68
|
+
"smoothed_lag": result["smoothed_lag"] if "smoothed" in emit else None,
|
|
69
|
+
"events": result["events"] if "events" in emit else [],
|
|
70
|
+
**({"params": result.get("params")} if "params" in emit else {}),
|
|
71
|
+
}
|
|
72
|
+
)
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
def run_stream(
|
|
76
|
+
session: OnlineSession,
|
|
77
|
+
stream: IO[str],
|
|
78
|
+
out: IO[str],
|
|
79
|
+
*,
|
|
80
|
+
emit: set[str],
|
|
81
|
+
every: int,
|
|
82
|
+
strict: bool,
|
|
83
|
+
follow: bool,
|
|
84
|
+
state_dir: Path | None,
|
|
85
|
+
checkpoint_every: int,
|
|
86
|
+
) -> int:
|
|
87
|
+
"""Process the CSV `stream` (header first) and write JSONL to `out`; returns the number of rows pushed."""
|
|
88
|
+
stop = [False]
|
|
89
|
+
session.emit_params = "params" in emit
|
|
90
|
+
|
|
91
|
+
def request_stop(signum: int, frame: Any) -> None: # noqa: ANN401
|
|
92
|
+
# raising (not just flagging) also ends a `readline()` blocked on an idle pipe; the `finally` below
|
|
93
|
+
# saves the state and the command exits normally
|
|
94
|
+
stop[0] = True
|
|
95
|
+
raise KeyboardInterrupt
|
|
96
|
+
|
|
97
|
+
previous: dict[int, Any] = {}
|
|
98
|
+
if threading.current_thread() is threading.main_thread():
|
|
99
|
+
previous = {s: signal.signal(s, request_stop) for s in (signal.SIGINT, signal.SIGTERM)}
|
|
100
|
+
pushed = 0
|
|
101
|
+
try:
|
|
102
|
+
lines = _lines(stream, follow, stop)
|
|
103
|
+
header_line = next(lines, None)
|
|
104
|
+
if header_line is None:
|
|
105
|
+
raise DataError("the input is empty (no header line)", path="--input")
|
|
106
|
+
header = next(csv.reader([header_line]))
|
|
107
|
+
missing = [c for c in session.required_columns if c not in header]
|
|
108
|
+
if missing:
|
|
109
|
+
raise DataError(f"missing column {missing[0]!r} in the input header {header}", path=missing[0])
|
|
110
|
+
emitted = 0
|
|
111
|
+
for number, line in enumerate(lines, start=2):
|
|
112
|
+
if not line.strip():
|
|
113
|
+
continue
|
|
114
|
+
fields = next(csv.reader([line]))
|
|
115
|
+
try:
|
|
116
|
+
if len(fields) != len(header):
|
|
117
|
+
raise DataError(
|
|
118
|
+
f"line {number}: {len(fields)} fields, expected {len(header)}", path="--input"
|
|
119
|
+
)
|
|
120
|
+
result = session.push(dict(zip(header, fields, strict=True)))
|
|
121
|
+
except DataError as exc:
|
|
122
|
+
if strict:
|
|
123
|
+
raise
|
|
124
|
+
print(f"skipped line {number}: {exc}", file=sys.stderr)
|
|
125
|
+
continue
|
|
126
|
+
pushed += 1
|
|
127
|
+
if result["filtered"] is None:
|
|
128
|
+
continue
|
|
129
|
+
emitted += 1
|
|
130
|
+
if emitted % every == 0 or result["events"]:
|
|
131
|
+
out.write(_emit_line(result, emit) + "\n")
|
|
132
|
+
out.flush()
|
|
133
|
+
if state_dir is not None and pushed % checkpoint_every == 0:
|
|
134
|
+
session.save(state_dir)
|
|
135
|
+
except KeyboardInterrupt:
|
|
136
|
+
pass # SIGINT / SIGTERM: stop reading, flush, save
|
|
137
|
+
finally:
|
|
138
|
+
for sig, handler in previous.items():
|
|
139
|
+
signal.signal(sig, handler)
|
|
140
|
+
if state_dir is not None:
|
|
141
|
+
session.save(state_dir)
|
|
142
|
+
return pushed
|
|
143
|
+
|
|
144
|
+
|
|
145
|
+
def add_stream_command(app: CliApp, exit_on_error: Callable[[], AbstractContextManager[None]]) -> None:
|
|
146
|
+
"""Register `stream` on `app` (called by `build_app`, so every application inherits it).
|
|
147
|
+
|
|
148
|
+
`exit_on_error` is the error-to-exit-code context manager of `hsmmkit.cli.app` (passed in so that this
|
|
149
|
+
module does not import the app module, which `python -m hsmmkit.cli.app` runs as `__main__`).
|
|
150
|
+
"""
|
|
151
|
+
ctx = app.context
|
|
152
|
+
|
|
153
|
+
@app.command("stream")
|
|
154
|
+
def stream_cmd(
|
|
155
|
+
config_path: Path,
|
|
156
|
+
model: Path = typer.Option(..., "--model", help="Model bundle directory."),
|
|
157
|
+
input_: str = typer.Option("-", "--input", help="CSV file, or - for stdin."),
|
|
158
|
+
follow: bool = typer.Option(False, "--follow", help="Tail a growing file (poll 0.5 s)."),
|
|
159
|
+
state: Path | None = typer.Option(
|
|
160
|
+
None, "--state", help="State directory: resume if it exists, save on exit."
|
|
161
|
+
),
|
|
162
|
+
emit: str = typer.Option("filtered,smoothed,events", "--emit", help="Fields to emit."),
|
|
163
|
+
every: int = typer.Option(1, "--every", min=1, help="Emit every k-th row (events always)."),
|
|
164
|
+
strict: bool = typer.Option(False, "--strict", help="A malformed row is an error (exit 3)."),
|
|
165
|
+
) -> None:
|
|
166
|
+
"""Stream rows through the online filter: JSONL of filtered / smoothed probabilities and events."""
|
|
167
|
+
with exit_on_error():
|
|
168
|
+
fields = _parse_emit(emit)
|
|
169
|
+
if not model.exists():
|
|
170
|
+
raise ConfigError(f"model bundle not found: {model}", path="--model")
|
|
171
|
+
project = ctx.project(config_path, logging=False)
|
|
172
|
+
fit = ctx.project_cls.load(model)
|
|
173
|
+
nominal_dt = None
|
|
174
|
+
if project.config.data.clock != "steps":
|
|
175
|
+
nominal_dt = ctx.load_prepared(project).nominal_dt
|
|
176
|
+
session = project.online(fit, nominal_dt=nominal_dt)
|
|
177
|
+
if state is not None and (state / "state.json").exists():
|
|
178
|
+
session.load(state)
|
|
179
|
+
online_cfg = project.config.online
|
|
180
|
+
checkpoint = online_cfg.checkpoint_every if online_cfg else 1000
|
|
181
|
+
if input_ == "-":
|
|
182
|
+
run_stream(
|
|
183
|
+
session, sys.stdin, sys.stdout, emit=fields, every=every, strict=strict,
|
|
184
|
+
follow=follow, state_dir=state, checkpoint_every=checkpoint,
|
|
185
|
+
) # fmt: skip
|
|
186
|
+
return
|
|
187
|
+
path = Path(input_)
|
|
188
|
+
if not path.is_file():
|
|
189
|
+
raise DataError(f"input file not found: {path}", path="--input")
|
|
190
|
+
with path.open(encoding="utf-8", newline="") as fh:
|
|
191
|
+
run_stream(
|
|
192
|
+
session, fh, sys.stdout, emit=fields, every=every, strict=strict,
|
|
193
|
+
follow=follow, state_dir=state, checkpoint_every=checkpoint,
|
|
194
|
+
) # fmt: skip
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"""Configuration schema, YAML I/O and migration."""
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
"""Numeric defaults referenced by `config/schema.py` cross-field validation."""
|
|
2
|
+
|
|
3
|
+
D_MAX_CAP = 500
|
|
4
|
+
"""Hard cap on the default `model.d_max` (overview §5.7)."""
|
|
5
|
+
|
|
6
|
+
D_MAX_SOJOURN_MULTIPLIER = 10
|
|
7
|
+
"""`d_max` defaults to `min(D_MAX_CAP, D_MAX_SOJOURN_MULTIPLIER * expected_sojourn_steps)`."""
|
|
8
|
+
|
|
9
|
+
D_MAX_WARN_SOJOURN_MULTIPLIER = 2
|
|
10
|
+
"""Warn when `d_max < D_MAX_WARN_SOJOURN_MULTIPLIER * max(expected_sojourn_steps)`."""
|
|
11
|
+
|
|
12
|
+
MAX_ORDER_WARN = 2
|
|
13
|
+
"""Warn when `transition.order > MAX_ORDER_WARN`."""
|
hsmmkit/config/gates.py
ADDED
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
"""Feature gates (E10-T10, Part II overview §5.11).
|
|
2
|
+
|
|
3
|
+
The schema accepts every key of the final `hsmmkit` schema 1 from E10-T10 on, so presets and the JSON
|
|
4
|
+
Schema validate. A key whose implementation has not landed is rejected when the model is **built**
|
|
5
|
+
(`check`), not when the config is validated. Each ticket that implements a feature removes its own row
|
|
6
|
+
from `GATES` and adds a test that the key now builds.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
from collections.abc import Callable
|
|
12
|
+
|
|
13
|
+
from hsmmkit.config.schema import ProjectConfig
|
|
14
|
+
from hsmmkit.utils.errors import ConfigError
|
|
15
|
+
|
|
16
|
+
__all__ = ["GATES", "check", "used_gates"]
|
|
17
|
+
|
|
18
|
+
Gate = tuple[Callable[[ProjectConfig], bool], str]
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
GATES: dict[str, Gate] = {}
|
|
22
|
+
"""Key path (or `key=value`) -> (predicate "the feature is used", ticket that removes the row). Ordered."""
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def used_gates(cfg: ProjectConfig) -> list[tuple[str, str]]:
|
|
26
|
+
"""`(path, ticket)` of every gated feature that `cfg` uses, in the order of `GATES`."""
|
|
27
|
+
return [(path, ticket) for path, (used, ticket) in GATES.items() if used(cfg)]
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def check(cfg: ProjectConfig) -> None:
|
|
31
|
+
"""Reject the first gated feature that `cfg` uses.
|
|
32
|
+
|
|
33
|
+
Raises:
|
|
34
|
+
ConfigError: `path` = the gated key, "not available before <ticket>".
|
|
35
|
+
"""
|
|
36
|
+
used = used_gates(cfg)
|
|
37
|
+
if used:
|
|
38
|
+
path, ticket = used[0]
|
|
39
|
+
raise ConfigError(f"not available before {ticket}", path=path.partition("=")[0])
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
"""`schema_version` migration hook: applies registered `v -> v+1` steps until the config class is current.
|
|
2
|
+
|
|
3
|
+
Migrations are registered per schema id (`ProjectConfig.SCHEMA_ID`: `"core"` for the core, an application's
|
|
4
|
+
own id for its subclass), so the core never sees an application's older layouts (D24).
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
from collections.abc import Callable
|
|
10
|
+
from typing import TYPE_CHECKING, Any
|
|
11
|
+
|
|
12
|
+
from hsmmkit.utils.errors import ConfigError
|
|
13
|
+
|
|
14
|
+
if TYPE_CHECKING:
|
|
15
|
+
from hsmmkit.config.schema import ProjectConfig
|
|
16
|
+
|
|
17
|
+
CURRENT_SCHEMA_VERSION = 1 # of the core schema (`ProjectConfig.SCHEMA_VERSION`)
|
|
18
|
+
|
|
19
|
+
MigrationStep = Callable[[dict[str, Any]], dict[str, Any]]
|
|
20
|
+
|
|
21
|
+
_MIGRATIONS: dict[tuple[str, int], MigrationStep] = {}
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def register_migration(schema_id: str, from_version: int) -> Callable[[MigrationStep], MigrationStep]:
|
|
25
|
+
"""Register `fn` as the migration of schema `schema_id` from `from_version` to `from_version + 1`."""
|
|
26
|
+
|
|
27
|
+
def decorator(fn: MigrationStep) -> MigrationStep:
|
|
28
|
+
_MIGRATIONS[(schema_id, from_version)] = fn
|
|
29
|
+
return fn
|
|
30
|
+
|
|
31
|
+
return decorator
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def migrate(raw: dict[str, Any], config_cls: type[ProjectConfig] | None = None) -> dict[str, Any]:
|
|
35
|
+
"""Apply registered migration steps until `schema_version == config_cls.SCHEMA_VERSION`."""
|
|
36
|
+
schema_id = "core" if config_cls is None else config_cls.SCHEMA_ID
|
|
37
|
+
current = CURRENT_SCHEMA_VERSION if config_cls is None else config_cls.SCHEMA_VERSION
|
|
38
|
+
if "schema_version" not in raw:
|
|
39
|
+
raise ConfigError("config is missing schema_version", path="schema_version")
|
|
40
|
+
version = raw["schema_version"]
|
|
41
|
+
if version > current:
|
|
42
|
+
raise ConfigError(
|
|
43
|
+
f"config newer than library (schema_version={version} > {current})", path="schema_version"
|
|
44
|
+
)
|
|
45
|
+
data = dict(raw)
|
|
46
|
+
while data["schema_version"] < current:
|
|
47
|
+
step = _MIGRATIONS.get((schema_id, data["schema_version"]))
|
|
48
|
+
if step is None:
|
|
49
|
+
raise ConfigError(
|
|
50
|
+
f"no migration registered for schema_version={data['schema_version']}", path="schema_version"
|
|
51
|
+
)
|
|
52
|
+
data = step(data)
|
|
53
|
+
return data
|