system-runtime-spec 0.1.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.
@@ -0,0 +1,105 @@
1
+ # DO NOT EDIT! This file is autogenerated.
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import Annotated, Literal, TYPE_CHECKING, Union # noqa: F401
6
+
7
+ import pydantic # noqa: F401
8
+ import pydantic_core # noqa: F401
9
+
10
+ from . import _sidex # noqa: F401
11
+
12
+
13
+ # Identifier of a runtime value, unique independently of health node IDs.
14
+ type ValueId = str
15
+
16
+
17
+ class ValueDefinition(_sidex.Model):
18
+ """A named measurement, independent of any health policy."""
19
+ model_config = pydantic.ConfigDict(populate_by_name=True, serialize_by_alias=True, defer_build=True)
20
+
21
+ id: ValueId = pydantic.Field(description="Unique value ID.")
22
+ origin: str | None = pydantic.Field(default=None, description="Ownership group for replacement or removal, matched exactly.")
23
+ label: str | None = pydantic.Field(default=None, description="Human-readable label.")
24
+ components: list[str] | None = pydantic.Field(default=None, description="Related component IDs; these associations do not imply health dependencies.")
25
+ unit: ValueUnit = pydantic.Field(description="Unit shared by observations and all thresholds referencing this value.")
26
+ max_age_ms: _sidex.U32 | None = pydantic.Field(default=None, description="Optional consumer limit on observation age, in milliseconds; must be positive.", validation_alias="maxAgeMs", serialization_alias="maxAgeMs")
27
+ expected_tag: str | None = pydantic.Field(default=None, description="Optional tag that observations must match exactly.", validation_alias="expectedTag", serialization_alias="expectedTag")
28
+
29
+
30
+ class ValueObservation(_sidex.Model):
31
+ """One measurement within a boot; publishing it does not assert health."""
32
+ model_config = pydantic.ConfigDict(populate_by_name=True, serialize_by_alias=True, defer_build=True)
33
+
34
+ id: ValueId = pydantic.Field(description="Observed value ID.")
35
+ origin: str | None = pydantic.Field(default=None, description="Ownership group; must match the definition's origin when specified.")
36
+ value: _sidex.F64 = pydantic.Field(description="Finite measurement in the definition's unit.")
37
+ boot_id: str = pydantic.Field(description="Boot identifier defining the observation clock domain.", validation_alias="bootId", serialization_alias="bootId")
38
+ observed_at_ms: _sidex.U64 = pydantic.Field(description="Milliseconds on the boot-time clock when the measurement was taken.", validation_alias="observedAtMs", serialization_alias="observedAtMs")
39
+ max_age_ms: _sidex.U32 = pydantic.Field(description="Positive validity duration in milliseconds.", validation_alias="maxAgeMs", serialization_alias="maxAgeMs")
40
+ tag: str | None = pydantic.Field(default=None, description="Opaque label identifying the measurement configuration or instance.")
41
+ message: str | None = pydantic.Field(default=None, description="Explanation supplied by the observer.")
42
+
43
+
44
+ class ValueBound(_sidex.Model):
45
+ """One endpoint of a numeric range, in the referenced value's unit."""
46
+ model_config = pydantic.ConfigDict(populate_by_name=True, serialize_by_alias=True, defer_build=True)
47
+
48
+ value: _sidex.F64 = pydantic.Field(description="Finite endpoint in the referenced value's unit.")
49
+ inclusive: _sidex.Bool = pydantic.Field(description="Whether equality with this endpoint is inside the range.")
50
+
51
+
52
+ class ValueRange(_sidex.Model):
53
+ """A nonempty interval; omitted endpoints are unbounded."""
54
+ model_config = pydantic.ConfigDict(populate_by_name=True, serialize_by_alias=True, defer_build=True)
55
+
56
+ lower: ValueBound | None = pydantic.Field(default=None, description="Optional lower endpoint.")
57
+ upper: ValueBound | None = pydantic.Field(default=None, description="Optional upper endpoint.")
58
+
59
+
60
+ class ValueUnit_Celsius(pydantic.RootModel[Literal["celsius"]]):
61
+ pass
62
+
63
+
64
+ class ValueUnit_Bytes(pydantic.RootModel[Literal["bytes"]]):
65
+ pass
66
+
67
+
68
+ class ValueUnit_Seconds(pydantic.RootModel[Literal["seconds"]]):
69
+ pass
70
+
71
+
72
+ class ValueUnit_Ratio(pydantic.RootModel[Literal["ratio"]]):
73
+ pass
74
+
75
+
76
+ class ValueUnit_Count(pydantic.RootModel[Literal["count"]]):
77
+ pass
78
+
79
+
80
+ class ValueUnit_BytesPerSecond(pydantic.RootModel[Literal["bytes-per-second"]]):
81
+ pass
82
+
83
+
84
+ class ValueUnit_Hertz(pydantic.RootModel[Literal["hertz"]]):
85
+ pass
86
+
87
+
88
+ class ValueUnit_Volts(pydantic.RootModel[Literal["volts"]]):
89
+ pass
90
+
91
+
92
+ class ValueUnit_Amperes(pydantic.RootModel[Literal["amperes"]]):
93
+ pass
94
+
95
+
96
+ class ValueUnit_Watts(pydantic.RootModel[Literal["watts"]]):
97
+ pass
98
+
99
+
100
+ class ValueUnit_RevolutionsPerMinute(pydantic.RootModel[Literal["revolutions-per-minute"]]):
101
+ pass
102
+
103
+
104
+ # Semantic unit; display prefixes, precision, and conversions are consumer choices.
105
+ type ValueUnit = ValueUnit_Celsius | ValueUnit_Bytes | ValueUnit_Seconds | ValueUnit_Ratio | ValueUnit_Count | ValueUnit_BytesPerSecond | ValueUnit_Hertz | ValueUnit_Volts | ValueUnit_Amperes | ValueUnit_Watts | ValueUnit_RevolutionsPerMinute
File without changes
@@ -0,0 +1,24 @@
1
+ """Select contributions by their ownership origin before evaluating a candidate."""
2
+
3
+ from .models.filesystem import RuntimeSnapshot
4
+
5
+
6
+ def without_origin(snapshot: RuntimeSnapshot, origin: str) -> RuntimeSnapshot:
7
+ """Remove an exact origin from all collections, preserving other constraints."""
8
+ return RuntimeSnapshot(
9
+ values=None
10
+ if snapshot.values is None
11
+ else [r for r in snapshot.values if r.origin != origin],
12
+ value_observations=None
13
+ if snapshot.value_observations is None
14
+ else [r for r in snapshot.value_observations if r.origin != origin],
15
+ components=[
16
+ record for record in snapshot.components if record.origin != origin
17
+ ],
18
+ health_nodes=[
19
+ record for record in snapshot.health_nodes if record.origin != origin
20
+ ],
21
+ health_statuses=[
22
+ record for record in snapshot.health_statuses if record.origin != origin
23
+ ],
24
+ )
@@ -0,0 +1,150 @@
1
+ """Validate numeric evidence and derive health from declared ranges."""
2
+
3
+ import math
4
+ from collections.abc import Sequence
5
+
6
+ from .models.health import (
7
+ HealthContext,
8
+ HealthNode,
9
+ HealthNodeResult,
10
+ HealthRule_Threshold,
11
+ HealthState_Degraded,
12
+ HealthState_Healthy,
13
+ HealthState_Unhealthy,
14
+ HealthState_Unknown,
15
+ )
16
+ from .models.value import (
17
+ ValueDefinition,
18
+ ValueObservation,
19
+ ValueRange,
20
+ )
21
+
22
+
23
+ class ValueEvidence:
24
+ """Validated definitions and measurements shared by threshold nodes."""
25
+
26
+ def __init__(
27
+ self,
28
+ definitions: Sequence[ValueDefinition],
29
+ observations: Sequence[ValueObservation],
30
+ ) -> None:
31
+ self.definitions = {v.id: v for v in definitions}
32
+ self.observations = {v.id: v for v in observations}
33
+ if len(self.definitions) != len(definitions):
34
+ raise ValueError("Duplicate value ID")
35
+ if len(self.observations) != len(observations):
36
+ raise ValueError("Duplicate value observation ID")
37
+ for definition in definitions:
38
+ if definition.max_age_ms == 0:
39
+ raise ValueError("Value has zero maxAgeMs")
40
+ for observation in observations:
41
+ validate_number(observation.value)
42
+ if observation.max_age_ms == 0:
43
+ raise ValueError("Value observation has zero maxAgeMs")
44
+
45
+ def validate(self, rule: HealthRule_Threshold) -> None:
46
+ """Require a value definition and nested, nonempty ranges."""
47
+ if rule.value not in self.definitions:
48
+ raise ValueError(f"Missing value {rule.value!r}")
49
+ if rule.max_age_ms == 0:
50
+ raise ValueError("Threshold has zero maxAgeMs")
51
+ for interval in (rule.healthy, rule.usable):
52
+ for bound in (interval.lower, interval.upper):
53
+ if bound is not None:
54
+ validate_number(bound.value)
55
+ if interval.lower is not None and interval.upper is not None:
56
+ lower, upper = (
57
+ interval.lower.value,
58
+ interval.upper.value,
59
+ )
60
+ if lower > upper or (
61
+ lower == upper
62
+ and not (interval.lower.inclusive and interval.upper.inclusive)
63
+ ):
64
+ raise ValueError("Empty or reversed value range")
65
+ for inner, outer, lower_bound in (
66
+ (rule.healthy.lower, rule.usable.lower, True),
67
+ (rule.healthy.upper, rule.usable.upper, False),
68
+ ):
69
+ if outer is not None:
70
+ if inner is None:
71
+ raise ValueError("Healthy range is outside usable range")
72
+ a, b = inner.value, outer.value
73
+ if (
74
+ (lower_bound and a < b)
75
+ or (not lower_bound and a > b)
76
+ or (a == b and inner.inclusive and not outer.inclusive)
77
+ ):
78
+ raise ValueError("Healthy range is outside usable range")
79
+
80
+ def evaluate(self, node: HealthNode, context: HealthContext) -> HealthNodeResult:
81
+ """Check value identity and freshness before applying the policy."""
82
+ rule = node.rule
83
+ assert isinstance(rule, HealthRule_Threshold)
84
+ definition = self.definitions[rule.value]
85
+ sample = self.observations.get(rule.value)
86
+ reason = None
87
+ if sample is None:
88
+ reason = "Missing value observation"
89
+ elif sample.boot_id != context.boot_id:
90
+ reason = "Value belongs to another boot"
91
+ elif definition.origin is not None and sample.origin != definition.origin:
92
+ reason = "Value origin does not match"
93
+ elif (
94
+ definition.expected_tag is not None
95
+ and sample.tag != definition.expected_tag
96
+ ):
97
+ reason = "Value tag does not match"
98
+ elif sample.observed_at_ms > context.now_ms:
99
+ reason = "Value is in the future"
100
+ elif context.now_ms - sample.observed_at_ms >= min(
101
+ sample.max_age_ms,
102
+ definition.max_age_ms
103
+ if definition.max_age_ms is not None
104
+ else sample.max_age_ms,
105
+ rule.max_age_ms if rule.max_age_ms is not None else sample.max_age_ms,
106
+ ):
107
+ reason = "Value has expired"
108
+ if reason is not None:
109
+ return HealthNodeResult(
110
+ id=node.id,
111
+ origin=node.origin,
112
+ state=HealthState_Unknown("unknown"),
113
+ inputs=[],
114
+ message=reason,
115
+ )
116
+ assert sample is not None
117
+ state = (
118
+ HealthState_Healthy("healthy")
119
+ if contains(rule.healthy, sample.value)
120
+ else HealthState_Degraded("degraded")
121
+ if contains(rule.usable, sample.value)
122
+ else HealthState_Unhealthy("unhealthy")
123
+ )
124
+ return HealthNodeResult(
125
+ id=node.id,
126
+ origin=node.origin,
127
+ state=state,
128
+ usable=state.root != "unhealthy",
129
+ inputs=[],
130
+ message=sample.message,
131
+ )
132
+
133
+
134
+ def validate_number(value: float) -> None:
135
+ """Reject non-finite measurements and endpoints."""
136
+ if not math.isfinite(value):
137
+ raise ValueError("Numeric value must be finite")
138
+
139
+
140
+ def contains(interval: ValueRange, value: float) -> bool:
141
+ """Test both endpoints with their declared inclusion rules."""
142
+ return (
143
+ interval.lower is None
144
+ or value > interval.lower.value
145
+ or (value == interval.lower.value and interval.lower.inclusive)
146
+ ) and (
147
+ interval.upper is None
148
+ or value < interval.upper.value
149
+ or (value == interval.upper.value and interval.upper.inclusive)
150
+ )
@@ -0,0 +1,186 @@
1
+ Metadata-Version: 2.5
2
+ Name: system-runtime-spec
3
+ Version: 0.1.0
4
+ Summary: System component compatibility, health evaluation, and filesystem discovery.
5
+ Project-URL: Repository, https://github.com/rugix/system-runtime-spec
6
+ Project-URL: Documentation, https://github.com/rugix/system-runtime-spec#readme
7
+ Project-URL: Issues, https://github.com/rugix/system-runtime-spec/issues
8
+ Author-email: Silitics GmbH <info@silitics.com>
9
+ License-Expression: MIT OR Apache-2.0
10
+ License-File: LICENSE-APACHE
11
+ License-File: LICENSE-MIT
12
+ Requires-Python: >=3.12
13
+ Requires-Dist: pydantic<3,>=2.11
14
+ Description-Content-Type: text/markdown
15
+
16
+ # System Runtime for Python
17
+
18
+ Use `system-runtime-spec` to load component and health files on Linux, check component
19
+ compatibility, and evaluate health graphs. Its models implement the
20
+ [System Runtime Specification](https://github.com/rugix/system-runtime-spec).
21
+
22
+ ## Installation
23
+
24
+ Python 3.12 or later is required. Install from PyPI:
25
+
26
+ ```sh
27
+ python -m pip install system-runtime-spec
28
+ ```
29
+
30
+ The distribution is named `system-runtime-spec`; import it as `system_runtime`.
31
+
32
+ ## Read and Check a System
33
+
34
+ `RuntimeDirectories.standard()` loads the specification's standard directories
35
+ and extension configurations. The returned `RuntimeSnapshot` contains components,
36
+ health nodes and statuses, and optional value definitions and observations.
37
+
38
+ ```python
39
+ from system_runtime import (
40
+ RuntimeDirectories,
41
+ check_components,
42
+ current_context,
43
+ evaluate_health,
44
+ )
45
+
46
+ snapshot = RuntimeDirectories.standard().load()
47
+ compatibility = check_components(snapshot.components)
48
+ health = evaluate_health(
49
+ snapshot.health_nodes,
50
+ snapshot.health_statuses,
51
+ current_context(),
52
+ values=snapshot.values or [],
53
+ value_observations=snapshot.value_observations or [],
54
+ )
55
+ print(compatibility.model_dump_json(), health.model_dump_json())
56
+ ```
57
+
58
+ `current_context()` reads the Linux boot ID and `CLOCK_BOOTTIME` for freshness
59
+ checks. For records from another system, supply that system's `HealthContext`.
60
+ Invalid declarations and discovery failures raise exceptions; a valid but
61
+ incompatible composition returns a report with `consistent == False`.
62
+
63
+ Pass `values` and `value_observations` to evaluate numeric threshold nodes.
64
+ The [value and threshold reference](https://github.com/rugix/system-runtime-spec#runtime-values-and-thresholds)
65
+ describes units, ranges, and evidence freshness.
66
+
67
+ ## Add Directories
68
+
69
+ Use extension files as described in the
70
+ [file discovery specification](https://github.com/rugix/system-runtime-spec#file-discovery),
71
+ or extend the sources in code:
72
+
73
+ ```python
74
+ from system_runtime import RuntimeDirectories
75
+ from system_runtime.filesystem import DirectoryConfig
76
+
77
+ directories = RuntimeDirectories.standard()
78
+ directories.extend(DirectoryConfig(components=["/opt/example/components"]))
79
+ snapshot = directories.load()
80
+ ```
81
+
82
+ Use `RuntimeDirectories()` to start with empty source lists.
83
+ `RuntimeDirectories.standard("/mnt/system")` relocates absolute source paths for
84
+ tests or alternate installations. Absolute symlink targets still resolve against
85
+ the host's root, rather than the supplied root.
86
+
87
+ ## Check an Update Candidate
88
+
89
+ An origin groups records owned by a system image, app, or other contributor.
90
+ `without_origin` returns a snapshot with new lists that exclude records owned by
91
+ that exact origin. Other records keep their requirements and references. Retained
92
+ record objects are shared with the original snapshot; copy a record before
93
+ modifying its fields.
94
+
95
+ ```python
96
+ from system_runtime import RuntimeDirectories, check_components, without_origin
97
+ from system_runtime.models.component import ComponentDeclaration
98
+
99
+ current = RuntimeDirectories.standard().load()
100
+ candidate = without_origin(current, "rugix.system")
101
+ candidate.components.append(
102
+ ComponentDeclaration(id="example.system", origin="rugix.system", version="2.0")
103
+ )
104
+ report = check_components(candidate.components)
105
+ print(report.consistent)
106
+ ```
107
+
108
+ The current records must already carry origins. Discovery does not infer
109
+ ownership from paths; attribute imported records before assembling the snapshot.
110
+ This operation changes only the in-memory candidate. After activation, evaluate
111
+ health using fresh records from the running system.
112
+
113
+ ### Import Records Without Origins
114
+
115
+ For existing records without origins, load each set of directories once before
116
+ constructing a candidate. This example builds a snapshot of components from
117
+ system-image and device-local directories without loading directory configuration
118
+ files:
119
+
120
+ ```python
121
+ from system_runtime import RuntimeDirectories
122
+
123
+ current = RuntimeDirectories(
124
+ components=["/etc/rugix/components", "/run/rugix/components"],
125
+ ).load()
126
+ image = RuntimeDirectories(components=["/usr/lib/rugix/components"]).load()
127
+ for component in image.components:
128
+ component.origin = "rugix.system"
129
+ current.components.extend(image.components)
130
+ ```
131
+
132
+ Use this prepared `current` in the replacement example instead of loading it with
133
+ `standard()`. Before evaluating the complete system, add app contributions and
134
+ any components from standard directories that the system relies on. Load health
135
+ nodes and statuses separately for health evaluation. Read each set of directories
136
+ once; combining this import with a standard load of the same files would
137
+ duplicate records. The assignments change only in-memory records. Device-local
138
+ records without an origin survive replacement.
139
+
140
+ ## Transport a Health Snapshot
141
+
142
+ Collect records first, then sample the observed system's clock:
143
+
144
+ ```python
145
+ from system_runtime import RuntimeDirectories, current_clock_sample, status_timestamp
146
+ from system_runtime.models.health import HealthSnapshot
147
+
148
+ records = RuntimeDirectories.standard().load()
149
+ snapshot = HealthSnapshot(
150
+ clock=current_clock_sample(),
151
+ nodes=records.health_nodes,
152
+ statuses=records.health_statuses,
153
+ values=records.values,
154
+ value_observations=records.value_observations,
155
+ )
156
+ payload = snapshot.model_dump_json()
157
+ received = HealthSnapshot.model_validate_json(payload)
158
+ for status in received.statuses:
159
+ print(status.id, status_timestamp(status, received.clock))
160
+ ```
161
+
162
+ `current_clock_sample()` samples UTC between two boot-time reads and pairs it
163
+ with their midpoint. `status_timestamp` returns an estimated UTC `datetime` for
164
+ display, or `None` for a wrong boot, future observation, or unsupported timestamp
165
+ range. Sampling uncertainty and wall-clock corrections limit the estimate.
166
+
167
+ Evaluating with `received.clock.context` gives health at capture time. Obtain
168
+ current evidence before making an update decision.
169
+
170
+ ## Models
171
+
172
+ Sidex generates Pydantic models in `system_runtime.models.component`,
173
+ `system_runtime.models.health`, `system_runtime.models.value`, and
174
+ `system_runtime.models.filesystem`. Python
175
+ attributes use snake_case, such as `boot_id`; serialized fields use names such as
176
+ `bootId`. Use `model_validate` or `model_validate_json` to parse records and
177
+ `model_dump_json()` to serialize them in the specified wire format. Unset
178
+ optional fields are omitted. Health node IDs are string type aliases.
179
+
180
+ See the [specification](https://github.com/rugix/system-runtime-spec) for wire
181
+ formats, version matching, and health semantics.
182
+
183
+ ## License
184
+
185
+ Available under either the [MIT License](LICENSE-MIT) or the
186
+ [Apache License 2.0](LICENSE-APACHE).
@@ -0,0 +1,21 @@
1
+ system_runtime/__init__.py,sha256=dIUKrBHFDKU_X3pKPBLuCD_7Ya8Kz6l74JwQJbSwCuA,618
2
+ system_runtime/_version.py,sha256=Y9auEfSe-kWWJ0413e5mEgiWzVwJf8gTgrAH9oQi69c,3288
3
+ system_runtime/clock.py,sha256=-rLZxdmmngb4pgXznKOT777mgaiPf6XPtO4WDURG9rY,1293
4
+ system_runtime/components.py,sha256=Iz4AZDgXTk_TtdrbUb3bMgEa_6d52GYozRa4NKyRBDw,3991
5
+ system_runtime/filesystem.py,sha256=ya_0me88YVtne-yr6E4aUU57VUEuuybv2DPCMVVCZHY,6709
6
+ system_runtime/health.py,sha256=k4XteHJxNV3_uIv0kp_iqJxxfgC3DXkoTx5MbME4uSc,7284
7
+ system_runtime/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
8
+ system_runtime/snapshot.py,sha256=DfveM1pfXOSQ5DuTbg0ABGzNgHBQQa2vEn5_gzQrWfs,958
9
+ system_runtime/threshold.py,sha256=5csm9glAbKijQqIlQhyOUYEIaVaS43bM3vd6BLGl7Rw,5735
10
+ system_runtime/models/__init__.py,sha256=056E0LePmP8xCnZIiHWMMAYkYkv_lKcghNygKvMajyg,720
11
+ system_runtime/models/_sidex.py,sha256=e8gnJvNc80lcmVyb5n7QkOztvfmvZkMu3miWgKpyypA,8938
12
+ system_runtime/models/component.py,sha256=pF4cgAW_1OKn9P8lJP7Esp-BUn_66e-FrVrahc44V3s,6908
13
+ system_runtime/models/filesystem.py,sha256=dqQ4zM7-Iv_4-E0wpXWCYQck7sRw9AYoDHOnTimi0qw,2736
14
+ system_runtime/models/health.py,sha256=8np4_K8qN4NWQXn0ierOOibZN8qK7Tv7ViVf9gSUSNg,10364
15
+ system_runtime/models/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
16
+ system_runtime/models/value.py,sha256=Bnps-yWcW6AC_Mel6g__M4x5nP-5kQSwkZhtgXhBQDw,4853
17
+ system_runtime_spec-0.1.0.dist-info/METADATA,sha256=yFAZ14lXXLTfeSS9YE76ABMvSQwys-Eoh96HIKoBCdI,7261
18
+ system_runtime_spec-0.1.0.dist-info/WHEEL,sha256=W3fkpkm7-wf9vBI5Z-7s0eWkeM-spu78I8Neb98DeEg,87
19
+ system_runtime_spec-0.1.0.dist-info/licenses/LICENSE-APACHE,sha256=WNHhf_5RCaeuKWyq_K39vmp9F28LxKsB4SpomwSZ2L0,11357
20
+ system_runtime_spec-0.1.0.dist-info/licenses/LICENSE-MIT,sha256=kMY66Qyxk-AjoXXX3ERVZ3ICH3qB6iVTKl0zzJ0hnwg,1071
21
+ system_runtime_spec-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.32.4
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any