-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathruntime.py
More file actions
5799 lines (5113 loc) · 336 KB
/
Copy pathruntime.py
File metadata and controls
5799 lines (5113 loc) · 336 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""Runtime traversal for the agami semantic-model-v2 path.
Implements the design doc's "Traversal" + "Runtime walkthrough" primitives as
pure functions over a parsed `Datasource` model, so they're equally usable from
the MCP server (`mcp_server.py`) and the skill CLI, and fully unit-testable
without a live database. Anything that needs to touch the DB (entity probing) is
injected as a `probe` callable — the caller wires in a real prober; tests pass a
fake.
Primitives (examples-first canonical loop):
list_subject_areas — pick area by description / intent
get_prompt_examples — examples FIRST; short-circuit on high-confidence match
resolve_entities — lexical match query -> entities (cold-start)
resolve_metrics — lexical match query -> metrics (cold-start)
identify_entity — opaque-literal type ID via value_pattern + probe-confirm
resolve_entity_instance — strategy chosen at runtime from sensitive + cardinality
pre_flight_check — per aggregate, whether a join multiplies the rows behind it
assemble_receipt — the full trust receipt for a statement that ran
assemble_refusal_receipt — the echo-bounded receipt every non-ok outcome carries
Pre-flight scope note (documented decision, recorded in the PR description):
The cardinality field on every relationship is the day-1 structural gate. The detector
here is **deterministic, and complete over what it can resolve**: given an aggregate
whose source tables resolve and the model's declared relationships, it finds every fan
and every chasm among them, and finds the same ones on every run.
**Bare "complete" was too strong, and this is where that stopped being invisible.** An
aggregate naming no column (`COUNT(*)`), an unqualified column with two or more tables
in scope, and one reading a CTE or derived table the walk does not enter are all cases
where nothing establishes which rows the value was computed from. That was always so;
keyed per finding it surfaced as an ABSENCE, which says nothing, and keying per
aggregate would have turned the same absence into `not_multiplied` — a positive claim
that the number is clean. So those report `undetermined`, and the section's marker
counts them. The gap in the other direction is ACE-083's: `MIN` / `MAX` /
`COUNT(DISTINCT)` are still counted as fan-out risks although a fan-out cannot change
what they return.
There is no rewrite and no refusal. Every detected trap is reported as a fact about
the aggregate it inflated, on an answer that RAN. This module used to rewrite the
textbook aggregation-only fan-trap by dropping the redundant join, on the grounds
that the transform was provably result-preserving; the transform was, but the premise
was not. Whether a multiplied total is wrong depends on the question, which this layer
never sees: the same statement is wrong for order revenue and right for line-item
exposure. So the analysis stays, and both the authoring and the refusing go.
"""
from __future__ import annotations
import functools
import re
from dataclasses import dataclass, field
from difflib import SequenceMatcher
from typing import Any, Callable, NamedTuple, Optional
# Absolute, not relative: `guardrail` is a flat top-level module that sits ALONGSIDE the
# `semantic_model` package in both layouts — next to it in `packages/agami-core/src/`, and next to it
# again in site-packages (it is listed in the distribution's `py-modules`). A relative import would
# look for `semantic_model.guardrail`, which exists in neither.
import guardrail
try:
import sqlglot
from sqlglot import expressions as exp
from sqlglot.errors import ErrorLevel, ParseError, TokenError
_HAVE_SQLGLOT = True
except ImportError: # pragma: no cover
_HAVE_SQLGLOT = False
from .models import (
Column,
Datasource,
Entity,
Metric,
Relationship,
)
from .models import (
bare_name as _bare,
)
from .sql_dialect import DialectUnresolved, engines_disagree, resolve_datasource_dialect
def _exp_nodes(*names: str) -> tuple[type, ...]:
"""The `sqlglot.expressions` classes among `names` that THIS sqlglot declares.
Resolved by name rather than by attribute because the package pins only `sqlglot>=20` and not
every node type below exists across that whole range: `exp.Nvl2` and `exp.DecodeCase` are
later additions. A class this version does not declare is a shape this version cannot parse, so
leaving it out of the tuple changes no answer; a bare `exp.Nvl2` in a module-level tuple would
instead make the whole module unimportable against a sqlglot that reads every statement here
perfectly well.
"""
return tuple(t for t in (getattr(exp, name, None) for name in names) if isinstance(t, type))
# A prober resolves a literal/value against the DB. Returns True if the value
# exists in <table>.<column>. Injected so runtime stays DB-agnostic.
Prober = Callable[[str, str, str], bool]
# ---------------------------------------------------------------------------
# Per-invocation guard context (ACE-045)
#
# The _model_safety battery (execute_sql.py) runs ~6 guards that EACH re-parse the SQL
# (sqlglot ×6) and rebuild their model index from scratch. `GuardContext` does that
# shared work ONCE — the SQL parsed once, each index built once — and is threaded through
# the guards via an optional `ctx=`. A guard given `ctx` returns the SAME verdict as one
# that builds its own (behaviour-preserving); `ctx=None` keeps the standalone callers
# (e.g. cli.py) working unchanged. `tree` is None when the SQL doesn't parse — guards then
# degrade to allow, exactly as the inline parse-and-except did before. That degrade-to-allow
# is why `unreadable` exists below: the readability gate refuses such a statement before any
# gate reaches it, so no gate is ever asked to judge a tree that is missing.
# ---------------------------------------------------------------------------
@dataclass(frozen=True)
class GuardContext:
sql: str
tree: "exp.Expression | None"
column_index: "dict[str, dict[str, Column]]"
cardinality_index: "list[Relationship]"
sensitive_by_table: "tuple[dict[str, set[str]], set[str]]"
model_table_index: "dict[str, tuple]"
# The sqlglot dialect every parse in this battery uses, or None when the datasource does
# not determine one. `unreadable` is the value-free reason the statement could not be read
# — an unresolvable engine, or SQL that does not parse in the resolved one — carried
# alongside `tree` so a caller can tell "read it and found nothing to object to" apart from
# "could not read it", which are the same empty tree and opposite verdicts.
dialect: "str | None" = None
unreadable: "UnreadableStatement | None" = None
class UnreadableStatement(NamedTuple):
"""Why a statement could not be read, as (cause, value-free detail).
`cause` is one of the module-level `UNREADABLE_*` constants — a stable token the refusing
caller maps to a rule, so the mapping from cause to `guardrail.RULE_*` lives at the
chokepoint that owns refusals rather than being decided here. `detail` never carries
statement text, data values, or model names, so a caller may surface it verbatim.
"""
cause: str
detail: str
# An engine the datasource does not determine. Nothing about the statement is wrong, so this is
# the operator's to fix and no re-emission of the query helps.
UNREADABLE_ENGINE = "engine"
# The statement does not parse in the engine's own grammar. The caller can re-emit and retry.
UNREADABLE_PARSE = "parse"
# The statement parses two ways and the guard cannot tell which the server will pick. Also the
# caller's to fix, and trivially: re-emitting in the engine's own quoting is unambiguous.
UNREADABLE_AMBIGUOUS = "ambiguous"
# Engines whose identifier quote is the backtick, so a double-quoted token is a *string literal* in
# their default mode — but an *identifier* when the server runs in an ANSI-quoting mode (MySQL's
# ANSI_QUOTES, and the equivalent on the Spark-family engines). The parse cannot tell which, because
# sqlglot does not preserve the quote character: `"x"` and `'x'` both arrive as the same literal.
_BACKTICK_QUOTING_DIALECTS = frozenset({"mysql", "bigquery", "databricks", "spark", "hive"})
# A grammar in which a double-quoted token is unambiguously an identifier, used only to ask "would
# this read as a column somewhere else?".
_ANSI_QUOTING_DIALECT = "postgres"
def _quote_ambiguous(sql: str, dialect: "str | None", tree: "exp.Expression | None") -> bool:
"""True when a double-quoted token would be a column under ANSI quoting but reads as a string
literal in this engine's default mode.
Such a statement means two different things depending on a server setting the guard cannot see.
Under the engine's default mode the gates are right that no column is projected; if the server
runs in ANSI-quoting mode the same text selects the column and the gates will have scored a real
column as a literal — a hole this change would otherwise OPEN, since the generic parse it
replaces read `"x"` as an identifier and caught it. Rather than guess the server's mode the
statement is treated as unreadable: it is trivially re-emitted in the engine's own quoting,
which is unambiguous.
"""
if tree is None or dialect not in _BACKTICK_QUOTING_DIALECTS:
return False
# The second parse is the expensive part of this whole change, and it can only find something
# when the statement actually contains a double quote — the character whose meaning is in
# doubt. Without this test every statement on a backtick engine pays it: measured at 0.38 ms
# against 0.18 ms per guard context, on the hosted server's per-request path.
if '"' not in sql:
return False
ansi = _parse_sql(sql, _ANSI_QUOTING_DIALECT)
if ansi is None:
# No second opinion available: the statement parsed in its own grammar but uses something
# the ANSI-quoting grammar cannot read (MySQL's two-argument LIMIT, say). Reporting
# "ambiguous" here would refuse a statement on the strength of a comparison that never
# happened, so the native reading — the engine's own declared default — is what the gates
# judge. Deliberately the permissive branch, and narrow: the statement still has to pass
# every scope gate on that reading.
return False
native_cols = {c.name.lower() for c in tree.find_all(exp.Column)}
ansi_cols = {c.name.lower() for c in ansi.find_all(exp.Column)}
return bool(ansi_cols - native_cols)
def _dialect_of(org: "Datasource | None") -> "tuple[str | None, str | None]":
"""Resolve the sqlglot dialect for `org` as (dialect, reason-it-could-not-be-resolved)."""
if org is None:
return None, "the statement was checked without a model, so its engine is unknown"
try:
return resolve_datasource_dialect(org), None
except DialectUnresolved as exc:
return None, str(exc)
except Exception:
# Anything else raised while interrogating the model — a shape that does not carry
# storage connections at all — is still the same fact: the engine is undetermined. The
# sentence is fixed rather than the exception's own, because this reason can reach a
# refusal and an arbitrary exception string is not value-free.
return None, "the datasource's storage engine could not be determined"
def _parse_sql(sql: str, dialect: "str | None" = None) -> "exp.Expression | None":
"""Parse SQL for the guard battery; None if sqlglot is unavailable or the SQL does not
parse. Centralized so a GuardContext parses exactly once.
Callers that need to tell "did not parse" apart from "parsed to nothing" want
`_parse_reporting`; this form is for the standalone callers that only need the tree.
"""
return _parse_reporting(sql, dialect)[0]
def _parse_reporting(
sql: str, dialect: "str | None" = None
) -> "tuple[exp.Expression | None, str | None]":
"""Parse `sql` in `dialect`, returning (tree, value-free reason it failed).
Two choices here, both load-bearing for every gate that reads the result:
* **The dialect is passed through.** Parsing in a grammar the engine does not use does not
merely lose detail, it returns a tree describing a DIFFERENT statement — on a
backtick-quoting engine one with no tables and no columns — and a gate inspecting that
finds nothing to object to.
* **Errors raise instead of being collected and discarded.** The level must be the
`ErrorLevel` enum: sqlglot's `check_errors` compares it against enum members, so a
*string* level matches no branch and every collected error is dropped, leaving a silently
truncated tree. `error_level="ignore"` was therefore not a lenient setting, it was no
setting at all. `TokenError` is raised for lexical faults such as an unterminated literal
regardless of level, so both it and `ParseError` are caught.
"""
if not _HAVE_SQLGLOT:
return None, None
try:
return sqlglot.parse_one(sql, dialect=dialect, error_level=ErrorLevel.RAISE), None
except (ParseError, TokenError):
return None, "the statement could not be parsed as SQL for this datasource's engine"
except Exception:
return None, "the statement could not be read"
def _why_unreadable(
sql: str,
dialect: "str | None",
tree: "exp.Expression | None",
why_no_dialect: "str | None",
why_no_parse: "str | None",
) -> "UnreadableStatement | None":
"""Why this statement could not be read, in the order the causes outrank each other.
Called once per invocation — from `build_guard_context` when there is a context, and from the
standalone path otherwise — so the ambiguity probe's second parse happens at most once and the
battery's parse-exactly-once property holds where it is observable.
"""
if why_no_dialect is not None:
# An unresolvable engine outranks a parse failure: the parse was only attempted without a
# grammar BECAUSE there was no engine to read the statement in, so reporting the parse
# would describe a symptom and hide the cause.
return UnreadableStatement(UNREADABLE_ENGINE, why_no_dialect)
if why_no_parse is not None:
return UnreadableStatement(UNREADABLE_PARSE, why_no_parse)
if _quote_ambiguous(sql, dialect, tree):
return UnreadableStatement(
UNREADABLE_AMBIGUOUS,
"a double-quoted identifier means either a column or a string literal on this "
"datasource's engine, depending on server configuration the guard cannot see",
)
return None
def build_guard_context(sql: str, org: Datasource) -> "GuardContext | None":
"""Parse `sql` once and build each guard index once, so the _model_safety battery shares
them instead of every guard redoing the work (audit P2 / ACE-045). Returns None when sqlglot
is unavailable: every guard then short-circuits to allow before it touches the context, so
building the indices would be pure wasted work in that fallback path."""
if not _HAVE_SQLGLOT:
return None
dialect, why_no_dialect = _dialect_of(org)
tree, why_no_parse = _parse_reporting(sql, dialect)
unreadable = _why_unreadable(sql, dialect, tree, why_no_dialect, why_no_parse)
return GuardContext(
sql=sql,
tree=tree,
column_index=_column_index(org),
cardinality_index=_cardinality_index(org),
sensitive_by_table=_sensitive_by_table(org),
model_table_index=_model_table_index(org),
dialect=dialect,
unreadable=unreadable,
)
# A statement the caller can fix by rewriting. The move is named, but the declared names are NOT
# listed: `guardrail.Refusal` forbids enumerating the declared surface, because a refusal that lists
# the alternatives is a schema-listing endpoint reachable by one deliberately-wrong query.
_REEMIT_REMEDIATION = (
"Re-emit the query using the declared table and column names, unquoted or quoted the way this "
"datasource's engine quotes identifiers."
)
# A statement no rewrite can fix, because the fault is in the deployment. It deliberately does NOT
# end in "then retry": an unactionable invitation to try again turns a configuration fault into a
# retry loop, with the caller re-emitting a statement that was never the problem.
_DECLARE_ENGINE_REMEDIATION = (
"Declare the datasource's engine (storage_connections[].storage_type) so its SQL can be parsed "
"for the right engine."
)
_RULE_FOR_CAUSE = {
UNREADABLE_ENGINE: (guardrail.RULE_MODEL_UNAVAILABLE, _DECLARE_ENGINE_REMEDIATION),
UNREADABLE_PARSE: (guardrail.RULE_UNPARSEABLE, _REEMIT_REMEDIATION),
UNREADABLE_AMBIGUOUS: (guardrail.RULE_UNPARSEABLE, _REEMIT_REMEDIATION),
}
def check_readable(
sql: str, org: Datasource, ctx: "GuardContext | None" = None
) -> "guardrail.Refusal | None":
"""Refuse a statement the guard cannot read in the datasource's own grammar.
**The boundary, stated: this is a 4c gate**, like the star ban and unlike the two scope gates.
It never claims the statement reached outside the declared surface — it claims we could not
establish whether it did, which is what `undetermined` means. Every rule it produces pins to
that reason.
**It must run above every other gate, and that ordering is the whole point.** A gate handed no
tree degrades to allow (see `GuardContext`), so each situation below otherwise arrives at the
scope gates looking like a statement with nothing to object to. Not hypothetical: on a
backtick-quoting engine the generic parse returns no tables and no columns, so table scope,
column scope and the star ban all pass a statement reading any table in the database.
Four situations, three rules, and the split decides the remediation rather than each call site
hand-matching one:
* the engine is undetermined — unmapped, undeclared, or two connections disagreeing. The
statement is irrelevant; the operator declares the engine. `model_unavailable`.
* it did not parse in the resolved grammar. The caller re-emits. `unparseable`.
* it parses two ways depending on server configuration we cannot see. Also the caller's, and
trivially fixed by quoting it the engine's own way. `unparseable`.
* it parses, reads from something, and still resolves to no named table. Nothing for the scope
walk to accept or reject, which is what `unscopable` names. A backstop rather than a
diagnosis: it does not depend on the dialect map being complete, so a quoting style nobody has
mapped yet fails closed on its own.
"""
if not _HAVE_SQLGLOT:
# No parser is a different fact from an unreadable statement, and not this gate's to report:
# every other gate short-circuits to allow here, and the receipt already says so in its own
# words (UNDETERMINED_NO_PARSER).
return None
if ctx is not None:
tree, unreadable = ctx.tree, ctx.unreadable
else:
dialect, why_no_dialect = _dialect_of(org)
tree, why_no_parse = _parse_reporting(sql, dialect)
unreadable = _why_unreadable(sql, dialect, tree, why_no_dialect, why_no_parse)
if unreadable is not None:
rule, remediation = _RULE_FOR_CAUSE[unreadable.cause]
return guardrail.refuse(rule, detail=unreadable.detail, remediation=remediation)
if tree is None:
# Belt and braces: a None tree with no recorded cause should be unreachable, and if it ever
# happens the safe reading is the one that refuses rather than the one that lets every gate
# below judge a statement none of them can see.
return guardrail.refuse(
guardrail.RULE_UNPARSEABLE,
detail="the statement could not be read as SQL",
remediation=_REEMIT_REMEDIATION,
)
# A statement with no FROM (`SELECT 1`) reads nothing and is left alone; one that reads from
# something and names no table cannot be attributed to the declared surface at all.
if tree.find(exp.From) is not None and tree.find(exp.Table) is None:
return guardrail.refuse(
guardrail.RULE_UNSCOPABLE,
detail="the query reads from a source that resolves to no named table",
remediation=_REEMIT_REMEDIATION,
)
return None
# A statement whose sources the scope walk cannot reason about. The remediation names the shape that
# would scope and never the declared names, for the same reason every other refusal does not: a
# refusal that lists the alternatives is a schema-listing endpoint reachable by one wrong query.
_DECLARED_SOURCE_REMEDIATION = (
"Query declared tables directly — replace the table function, VALUES, UNNEST or LATERAL source "
"with a plain FROM/JOIN on a declared table, or add the source to the model if it should be "
"queryable."
)
def _unscopable(detail: str) -> "guardrail.Refusal":
return guardrail.refuse(
guardrail.RULE_UNSCOPABLE,
detail=detail,
remediation=_DECLARED_SOURCE_REMEDIATION,
)
def check_scopable(sql: str, org: Datasource,
ctx: "GuardContext | None" = None) -> "guardrail.Refusal | None":
"""Refuse a statement that parses perfectly and still presents a source the scope walk cannot
reason about.
**The boundary, stated: this is a 4c gate**, and it is the second half of a split the contract
makes on purpose. `unparseable` is a statement sqlglot cannot read at all and belongs to
`check_readable` above; `unscopable` is one that reads fine and offers the scope walk nothing to
accept or reject. Collapsing them would make the remediation a guess — "re-emit the query" is
useless advice to someone whose query parsed.
**Why the gate above does not already cover this.** `check_readable`'s backstop refuses a
statement that resolves to NO named table, which is the right shape for a quoting style nobody
has mapped. It is not the right shape here, twice over: a table function parses to an
`exp.Table` with an EMPTY name, so the backstop's `find(exp.Table) is None` sees a table and
passes; and one declared table leading a comma-join is enough to satisfy it while every source
after the comma goes unexamined. Measured on this tree, six such statements reached the database
with every gate silent.
**Why the scope gates do not catch it either.** `check_table_scope` skips an empty-name table by
design — that is how it lets a CTE reference through — so the same node it must ignore is the one
a table function arrives as. The gate cannot be taught the difference without breaking the case
it exists for, which is why this is a separate slice rather than a condition bolted onto it.
Refuses four shapes, each looked for anywhere in the tree so that every set-operation arm and
nested subquery is covered by the same walk:
* a table function or `ROWS FROM` — an `exp.Table` carrying a function rather than a name.
* a `LATERAL`, in both the Postgres `LATERAL (...)` and Hive `LATERAL VIEW` spellings.
* a `VALUES` list, which is not always a FROM/JOIN source: as a set-operation arm it hangs off
the `Union` instead, contributing rows while the source walk below cannot see it.
* `UNNEST`, or any other FROM/JOIN source that is neither an `exp.Table` nor a derived
`exp.Subquery` — including one reached through a comma-join, whose extra sources some sqlglot
versions hang off `From.expressions` rather than normalizing into a `Join`.
The first three are whole-tree `find`s rather than source-walk cases on purpose: each has at
least one spelling that is not a FROM/JOIN source, so a walk that only visited sources would
miss it while it still shaped the result.
Reuses `ctx.tree` and never parses a second time: a gate that re-parsed could disagree with the
tree every other gate judged, which is the divergence this whole family exists to prevent.
Inert when the model declares no tables, matching `check_table_scope` — a deployment with no
declared surface is not scoping anything. Returns `None` when satisfied.
"""
if not _HAVE_SQLGLOT:
return None
if not (ctx.model_table_index if ctx is not None else _model_table_index(org)):
return None
tree = ctx.tree if ctx is not None else _parse_sql(sql, _dialect_of(org)[0])
# An unparseable statement and a non-SELECT are both somebody else's refusal — `check_readable`
# above and the read-only guard respectively. Passing here says nothing about them.
if tree is None or tree.find(exp.Select) is None:
return None
# A table function and `ROWS FROM` parse to an `exp.Table` whose name is empty, the function
# sitting in `.this`. Checked first because it is the shape the two gates above each look
# straight through.
for tbl in tree.find_all(exp.Table):
if not tbl.name:
return _unscopable(
"a FROM/JOIN source is a table function rather than a named table, so there is "
"nothing to check against the declared surface"
)
# sqlglot attaches a LATERAL under the From/Join for Postgres' `LATERAL (...)` and as a Select
# property for Hive's `LATERAL VIEW`, so sweep the whole tree rather than the sources alone.
if tree.find(exp.Lateral) is not None:
return _unscopable(
"a FROM/JOIN source is a LATERAL rather than a named table, so there is nothing to "
"check against the declared surface"
)
# `VALUES` is swept whole-tree for the same reason, and the reason is not symmetry.
# A parenthesized `VALUES` used as a set-operation ARM — `SELECT id FROM orders UNION ALL
# (VALUES (1))` — is not a FROM/JOIN source at all: it hangs off the `Union` beside the select,
# so the source walk below never reaches it while it contributes rows to the result exactly as
# an arm reading a table would. Found by review, and it executed against a real engine with all
# three gates silent. A read-only SELECT over declared tables carries no `Values` node —
# `IN (1, 2, 3)` is an `exp.In` over expressions, not this — so the sweep costs no false refusal.
if tree.find(exp.Values) is not None:
return _unscopable(
"the query builds rows from a VALUES list rather than reading a named table, so there "
"is nothing to check against the declared surface"
)
# Every remaining non-`Table`, non-derived-subquery source. `From.expressions` carries the extra
# sources of a comma-join on the sqlglot versions that do not normalize them into a `Join`, so a
# declared table written first cannot shield what follows it.
for node in tree.find_all(exp.From, exp.Join):
for src in [node.this, *(node.args.get("expressions") or [])]:
if src is not None and not isinstance(src, (exp.Table, exp.Subquery)):
# The node's class name describes the SQL construct the caller wrote, not a value
# from it or a name from the model — value-free in the sense the contract means.
return _unscopable(
f"a FROM/JOIN source is a {type(src).__name__.upper()} rather than a named "
"table, so there is nothing to check against the declared surface"
)
return None
def statement_shape(ctx: "GuardContext | None") -> "str | None":
"""`"aggregate"` when the statement groups, `"listing"` otherwise, `None` when there is no
tree to read (sqlglot absent, or the SQL did not parse).
This exists so that `execute_sql` can word the result-bound refusal for the right shape
without importing sqlglot (ACE-087). It cannot live there: `execute_sql` ships in the
stdlib-only vendored mirror, which does not carry this module — the same reason
`sql_guard` is regex rather than a parse. So the classification happens here, where the
tree `build_guard_context` already parsed is in hand, and travels as a plain string.
`GROUP BY` anywhere in the tree is the whole predicate, and it is deliberately coarse.
`exp.Group` covers `GROUP BY`, `ROLLUP`, `CUBE` and `GROUPING SETS`, and looking anywhere
rather than at the outermost select means a set operation with one grouped arm reads as an
aggregate. That is the direction to be wrong in: the aggregate remediation never says
`LIMIT`, and telling a caller to `LIMIT` an aggregate hands them a partial breakdown that
reads as complete. A bare `COUNT(*)` returns one row and cannot reach the bound at all; a
window function returns one row per input row, which is a listing, and `LIMIT` is right
for it.
Being a pure function of the tree is what keeps principle 9 true of the refusal's wording:
the same statement against the same model produces the same remediation, every run.
"""
if ctx is None or ctx.tree is None:
return None
return "aggregate" if ctx.tree.find(exp.Group) is not None else "listing"
# Ambiguity threshold — "ask, don't guess" when top-two are within this delta.
AMBIGUITY_DELTA = 0.15
# Instance-resolution strategy thresholds.
CACHED_INDEX_MAX_CARDINALITY = 10_000
ENUM_MAX_CARDINALITY = 50
# ---------------------------------------------------------------------------
# Step 1 — subject areas
# ---------------------------------------------------------------------------
def list_subject_areas(org: Datasource) -> list[dict[str, Any]]:
"""Compact listing for area selection — also the one-call model map. The counts
tell a caller the whole shape of each area (and where things live: relationships
and entities/metrics are area-level, not per-table) without reading any YAML."""
return [
{
"name": sa.name,
"description": sa.description,
"table_count": len(sa.tables),
"entity_count": len(sa.entities),
"metric_count": len(sa.metrics),
"relationship_count": len(sa.relationships),
"default_time_window": sa.default_time_window,
}
for sa in org.subject_areas
]
# ---------------------------------------------------------------------------
# Step 2 — examples first
# ---------------------------------------------------------------------------
@dataclass
class ExampleMatch:
example: dict[str, Any]
score: float
def get_prompt_examples(
query: str, examples: list[dict[str, Any]], *, top_k: int = 5
) -> list[ExampleMatch]:
"""Rank scope-tagged examples by similarity to `query`. Highest first.
Each example is a dict with at least a `question` (and typically `sql`,
`tables`, `columns`, `metric`, `default_filters` scope tags). A top match with
score >= HIGH_CONFIDENCE short-circuits the cold-start path (caller's job).
"""
scored: list[ExampleMatch] = []
for ex in examples:
q = ex.get("question") or ex.get("nl") or ""
scored.append(ExampleMatch(ex, _similarity(query, q)))
scored.sort(key=lambda m: m.score, reverse=True)
return scored[:top_k]
HIGH_CONFIDENCE_EXAMPLE = 0.82
def is_high_confidence(matches: list[ExampleMatch]) -> bool:
return bool(matches) and matches[0].score >= HIGH_CONFIDENCE_EXAMPLE
# ---------------------------------------------------------------------------
# Step 3 — resolve entities / metrics (cold-start, lexical)
# ---------------------------------------------------------------------------
def _area_entities(org: Datasource, area: Optional[str]) -> list[tuple[Optional[str], Entity]]:
out: list[tuple[Optional[str], Entity]] = []
for sa in org.subject_areas:
if area and sa.name != area:
continue
for e in sa.entities:
out.append((sa.name, e))
for e in org.cross_subject_area_entities:
out.append((None, e))
return out
def resolve_entities(
query: str, org: Datasource, *, area: Optional[str] = None, top_k: int = 5
) -> list[dict[str, Any]]:
"""Lexically match query terms to entity name / plural / other_names."""
q = query.lower()
ranked: list[tuple[float, dict[str, Any]]] = []
for area_name, ent in _area_entities(org, area):
names = [ent.name] + ([ent.plural] if ent.plural else []) + list(ent.other_names)
score = max((_term_score(q, n) for n in names if n), default=0.0)
if score > 0:
primary = next((m for m in ent.maps_to if m.primary), None) or (
ent.maps_to[0] if ent.maps_to else None
)
ranked.append(
(
score,
{
"entity": ent.name,
"subject_area": area_name,
"score": round(score, 3),
"primary_mapping": (
{"table": primary.table, "column": primary.column}
if primary
else None
),
"value_pattern": ent.value_pattern,
},
)
)
ranked.sort(key=lambda t: t[0], reverse=True)
return [d for _, d in ranked[:top_k]]
def resolve_metrics(
query: str, org: Datasource, *, area: Optional[str] = None, top_k: int = 5
) -> list[dict[str, Any]]:
from . import derived as _D
q = query.lower()
ranked: list[tuple[float, dict[str, Any]]] = []
metrics: list[tuple[Optional[str], Metric]] = []
for sa in org.subject_areas:
if area and sa.name != area:
continue
for mm in sa.metrics:
metrics.append((sa.name, mm))
for mm in org.cross_subject_area_metrics:
metrics.append((None, mm))
idx = _D.metric_index(org)
for area_name, mm in metrics:
names = [mm.name] + list(mm.other_names)
score = max((_term_score(q, n) for n in names if n), default=0.0)
if score > 0:
# A derived metric surfaces its COMPOSED SQL (base placeholders resolved) so
# the generator gets ready-to-run SQL and the single-source-of-truth holds.
# Fall back to the raw binding if expansion fails (validator gates the model).
bindings = mm.bindings
if _D.is_derived(mm) or _D.is_second_order(mm):
try:
bindings = _D.expanded_bindings(mm, idx)
except _D.DerivedError:
bindings = mm.bindings
ranked.append(
(
score,
{
"metric": mm.name,
"subject_area": area_name,
"score": round(score, 3),
"calculation": mm.calculation,
"bindings": bindings,
"confidence": mm.confidence,
},
)
)
ranked.sort(key=lambda t: t[0], reverse=True)
return [d for _, d in ranked[:top_k]]
# ---------------------------------------------------------------------------
# Entity resolution — type identification (value_pattern + probe)
# ---------------------------------------------------------------------------
@dataclass
class IdentifyResult:
status: str # "resolved" | "clarify" | "unrecognized"
candidates: list[dict[str, Any]] = field(default_factory=list)
question_template: Optional[str] = None
def identify_entity(
literal: str,
org: Datasource,
*,
area: Optional[str] = None,
probe: Optional[Prober] = None,
query_context: str = "",
) -> IdentifyResult:
"""Identify what kind of thing an opaque literal is.
1. value_pattern regex match across entities.
2. For pattern matches, probe each candidate's primary mapping to confirm
the value exists (when a prober is supplied).
3. single confirmed -> resolved; multiple -> clarify; none -> probe small
candidates as fallback; still none -> unrecognized.
"""
pattern_hits: list[tuple[Optional[str], Entity]] = []
for area_name, ent in _area_entities(org, area):
if ent.value_pattern:
try:
if re.search(ent.value_pattern, literal):
pattern_hits.append((area_name, ent))
except re.error:
continue
confirmed: list[dict[str, Any]] = []
for area_name, ent in pattern_hits:
ok = True
mapping = next((m for m in ent.maps_to if m.primary), None) or (
ent.maps_to[0] if ent.maps_to else None
)
if probe and mapping:
try:
ok = probe(mapping.table, mapping.column, literal)
except Exception:
ok = False
confirmed.append(
{
"entity": ent.name,
"subject_area": area_name,
"matched_pattern": ent.value_pattern,
"probe_confirmed": ok if probe else None,
"mapping": (
{"table": mapping.table, "column": mapping.column} if mapping else None
),
}
)
# filter to probe-confirmed when probing happened
effective = [c for c in confirmed if c["probe_confirmed"] in (True, None)]
if probe:
effective = [c for c in confirmed if c["probe_confirmed"] is True] or []
if len(effective) == 1:
return IdentifyResult("resolved", effective)
if len(effective) > 1:
names = " or ".join(c["entity"] for c in effective)
return IdentifyResult(
"clarify",
effective,
question_template=(
f"'{literal}' could be a {names}. Which did you mean?"
),
)
# no pattern/probe match: fallback probe of small-cardinality candidates
# (caller supplies cardinalities via resolve_entity_instance normally; here
# we just report unrecognized when nothing matched).
if not pattern_hits:
return IdentifyResult("unrecognized")
# pattern matched but probe disconfirmed all
return IdentifyResult("unrecognized", confirmed)
def resolve_entity_instance(
entity: Entity,
*,
sensitive: Optional[bool] = None,
cardinality: Optional[int] = None,
) -> str:
"""Decide the instance-resolution strategy generically from properties.
sensitive -> db_probe (never extract).
cardinality > 10K -> db_probe.
cardinality <= 50 -> enum.
else -> cached_index.
A per-entity clarification_strictness=high doesn't change strategy; it's a
runtime ask-always flag honored by the caller.
"""
if sensitive is None:
# infer from any mapped column flagged sensitive is the caller's job; default false
sensitive = False
if sensitive:
return "db_probe"
if cardinality is None:
return "db_probe" # unknown -> safest live probe
if cardinality <= ENUM_MAX_CARDINALITY:
return "enum"
if cardinality <= CACHED_INDEX_MAX_CARDINALITY:
return "cached_index"
return "db_probe"
# ---------------------------------------------------------------------------
# Pre-flight: fan-trap / chasm-trap
# ---------------------------------------------------------------------------
@dataclass
class Finding:
"""One thing the pre-flight established about a statement, against the model.
A finding is a FACT, not a verdict. Whether a join multiplies the rows an aggregate is computed
from is derivable from the SQL and the model alone; whether that multiplication is a *bug*
depends on the question, which this layer never sees — the same statement is wrong for order
revenue and right for line-item exposure. So this describes and stops, and the caller, who has
the question, decides.
It carries no `suggestion`. That field existed to give a refusal a way forward, and a
disclosure naming an alternative presumes an intent principle 6 forbids us to presume.
"""
# "fan_trap" | "fan_out_invariant" | "chasm_trap" | "bad_aggregation" | "semi_additive".
# `fan_out_invariant` is the fan its aggregate is immune to: the rows really were multiplied and
# the number is the same either way, so it belongs beside `fan_trap` and not instead of it.
risk: str
reason: str
triggering_joins: list[str] = field(default_factory=list)
# WHICH aggregate this is about, as the parser read it. Without it a finding names the measure
# TABLE and the reader infers which number was affected, which is guesswork the moment a
# statement computes two aggregates over one table. Null only where a finding could not be
# attributed to one aggregate, which nothing currently produces.
#
# This is `runtime.Finding`. `validator.Finding` is a different class with a live `severity`
# field and four consumers; neither borrows from the other.
aggregate: Optional[str] = None
def as_dict(self) -> dict[str, Any]:
return {
"risk": self.risk,
"reason": self.reason,
"triggering_joins": self.triggering_joins,
"aggregate": self.aggregate,
}
@dataclass
class AggregateReport:
"""One aggregate the statement computes, and whether a join multiplied the rows behind it.
The unit REQ-022 asks for: *"for each aggregate whether a join multiplies the rows its value is
computed from"*. Keyed per aggregate rather than per finding, which is what lets the section say
the thing a finding list cannot — that a number is CLEAN. An aggregate the analysis cleared
produces no finding, and a section built from findings alone therefore reports it by saying
nothing, which is the reading `ReceiptSection.undetermined` exists one level up to prevent.
`status` answers exactly one question, and `findings` is the other axis. A `SUM` of a rate on an
unjoined table is `not_multiplied` AND meaningless; folding the aggregation-class findings into
the status enum would force this to drop one of two true facts.
"""
aggregate: str # as the parser read it, sanitized and bounded — see `_echo_expr`
# Which query scope wrote it: "main", plus ACE-043's `#<n>` arm ordinal inside a set operation.
# Aggregates are only read from the output SELECT list, so the scope family is always `main`.
scope: str
# "multiplied" — a join multiplies the rows this value is computed from, and `joins` names it;
# "not_multiplied" — it does not, and this is the positive claim that the number is clean;
# "undetermined" — the analysis could not resolve what this aggregate reads, so it may not
# claim either. `COUNT(*)` is the case that forces the third state to exist: it names no column,
# so no source table resolves and a fan around it is invisible to the detector. Reporting that
# as `not_multiplied` would put a clean bill of health on the one number the join inflated.
status: str
joins: list[str] = field(default_factory=list)
findings: list[Finding] = field(default_factory=list)
# Why the status is "undetermined", in the words of the one blindness the analysis hit, and None
# on the other two statuses. One word for four different causes sent a reader to the join when
# the aggregate simply named no column.
reason: Optional[str] = None
def as_dict(self) -> dict[str, Any]:
return {
"aggregate": self.aggregate,
"scope": self.scope,
"status": self.status,
"joins": self.joins,
"findings": [f.as_dict() for f in self.findings],
"reason": self.reason,
}
# The three values `AggregateReport.status` takes. Named, unlike the declared-filter statuses, which
# are bare literals: those are set in one function and read in one other, while these are set here,
# compared in the marker composition, rendered by two CLI commands and a template, and asserted in
# the battery. A string that crosses that many surfaces gets one spelling.
MULTIPLIED = "multiplied"
NOT_MULTIPLIED = "not_multiplied"
UNDETERMINED = "undetermined"
# And the values a `joins` item's status takes, named for exactly the same reason: they are set in
# the assembler, counted by `_joins_marker`, rendered by the chart template and asserted in the
# battery, which is more than two surfaces.
#
# `UNDETERMINED` above is REUSED rather than given a fourth spelling at the same value. The two
# sections are answering different questions — one about multiplication, one about declaration —
# but the third state is the same state in both: the analysis could not settle it. A second
# constant holding "undetermined" would be one more thing to keep in step and would let the two
# drift to different strings for one meaning.
DECLARED = "declared"
UNDECLARED = "undeclared"
UNDECLARABLE = "undeclarable"
# And the values a `columns` output item's status takes, named for the same reason again: set in the
# assembler, counted by `_columns_marker`, read by the chart template's approve/change banner and
# asserted in the battery.
#
# `UNDETERMINED` is reused a third time rather than given its own spelling. All three sections ask
# different questions — was the value multiplied, is the join declared, which metric is this column —
# but "the analysis could not settle it" is one state, and three constants holding one string is
# three things to keep in step.
#
# There is no fourth value here answering to `UNDECLARABLE`. A join can have an endpoint no
# declaration could ever be about; an output column cannot be a thing no metric could ever compute,
# because a metric's binding is an arbitrary expression. So the settled negative is `UNMATCHED` and
# it means exactly one thing: every candidate binding was read, and none of them is this column.
MATCHED = "matched"
UNMATCHED = "unmatched"
# Why the checks did not run, when they did not. `None` means they DID — the analysis reached the
# statement and an empty `findings` is then a real "nothing found". These sentences are the same
# device the receipt's section markers are, for the same reason: an empty list and an unchecked list
# read identically to a consumer, so silence reads as clean unless something says otherwise.
UNCHECKED_NO_PARSER = (
"sqlglot is not installed here, so the statement was not parsed and no aggregate was checked."
)
UNCHECKED_UNPARSEABLE = (
"The statement could not be parsed, so no aggregate in it was checked."
)
UNCHECKED_NO_SELECT = (
"The statement contains no SELECT, so there was no aggregate to check."
)
@dataclass
class PreFlightResult:
"""Every finding the pre-flight made, in the order the walk made them.
Plural, and the plurality is the point. This carried one `risk` and one `action`, and every path
returned on the first hit — which is right for a verdict, because the first reason to refuse is
reason enough, and wrong for a description, because the second fact is not made false by the
first. A channel that can hold one fact is a verdict with the name changed.
It carries no statement of any kind, and no action: `auto_rewrite` went with the fan-join
rewrite, and `refuse` went when correctness stopped being a refusal, which left one value and
therefore no field.
"""
findings: list[Finding] = field(default_factory=list)
# Every aggregate the statement computes, cleared ones included — the roster the findings are a
# projection of. It lives HERE rather than only inside the receipt assembler so that the CLI
# commands and the receipt state the same facts about the same statement: a surface that listed
# only the findings would report a cleared aggregate by omitting it, which is the reading this
# layer exists to prevent, reappearing at whichever surface did not get the roster.
aggregates: list[AggregateReport] = field(default_factory=list)
# Null when the checks ran. A sentence when they could not, so that `findings == []` is never
# asked to mean two different things at once.
unchecked: Optional[str] = None
def as_dict(self) -> dict[str, Any]:
return {
"findings": [f.as_dict() for f in self.findings],
"aggregates": [a.as_dict() for a in self.aggregates],
"unchecked": self.unchecked,
}
# ---------------------------------------------------------------------------
# Sensitive-column projection — REPORTED, not enforced
#
# `sensitive` is the model author's statement that a column holds values people should be careful
# with. It is a description, and this reports it: which sensitive columns a statement projects raw
# is a fact, and it rides on the receipt beside the answer.
#
# It used to be a gate, refusing the projection. That gate is gone and its absence is deliberate.
# It was the last remnant of a masking programme already cancelled — ACE-041 (mask-else-refuse),
# ACE-062 and ACE-080 were all abandoned on principle 5 on 2026-07-30, and nothing that masks or
# redacts ever shipped. Agami holds no access policy of its own and reads as the connection reads,
# so disclosure control lives in exactly two places: the MODEL, where a column that must not be
# readable is simply not declared and 4b refuses any statement reaching it, and the CONNECTION,
# whose grants and warehouse masking policies apply per role.
#
# `SensitiveCheckResult` went with the gate: an `action` field on a describer is a verdict with the
# name changed.