ostrict 0.3.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,436 @@
1
+ """Deterministic compiler: structured request -> one SQL statement, via sqlglot ASTs.
2
+
3
+ Pipeline (per request):
4
+ 1. SV-R10.7: at least one metric; resolve names (synonyms, ``__grain`` suffixes)
5
+ 2. expand derived metrics; group base metrics by their home table
6
+ 3. SV-R3.4: every dimension and filter must be reachable from EVERY home table
7
+ along child->parent paths (otherwise the join would fan out — refused)
8
+ 4. one aggregate subquery per home table (joins sorted by path length then name,
9
+ so the emitted SQL is byte-for-byte identical across runs)
10
+ 5. several home tables: drill across via UNION ALL + GROUP BY + MAX — metrics of
11
+ different grains combine without double counting (NULL dimension values group
12
+ correctly, which outer joins would not do)
13
+ 6. outer SELECT: derived metrics (safe division), metric filters, ORDER BY, LIMIT
14
+ """
15
+
16
+ from __future__ import annotations
17
+
18
+ import re
19
+
20
+ import sqlglot
21
+ from sqlglot import exp
22
+
23
+ from ..models.ast import Dimension, Metric, SemanticView
24
+ from ..models.errors import (
25
+ ERR_FANOUT_JOIN_FORBIDDEN,
26
+ ERR_INVALID_FILTER,
27
+ ERR_UNKNOWN_FIELD,
28
+ ERR_UNKNOWN_TABLE,
29
+ CompilerError,
30
+ )
31
+ from ..models.query import FILTER_OPS, CompiledQuery, Filter, SemanticQueryRequest
32
+ from .guardrails import (
33
+ CompileConfig,
34
+ partition_predicates,
35
+ require_metrics,
36
+ resolve_limit,
37
+ snapshot_binding,
38
+ )
39
+ from .resolver import Graph, build_graph
40
+
41
+ _OPS = {
42
+ "=": exp.EQ,
43
+ "!=": exp.NEQ,
44
+ "<>": exp.NEQ,
45
+ ">": exp.GT,
46
+ ">=": exp.GTE,
47
+ "<": exp.LT,
48
+ "<=": exp.LTE,
49
+ }
50
+ _SELECT_SOURCE = re.compile(r"^\s*(select|with)\b", re.I)
51
+
52
+
53
+ # --------------------------------------------------------------------------- expressions
54
+
55
+
56
+ def _replace(root: exp.Expression, node: exp.Expression, new: exp.Expression) -> exp.Expression:
57
+ if node is root:
58
+ return new
59
+ node.replace(new)
60
+ return root
61
+
62
+
63
+ def resolve_expr(
64
+ view: SemanticView, expr_sql: str, home: str, _stack: tuple[str, ...] = ()
65
+ ) -> tuple[exp.Expression, set[str]]:
66
+ """Qualify every column with its logical table alias and inline same-table facts.
67
+
68
+ Bare columns belong to ``home``; ``other_table.column`` reaches an ancestor
69
+ (reachability is checked by the caller). Returns (tree, logical tables used).
70
+ """
71
+ tree = view.parse_expr(expr_sql)
72
+ tables = {home}
73
+ for col in list(tree.find_all(exp.Column)):
74
+ owner = col.table or home
75
+ if owner not in view.tables:
76
+ raise CompilerError(
77
+ ERR_UNKNOWN_TABLE, f"expression '{expr_sql}' references unknown table '{owner}'"
78
+ )
79
+ key = f"{owner}.{col.name}"
80
+ fact = next((f for f in view.facts if f.table == owner and f.name == col.name), None)
81
+ if fact is not None and key not in _stack:
82
+ sub, used = resolve_expr(view, fact.expr, owner, (*_stack, key))
83
+ tables |= used
84
+ atomic = col is tree or isinstance(sub, (exp.Column, exp.Literal, exp.Paren))
85
+ tree = _replace(tree, col, sub if atomic else exp.Paren(this=sub))
86
+ continue
87
+ tables.add(owner)
88
+ tree = _replace(tree, col, exp.column(col.this.copy(), table=owner))
89
+ return tree, tables
90
+
91
+
92
+ def _dim_expr(view: SemanticView, dim: Dimension, grain: str | None) -> tuple[exp.Expression, set[str]]:
93
+ tree, tables = resolve_expr(view, dim.expr, dim.table)
94
+ if grain:
95
+ cls = exp.DateTrunc if dim.time_type == "date" else exp.TimestampTrunc
96
+ tree = cls(this=tree, unit=exp.var(grain.upper()))
97
+ return tree, tables
98
+
99
+
100
+ def _condition(tree: exp.Expression, flt: Filter) -> exp.Expression:
101
+ op, v = flt.op.lower(), flt.value
102
+ if op not in FILTER_OPS:
103
+ raise CompilerError(
104
+ ERR_INVALID_FILTER, f"filter on '{flt.field}': unknown op '{flt.op}'", hint=f"use one of {FILTER_OPS}"
105
+ )
106
+ if op in _OPS:
107
+ if v is None:
108
+ raise CompilerError(ERR_INVALID_FILTER, f"filter on '{flt.field}' with '{op}' needs a value (use 'is null')")
109
+ return _OPS[op](this=tree, expression=exp.convert(v))
110
+ if op in ("in", "not in"):
111
+ if not isinstance(v, (list, tuple)) or not v:
112
+ raise CompilerError(ERR_INVALID_FILTER, f"filter on '{flt.field}' with '{op}' needs a non-empty list")
113
+ cond: exp.Expression = exp.In(this=tree, expressions=[exp.convert(x) for x in v])
114
+ return exp.Not(this=cond) if op == "not in" else cond
115
+ if op == "between":
116
+ if not isinstance(v, (list, tuple)) or len(v) != 2:
117
+ raise CompilerError(ERR_INVALID_FILTER, f"filter on '{flt.field}' with 'between' needs [low, high]")
118
+ return exp.Between(this=tree, low=exp.convert(v[0]), high=exp.convert(v[1]))
119
+ if op in ("like", "not like"):
120
+ cond = exp.Like(this=tree, expression=exp.convert(str(v)))
121
+ return exp.Not(this=cond) if op == "not like" else cond
122
+ cond = exp.Is(this=tree, expression=exp.null())
123
+ return exp.Not(this=cond) if op == "is not null" else cond
124
+
125
+
126
+ def _safe_metric_expr(view: SemanticView, metric: Metric) -> exp.Expression:
127
+ """A requested metric in terms of subquery ``q``'s columns; '/' becomes NULL-safe."""
128
+ if not metric.is_derived:
129
+ return exp.column(metric.name, table="q")
130
+ tree = view.parse_expr(metric.expr)
131
+ for col in list(tree.find_all(exp.Column)):
132
+ sub = _safe_metric_expr(view, view.find_metric(col.name))
133
+ tree = _replace(tree, col, sub if isinstance(sub, exp.Column) else exp.Paren(this=sub))
134
+ for div in list(tree.find_all(exp.Div)):
135
+ tree = _replace(
136
+ tree,
137
+ div,
138
+ exp.Div(
139
+ this=exp.Cast(this=div.this.copy(), to=exp.DataType.build("double")),
140
+ expression=exp.Nullif(this=div.expression.copy(), expression=exp.Literal.number(0)),
141
+ ),
142
+ )
143
+ return tree
144
+
145
+
146
+ # --------------------------------------------------------------------------- sources & joins
147
+
148
+
149
+ def _source(view: SemanticView, table: str, partition_preds: list[exp.Expression]) -> exp.Expression:
150
+ """The table as it appears in FROM/JOIN, aliased by its logical name. Partition
151
+ bounds go inside a derived table — the only placement engines like BigQuery
152
+ honor for required partition filters on joined tables."""
153
+ t = view.tables[table]
154
+ if _SELECT_SOURCE.match(t.source):
155
+ base: exp.Expression = sqlglot.parse_one(t.source, read=view.dialect).subquery(table)
156
+ else:
157
+ base = exp.to_table(t.source, dialect=view.dialect)
158
+ base.set("alias", exp.TableAlias(this=exp.to_identifier(table)))
159
+ if not partition_preds:
160
+ return base
161
+ return exp.select(exp.Star()).from_(base).where(exp.and_(*partition_preds)).subquery(table)
162
+
163
+
164
+ def _guard_reach(
165
+ view: SemanticView, graph: Graph, home: str, used: set[str], what: str, metrics: list[Metric]
166
+ ) -> None:
167
+ bad = sorted(t for t in used if t != home and t not in graph.reach[home])
168
+ if bad:
169
+ names = ", ".join(m.name for m in metrics) or f"table '{home}'"
170
+ raise CompilerError(
171
+ ERR_FANOUT_JOIN_FORBIDDEN,
172
+ f"{what} lives on '{bad[0]}', which is not an ancestor of '{home}' (base table of {names}); "
173
+ "joining downward or across would duplicate rows",
174
+ hint="query that dimension with metrics based on its own table, or drop it",
175
+ )
176
+
177
+
178
+ # --------------------------------------------------------------------------- aggregates
179
+
180
+
181
+ def _aggregate(view, graph, home, metrics, dims, dim_filters, config):
182
+ """One aggregate SELECT at `home`'s grain. dims: [(Dimension, grain, alias)];
183
+ dim_filters: [(Dimension, grain, Filter)]. Returns (select, used tables, join names)."""
184
+ tables: set[str] = {home}
185
+ projections: list[exp.Expression] = []
186
+ group_keys: list[exp.Expression] = []
187
+
188
+ for dim, grain, alias in dims:
189
+ tree, used = _dim_expr(view, dim, grain)
190
+ _guard_reach(view, graph, home, used, f"dimension '{dim.name}'", metrics)
191
+ tables |= used
192
+ projections.append(exp.alias_(tree, alias))
193
+ group_keys.append(tree.copy())
194
+
195
+ for m in metrics:
196
+ tree, used = resolve_expr(view, m.expr, home)
197
+ _guard_reach(view, graph, home, used, f"metric '{m.name}'", metrics)
198
+ tables |= used
199
+ projections.append(exp.alias_(tree, m.name))
200
+
201
+ conditions: list[exp.Expression] = []
202
+ for dim, grain, flt in dim_filters:
203
+ tree, used = _dim_expr(view, dim, grain)
204
+ _guard_reach(view, graph, home, used, f"filter on '{dim.name}'", metrics)
205
+ tables |= used
206
+ conditions.append(_condition(tree, flt))
207
+
208
+ # always-on table filters apply to every involved table (and may pull in ancestors),
209
+ # so a metric's population never depends on which dimensions were requested
210
+ queue = sorted(tables)
211
+ seen_filters: set[str] = set()
212
+ while queue:
213
+ t = queue.pop(0)
214
+ if t in seen_filters:
215
+ continue
216
+ seen_filters.add(t)
217
+ tf = view.tables[t].filter
218
+ if tf:
219
+ tree, used = resolve_expr(view, tf, t)
220
+ _guard_reach(view, graph, home, used, f"table filter on '{t}'", metrics)
221
+ new = sorted(used - tables)
222
+ tables |= used
223
+ queue += new
224
+ conditions.append(tree)
225
+
226
+ # FinOps: partition requirements for every involved table
227
+ preds_by_table = {t: partition_predicates(view, view.tables[t], dim_filters, config) for t in sorted(tables)}
228
+
229
+ sel = exp.select(*projections).from_(_source(view, home, preds_by_table[home]))
230
+ joined: list[str] = []
231
+ seen: set[str] = {home}
232
+ for t in sorted(tables - {home}, key=lambda t: (len(graph.reach[home][t]), t)):
233
+ for rel in graph.reach[home][t]:
234
+ if rel.parent in seen:
235
+ continue
236
+ seen.add(rel.parent)
237
+ on = exp.and_(
238
+ *[
239
+ exp.EQ(
240
+ this=exp.column(fk, table=rel.child),
241
+ expression=exp.column(pk, table=rel.parent),
242
+ )
243
+ for fk, pk in zip(rel.child_columns, rel.parent_columns, strict=True)
244
+ ]
245
+ )
246
+ sel = sel.join(_source(view, rel.parent, preds_by_table[rel.parent]), on=on, join_type="left")
247
+ joined.append(rel.name)
248
+ for c in conditions:
249
+ sel = sel.where(c)
250
+ if group_keys:
251
+ sel = sel.group_by(*group_keys)
252
+ return sel, tables, joined
253
+
254
+
255
+ # --------------------------------------------------------------------------- entry point
256
+
257
+
258
+ def build_query(
259
+ view: SemanticView, request: SemanticQueryRequest, dialect: str, config: CompileConfig
260
+ ) -> CompiledQuery:
261
+ graph = build_graph(view)
262
+ require_metrics(request.metrics)
263
+
264
+ metrics: list[Metric] = []
265
+ for ref in request.metrics:
266
+ m = view.find_metric(ref)
267
+ if m not in metrics:
268
+ metrics.append(m)
269
+
270
+ dims: list[tuple[Dimension, str | None, str]] = []
271
+ for ref in request.dimensions:
272
+ dim, grain = view.find_dimension(ref)
273
+ alias = f"{dim.name}__{grain}" if grain else dim.name
274
+ if not any(a == alias for _, _, a in dims):
275
+ dims.append((dim, grain, alias))
276
+
277
+ dim_filters: list[tuple[Dimension, str | None, Filter]] = []
278
+ metric_filters: list[tuple[Metric, Filter]] = []
279
+ for flt in request.filters:
280
+ if flt.op.lower() not in FILTER_OPS:
281
+ raise CompilerError(
282
+ ERR_INVALID_FILTER, f"filter on '{flt.field}': unknown op '{flt.op}'", hint=f"use one of {FILTER_OPS}"
283
+ )
284
+ try:
285
+ dim, grain = view.find_dimension(flt.field)
286
+ dim_filters.append((dim, grain, flt))
287
+ except CompilerError:
288
+ try:
289
+ metric_filters.append((view.find_metric(flt.field), flt))
290
+ except CompilerError:
291
+ raise CompilerError(
292
+ ERR_UNKNOWN_FIELD,
293
+ f"filter field '{flt.field}' is neither a dimension nor a metric of '{view.name}'",
294
+ ) from None
295
+
296
+ base: list[Metric] = []
297
+ for m in [*metrics, *(m for m, _ in metric_filters)]:
298
+ for b in view.base_metrics(m):
299
+ if b not in base:
300
+ base.append(b)
301
+
302
+ homes: dict[str, list[Metric]] = {}
303
+ for b in base:
304
+ homes.setdefault(b.table, []).append(b)
305
+
306
+ # SV-R7: snapshot bindings checked per home table
307
+ for home in homes:
308
+ t = view.tables[home]
309
+ if t.snapshot:
310
+ snapshot_binding(view, t, [(d, g) for d, g, _ in dims], dim_filters)
311
+
312
+ selects: list[tuple[exp.Select, list[Metric]]] = []
313
+ used_tables: set[str] = set()
314
+ join_paths: dict[str, list[str]] = {}
315
+ for home, ms in homes.items():
316
+ sel, used, joined = _aggregate(view, graph, home, ms, dims, dim_filters, config)
317
+ selects.append((sel, ms))
318
+ used_tables |= used
319
+ join_paths[home] = joined
320
+
321
+ dim_cols = [exp.column(alias) for _, _, alias in dims]
322
+ if len(selects) == 1:
323
+ core: exp.Select = selects[0][0]
324
+ else:
325
+ branches = []
326
+ for i, (sel, ms) in enumerate(selects):
327
+ own = {m.name for m in ms}
328
+ cols = [*dim_cols] + [
329
+ exp.column(b.name) if b.name in own else exp.alias_(exp.null(), b.name) for b in base
330
+ ]
331
+ branches.append(exp.select(*[c.copy() for c in cols]).from_(sel.subquery(f"g{i}")))
332
+ union: exp.Expression = branches[0]
333
+ for br in branches[1:]:
334
+ union = exp.union(union, br, distinct=False)
335
+ core = exp.select(
336
+ *[c.copy() for c in dim_cols],
337
+ *[exp.alias_(exp.Max(this=exp.column(b.name)), b.name) for b in base],
338
+ ).from_(union.subquery("u"))
339
+ if dim_cols:
340
+ core = core.group_by(*[c.copy() for c in dim_cols])
341
+
342
+ outer = exp.select(*[exp.column(alias, table="q") for _, _, alias in dims]).from_(core.subquery("q"))
343
+ for m in metrics:
344
+ outer = outer.select(exp.alias_(_safe_metric_expr(view, m), m.name), append=True)
345
+ for m, flt in metric_filters:
346
+ outer = outer.where(_condition(_safe_metric_expr(view, m), flt))
347
+
348
+ columns = [alias for _, _, alias in dims] + [m.name for m in metrics]
349
+ for item in request.order_by:
350
+ desc = item.startswith("-")
351
+ name = item.lstrip("+-")
352
+ if name not in columns:
353
+ raise CompilerError(
354
+ ERR_UNKNOWN_FIELD, f"order_by '{name}' must be one of the requested columns: {', '.join(columns)}"
355
+ )
356
+ outer = outer.order_by(exp.Ordered(this=exp.column(name), desc=desc, nulls_first=False))
357
+ outer = outer.limit(resolve_limit(request.limit, config))
358
+
359
+ return CompiledQuery(
360
+ sql=outer.sql(dialect=dialect or None, pretty=True),
361
+ dialect=dialect or "",
362
+ columns=columns,
363
+ tables=sorted(used_tables),
364
+ join_paths=dict(sorted(join_paths.items())),
365
+ )
366
+
367
+
368
+ def build_dimension_values_query(
369
+ view: SemanticView,
370
+ dimension: str,
371
+ search: str | None,
372
+ filters: list[Filter],
373
+ limit: int,
374
+ dialect: str,
375
+ config: CompileConfig,
376
+ ) -> CompiledQuery:
377
+ """SELECT DISTINCT <dim> — the sanctioned, bounded escape hatch from SV-R10.7."""
378
+ graph = build_graph(view)
379
+ dim, grain = view.find_dimension(dimension)
380
+ home = dim.table
381
+
382
+ dim_filters: list[tuple[Dimension, str | None, Filter]] = []
383
+ for flt in filters:
384
+ d, g = view.find_dimension(flt.field)
385
+ dim_filters.append((d, g, flt))
386
+
387
+ tree, tables = _dim_expr(view, dim, grain)
388
+ _guard_reach(view, graph, home, tables, f"dimension '{dim.name}'", [])
389
+ conditions: list[exp.Expression] = []
390
+ for d, g, flt in dim_filters:
391
+ ftree, used = _dim_expr(view, d, g)
392
+ _guard_reach(view, graph, home, used, f"filter on '{d.name}'", [])
393
+ tables |= used
394
+ conditions.append(_condition(ftree, flt))
395
+ for t in sorted(tables):
396
+ tf = view.tables[t].filter
397
+ if tf:
398
+ ftree, used = resolve_expr(view, tf, t)
399
+ tables |= used
400
+ conditions.append(ftree)
401
+ if search:
402
+ needle = search.lower().replace("%", "").replace("_", " ")
403
+ conditions.append(
404
+ exp.Like(
405
+ this=exp.Lower(this=exp.Cast(this=tree.copy(), to=exp.DataType.build("text"))),
406
+ expression=exp.convert(f"%{needle}%"),
407
+ )
408
+ )
409
+
410
+ preds_by_table = {t: partition_predicates(view, view.tables[t], dim_filters, config) for t in sorted(tables)}
411
+ sel = exp.select(exp.alias_(tree, "value")).distinct().from_(_source(view, home, preds_by_table[home]))
412
+ seen = {home}
413
+ for t in sorted(tables - {home}, key=lambda t: (len(graph.reach[home][t]), t)):
414
+ for rel in graph.reach[home][t]:
415
+ if rel.parent in seen:
416
+ continue
417
+ seen.add(rel.parent)
418
+ on = exp.and_(
419
+ *[
420
+ exp.EQ(this=exp.column(fk, table=rel.child), expression=exp.column(pk, table=rel.parent))
421
+ for fk, pk in zip(rel.child_columns, rel.parent_columns, strict=True)
422
+ ]
423
+ )
424
+ sel = sel.join(_source(view, rel.parent, preds_by_table[rel.parent]), on=on, join_type="left")
425
+ for c in conditions:
426
+ sel = sel.where(c)
427
+ sel = sel.order_by(exp.Ordered(this=exp.column("value"), desc=False, nulls_first=False))
428
+ sel = sel.limit(max(1, min(limit, 50)))
429
+
430
+ return CompiledQuery(
431
+ sql=sel.sql(dialect=dialect or None, pretty=True),
432
+ dialect=dialect or "",
433
+ columns=["value"],
434
+ tables=sorted(tables),
435
+ join_paths={home: list(dict.fromkeys(n for t in sorted(tables) if t != home for n in graph.path_names(home, t)))},
436
+ )
@@ -0,0 +1,29 @@
1
+ """Warehouse connectors and the config-file factory."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from pathlib import Path
6
+
7
+ from .base import WarehouseConnector
8
+
9
+ __all__ = ["WarehouseConnector", "from_config"]
10
+
11
+
12
+ def from_config(cfg: dict, base_dir: str | Path = ".") -> WarehouseConnector:
13
+ kind = (cfg or {}).get("type")
14
+ if kind == "duckdb":
15
+ from .duckdb import DuckDBConnector
16
+
17
+ seed = cfg.get("seed")
18
+ seed_sql = (Path(base_dir) / seed).read_text() if seed else None
19
+ return DuckDBConnector(database=cfg.get("database", ":memory:"), seed_sql=seed_sql)
20
+ if kind == "bigquery":
21
+ from .bigquery import BigQueryConnector
22
+
23
+ return BigQueryConnector(
24
+ project=cfg["project"],
25
+ credentials=cfg.get("credentials"),
26
+ max_bytes=cfg.get("max_bytes"),
27
+ location=cfg.get("location"),
28
+ )
29
+ raise ValueError(f"unknown connector type '{kind}' (duckdb | bigquery)")
@@ -0,0 +1,16 @@
1
+ """Warehouse connector protocol — the only database-specific surface."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import Any, Protocol, runtime_checkable
6
+
7
+
8
+ @runtime_checkable
9
+ class WarehouseConnector(Protocol):
10
+ dialect: str
11
+
12
+ def execute(self, sql: str, max_rows: int | None = None) -> list[dict[str, Any]]: ...
13
+
14
+ def estimate_bytes(self, sql: str) -> int | None:
15
+ """Bytes the query would scan, or None when the engine cannot tell."""
16
+ ...
@@ -0,0 +1,53 @@
1
+ """BigQuery connector: dry-run byte estimation and a hard maximum_bytes_billed cap.
2
+
3
+ Lesson baked in from production use: BigQuery only honors required partition
4
+ filters on *joined* tables when they sit inside the table's own subquery — the
5
+ compiler does that; this connector adds the cost ceiling on top.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ from typing import Any
11
+
12
+ from ..models.errors import ERR_COST_LIMIT, CompilerError
13
+
14
+
15
+ class BigQueryConnector:
16
+ dialect = "bigquery"
17
+
18
+ def __init__(
19
+ self,
20
+ project: str,
21
+ credentials: str | None = None,
22
+ max_bytes: int | None = None,
23
+ location: str | None = None,
24
+ labels: dict[str, str] | None = None,
25
+ ):
26
+ from google.cloud import bigquery
27
+
28
+ self._bq = bigquery
29
+ self.client = (
30
+ bigquery.Client.from_service_account_json(credentials, project=project)
31
+ if credentials
32
+ else bigquery.Client(project=project)
33
+ )
34
+ self.max_bytes = max_bytes
35
+ self.location = location
36
+ self.labels = labels or {"tool": "ostrict"}
37
+
38
+ def estimate_bytes(self, sql: str) -> int | None:
39
+ cfg = self._bq.QueryJobConfig(dry_run=True, use_query_cache=False)
40
+ return self.client.query(sql, job_config=cfg, location=self.location).total_bytes_processed
41
+
42
+ def execute(self, sql: str, max_rows: int | None = None) -> list[dict[str, Any]]:
43
+ if self.max_bytes is not None:
44
+ est = self.estimate_bytes(sql)
45
+ if est is not None and est > self.max_bytes:
46
+ raise CompilerError(
47
+ ERR_COST_LIMIT,
48
+ f"query would scan {est / 1e9:,.1f} GB, over the {self.max_bytes / 1e9:,.1f} GB limit",
49
+ hint="narrow the date range or drop dimensions",
50
+ )
51
+ cfg = self._bq.QueryJobConfig(maximum_bytes_billed=self.max_bytes, labels=self.labels)
52
+ rows = self.client.query(sql, job_config=cfg, location=self.location).result(max_results=max_rows)
53
+ return [dict(r.items()) for r in rows]
@@ -0,0 +1,25 @@
1
+ """DuckDB connector: local zero-cost testing and the eval runner's fixture engine."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import Any
6
+
7
+
8
+ class DuckDBConnector:
9
+ dialect = "duckdb"
10
+
11
+ def __init__(self, database: str = ":memory:", seed_sql: str | None = None, connection=None):
12
+ import duckdb
13
+
14
+ self.con = connection or duckdb.connect(database)
15
+ if seed_sql:
16
+ self.con.execute(seed_sql)
17
+
18
+ def execute(self, sql: str, max_rows: int | None = None) -> list[dict[str, Any]]:
19
+ cur = self.con.execute(sql)
20
+ cols = [d[0] for d in cur.description]
21
+ rows = cur.fetchmany(max_rows) if max_rows else cur.fetchall()
22
+ return [dict(zip(cols, r, strict=True)) for r in rows]
23
+
24
+ def estimate_bytes(self, sql: str) -> int | None:
25
+ return None
File without changes
ostrict/eval/runner.py ADDED
@@ -0,0 +1,120 @@
1
+ """Golden Questions eval runner (SV-R10.2): deterministic grading, no LLM judge.
2
+
3
+ A cases file pins the semantic view, an optional DuckDB seed, and a list of
4
+ cases. `answer` cases compile, execute and compare rows exactly (order-free,
5
+ numbers as floats, dates as ISO strings); `refuse` and `clarify` cases expect a
6
+ specific error code (clarify marks requests an agent should repair, e.g. a typo
7
+ with suggestions).
8
+
9
+ view: ./ecommerce.sql
10
+ seed: ./seed_ecommerce.sql
11
+ cases:
12
+ - id: totals_january
13
+ family: revenue
14
+ kind: answer # answer | refuse | clarify
15
+ question: "What was total revenue in January 2026?"
16
+ request: { metrics: [revenue], filters: [...] }
17
+ expect:
18
+ rows: [{ revenue: 94.0 }]
19
+ - id: fanout
20
+ kind: refuse
21
+ request: { metrics: [customer_count], dimensions: [channel] }
22
+ expect: { error: ERR_FANOUT_JOIN_FORBIDDEN, message_contains: ancestor }
23
+ """
24
+
25
+ from __future__ import annotations
26
+
27
+ import datetime as dt
28
+ import json
29
+ from dataclasses import dataclass, field
30
+ from decimal import Decimal
31
+ from pathlib import Path
32
+
33
+ import yaml
34
+
35
+ from ..compiler import compile_semantic_query, execute_semantic_query
36
+ from ..connectors.duckdb import DuckDBConnector
37
+ from ..models.errors import CompilerError
38
+ from ..parsers import load_view
39
+
40
+
41
+ @dataclass
42
+ class CaseResult:
43
+ id: str
44
+ kind: str
45
+ passed: bool
46
+ detail: str = ""
47
+
48
+
49
+ @dataclass
50
+ class EvalReport:
51
+ results: list[CaseResult] = field(default_factory=list)
52
+
53
+ @property
54
+ def ok(self) -> bool:
55
+ return all(r.passed for r in self.results)
56
+
57
+ def render(self) -> str:
58
+ lines = [
59
+ f"{'PASS' if r.passed else 'FAIL'} {r.id} ({r.kind})" + (f": {r.detail}" if r.detail else "")
60
+ for r in self.results
61
+ ]
62
+ n = sum(r.passed for r in self.results)
63
+ return "\n".join([*lines, f"{n}/{len(self.results)} golden cases passed"])
64
+
65
+
66
+ def _norm(v):
67
+ if isinstance(v, Decimal):
68
+ return float(v)
69
+ if isinstance(v, dt.datetime):
70
+ # engines disagree on whether DATE_TRUNC returns a date or a midnight
71
+ # timestamp; expectations are written as plain dates
72
+ if v.tzinfo is None and v.time() == dt.time.min:
73
+ return v.date().isoformat()
74
+ return v.isoformat()
75
+ if isinstance(v, dt.date):
76
+ return v.isoformat()
77
+ return v
78
+
79
+
80
+ def _rowset(rows: list[dict]) -> list[str]:
81
+ return sorted(json.dumps({k: _norm(v) for k, v in r.items()}, sort_keys=True, default=str) for r in rows)
82
+
83
+
84
+ def run_eval(cases_path: str | Path, seed: str | None = None) -> EvalReport:
85
+ path = Path(cases_path)
86
+ spec = yaml.safe_load(path.read_text())
87
+ base = path.parent
88
+ view = load_view(base / spec["view"])
89
+ seed_path = Path(seed) if seed else (base / spec["seed"] if spec.get("seed") else None)
90
+ connector = DuckDBConnector(seed_sql=seed_path.read_text() if seed_path else None)
91
+
92
+ report = EvalReport()
93
+ for case in spec.get("cases", []):
94
+ cid, kind = str(case.get("id")), case.get("kind", "answer")
95
+ expect = case.get("expect") or {}
96
+ try:
97
+ if kind == "answer":
98
+ result = execute_semantic_query(view, case["request"], connector)
99
+ got, want = _rowset(result.rows), _rowset(expect.get("rows", []))
100
+ if got == want:
101
+ report.results.append(CaseResult(cid, kind, True))
102
+ else:
103
+ report.results.append(CaseResult(cid, kind, False, f"rows {got} != expected {want}"))
104
+ else: # refuse | clarify: the compiler must say no, with the exact code
105
+ try:
106
+ compile_semantic_query(view, case["request"], dialect=connector.dialect)
107
+ report.results.append(CaseResult(cid, kind, False, "compiled but a refusal was expected"))
108
+ except CompilerError as e:
109
+ want_code = expect.get("error")
110
+ needle = expect.get("message_contains", "")
111
+ said = f"{e} {e.hint}".lower()
112
+ if e.code == want_code and needle.lower() in said:
113
+ report.results.append(CaseResult(cid, kind, True))
114
+ else:
115
+ report.results.append(
116
+ CaseResult(cid, kind, False, f"got [{e.code}] {e}; expected [{want_code}] ~'{needle}'")
117
+ )
118
+ except Exception as e: # noqa: BLE001 - a crashing case is a failing case
119
+ report.results.append(CaseResult(cid, kind, False, f"{type(e).__name__}: {e}"))
120
+ return report