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/modeling.py ADDED
@@ -0,0 +1,602 @@
1
+ """Object-style modelling API.
2
+
3
+ import glosslayer
4
+ from glosslayer import Table, Column, Relationship, Metric, Human
5
+
6
+ g = glosslayer.open("sqlite:///gloss.db")
7
+
8
+ orders = Table("shop.orders", primary_key=[Column("order_id", "Integer")])
9
+
10
+ returns = Table("shop.returns", source="warehouse.shop.returns",
11
+ description="One row per returned order",
12
+ primary_key=[Column("return_id", "Integer")])
13
+ returns.add_columns(
14
+ Column("order_id", int, description="The order that was returned"),
15
+ Column("reason", "String", synonyms=["return reason"]),
16
+ )
17
+
18
+ g.add(returns, orders,
19
+ Relationship("returns_orders", on={returns["order_id"]: orders["order_id"]}),
20
+ source=Human("edward"))
21
+
22
+ Objects are *descriptions*: saving them proposes one fact per attribute, so
23
+ everything still goes through review and the log. Saving the same object twice
24
+ is a no-op; changing one attribute proposes only that attribute.
25
+ ``Table.load(g, key)`` / ``g.table(key)`` reads a table back from the ledger.
26
+ """
27
+
28
+ from __future__ import annotations
29
+
30
+ import datetime as _dt
31
+ import decimal as _decimal
32
+ from collections.abc import Iterator, Mapping, Sequence
33
+ from dataclasses import dataclass, field
34
+ from typing import TYPE_CHECKING, Any, Union
35
+
36
+ from .dtypes import DType
37
+ from .dtypes import parse as parse_dtype
38
+ from .ids import SubjectId
39
+ from .model import DATATYPES, Status, new_id
40
+ from .types import to_ossie_datatype
41
+
42
+ if TYPE_CHECKING:
43
+ from .ledger import Gloss, Proposal
44
+
45
+ _PY_TYPES: dict[type, str] = {
46
+ bool: "Boolean", # before int: bool is a subclass of int
47
+ int: "Integer",
48
+ float: "Float",
49
+ str: "String",
50
+ _decimal.Decimal: "Decimal",
51
+ _dt.datetime: "DateTime", # before date: datetime is a subclass of date
52
+ _dt.date: "Date",
53
+ _dt.time: "Time",
54
+ }
55
+
56
+ # attributes shared by everything, in the order they are proposed
57
+ _COMMON = ("description", "ai_instructions", "synonyms", "examples", "confidentiality", "owner")
58
+
59
+
60
+ DatatypeLike = Union[str, type, DType, None]
61
+
62
+
63
+ def _datatype(value: DatatypeLike) -> tuple[str | None, str | None]:
64
+ """Resolve to (Ossie datatype, physical type).
65
+
66
+ Accepts Gloss types (``Int(32)``, ``Decimal(18, 2)``, or a bare ``Int``), Ossie names
67
+ (``"Integer"``), catalog type names (``"Int64"``, ``"varchar(20)"``) and Python types (``int``).
68
+ """
69
+ if value is None:
70
+ return None, None
71
+ if isinstance(value, DType):
72
+ return value.ossie, value.physical
73
+ if isinstance(value, type):
74
+ if issubclass(value, DType):
75
+ inst = value()
76
+ return inst.ossie, inst.physical
77
+ for py, ossie in _PY_TYPES.items():
78
+ if issubclass(value, py):
79
+ return ossie, None
80
+ raise ValueError(f"No Ossie datatype for Python type {value.__name__}")
81
+ if value in DATATYPES:
82
+ return value, None
83
+ mapped = to_ossie_datatype(value)
84
+ if mapped == "Opaque" and value.lower() != "opaque":
85
+ raise ValueError(f"Unknown datatype {value!r}; use a Gloss type like Int(32), an Ossie name, or a catalog type")
86
+ return mapped, value # keep the catalog's own spelling as the physical type
87
+
88
+
89
+ def _facts(obj: Any, names: Sequence[str]) -> Iterator[tuple[str, Any]]:
90
+ for name in names:
91
+ value = getattr(obj, name)
92
+ if value is not None and value != []:
93
+ yield name, value
94
+
95
+
96
+ @dataclass
97
+ class SemanticType:
98
+ """A reusable meaning that many columns share, e.g. an e-mail address.
99
+
100
+ Email = SemanticType(
101
+ "email_address",
102
+ dtype=String(320),
103
+ description="An e-mail address",
104
+ confidentiality="restricted",
105
+ classification=["pii.email"],
106
+ synonyms=["e-mail", "mail address"],
107
+ checks=[checks.matches(r"^[^@\\s]+@[^@\\s]+\\.[^@\\s]+$")],
108
+ name_patterns=[r"e[-_]?mail"], # used to suggest this type for matching columns
109
+ )
110
+ Column("customer_email", Email)
111
+
112
+ A column using a type inherits everything it doesn't state itself; checks are combined.
113
+ Changing an accepted type changes every column that uses it.
114
+ """
115
+
116
+ name: str
117
+ dtype: DatatypeLike = None
118
+ description: str | None = None
119
+ label: str | None = None
120
+ confidentiality: str | None = None
121
+ classification: list[str] = field(default_factory=list)
122
+ synonyms: list[str] = field(default_factory=list)
123
+ examples: list[str] = field(default_factory=list)
124
+ ai_instructions: str | None = None
125
+ owner: str | None = None
126
+ checks: list[Any] = field(default_factory=list)
127
+ name_patterns: list[str] = field(default_factory=list)
128
+ namespace: str | None = None # the namespace that owns the type; None for a ledger-wide type
129
+
130
+ def __post_init__(self) -> None:
131
+ sid = SubjectId.for_type(self.name, self.namespace) # also accepts "crm::email_address"
132
+ self.name, self.namespace = sid.name or "", sid.namespace
133
+ self.datatype, self.physical_type = _datatype(self.dtype)
134
+
135
+ @property
136
+ def subject(self) -> SubjectId:
137
+ """The ``type:`` subject this type's facts are stated about."""
138
+ return SubjectId.for_type(self.name, self.namespace)
139
+
140
+ @property
141
+ def ref(self) -> str:
142
+ """How columns refer to this type: ``crm::email_address``, or the bare name."""
143
+ return self.subject.ref
144
+
145
+ @property
146
+ def resolved_dtype(self) -> DType | None:
147
+ """The precise type, e.g. ``String(320)``, rebuilt from the physical and Ossie types."""
148
+ return parse_dtype(self.physical_type, self.datatype)
149
+
150
+ def proposals(self) -> Iterator[Proposal]:
151
+ """One proposal per attribute that is set; checks are normalised to their stored form."""
152
+ from .checks import normalise
153
+ from .ledger import Proposal
154
+
155
+ subj = str(self.subject)
156
+ for attr in ("datatype", "physical_type", "description", "label", "confidentiality", "classification",
157
+ "synonyms", "examples", "ai_instructions", "owner", "name_patterns"):
158
+ value = getattr(self, attr)
159
+ if value is not None and value != []:
160
+ yield Proposal(subj, attr, value)
161
+ if self.checks:
162
+ yield Proposal(subj, "checks", normalise(self.checks))
163
+
164
+ @classmethod
165
+ def load(cls, gloss: Gloss, name: str, *, include_pending: bool = False) -> SemanticType:
166
+ """Read a type back from the ledger (accepted facts; optionally open proposals too)."""
167
+ ref =SubjectId.for_type(name).ref
168
+ state = gloss.snapshot(read_statuses(include_pending), datasets=[], relationships=False)
169
+ if ref not in state.types:
170
+ raise KeyError(f"No semantic type {name!r}")
171
+ return cls._from_attrs(ref, state.types[ref].attrs)
172
+
173
+ @classmethod
174
+ def _from_attrs(cls, ref: str, attrs: dict[str, Any]) -> SemanticType:
175
+ dtype = parse_dtype(attrs.get("physical_type"), attrs.get("datatype"))
176
+ keep = {f for f in cls.__dataclass_fields__} - {"name", "dtype", "namespace"}
177
+ return cls(ref, dtype=dtype, **{k: v for k, v in attrs.items() if k in keep})
178
+
179
+ def __hash__(self) -> int:
180
+ return hash(("semantic_type", self.ref))
181
+
182
+
183
+ @dataclass(eq=False) # identity semantics: columns are hashable and can key `on={...}`
184
+ class Column:
185
+ """A column of a table: ``Column("amount", Decimal(18, 2), description="Order total")``.
186
+
187
+ The datatype may be a Gloss type, an Ossie name, a catalog type name, a Python type or a
188
+ ``SemanticType``, whose attributes the column inherits. Columns compare by identity, so they
189
+ can key a relationship's ``on={...}``; a column belongs to at most one table.
190
+ """
191
+
192
+ name: str
193
+ datatype: DatatypeLike = None # stored as the Ossie name after construction
194
+ expression: str | dict[str, Any] | None = None # defaults to the column name on export
195
+ description: str | None = None
196
+ label: str | None = None
197
+ is_time: bool | None = None
198
+ synonyms: list[str] = field(default_factory=list)
199
+ examples: list[str] = field(default_factory=list)
200
+ ai_instructions: str | None = None
201
+ confidentiality: str | None = None
202
+ classification: list[str] = field(default_factory=list)
203
+ owner: str | None = None
204
+ role: str | None = None # what the column is to a metric: "key", "time", "category" or "amount"
205
+ physical_type: str | None = None # e.g. "Int32"; filled in from a Gloss type like Int(32)
206
+ semantic_type: SemanticType | str | None = None # also accepted as the datatype: Column("email", Email)
207
+ checks: list[Any] = field(default_factory=list) # in addition to the semantic type's checks
208
+ table: str | None = field(default=None, repr=False) # set when the column is added to a Table
209
+
210
+ def __post_init__(self) -> None:
211
+ if isinstance(self.datatype, SemanticType):
212
+ if self.semantic_type is not None and self.semantic_type is not self.datatype:
213
+ raise ValueError("Give the semantic type once: as the datatype or as semantic_type=")
214
+ self.semantic_type, self.datatype = self.datatype, None
215
+ ossie, physical = _datatype(self.datatype)
216
+ self.datatype = ossie
217
+ if self.physical_type is None:
218
+ self.physical_type = physical
219
+
220
+ @property
221
+ def semantic_type_name(self) -> str | None:
222
+ """The semantic type's reference, whether it was given as an object or a name."""
223
+ st = self.semantic_type
224
+ return st.ref if isinstance(st, SemanticType) else st
225
+
226
+ @property
227
+ def dtype(self) -> DType | None:
228
+ """The precise type, e.g. ``Int(32)``; falls back to the semantic type's, then the Ossie type."""
229
+ own = parse_dtype(self.physical_type, self.datatype) # type: ignore[arg-type]
230
+ if own is None and isinstance(self.semantic_type, SemanticType):
231
+ return self.semantic_type.resolved_dtype
232
+ return own
233
+
234
+ def facts(self) -> Iterator[tuple[str, Any]]:
235
+ """The column's own ``(attribute, value)`` pairs that are set; inherited ones are not repeated."""
236
+ from .checks import normalise
237
+
238
+ yield from _facts(
239
+ self, ("expression", "datatype", "physical_type", "is_time", "label", *_COMMON, "classification",
240
+ "role")
241
+ )
242
+ if self.semantic_type_name:
243
+ yield "semantic_type", self.semantic_type_name
244
+ if self.checks:
245
+ yield "checks", normalise(self.checks)
246
+
247
+ @property
248
+ def qualified_name(self) -> str:
249
+ """``table.column`` once the column belongs to a table, else the bare name."""
250
+ return f"{self.table}.{self.name}" if self.table else self.name
251
+
252
+
253
+ @dataclass
254
+ class Metric:
255
+ """A number with an agreed definition.
256
+
257
+ ``expression`` is the SQL that computes it and is all Ossie needs. The structured parts are
258
+ optional and let a host answer "this metric by these dimensions over this period" without
259
+ parsing SQL: ``aggregate`` (``"sum(amount)"``), ``filter``, ``time_column``, the allowed
260
+ ``dimensions`` and a number ``format``. Compiling a query from them is the host's job.
261
+ """
262
+
263
+ name: str
264
+ expression: str | dict[str, Any]
265
+ description: str | None = None
266
+ datatype: DatatypeLike = None
267
+ synonyms: list[str] = field(default_factory=list)
268
+ examples: list[str] = field(default_factory=list)
269
+ ai_instructions: str | None = None
270
+ confidentiality: str | None = None
271
+ owner: str | None = None
272
+ table: str | None = None # set for a metric that belongs to one table
273
+ namespace: str | None = None # set for a metric owned by a namespace
274
+ aggregate: str | None = None
275
+ filter: str | None = None
276
+ time_column: str | None = None
277
+ dimensions: list[str] = field(default_factory=list)
278
+ format: str | None = None
279
+ version: int | None = field(default=None, compare=False, repr=False) # set when read from a ledger
280
+
281
+ def __post_init__(self) -> None:
282
+ self.datatype = _datatype(self.datatype)[0]
283
+ sid = SubjectId.for_metric(self.name, self.table, namespace=self.namespace)
284
+ self.name, self.namespace = sid.name or "", sid.namespace
285
+
286
+ @property
287
+ def subject(self) -> SubjectId:
288
+ """The ``metric:`` subject: scoped to its table, its namespace, or the whole ledger."""
289
+ return SubjectId.for_metric(self.name, self.table, namespace=self.namespace)
290
+
291
+ def facts(self) -> Iterator[tuple[str, Any]]:
292
+ """The metric's ``(attribute, value)`` pairs that are set."""
293
+ yield from _facts(
294
+ self, ("expression", "datatype", *_COMMON, "aggregate", "filter", "time_column", "dimensions", "format")
295
+ )
296
+
297
+ def proposals(self) -> Iterator[Proposal]:
298
+ """The metric's facts as one review group, so the definition is accepted or rejected whole."""
299
+ from .ledger import Proposal
300
+
301
+ group = new_id() # a metric's facts are reviewed as one definition
302
+ for attr, value in self.facts():
303
+ yield Proposal(str(self.subject), attr, value, group=group)
304
+
305
+
306
+ ColumnRef = Union["Column", str]
307
+ TableRef = Union["Table", str]
308
+
309
+
310
+ def _table_key(t: TableRef | None) -> str | None:
311
+ return t.key if isinstance(t, Table) else t
312
+
313
+
314
+ @dataclass
315
+ class Relationship:
316
+ """A join: many ``from_table`` rows to one ``to_table`` row.
317
+
318
+ The tables can be left out when the columns already belong to tables:
319
+
320
+ Relationship("returns_orders", on={returns["order_id"]: orders["order_id"]})
321
+ Relationship("returns_orders", "shop.returns", "shop.orders", on={"order_id": "order_id"})
322
+ """
323
+
324
+ name: str
325
+ from_table: TableRef | None = None
326
+ to_table: TableRef | None = None
327
+ on: Mapping[ColumnRef, ColumnRef] | None = None
328
+ from_columns: list[ColumnRef] = field(default_factory=list)
329
+ to_columns: list[ColumnRef] = field(default_factory=list)
330
+ description: str | None = None
331
+ ai_instructions: str | None = None
332
+ namespace: str | None = None # the namespace that owns the relationship
333
+ version: int | None = field(default=None, compare=False, repr=False) # set when read from a ledger
334
+
335
+ @property
336
+ def subject(self) -> SubjectId:
337
+ """The ``relationship:`` subject this join's facts are stated about."""
338
+ return SubjectId.for_relationship(self.name, self.namespace)
339
+
340
+ def __post_init__(self) -> None:
341
+ sid = SubjectId.for_relationship(self.name, self.namespace)
342
+ self.name, self.namespace = sid.name or "", sid.namespace
343
+ if self.on:
344
+ self.from_columns = list(self.on.keys())
345
+ self.to_columns = list(self.on.values())
346
+ if not self.from_columns or len(self.from_columns) != len(self.to_columns):
347
+ raise ValueError(f"Relationship {self.name}: give `on` or matching from_columns/to_columns")
348
+ self.from_table, self.from_columns = self._resolve("from", self.from_table, self.from_columns)
349
+ self.to_table, self.to_columns = self._resolve("to", self.to_table, self.to_columns)
350
+
351
+ def _resolve(self, side: str, table: TableRef | None, cols: list[ColumnRef]) -> tuple[str, list[str]]:
352
+ key = _table_key(table)
353
+ owners = {c.table for c in cols if isinstance(c, Column)}
354
+ if None in owners:
355
+ raise ValueError(f"Relationship {self.name}: {side}-columns must be added to a Table first")
356
+ if len(owners) > 1:
357
+ raise ValueError(f"Relationship {self.name}: {side}-columns come from different tables {sorted(owners)}")
358
+ if owners:
359
+ owner = owners.pop()
360
+ if key is not None and key != owner:
361
+ raise ValueError(f"Relationship {self.name}: {side}_table {key!r} but columns belong to {owner!r}")
362
+ key = owner
363
+ if key is None:
364
+ raise ValueError(f"Relationship {self.name}: give {side}_table or use columns that belong to a Table")
365
+ return key, [c.name if isinstance(c, Column) else c for c in cols]
366
+
367
+ def proposals(self) -> Iterator[Proposal]:
368
+ """The join's tables, columns and descriptions as one review group."""
369
+ from .ledger import Proposal
370
+
371
+ subj = str(self.subject)
372
+ group = new_id() # the four facts of a join only make sense together
373
+ yield Proposal(subj, "from", self.from_table, group=group)
374
+ yield Proposal(subj, "to", self.to_table, group=group)
375
+ yield Proposal(subj, "from_columns", list(self.from_columns), group=group)
376
+ yield Proposal(subj, "to_columns", list(self.to_columns), group=group)
377
+ for attr, value in _facts(self, ("description", "ai_instructions")):
378
+ yield Proposal(subj, attr, value, group=group)
379
+
380
+
381
+ @dataclass
382
+ class Table:
383
+ """A dataset, keyed by its Gloss key (``shop.returns``), with its columns and table metrics.
384
+
385
+ ``source`` names the physical table or view and defaults to the key on export. Columns given
386
+ in ``primary_key`` or ``unique_keys`` are added to the table; ``t["col"]`` returns a column.
387
+ """
388
+
389
+ key: str # Gloss dataset key, e.g. "shop.returns"
390
+ source: str | None = None # physical table/view; defaults to the key on export
391
+ description: str | None = None
392
+ primary_key: list[ColumnRef] | ColumnRef = field(default_factory=list) # Columns are added to the table
393
+ unique_keys: list[list[ColumnRef]] = field(default_factory=list)
394
+ synonyms: list[str] = field(default_factory=list)
395
+ examples: list[str] = field(default_factory=list)
396
+ ai_instructions: str | None = None
397
+ confidentiality: str | None = None
398
+ classification: list[str] = field(default_factory=list)
399
+ owner: str | None = None
400
+ columns: dict[str, Column] = field(default_factory=dict)
401
+ metrics: dict[str, Metric] = field(default_factory=dict)
402
+
403
+ def __post_init__(self) -> None:
404
+ cols, self.columns = self.columns, {}
405
+ for c in cols.values() if isinstance(cols, dict) else cols:
406
+ self.add_column(c)
407
+ self.primary_key = self._key_names(self.primary_key)
408
+ self.unique_keys = [self._key_names(k) for k in self.unique_keys]
409
+
410
+ def _key_names(self, items: list[ColumnRef] | ColumnRef) -> list[str]:
411
+ """Turn a key given as Columns and/or names into names, adding new Columns to the table."""
412
+ if isinstance(items, (Column, str)):
413
+ items = [items]
414
+ names = []
415
+ for item in items:
416
+ if isinstance(item, Column):
417
+ if self.columns.get(item.name) is not item:
418
+ self.add_column(item)
419
+ names.append(item.name)
420
+ else:
421
+ names.append(item)
422
+ return names
423
+
424
+ # -- building -----------------------------------------------------------
425
+ def add_column(self, column: Column | str, datatype: DatatypeLike = None, **attrs: Any) -> Table:
426
+ """``add_column(Column("id", "Integer"))`` or the short form ``add_column("id", int)``."""
427
+ if isinstance(column, str):
428
+ column = Column(column, datatype, **attrs)
429
+ elif datatype is not None or attrs:
430
+ raise TypeError("Pass either a Column or a name with attributes, not both")
431
+ if column.name in self.columns:
432
+ raise ValueError(f"Table {self.key} already has a column {column.name!r}")
433
+ if column.table not in (None, self.key):
434
+ raise ValueError(
435
+ f"Column {column.name!r} already belongs to {column.table!r}; "
436
+ "use dataclasses.replace(column, table=None) to copy it"
437
+ )
438
+ column.table = self.key
439
+ self.columns[column.name] = column
440
+ return self
441
+
442
+ def add_columns(self, *columns: Column) -> Table:
443
+ """Add several columns; returns the table for chaining."""
444
+ for c in columns:
445
+ self.add_column(c)
446
+ return self
447
+
448
+ def add_metric(self, metric: Metric) -> Table:
449
+ """Attach a metric to this table, replacing one of the same name."""
450
+ metric.table = self.key
451
+ self.metrics[metric.name] = metric
452
+ return self
453
+
454
+ def column(self, name: str) -> Column:
455
+ """The column called ``name``; ``KeyError`` if there is none."""
456
+ return self.columns[name]
457
+
458
+ def __getitem__(self, name: str) -> Column:
459
+ return self.columns[name]
460
+
461
+ def __contains__(self, name: object) -> bool:
462
+ return name in self.columns
463
+
464
+ def __iter__(self) -> Iterator[Column]:
465
+ return iter(self.columns.values())
466
+
467
+ def __len__(self) -> int:
468
+ return len(self.columns)
469
+
470
+ # -- saving -------------------------------------------------------------
471
+ def proposals(self) -> Iterator[Proposal]:
472
+ """Proposals for the table, its columns' semantic types, its columns and its metrics.
473
+
474
+ A column with neither an expression nor a datatype still gets ``expression`` so it leaves
475
+ a trace in the ledger.
476
+ """
477
+ from .ledger import Proposal
478
+
479
+ ds = str(SubjectId.for_dataset(self.key))
480
+ for attr, value in _facts(
481
+ self, ("source", "primary_key", "unique_keys", *_COMMON, "classification")
482
+ ):
483
+ yield Proposal(ds, attr, value)
484
+ seen_types: set[str] = set()
485
+ for col in self.columns.values():
486
+ st = col.semantic_type
487
+ if isinstance(st, SemanticType) and st.ref not in seen_types:
488
+ seen_types.add(st.ref)
489
+ yield from st.proposals()
490
+ for col in self.columns.values():
491
+ subj = str(SubjectId.for_field(self.key, col.name))
492
+ facts = list(col.facts())
493
+ if not any(a in ("expression", "datatype") for a, _ in facts):
494
+ facts.insert(0, ("expression", {"sql": col.name})) # a column must leave a trace
495
+ for attr, value in facts:
496
+ yield Proposal(subj, attr, value)
497
+ for m in self.metrics.values():
498
+ yield from m.proposals()
499
+
500
+ # -- loading ------------------------------------------------------------
501
+ @classmethod
502
+ def load(cls, gloss: Gloss, key: str, *, include_pending: bool = False) -> Table:
503
+ """Build a Table from the ledger (accepted facts; optionally open proposals too)."""
504
+ statuses = read_statuses(include_pending)
505
+ state = gloss.snapshot(statuses, datasets=[key], relationships=False)
506
+ if key not in state.datasets:
507
+ raise KeyError(
508
+ f"No table {key!r} with facts in {[s.value for s in statuses]}"
509
+ + ("" if include_pending else " (pass include_pending=True to see proposals)")
510
+ )
511
+ return cls._from_state(key, state, types_from_state(state))
512
+
513
+ @classmethod
514
+ def _from_state(cls, key: str, state: Any, types: dict[str, SemanticType]) -> Table:
515
+ d = state.datasets[key]
516
+ known = {f for f in cls.__dataclass_fields__ if f not in ("key", "columns", "metrics")}
517
+ t = cls(key, **{k: v for k, v in d.attrs.items() if k in known})
518
+ col_fields = set(Column.__dataclass_fields__) - {"name", "table", "semantic_type"}
519
+ for name, f in d.fields.items():
520
+ own = f.own_attrs
521
+ col = Column(name, **{k: v for k, v in own.items() if k in col_fields})
522
+ col.checks = [c for i, c in enumerate(f.attrs.get("checks") or []) if i not in f.check_origins]
523
+ tname = own.get("semantic_type")
524
+ col.semantic_type = types.get(tname, tname) if tname else None
525
+ t.add_column(col)
526
+ for name, m in d.metrics.items():
527
+ met = metric_from_attrs(name, m.attrs, table=key)
528
+ if met is not None:
529
+ t.metrics[name] = met
530
+ return t
531
+
532
+ def __repr__(self) -> str:
533
+ cols = ", ".join(f"{c.name}:{c.dtype or '?'}" for c in self.columns.values())
534
+ return f"Table({self.key!r}, columns=[{cols}])"
535
+
536
+
537
+ # ---------------------------------------------------------------------- reading helpers
538
+ def read_statuses(include_pending: bool) -> list[Status]:
539
+ """The statuses a reader sees: accepted, plus proposed and reviewed when ``include_pending``."""
540
+ return [Status.ACCEPTED] + ([Status.PROPOSED, Status.REVIEWED] if include_pending else [])
541
+
542
+
543
+ def types_from_state(state: Any) -> dict[str, SemanticType]:
544
+ """Every semantic type in a snapshot, keyed by its reference."""
545
+ return {n: SemanticType._from_attrs(n, e.attrs) for n, e in state.types.items()}
546
+
547
+
548
+ def metric_from_attrs(name: str, attrs: dict[str, Any], *, table: str | None = None) -> Metric | None:
549
+ """A Metric from snapshot attributes; None while it has no expression yet.
550
+
551
+ ``name`` is the bare name for a table's metric, otherwise a reference like ``sales::revenue``.
552
+ """
553
+ if "expression" not in attrs:
554
+ return None
555
+ keep = set(Metric.__dataclass_fields__) - {"name", "table", "namespace", "version"}
556
+ return Metric(name, table=table, **{k: v for k, v in attrs.items() if k in keep})
557
+
558
+
559
+ def relationship_from_attrs(name: str, attrs: dict[str, Any]) -> Relationship | None:
560
+ """A Relationship from snapshot attributes; None while its facts do not form a valid join."""
561
+ if not all(attrs.get(k) for k in ("from", "to", "from_columns", "to_columns")):
562
+ return None
563
+ try:
564
+ return Relationship(
565
+ name,
566
+ attrs["from"],
567
+ attrs["to"],
568
+ from_columns=list(attrs["from_columns"]),
569
+ to_columns=list(attrs["to_columns"]),
570
+ description=attrs.get("description"),
571
+ ai_instructions=attrs.get("ai_instructions"),
572
+ )
573
+ except ValueError:
574
+ return None
575
+
576
+
577
+ @dataclass
578
+ class AddResult:
579
+ """What ``Gloss.add`` / ``Gloss.apply`` did, counted per fact: new, corroborated, unchanged, etc.
580
+
581
+ ``previously_rejected`` facts were skipped because the same value was rejected before.
582
+ """
583
+
584
+ created: int = 0
585
+ corroborated: int = 0
586
+ unchanged: int = 0
587
+ previously_rejected: int = 0
588
+ accepted: int = 0
589
+ retracted: int = 0 # by Gloss.apply: stated before, no longer declared
590
+ assertion_ids: list[str] = field(default_factory=list)
591
+
592
+ def __str__(self) -> str:
593
+ parts = [f"{self.created} new", f"{self.unchanged} unchanged"]
594
+ if self.corroborated:
595
+ parts.append(f"{self.corroborated} corroborated")
596
+ if self.previously_rejected:
597
+ parts.append(f"{self.previously_rejected} previously rejected")
598
+ if self.accepted:
599
+ parts.append(f"{self.accepted} accepted")
600
+ if self.retracted:
601
+ parts.append(f"{self.retracted} retracted")
602
+ return ", ".join(parts)
@@ -0,0 +1,13 @@
1
+ """Apache Ossie interop: import documents as proposals, export accepted facts as documents.
2
+
3
+ ``ossie-schema.json`` is the Apache Ossie core JSON Schema (Apache License 2.0),
4
+ vendored unchanged for validation. See NOTICE.
5
+ """
6
+
7
+ GLOSS_VENDOR = "gloss"
8
+ OSSIE_VERSION = "0.3.0.dev0"
9
+
10
+ from .exporter import OssieSink, to_ossie, validate # noqa: E402
11
+ from .importer import OssieSource, load_document # noqa: E402
12
+
13
+ __all__ = ["GLOSS_VENDOR", "OSSIE_VERSION", "OssieSink", "OssieSource", "load_document", "to_ossie", "validate"]