glosslayer 0.1.0__tar.gz → 0.2.0__tar.gz

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.
Files changed (85) hide show
  1. {glosslayer-0.1.0 → glosslayer-0.2.0}/CHANGELOG.md +19 -0
  2. {glosslayer-0.1.0 → glosslayer-0.2.0}/PKG-INFO +122 -3
  3. {glosslayer-0.1.0 → glosslayer-0.2.0}/README.md +121 -2
  4. {glosslayer-0.1.0 → glosslayer-0.2.0}/docs/architecture.md +22 -2
  5. {glosslayer-0.1.0 → glosslayer-0.2.0}/pyproject.toml +1 -1
  6. {glosslayer-0.1.0 → glosslayer-0.2.0}/src/glosslayer/__init__.py +1 -1
  7. glosslayer-0.2.0/src/glosslayer/dialect.py +74 -0
  8. glosslayer-0.2.0/src/glosslayer/joins.py +211 -0
  9. {glosslayer-0.1.0 → glosslayer-0.2.0}/src/glosslayer/ledger.py +138 -0
  10. {glosslayer-0.1.0 → glosslayer-0.2.0}/src/glosslayer/modeling.py +3 -3
  11. glosslayer-0.2.0/src/glosslayer/modelview.py +413 -0
  12. glosslayer-0.2.0/src/glosslayer/query.py +558 -0
  13. glosslayer-0.2.0/src/glosslayer/rules.py +557 -0
  14. {glosslayer-0.1.0 → glosslayer-0.2.0}/src/glosslayer/visibility.py +38 -2
  15. glosslayer-0.2.0/tests/test_joins.py +143 -0
  16. glosslayer-0.2.0/tests/test_modelview.py +231 -0
  17. glosslayer-0.2.0/tests/test_query.py +273 -0
  18. {glosslayer-0.1.0 → glosslayer-0.2.0}/tests/test_readme.py +4 -0
  19. glosslayer-0.2.0/tests/test_rules.py +268 -0
  20. {glosslayer-0.1.0 → glosslayer-0.2.0}/tests/test_scoped_reads.py +9 -0
  21. glosslayer-0.2.0/tests/test_visibility_above.py +56 -0
  22. glosslayer-0.2.0/tests/test_withdraw.py +113 -0
  23. {glosslayer-0.1.0 → glosslayer-0.2.0}/.gitignore +0 -0
  24. {glosslayer-0.1.0 → glosslayer-0.2.0}/LICENSE +0 -0
  25. {glosslayer-0.1.0 → glosslayer-0.2.0}/NOTICE +0 -0
  26. {glosslayer-0.1.0 → glosslayer-0.2.0}/examples/catalog.yaml +0 -0
  27. {glosslayer-0.1.0 → glosslayer-0.2.0}/examples/catalog_v2.yaml +0 -0
  28. {glosslayer-0.1.0 → glosslayer-0.2.0}/examples/e2e_shop.py +0 -0
  29. {glosslayer-0.1.0 → glosslayer-0.2.0}/examples/e2e_shop_output.txt +0 -0
  30. {glosslayer-0.1.0 → glosslayer-0.2.0}/examples/mcp_client.py +0 -0
  31. {glosslayer-0.1.0 → glosslayer-0.2.0}/examples/semantic_model.yaml +0 -0
  32. {glosslayer-0.1.0 → glosslayer-0.2.0}/scripts/bench.py +0 -0
  33. {glosslayer-0.1.0 → glosslayer-0.2.0}/src/glosslayer/actors.py +0 -0
  34. {glosslayer-0.1.0 → glosslayer-0.2.0}/src/glosslayer/ai.py +0 -0
  35. {glosslayer-0.1.0 → glosslayer-0.2.0}/src/glosslayer/catalogs/__init__.py +0 -0
  36. {glosslayer-0.1.0 → glosslayer-0.2.0}/src/glosslayer/catalogs/file.py +0 -0
  37. {glosslayer-0.1.0 → glosslayer-0.2.0}/src/glosslayer/checks.py +0 -0
  38. {glosslayer-0.1.0 → glosslayer-0.2.0}/src/glosslayer/cli.py +0 -0
  39. {glosslayer-0.1.0 → glosslayer-0.2.0}/src/glosslayer/client.py +0 -0
  40. {glosslayer-0.1.0 → glosslayer-0.2.0}/src/glosslayer/dtypes.py +0 -0
  41. {glosslayer-0.1.0 → glosslayer-0.2.0}/src/glosslayer/ids.py +0 -0
  42. {glosslayer-0.1.0 → glosslayer-0.2.0}/src/glosslayer/mcp_server.py +0 -0
  43. {glosslayer-0.1.0 → glosslayer-0.2.0}/src/glosslayer/model.py +0 -0
  44. {glosslayer-0.1.0 → glosslayer-0.2.0}/src/glosslayer/ossie/__init__.py +0 -0
  45. {glosslayer-0.1.0 → glosslayer-0.2.0}/src/glosslayer/ossie/exporter.py +0 -0
  46. {glosslayer-0.1.0 → glosslayer-0.2.0}/src/glosslayer/ossie/importer.py +0 -0
  47. {glosslayer-0.1.0 → glosslayer-0.2.0}/src/glosslayer/ossie/ossie-schema.json +0 -0
  48. {glosslayer-0.1.0 → glosslayer-0.2.0}/src/glosslayer/plugins.py +0 -0
  49. {glosslayer-0.1.0 → glosslayer-0.2.0}/src/glosslayer/policy.py +0 -0
  50. {glosslayer-0.1.0 → glosslayer-0.2.0}/src/glosslayer/references.py +0 -0
  51. {glosslayer-0.1.0 → glosslayer-0.2.0}/src/glosslayer/schema.py +0 -0
  52. {glosslayer-0.1.0 → glosslayer-0.2.0}/src/glosslayer/seams.py +0 -0
  53. {glosslayer-0.1.0 → glosslayer-0.2.0}/src/glosslayer/search_index.py +0 -0
  54. {glosslayer-0.1.0 → glosslayer-0.2.0}/src/glosslayer/semantic.py +0 -0
  55. {glosslayer-0.1.0 → glosslayer-0.2.0}/src/glosslayer/server.py +0 -0
  56. {glosslayer-0.1.0 → glosslayer-0.2.0}/src/glosslayer/sinks.py +0 -0
  57. {glosslayer-0.1.0 → glosslayer-0.2.0}/src/glosslayer/store/__init__.py +0 -0
  58. {glosslayer-0.1.0 → glosslayer-0.2.0}/src/glosslayer/store/base.py +0 -0
  59. {glosslayer-0.1.0 → glosslayer-0.2.0}/src/glosslayer/store/sql.py +0 -0
  60. {glosslayer-0.1.0 → glosslayer-0.2.0}/src/glosslayer/sync.py +0 -0
  61. {glosslayer-0.1.0 → glosslayer-0.2.0}/src/glosslayer/types.py +0 -0
  62. {glosslayer-0.1.0 → glosslayer-0.2.0}/src/glosslayer/viz.py +0 -0
  63. {glosslayer-0.1.0 → glosslayer-0.2.0}/tests/conftest.py +0 -0
  64. {glosslayer-0.1.0 → glosslayer-0.2.0}/tests/ossie_renamed_fields.yaml +0 -0
  65. {glosslayer-0.1.0 → glosslayer-0.2.0}/tests/test_ai.py +0 -0
  66. {glosslayer-0.1.0 → glosslayer-0.2.0}/tests/test_checks_plan.py +0 -0
  67. {glosslayer-0.1.0 → glosslayer-0.2.0}/tests/test_client.py +0 -0
  68. {glosslayer-0.1.0 → glosslayer-0.2.0}/tests/test_concurrency.py +0 -0
  69. {glosslayer-0.1.0 → glosslayer-0.2.0}/tests/test_definitions.py +0 -0
  70. {glosslayer-0.1.0 → glosslayer-0.2.0}/tests/test_e2e_example.py +0 -0
  71. {glosslayer-0.1.0 → glosslayer-0.2.0}/tests/test_host_database.py +0 -0
  72. {glosslayer-0.1.0 → glosslayer-0.2.0}/tests/test_ids.py +0 -0
  73. {glosslayer-0.1.0 → glosslayer-0.2.0}/tests/test_interfaces.py +0 -0
  74. {glosslayer-0.1.0 → glosslayer-0.2.0}/tests/test_ledger.py +0 -0
  75. {glosslayer-0.1.0 → glosslayer-0.2.0}/tests/test_misc_interfaces.py +0 -0
  76. {glosslayer-0.1.0 → glosslayer-0.2.0}/tests/test_modeling.py +0 -0
  77. {glosslayer-0.1.0 → glosslayer-0.2.0}/tests/test_modeling_v2.py +0 -0
  78. {glosslayer-0.1.0 → glosslayer-0.2.0}/tests/test_ossie.py +0 -0
  79. {glosslayer-0.1.0 → glosslayer-0.2.0}/tests/test_policy.py +0 -0
  80. {glosslayer-0.1.0 → glosslayer-0.2.0}/tests/test_readers.py +0 -0
  81. {glosslayer-0.1.0 → glosslayer-0.2.0}/tests/test_rekey.py +0 -0
  82. {glosslayer-0.1.0 → glosslayer-0.2.0}/tests/test_search.py +0 -0
  83. {glosslayer-0.1.0 → glosslayer-0.2.0}/tests/test_semantic_types.py +0 -0
  84. {glosslayer-0.1.0 → glosslayer-0.2.0}/tests/test_sync.py +0 -0
  85. {glosslayer-0.1.0 → glosslayer-0.2.0}/tests/test_sync_events.py +0 -0
@@ -1,5 +1,24 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.2.0 (2026-11-25)
4
+
5
+ Only additions: the event format, subject grammar and database schema are unchanged.
6
+
7
+ ### Queries and data
8
+ - `glosslayer.query`: compile a metric by dimensions, filters and time grain into one SQL statement, following joins
9
+ many to one; `check_metric` (compile and dry-run a proposal) and `dependents` (what stops compiling without a join).
10
+ - `glosslayer.joins`: measure a join's two sides (`ok`, `reversed`, `many_to_many`, `unchecked`), one or a whole
11
+ model's, and `validate` one without asking the data.
12
+ - `glosslayer.rules`: suggest column roles, joins and metrics from types and one aggregate per table, and store them
13
+ as proposals with their evidence, optionally in an AI's words.
14
+ - `glosslayer.dialect`: SQL quoting, literals and date truncation, and the contract of a host's `execute`.
15
+
16
+ ### Reading and reviewing
17
+ - `Gloss.model_view`: a namespace's model with its review state beside it; `Gloss.facts`, `Gloss.review_queue`,
18
+ `Gloss.metric_names`.
19
+ - `visibility.above`: datasets and columns above a level by the strongest live claim.
20
+ - `Gloss.withdraw`, `withdraw_subject`, `can_withdraw`, `clear` and `retract_left_out`.
21
+
3
22
  ## 0.1.0 (2026-11-24)
4
23
 
5
24
  First public version. The event format, subject grammar and schema are at version 1; ledgers created by
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: glosslayer
3
- Version: 0.1.0
3
+ Version: 0.2.0
4
4
  Summary: A catalog-agnostic semantic layer: track, review, visualize and serve Apache Ossie semantic models.
5
5
  Project-URL: Homepage, https://github.com/Edwardvaneechoud/glosslayer
6
6
  Project-URL: Repository, https://github.com/Edwardvaneechoud/glosslayer
@@ -400,7 +400,8 @@ before and no longer declare (a column you deleted from the `Table`).
400
400
  `Relationship(..., namespace="sales")`, `Metric(..., namespace="sales")` and
401
401
  `SemanticType(..., namespace="crm")` put a definition in a namespace. A metric can also carry its
402
402
  structured parts next to the SQL (`aggregate`, `filter`, `time_column`, `dimensions`, `format`), and a
403
- column its `role` (`key`, `time`, `category`, `amount`), for hosts that build metric queries.
403
+ column its `role` (`key`, `time`, `category`, `amount`); [metric queries](#metric-queries-joins-and-suggestions)
404
+ are compiled from them.
404
405
 
405
406
  ### Review
406
407
 
@@ -429,6 +430,12 @@ value automatically supersedes the previously accepted one, and `g.restore(old_i
429
430
  value back. Accepting one fact of a relationship's or metric's proposal group accepts the group
430
431
  (`g.accept_group(group, ...)` says so explicitly); if one part cannot be accepted, none is.
431
432
 
433
+ To take something away without deciding fact by fact, `g.withdraw(facts, ...)` retracts what is held (an
434
+ accepted fact, your own proposal) and rejects what someone else proposed, all or nothing.
435
+ `g.withdraw_subject("metric:crm.orders/revenue", ...)` removes a whole definition,
436
+ `g.clear([(subject, "description")], ...)` empties single attributes, and `g.can_withdraw(subjects, ...)` asks the
437
+ policy first. The history keeps everything.
438
+
432
439
  Who may do what is the policy's decision: see [Policies and review modes](#policies-and-review-modes).
433
440
 
434
441
  ### Read back
@@ -613,6 +620,114 @@ are what's redacted.
613
620
  On SQLite search uses FTS5; on Postgres `tsvector` with GIN indexes. Both stem words and feed the
614
621
  spelling suggestions. Any other database falls back to plain matching.
615
622
 
623
+ ## Metric queries, joins and suggestions
624
+
625
+ Gloss compiles, measures and suggests; it never connects to your data. A query is compiled to one SQL statement
626
+ you run; anything that needs an answer from the data takes an `execute` function that runs a statement and
627
+ returns its rows.
628
+
629
+ ### Ask for a metric
630
+
631
+ ```python
632
+ from glosslayer.query import Filter, MetricQuery, QueryModel, compile_query
633
+
634
+ model = QueryModel.read(g) # the accepted metrics, joins and columns
635
+ q = compile_query(model, MetricQuery("revenue", ["customers.country"], [Filter("status", "=", "open")]))
636
+ print(q.sql)
637
+ # SELECT "orders"."__gloss_d1" AS "customers.country", SUM(orders.amount) AS "revenue"
638
+ # FROM (SELECT "orders".*, "j1"."country" AS "__gloss_d1" FROM "crm.orders" AS "orders" LEFT JOIN "crm.customers" AS "j1" ON "orders"."customer_id" = "j1"."customer_id" WHERE "orders"."status" = 'open') AS "orders"
639
+ # GROUP BY "orders"."__gloss_d1"
640
+ # ORDER BY "customers.country" ASC
641
+ # LIMIT 1000
642
+ print(q.tables, q.metric.version is not None) # ['crm.orders', 'crm.customers'] True
643
+ ```
644
+
645
+ - Joins are followed only from their many side to their one side, so a joined table never multiplies the base
646
+ table's rows. A metric's own expression and filter may name a joined table's column (`customers.country`).
647
+ - Free SQL comes only from the accepted metric. Names in a query are checked against the model and quoted, values
648
+ are written as literals, and what cannot compile is a `ValueError` that says what to write instead.
649
+ - `grain="month"` groups by the metric's `time_column`; a metric with `dimensions` may only be broken down by those.
650
+ - `table_names={key: name}` writes a table under another name, `dialect=` is `ansi` (default), `postgres`, `duckdb`,
651
+ `snowflake` or `bigquery`.
652
+ - `check_metric(model, metric, execute)` refuses a proposed metric that does not compile or run, and
653
+ `dependents(model, join)` lists the metrics that would stop compiling without a join.
654
+
655
+ ### Measure a join
656
+
657
+ A join whose *to* side repeats its key silently multiplies every number over it, so measure it before you trust it:
658
+
659
+ ```python
660
+ import sqlite3
661
+ from glosslayer import joins
662
+
663
+ warehouse = sqlite3.connect(":memory:")
664
+ warehouse.executescript('''
665
+ CREATE TABLE "crm.customers" (customer_id, country);
666
+ INSERT INTO "crm.customers" VALUES (1, 'NL'), (2, 'BE');
667
+ CREATE TABLE "crm.orders" (order_id, customer_id, amount);
668
+ INSERT INTO "crm.orders" VALUES (1, 1, 10.0), (2, 1, 5.5), (3, 2, 10.0);
669
+ ''')
670
+
671
+ def execute(sql): # raise QueryFailed / EngineUnavailable (glosslayer.dialect) on errors
672
+ return warehouse.execute(sql).fetchall()
673
+
674
+ found = joins.check("crm.orders", ["customer_id"], "crm.customers", ["customer_id"], execute)
675
+ print(found.verdict, "-", found.message)
676
+ # ok - customer_id is unique in customers (2 of 2 rows) and repeats in orders (2 distinct in 3 rows).
677
+ print(joins.check("crm.customers", ["customer_id"], "crm.orders", ["customer_id"], execute).verdict) # reversed
678
+ ```
679
+
680
+ ### Let rules suggest
681
+
682
+ Rules read column types and one aggregate per table, never what a name seems to mean, and propose roles, joins and
683
+ metrics with their evidence:
684
+
685
+ ```python
686
+ from glosslayer import rules
687
+ from glosslayer.model import LIVE_STATUSES
688
+ from glosslayer.seams import AssetSchema
689
+ from glosslayer.seams import Column as CatalogColumn
690
+
691
+ tables = [ # what your catalog lists: a Catalog plugin's describe() gives these
692
+ AssetSchema("crm.customers", [CatalogColumn("customer_id", "Int64"), CatalogColumn("country", "String")]),
693
+ AssetSchema("crm.orders", [CatalogColumn("order_id", "Int64"), CatalogColumn("customer_id", "Int64"),
694
+ CatalogColumn("amount", "Float64")]),
695
+ ]
696
+ stats, problem = rules.collect_stats(tables, execute)
697
+ suggestions = rules.suggest(stats)
698
+ print([(m.table, m.name) for m in suggestions.metrics][1:3])
699
+ # [('crm.orders', 'order_count'), ('crm.orders', 'total_amount')]
700
+
701
+ draft = glosslayer.open("sqlite://")
702
+ view = draft.model_view("crm", tables=tables, statuses=LIVE_STATUSES)
703
+ print(rules.propose(draft.as_actor(Human("edward")), view, suggestions).added)
704
+ # Counts(roles=5, descriptions=0, joins=1, metrics=5)
705
+ ```
706
+
707
+ They are stated by `inferred:rules`, so they queue for review; a second run skips what the model holds. An AI's
708
+ better names and descriptions go in as `words=`, stated by the agent that wrote them.
709
+
710
+ ### What waits, beside what is agreed
711
+
712
+ `g.table(...)` and friends answer "what is the model". A screen that edits and reviews one also needs what is
713
+ waiting next to it, who stated it and why:
714
+
715
+ ```python
716
+ view = draft.model_view("crm", tables=tables, statuses=LIVE_STATUSES)
717
+ amount = view.table("orders").column("amount")
718
+ print(amount.value("role"), amount.pending[0].source, "-", amount.pending[0].rationale)
719
+ # amount inferred:rules - Rule: amount is numeric (Float64) and repeats (2 distinct in 3 rows).
720
+ print(len(draft.review_queue("crm", tables=tables))) # 11
721
+
722
+ total = next(m for m in view.metrics if m.name == "total_amount")
723
+ draft.accept_group(total.group, actor=Human("alice"))
724
+ print(len(draft.review_queue("crm", tables=tables))) # 10
725
+ draft.close()
726
+ ```
727
+
728
+ A join or a metric is one entry with its whole proposal group. With accepted facts only (the default) the view is
729
+ the published model, and `compile_query` takes it as it is.
730
+
616
731
  ## AI agents
617
732
 
618
733
  ### MCP
@@ -1058,6 +1173,11 @@ src/glosslayer/
1058
1173
  dtypes.py Int(32), Decimal(18, 2), String(255), DateTime(tz=…)
1059
1174
  checks.py data quality checks, single-pass Polars plan, SQL generation
1060
1175
  semantic.py TypeSuggester
1176
+ query.py compiling metric queries to SQL, checking metrics, what depends on a join
1177
+ joins.py measuring joins against the data
1178
+ rules.py rule-based suggestions: roles, joins, metrics
1179
+ modelview.py a namespace's model with its review state beside it, the review queue
1180
+ dialect.py quoting, literals and the contract of `execute`
1061
1181
  visibility.py confidentiality levels of subjects
1062
1182
  references.py which facts mention a column or table
1063
1183
  search_index.py search index rows, incremental updates, rebuild
@@ -1091,7 +1211,6 @@ and [CLAUDE.md](CLAUDE.md) for conventions.
1091
1211
  - Review UI as an embeddable component
1092
1212
  - An AI suggester source: describe undocumented fields in batches, as proposals
1093
1213
  - Table-level and cross-column checks; retention for check results
1094
- - Compiling structured metrics into queries (the host's engine does this today)
1095
1214
  - A per-dataset Ossie name override for exports
1096
1215
  - Semantic (embedding) search; an optional Rust search core for very large ledgers
1097
1216
 
@@ -345,7 +345,8 @@ before and no longer declare (a column you deleted from the `Table`).
345
345
  `Relationship(..., namespace="sales")`, `Metric(..., namespace="sales")` and
346
346
  `SemanticType(..., namespace="crm")` put a definition in a namespace. A metric can also carry its
347
347
  structured parts next to the SQL (`aggregate`, `filter`, `time_column`, `dimensions`, `format`), and a
348
- column its `role` (`key`, `time`, `category`, `amount`), for hosts that build metric queries.
348
+ column its `role` (`key`, `time`, `category`, `amount`); [metric queries](#metric-queries-joins-and-suggestions)
349
+ are compiled from them.
349
350
 
350
351
  ### Review
351
352
 
@@ -374,6 +375,12 @@ value automatically supersedes the previously accepted one, and `g.restore(old_i
374
375
  value back. Accepting one fact of a relationship's or metric's proposal group accepts the group
375
376
  (`g.accept_group(group, ...)` says so explicitly); if one part cannot be accepted, none is.
376
377
 
378
+ To take something away without deciding fact by fact, `g.withdraw(facts, ...)` retracts what is held (an
379
+ accepted fact, your own proposal) and rejects what someone else proposed, all or nothing.
380
+ `g.withdraw_subject("metric:crm.orders/revenue", ...)` removes a whole definition,
381
+ `g.clear([(subject, "description")], ...)` empties single attributes, and `g.can_withdraw(subjects, ...)` asks the
382
+ policy first. The history keeps everything.
383
+
377
384
  Who may do what is the policy's decision: see [Policies and review modes](#policies-and-review-modes).
378
385
 
379
386
  ### Read back
@@ -558,6 +565,114 @@ are what's redacted.
558
565
  On SQLite search uses FTS5; on Postgres `tsvector` with GIN indexes. Both stem words and feed the
559
566
  spelling suggestions. Any other database falls back to plain matching.
560
567
 
568
+ ## Metric queries, joins and suggestions
569
+
570
+ Gloss compiles, measures and suggests; it never connects to your data. A query is compiled to one SQL statement
571
+ you run; anything that needs an answer from the data takes an `execute` function that runs a statement and
572
+ returns its rows.
573
+
574
+ ### Ask for a metric
575
+
576
+ ```python
577
+ from glosslayer.query import Filter, MetricQuery, QueryModel, compile_query
578
+
579
+ model = QueryModel.read(g) # the accepted metrics, joins and columns
580
+ q = compile_query(model, MetricQuery("revenue", ["customers.country"], [Filter("status", "=", "open")]))
581
+ print(q.sql)
582
+ # SELECT "orders"."__gloss_d1" AS "customers.country", SUM(orders.amount) AS "revenue"
583
+ # FROM (SELECT "orders".*, "j1"."country" AS "__gloss_d1" FROM "crm.orders" AS "orders" LEFT JOIN "crm.customers" AS "j1" ON "orders"."customer_id" = "j1"."customer_id" WHERE "orders"."status" = 'open') AS "orders"
584
+ # GROUP BY "orders"."__gloss_d1"
585
+ # ORDER BY "customers.country" ASC
586
+ # LIMIT 1000
587
+ print(q.tables, q.metric.version is not None) # ['crm.orders', 'crm.customers'] True
588
+ ```
589
+
590
+ - Joins are followed only from their many side to their one side, so a joined table never multiplies the base
591
+ table's rows. A metric's own expression and filter may name a joined table's column (`customers.country`).
592
+ - Free SQL comes only from the accepted metric. Names in a query are checked against the model and quoted, values
593
+ are written as literals, and what cannot compile is a `ValueError` that says what to write instead.
594
+ - `grain="month"` groups by the metric's `time_column`; a metric with `dimensions` may only be broken down by those.
595
+ - `table_names={key: name}` writes a table under another name, `dialect=` is `ansi` (default), `postgres`, `duckdb`,
596
+ `snowflake` or `bigquery`.
597
+ - `check_metric(model, metric, execute)` refuses a proposed metric that does not compile or run, and
598
+ `dependents(model, join)` lists the metrics that would stop compiling without a join.
599
+
600
+ ### Measure a join
601
+
602
+ A join whose *to* side repeats its key silently multiplies every number over it, so measure it before you trust it:
603
+
604
+ ```python
605
+ import sqlite3
606
+ from glosslayer import joins
607
+
608
+ warehouse = sqlite3.connect(":memory:")
609
+ warehouse.executescript('''
610
+ CREATE TABLE "crm.customers" (customer_id, country);
611
+ INSERT INTO "crm.customers" VALUES (1, 'NL'), (2, 'BE');
612
+ CREATE TABLE "crm.orders" (order_id, customer_id, amount);
613
+ INSERT INTO "crm.orders" VALUES (1, 1, 10.0), (2, 1, 5.5), (3, 2, 10.0);
614
+ ''')
615
+
616
+ def execute(sql): # raise QueryFailed / EngineUnavailable (glosslayer.dialect) on errors
617
+ return warehouse.execute(sql).fetchall()
618
+
619
+ found = joins.check("crm.orders", ["customer_id"], "crm.customers", ["customer_id"], execute)
620
+ print(found.verdict, "-", found.message)
621
+ # ok - customer_id is unique in customers (2 of 2 rows) and repeats in orders (2 distinct in 3 rows).
622
+ print(joins.check("crm.customers", ["customer_id"], "crm.orders", ["customer_id"], execute).verdict) # reversed
623
+ ```
624
+
625
+ ### Let rules suggest
626
+
627
+ Rules read column types and one aggregate per table, never what a name seems to mean, and propose roles, joins and
628
+ metrics with their evidence:
629
+
630
+ ```python
631
+ from glosslayer import rules
632
+ from glosslayer.model import LIVE_STATUSES
633
+ from glosslayer.seams import AssetSchema
634
+ from glosslayer.seams import Column as CatalogColumn
635
+
636
+ tables = [ # what your catalog lists: a Catalog plugin's describe() gives these
637
+ AssetSchema("crm.customers", [CatalogColumn("customer_id", "Int64"), CatalogColumn("country", "String")]),
638
+ AssetSchema("crm.orders", [CatalogColumn("order_id", "Int64"), CatalogColumn("customer_id", "Int64"),
639
+ CatalogColumn("amount", "Float64")]),
640
+ ]
641
+ stats, problem = rules.collect_stats(tables, execute)
642
+ suggestions = rules.suggest(stats)
643
+ print([(m.table, m.name) for m in suggestions.metrics][1:3])
644
+ # [('crm.orders', 'order_count'), ('crm.orders', 'total_amount')]
645
+
646
+ draft = glosslayer.open("sqlite://")
647
+ view = draft.model_view("crm", tables=tables, statuses=LIVE_STATUSES)
648
+ print(rules.propose(draft.as_actor(Human("edward")), view, suggestions).added)
649
+ # Counts(roles=5, descriptions=0, joins=1, metrics=5)
650
+ ```
651
+
652
+ They are stated by `inferred:rules`, so they queue for review; a second run skips what the model holds. An AI's
653
+ better names and descriptions go in as `words=`, stated by the agent that wrote them.
654
+
655
+ ### What waits, beside what is agreed
656
+
657
+ `g.table(...)` and friends answer "what is the model". A screen that edits and reviews one also needs what is
658
+ waiting next to it, who stated it and why:
659
+
660
+ ```python
661
+ view = draft.model_view("crm", tables=tables, statuses=LIVE_STATUSES)
662
+ amount = view.table("orders").column("amount")
663
+ print(amount.value("role"), amount.pending[0].source, "-", amount.pending[0].rationale)
664
+ # amount inferred:rules - Rule: amount is numeric (Float64) and repeats (2 distinct in 3 rows).
665
+ print(len(draft.review_queue("crm", tables=tables))) # 11
666
+
667
+ total = next(m for m in view.metrics if m.name == "total_amount")
668
+ draft.accept_group(total.group, actor=Human("alice"))
669
+ print(len(draft.review_queue("crm", tables=tables))) # 10
670
+ draft.close()
671
+ ```
672
+
673
+ A join or a metric is one entry with its whole proposal group. With accepted facts only (the default) the view is
674
+ the published model, and `compile_query` takes it as it is.
675
+
561
676
  ## AI agents
562
677
 
563
678
  ### MCP
@@ -1003,6 +1118,11 @@ src/glosslayer/
1003
1118
  dtypes.py Int(32), Decimal(18, 2), String(255), DateTime(tz=…)
1004
1119
  checks.py data quality checks, single-pass Polars plan, SQL generation
1005
1120
  semantic.py TypeSuggester
1121
+ query.py compiling metric queries to SQL, checking metrics, what depends on a join
1122
+ joins.py measuring joins against the data
1123
+ rules.py rule-based suggestions: roles, joins, metrics
1124
+ modelview.py a namespace's model with its review state beside it, the review queue
1125
+ dialect.py quoting, literals and the contract of `execute`
1006
1126
  visibility.py confidentiality levels of subjects
1007
1127
  references.py which facts mention a column or table
1008
1128
  search_index.py search index rows, incremental updates, rebuild
@@ -1036,7 +1156,6 @@ and [CLAUDE.md](CLAUDE.md) for conventions.
1036
1156
  - Review UI as an embeddable component
1037
1157
  - An AI suggester source: describe undocumented fields in batches, as proposals
1038
1158
  - Table-level and cross-column checks; retention for check results
1039
- - Compiling structured metrics into queries (the host's engine does this today)
1040
1159
  - A per-dataset Ossie name override for exports
1041
1160
  - Semantic (embedding) search; an optional Rust search core for very large ledgers
1042
1161
 
@@ -5,7 +5,7 @@
5
5
  | Layer | Owns | Does not own |
6
6
  |---|---|---|
7
7
  | **Apache Ossie** | The *format* of a semantic model: datasets, fields, relationships, metrics, AI context | Workflow, review, confidentiality, history |
8
- | **Gloss core** | Facts about the model, their lifecycle, the event log, the mechanism of review and scoped reads, projections | Any specific catalog, tool or UI; who the users are; what they are allowed |
8
+ | **Gloss core** | Facts about the model, their lifecycle, the event log, the mechanism of review and scoped reads, projections; compiling metric queries, the questions that measure a join or a column | Any specific catalog, tool or UI; who the users are; what they are allowed; running SQL |
9
9
  | **The host's policy** | Who may do what, what is accepted without review, who reads what | The mechanism |
10
10
  | **Plugins** | Talking to a specific catalog, importer, exporter or AI | The workflow rules |
11
11
 
@@ -119,6 +119,25 @@ where the status is accepted makes a lost race an error the ledger retries, not
119
119
  and pending markers are exported under `nonportable_extensions[vendor_name=gloss]`, so exports stay
120
120
  valid Ossie and round trips keep them.
121
121
 
122
+ **Gloss writes SQL and never runs it.** Compiling a metric query, measuring a join and collecting the
123
+ statistics rules need are the same everywhere; where the data lives and who may read it are not. So
124
+ `glosslayer.query` returns a statement, and what needs an answer (`joins.check`, `rules.collect_stats`, a
125
+ metric's dry-run) takes the host's `execute(sql) -> rows`. `execute` tells a failed statement
126
+ (`QueryFailed`) from an engine that is not there (`EngineUnavailable`), because the first is about one table
127
+ and the second about every statement after it: authoring goes on without an engine, and nothing is refused for
128
+ its absence. Table naming and the dialect are options, not assumptions.
129
+
130
+ **Two ways of reading a model.** `snapshot`, `tables()` and the other readers merge statuses into one value per
131
+ attribute: what the model *is*. `model_view` keeps the accepted value and the open facts beside it, because a
132
+ reviewer decides between them. Both go through the reader's scope and redaction.
133
+
134
+ **The published level and the withheld level differ.** `visibility.levels` is what was agreed, with a column's own
135
+ level winning over its type's. `visibility.above` is for a host deciding what must not leave it: the strongest of
136
+ every live claim counts, so a proposal protects before anyone has reviewed it.
137
+
138
+ **Taking away is append-only too.** `withdraw` is not a delete: it retracts what is held and rejects what someone
139
+ else proposed, in one transaction, and asks the policy per fact like any other decision.
140
+
122
141
  ## Embedding vs service
123
142
 
124
143
  Both modes use the same `Gloss` object:
@@ -150,4 +169,5 @@ only ever touches tables prefixed `gloss_`.
150
169
  - The first sync of a very large catalog is about a minute (≈55 s for 10k tables on SQLite).
151
170
  - On Postgres appends are serialised by an advisory lock (so sequence order is commit order). That is
152
171
  one writer at a time per database, which is plenty for metadata and would not be for telemetry.
153
- - Structured metric attributes are stored and exported; compiling them into queries is left to the host.
172
+ - A metric query reads one metric of one table; namespace metrics (no table) are not compiled. Expressions are
173
+ tokenized, not parsed, to find `table.column` chains.
@@ -4,7 +4,7 @@ build-backend = "hatchling.build"
4
4
 
5
5
  [project]
6
6
  name = "glosslayer"
7
- version = "0.1.0"
7
+ version = "0.2.0"
8
8
  description = "A catalog-agnostic semantic layer: track, review, visualize and serve Apache Ossie semantic models."
9
9
  readme = "README.md"
10
10
  license = "Apache-2.0"
@@ -30,7 +30,7 @@ from .seams import AssetSchema, Catalog, Coverage, Sink, Source
30
30
  from .semantic import TypeSuggester
31
31
  from .store import ConcurrentWrite, Query, SQLStore, Store
32
32
 
33
- __version__ = "0.1.0"
33
+ __version__ = "0.2.0"
34
34
 
35
35
  __all__ = [
36
36
  "AI",
@@ -0,0 +1,74 @@
1
+ """The SQL text Gloss writes for a host to run, and how the host hands back the answer.
2
+
3
+ Gloss never connects to a warehouse. Code that measures data (``glosslayer.joins``, ``glosslayer.rules``) or
4
+ dry-runs a metric (``glosslayer.query``) is given ``execute``: a callable that runs one statement where the data
5
+ lives and returns its rows in select-list order, as any DB-API ``fetchall()`` does.
6
+
7
+ def execute(sql):
8
+ return duckdb_connection.execute(sql).fetchall()
9
+
10
+ ``execute`` raises :class:`QueryFailed` when the engine refused that one statement and :class:`EngineUnavailable`
11
+ when there is no engine to ask. Callers treat them differently: a failed statement is about one table, while an
12
+ unavailable engine means every further statement would fail too.
13
+
14
+ Dialects are named as in ``glosslayer.checks.to_sql``: ``ansi`` (the default), ``postgres``, ``duckdb``,
15
+ ``snowflake`` and ``bigquery``.
16
+ """
17
+
18
+ from __future__ import annotations
19
+
20
+ import math
21
+ from collections.abc import Callable, Sequence
22
+ from typing import Any
23
+
24
+ Execute = Callable[[str], Sequence[Sequence[Any]]]
25
+ DIALECTS = frozenset({"ansi", "postgres", "duckdb", "snowflake", "bigquery"})
26
+
27
+
28
+ class QueryFailed(Exception):
29
+ """The engine refused or failed one statement; the message is its reason."""
30
+
31
+
32
+ class EngineUnavailable(Exception):
33
+ """There is no engine to run statements on; the next one would fail the same way."""
34
+
35
+
36
+ def _known(dialect: str) -> str:
37
+ if dialect not in DIALECTS:
38
+ raise ValueError(f"Unknown SQL dialect {dialect!r} (use one of {sorted(DIALECTS)})")
39
+ return dialect
40
+
41
+
42
+ def quote_char(dialect: str = "ansi") -> str:
43
+ """The character that quotes an identifier: a backtick for BigQuery, a double quote elsewhere."""
44
+ return "`" if _known(dialect) == "bigquery" else '"'
45
+
46
+
47
+ def quote(name: str, dialect: str = "ansi") -> str:
48
+ """``name`` as one quoted identifier, embedded quote characters doubled; always quoted, whatever it holds."""
49
+ q = quote_char(dialect)
50
+ return q + str(name).replace(q, q + q) + q
51
+
52
+
53
+ def literal(value: Any) -> str:
54
+ """A JSON value (or a list of them, as a parenthesised list) as a SQL literal."""
55
+ if value is None:
56
+ return "NULL"
57
+ if isinstance(value, bool):
58
+ return "TRUE" if value else "FALSE"
59
+ if isinstance(value, int | float):
60
+ if isinstance(value, float) and not math.isfinite(value):
61
+ raise ValueError(f"{value!r} is not a number a filter can compare with")
62
+ return repr(value)
63
+ if isinstance(value, str):
64
+ return "'" + value.replace("'", "''") + "'"
65
+ if isinstance(value, list):
66
+ return "(" + ", ".join(literal(v) for v in value) + ")"
67
+ raise ValueError(f"A filter value must be text, a number, a boolean, a date or a list, not {type(value).__name__}")
68
+
69
+
70
+ def date_trunc(grain: str, expression: str, dialect: str = "ansi") -> str:
71
+ """``expression`` truncated to ``grain`` (``day``, ``week``, ``month``, ``quarter`` or ``year``)."""
72
+ if _known(dialect) == "bigquery":
73
+ return f"DATE_TRUNC({expression}, {grain.upper()})"
74
+ return f"DATE_TRUNC({literal(grain)}, {expression})"