glosslayer 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.
- glosslayer/__init__.py +100 -0
- glosslayer/actors.py +152 -0
- glosslayer/ai.py +126 -0
- glosslayer/catalogs/__init__.py +1 -0
- glosslayer/catalogs/file.py +87 -0
- glosslayer/checks.py +512 -0
- glosslayer/cli.py +560 -0
- glosslayer/client.py +417 -0
- glosslayer/dtypes.py +237 -0
- glosslayer/ids.py +203 -0
- glosslayer/ledger.py +1654 -0
- glosslayer/mcp_server.py +108 -0
- glosslayer/model.py +589 -0
- glosslayer/modeling.py +602 -0
- glosslayer/ossie/__init__.py +13 -0
- glosslayer/ossie/exporter.py +322 -0
- glosslayer/ossie/importer.py +179 -0
- glosslayer/ossie/ossie-schema.json +398 -0
- glosslayer/plugins.py +108 -0
- glosslayer/policy.py +375 -0
- glosslayer/references.py +52 -0
- glosslayer/schema.py +162 -0
- glosslayer/seams.py +147 -0
- glosslayer/search_index.py +218 -0
- glosslayer/semantic.py +75 -0
- glosslayer/server.py +690 -0
- glosslayer/sinks.py +56 -0
- glosslayer/store/__init__.py +8 -0
- glosslayer/store/base.py +50 -0
- glosslayer/store/sql.py +918 -0
- glosslayer/sync.py +381 -0
- glosslayer/types.py +34 -0
- glosslayer/visibility.py +85 -0
- glosslayer/viz.py +110 -0
- glosslayer-0.1.0.dist-info/METADATA +1101 -0
- glosslayer-0.1.0.dist-info/RECORD +40 -0
- glosslayer-0.1.0.dist-info/WHEEL +4 -0
- glosslayer-0.1.0.dist-info/entry_points.txt +13 -0
- glosslayer-0.1.0.dist-info/licenses/LICENSE +201 -0
- glosslayer-0.1.0.dist-info/licenses/NOTICE +12 -0
glosslayer/model.py
ADDED
|
@@ -0,0 +1,589 @@
|
|
|
1
|
+
"""Core data model: assertions (facts), events (the log) and the review workflow.
|
|
2
|
+
|
|
3
|
+
An *assertion* is one small piece of semantic knowledge: "the description of
|
|
4
|
+
field sales.orders/amount is 'Order value incl. VAT'", proposed by some
|
|
5
|
+
source with some confidence. Assertions are never edited in place. Every
|
|
6
|
+
change is an *event* appended to the log; the current state of an assertion
|
|
7
|
+
is a pure fold over its events (see :func:`apply_event`).
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
from __future__ import annotations
|
|
11
|
+
|
|
12
|
+
import hashlib
|
|
13
|
+
import json
|
|
14
|
+
import re
|
|
15
|
+
import uuid
|
|
16
|
+
from collections.abc import Callable, Iterable, Iterator, Mapping
|
|
17
|
+
from dataclasses import dataclass, field, replace
|
|
18
|
+
from datetime import datetime, timezone
|
|
19
|
+
from enum import Enum
|
|
20
|
+
from typing import TYPE_CHECKING, Any
|
|
21
|
+
|
|
22
|
+
from .ids import NS_SEP, Kind, SubjectId
|
|
23
|
+
|
|
24
|
+
if TYPE_CHECKING:
|
|
25
|
+
from .actors import Actor
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
class Status(str, Enum):
|
|
29
|
+
"""Where an assertion is in the review workflow; only *accepted* facts make up the published model."""
|
|
30
|
+
PROPOSED = "proposed" # modelled, not yet reviewed
|
|
31
|
+
REVIEWED = "reviewed" # a reviewer looked at it and approved; awaiting acceptance
|
|
32
|
+
ACCEPTED = "accepted" # part of the published model
|
|
33
|
+
REJECTED = "rejected"
|
|
34
|
+
SUPERSEDED = "superseded" # replaced by a newer accepted value
|
|
35
|
+
STALE = "stale" # the underlying data changed; needs re-review
|
|
36
|
+
RETRACTED = "retracted" # withdrawn by its source
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
OPEN_STATUSES = frozenset({Status.PROPOSED, Status.REVIEWED, Status.STALE})
|
|
40
|
+
LIVE_STATUSES = OPEN_STATUSES | {Status.ACCEPTED}
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
class InvalidTransition(ValueError):
|
|
44
|
+
"""An event cannot be applied to an assertion in its current status."""
|
|
45
|
+
pass
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
class Confidentiality(str, Enum):
|
|
49
|
+
"""How sensitive a subject is. Levels compare by rank: public < internal < confidential < restricted."""
|
|
50
|
+
PUBLIC = "public"
|
|
51
|
+
INTERNAL = "internal"
|
|
52
|
+
CONFIDENTIAL = "confidential"
|
|
53
|
+
RESTRICTED = "restricted"
|
|
54
|
+
|
|
55
|
+
@property
|
|
56
|
+
def rank(self) -> int:
|
|
57
|
+
"""Position in the order, used to compare levels and to store them as integers."""
|
|
58
|
+
return _CONF_ORDER.index(self)
|
|
59
|
+
|
|
60
|
+
@classmethod
|
|
61
|
+
def from_rank(cls, rank: int) -> Confidentiality:
|
|
62
|
+
"""The level at ``rank`` (the inverse of :attr:`rank`)."""
|
|
63
|
+
return _CONF_ORDER[rank]
|
|
64
|
+
|
|
65
|
+
def __ge__(self, other: Confidentiality) -> bool: # type: ignore[override]
|
|
66
|
+
return self.rank >= Confidentiality(other).rank
|
|
67
|
+
|
|
68
|
+
def __gt__(self, other: Confidentiality) -> bool: # type: ignore[override]
|
|
69
|
+
return self.rank > Confidentiality(other).rank
|
|
70
|
+
|
|
71
|
+
def __le__(self, other: Confidentiality) -> bool: # type: ignore[override]
|
|
72
|
+
return self.rank <= Confidentiality(other).rank
|
|
73
|
+
|
|
74
|
+
def __lt__(self, other: Confidentiality) -> bool: # type: ignore[override]
|
|
75
|
+
return self.rank < Confidentiality(other).rank
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
_CONF_ORDER = [
|
|
79
|
+
Confidentiality.PUBLIC,
|
|
80
|
+
Confidentiality.INTERNAL,
|
|
81
|
+
Confidentiality.CONFIDENTIAL,
|
|
82
|
+
Confidentiality.RESTRICTED,
|
|
83
|
+
]
|
|
84
|
+
|
|
85
|
+
DATATYPES = frozenset(
|
|
86
|
+
{"String", "Integer", "Decimal", "Float", "Boolean", "Date", "Time", "DateTime", "DateTimeTz", "Opaque"}
|
|
87
|
+
)
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
@dataclass(frozen=True)
|
|
91
|
+
class AttributeSpec:
|
|
92
|
+
"""One attribute a fact can state, and how the rest of Gloss treats it.
|
|
93
|
+
|
|
94
|
+
``inherited`` a field takes it from its semantic type when it does not state it itself;
|
|
95
|
+
``detail`` its value is hidden from readers below the subject's confidentiality level;
|
|
96
|
+
``searchable`` its words go into the search index (gated by level when ``detail``);
|
|
97
|
+
``ossie`` Ossie has a native place for it; otherwise it travels in ``nonportable_extensions``;
|
|
98
|
+
``structural`` it describes physical structure, which a catalog is the authority on.
|
|
99
|
+
"""
|
|
100
|
+
|
|
101
|
+
name: str
|
|
102
|
+
kinds: frozenset[Kind]
|
|
103
|
+
validate: Callable[[Any], Any] | None = None
|
|
104
|
+
inherited: bool = False
|
|
105
|
+
detail: bool = False
|
|
106
|
+
searchable: bool = False
|
|
107
|
+
ossie: bool = False
|
|
108
|
+
structural: bool = False
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
_ATTRIBUTES: dict[str, AttributeSpec] = {}
|
|
112
|
+
|
|
113
|
+
|
|
114
|
+
def register_attribute(
|
|
115
|
+
name: str,
|
|
116
|
+
kinds: Iterable[Kind | str],
|
|
117
|
+
*,
|
|
118
|
+
validate: Callable[[Any], Any] | None = None,
|
|
119
|
+
inherited: bool = False,
|
|
120
|
+
detail: bool = False,
|
|
121
|
+
searchable: bool = False,
|
|
122
|
+
ossie: bool = False,
|
|
123
|
+
structural: bool = False,
|
|
124
|
+
) -> AttributeSpec:
|
|
125
|
+
"""Make an attribute known, so hosts can extend the vocabulary without changing Gloss.
|
|
126
|
+
|
|
127
|
+
glosslayer.register_attribute("time_column", ["metric"], validate=str)
|
|
128
|
+
|
|
129
|
+
Registering a name again replaces its definition. Facts stating an attribute this process
|
|
130
|
+
does not know stay readable; they just cannot be proposed until it is registered.
|
|
131
|
+
"""
|
|
132
|
+
if not name or not re.fullmatch(r"[a-z][a-z0-9_]*", name):
|
|
133
|
+
raise ValueError(f"Attribute name {name!r} must be lower snake case")
|
|
134
|
+
spec = AttributeSpec(
|
|
135
|
+
name, frozenset(Kind(k) for k in kinds), validate, inherited, detail, searchable, ossie, structural
|
|
136
|
+
)
|
|
137
|
+
if not spec.kinds:
|
|
138
|
+
raise ValueError(f"Attribute {name!r} needs at least one subject kind")
|
|
139
|
+
_ATTRIBUTES[name] = spec
|
|
140
|
+
return spec
|
|
141
|
+
|
|
142
|
+
|
|
143
|
+
def attribute(name: str) -> AttributeSpec | None:
|
|
144
|
+
"""The registered spec for ``name``, or None when this process does not know it."""
|
|
145
|
+
return _ATTRIBUTES.get(name)
|
|
146
|
+
|
|
147
|
+
|
|
148
|
+
def attributes_for(kind: Kind) -> frozenset[str]:
|
|
149
|
+
"""Names of the registered attributes a subject of ``kind`` may state."""
|
|
150
|
+
return frozenset(n for n, s in _ATTRIBUTES.items() if kind in s.kinds)
|
|
151
|
+
|
|
152
|
+
|
|
153
|
+
def inherited_attributes() -> tuple[str, ...]:
|
|
154
|
+
"""What a field inherits from its semantic type when it doesn't state the attribute itself."""
|
|
155
|
+
return tuple(n for n, s in _ATTRIBUTES.items() if s.inherited)
|
|
156
|
+
|
|
157
|
+
|
|
158
|
+
def detail_attributes() -> frozenset[str]:
|
|
159
|
+
"""Attributes whose values are withheld from readers below the subject's confidentiality level."""
|
|
160
|
+
return frozenset(n for n, s in _ATTRIBUTES.items() if s.detail)
|
|
161
|
+
|
|
162
|
+
|
|
163
|
+
def is_structural(subject: SubjectId, attribute_name: str) -> bool:
|
|
164
|
+
"""Physical structure of a dataset or field: the only facts a catalog may accept on its own."""
|
|
165
|
+
spec = _ATTRIBUTES.get(attribute_name)
|
|
166
|
+
return bool(spec and spec.structural and subject.kind in (Kind.DATASET, Kind.FIELD))
|
|
167
|
+
|
|
168
|
+
|
|
169
|
+
class _AttributesByKind(Mapping[Kind, frozenset[str]]):
|
|
170
|
+
"""Read-only ``{kind: attribute names}`` view of the registry."""
|
|
171
|
+
|
|
172
|
+
def __getitem__(self, kind: Kind) -> frozenset[str]:
|
|
173
|
+
return attributes_for(Kind(kind))
|
|
174
|
+
|
|
175
|
+
def __iter__(self) -> Iterator[Kind]:
|
|
176
|
+
return iter(Kind)
|
|
177
|
+
|
|
178
|
+
def __len__(self) -> int:
|
|
179
|
+
return len(Kind)
|
|
180
|
+
|
|
181
|
+
|
|
182
|
+
ATTRIBUTES: Mapping[Kind, frozenset[str]] = _AttributesByKind()
|
|
183
|
+
|
|
184
|
+
|
|
185
|
+
def _text(value: Any) -> str:
|
|
186
|
+
if not isinstance(value, str) or not value.strip():
|
|
187
|
+
raise ValueError("must be a non-empty string")
|
|
188
|
+
return value
|
|
189
|
+
|
|
190
|
+
|
|
191
|
+
def _str_list(value: Any) -> list[str]:
|
|
192
|
+
if isinstance(value, str):
|
|
193
|
+
value = [value]
|
|
194
|
+
if not isinstance(value, list) or not all(isinstance(v, str) for v in value):
|
|
195
|
+
raise ValueError("must be a list of strings")
|
|
196
|
+
return value
|
|
197
|
+
|
|
198
|
+
|
|
199
|
+
def _key_lists(value: Any) -> list[list[str]]:
|
|
200
|
+
if not isinstance(value, list) or not all(isinstance(k, list) for k in value):
|
|
201
|
+
raise ValueError("must be a list of lists of field names")
|
|
202
|
+
return value
|
|
203
|
+
|
|
204
|
+
|
|
205
|
+
def _confidentiality(value: Any) -> str:
|
|
206
|
+
return Confidentiality(value).value
|
|
207
|
+
|
|
208
|
+
|
|
209
|
+
def _datatype(value: Any) -> str:
|
|
210
|
+
if value not in DATATYPES:
|
|
211
|
+
raise ValueError(f"must be one of {sorted(DATATYPES)}, got {value!r}")
|
|
212
|
+
return value
|
|
213
|
+
|
|
214
|
+
|
|
215
|
+
def _type_ref(value: Any) -> str:
|
|
216
|
+
if not isinstance(value, str) or not value or "/" in value or ":" in value.replace(NS_SEP, ""):
|
|
217
|
+
raise ValueError("must be a type name like 'email_address' or 'crm::email_address'")
|
|
218
|
+
return SubjectId.for_type(value).ref
|
|
219
|
+
|
|
220
|
+
|
|
221
|
+
def _checks(value: Any) -> list[dict[str, Any]]:
|
|
222
|
+
from .checks import normalise
|
|
223
|
+
|
|
224
|
+
if not isinstance(value, list):
|
|
225
|
+
raise ValueError("must be a list")
|
|
226
|
+
return normalise(value)
|
|
227
|
+
|
|
228
|
+
|
|
229
|
+
def _patterns(value: Any) -> list[str]:
|
|
230
|
+
value = _str_list(value)
|
|
231
|
+
for p in value:
|
|
232
|
+
re.compile(p)
|
|
233
|
+
return value
|
|
234
|
+
|
|
235
|
+
|
|
236
|
+
def _bool(value: Any) -> bool:
|
|
237
|
+
if not isinstance(value, bool):
|
|
238
|
+
raise ValueError("must be a boolean")
|
|
239
|
+
return value
|
|
240
|
+
|
|
241
|
+
|
|
242
|
+
ROLES = frozenset({"key", "time", "category", "amount"})
|
|
243
|
+
|
|
244
|
+
|
|
245
|
+
def _role(value: Any) -> str:
|
|
246
|
+
if value not in ROLES:
|
|
247
|
+
raise ValueError(f"must be one of {sorted(ROLES)}, got {value!r}")
|
|
248
|
+
return value
|
|
249
|
+
|
|
250
|
+
|
|
251
|
+
def normalise_expression(value: Any) -> dict[str, Any]:
|
|
252
|
+
"""Accept a bare SQL string or an Ossie Expression object."""
|
|
253
|
+
if isinstance(value, str):
|
|
254
|
+
return {"sql": value}
|
|
255
|
+
if isinstance(value, dict) and ("sql" in value or "dialects" in value):
|
|
256
|
+
return value
|
|
257
|
+
raise ValueError("expression must be a SQL string or an Ossie expression object {sql|dialects}")
|
|
258
|
+
|
|
259
|
+
|
|
260
|
+
def _register_builtins() -> None:
|
|
261
|
+
K = Kind
|
|
262
|
+
everything = list(Kind)
|
|
263
|
+
described = [K.DATASET, K.FIELD, K.RELATIONSHIP, K.METRIC, K.TYPE]
|
|
264
|
+
reg = register_attribute
|
|
265
|
+
# Registration order is the order fields inherit in and proposals are listed in.
|
|
266
|
+
reg("name", [K.MODEL], validate=_text, ossie=True)
|
|
267
|
+
reg("datatype", [K.FIELD, K.METRIC, K.TYPE], validate=_datatype, inherited=True, ossie=True, structural=True)
|
|
268
|
+
reg("physical_type", [K.FIELD, K.TYPE], validate=_text, inherited=True, structural=True)
|
|
269
|
+
reg("description", everything, inherited=True, detail=True, searchable=True, ossie=True)
|
|
270
|
+
reg("label", [K.FIELD, K.TYPE], inherited=True, detail=True, searchable=True, ossie=True)
|
|
271
|
+
reg("confidentiality", described, validate=_confidentiality, inherited=True)
|
|
272
|
+
reg("classification", [K.DATASET, K.FIELD, K.TYPE], validate=_str_list, inherited=True, detail=True,
|
|
273
|
+
searchable=True)
|
|
274
|
+
reg("synonyms", everything, validate=_str_list, inherited=True, detail=True, searchable=True, ossie=True)
|
|
275
|
+
reg("examples", everything, validate=_str_list, inherited=True, detail=True, searchable=True, ossie=True)
|
|
276
|
+
reg("ai_instructions", everything, inherited=True, detail=True, searchable=True, ossie=True)
|
|
277
|
+
reg("owner", everything, inherited=True)
|
|
278
|
+
reg("source", [K.DATASET], searchable=True, ossie=True, structural=True)
|
|
279
|
+
reg("primary_key", [K.DATASET], validate=_str_list, ossie=True, structural=True)
|
|
280
|
+
reg("unique_keys", [K.DATASET], validate=_key_lists, ossie=True)
|
|
281
|
+
reg("expression", [K.FIELD, K.METRIC], validate=normalise_expression, detail=True, ossie=True, structural=True)
|
|
282
|
+
reg("is_time", [K.FIELD], validate=_bool, ossie=True)
|
|
283
|
+
reg("semantic_type", [K.FIELD], validate=_type_ref)
|
|
284
|
+
reg("checks", [K.FIELD, K.TYPE], validate=_checks)
|
|
285
|
+
reg("name_patterns", [K.TYPE], validate=_patterns)
|
|
286
|
+
reg("from", [K.RELATIONSHIP], validate=_text, searchable=True, ossie=True)
|
|
287
|
+
reg("to", [K.RELATIONSHIP], validate=_text, searchable=True, ossie=True)
|
|
288
|
+
reg("from_columns", [K.RELATIONSHIP], validate=_str_list, ossie=True)
|
|
289
|
+
reg("to_columns", [K.RELATIONSHIP], validate=_str_list, ossie=True)
|
|
290
|
+
# A metric's structured definition, beside its SQL expression. Ossie has no place for these yet.
|
|
291
|
+
reg("aggregate", [K.METRIC], validate=_text, detail=True)
|
|
292
|
+
reg("filter", [K.METRIC], validate=_text, detail=True)
|
|
293
|
+
reg("time_column", [K.METRIC], validate=_text)
|
|
294
|
+
reg("dimensions", [K.METRIC], validate=_str_list)
|
|
295
|
+
reg("format", [K.METRIC], validate=_text)
|
|
296
|
+
reg("role", [K.FIELD], validate=_role)
|
|
297
|
+
|
|
298
|
+
|
|
299
|
+
_register_builtins()
|
|
300
|
+
|
|
301
|
+
# Attributes whose value names another subject. A re-key rewrites them so references keep resolving.
|
|
302
|
+
DATASET_REFERENCES = ("from", "to")
|
|
303
|
+
|
|
304
|
+
# Subjects whose facts only make sense together: a group of proposals for one is decided as a unit.
|
|
305
|
+
ATOMIC_KINDS = frozenset({Kind.RELATIONSHIP, Kind.METRIC})
|
|
306
|
+
|
|
307
|
+
|
|
308
|
+
def validate_value(subject: SubjectId, attribute_name: str, value: Any) -> Any:
|
|
309
|
+
"""Check an attribute is allowed for the subject kind and normalise its value."""
|
|
310
|
+
spec = _ATTRIBUTES.get(attribute_name)
|
|
311
|
+
if spec is None or subject.kind not in spec.kinds:
|
|
312
|
+
allowed = ", ".join(sorted(attributes_for(subject.kind)))
|
|
313
|
+
raise ValueError(
|
|
314
|
+
f"Attribute {attribute_name!r} is not valid for {subject.kind.value} subjects (allowed: {allowed})"
|
|
315
|
+
)
|
|
316
|
+
if spec.validate is None:
|
|
317
|
+
return value
|
|
318
|
+
try:
|
|
319
|
+
return spec.validate(value)
|
|
320
|
+
except ValueError as exc:
|
|
321
|
+
raise ValueError(f"{attribute_name} {exc}" if not str(exc).startswith(attribute_name) else str(exc)) from None
|
|
322
|
+
|
|
323
|
+
|
|
324
|
+
def value_hash(value: Any) -> str:
|
|
325
|
+
"""A short, stable hash of a JSON value, so facts with equal values are found by index."""
|
|
326
|
+
blob = json.dumps(value, sort_keys=True, separators=(",", ":"), default=str)
|
|
327
|
+
return hashlib.sha256(blob.encode()).hexdigest()[:16]
|
|
328
|
+
|
|
329
|
+
|
|
330
|
+
class EventType(str, Enum):
|
|
331
|
+
"""The kinds of event in the log. Their values are written into events, so they never change."""
|
|
332
|
+
PROPOSED = "proposed"
|
|
333
|
+
CORROBORATED = "corroborated" # another source stated the same value
|
|
334
|
+
REVIEWED = "reviewed"
|
|
335
|
+
ACCEPTED = "accepted"
|
|
336
|
+
REJECTED = "rejected"
|
|
337
|
+
REOPENED = "reopened"
|
|
338
|
+
SUPERSEDED = "superseded"
|
|
339
|
+
MARKED_STALE = "marked_stale"
|
|
340
|
+
RETRACTED = "retracted"
|
|
341
|
+
RESTORED = "restored" # a superseded value was put back
|
|
342
|
+
REKEYED = "rekeyed" # the subject (or a subject its value names) was renamed or moved
|
|
343
|
+
COMMENTED = "commented"
|
|
344
|
+
|
|
345
|
+
|
|
346
|
+
EVENT_TARGET_STATUS: dict[EventType, Status] = {
|
|
347
|
+
EventType.REVIEWED: Status.REVIEWED,
|
|
348
|
+
EventType.ACCEPTED: Status.ACCEPTED,
|
|
349
|
+
EventType.REJECTED: Status.REJECTED,
|
|
350
|
+
EventType.REOPENED: Status.PROPOSED,
|
|
351
|
+
EventType.SUPERSEDED: Status.SUPERSEDED,
|
|
352
|
+
EventType.MARKED_STALE: Status.STALE,
|
|
353
|
+
EventType.RETRACTED: Status.RETRACTED,
|
|
354
|
+
EventType.RESTORED: Status.ACCEPTED,
|
|
355
|
+
}
|
|
356
|
+
|
|
357
|
+
# The statuses each event may be applied from. Superseded values come back only through `restored`.
|
|
358
|
+
EVENT_FROM_STATUSES: dict[EventType, frozenset[Status]] = {
|
|
359
|
+
EventType.REVIEWED: frozenset({Status.PROPOSED, Status.STALE}),
|
|
360
|
+
EventType.ACCEPTED: frozenset({Status.PROPOSED, Status.REVIEWED, Status.STALE}),
|
|
361
|
+
EventType.REJECTED: frozenset({Status.PROPOSED, Status.REVIEWED, Status.STALE}),
|
|
362
|
+
EventType.REOPENED: frozenset({Status.REJECTED, Status.REVIEWED}),
|
|
363
|
+
EventType.SUPERSEDED: frozenset({Status.ACCEPTED}),
|
|
364
|
+
EventType.MARKED_STALE: frozenset({Status.PROPOSED, Status.REVIEWED, Status.ACCEPTED}),
|
|
365
|
+
EventType.RETRACTED: frozenset({Status.PROPOSED, Status.REVIEWED, Status.ACCEPTED, Status.STALE}),
|
|
366
|
+
EventType.RESTORED: frozenset({Status.SUPERSEDED}),
|
|
367
|
+
}
|
|
368
|
+
|
|
369
|
+
|
|
370
|
+
def _transitions() -> dict[Status, frozenset[Status]]:
|
|
371
|
+
out: dict[Status, set[Status]] = {s: set() for s in Status}
|
|
372
|
+
for etype, sources in EVENT_FROM_STATUSES.items():
|
|
373
|
+
for s in sources:
|
|
374
|
+
out[s].add(EVENT_TARGET_STATUS[etype])
|
|
375
|
+
return {s: frozenset(t) for s, t in out.items()}
|
|
376
|
+
|
|
377
|
+
|
|
378
|
+
TRANSITIONS: dict[Status, frozenset[Status]] = _transitions()
|
|
379
|
+
|
|
380
|
+
|
|
381
|
+
def can_apply(event_type: EventType, status: Status) -> bool:
|
|
382
|
+
"""Whether a status-changing event may apply to an assertion in ``status`` (False for other events)."""
|
|
383
|
+
return status in EVENT_FROM_STATUSES.get(event_type, frozenset())
|
|
384
|
+
|
|
385
|
+
|
|
386
|
+
def utcnow() -> datetime:
|
|
387
|
+
"""The current time as timezone-aware UTC, the only kind Gloss stores."""
|
|
388
|
+
return datetime.now(timezone.utc)
|
|
389
|
+
|
|
390
|
+
|
|
391
|
+
def new_id() -> str:
|
|
392
|
+
"""A fresh random id (32 hex characters) for events, assertions and correlations."""
|
|
393
|
+
return uuid.uuid4().hex
|
|
394
|
+
|
|
395
|
+
|
|
396
|
+
@dataclass(frozen=True)
|
|
397
|
+
class Event:
|
|
398
|
+
"""One entry in the append-only log. Never edited; an assertion's state is the fold of its events."""
|
|
399
|
+
type: EventType
|
|
400
|
+
assertion_id: str
|
|
401
|
+
actor: str
|
|
402
|
+
data: dict[str, Any] = field(default_factory=dict)
|
|
403
|
+
id: str = field(default_factory=new_id)
|
|
404
|
+
ts: datetime = field(default_factory=utcnow)
|
|
405
|
+
seq: int | None = None # assigned by the store
|
|
406
|
+
correlation: str | None = None # groups the events of one request, sync run or bulk action
|
|
407
|
+
via: str | None = None # the channel the actor came through: an agent, a server
|
|
408
|
+
|
|
409
|
+
def __repr__(self) -> str:
|
|
410
|
+
note = self.data.get("comment") or self.data.get("reason")
|
|
411
|
+
extra = f" {note!r}" if note else ""
|
|
412
|
+
seq = f"#{self.seq} " if self.seq is not None else ""
|
|
413
|
+
return f"<{seq}{self.type.value} {self.assertion_id[:8]} by {self.actor} {self.ts:%Y-%m-%d %H:%M:%S}{extra}>"
|
|
414
|
+
|
|
415
|
+
def to_dict(self) -> dict[str, Any]:
|
|
416
|
+
"""JSON-ready form; :meth:`from_dict` reverses it."""
|
|
417
|
+
return {
|
|
418
|
+
"seq": self.seq,
|
|
419
|
+
"id": self.id,
|
|
420
|
+
"ts": self.ts.isoformat(),
|
|
421
|
+
"type": self.type.value,
|
|
422
|
+
"assertion_id": self.assertion_id,
|
|
423
|
+
"actor": self.actor,
|
|
424
|
+
"via": self.via,
|
|
425
|
+
"correlation": self.correlation,
|
|
426
|
+
"data": self.data,
|
|
427
|
+
}
|
|
428
|
+
|
|
429
|
+
@classmethod
|
|
430
|
+
def from_dict(cls, d: dict[str, Any]) -> Event:
|
|
431
|
+
"""Rebuild an event from :meth:`to_dict` output."""
|
|
432
|
+
return cls(
|
|
433
|
+
EventType(d["type"]), d["assertion_id"], d["actor"], d.get("data") or {}, d["id"],
|
|
434
|
+
datetime.fromisoformat(d["ts"]), d.get("seq"), d.get("correlation"), d.get("via"),
|
|
435
|
+
)
|
|
436
|
+
|
|
437
|
+
|
|
438
|
+
@dataclass(frozen=True)
|
|
439
|
+
class Assertion:
|
|
440
|
+
"""The current state of one fact: one value for one attribute of one subject, with its status and sources.
|
|
441
|
+
|
|
442
|
+
A projection of the fact's events (see :func:`apply_event`); never written directly.
|
|
443
|
+
"""
|
|
444
|
+
id: str
|
|
445
|
+
subject: str
|
|
446
|
+
attribute: str
|
|
447
|
+
value: Any
|
|
448
|
+
source: str
|
|
449
|
+
status: Status
|
|
450
|
+
confidence: float | None
|
|
451
|
+
created_at: datetime
|
|
452
|
+
updated_at: datetime
|
|
453
|
+
created_by: str
|
|
454
|
+
sources: tuple[str, ...] = () # all sources that stated this value (corroboration)
|
|
455
|
+
evidence: tuple[dict[str, Any], ...] = ()
|
|
456
|
+
last_comment: str | None = None
|
|
457
|
+
group: str | None = None # proposals made together; decided as a unit for relationships and metrics
|
|
458
|
+
redacted: bool = False # view-only: the value was withheld from this reader
|
|
459
|
+
|
|
460
|
+
@property
|
|
461
|
+
def subject_id(self) -> SubjectId:
|
|
462
|
+
"""The subject parsed into a :class:`~glosslayer.ids.SubjectId`."""
|
|
463
|
+
return SubjectId.parse(self.subject)
|
|
464
|
+
|
|
465
|
+
@property
|
|
466
|
+
def dataset(self) -> str | None:
|
|
467
|
+
"""The dataset the subject belongs to, or None for ledger-wide and namespace subjects."""
|
|
468
|
+
return self.subject_id.owning_dataset
|
|
469
|
+
|
|
470
|
+
@property
|
|
471
|
+
def scope_path(self) -> str | None:
|
|
472
|
+
"""The dotted path access rules apply to (dataset key or namespace); None when ledger-wide."""
|
|
473
|
+
return self.subject_id.scope_path
|
|
474
|
+
|
|
475
|
+
def __repr__(self) -> str:
|
|
476
|
+
v = self.value if isinstance(self.value, str) else json.dumps(self.value, ensure_ascii=False)
|
|
477
|
+
if len(v) > 50:
|
|
478
|
+
v = v[:49] + "…"
|
|
479
|
+
conf = f" {self.confidence:.2f}" if self.confidence is not None else ""
|
|
480
|
+
return f"<{self.status.value} {self.subject} {self.attribute}={v!r} by {self.source}{conf} id={self.id[:8]}>"
|
|
481
|
+
|
|
482
|
+
@property
|
|
483
|
+
def source_actor(self) -> Actor:
|
|
484
|
+
"""The source as an :class:`~glosslayer.actors.Actor`, parsed from its ``kind:id`` string."""
|
|
485
|
+
from .actors import Actor
|
|
486
|
+
|
|
487
|
+
return Actor.parse(self.source)
|
|
488
|
+
|
|
489
|
+
@property
|
|
490
|
+
def is_open(self) -> bool:
|
|
491
|
+
"""Whether it still awaits a decision: proposed, reviewed or stale."""
|
|
492
|
+
return self.status in OPEN_STATUSES
|
|
493
|
+
|
|
494
|
+
def to_dict(self) -> dict[str, Any]:
|
|
495
|
+
"""JSON-ready form; ``redacted`` appears only when the value was withheld from the reader."""
|
|
496
|
+
out = {
|
|
497
|
+
"id": self.id,
|
|
498
|
+
"subject": self.subject,
|
|
499
|
+
"attribute": self.attribute,
|
|
500
|
+
"value": self.value,
|
|
501
|
+
"source": self.source,
|
|
502
|
+
"sources": list(self.sources),
|
|
503
|
+
"status": self.status.value,
|
|
504
|
+
"confidence": self.confidence,
|
|
505
|
+
"evidence": list(self.evidence),
|
|
506
|
+
"created_at": self.created_at.isoformat(),
|
|
507
|
+
"updated_at": self.updated_at.isoformat(),
|
|
508
|
+
"created_by": self.created_by,
|
|
509
|
+
"last_comment": self.last_comment,
|
|
510
|
+
"group": self.group,
|
|
511
|
+
}
|
|
512
|
+
if self.redacted:
|
|
513
|
+
out["redacted"] = True
|
|
514
|
+
return out
|
|
515
|
+
|
|
516
|
+
@classmethod
|
|
517
|
+
def from_dict(cls, d: dict[str, Any]) -> Assertion:
|
|
518
|
+
"""Rebuild an assertion from :meth:`to_dict` output."""
|
|
519
|
+
return cls(
|
|
520
|
+
id=d["id"], subject=d["subject"], attribute=d["attribute"], value=d.get("value"),
|
|
521
|
+
source=d["source"], status=Status(d["status"]), confidence=d.get("confidence"),
|
|
522
|
+
created_at=datetime.fromisoformat(d["created_at"]), updated_at=datetime.fromisoformat(d["updated_at"]),
|
|
523
|
+
created_by=d["created_by"], sources=tuple(d.get("sources") or ()),
|
|
524
|
+
evidence=tuple(d.get("evidence") or ()), last_comment=d.get("last_comment"),
|
|
525
|
+
group=d.get("group"), redacted=bool(d.get("redacted")),
|
|
526
|
+
)
|
|
527
|
+
|
|
528
|
+
|
|
529
|
+
def apply_event(current: Assertion | None, event: Event) -> Assertion:
|
|
530
|
+
"""Fold one event into an assertion's state. Pure: the projection is rebuildable from the log."""
|
|
531
|
+
d = event.data
|
|
532
|
+
if event.type is EventType.PROPOSED:
|
|
533
|
+
if current is not None:
|
|
534
|
+
raise InvalidTransition(f"Assertion {event.assertion_id} already exists")
|
|
535
|
+
return Assertion(
|
|
536
|
+
id=event.assertion_id,
|
|
537
|
+
subject=d["subject"],
|
|
538
|
+
attribute=d["attribute"],
|
|
539
|
+
value=d["value"],
|
|
540
|
+
source=d["source"],
|
|
541
|
+
status=Status.PROPOSED,
|
|
542
|
+
confidence=d.get("confidence"),
|
|
543
|
+
created_at=event.ts,
|
|
544
|
+
updated_at=event.ts,
|
|
545
|
+
created_by=event.actor,
|
|
546
|
+
sources=(d["source"],),
|
|
547
|
+
evidence=tuple(d.get("evidence") or ()),
|
|
548
|
+
last_comment=d.get("comment"),
|
|
549
|
+
group=d.get("group"),
|
|
550
|
+
)
|
|
551
|
+
|
|
552
|
+
if current is None:
|
|
553
|
+
raise InvalidTransition(f"Event {event.type.value} for unknown assertion {event.assertion_id}")
|
|
554
|
+
|
|
555
|
+
if event.type is EventType.CORROBORATED:
|
|
556
|
+
sources = current.sources if d["source"] in current.sources else current.sources + (d["source"],)
|
|
557
|
+
conf = current.confidence
|
|
558
|
+
if d.get("confidence") is not None:
|
|
559
|
+
conf = max(conf or 0.0, d["confidence"])
|
|
560
|
+
return replace(
|
|
561
|
+
current,
|
|
562
|
+
sources=sources,
|
|
563
|
+
confidence=conf,
|
|
564
|
+
evidence=current.evidence + tuple(d.get("evidence") or ()),
|
|
565
|
+
updated_at=event.ts,
|
|
566
|
+
)
|
|
567
|
+
|
|
568
|
+
if event.type is EventType.COMMENTED:
|
|
569
|
+
return replace(current, last_comment=d.get("comment"), updated_at=event.ts)
|
|
570
|
+
|
|
571
|
+
if event.type is EventType.REKEYED:
|
|
572
|
+
return replace(
|
|
573
|
+
current,
|
|
574
|
+
subject=d.get("subject", current.subject),
|
|
575
|
+
value=d["value"] if "value" in d else current.value,
|
|
576
|
+
updated_at=event.ts,
|
|
577
|
+
)
|
|
578
|
+
|
|
579
|
+
if not can_apply(event.type, current.status):
|
|
580
|
+
target = EVENT_TARGET_STATUS[event.type]
|
|
581
|
+
raise InvalidTransition(
|
|
582
|
+
f"Cannot move assertion {current.id} from {current.status.value} to {target.value}"
|
|
583
|
+
)
|
|
584
|
+
return replace(
|
|
585
|
+
current,
|
|
586
|
+
status=EVENT_TARGET_STATUS[event.type],
|
|
587
|
+
updated_at=event.ts,
|
|
588
|
+
last_comment=d.get("comment", current.last_comment),
|
|
589
|
+
)
|