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/ledger.py ADDED
@@ -0,0 +1,1654 @@
1
+ """The Gloss facade: the one object hosts embed.
2
+
3
+ import glosslayer
4
+ g = glosslayer.open("sqlite:///gloss.db")
5
+ a = g.propose("field:sales.orders/amount", "description", "Order value incl. VAT",
6
+ source="ai:claude", confidence=0.8)
7
+ g.accept(a.id, actor="human:alice")
8
+ g.current("field:sales.orders/amount") # {'description': 'Order value incl. VAT'}
9
+
10
+ A ``Gloss`` opened like this is the host's own, trusted handle: it reads everything and
11
+ every write names its actor. ``g.as_actor(...)`` returns a view bound to one actor: its
12
+ reads are limited to what the policy lets that actor see, and its writes are made as them.
13
+ """
14
+
15
+ from __future__ import annotations
16
+
17
+ import copy
18
+ import logging
19
+ from collections import defaultdict
20
+ from collections.abc import Callable, Iterable, Iterator, Mapping, Sequence
21
+ from dataclasses import dataclass, field, replace
22
+ from itertools import islice
23
+ from typing import Any
24
+
25
+ from . import policy as P
26
+ from .actors import ActorDirectory, IdentityDirectory, split_actor
27
+ from .ids import Kind, SubjectId, path_covers
28
+ from .model import (
29
+ ATOMIC_KINDS,
30
+ DATASET_REFERENCES,
31
+ LIVE_STATUSES,
32
+ OPEN_STATUSES,
33
+ Assertion,
34
+ Confidentiality,
35
+ Event,
36
+ EventType,
37
+ InvalidTransition,
38
+ Status,
39
+ apply_event,
40
+ can_apply,
41
+ detail_attributes,
42
+ inherited_attributes,
43
+ new_id,
44
+ validate_value,
45
+ value_hash,
46
+ )
47
+ from .policy import Context, Decision, DefaultPolicy, PermissionDenied, Policy, Scope
48
+ from .store import ConcurrentWrite, Query, SQLStore
49
+
50
+ log = logging.getLogger("gloss")
51
+
52
+
53
+ @dataclass
54
+ class Proposal:
55
+ """A fact a source wants Gloss to consider. Sources yield these; Gloss decides what becomes of them.
56
+
57
+ Proposals sharing a ``group`` were made together. For relationships and metrics a group is
58
+ accepted or rejected as a unit, because their facts only make sense together.
59
+ """
60
+
61
+ subject: str
62
+ attribute: str
63
+ value: Any
64
+ confidence: float | None = None
65
+ evidence: list[dict[str, Any]] = field(default_factory=list)
66
+ comment: str | None = None
67
+ group: str | None = None
68
+
69
+
70
+ @dataclass
71
+ class ProposeResult:
72
+ """What became of one proposal: the assertion it landed on, how, and whether it was accepted at once."""
73
+ assertion: Assertion
74
+ outcome: str # "created" | "corroborated" | "unchanged" | "previously_rejected"
75
+ accepted: bool = False # accepted in this same call (asked for, or by a policy rule)
76
+
77
+
78
+ @dataclass
79
+ class RekeyResult:
80
+ """What a rename or move changed: subjects re-keyed, references rewritten, facts sent back."""
81
+
82
+ subjects: dict[str, str] = field(default_factory=dict) # old subject -> new subject
83
+ moved: int = 0 # assertions whose subject changed
84
+ rewritten: int = 0 # assertions whose value named a moved subject
85
+ superseded: int = 0 # moved facts that lost to a value already accepted at the target
86
+ staled: int = 0 # facts sent back to review because they may mention the old name
87
+
88
+
89
+ @dataclass(frozen=True)
90
+ class ReadRecord:
91
+ """Which subjects were handed to which actor, for hosts that keep a record of what AI read."""
92
+
93
+ actor: str | None
94
+ via: str | None
95
+ tool: str
96
+ subjects: tuple[str, ...]
97
+
98
+
99
+ _ACTION_EVENTS = {
100
+ P.REVIEW: EventType.REVIEWED,
101
+ P.ACCEPT: EventType.ACCEPTED,
102
+ P.REJECT: EventType.REJECTED,
103
+ P.RETRACT: EventType.RETRACTED,
104
+ P.REOPEN: EventType.REOPENED,
105
+ P.RESTORE: EventType.RESTORED,
106
+ P.MARK_STALE: EventType.MARKED_STALE,
107
+ }
108
+ # Actions that make a value the accepted one, replacing whatever was accepted before.
109
+ _ACCEPTING = (P.ACCEPT, P.RESTORE)
110
+ # Actions that apply to a whole proposal group for relationships and metrics.
111
+ _GROUPED = (P.ACCEPT, P.REJECT)
112
+
113
+ _UNSET: Any = object()
114
+
115
+
116
+ class _Shared:
117
+ """State common to a ledger and every actor-bound view of it."""
118
+
119
+ def __init__(self) -> None:
120
+ self.subscribers: list[Callable[[list[Event]], None]] = []
121
+ self.readers: list[Callable[[ReadRecord], None]] = []
122
+ self.search_ready = False
123
+
124
+
125
+ class _Batch:
126
+ """Events and the states they produce, collected for one atomic append."""
127
+
128
+ def __init__(self, actor: str, correlation: str, via: str | None):
129
+ self.actor, self.correlation, self.via = actor, correlation, via
130
+ self.events: list[Event] = []
131
+ self.states: dict[str, Assertion] = {}
132
+
133
+ def now(self, a: Assertion) -> Assertion:
134
+ return self.states.get(a.id, a)
135
+
136
+ def emit(self, etype: EventType, assertion: Assertion | None, data: dict[str, Any],
137
+ assertion_id: str | None = None) -> Assertion:
138
+ ev = Event(etype, assertion.id if assertion else assertion_id or new_id(), self.actor,
139
+ {k: v for k, v in data.items() if v is not None},
140
+ correlation=self.correlation, via=self.via)
141
+ state = apply_event(self.now(assertion) if assertion else None, ev)
142
+ self.events.append(ev)
143
+ self.states[state.id] = state
144
+ return state
145
+
146
+ def rollback(self, mark: tuple[int, dict[str, Assertion]]) -> None:
147
+ n, states = mark
148
+ del self.events[n:]
149
+ self.states = states
150
+
151
+ def mark(self) -> tuple[int, dict[str, Assertion]]:
152
+ return len(self.events), dict(self.states)
153
+
154
+
155
+ class Gloss:
156
+ """The ledger facade: proposals, review transitions, readers, search and export over one store.
157
+
158
+ Unbound, it is the host's trusted handle and reads everything; :meth:`as_actor` returns a view whose
159
+ reads are scoped and redacted by the policy and whose writes are made as that actor.
160
+ """
161
+ def __init__(self, store: SQLStore, policy: Policy | None = None, *, directory: ActorDirectory | None = None):
162
+ self.store = store
163
+ self.policy: Policy = policy or DefaultPolicy()
164
+ self.directory: ActorDirectory = directory or IdentityDirectory()
165
+ self.actor: str | None = None
166
+ self.context: Context | None = None
167
+ self.correlation: str | None = None
168
+ self._scope: Scope | None = None
169
+ self._shared = _Shared()
170
+
171
+ # ----------------------------------------------------------------- binding
172
+ def as_actor(
173
+ self,
174
+ actor: str,
175
+ *,
176
+ via: str | None = None,
177
+ context: Mapping[str, Any] | None = None,
178
+ correlation: str | None = None,
179
+ ) -> Gloss:
180
+ """A view of this ledger for one actor: scoped reads, and writes made as them.
181
+
182
+ ``via`` names the channel the actor came through (``"ai:claude"`` for a person working
183
+ through an agent, ``"server:eu-1"``) and is recorded on every event. ``context`` is opaque
184
+ host data handed to the policy. Bind once per request; the scope is resolved here.
185
+ """
186
+ split_actor(actor)
187
+ view = copy.copy(self)
188
+ view.actor = str(actor)
189
+ view.context = Context(via=via, attrs=dict(context or {}))
190
+ view.correlation = correlation or self.correlation
191
+ view._scope = self.policy.scope(view.actor, view.context)
192
+ return view
193
+
194
+ def correlated(self, correlation: str | None = None) -> Gloss:
195
+ """The same ledger with one correlation id on every event it writes (a request, a sync run)."""
196
+ view = copy.copy(self)
197
+ view.correlation = correlation or new_id()
198
+ return view
199
+
200
+ @property
201
+ def scope(self) -> Scope:
202
+ """What this handle reads: everything, unless it is bound to an actor."""
203
+ return self._scope or Scope.everything()
204
+
205
+ def _who(self, actor: str | None, fallback: str | None = None) -> str:
206
+ if self.actor is not None:
207
+ if actor is not None and str(actor) != self.actor:
208
+ raise PermissionDenied(f"This view acts as {self.actor}, not {actor}")
209
+ return self.actor
210
+ who = actor or fallback
211
+ if who is None:
212
+ raise ValueError("Pass actor= (e.g. 'human:alice'), or bind one with g.as_actor(...)")
213
+ split_actor(who)
214
+ return str(who)
215
+
216
+ def _batch(self, actor: str) -> _Batch:
217
+ return _Batch(actor, self.correlation or new_id(), self.context.via if self.context else None)
218
+
219
+ def _q(self, **criteria: Any) -> Query:
220
+ return Query(scope=self._scope, **criteria)
221
+
222
+ def _visible(self, a: Assertion) -> bool:
223
+ return self._scope is None or self._scope.covers(a.scope_path)
224
+
225
+ @property
226
+ def _limit(self) -> Confidentiality | None:
227
+ """The reader's confidentiality ceiling, or None when nothing has to be withheld."""
228
+ if self._scope is None or self._scope.max_confidentiality is Confidentiality.RESTRICTED:
229
+ return None
230
+ return self._scope.max_confidentiality
231
+
232
+ def _hidden_subjects(self, subjects: Iterable[str]) -> set[str]:
233
+ limit = self._limit
234
+ if limit is None:
235
+ return set()
236
+ from .visibility import levels
237
+
238
+ return {s for s, lv in levels(self.store, subjects).items() if lv > limit}
239
+
240
+ def _redact(self, rows: list[Assertion]) -> list[Assertion]:
241
+ if self._limit is None or not rows:
242
+ return rows
243
+ hidden = self._hidden_subjects({a.subject for a in rows})
244
+ detail = detail_attributes()
245
+ return [
246
+ replace(a, value=None, evidence=(), last_comment=None, redacted=True)
247
+ if a.subject in hidden and a.attribute in detail
248
+ else a
249
+ for a in rows
250
+ ]
251
+
252
+ def _redact_events(self, events: list[Event]) -> list[Event]:
253
+ if self._limit is None or not events:
254
+ return events
255
+ known = self.store.get_many({e.assertion_id for e in events})
256
+ hidden = self._hidden_subjects({a.subject for a in known.values()})
257
+ detail = detail_attributes()
258
+ secret = ("value", "from_value", "evidence", "comment", "reason")
259
+ out = []
260
+ for e in events:
261
+ a = known.get(e.assertion_id)
262
+ if a is not None and a.subject in hidden and a.attribute in detail:
263
+ e = replace(e, data={**{k: v for k, v in e.data.items() if k not in secret}, "redacted": True})
264
+ out.append(e)
265
+ return out
266
+
267
+ # ------------------------------------------------------------------ hooks
268
+ def subscribe(self, callback: Callable[[list[Event]], None]) -> Callable[[], None]:
269
+ """Call ``callback(events)`` after every committed write, with ``seq`` filled in.
270
+
271
+ Returns a function that unsubscribes. A failing subscriber is logged and never undoes the write.
272
+ """
273
+ self._shared.subscribers.append(callback)
274
+ return lambda: self._shared.subscribers.remove(callback)
275
+
276
+ def on_read(self, callback: Callable[[ReadRecord], None]) -> Callable[[], None]:
277
+ """Call ``callback(ReadRecord)`` whenever an AI-facing view hands subjects to an actor."""
278
+ self._shared.readers.append(callback)
279
+ return lambda: self._shared.readers.remove(callback)
280
+
281
+ def report_read(self, tool: str, subjects: Iterable[str]) -> None:
282
+ """Tell the ``on_read`` hooks that ``tool`` handed ``subjects`` to this view's actor.
283
+
284
+ A failing hook is logged, never raised: a host's bookkeeping must not break a read.
285
+ """
286
+ if not self._shared.readers:
287
+ return
288
+ record = ReadRecord(self.actor, self.context.via if self.context else None, tool, tuple(subjects))
289
+ for fn in list(self._shared.readers):
290
+ try:
291
+ fn(record)
292
+ except Exception: # a host's bookkeeping must not break a read
293
+ log.exception("gloss read hook failed")
294
+
295
+ def _notify(self, events: list[Event]) -> None:
296
+ for fn in list(self._shared.subscribers):
297
+ try:
298
+ fn(events)
299
+ except Exception:
300
+ log.exception("gloss subscriber failed")
301
+
302
+ def _commit(self, batch: _Batch, also_reindex: Iterable[str] = (),
303
+ renames: dict[str, str] | None = None) -> None:
304
+ """Append a batch and update the search index in one transaction, then tell subscribers."""
305
+ if not batch.events:
306
+ return
307
+ wanted = bool(self._shared.subscribers)
308
+ with self.store.transaction():
309
+ stored = self.store.append(batch.events, list(batch.states.values()), returning=wanted)
310
+ if renames:
311
+ self.store.rename_check_subjects(renames)
312
+ self._reindex_after(batch.events, batch.states, also_reindex)
313
+ if wanted:
314
+ self.store.after_commit(lambda: self._notify(stored))
315
+
316
+ def _reindex_after(self, events: Sequence[Event], states: dict[str, Assertion],
317
+ extra: Iterable[str] = ()) -> None:
318
+ """Update search rows for subjects whose accepted knowledge just changed.
319
+
320
+ Rows that inherit from a changed subject follow only when what they inherit changed: a
321
+ table's confidentiality, or anything about a semantic type.
322
+ """
323
+ changed = set(extra)
324
+ cascade = set(extra)
325
+ for e in events:
326
+ state = states[e.assertion_id]
327
+ subject = state.subject
328
+ hit = e.type in (EventType.ACCEPTED, EventType.SUPERSEDED, EventType.RESTORED, EventType.REKEYED) or (
329
+ e.type in (EventType.MARKED_STALE, EventType.RETRACTED)
330
+ and e.data.get("from_status") == Status.ACCEPTED.value
331
+ )
332
+ if not hit:
333
+ continue
334
+ changed.add(subject)
335
+ if e.type is EventType.REKEYED and e.data.get("from_subject"):
336
+ changed.add(e.data["from_subject"])
337
+ if subject.startswith("type:") or state.attribute == "confidentiality" or e.type is EventType.REKEYED:
338
+ cascade.add(subject)
339
+ if changed:
340
+ from .search_index import reindex
341
+
342
+ reindex(self, changed, cascade=cascade)
343
+
344
+ # ------------------------------------------------------------------ write
345
+ def propose(
346
+ self,
347
+ subject: str | SubjectId,
348
+ attribute: str,
349
+ value: Any,
350
+ *,
351
+ source: str | None = None,
352
+ actor: str | None = None,
353
+ confidence: float | None = None,
354
+ evidence: Sequence[dict[str, Any]] | None = None,
355
+ comment: str | None = None,
356
+ force: bool = False,
357
+ accept: bool = False,
358
+ group: str | None = None,
359
+ ) -> Assertion:
360
+ """Propose one fact and return the assertion it landed on; see :meth:`propose_many` for the rules."""
361
+ return self.propose_many(
362
+ [Proposal(str(subject), attribute, value, confidence, list(evidence or []), comment, group)],
363
+ source=source,
364
+ actor=actor,
365
+ force=force,
366
+ accept=accept,
367
+ )[0].assertion
368
+
369
+ def propose_many(
370
+ self,
371
+ proposals: Iterable[Proposal],
372
+ *,
373
+ source: str | None = None,
374
+ actor: str | None = None,
375
+ force: bool = False,
376
+ accept: bool = False,
377
+ auto_accept: bool = True,
378
+ comment: str | None = None,
379
+ batch_size: int = 500,
380
+ ) -> list[ProposeResult]:
381
+ """Propose many facts efficiently, with de-duplication.
382
+
383
+ * the same value already live (open or accepted) → the source is recorded as *corroborating* it;
384
+ * the same value previously rejected → nothing happens unless ``force`` (stops AI re-suggesting);
385
+ * otherwise a new assertion is created in status *proposed*.
386
+
387
+ What happens next is the policy's call (``Policy.on_propose``): the proposal is queued for
388
+ review, or accepted at once under a named rule (a solo user's own edit, a catalog stating
389
+ structure), or refused. ``auto_accept=False`` queues everything regardless. ``accept=True``
390
+ asks to accept everything proposed here as the actor, which the policy must allow.
391
+
392
+ Proposals are processed in chunks. Each chunk is one lookup and one transaction, and the
393
+ proposed, superseded and accepted events of a chunk are written together.
394
+ """
395
+ actor = self._who(actor, source)
396
+ source = str(source or actor)
397
+ split_actor(source)
398
+ ctx = self.context
399
+ if not self.policy.can(actor, P.PROPOSE, None, ctx):
400
+ raise PermissionDenied(f"{actor} may not propose")
401
+ results: list[ProposeResult] = []
402
+ it = iter(proposals)
403
+ while chunk := list(islice(it, batch_size)):
404
+ prepared = []
405
+ for prop in chunk:
406
+ sid = SubjectId.parse(prop.subject)
407
+ if self._scope is not None and not self._scope.covers(sid.scope_path):
408
+ raise PermissionDenied(f"{actor} may not propose facts about {sid}")
409
+ val = validate_value(sid, prop.attribute, prop.value)
410
+ if prop.confidence is not None and not 0.0 <= prop.confidence <= 1.0:
411
+ raise ValueError("confidence must be between 0 and 1")
412
+ decision = Decision.of(self.policy.on_propose(actor, source, sid, prop.attribute, ctx))
413
+ if decision.outcome == "refuse":
414
+ raise PermissionDenied(
415
+ f"{actor} may not propose {prop.attribute!r} for {sid}"
416
+ + (f": {decision.rule}" if decision.rule else "")
417
+ )
418
+ rule = decision.rule or "policy" if decision.outcome == "accept" and auto_accept else None
419
+ prepared.append((sid, str(sid), val, value_hash(val), prop, rule))
420
+
421
+ for attempt in (1, 2):
422
+ try:
423
+ results += self._propose_chunk(prepared, source, actor, force, accept, comment)
424
+ break
425
+ except ConcurrentWrite:
426
+ if attempt == 2:
427
+ raise
428
+ return results
429
+
430
+ def _propose_chunk(
431
+ self, prepared: list[tuple[Any, ...]], source: str, actor: str, force: bool, accept: bool,
432
+ comment: str | None,
433
+ ) -> list[ProposeResult]:
434
+ ctx = self.context
435
+ index: dict[tuple[str, str, str], list[Assertion]] = defaultdict(list)
436
+ accepted: dict[tuple[str, str], list[Assertion]] = defaultdict(list)
437
+ for a in self.store.find_for_subjects({p[1] for p in prepared}):
438
+ index[(a.subject, a.attribute, value_hash(a.value))].append(a)
439
+ if a.status is Status.ACCEPTED:
440
+ accepted[(a.subject, a.attribute)].append(a)
441
+
442
+ batch = self._batch(actor)
443
+ results: list[ProposeResult] = []
444
+ for _sid, subj, val, vh, prop, rule in prepared:
445
+ key = (subj, prop.attribute, vh)
446
+ matches = [batch.now(m) for m in index[key]]
447
+ live = [m for m in matches if m.status in LIVE_STATUSES]
448
+ existing = live[0] if live else None
449
+ if existing is None and not force:
450
+ rejected = [m for m in matches if m.status is Status.REJECTED]
451
+ if rejected:
452
+ results.append(ProposeResult(rejected[-1], "previously_rejected"))
453
+ continue
454
+ if existing is not None:
455
+ if source in existing.sources and prop.confidence in (None, existing.confidence):
456
+ state, outcome = existing, "unchanged"
457
+ else:
458
+ state = batch.emit(
459
+ EventType.CORROBORATED,
460
+ existing,
461
+ {"source": source, "confidence": prop.confidence, "evidence": prop.evidence},
462
+ )
463
+ outcome = "corroborated"
464
+ else:
465
+ state = batch.emit(
466
+ EventType.PROPOSED,
467
+ None,
468
+ {
469
+ "subject": subj,
470
+ "attribute": prop.attribute,
471
+ "value": val,
472
+ "source": source,
473
+ "confidence": prop.confidence,
474
+ "evidence": prop.evidence,
475
+ "comment": prop.comment,
476
+ "group": prop.group,
477
+ },
478
+ )
479
+ index[key] = [state, *index[key]]
480
+ outcome = "created"
481
+
482
+ took = False
483
+ if state.is_open and (rule or accept):
484
+ if rule is None and not self.policy.can(actor, P.ACCEPT, state, ctx):
485
+ raise PermissionDenied(f"{actor} may not accept assertion {state.id}")
486
+ extra = {"auto": True, "rule": rule} if rule else {"comment": comment}
487
+ state = self._make_accepted(batch, state, EventType.ACCEPTED, accepted, extra)
488
+ took = True
489
+ results.append(ProposeResult(state, outcome, took))
490
+ self._commit(batch)
491
+ # results carry the state at the end of the batch (a later proposal may have superseded an earlier one)
492
+ return [replace(r, assertion=batch.now(r.assertion)) for r in results]
493
+
494
+ def _make_accepted(
495
+ self, batch: _Batch, a: Assertion, etype: EventType, accepted: dict[tuple[str, str], list[Assertion]],
496
+ data: dict[str, Any],
497
+ ) -> Assertion:
498
+ """Emit the events that make ``a`` the accepted value, superseding the one before it."""
499
+ key = (a.subject, a.attribute)
500
+ for prev in accepted[key]:
501
+ prev = batch.now(prev)
502
+ if prev.id != a.id and prev.status is Status.ACCEPTED:
503
+ batch.emit(EventType.SUPERSEDED, prev, {"by": a.id})
504
+ new = batch.emit(etype, a, {"from_status": batch.now(a).status.value, **data})
505
+ accepted[key] = [new]
506
+ return new
507
+
508
+ def transition_many(
509
+ self,
510
+ action: str,
511
+ assertion_ids: Iterable[str],
512
+ *,
513
+ actor: str | None = None,
514
+ comment: str | None = None,
515
+ batch_size: int = 1000,
516
+ **data: Any,
517
+ ) -> tuple[list[Assertion], list[tuple[str, Exception]]]:
518
+ """Apply one action to many assertions with batched reads and one transaction per batch.
519
+
520
+ Returns ``(changed, [(id, error), ...])``; failures do not stop the rest.
521
+ Accepting (or restoring) supersedes the previously accepted value for the same subject and
522
+ attribute. For relationships and metrics, accepting or rejecting one fact of a proposal
523
+ group decides the whole group: all of it applies, or none of it does.
524
+ """
525
+ if action not in _ACTION_EVENTS:
526
+ raise ValueError(f"Unknown action {action!r}")
527
+ actor = self._who(actor)
528
+ done: list[Assertion] = []
529
+ errors: list[tuple[str, Exception]] = []
530
+ it = iter(assertion_ids)
531
+ while ids := list(islice(it, batch_size)):
532
+ for attempt in (1, 2):
533
+ try:
534
+ d, e = self._transition_batch(action, ids, actor, comment, data)
535
+ done += d
536
+ errors += e
537
+ break
538
+ except ConcurrentWrite as exc:
539
+ if attempt == 2:
540
+ errors += [(aid, exc) for aid in ids]
541
+ return done, errors
542
+
543
+ def _transition_batch(
544
+ self, action: str, ids: list[str], actor: str, comment: str | None, data: dict[str, Any]
545
+ ) -> tuple[list[Assertion], list[tuple[str, Exception]]]:
546
+ etype = _ACTION_EVENTS[action]
547
+ ctx = self.context
548
+ current = {k: a for k, a in self.store.get_many(ids).items() if self._visible(a)}
549
+
550
+ # units: an assertion on its own, or every open member of its proposal group
551
+ units: list[list[str]] = []
552
+ seen: set[str] = set()
553
+ if action in _GROUPED:
554
+ grouped = [a for a in current.values() if a.group and a.subject_id.kind in ATOMIC_KINDS]
555
+ members: dict[tuple[str, str], list[Assertion]] = defaultdict(list)
556
+ if grouped:
557
+ for m in self.store.find_for_subjects({a.subject for a in grouped}):
558
+ if m.group and can_apply(etype, m.status):
559
+ members[(m.subject, m.group)].append(m)
560
+ current.setdefault(m.id, m)
561
+ for aid in ids:
562
+ if aid in seen:
563
+ continue
564
+ a = current.get(aid)
565
+ unit = [aid]
566
+ if a is not None and action in _GROUPED and a.group and a.subject_id.kind in ATOMIC_KINDS:
567
+ unit = [aid] + [m.id for m in members[(a.subject, a.group)] if m.id != aid]
568
+ seen.update(unit)
569
+ units.append(unit)
570
+
571
+ accepted: dict[tuple[str, str], list[Assertion]] = defaultdict(list)
572
+ if action in _ACCEPTING:
573
+ for a in self.store.find_for_subjects({c.subject for c in current.values()}, [Status.ACCEPTED]):
574
+ accepted[(a.subject, a.attribute)].append(a)
575
+
576
+ batch = self._batch(actor)
577
+ done: list[Assertion] = []
578
+ errors: list[tuple[str, Exception]] = []
579
+ requested = set(ids)
580
+ for unit in units:
581
+ mark, held = batch.mark(), {k: list(v) for k, v in accepted.items()}
582
+ changed: list[Assertion] = []
583
+ failure: Exception | None = None
584
+ for aid in unit:
585
+ a = current.get(aid)
586
+ a = batch.now(a) if a is not None else None
587
+ if a is None:
588
+ failure = KeyError(f"No assertion {aid!r}")
589
+ elif not self.policy.can(actor, action, a, ctx):
590
+ failure = PermissionDenied(f"{actor} may not {action} assertion {aid}")
591
+ elif not can_apply(etype, a.status):
592
+ failure = InvalidTransition(f"Cannot {action} assertion {aid}: it is {a.status.value}")
593
+ if failure is not None:
594
+ break
595
+ payload = {"comment": comment, **data}
596
+ if len(unit) > 1:
597
+ payload["group"] = a.group
598
+ if action in _ACCEPTING:
599
+ changed.append(self._make_accepted(batch, a, etype, accepted, payload))
600
+ else:
601
+ changed.append(batch.emit(etype, a, {"from_status": a.status.value, **payload}))
602
+ if failure is not None:
603
+ batch.rollback(mark)
604
+ accepted.clear()
605
+ accepted.update(held)
606
+ if len(unit) > 1 and not isinstance(failure, KeyError):
607
+ failure = type(failure)(f"{failure.args[0]} (decided as a group; nothing in the group changed)")
608
+ errors += [(aid, failure) for aid in unit if aid in requested]
609
+ else:
610
+ done += changed
611
+ self._commit(batch)
612
+ return [batch.now(a) for a in done], errors
613
+
614
+ def _transition(
615
+ self, assertion_id: str, action: str, actor: str | None, comment: str | None = None, **data: Any
616
+ ) -> Assertion:
617
+ aid = self._require(assertion_id).id
618
+ done, errors = self.transition_many(action, [aid], actor=actor, comment=comment, **data)
619
+ if errors:
620
+ raise errors[0][1]
621
+ return next(a for a in done if a.id == aid)
622
+
623
+ def review(self, assertion_id: str, *, actor: str | None = None, comment: str | None = None) -> Assertion:
624
+ """Mark a fact reviewed: a reviewer approved it, and it still awaits acceptance."""
625
+ return self._transition(assertion_id, P.REVIEW, actor, comment)
626
+
627
+ def accept(self, assertion_id: str, *, actor: str | None = None, comment: str | None = None) -> Assertion:
628
+ """Make a fact the accepted value, superseding the one accepted before.
629
+
630
+ For a relationship or metric, the rest of its proposal group is accepted with it, or nothing is.
631
+ """
632
+ return self._transition(assertion_id, P.ACCEPT, actor, comment)
633
+
634
+ def reject(self, assertion_id: str, *, actor: str | None = None, comment: str | None = None) -> Assertion:
635
+ """Reject a fact; the same value proposed again is then ignored unless ``force``.
636
+
637
+ For a relationship or metric, the rest of its proposal group is rejected with it, or nothing is.
638
+ """
639
+ return self._transition(assertion_id, P.REJECT, actor, comment)
640
+
641
+ def retract(self, assertion_id: str, *, actor: str | None = None, comment: str | None = None) -> Assertion:
642
+ """Withdraw a fact, open or accepted (the default policy lets a source retract what it stated)."""
643
+ return self._transition(assertion_id, P.RETRACT, actor, comment)
644
+
645
+ def reopen(self, assertion_id: str, *, actor: str | None = None, comment: str | None = None) -> Assertion:
646
+ """Send a rejected or reviewed fact back to *proposed*."""
647
+ return self._transition(assertion_id, P.REOPEN, actor, comment)
648
+
649
+ def restore(self, assertion_id: str, *, actor: str | None = None, comment: str | None = None) -> Assertion:
650
+ """Put a superseded value back as the accepted one (the value now accepted is superseded)."""
651
+ return self._transition(assertion_id, P.RESTORE, actor, comment)
652
+
653
+ def mark_stale(self, assertion_id: str, *, actor: str | None = None, reason: str) -> Assertion:
654
+ """Send a fact back to review because what it describes changed; ``reason`` goes on the event."""
655
+ return self._transition(assertion_id, P.MARK_STALE, actor, reason, reason=reason)
656
+
657
+ def accept_group(self, group: str, *, actor: str | None = None, comment: str | None = None) -> list[Assertion]:
658
+ """Accept every open fact of one proposal group, all or nothing."""
659
+ return self._decide_group(P.ACCEPT, group, actor, comment)
660
+
661
+ def reject_group(self, group: str, *, actor: str | None = None, comment: str | None = None) -> list[Assertion]:
662
+ """Reject every open fact of one proposal group, all or nothing."""
663
+ return self._decide_group(P.REJECT, group, actor, comment)
664
+
665
+ def _decide_group(self, action: str, group: str, actor: str | None, comment: str | None) -> list[Assertion]:
666
+ etype = _ACTION_EVENTS[action]
667
+ ids = [a.id for a in self.store.find(self._q(group=group)) if can_apply(etype, a.status)]
668
+ if not ids:
669
+ raise KeyError(f"No open facts in group {group!r}")
670
+ with self.store.transaction():
671
+ done, errors = self.transition_many(action, ids, actor=actor, comment=comment)
672
+ if errors:
673
+ raise errors[0][1]
674
+ return done
675
+
676
+ def comment(self, assertion_id: str, *, actor: str | None = None, comment: str) -> Assertion:
677
+ """Add a comment to a fact's history without changing its status."""
678
+ actor = self._who(actor)
679
+ current = self._require(assertion_id)
680
+ if not self.policy.can(actor, P.COMMENT, current, self.context):
681
+ raise PermissionDenied(f"{actor} may not comment")
682
+ batch = self._batch(actor)
683
+ state = batch.emit(EventType.COMMENTED, current, {"comment": comment})
684
+ self._commit(batch)
685
+ return state
686
+
687
+ def bulk(
688
+ self, action: str, query: Query, *, actor: str | None = None, comment: str | None = None
689
+ ) -> tuple[list[Assertion], list[tuple[str, str]]]:
690
+ """Apply an action to every matching assertion that can take it. Returns (changed, [(id, error)])."""
691
+ etype = _ACTION_EVENTS[action]
692
+ if self._scope is not None:
693
+ query = replace(query, scope=self._scope)
694
+ ids = [a.id for a in self.store.find(query) if can_apply(etype, a.status)]
695
+ done, errors = self.transition_many(action, ids, actor=actor, comment=comment)
696
+ return done, [(aid, str(exc)) for aid, exc in errors]
697
+
698
+ def add(
699
+ self,
700
+ *objects: Any,
701
+ source: str | None = None,
702
+ actor: str | None = None,
703
+ accept: bool = False,
704
+ comment: str | None = None,
705
+ ) -> Any:
706
+ """Save Table / Relationship / Metric / SemanticType objects as proposals.
707
+
708
+ ``source`` defaults to the actor. With ``accept=True`` the actor accepts everything it just
709
+ proposed, in the same transaction, which the policy must allow. Under a solo policy a
710
+ person's own objects are accepted without asking.
711
+ """
712
+ from .modeling import AddResult
713
+
714
+ props = [p for obj in objects for p in obj.proposals()]
715
+ results = self.propose_many(props, source=source, actor=actor, accept=accept, comment=comment)
716
+ out = AddResult()
717
+ for r in results:
718
+ setattr(out, r.outcome, getattr(out, r.outcome) + 1)
719
+ out.assertion_ids = list(dict.fromkeys(r.assertion.id for r in results))
720
+ out.accepted = len({r.assertion.id for r in results if r.accepted})
721
+ return out
722
+
723
+ def apply(
724
+ self,
725
+ *objects: Any,
726
+ source: str | None = None,
727
+ actor: str | None = None,
728
+ accept: bool = False,
729
+ comment: str | None = None,
730
+ ) -> Any:
731
+ """Like :meth:`add`, and converge: what this source no longer declares is retracted.
732
+
733
+ For a model kept in code. Facts the same ``source`` stated earlier about these objects (a
734
+ table with its columns and metrics, a relationship, a metric, a type) that the objects no
735
+ longer declare are retracted, so removing a column from a ``Table`` removes what was said
736
+ about it. Facts other sources also stated are left alone: they are no longer only yours.
737
+ """
738
+ who = self._who(actor, source)
739
+ src = str(source or who)
740
+ declared: set[tuple[str, str, str]] = set()
741
+ covered: list[Query] = []
742
+ for obj in objects:
743
+ for p in obj.proposals():
744
+ sid = SubjectId.parse(p.subject)
745
+ declared.add((str(sid), p.attribute, value_hash(validate_value(sid, p.attribute, p.value))))
746
+ key = getattr(obj, "key", None)
747
+ covered.append(Query(dataset=key) if key else Query(subject=str(obj.subject)))
748
+ with self.store.transaction():
749
+ out = self.add(*objects, source=source, actor=actor, accept=accept, comment=comment)
750
+ gone = [
751
+ a.id
752
+ for q in covered
753
+ for a in self.store.find(replace(q, statuses=list(LIVE_STATUSES)))
754
+ if a.sources == (src,) and (a.subject, a.attribute, value_hash(a.value)) not in declared
755
+ ]
756
+ done, errors = self.transition_many(
757
+ P.RETRACT, list(dict.fromkeys(gone)), actor=who, comment=comment or "no longer declared"
758
+ )
759
+ if errors:
760
+ raise errors[0][1]
761
+ out.retracted = len(done)
762
+ return out
763
+
764
+ # ---------------------------------------------------------------- re-keying
765
+ def rekey(
766
+ self, old: str | SubjectId, new: str | SubjectId, *, actor: str | None = None, comment: str | None = None
767
+ ) -> RekeyResult:
768
+ """Record that a subject was renamed or moved, so everything known about it follows.
769
+
770
+ ``old`` and ``new`` are subjects of the same kind:
771
+
772
+ * a dataset: the dataset, its fields and its metrics move; relationships that join it are rewritten;
773
+ * a field (same dataset): the column is renamed; keys and joins that list it are rewritten, and
774
+ metrics that seem to use it go back to review;
775
+ * a relationship, metric or semantic type: it is renamed or moved to another namespace; fields
776
+ using a renamed type are rewritten.
777
+
778
+ Nothing is lost and nothing is edited: each affected assertion gets a ``rekeyed`` event, so
779
+ ``history()`` of the new subject shows its whole past. If the target already has an accepted
780
+ value for an attribute, that one stays and the moved one is superseded.
781
+ """
782
+ o, n = SubjectId.parse(old), SubjectId.parse(new)
783
+ if o.kind is not n.kind:
784
+ raise ValueError(f"Cannot re-key a {o.kind.value} as a {n.kind.value}")
785
+ if o == n:
786
+ raise ValueError(f"{o} is already its own key")
787
+ if o.kind is Kind.FIELD and o.dataset != n.dataset:
788
+ raise ValueError("A field moves with its dataset; re-key the dataset instead")
789
+ actor = self._who(actor)
790
+ moves: dict[str, tuple[Assertion, str | None, Any]] = {}
791
+ stale: list[tuple[Assertion, str]] = []
792
+
793
+ if o.kind is Kind.DATASET:
794
+ for a in self.store.find(Query(dataset=o.dataset)):
795
+ moves[a.id] = (a, str(replace(a.subject_id, dataset=n.dataset)), _UNSET)
796
+ for attr in DATASET_REFERENCES:
797
+ for a in self.store.find(Query(attribute=attr, value_hash=value_hash(o.dataset))):
798
+ moves[a.id] = (a, None, n.dataset)
799
+ self._stale_renamed_table(o.dataset, n.dataset, moves, stale)
800
+ else:
801
+ for a in self.store.find(Query(subject=str(o))):
802
+ moves[a.id] = (a, str(n), _UNSET)
803
+ if o.kind is Kind.TYPE:
804
+ for a in self.store.find(Query(attribute="semantic_type", value_hash=value_hash(o.ref))):
805
+ moves[a.id] = (a, None, n.ref)
806
+ if o.kind is Kind.FIELD:
807
+ self._field_references(o, n, moves, stale)
808
+ if not moves:
809
+ raise KeyError(f"Nothing known about {o}")
810
+ return self._apply_rekey(moves, stale, actor, comment)
811
+
812
+ def rekey_namespace(
813
+ self, old: str, new: str, *, actor: str | None = None, comment: str | None = None
814
+ ) -> RekeyResult:
815
+ """Record that a whole path was renamed or moved: a catalog, a schema, a namespace.
816
+
817
+ Every subject at or under ``old`` (datasets by key, relationships, metrics and types by
818
+ namespace) moves to the same place under ``new``, and facts naming them are rewritten.
819
+ """
820
+ old, new = old.rstrip("."), new.rstrip(".")
821
+ if not old or not new:
822
+ raise ValueError("Give the old and the new path")
823
+ if path_covers(old, new) or path_covers(new, old):
824
+ raise ValueError(f"Cannot move {old!r} to {new!r}: one path contains the other")
825
+ actor = self._who(actor)
826
+ moves: dict[str, tuple[Assertion, str | None, Any]] = {}
827
+ types: dict[str, str] = {}
828
+ for a in self.store.find(Query(namespace=old)):
829
+ target = a.subject_id.moved(old, new)
830
+ if target is None:
831
+ continue
832
+ moves[a.id] = (a, str(target), _UNSET)
833
+ if target.kind is Kind.TYPE:
834
+ types[a.subject_id.ref] = target.ref
835
+ if not moves:
836
+ raise KeyError(f"Nothing known under {old!r}")
837
+ from .ids import replace_prefix
838
+
839
+ for a in self.store.find(Query(kind=Kind.RELATIONSHIP.value, attributes=DATASET_REFERENCES)):
840
+ if isinstance(a.value, str) and path_covers(old, a.value):
841
+ subject = moves[a.id][1] if a.id in moves else None
842
+ moves[a.id] = (a, subject, replace_prefix(a.value, old, new))
843
+ for old_ref, new_ref in types.items():
844
+ for a in self.store.find(Query(attribute="semantic_type", value_hash=value_hash(old_ref))):
845
+ subject = moves[a.id][1] if a.id in moves else None
846
+ moves[a.id] = (a, subject, new_ref)
847
+ return self._apply_rekey(moves, [], actor, comment)
848
+
849
+ def _field_references(
850
+ self, o: SubjectId, n: SubjectId, moves: dict[str, tuple[Assertion, str | None, Any]],
851
+ stale: list[tuple[Assertion, str]],
852
+ ) -> None:
853
+ """Value rewrites and stale candidates for a renamed column."""
854
+ from .references import mentions_column, quote_ident
855
+
856
+ ds, was, now = o.dataset or "", o.name or "", n.name or ""
857
+
858
+ def swap(names: list[str]) -> list[str]:
859
+ return [now if c == was else c for c in names]
860
+
861
+ for a in self.store.find(Query(subject=str(SubjectId.for_dataset(ds)),
862
+ attributes=("primary_key", "unique_keys"))):
863
+ if a.attribute == "primary_key" and was in (a.value or []):
864
+ moves[a.id] = (a, None, swap(a.value))
865
+ elif a.attribute == "unique_keys" and any(was in k for k in a.value or []):
866
+ moves[a.id] = (a, None, [swap(k) for k in a.value])
867
+ # relationship columns: from_columns belong to the `from` dataset, to_columns to the `to` dataset
868
+ ends: dict[str, set[str]] = defaultdict(set)
869
+ for attr in DATASET_REFERENCES:
870
+ for a in self.store.find(Query(attribute=attr, value_hash=value_hash(ds))):
871
+ ends[a.subject].add(f"{attr}_columns")
872
+ for a in self.store.find_for_subjects(ends, attributes=("from_columns", "to_columns")):
873
+ if a.attribute in ends[a.subject] and was in (a.value or []):
874
+ moves[a.id] = (a, None, swap(a.value))
875
+ for a_id, (a, subject, _value) in list(moves.items()):
876
+ if subject and a.attribute == "expression" and a.value == {"sql": quote_ident(was)}:
877
+ moves[a_id] = (a, subject, {"sql": quote_ident(now)})
878
+ reason = f"column {was!r} of {ds} was renamed to {now!r}"
879
+ for a in self.store.find(Query(kind=Kind.METRIC.value, attribute="expression",
880
+ statuses=[Status.PROPOSED, Status.REVIEWED, Status.ACCEPTED])):
881
+ if mentions_column(a.value, ds, was, scoped=a.dataset == ds):
882
+ stale.append((a, reason))
883
+
884
+ def _stale_renamed_table(
885
+ self, old: str, new: str, moves: dict[str, tuple[Assertion, str | None, Any]],
886
+ stale: list[tuple[Assertion, str]],
887
+ ) -> None:
888
+ """Metrics outside the table that name it in SQL go back to review when its short name changed."""
889
+ from .references import mentions_dataset, short_name
890
+
891
+ if short_name(old) == short_name(new):
892
+ return
893
+ reason = f"table {old} was renamed to {new}"
894
+ for a in self.store.find(Query(kind=Kind.METRIC.value, attribute="expression",
895
+ statuses=[Status.PROPOSED, Status.REVIEWED, Status.ACCEPTED])):
896
+ if mentions_dataset(a.value, old):
897
+ stale.append((a, reason))
898
+
899
+ def _apply_rekey(
900
+ self, moves: dict[str, tuple[Assertion, str | None, Any]], stale: list[tuple[Assertion, str]],
901
+ actor: str, comment: str | None,
902
+ ) -> RekeyResult:
903
+ ctx = self.context or Context()
904
+ result = RekeyResult()
905
+ for a, subject, _value in moves.values():
906
+ if subject is None:
907
+ continue
908
+ if not self._visible(a):
909
+ raise KeyError(f"Nothing known about {a.subject}")
910
+ to_ctx = Context(via=ctx.via, attrs={**ctx.attrs, "to": subject})
911
+ if not self.policy.can(actor, P.REKEY, a, to_ctx):
912
+ raise PermissionDenied(f"{actor} may not move {a.subject} to {subject}")
913
+ result.subjects[a.subject] = subject
914
+
915
+ moving = set(moves)
916
+ taken: dict[tuple[str, str], Assertion] = {}
917
+ for a in self.store.find_for_subjects(set(result.subjects.values()), [Status.ACCEPTED]):
918
+ if a.id not in moving:
919
+ taken[(a.subject, a.attribute)] = a
920
+
921
+ batch = self._batch(actor)
922
+ for a, subject, value in moves.values():
923
+ data: dict[str, Any] = {"comment": comment}
924
+ if subject is not None:
925
+ data.update(from_subject=a.subject, subject=subject)
926
+ result.moved += 1
927
+ if value is not _UNSET:
928
+ data.update(from_value=a.value, value=value)
929
+ result.rewritten += 1
930
+ state = batch.emit(EventType.REKEYED, a, data)
931
+ winner = taken.get((state.subject, state.attribute))
932
+ if subject is not None and winner is not None and state.status is Status.ACCEPTED:
933
+ batch.emit(EventType.SUPERSEDED, state, {"by": winner.id})
934
+ result.superseded += 1
935
+ for a, reason in stale:
936
+ now = batch.now(a)
937
+ if can_apply(EventType.MARKED_STALE, now.status):
938
+ batch.emit(EventType.MARKED_STALE, now,
939
+ {"from_status": now.status.value, "comment": reason, "reason": reason})
940
+ result.staled += 1
941
+ fields = {o: n for o, n in result.subjects.items() if o.startswith("field:")}
942
+ self._commit(batch, also_reindex=set(result.subjects) | set(result.subjects.values()), renames=fields)
943
+ return result
944
+
945
+ # ------------------------------------------------------------------ export
946
+ def to_ossie(
947
+ self,
948
+ *,
949
+ name: str | None = None,
950
+ include_pending: bool = False,
951
+ tables: str | None = None,
952
+ annotate: bool = True,
953
+ namespace: str | None = None,
954
+ ) -> Any:
955
+ """The model as an Apache Ossie document (``.document`` dict, ``.warnings``, ``.to_yaml()``).
956
+
957
+ Accepted facts only unless ``include_pending``; ``tables`` limits it to keys with that prefix.
958
+ """
959
+ from .ossie.exporter import to_ossie
960
+
961
+ return to_ossie(self, name=name, include_pending=include_pending, annotate=annotate,
962
+ dataset_prefix=tables, namespace=namespace)
963
+
964
+ def to_yaml(
965
+ self,
966
+ path: Any = None,
967
+ *,
968
+ name: str | None = None,
969
+ include_pending: bool = False,
970
+ tables: str | None = None,
971
+ annotate: bool = True,
972
+ namespace: str | None = None,
973
+ ) -> str:
974
+ """The model as Ossie YAML text; also written to ``path`` when given."""
975
+ text = self.to_ossie(name=name, include_pending=include_pending, tables=tables, annotate=annotate,
976
+ namespace=namespace).to_yaml()
977
+ if path:
978
+ from pathlib import Path
979
+
980
+ Path(path).write_text(text)
981
+ return text
982
+
983
+ # ------------------------------------------------------------- read as objects
984
+ def table(self, key: str, *, include_pending: bool = False) -> Any:
985
+ """One table as a :class:`glosslayer.Table` (columns, keys, semantic types, its metrics).
986
+
987
+ Readers return accepted facts by default; ``include_pending=True`` adds open proposals.
988
+ """
989
+ from .modeling import Table
990
+
991
+ return Table.load(self, key, include_pending=include_pending)
992
+
993
+ def __getitem__(self, key: str) -> Any:
994
+ """``g["shop.customers"]`` → Table. Full subjects work too (accepted facts only):
995
+
996
+ ``g["type:email_address"]`` → SemanticType, ``g["relationship:orders_customers"]`` → Relationship,
997
+ ``g["metric:shop.orders/revenue"]`` → Metric, ``g["field:shop.customers/email"]`` → Column.
998
+ Use ``g.table(key, include_pending=True)`` and friends to include proposals.
999
+ """
1000
+ if not isinstance(key, str):
1001
+ raise TypeError("Gloss keys are strings: a table key like 'shop.customers' or a subject like 'type:x'")
1002
+ kind = key.split(":", 1)[0] if ":" in key else None
1003
+ if kind not in {k.value for k in Kind}:
1004
+ return self._get_or_hint(lambda: self.table(key), key)
1005
+ sid = SubjectId.parse(key)
1006
+ if sid.kind is Kind.DATASET:
1007
+ return self._get_or_hint(lambda: self.table(sid.dataset), key)
1008
+ if sid.kind is Kind.FIELD:
1009
+ table = self._get_or_hint(lambda: self.table(sid.dataset), key)
1010
+ if sid.name not in table:
1011
+ raise KeyError(f"Table {sid.dataset!r} has no accepted column {sid.name!r}")
1012
+ return table[sid.name]
1013
+ if sid.kind is Kind.TYPE:
1014
+ return self._get_or_hint(lambda: self.semantic_type(sid.ref), key)
1015
+ if sid.kind is Kind.RELATIONSHIP:
1016
+ return self._get_or_hint(lambda: self.relationship(sid.ref), key)
1017
+ if sid.kind is Kind.METRIC:
1018
+ return self._get_or_hint(
1019
+ lambda: self.metric(sid.name, table=sid.dataset, namespace=sid.namespace), key
1020
+ )
1021
+ raise KeyError(f"Use g.current({key!r}) for the model itself")
1022
+
1023
+ def _get_or_hint(self, fetch: Any, key: str) -> Any:
1024
+ try:
1025
+ return fetch()
1026
+ except KeyError:
1027
+ pending = self.find(subject_prefix=_subject_prefix_for(key), statuses=list(OPEN_STATUSES), limit=1)
1028
+ if pending:
1029
+ raise KeyError(
1030
+ f"{key!r} has only proposed facts so far; accept them, or read the proposals with "
1031
+ f"include_pending=True (e.g. g.table(..., include_pending=True))"
1032
+ ) from None
1033
+ raise KeyError(f"Nothing known about {key!r}") from None
1034
+
1035
+ def __contains__(self, key: object) -> bool:
1036
+ try:
1037
+ self[key] # type: ignore[index]
1038
+ except (KeyError, TypeError, ValueError):
1039
+ return False
1040
+ return True
1041
+
1042
+ def tables(self, prefix: str | None = None, *, include_pending: bool = False) -> list[Any]:
1043
+ """All tables (optionally those whose key starts with ``prefix``), sorted by key."""
1044
+ from .modeling import Table, read_statuses, types_from_state
1045
+
1046
+ state = self.snapshot(read_statuses(include_pending), dataset_prefix=prefix, relationships=False)
1047
+ types = types_from_state(state)
1048
+ return [Table._from_state(key, state, types) for key in sorted(state.datasets)]
1049
+
1050
+ def semantic_type(self, name: str, *, include_pending: bool = False) -> Any:
1051
+ """One semantic type as a :class:`glosslayer.SemanticType`; ``name`` may be ``"crm::email_address"``."""
1052
+ from .modeling import SemanticType
1053
+
1054
+ return SemanticType.load(self, name, include_pending=include_pending)
1055
+
1056
+ def semantic_types(self, *, include_pending: bool = False) -> list[Any]:
1057
+ """All semantic types, sorted by name."""
1058
+ from .modeling import read_statuses, types_from_state
1059
+
1060
+ types = types_from_state(self.snapshot(read_statuses(include_pending), datasets=[]))
1061
+ return [types[n] for n in sorted(types)]
1062
+
1063
+ def relationships(self, table: str | None = None, *, include_pending: bool = False) -> list[Any]:
1064
+ """All complete relationships (optionally only those touching ``table``), sorted by name.
1065
+
1066
+ A relationship whose accepted facts do not yet form a valid join is left out, not raised.
1067
+ """
1068
+ from .modeling import read_statuses, relationship_from_attrs
1069
+
1070
+ state = self.snapshot(read_statuses(include_pending), datasets=[table] if table else [])
1071
+ out = []
1072
+ for ref in sorted(state.relationships):
1073
+ rel = relationship_from_attrs(ref, state.relationships[ref].attrs)
1074
+ if rel is not None and (table is None or table in (rel.from_table, rel.to_table)):
1075
+ out.append(rel)
1076
+ return self._with_versions(out)
1077
+
1078
+ def relationship(self, name: str, *, include_pending: bool = False) -> Any:
1079
+ """One relationship as a :class:`glosslayer.Relationship`; ``name`` may be ``"sales::orders_customers"``."""
1080
+ from .modeling import read_statuses, relationship_from_attrs
1081
+
1082
+ sid = SubjectId.for_relationship(name)
1083
+ rel = relationship_from_attrs(sid.ref, self._attrs(sid, read_statuses(include_pending)))
1084
+ if rel is None:
1085
+ raise KeyError(f"No complete relationship {name!r}"
1086
+ + ("" if include_pending else " (pass include_pending=True to see proposals)"))
1087
+ return self._with_versions([rel])[0]
1088
+
1089
+ def metrics(self, table: str | None = None, *, include_pending: bool = False) -> list[Any]:
1090
+ """Metrics as :class:`glosslayer.Metric`: ledger-wide and namespace ones, plus every table's own.
1091
+
1092
+ With ``table`` only that table's metrics are returned.
1093
+ """
1094
+ from .modeling import metric_from_attrs, read_statuses
1095
+
1096
+ state = self.snapshot(read_statuses(include_pending), datasets=[table] if table else None)
1097
+ out = []
1098
+ if table is None:
1099
+ for ref in sorted(state.metrics):
1100
+ m = metric_from_attrs(ref, state.metrics[ref].attrs)
1101
+ if m is not None:
1102
+ out.append(m)
1103
+ for key in sorted(state.datasets):
1104
+ if table is not None and key != table:
1105
+ continue
1106
+ for name in sorted(state.datasets[key].metrics):
1107
+ m = metric_from_attrs(name, state.datasets[key].metrics[name].attrs, table=key)
1108
+ if m is not None:
1109
+ out.append(m)
1110
+ return self._with_versions(out)
1111
+
1112
+ def metric(self, name: str, *, table: str | None = None, namespace: str | None = None,
1113
+ include_pending: bool = False) -> Any:
1114
+ """One metric; give ``table`` for a table's own metric, ``namespace`` for a namespace's."""
1115
+ from .modeling import metric_from_attrs, read_statuses
1116
+
1117
+ sid = SubjectId.for_metric(name, table, namespace=namespace)
1118
+ m = metric_from_attrs(sid.name if table else sid.ref, self._attrs(sid, read_statuses(include_pending)),
1119
+ table=table)
1120
+ if m is None:
1121
+ where = f" on {table!r}" if table else ""
1122
+ raise KeyError(f"No metric {name!r}{where}"
1123
+ + ("" if include_pending else " (pass include_pending=True to see proposals)"))
1124
+ return self._with_versions([m])[0]
1125
+
1126
+ def _attrs(self, subject: SubjectId, statuses: Sequence[Status]) -> dict[str, Any]:
1127
+ """Best value per attribute of one subject (accepted wins, then the most recent)."""
1128
+ rows = self._redact(self.store.find_for_subjects([str(subject)], statuses, scope=self._scope))
1129
+ return {a.attribute: a.value for a in _best(rows).values() if not a.redacted}
1130
+
1131
+ def _with_versions(self, objects: list[Any]) -> list[Any]:
1132
+ versions = self.store.subject_versions(str(o.subject) for o in objects)
1133
+ for o in objects:
1134
+ o.version = versions.get(str(o.subject))
1135
+ return objects
1136
+
1137
+ def version(self, subject: str | SubjectId) -> int | None:
1138
+ """A number that grows whenever the accepted definition of ``subject`` may have changed.
1139
+
1140
+ It is the sequence number of the last accepting, superseding, restoring, retracting, staling
1141
+ or re-keying event on the subject's facts; None when it never had an accepted fact.
1142
+ """
1143
+ s = str(SubjectId.parse(subject))
1144
+ return self.store.subject_versions([s]).get(s)
1145
+
1146
+ # ------------------------------------------------------------------- read
1147
+ def _require(self, assertion_id: str) -> Assertion:
1148
+ a = self.store.get(assertion_id)
1149
+ if a is None and 4 <= len(assertion_id) < 32: # allow unambiguous short ids, git-style
1150
+ matches = [m for m in self.store.by_id_prefix(assertion_id) if self._visible(m)]
1151
+ if len(matches) > 1:
1152
+ raise KeyError(f"Assertion id prefix {assertion_id!r} is ambiguous")
1153
+ a = matches[0] if matches else None
1154
+ if a is None or not self._visible(a):
1155
+ raise KeyError(f"No assertion {assertion_id!r}")
1156
+ return a
1157
+
1158
+ def get(self, assertion_id: str) -> Assertion:
1159
+ """One assertion by id or short prefix, redacted; ``KeyError`` when unknown or out of scope."""
1160
+ return self._redact([self._require(assertion_id)])[0]
1161
+
1162
+ def find(self, **criteria: Any) -> list[Assertion]:
1163
+ """Assertions matching :class:`~glosslayer.store.Query` criteria, within this reader's scope and redacted.
1164
+
1165
+ For example ``subject=``, ``dataset=``, ``attribute=``, ``statuses=``, ``limit=``.
1166
+ """
1167
+ if criteria.get("statuses") is not None:
1168
+ criteria["statuses"] = [Status(s) for s in criteria["statuses"]]
1169
+ return self._redact(self.store.find(self._q(**criteria)))
1170
+
1171
+ def count(self, **criteria: Any) -> int:
1172
+ """How many assertions match, for paging through ``find(limit=..., offset=...)``."""
1173
+ if criteria.get("statuses") is not None:
1174
+ criteria["statuses"] = [Status(s) for s in criteria["statuses"]]
1175
+ criteria.pop("limit", None)
1176
+ criteria.pop("offset", None)
1177
+ return self.store.count(self._q(**criteria))
1178
+
1179
+ def pending(self, **criteria: Any) -> list[Assertion]:
1180
+ """Everything that needs a human: proposed, reviewed and stale facts."""
1181
+ criteria.setdefault("statuses", list(OPEN_STATUSES))
1182
+ return self.find(**criteria)
1183
+
1184
+ def current(self, subject: str | SubjectId) -> dict[str, Any]:
1185
+ """Accepted value per attribute for one subject."""
1186
+ rows = self.find(subject=str(SubjectId.parse(subject)), statuses=[Status.ACCEPTED])
1187
+ return {a.attribute: a.value for a in rows if not a.redacted}
1188
+
1189
+ def current_many(
1190
+ self, subjects: Iterable[str | SubjectId], *, attributes: Sequence[str] | None = None
1191
+ ) -> dict[str, dict[str, Any]]:
1192
+ """Accepted values for many subjects in one lookup: ``{subject: {attribute: value}}``."""
1193
+ rows = self.store.find_for_subjects(
1194
+ {str(SubjectId.parse(s)) for s in subjects}, [Status.ACCEPTED], attributes=attributes, scope=self._scope
1195
+ )
1196
+ out: dict[str, dict[str, Any]] = defaultdict(dict)
1197
+ for a in self._redact(rows):
1198
+ if not a.redacted:
1199
+ out[a.subject][a.attribute] = a.value
1200
+ return dict(out)
1201
+
1202
+ def effective(self, subject: str | SubjectId) -> dict[str, Any]:
1203
+ """Accepted values for one subject, including what a field inherits from its semantic type."""
1204
+ own = self.current(subject)
1205
+ tname = own.get("semantic_type")
1206
+ if not tname:
1207
+ return own
1208
+ t = self.current(SubjectId.for_type(tname))
1209
+ out = dict(own)
1210
+ for attr in inherited_attributes():
1211
+ if attr not in out and attr in t:
1212
+ out[attr] = t[attr]
1213
+ if t.get("checks"):
1214
+ out["checks"] = list(t["checks"]) + [c for c in own.get("checks", []) if c not in t["checks"]]
1215
+ return out
1216
+
1217
+ def type_usages(self, type_name: str) -> list[str]:
1218
+ """Subjects of every field that (accepted) uses a semantic type."""
1219
+ ref = SubjectId.for_type(type_name).ref
1220
+ rows = self.store.find(self._q(attribute="semantic_type", value_hash=value_hash(ref),
1221
+ statuses=[Status.ACCEPTED]))
1222
+ return sorted(a.subject for a in rows)
1223
+
1224
+ def record_check_results(self, results: Iterable[Any], *, runner: str = "system:checks",
1225
+ run_id: str | None = None) -> str:
1226
+ """Log a run of data quality checks (see glosslayer.checks). Returns the run id.
1227
+
1228
+ Pass the host's own ``run_id`` to tie the results to the run that produced them.
1229
+ """
1230
+ run_id = run_id or new_id()
1231
+ self.store.append_check_results([
1232
+ {
1233
+ "ts": r.ts, "subject": r.subject, "check": r.check, "passed": r.passed,
1234
+ "failed_rows": r.failed_rows, "total_rows": r.total_rows, "origin": r.origin,
1235
+ "error": r.error, "runner": str(runner), "run_id": run_id,
1236
+ }
1237
+ for r in results
1238
+ ])
1239
+ return run_id
1240
+
1241
+ def check_history(self, subject: str | SubjectId | None = None, *, dataset: str | None = None,
1242
+ run_id: str | None = None, limit: int | None = 200) -> list[dict[str, Any]]:
1243
+ """Logged check results, newest first, for one field, a whole dataset or one run."""
1244
+ prefix = f"field:{dataset}/" if dataset else None
1245
+ rows = self.store.check_results(str(SubjectId.parse(subject)) if subject else None, prefix, limit,
1246
+ run_id=run_id)
1247
+ if self._scope is not None:
1248
+ rows = [r for r in rows if self._scope.covers_subject(r["subject"])]
1249
+ return rows
1250
+
1251
+ def history(self, subject: str | SubjectId) -> list[Event]:
1252
+ """Every event of the facts now at ``subject``, including those from before it was re-keyed."""
1253
+ sid = SubjectId.parse(subject)
1254
+ if self._scope is not None and not self._scope.covers(sid.scope_path):
1255
+ return []
1256
+ return self._redact_events(self.store.events_for_subject(str(sid)))
1257
+
1258
+ def log(self, after_seq: int = 0, limit: int | None = None, *, correlation: str | None = None) -> list[Event]:
1259
+ """Events after ``after_seq`` in ``seq`` order, optionally one ``correlation``; scoped, redacted."""
1260
+ return self._redact_events(
1261
+ self.store.events(after_seq=after_seq, limit=limit, correlation=correlation, scope=self._scope)
1262
+ )
1263
+
1264
+ def progress(self, dataset_prefix: str | None = None) -> dict[str, dict[str, int]]:
1265
+ """Review progress per dataset or namespace: {path: {status: count, ...}}."""
1266
+ counts = self.store.count_by_status(self._q())
1267
+ out: dict[str, dict[str, int]] = defaultdict(lambda: {s.value: 0 for s in Status})
1268
+ for (path, st), n in counts.items():
1269
+ key = path or "(model-level)"
1270
+ if dataset_prefix and not key.startswith(dataset_prefix):
1271
+ continue
1272
+ out[key][st.value] += n
1273
+ return dict(sorted(out.items()))
1274
+
1275
+ def snapshot(
1276
+ self,
1277
+ statuses: Iterable[Status] = (Status.ACCEPTED,),
1278
+ *,
1279
+ datasets: Iterable[str] | None = None,
1280
+ dataset_prefix: str | None = None,
1281
+ relationships: bool = True,
1282
+ ) -> ModelState:
1283
+ """The model as nested dicts, built from assertions in the given statuses.
1284
+
1285
+ With ``datasets`` only those tables are loaded (plus relationships touching them, semantic
1286
+ types and model-level facts); with ``dataset_prefix`` those whose key starts with it. Both
1287
+ keep per-table lookups fast on big models.
1288
+
1289
+ When several assertions for the same subject+attribute qualify, accepted wins,
1290
+ then the most recent one. On an actor-bound view the snapshot holds only what that
1291
+ actor may read, with details above their confidentiality level removed.
1292
+ """
1293
+ wanted = [Status(s) for s in statuses]
1294
+ state = ModelState()
1295
+ find = self.store.find
1296
+ if datasets is None and dataset_prefix is None:
1297
+ source_rows = find(self._q(statuses=wanted))
1298
+ else:
1299
+ source_rows = []
1300
+ keys = list(datasets or [])
1301
+ for k in keys:
1302
+ source_rows += find(self._q(dataset=k, statuses=wanted))
1303
+ if dataset_prefix is not None:
1304
+ source_rows += find(self._q(dataset_prefix=dataset_prefix, statuses=wanted))
1305
+ if relationships and datasets is not None:
1306
+ if keys:
1307
+ rel_subjects = {
1308
+ a.subject
1309
+ for k in keys
1310
+ for attr in DATASET_REFERENCES
1311
+ for a in find(self._q(attribute=attr, value_hash=value_hash(k), statuses=wanted))
1312
+ }
1313
+ source_rows += self.store.find_for_subjects(rel_subjects, wanted, scope=self._scope)
1314
+ else:
1315
+ source_rows += find(self._q(kind=Kind.RELATIONSHIP.value, statuses=wanted))
1316
+ elif relationships:
1317
+ source_rows += find(self._q(kind=Kind.RELATIONSHIP.value, statuses=wanted))
1318
+ source_rows += find(self._q(kind=Kind.TYPE.value, statuses=wanted))
1319
+ source_rows += find(self._q(kind=Kind.MODEL.value, statuses=wanted))
1320
+ # insert in creation order so fields keep the order their catalog/source gave them
1321
+ for a in sorted(_best(source_rows).values(), key=lambda x: x.created_at):
1322
+ state.add(SubjectId.parse(a.subject), a.attribute, a)
1323
+ if self._scope is not None and not self._scope.all_paths:
1324
+ state.relationships = {
1325
+ ref: r for ref, r in state.relationships.items()
1326
+ if all(self._scope.covers(r.attrs[side]) for side in DATASET_REFERENCES
1327
+ if isinstance(r.attrs.get(side), str))
1328
+ }
1329
+ state.apply_types()
1330
+ if self._limit is not None:
1331
+ state.redact(self._limit)
1332
+ return state
1333
+
1334
+ # ------------------------------------------------------------- maintenance
1335
+ def rebuild_projection(self) -> int:
1336
+ """Recompute every assertion's state (and the search index) from the event log."""
1337
+ states: dict[str, Assertion] = {}
1338
+ for ev in self.store.events():
1339
+ states[ev.assertion_id] = apply_event(states.get(ev.assertion_id), ev)
1340
+ self.store.reset_projection(states.values())
1341
+ self.rebuild_search_index()
1342
+ return len(states)
1343
+
1344
+ # ----------------------------------------------------------------- search
1345
+ def rebuild_search_index(self) -> int:
1346
+ """Recreate the search index from accepted facts. Returns the number of rows written."""
1347
+ from .search_index import rebuild
1348
+
1349
+ return rebuild(self)
1350
+
1351
+ def search(
1352
+ self,
1353
+ text: str,
1354
+ *,
1355
+ kinds: Sequence[str] | None = None,
1356
+ dataset_prefix: str | None = None,
1357
+ limit: int = 20,
1358
+ for_ai: bool | None = None,
1359
+ ) -> list[dict[str, Any]]:
1360
+ """Ranked search over accepted knowledge: names, descriptions, synonyms, semantic types.
1361
+
1362
+ Filler words ("per", "the", "by" …) are ignored, prefixes count ("rev" finds "revenue") and words
1363
+ are stemmed ("emails" finds "email"). Columns are also found by their semantic type's synonyms.
1364
+ Hits matching *every* word come first; if there are none, hits matching *any* word are returned
1365
+ with ``matched`` listing the words they cover; if still nothing, words are looked for *inside*
1366
+ names ("mail" finds "useremail"); then misspelt words are corrected from the index's own
1367
+ vocabulary and hits carry ``did_you_mean``.
1368
+
1369
+ Who is asking decides what comes back. On an actor-bound view the policy's scope applies:
1370
+ only subjects the actor may read, with items above their confidentiality level found by
1371
+ name but returned redacted. On an unbound ledger the AI limit applies unless
1372
+ ``for_ai=False`` (the safe default for a result that may reach a model).
1373
+ """
1374
+ from .search_index import INDEX_VERSION, content_tokens, correct_spelling, tokens
1375
+
1376
+ shared = self._shared
1377
+ if not shared.search_ready:
1378
+ outdated = self.store.get_meta("search_index_version") != INDEX_VERSION
1379
+ if (outdated or self.store.search_is_empty()) and self.store.accepted_subjects():
1380
+ self.rebuild_search_index()
1381
+ elif outdated:
1382
+ self.store.set_meta("search_index_version", INDEX_VERSION)
1383
+ shared.search_ready = True
1384
+
1385
+ limit_level = self.scope.max_confidentiality
1386
+ if for_ai or (for_ai is None and self._scope is None):
1387
+ ai_level = self.policy.scope("ai:anonymous", None).max_confidentiality
1388
+ limit_level = min(limit_level, ai_level, key=lambda c: c.rank)
1389
+ names_only = limit_level is not Confidentiality.RESTRICTED
1390
+ words = content_tokens(text)
1391
+ filters = {"kinds": kinds, "dataset_prefix": dataset_prefix, "scope": self._scope, "limit": limit}
1392
+
1393
+ def run(ws: list[str], any_word: bool) -> list[dict[str, Any]]:
1394
+ return self.store.search(ws, max_level=limit_level.rank, match_any=any_word, **filters)
1395
+
1396
+ # 1. every word; 2. any word (natural questions span several subjects)
1397
+ how, corrected = "all", None
1398
+ rows = run(words, False)
1399
+ if not rows and len(words) > 1:
1400
+ rows, how = run(words, True), "any"
1401
+ if not rows and words: # 3. the words inside names ("mail" in "useremail")
1402
+ rows = self.store.search_names_containing(words, **filters)
1403
+ if rows:
1404
+ how = "within"
1405
+ if not rows and words: # 4. spelling correction
1406
+ # limited callers get suggestions from names only: description words may be confidential
1407
+ vocab = self.store.search_vocabulary(names_only=names_only)
1408
+ fixed = [self._unstem(w, names_only=names_only) for w in correct_spelling(words, vocab)]
1409
+ if fixed != words:
1410
+ corrected = " ".join(fixed)
1411
+ rows, how = run(fixed, False), "all"
1412
+ if not rows and len(fixed) > 1:
1413
+ rows, how = run(fixed, True), "any"
1414
+ words = fixed
1415
+
1416
+ rows = self._drop_hidden_joins(rows)
1417
+ out = []
1418
+ for r in rows:
1419
+ hit: dict[str, Any] = {"subject": r["subject"], "kind": r["kind"], "name": r["name"]}
1420
+ if how == "any": # tell the caller which words this hit actually covers
1421
+ visible = r["name_text"] + (" " + r["detail_text"] if r["level"] <= limit_level.rank else "")
1422
+ have = set(tokens(visible))
1423
+ # prefix either way, so plurals and stems count ("emails" ~ "email")
1424
+ hit["matched"] = [w for w in words if any(t.startswith(w) or (len(t) > 3 and w.startswith(t))
1425
+ for t in have)]
1426
+ if corrected:
1427
+ hit["did_you_mean"] = corrected
1428
+ if r["dataset"]:
1429
+ hit["dataset"] = r["dataset"]
1430
+ if r["datatype"]:
1431
+ hit["datatype"] = r["datatype"]
1432
+ if r["semantic_type"]:
1433
+ hit["semantic_type"] = r["semantic_type"]
1434
+ if r["level"] > limit_level.rank:
1435
+ hit["confidentiality"] = Confidentiality.from_rank(r["level"]).value
1436
+ hit["redacted"] = True
1437
+ elif r["description"]:
1438
+ hit["description"] = r["description"]
1439
+ out.append(hit)
1440
+ return out
1441
+
1442
+ def _drop_hidden_joins(self, rows: list[dict[str, Any]]) -> list[dict[str, Any]]:
1443
+ """A relationship is only shown to a reader who may read both tables it joins."""
1444
+ scope = self._scope
1445
+ joins = [r["subject"] for r in rows if r["kind"] == Kind.RELATIONSHIP.value]
1446
+ if scope is None or scope.all_paths or not joins:
1447
+ return rows
1448
+ hidden = {
1449
+ a.subject
1450
+ for a in self.store.find_for_subjects(joins, [Status.ACCEPTED], attributes=DATASET_REFERENCES)
1451
+ if isinstance(a.value, str) and not scope.covers(a.value)
1452
+ }
1453
+ return [r for r in rows if r["subject"] not in hidden]
1454
+
1455
+ def _unstem(self, word: str, *, names_only: bool = True) -> str:
1456
+ """The index stores stems ("revenu"); show a real word that has this stem ("revenue")."""
1457
+ from .search_index import tokens
1458
+
1459
+ level = Confidentiality.PUBLIC if names_only else Confidentiality.RESTRICTED
1460
+ rows = self.store.search([word], max_level=level.rank, limit=1, scope=self._scope)
1461
+ if not rows:
1462
+ return word
1463
+ text = rows[0]["name_text"] + ("" if names_only else " " + rows[0]["detail_text"])
1464
+ candidates = [t for t in tokens(text) if t.startswith(word)]
1465
+ return min(candidates, key=len) if candidates else word
1466
+
1467
+ def close(self) -> None:
1468
+ """Close the underlying store."""
1469
+ self.store.close()
1470
+
1471
+ def __enter__(self) -> Gloss:
1472
+ return self
1473
+
1474
+ def __exit__(self, *exc: object) -> None:
1475
+ self.close()
1476
+
1477
+
1478
+ def _best(rows: Iterable[Assertion]) -> dict[tuple[str, str], Assertion]:
1479
+ """One assertion per subject and attribute: accepted wins, then the most recently updated."""
1480
+ best: dict[tuple[str, str], Assertion] = {}
1481
+ for a in rows:
1482
+ k = (a.subject, a.attribute)
1483
+ cur = best.get(k)
1484
+ if cur is None or (a.status is not Status.ACCEPTED, -a.updated_at.timestamp()) < (
1485
+ cur.status is not Status.ACCEPTED,
1486
+ -cur.updated_at.timestamp(),
1487
+ ):
1488
+ best[k] = a
1489
+ return best
1490
+
1491
+
1492
+ @dataclass
1493
+ class Entry:
1494
+ """Attributes of one subject in a snapshot, with the assertions behind them.
1495
+
1496
+ ``inherited`` maps attributes that came from a semantic type to that type's name;
1497
+ ``check_origins`` maps positions in ``attrs["checks"]`` to ``"type:<name>"``;
1498
+ ``redacted`` is the subject's confidentiality level when its details were withheld.
1499
+ """
1500
+
1501
+ attrs: dict[str, Any] = field(default_factory=dict)
1502
+ assertions: dict[str, Assertion] = field(default_factory=dict)
1503
+ inherited: dict[str, str] = field(default_factory=dict)
1504
+ check_origins: dict[int, str] = field(default_factory=dict)
1505
+ redacted: str | None = None
1506
+
1507
+ @property
1508
+ def own_attrs(self) -> dict[str, Any]:
1509
+ """The attributes the subject states itself, without those inherited from its semantic type."""
1510
+ return {k: v for k, v in self.attrs.items() if k not in self.inherited}
1511
+
1512
+ def set(self, attribute: str, a: Assertion) -> None:
1513
+ """Record ``a`` as the assertion behind ``attribute``."""
1514
+ self.attrs[attribute] = a.value
1515
+ self.assertions[attribute] = a
1516
+
1517
+ @property
1518
+ def all_accepted(self) -> bool:
1519
+ """Whether every value here comes from an accepted fact (nothing is pending)."""
1520
+ return all(a.status is Status.ACCEPTED for a in self.assertions.values())
1521
+
1522
+ def level(self, inherited: Confidentiality | None = None) -> Confidentiality:
1523
+ """The subject's own confidentiality, else ``inherited``, else ``internal``."""
1524
+ raw = self.attrs.get("confidentiality")
1525
+ return Confidentiality(raw) if raw else inherited or Confidentiality.INTERNAL
1526
+
1527
+ def withhold(self, level: Confidentiality, limit: Confidentiality) -> None:
1528
+ """Drop detail attributes when ``level`` is above ``limit``, recording the level in ``redacted``."""
1529
+ if level > limit:
1530
+ for attr in detail_attributes() & self.attrs.keys():
1531
+ del self.attrs[attr]
1532
+ self.assertions.pop(attr, None)
1533
+ self.inherited.pop(attr, None)
1534
+ self.redacted = level.value
1535
+
1536
+
1537
+ @dataclass
1538
+ class DatasetEntry(Entry):
1539
+ """A dataset in a snapshot, with its fields and its own metrics by name."""
1540
+ fields: dict[str, Entry] = field(default_factory=dict)
1541
+ metrics: dict[str, Entry] = field(default_factory=dict)
1542
+
1543
+
1544
+ @dataclass
1545
+ class ModelState:
1546
+ """A snapshot. Relationships, metrics and types are keyed by reference (``sales::revenue`` or a bare name)."""
1547
+
1548
+ model: Entry = field(default_factory=Entry)
1549
+ models: dict[str, Entry] = field(default_factory=dict) # per namespace
1550
+ datasets: dict[str, DatasetEntry] = field(default_factory=dict)
1551
+ relationships: dict[str, Entry] = field(default_factory=dict)
1552
+ metrics: dict[str, Entry] = field(default_factory=dict)
1553
+ types: dict[str, Entry] = field(default_factory=dict)
1554
+
1555
+ def apply_types(self) -> None:
1556
+ """Let fields inherit from their semantic type (own facts win; checks are combined)."""
1557
+ inherit = inherited_attributes()
1558
+ for d in self.datasets.values():
1559
+ for f in d.fields.values():
1560
+ tname = f.attrs.get("semantic_type")
1561
+ t = self.types.get(tname) if tname else None
1562
+ if t is None:
1563
+ continue
1564
+ for attr in inherit:
1565
+ if attr not in f.attrs and attr in t.attrs:
1566
+ f.attrs[attr] = t.attrs[attr]
1567
+ f.inherited[attr] = tname
1568
+ type_checks = t.attrs.get("checks") or []
1569
+ if type_checks:
1570
+ own = [c for c in f.attrs.get("checks") or [] if c not in type_checks]
1571
+ f.attrs["checks"] = list(type_checks) + own
1572
+ f.check_origins = {i: f"type:{tname}" for i in range(len(type_checks))}
1573
+
1574
+ def redact(self, limit: Confidentiality) -> None:
1575
+ """Remove the details of every subject above ``limit``; names and structure stay."""
1576
+ levels: dict[str, Confidentiality] = {}
1577
+ for key, d in self.datasets.items():
1578
+ levels[key] = dl = d.level()
1579
+ d.withhold(dl, limit)
1580
+ for f in d.fields.values():
1581
+ f.withhold(f.level(dl), limit)
1582
+ for m in d.metrics.values():
1583
+ m.withhold(m.level(dl), limit)
1584
+ for r in self.relationships.values():
1585
+ ends = [levels[x] for x in (r.attrs.get("from"), r.attrs.get("to")) if x in levels]
1586
+ r.withhold(max([r.level(), *ends], key=lambda c: c.rank), limit)
1587
+ for m in self.metrics.values():
1588
+ m.withhold(m.level(), limit)
1589
+
1590
+ def usages(self, type_name: str) -> list[SubjectId]:
1591
+ """Fields in this snapshot whose semantic type is ``type_name`` (e.g. ``crm::email_address``)."""
1592
+ return [
1593
+ SubjectId.for_field(dk, fk)
1594
+ for dk, d in self.datasets.items()
1595
+ for fk, f in d.fields.items()
1596
+ if f.attrs.get("semantic_type") == type_name
1597
+ ]
1598
+
1599
+ def dataset(self, key: str) -> DatasetEntry:
1600
+ """The entry for dataset ``key``, created empty if the snapshot has none yet."""
1601
+ return self.datasets.setdefault(key, DatasetEntry())
1602
+
1603
+ def add(self, sid: SubjectId, attribute: str, a: Assertion) -> None:
1604
+ """Place one assertion in the entry of its subject."""
1605
+ if sid.kind is Kind.MODEL:
1606
+ (self.models.setdefault(sid.namespace, Entry()) if sid.namespace else self.model).set(attribute, a)
1607
+ elif sid.kind is Kind.DATASET:
1608
+ self.dataset(sid.dataset or "").set(attribute, a)
1609
+ elif sid.kind is Kind.FIELD:
1610
+ self.dataset(sid.dataset or "").fields.setdefault(sid.name or "", Entry()).set(attribute, a)
1611
+ elif sid.kind is Kind.RELATIONSHIP:
1612
+ self.relationships.setdefault(sid.ref, Entry()).set(attribute, a)
1613
+ elif sid.kind is Kind.METRIC:
1614
+ if sid.dataset:
1615
+ self.dataset(sid.dataset).metrics.setdefault(sid.name or "", Entry()).set(attribute, a)
1616
+ else:
1617
+ self.metrics.setdefault(sid.ref, Entry()).set(attribute, a)
1618
+ elif sid.kind is Kind.TYPE:
1619
+ self.types.setdefault(sid.ref, Entry()).set(attribute, a)
1620
+
1621
+ def iter_subjects(self) -> Iterator[tuple[SubjectId, Entry]]:
1622
+ """Every subject in the snapshot with its entry.
1623
+
1624
+ Covers models, datasets (with fields and metrics), relationships, metrics and semantic types.
1625
+ """
1626
+ yield SubjectId.model(), self.model
1627
+ for ns, m in self.models.items():
1628
+ yield SubjectId.model(ns), m
1629
+ for dk, d in self.datasets.items():
1630
+ yield SubjectId.for_dataset(dk), d
1631
+ for fk, f in d.fields.items():
1632
+ yield SubjectId.for_field(dk, fk), f
1633
+ for mk, m in d.metrics.items():
1634
+ yield SubjectId.for_metric(mk, dk), m
1635
+ for rk, r in self.relationships.items():
1636
+ yield SubjectId.for_relationship(rk), r
1637
+ for mk, m in self.metrics.items():
1638
+ yield SubjectId.for_metric(mk), m
1639
+ for tk, t in self.types.items():
1640
+ yield SubjectId.for_type(tk), t
1641
+
1642
+
1643
+ def _subject_prefix_for(key: str) -> str:
1644
+ """The subject prefix that covers everything about ``key`` (a table key or a subject)."""
1645
+ if ":" not in key or key.split(":", 1)[0] not in {k.value for k in Kind}:
1646
+ return f"dataset:{key}"
1647
+ return str(SubjectId.parse(key))
1648
+
1649
+
1650
+ def open( # noqa: A001
1651
+ url: str = "sqlite:///gloss.db", *, policy: Policy | None = None, directory: ActorDirectory | None = None
1652
+ ) -> Gloss:
1653
+ """Open (and create if needed) a Gloss ledger at a SQLAlchemy URL."""
1654
+ return Gloss(SQLStore(url), policy=policy, directory=directory)