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.
@@ -0,0 +1,918 @@
1
+ """SQLAlchemy store: SQLite for embedded use, Postgres for a shared service.
2
+
3
+ Tables (all prefixed ``gloss_``)
4
+ --------------------------------
5
+ gloss_events append-only log (never updated or deleted)
6
+ gloss_assertions projection: the current state of every assertion
7
+ gloss_search projection: one search row per subject with accepted facts
8
+ gloss_assets last seen physical schema per catalog asset (drift detection)
9
+ gloss_check_results logged data quality runs
10
+ gloss_meta schema version and index version
11
+
12
+ A store given a URL owns its engine: it sets SQLite pragmas and creates or upgrades the
13
+ schema. A store given a host's ``Engine`` touches neither: no connection listeners, no DDL.
14
+ The host runs :func:`glosslayer.schema.upgrade` from its own migrations.
15
+ """
16
+
17
+ from __future__ import annotations
18
+
19
+ from collections.abc import Callable, Iterable, Iterator, Sequence
20
+ from contextlib import contextmanager
21
+ from contextvars import ContextVar
22
+ from dataclasses import dataclass, field, replace
23
+ from datetime import datetime, timezone
24
+ from typing import TYPE_CHECKING, Any
25
+
26
+ import sqlalchemy as sa
27
+ from sqlalchemy.engine import Connection, Engine
28
+ from sqlalchemy.exc import IntegrityError
29
+
30
+ from ..model import Assertion, Event, EventType, Status, value_hash
31
+ from .base import AssetRecord, Query
32
+
33
+ if TYPE_CHECKING:
34
+ from ..policy import Scope
35
+
36
+ metadata = sa.MetaData()
37
+
38
+ # 64-bit sequence numbers; SQLite only auto-increments a plain INTEGER primary key.
39
+ _BigSerial = sa.BigInteger().with_variant(sa.Integer, "sqlite")
40
+
41
+ events_t = sa.Table(
42
+ "gloss_events",
43
+ metadata,
44
+ sa.Column("seq", _BigSerial, primary_key=True, autoincrement=True),
45
+ sa.Column("id", sa.String(32), nullable=False, unique=True),
46
+ sa.Column("ts", sa.DateTime(timezone=True), nullable=False),
47
+ sa.Column("type", sa.String(32), nullable=False),
48
+ sa.Column("assertion_id", sa.String(32), nullable=False, index=True),
49
+ sa.Column("subject", sa.String(512), nullable=False, index=True), # the subject when the event happened
50
+ sa.Column("actor", sa.String(256), nullable=False),
51
+ sa.Column("via", sa.String(256), nullable=True),
52
+ sa.Column("correlation", sa.String(64), nullable=True, index=True),
53
+ sa.Column("data", sa.JSON, nullable=False),
54
+ )
55
+
56
+ assertions_t = sa.Table(
57
+ "gloss_assertions",
58
+ metadata,
59
+ sa.Column("id", sa.String(32), primary_key=True),
60
+ sa.Column("subject", sa.String(512), nullable=False, index=True),
61
+ sa.Column("kind", sa.String(16), nullable=False, index=True),
62
+ sa.Column("dataset", sa.String(512), nullable=True, index=True),
63
+ sa.Column("namespace", sa.String(512), nullable=True), # scope path: dataset key or owning namespace
64
+ sa.Column("attribute", sa.String(64), nullable=False, index=True),
65
+ sa.Column("value", sa.JSON, nullable=True),
66
+ sa.Column("value_hash", sa.String(16), nullable=False),
67
+ sa.Column("source", sa.String(256), nullable=False, index=True),
68
+ sa.Column("sources", sa.JSON, nullable=False),
69
+ sa.Column("status", sa.String(16), nullable=False, index=True),
70
+ sa.Column("confidence", sa.Float, nullable=True),
71
+ sa.Column("evidence", sa.JSON, nullable=False),
72
+ sa.Column("created_at", sa.DateTime(timezone=True), nullable=False),
73
+ sa.Column("updated_at", sa.DateTime(timezone=True), nullable=False),
74
+ sa.Column("created_by", sa.String(256), nullable=False),
75
+ sa.Column("last_comment", sa.Text, nullable=True),
76
+ sa.Column("group_id", sa.String(64), nullable=True, index=True),
77
+ sa.Index("ix_gloss_assertions_subject_attr", "subject", "attribute"),
78
+ # composite indexes so the planner never falls back to scanning every accepted fact
79
+ sa.Index("ix_gloss_assertions_dataset_status", "dataset", "status"),
80
+ sa.Index("ix_gloss_assertions_namespace_status", "namespace", "status"),
81
+ sa.Index("ix_gloss_assertions_kind_status", "kind", "status"),
82
+ sa.Index("ix_gloss_assertions_attr_hash", "attribute", "value_hash"),
83
+ sa.Index("ix_gloss_assertions_subject_status", "subject", "status"),
84
+ # at most one accepted value per subject and attribute, enforced by the database
85
+ sa.Index(
86
+ "uq_gloss_assertions_accepted",
87
+ "subject",
88
+ "attribute",
89
+ unique=True,
90
+ sqlite_where=sa.text("status = 'accepted'"),
91
+ postgresql_where=sa.text("status = 'accepted'"),
92
+ ),
93
+ )
94
+
95
+ assets_t = sa.Table(
96
+ "gloss_assets",
97
+ metadata,
98
+ sa.Column("catalog", sa.String(128), primary_key=True),
99
+ sa.Column("key", sa.String(512), primary_key=True),
100
+ sa.Column("fingerprint", sa.String(128), nullable=False),
101
+ sa.Column("schema", sa.JSON, nullable=False),
102
+ sa.Column("uid", sa.String(256), nullable=True),
103
+ sa.Column("seen_at", sa.DateTime(timezone=True), nullable=False),
104
+ )
105
+
106
+ search_t = sa.Table(
107
+ "gloss_search",
108
+ metadata,
109
+ sa.Column("subject", sa.String(512), primary_key=True),
110
+ sa.Column("kind", sa.String(16), nullable=False, index=True),
111
+ sa.Column("dataset", sa.String(512), nullable=True, index=True),
112
+ sa.Column("namespace", sa.String(512), nullable=True, index=True),
113
+ sa.Column("name", sa.String(512), nullable=False),
114
+ sa.Column("name_text", sa.Text, nullable=False), # always searchable (names, keys, type)
115
+ sa.Column("detail_text", sa.Text, nullable=False), # searchable only up to the caller's level
116
+ sa.Column("description", sa.Text, nullable=True),
117
+ sa.Column("datatype", sa.String(32), nullable=True),
118
+ sa.Column("semantic_type", sa.String(512), nullable=True),
119
+ sa.Column("level", sa.Integer, nullable=False), # confidentiality rank: 0 public … 3 restricted
120
+ )
121
+
122
+ meta_t = sa.Table(
123
+ "gloss_meta",
124
+ metadata,
125
+ sa.Column("key", sa.String(64), primary_key=True),
126
+ sa.Column("value", sa.Text, nullable=False),
127
+ )
128
+
129
+ check_results_t = sa.Table(
130
+ "gloss_check_results",
131
+ metadata,
132
+ sa.Column("id", _BigSerial, primary_key=True, autoincrement=True),
133
+ sa.Column("ts", sa.DateTime(timezone=True), nullable=False),
134
+ sa.Column("subject", sa.String(512), nullable=False, index=True),
135
+ sa.Column("check", sa.JSON, nullable=False),
136
+ sa.Column("passed", sa.Boolean, nullable=False),
137
+ sa.Column("failed_rows", sa.BigInteger, nullable=False),
138
+ sa.Column("total_rows", sa.BigInteger, nullable=False),
139
+ sa.Column("origin", sa.String(512), nullable=True),
140
+ sa.Column("error", sa.Text, nullable=True),
141
+ sa.Column("runner", sa.String(256), nullable=False),
142
+ sa.Column("run_id", sa.String(128), nullable=False, index=True),
143
+ )
144
+
145
+ FTS_TOKENIZER = "porter unicode61 remove_diacritics 2" # stemming: emails → email
146
+
147
+
148
+ def pg_tsvector(column: str) -> str:
149
+ """Postgres full-text expression for a search column, as indexed (see ``schema.create_fts``).
150
+
151
+ Punctuation becomes spaces first, so ``sales.orders`` and ``order_id`` are words, not a host name.
152
+ """
153
+ return f"to_tsvector('english', regexp_replace({column}, '[^[:alnum:]]+', ' ', 'g'))"
154
+ _ADVISORY_LOCK = 0x676C6F7373 # "gloss": serialises appends on Postgres so seq order is commit order
155
+
156
+ # Events that can change which value of a subject is the accepted one.
157
+ VERSION_EVENTS = ("accepted", "superseded", "restored", "retracted", "marked_stale", "rekeyed")
158
+
159
+
160
+ class ConcurrentWrite(RuntimeError):
161
+ """Another writer accepted a value for the same subject and attribute first. Read again and retry."""
162
+
163
+
164
+ def _aware(dt: datetime) -> datetime:
165
+ # SQLite drops tzinfo; everything Gloss writes is UTC.
166
+ return dt if dt.tzinfo else dt.replace(tzinfo=timezone.utc)
167
+
168
+
169
+ def _row_to_assertion(r: Any) -> Assertion:
170
+ return Assertion(
171
+ id=r.id,
172
+ subject=r.subject,
173
+ attribute=r.attribute,
174
+ value=r.value,
175
+ source=r.source,
176
+ status=Status(r.status),
177
+ confidence=r.confidence,
178
+ created_at=_aware(r.created_at),
179
+ updated_at=_aware(r.updated_at),
180
+ created_by=r.created_by,
181
+ sources=tuple(r.sources or ()),
182
+ evidence=tuple(r.evidence or ()),
183
+ last_comment=r.last_comment,
184
+ group=r.group_id,
185
+ )
186
+
187
+
188
+ def _assertion_to_row(a: Assertion) -> dict[str, Any]:
189
+ sid = a.subject_id
190
+ return {
191
+ "id": a.id,
192
+ "subject": a.subject,
193
+ "kind": sid.kind.value,
194
+ "dataset": sid.owning_dataset,
195
+ "namespace": sid.scope_path,
196
+ "attribute": a.attribute,
197
+ "value": a.value,
198
+ "value_hash": value_hash(a.value),
199
+ "source": a.source,
200
+ "sources": list(a.sources),
201
+ "status": a.status.value,
202
+ "confidence": a.confidence,
203
+ "evidence": list(a.evidence),
204
+ "created_at": a.created_at,
205
+ "updated_at": a.updated_at,
206
+ "created_by": a.created_by,
207
+ "last_comment": a.last_comment,
208
+ "group_id": a.group,
209
+ }
210
+
211
+
212
+ def _row_to_event(r: Any) -> Event:
213
+ return Event(
214
+ type=EventType(r.type),
215
+ assertion_id=r.assertion_id,
216
+ actor=r.actor,
217
+ data=r.data or {},
218
+ id=r.id,
219
+ ts=_aware(r.ts),
220
+ seq=r.seq,
221
+ correlation=r.correlation,
222
+ via=r.via,
223
+ )
224
+
225
+
226
+ def _sqlite_pragmas(dbapi_conn: Any, _record: Any) -> None:
227
+ cur = dbapi_conn.cursor()
228
+ cur.execute("PRAGMA journal_mode=WAL") # readers don't block the writer
229
+ cur.execute("PRAGMA synchronous=NORMAL") # durable at checkpoints; far fewer fsyncs
230
+ cur.close()
231
+
232
+
233
+ @dataclass
234
+ class _Tx:
235
+ conn: Connection
236
+ after: list[Callable[[], None]] = field(default_factory=list)
237
+
238
+
239
+ class SQLStore:
240
+ """Store backed by SQLAlchemy, on SQLite or Postgres."""
241
+
242
+ def __init__(self, url_or_engine: str | Engine, *, create: bool | None = None, echo: bool = False):
243
+ """Open a store on a URL (which it owns) or on a host's ``Engine`` (which it only uses).
244
+
245
+ ``create`` defaults to whether the store owns its engine: True creates or upgrades the schema,
246
+ False only checks that it is up to date (:func:`glosslayer.schema.require`).
247
+ """
248
+ from .. import schema
249
+
250
+ self.owns_engine = not isinstance(url_or_engine, Engine)
251
+ if isinstance(url_or_engine, Engine):
252
+ self.engine = url_or_engine
253
+ elif url_or_engine in ("sqlite://", "sqlite:///:memory:"):
254
+ # One shared connection, otherwise every connection gets its own empty database.
255
+ self.engine = sa.create_engine(
256
+ url_or_engine,
257
+ echo=echo,
258
+ poolclass=sa.pool.StaticPool,
259
+ connect_args={"check_same_thread": False},
260
+ )
261
+ else:
262
+ self.engine = sa.create_engine(url_or_engine, echo=echo)
263
+ self.dialect = self.engine.dialect.name
264
+ if self.owns_engine and self.dialect == "sqlite":
265
+ sa.event.listen(self.engine, "connect", _sqlite_pragmas)
266
+ if self.owns_engine if create is None else create:
267
+ schema.upgrade(self.engine)
268
+ else:
269
+ schema.require(self.engine)
270
+ self._tx: ContextVar[_Tx | None] = ContextVar(f"gloss_tx_{id(self)}", default=None)
271
+ # "fts5" (SQLite), "tsvector" (Postgres) or "like" (anything else, and SQLite without FTS5)
272
+ self.search_engine = "like"
273
+ if self.dialect == "postgresql":
274
+ self.search_engine = "tsvector"
275
+ elif self.dialect == "sqlite":
276
+ with self._read() as conn:
277
+ self.search_engine = "fts5" if schema.has_fts(conn) else "like"
278
+
279
+ @property
280
+ def fts(self) -> bool:
281
+ """Whether the database's own full-text search is used (stemming, spelling vocabulary)."""
282
+ return self.search_engine != "like"
283
+
284
+ @fts.setter
285
+ def fts(self, enabled: bool) -> None:
286
+ if not enabled:
287
+ self.search_engine = "like" # plain matching, e.g. to test the portable path
288
+
289
+ # -- prefixes and scopes ------------------------------------------------------
290
+ def _starts(self, column: Any, prefix: str) -> Any:
291
+ """``column`` starts with ``prefix``, written so the database can use an index for it.
292
+
293
+ SQLite compares text bytewise, so a range is a prefix match and uses a plain index (its
294
+ LIKE does not). Postgres uses LIKE, served by the ``text_pattern_ops`` indexes in the schema.
295
+ """
296
+ if not prefix:
297
+ return column.isnot(None)
298
+ if self.dialect == "sqlite" and ord(prefix[-1]) < 0x10FFFF:
299
+ return sa.and_(column >= prefix, column < prefix[:-1] + chr(ord(prefix[-1]) + 1))
300
+ return column.startswith(prefix, autoescape=True)
301
+
302
+ def _under(self, column: Any, path: str) -> Any:
303
+ """Rows whose dotted path is ``path`` or lies under it."""
304
+ p = path.rstrip(".")
305
+ if not p:
306
+ return column.isnot(None)
307
+ return sa.or_(column == p, self._starts(column, p + "."))
308
+
309
+ def _readable(self, column: Any, scope: Scope | None) -> Any | None:
310
+ """SQL for "this row's scope path is readable", or None when nothing needs filtering."""
311
+ if scope is None or scope.all_paths:
312
+ return None
313
+ parts: list[Any] = []
314
+ if scope.include_global:
315
+ parts.append(column.is_(None))
316
+ if scope.prefixes is None:
317
+ parts.append(column.isnot(None))
318
+ else:
319
+ parts += [self._under(column, p) for p in scope.prefixes]
320
+ return sa.or_(*parts) if parts else sa.false()
321
+
322
+ # -- transactions -----------------------------------------------------------
323
+ @contextmanager
324
+ def transaction(self) -> Iterator[Connection]:
325
+ """One transaction for everything the store does inside the block. Re-entrant."""
326
+ tx = self._tx.get()
327
+ if tx is not None:
328
+ yield tx.conn
329
+ return
330
+ with self.engine.begin() as conn:
331
+ tx = _Tx(conn)
332
+ token = self._tx.set(tx)
333
+ try:
334
+ yield conn
335
+ finally:
336
+ self._tx.reset(token)
337
+ for fn in tx.after:
338
+ fn()
339
+
340
+ @contextmanager
341
+ def using(self, connection: Connection) -> Iterator[Connection]:
342
+ """Run inside the host's own transaction: Gloss neither commits nor rolls back.
343
+
344
+ Post-commit callbacks (subscribers) run when the block ends, so end it after the host commits
345
+ or accept that they fire slightly early.
346
+ """
347
+ tx = _Tx(connection)
348
+ token = self._tx.set(tx)
349
+ try:
350
+ yield connection
351
+ finally:
352
+ self._tx.reset(token)
353
+ for fn in tx.after:
354
+ fn()
355
+
356
+ @contextmanager
357
+ def _read(self) -> Iterator[Connection]:
358
+ tx = self._tx.get()
359
+ if tx is not None:
360
+ yield tx.conn
361
+ return
362
+ with self.engine.connect() as conn:
363
+ yield conn
364
+
365
+ def after_commit(self, fn: Callable[[], None]) -> None:
366
+ """Run ``fn`` once the current transaction has committed, or right away when none is open."""
367
+ tx = self._tx.get()
368
+ if tx is not None:
369
+ tx.after.append(fn)
370
+ else:
371
+ fn()
372
+
373
+ # -- writes ---------------------------------------------------------------
374
+ def append(self, events: Sequence[Event], states: Sequence[Assertion], *, returning: bool = False) -> list[Event]:
375
+ """Insert events and upsert the resulting states in one transaction.
376
+
377
+ Events of type ``proposed`` create their assertion; all other states are updates. With
378
+ ``returning`` the events come back carrying the ``seq`` the database gave them.
379
+ """
380
+ if not events and not states:
381
+ return []
382
+ subjects = {st.id: st.subject for st in states}
383
+ new_ids = {ev.assertion_id for ev in events if ev.type is EventType.PROPOSED}
384
+ out = list(events)
385
+ try:
386
+ with self.transaction() as conn:
387
+ if self.dialect == "postgresql":
388
+ conn.execute(sa.text("SELECT pg_advisory_xact_lock(:k)"), {"k": _ADVISORY_LOCK})
389
+ missing = {ev.assertion_id for ev in events} - subjects.keys() - new_ids
390
+ if missing:
391
+ rows = conn.execute(
392
+ sa.select(assertions_t.c.id, assertions_t.c.subject).where(assertions_t.c.id.in_(missing))
393
+ )
394
+ subjects.update({r.id: r.subject for r in rows})
395
+ # States leaving `accepted` are written before states entering it, so the
396
+ # one-accepted-value index holds at every statement.
397
+ leaving = [_assertion_to_row(st) for st in states if st.id not in new_ids
398
+ and st.status is not Status.ACCEPTED]
399
+ entering = [_assertion_to_row(st) for st in states if st.id not in new_ids
400
+ and st.status is Status.ACCEPTED]
401
+ inserts = [_assertion_to_row(st) for st in states if st.id in new_ids]
402
+ if events:
403
+ rows_in = [
404
+ {
405
+ "id": ev.id,
406
+ "ts": ev.ts,
407
+ "type": ev.type.value,
408
+ "assertion_id": ev.assertion_id,
409
+ "subject": ev.data.get("subject") or subjects.get(ev.assertion_id, ""),
410
+ "actor": ev.actor,
411
+ "via": ev.via,
412
+ "correlation": ev.correlation,
413
+ "data": ev.data,
414
+ }
415
+ for ev in events
416
+ ]
417
+ if returning:
418
+ res = conn.execute(events_t.insert().returning(events_t.c.id, events_t.c.seq), rows_in)
419
+ seqs = {r.id: r.seq for r in res}
420
+ out = [replace(ev, seq=seqs.get(ev.id)) for ev in events]
421
+ else:
422
+ conn.execute(events_t.insert(), rows_in)
423
+ for batch in (leaving, None, entering):
424
+ if batch is None:
425
+ if inserts:
426
+ conn.execute(assertions_t.insert(), inserts)
427
+ continue
428
+ if batch:
429
+ cols = [c for c in batch[0] if c != "id"]
430
+ stmt = (
431
+ assertions_t.update()
432
+ .where(assertions_t.c.id == sa.bindparam("_id"))
433
+ .values({c: sa.bindparam(c) for c in cols})
434
+ )
435
+ conn.execute(stmt, [{**{c: r[c] for c in cols}, "_id": r["id"]} for r in batch])
436
+ except IntegrityError as exc:
437
+ if "uq_gloss_assertions_accepted" in str(exc) or "gloss_assertions.subject" in str(exc):
438
+ raise ConcurrentWrite(
439
+ "Another writer accepted a value for the same subject and attribute"
440
+ ) from exc
441
+ raise
442
+ return out
443
+
444
+ def reset_projection(self, states: Iterable[Assertion]) -> None:
445
+ """Replace every row of ``gloss_assertions`` with ``states``, in one transaction."""
446
+ with self.transaction() as conn:
447
+ conn.execute(assertions_t.delete())
448
+ rows = [_assertion_to_row(s) for s in states]
449
+ for i in range(0, len(rows), 5000):
450
+ conn.execute(assertions_t.insert(), rows[i : i + 5000])
451
+
452
+ # -- reads ----------------------------------------------------------------
453
+ def get(self, assertion_id: str) -> Assertion | None:
454
+ """The assertion with this id, or None."""
455
+ with self._read() as conn:
456
+ r = conn.execute(sa.select(assertions_t).where(assertions_t.c.id == assertion_id)).first()
457
+ return _row_to_assertion(r) if r else None
458
+
459
+ def get_many(self, ids: Iterable[str]) -> dict[str, Assertion]:
460
+ """Assertions by id, looked up in batches of 500; unknown ids are left out."""
461
+ ids = list(ids)
462
+ out: dict[str, Assertion] = {}
463
+ with self._read() as conn:
464
+ for i in range(0, len(ids), 500):
465
+ rows = conn.execute(sa.select(assertions_t).where(assertions_t.c.id.in_(ids[i : i + 500])))
466
+ out.update({r.id: _row_to_assertion(r) for r in rows})
467
+ return out
468
+
469
+ def by_id_prefix(self, prefix: str, limit: int = 2) -> list[Assertion]:
470
+ """Assertions whose id starts with ``prefix``; two tell a unique prefix from an ambiguous one."""
471
+ stmt = sa.select(assertions_t).where(self._starts(assertions_t.c.id, prefix)).limit(limit)
472
+ with self._read() as conn:
473
+ return [_row_to_assertion(r) for r in conn.execute(stmt)]
474
+
475
+ def find_for_subjects(
476
+ self,
477
+ subjects: Iterable[str],
478
+ statuses: Sequence[Status] | None = None,
479
+ *,
480
+ attributes: Sequence[str] | None = None,
481
+ scope: Scope | None = None,
482
+ ) -> list[Assertion]:
483
+ """All assertions about any of the given subjects (batched lookups for bulk operations)."""
484
+ subjects = sorted(set(subjects))
485
+ out: list[Assertion] = []
486
+ extra = []
487
+ if statuses:
488
+ extra.append(assertions_t.c.status.in_([Status(s).value for s in statuses]))
489
+ if attributes:
490
+ extra.append(assertions_t.c.attribute.in_(list(attributes)))
491
+ clause = self._readable(assertions_t.c.namespace, scope)
492
+ if clause is not None:
493
+ extra.append(clause)
494
+ with self._read() as conn:
495
+ for i in range(0, len(subjects), 500):
496
+ stmt = sa.select(assertions_t).where(assertions_t.c.subject.in_(subjects[i : i + 500]), *extra)
497
+ out += [_row_to_assertion(r) for r in conn.execute(stmt.order_by(assertions_t.c.created_at))]
498
+ return out
499
+
500
+ def _where(self, q: Query) -> list[Any]:
501
+ c = assertions_t.c
502
+ w: list[Any] = []
503
+ if q.subject is not None:
504
+ w.append(c.subject == q.subject)
505
+ if q.subject_prefix is not None:
506
+ w.append(self._starts(c.subject, q.subject_prefix))
507
+ if q.dataset is not None:
508
+ w.append(c.dataset == q.dataset)
509
+ if q.dataset_prefix is not None:
510
+ w.append(self._starts(c.dataset, q.dataset_prefix))
511
+ if q.namespace is not None:
512
+ w.append(self._under(c.namespace, q.namespace))
513
+ if q.kind is not None:
514
+ w.append(c.kind == q.kind)
515
+ if q.attribute is not None:
516
+ w.append(c.attribute == q.attribute)
517
+ if q.attributes:
518
+ w.append(c.attribute.in_(list(q.attributes)))
519
+ if q.statuses:
520
+ w.append(c.status.in_([Status(s).value for s in q.statuses]))
521
+ if q.source_prefix is not None:
522
+ w.append(self._starts(c.source, q.source_prefix))
523
+ if q.value_hash is not None:
524
+ w.append(c.value_hash == q.value_hash)
525
+ if q.group is not None:
526
+ w.append(c.group_id == q.group)
527
+ clause = self._readable(c.namespace, q.scope)
528
+ if clause is not None:
529
+ w.append(clause)
530
+ return w
531
+
532
+ def find(self, query: Query) -> list[Assertion]:
533
+ """Matching assertions, ordered by subject, attribute and age.
534
+
535
+ Without a limit the rows are sorted here, not in SQL: an ORDER BY tempts the planner into
536
+ walking the whole subject index in order, when a filter's own index would find a handful of rows.
537
+ """
538
+ stmt = sa.select(assertions_t).where(*self._where(query))
539
+ paged = query.limit is not None or query.offset
540
+ if paged:
541
+ stmt = stmt.order_by(
542
+ assertions_t.c.subject, assertions_t.c.attribute, assertions_t.c.created_at
543
+ ).offset(query.offset)
544
+ if query.limit is not None:
545
+ stmt = stmt.limit(query.limit)
546
+ with self._read() as conn:
547
+ rows = [_row_to_assertion(r) for r in conn.execute(stmt)]
548
+ if not paged:
549
+ rows.sort(key=lambda a: (a.subject, a.attribute, a.created_at))
550
+ return rows
551
+
552
+ def count(self, query: Query) -> int:
553
+ """Number of assertions matching ``query`` (its ``limit`` and ``offset`` are ignored)."""
554
+ stmt = sa.select(sa.func.count()).select_from(assertions_t).where(*self._where(query))
555
+ with self._read() as conn:
556
+ return conn.execute(stmt).scalar() or 0
557
+
558
+ def count_by_status(self, query: Query) -> dict[tuple[str | None, Status], int]:
559
+ """Counts grouped by (scope path, status)."""
560
+ c = assertions_t.c
561
+ stmt = (
562
+ sa.select(c.namespace, c.status, sa.func.count())
563
+ .where(*self._where(query))
564
+ .group_by(c.namespace, c.status)
565
+ )
566
+ with self._read() as conn:
567
+ return {(ns, Status(st)): n for ns, st, n in conn.execute(stmt)}
568
+
569
+ def distinct_subjects(self, query: Query) -> list[str]:
570
+ """Subjects with at least one assertion matching ``query``, in no particular order."""
571
+ stmt = sa.select(assertions_t.c.subject).where(*self._where(query)).distinct()
572
+ with self._read() as conn:
573
+ return [r[0] for r in conn.execute(stmt)]
574
+
575
+ def events(
576
+ self,
577
+ assertion_ids: Iterable[str] | None = None,
578
+ after_seq: int = 0,
579
+ limit: int | None = None,
580
+ *,
581
+ correlation: str | None = None,
582
+ scope: Scope | None = None,
583
+ ) -> list[Event]:
584
+ """Events after ``after_seq`` in log order, optionally of some assertions or one correlation only.
585
+
586
+ With ``scope``, only events of assertions whose current scope path the reader may see.
587
+ """
588
+ stmt = sa.select(events_t).where(events_t.c.seq > after_seq).order_by(events_t.c.seq)
589
+ if assertion_ids is not None:
590
+ stmt = stmt.where(events_t.c.assertion_id.in_(list(assertion_ids)))
591
+ if correlation is not None:
592
+ stmt = stmt.where(events_t.c.correlation == correlation)
593
+ clause = self._readable(assertions_t.c.namespace, scope)
594
+ if clause is not None:
595
+ stmt = stmt.where(
596
+ events_t.c.assertion_id.in_(sa.select(assertions_t.c.id).where(clause))
597
+ )
598
+ if limit is not None:
599
+ stmt = stmt.limit(limit)
600
+ with self._read() as conn:
601
+ return [_row_to_event(r) for r in conn.execute(stmt)]
602
+
603
+ def last_seq(self) -> int:
604
+ """Sequence number of the newest event (0 when empty)."""
605
+ with self._read() as conn:
606
+ return conn.execute(sa.select(sa.func.max(events_t.c.seq))).scalar() or 0
607
+
608
+ def events_for_subject(self, subject: str) -> list[Event]:
609
+ """Every event of the assertions now at ``subject``, so history follows a renamed subject."""
610
+ ids = sa.select(assertions_t.c.id).where(assertions_t.c.subject == subject)
611
+ stmt = sa.select(events_t).where(events_t.c.assertion_id.in_(ids)).order_by(events_t.c.seq)
612
+ with self._read() as conn:
613
+ return [_row_to_event(r) for r in conn.execute(stmt)]
614
+
615
+ def subject_versions(self, subjects: Iterable[str]) -> dict[str, int]:
616
+ """Per subject, the seq of the last event that could have changed its accepted definition."""
617
+ subjects = sorted(set(subjects))
618
+ out: dict[str, int] = {}
619
+ with self._read() as conn:
620
+ for i in range(0, len(subjects), 500):
621
+ stmt = (
622
+ sa.select(assertions_t.c.subject, sa.func.max(events_t.c.seq))
623
+ .select_from(events_t.join(assertions_t, assertions_t.c.id == events_t.c.assertion_id))
624
+ .where(assertions_t.c.subject.in_(subjects[i : i + 500]), events_t.c.type.in_(VERSION_EVENTS))
625
+ .group_by(assertions_t.c.subject)
626
+ )
627
+ out.update({s: int(v) for s, v in conn.execute(stmt)})
628
+ return out
629
+
630
+ # -- assets ---------------------------------------------------------------
631
+ @staticmethod
632
+ def _asset(r: Any) -> AssetRecord:
633
+ return AssetRecord(r.key, r.catalog, r.fingerprint, r.schema, r.uid)
634
+
635
+ def get_asset(self, catalog: str, key: str) -> AssetRecord | None:
636
+ """The last recorded shape of a catalog's asset, or None when it was never seen."""
637
+ with self._read() as conn:
638
+ r = conn.execute(
639
+ sa.select(assets_t).where(assets_t.c.catalog == catalog, assets_t.c.key == key)
640
+ ).first()
641
+ return self._asset(r) if r else None
642
+
643
+ def put_asset(self, record: AssetRecord) -> None:
644
+ """Record one asset's current shape (see :meth:`put_assets`)."""
645
+ self.put_assets([record])
646
+
647
+ def put_assets(self, records: Sequence[AssetRecord]) -> None:
648
+ """Replace the stored shape of each asset in ``records``, stamped now, in one transaction."""
649
+ if not records:
650
+ return
651
+ now = datetime.now(timezone.utc)
652
+ catalogs = {r.catalog for r in records}
653
+ with self.transaction() as conn:
654
+ for cat in catalogs:
655
+ keys = [r.key for r in records if r.catalog == cat]
656
+ for i in range(0, len(keys), 500):
657
+ conn.execute(
658
+ assets_t.delete().where(assets_t.c.catalog == cat, assets_t.c.key.in_(keys[i : i + 500]))
659
+ )
660
+ conn.execute(
661
+ assets_t.insert(),
662
+ [
663
+ {"catalog": r.catalog, "key": r.key, "fingerprint": r.fingerprint, "schema": r.schema,
664
+ "uid": r.uid, "seen_at": now}
665
+ for r in records
666
+ ],
667
+ )
668
+
669
+ def list_assets(self, catalog: str) -> list[AssetRecord]:
670
+ """Every recorded asset of one catalog."""
671
+ with self._read() as conn:
672
+ rows = conn.execute(sa.select(assets_t).where(assets_t.c.catalog == catalog))
673
+ return [self._asset(r) for r in rows]
674
+
675
+ def delete_asset(self, catalog: str, key: str) -> None:
676
+ """Forget an asset's recorded shape."""
677
+ with self.transaction() as conn:
678
+ conn.execute(assets_t.delete().where(assets_t.c.catalog == catalog, assets_t.c.key == key))
679
+
680
+ # -- search index -----------------------------------------------------------
681
+ def recreate_search_tables(self) -> None:
682
+ """Drop and recreate the full-text tables (needed when the tokenizer changes)."""
683
+ from .. import schema
684
+
685
+ if self.search_engine != "fts5":
686
+ return
687
+ with self.transaction() as conn:
688
+ conn.exec_driver_sql("DROP TABLE IF EXISTS gloss_search_vocab")
689
+ conn.exec_driver_sql("DROP TABLE IF EXISTS gloss_search_fts")
690
+ schema.create_fts(conn)
691
+
692
+ def _search_filters(
693
+ self, kinds: Sequence[str] | None, dataset_prefix: str | None, scope: Scope | None
694
+ ) -> list[Any]:
695
+ filters: list[Any] = []
696
+ if kinds:
697
+ filters.append(search_t.c.kind.in_(list(kinds)))
698
+ if dataset_prefix:
699
+ filters.append(self._starts(search_t.c.dataset, dataset_prefix))
700
+ clause = self._readable(search_t.c.namespace, scope)
701
+ if clause is not None:
702
+ filters.append(clause)
703
+ return filters
704
+
705
+ def search_names_containing(
706
+ self,
707
+ words: Sequence[str],
708
+ *,
709
+ kinds: Sequence[str] | None = None,
710
+ dataset_prefix: str | None = None,
711
+ scope: Scope | None = None,
712
+ limit: int = 20,
713
+ ) -> list[dict[str, Any]]:
714
+ """Rows whose *names* contain every word anywhere ("mail" in "useremail"). A slow-path fallback."""
715
+ if not words:
716
+ return []
717
+ where = [search_t.c.name_text.ilike(f"%{w}%") for w in words]
718
+ stmt = (
719
+ sa.select(search_t, sa.literal(0).label("score"))
720
+ .where(*where, *self._search_filters(kinds, dataset_prefix, scope))
721
+ .order_by(sa.func.length(search_t.c.name), search_t.c.subject)
722
+ .limit(limit)
723
+ )
724
+ with self._read() as conn:
725
+ return [dict(r._mapping) for r in conn.execute(stmt)]
726
+
727
+ def replace_search_rows(self, subjects: Iterable[str], rows: Sequence[dict[str, Any]]) -> None:
728
+ """Delete the index rows of ``subjects`` and insert ``rows`` (a subset of them) in one transaction."""
729
+ subjects = list(set(subjects) | {r["subject"] for r in rows})
730
+ with self.transaction() as conn:
731
+ for i in range(0, len(subjects), 500):
732
+ chunk = subjects[i : i + 500]
733
+ conn.execute(search_t.delete().where(search_t.c.subject.in_(chunk)))
734
+ if self.search_engine == "fts5":
735
+ marks = ",".join("?" * len(chunk))
736
+ conn.exec_driver_sql(f"DELETE FROM gloss_search_fts WHERE subject IN ({marks})", tuple(chunk))
737
+ if rows:
738
+ conn.execute(search_t.insert(), list(rows))
739
+ if self.search_engine == "fts5":
740
+ conn.exec_driver_sql(
741
+ "INSERT INTO gloss_search_fts (subject, name_text, detail_text) VALUES (?, ?, ?)",
742
+ [(r["subject"], r["name_text"], r["detail_text"]) for r in rows],
743
+ )
744
+
745
+ def clear_search(self) -> None:
746
+ """Delete every row of the search index, including the full-text table on SQLite."""
747
+ with self.transaction() as conn:
748
+ conn.execute(search_t.delete())
749
+ if self.search_engine == "fts5":
750
+ conn.exec_driver_sql("DELETE FROM gloss_search_fts")
751
+
752
+ def search_is_empty(self) -> bool:
753
+ """Whether the search index has no rows (e.g. it was never built)."""
754
+ with self._read() as conn:
755
+ return conn.execute(sa.select(search_t.c.subject).limit(1)).first() is None
756
+
757
+ def accepted_subjects(self) -> list[str]:
758
+ """Every subject with at least one accepted fact."""
759
+ return self.distinct_subjects(Query(statuses=[Status.ACCEPTED]))
760
+
761
+ def search(
762
+ self,
763
+ tokens: Sequence[str],
764
+ *,
765
+ max_level: int,
766
+ kinds: Sequence[str] | None = None,
767
+ dataset_prefix: str | None = None,
768
+ scope: Scope | None = None,
769
+ limit: int = 20,
770
+ match_any: bool = False,
771
+ ) -> list[dict[str, Any]]:
772
+ """Rows matching every token (or, with ``match_any``, at least one), ranked.
773
+
774
+ Details only count for rows at or below ``max_level``; above it, only names match.
775
+ """
776
+ if not tokens:
777
+ return []
778
+ exact = "_".join(tokens)
779
+ filters = self._search_filters(kinds, dataset_prefix, scope)
780
+ lname = sa.func.lower(search_t.c.name)
781
+ rank = sa.case(
782
+ (sa.or_(lname == exact, lname.like(f"%.{exact}")), 0), (lname.like(f"{exact}%"), 1), else_=2
783
+ )
784
+ with self._read() as conn:
785
+ if self.search_engine == "fts5":
786
+ joiner = " OR " if match_any else " AND "
787
+ q_all = joiner.join(f'"{t}"*' for t in tokens)
788
+ q_name = joiner.join(f'name_text : "{t}"*' for t in tokens)
789
+ fts = sa.table("gloss_search_fts", sa.column("subject"))
790
+ match = sa.text("gloss_search_fts MATCH :q_all")
791
+ by_name = sa.text("SELECT subject FROM gloss_search_fts WHERE gloss_search_fts MATCH :q_name")
792
+ score = sa.literal_column("bm25(gloss_search_fts, 0.0, 10.0, 1.0)").label("score")
793
+ stmt = (
794
+ sa.select(search_t, score)
795
+ .select_from(fts.join(search_t, search_t.c.subject == fts.c.subject))
796
+ .where(
797
+ match,
798
+ sa.or_(search_t.c.level <= max_level, search_t.c.subject.in_(by_name)),
799
+ *filters,
800
+ )
801
+ .order_by(*(["score"] if match_any else [rank, "score"]))
802
+ .limit(limit)
803
+ )
804
+ rows = conn.execute(stmt, {"q_all": q_all, "q_name": q_name})
805
+ return [dict(r._mapping) for r in rows]
806
+ # every token in the names, or in the details when visible: stemmed prefix matches on
807
+ # Postgres, plain substring matches elsewhere
808
+ if self.search_engine == "tsvector":
809
+ names = sa.literal_column(pg_tsvector("gloss_search.name_text"))
810
+ details = sa.literal_column(pg_tsvector("gloss_search.detail_text"))
811
+
812
+ def in_name(t: str) -> Any:
813
+ return names.op("@@")(sa.func.to_tsquery(sa.literal_column("'english'"), f"{t}:*"))
814
+
815
+ def in_detail(t: str) -> Any:
816
+ return details.op("@@")(sa.func.to_tsquery(sa.literal_column("'english'"), f"{t}:*"))
817
+ else:
818
+ def in_name(t: str) -> Any:
819
+ return search_t.c.name_text.ilike(f"%{t}%")
820
+
821
+ def in_detail(t: str) -> Any:
822
+ return search_t.c.detail_text.ilike(f"%{t}%")
823
+
824
+ cond = [
825
+ sa.or_(in_name(t), sa.and_(in_detail(t), search_t.c.level <= max_level)) for t in tokens
826
+ ]
827
+ matched = cond[0] if len(cond) == 1 else (sa.or_(*cond) if match_any else sa.and_(*cond))
828
+ hits_per_row = sum(sa.case((c, 1), else_=0) for c in cond)
829
+ name_hits = sum(sa.case((in_name(t), 1), else_=0) for t in tokens)
830
+ score = -(hits_per_row * 10 + name_hits)
831
+ stmt = (
832
+ sa.select(search_t, score.label("score"))
833
+ .where(matched, *filters)
834
+ .order_by(*(["score"] if match_any else [rank, "score"]), search_t.c.subject)
835
+ .limit(limit)
836
+ )
837
+ return [dict(r._mapping) for r in conn.execute(stmt)]
838
+
839
+ def search_vocabulary(self, *, names_only: bool = False) -> list[str]:
840
+ """Words (stems) in the search index; ``names_only`` limits them to always-visible names.
841
+
842
+ Needs the database's full-text search; empty for the plain-matching fallback.
843
+ """
844
+ if self.search_engine == "like":
845
+ return []
846
+ if self.search_engine == "tsvector":
847
+ text = "name_text" if names_only else "name_text || ' ' || detail_text"
848
+ inner = f"SELECT {pg_tsvector(text)} FROM gloss_search".replace("'", "''")
849
+ with self._read() as conn:
850
+ return [r[0] for r in conn.exec_driver_sql(f"SELECT word FROM ts_stat('{inner}')")]
851
+ sql = "SELECT DISTINCT term FROM gloss_search_vocab"
852
+ if names_only:
853
+ sql += " WHERE col = 'name_text'"
854
+ with self._read() as conn:
855
+ return [r[0] for r in conn.exec_driver_sql(sql)]
856
+
857
+ def get_meta(self, key: str) -> str | None:
858
+ """A value from ``gloss_meta`` (schema and index versions), or None."""
859
+ with self._read() as conn:
860
+ return conn.execute(sa.select(meta_t.c.value).where(meta_t.c.key == key)).scalar()
861
+
862
+ def set_meta(self, key: str, value: str) -> None:
863
+ """Insert or overwrite a value in ``gloss_meta``."""
864
+ with self.transaction() as conn:
865
+ if not conn.execute(meta_t.update().where(meta_t.c.key == key).values(value=value)).rowcount:
866
+ conn.execute(meta_t.insert().values(key=key, value=value))
867
+
868
+ # -- check results --------------------------------------------------------
869
+ def append_check_results(self, rows: Sequence[dict[str, Any]]) -> None:
870
+ """Insert logged check results (rows shaped like ``gloss_check_results``) in one transaction."""
871
+ if rows:
872
+ with self.transaction() as conn:
873
+ conn.execute(check_results_t.insert(), list(rows))
874
+
875
+ def check_results(
876
+ self,
877
+ subject: str | None = None,
878
+ subject_prefix: str | None = None,
879
+ limit: int | None = 200,
880
+ *,
881
+ run_id: str | None = None,
882
+ ) -> list[dict[str, Any]]:
883
+ """Logged check results, newest first; a falsy ``limit`` returns all of them."""
884
+ stmt = sa.select(check_results_t).order_by(check_results_t.c.id.desc())
885
+ if subject:
886
+ stmt = stmt.where(check_results_t.c.subject == subject)
887
+ if subject_prefix:
888
+ stmt = stmt.where(self._starts(check_results_t.c.subject, subject_prefix))
889
+ if run_id:
890
+ stmt = stmt.where(check_results_t.c.run_id == run_id)
891
+ if limit:
892
+ stmt = stmt.limit(limit)
893
+ with self._read() as conn:
894
+ return [{**r._asdict(), "ts": _aware(r.ts)} for r in conn.execute(stmt)]
895
+
896
+ def rename_check_subjects(self, renames: dict[str, str]) -> None:
897
+ """Keep logged check results with their field when its subject is re-keyed."""
898
+ if not renames:
899
+ return
900
+ stmt = (
901
+ check_results_t.update()
902
+ .where(check_results_t.c.subject == sa.bindparam("_old"))
903
+ .values(subject=sa.bindparam("_new"))
904
+ )
905
+ with self.transaction() as conn:
906
+ conn.execute(stmt, [{"_old": o, "_new": n} for o, n in renames.items()])
907
+
908
+ def close(self) -> None:
909
+ """Dispose of an owned engine, refreshing SQLite's statistics first; a host's is left alone."""
910
+ if not self.owns_engine:
911
+ return # the host's engine is the host's to dispose
912
+ if self.dialect == "sqlite":
913
+ try:
914
+ with self.engine.begin() as conn:
915
+ conn.exec_driver_sql("PRAGMA optimize") # refresh planner statistics cheaply
916
+ except Exception:
917
+ pass
918
+ self.engine.dispose()