agent2dashboard 0.2.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.
Files changed (79) hide show
  1. agent2dashboard/__init__.py +593 -0
  2. agent2dashboard/__main__.py +3 -0
  3. agent2dashboard/_env.py +79 -0
  4. agent2dashboard/a2ui/__init__.py +1 -0
  5. agent2dashboard/a2ui/catalogs/dashboard/v1/catalog.json +496 -0
  6. agent2dashboard/a2ui/checks.py +656 -0
  7. agent2dashboard/a2ui/express.py +349 -0
  8. agent2dashboard/a2ui/layout_actions.py +409 -0
  9. agent2dashboard/a2ui/render.py +252 -0
  10. agent2dashboard/a2ui/state.py +600 -0
  11. agent2dashboard/a2ui/surfaces.py +23 -0
  12. agent2dashboard/agent/__init__.py +83 -0
  13. agent2dashboard/agent/builtin_tools.py +258 -0
  14. agent2dashboard/agent/history.py +218 -0
  15. agent2dashboard/agent/loop.py +341 -0
  16. agent2dashboard/agent/prompt.py +66 -0
  17. agent2dashboard/agent/tools.py +162 -0
  18. agent2dashboard/agent/turn.py +201 -0
  19. agent2dashboard/auth.py +350 -0
  20. agent2dashboard/cli/__init__.py +50 -0
  21. agent2dashboard/errors.py +18 -0
  22. agent2dashboard/http/__init__.py +40 -0
  23. agent2dashboard/http/dashboards.py +100 -0
  24. agent2dashboard/http/functions.py +462 -0
  25. agent2dashboard/http/queries.py +168 -0
  26. agent2dashboard/http/revisions.py +126 -0
  27. agent2dashboard/http/router.py +353 -0
  28. agent2dashboard/http/schemas.py +102 -0
  29. agent2dashboard/llm/__init__.py +7 -0
  30. agent2dashboard/llm/_messages_api.py +123 -0
  31. agent2dashboard/llm/bedrock.py +96 -0
  32. agent2dashboard/llm/direct.py +40 -0
  33. agent2dashboard/llm/messages.py +45 -0
  34. agent2dashboard/migrations/__init__.py +383 -0
  35. agent2dashboard/migrations/versions/0001_initial.py +228 -0
  36. agent2dashboard/ports.py +538 -0
  37. agent2dashboard/py.typed +0 -0
  38. agent2dashboard/query/__init__.py +65 -0
  39. agent2dashboard/query/errors.py +39 -0
  40. agent2dashboard/query/executor.py +203 -0
  41. agent2dashboard/query/filters.py +446 -0
  42. agent2dashboard/query/governed.py +155 -0
  43. agent2dashboard/query/readonly.py +166 -0
  44. agent2dashboard/query/registry.py +213 -0
  45. agent2dashboard/query/row_filter.py +135 -0
  46. agent2dashboard/query/service.py +93 -0
  47. agent2dashboard/query/sql_guard.py +219 -0
  48. agent2dashboard/runs/__init__.py +87 -0
  49. agent2dashboard/runs/errors.py +65 -0
  50. agent2dashboard/runs/events.py +147 -0
  51. agent2dashboard/runs/hooks.py +135 -0
  52. agent2dashboard/runs/http.py +169 -0
  53. agent2dashboard/runs/memory.py +148 -0
  54. agent2dashboard/runs/redis_bus.py +219 -0
  55. agent2dashboard/runs/service.py +728 -0
  56. agent2dashboard/runs/writer.py +95 -0
  57. agent2dashboard/semantic/__init__.py +6 -0
  58. agent2dashboard/semantic/cube.py +39 -0
  59. agent2dashboard/semantic/static.py +81 -0
  60. agent2dashboard/storage/__init__.py +60 -0
  61. agent2dashboard/storage/lifecycle.py +105 -0
  62. agent2dashboard/storage/memory.py +488 -0
  63. agent2dashboard/storage/records.py +219 -0
  64. agent2dashboard/storage/sql.py +666 -0
  65. agent2dashboard/storage/tables.py +387 -0
  66. agent2dashboard/testing/__init__.py +20 -0
  67. agent2dashboard/testing/event_bus.py +10 -0
  68. agent2dashboard/testing/fake_llm.py +129 -0
  69. agent2dashboard/testing/host.py +191 -0
  70. agent2dashboard/tracing/__init__.py +36 -0
  71. agent2dashboard/tracing/db.py +143 -0
  72. agent2dashboard/tracing/fanout.py +153 -0
  73. agent2dashboard/tracing/langfuse.py +339 -0
  74. agent2dashboard/tracing/masking.py +26 -0
  75. agent2dashboard-0.2.0.dist-info/METADATA +81 -0
  76. agent2dashboard-0.2.0.dist-info/RECORD +79 -0
  77. agent2dashboard-0.2.0.dist-info/WHEEL +4 -0
  78. agent2dashboard-0.2.0.dist-info/entry_points.txt +3 -0
  79. agent2dashboard-0.2.0.dist-info/licenses/LICENSE +202 -0
@@ -0,0 +1,155 @@
1
+ """The governed schema: the only tables model-written SQL may read (design §3.1)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import typing
6
+ from collections.abc import Iterable, Mapping, Sequence
7
+ from enum import StrEnum
8
+ from types import MappingProxyType
9
+ from typing import Any
10
+
11
+ from sqlalchemy import Date, DateTime, Enum, MetaData, Table
12
+ from sqlalchemy.engine import Connection, Engine
13
+ from sqlalchemy.ext.asyncio import AsyncEngine
14
+
15
+ from agent2dashboard.ports import GovernedColumn, GovernedTable
16
+
17
+ __all__ = ["FILTERABLE_TYPES", "GovernedSchema", "filter_sql_type"]
18
+
19
+ # SQL types a dimension filter may compare against, by type-name prefix, and the Postgres
20
+ # type its value is cast to.
21
+ FILTERABLE_TYPES: Mapping[str, str] = MappingProxyType(
22
+ {
23
+ "VARCHAR": "text",
24
+ "TEXT": "text",
25
+ "CHAR": "text",
26
+ "BOOLEAN": "boolean",
27
+ "INTEGER": "bigint",
28
+ "BIGINT": "bigint",
29
+ "SMALLINT": "bigint",
30
+ }
31
+ )
32
+
33
+
34
+ def filter_sql_type(column: GovernedColumn) -> str | None:
35
+ """The Postgres type a filter on `column` binds its value as; None when the column can't
36
+ back a dimension filter (dates, ids of other types, JSON, ...)."""
37
+ if not column.filterable:
38
+ return None
39
+ sql_type = column.sql_type.upper()
40
+ return next(
41
+ (cast for prefix, cast in FILTERABLE_TYPES.items() if sql_type.startswith(prefix)), None
42
+ )
43
+
44
+
45
+ def _filterable_by_type(sql_type: str) -> bool:
46
+ upper = sql_type.upper()
47
+ return any(upper.startswith(prefix) for prefix in FILTERABLE_TYPES)
48
+
49
+
50
+ def _enum_hints(model: type) -> dict[str, tuple[str, ...]]:
51
+ """Column name -> values, for ORM attributes typed with a StrEnum (stored as VARCHAR, so
52
+ the enum only survives on the `Mapped[...]` hint)."""
53
+ found: dict[str, tuple[str, ...]] = {}
54
+ try:
55
+ hints = typing.get_type_hints(model)
56
+ except Exception: # unresolvable forward references: no enum hints, not an error
57
+ return found
58
+ for name, hint in hints.items():
59
+ for arg in typing.get_args(hint) or (hint,):
60
+ for inner in typing.get_args(arg) or (arg,):
61
+ if isinstance(inner, type) and issubclass(inner, StrEnum):
62
+ found[name] = tuple(member.value for member in inner)
63
+ return found
64
+
65
+
66
+ def _describe(
67
+ table: Table, enum_hints: Mapping[str, tuple[str, ...]] | None = None
68
+ ) -> GovernedTable:
69
+ enum_hints = enum_hints or {}
70
+ columns = []
71
+ time_columns = []
72
+ for col in table.columns:
73
+ sql_type = str(col.type)
74
+ foreign = next(iter(col.foreign_keys), None)
75
+ enum_values: tuple[str, ...] | None = None
76
+ if isinstance(col.type, Enum) and col.type.enums:
77
+ enum_values = tuple(col.type.enums)
78
+ elif col.key in enum_hints or col.name in enum_hints:
79
+ enum_values = enum_hints.get(col.key) or enum_hints.get(col.name)
80
+ filterable = col.info.get("a2d_filterable", _filterable_by_type(sql_type))
81
+ columns.append(
82
+ GovernedColumn(
83
+ name=col.name,
84
+ sql_type=sql_type,
85
+ nullable=bool(col.nullable) if col.nullable is not None else True,
86
+ primary_key=bool(col.primary_key),
87
+ unique=bool(col.unique),
88
+ foreign_key=(
89
+ (foreign.column.table.name, foreign.column.name)
90
+ if foreign is not None
91
+ else None
92
+ ),
93
+ enum_values=enum_values,
94
+ filterable=bool(filterable),
95
+ )
96
+ )
97
+ if isinstance(col.type, Date | DateTime):
98
+ time_columns.append(col.name)
99
+ return GovernedTable(name=table.name, columns=tuple(columns), time_columns=tuple(time_columns))
100
+
101
+
102
+ class GovernedSchema:
103
+ """A fixed set of governed tables; implements `agent2dashboard.ports.GovernedSchema`.
104
+
105
+ Build it from the host's SQLAlchemy models (`from_models`) or by reflecting an allowlist
106
+ of tables from the database (`from_reflection`). Never govern a table holding users,
107
+ credentials or logs: every governed table is readable by model-written SQL.
108
+ """
109
+
110
+ def __init__(self, tables: Iterable[GovernedTable]) -> None:
111
+ by_name: dict[str, GovernedTable] = {}
112
+ for table in tables:
113
+ if table.name in by_name:
114
+ raise ValueError(f"Table {table.name} is governed twice.")
115
+ by_name[table.name] = table
116
+ self._tables = MappingProxyType(by_name)
117
+
118
+ def tables(self) -> Mapping[str, GovernedTable]:
119
+ return self._tables
120
+
121
+ def __repr__(self) -> str:
122
+ return f"GovernedSchema({', '.join(sorted(self._tables))})"
123
+
124
+ @classmethod
125
+ def from_models(cls, models: Sequence[Any]) -> GovernedSchema:
126
+ """From declarative models (or `Table` objects). A column's `info={"a2d_filterable":
127
+ False}` keeps it out of dimension filters."""
128
+ described = []
129
+ for model in models:
130
+ if isinstance(model, Table):
131
+ described.append(_describe(model))
132
+ else:
133
+ described.append(_describe(model.__table__, _enum_hints(model)))
134
+ return cls(described)
135
+
136
+ @classmethod
137
+ def from_reflection(cls, engine: Engine | Connection, allow: Sequence[str]) -> GovernedSchema:
138
+ """Reflect exactly the `allow` tables with a sync engine or connection."""
139
+ metadata = MetaData()
140
+ metadata.reflect(bind=engine, only=list(allow))
141
+ return cls._from_metadata(metadata, allow)
142
+
143
+ @classmethod
144
+ async def from_reflection_async(
145
+ cls, engine: AsyncEngine, allow: Sequence[str]
146
+ ) -> GovernedSchema:
147
+ """`from_reflection` for an async engine."""
148
+ metadata = MetaData()
149
+ async with engine.connect() as connection:
150
+ await connection.run_sync(lambda sync: metadata.reflect(bind=sync, only=list(allow)))
151
+ return cls._from_metadata(metadata, allow)
152
+
153
+ @classmethod
154
+ def _from_metadata(cls, metadata: MetaData, allow: Sequence[str]) -> GovernedSchema:
155
+ return cls(_describe(metadata.tables[name]) for name in allow)
@@ -0,0 +1,166 @@
1
+ """Startup check of the query connection (design §7).
2
+
3
+ Outside local development, queries must run as a read-only role. `check_readonly_role`
4
+ refuses to start when there is no read-only URL (unless the host opted in with
5
+ `allow_app_connection_for_queries`), and otherwise proves the role:
6
+ - is not a superuser and doesn't bypass RLS;
7
+ - can read every governed table;
8
+ - can't write any governed table, and an actual INSERT, in a transaction that is rolled back,
9
+ fails with a privilege error;
10
+ - can't read any table outside the governed schema, and an actual SELECT of one fails.
11
+ """
12
+
13
+ from __future__ import annotations
14
+
15
+ from dataclasses import dataclass
16
+
17
+ from sqlalchemy import text
18
+ from sqlalchemy.exc import DBAPIError
19
+
20
+ from agent2dashboard.query.errors import ReadOnlyRoleError
21
+ from agent2dashboard.query.executor import SqlAlchemyDataSource
22
+
23
+ __all__ = ["LOCAL_ENVIRONMENTS", "ReadOnlyCheck", "check_readonly_role"]
24
+
25
+ LOCAL_ENVIRONMENTS = frozenset({"local"})
26
+ _INSUFFICIENT_PRIVILEGE = "42501"
27
+
28
+ _OTHER_READABLE = text(
29
+ """
30
+ SELECT n.nspname AS schema_name, c.relname AS table_name,
31
+ has_table_privilege(c.oid, 'SELECT') AS readable
32
+ FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace
33
+ WHERE c.relkind IN ('r', 'v', 'm', 'p', 'f')
34
+ AND n.nspname NOT IN ('pg_catalog', 'information_schema')
35
+ AND n.nspname NOT LIKE 'pg\\_toast%' AND n.nspname NOT LIKE 'pg\\_temp%'
36
+ AND NOT (c.oid = ANY(CAST(:governed AS oid[])))
37
+ ORDER BY readable DESC, n.nspname, c.relname
38
+ """
39
+ )
40
+
41
+
42
+ @dataclass(frozen=True)
43
+ class ReadOnlyCheck:
44
+ skipped: bool
45
+ """True when queries use the app connection (allowed only locally or by opt-in)."""
46
+ role: str | None = None
47
+ governed_tables: tuple[str, ...] = ()
48
+ probed_other_table: str | None = None
49
+
50
+
51
+ def _sqlstate(exc: DBAPIError) -> str | None:
52
+ orig = exc.orig
53
+ return getattr(orig, "sqlstate", None) or getattr(orig, "pgcode", None)
54
+
55
+
56
+ def _quote(name: str) -> str:
57
+ return '"' + name.replace('"', '""') + '"'
58
+
59
+
60
+ async def check_readonly_role(
61
+ data: SqlAlchemyDataSource,
62
+ *,
63
+ environment: str,
64
+ allow_app_connection_for_queries: bool = False,
65
+ ) -> ReadOnlyCheck:
66
+ """Raise `ReadOnlyRoleError` unless queries run as a proper read-only role (or the app
67
+ connection is allowed here). Call it at startup, before serving."""
68
+ if data.uses_app_connection:
69
+ if environment in LOCAL_ENVIRONMENTS or allow_app_connection_for_queries:
70
+ return ReadOnlyCheck(skipped=True)
71
+ raise ReadOnlyRoleError(
72
+ [
73
+ f"No read-only database URL for queries in environment {environment!r}. "
74
+ "Configure a role that can only SELECT the governed tables, or set "
75
+ "SDKConfig.allow_app_connection_for_queries=True for local development."
76
+ ]
77
+ )
78
+
79
+ governed = sorted(data.governed.tables())
80
+ problems: list[str] = []
81
+ async with data.engine.connect() as connection:
82
+ role_row = (
83
+ await connection.execute(
84
+ text(
85
+ "SELECT current_user AS role, r.rolsuper, r.rolbypassrls "
86
+ "FROM pg_roles r WHERE r.rolname = current_user"
87
+ )
88
+ )
89
+ ).one()
90
+ role = role_row.role
91
+ if role_row.rolsuper:
92
+ problems.append(f"Role {role} is a superuser.")
93
+ if role_row.rolbypassrls:
94
+ problems.append(f"Role {role} bypasses row-level security.")
95
+
96
+ oids: list[int] = []
97
+ for name in governed:
98
+ row = (
99
+ await connection.execute(
100
+ text(
101
+ "SELECT c.oid AS oid, has_table_privilege(c.oid, 'SELECT') AS can_read, "
102
+ "has_any_column_privilege(c.oid, 'INSERT') "
103
+ "OR has_any_column_privilege(c.oid, 'UPDATE') "
104
+ "OR has_table_privilege(c.oid, 'DELETE') "
105
+ "OR has_table_privilege(c.oid, 'TRUNCATE') AS can_write "
106
+ "FROM pg_class c WHERE c.oid = to_regclass(:name)"
107
+ ),
108
+ {"name": _quote(name)},
109
+ )
110
+ ).one_or_none()
111
+ if row is None:
112
+ problems.append(f"Governed table {name} does not exist for role {role}.")
113
+ continue
114
+ oids.append(row.oid)
115
+ if not row.can_read:
116
+ problems.append(f"Role {role} cannot read governed table {name}.")
117
+ if row.can_write:
118
+ problems.append(f"Role {role} can write governed table {name}.")
119
+
120
+ if governed:
121
+ probe = governed[0]
122
+ insert_error = None
123
+ try:
124
+ # Inserts no row, so no default, sequence or constraint can fail first: only
125
+ # the privilege check decides.
126
+ await connection.execute(
127
+ text(f"INSERT INTO {_quote(probe)} SELECT * FROM {_quote(probe)} WHERE false")
128
+ )
129
+ except DBAPIError as exc:
130
+ insert_error = _sqlstate(exc)
131
+ finally:
132
+ await connection.rollback()
133
+ if insert_error != _INSUFFICIENT_PRIVILEGE:
134
+ problems.append(
135
+ f"An INSERT into {probe} as {role} was not refused for lack of privilege."
136
+ )
137
+
138
+ others = (await connection.execute(_OTHER_READABLE, {"governed": oids})).all()
139
+ readable = [f"{r.schema_name}.{r.table_name}" for r in others if r.readable]
140
+ if readable:
141
+ shown = ", ".join(readable[:5]) + (" ..." if len(readable) > 5 else "")
142
+ problems.append(f"Role {role} can read tables outside the governed schema: {shown}.")
143
+ probed = None
144
+ if others:
145
+ target = others[-1] # an unreadable one when there is one
146
+ probed = f"{target.schema_name}.{target.table_name}"
147
+ select_error = None
148
+ try:
149
+ await connection.execute(
150
+ text(
151
+ f"SELECT 1 FROM {_quote(target.schema_name)}.{_quote(target.table_name)}"
152
+ " LIMIT 0"
153
+ )
154
+ )
155
+ except DBAPIError as exc:
156
+ select_error = _sqlstate(exc)
157
+ finally:
158
+ await connection.rollback()
159
+ if select_error != _INSUFFICIENT_PRIVILEGE:
160
+ problems.append(f"Role {role} could read {probed}, which is not governed.")
161
+
162
+ if problems:
163
+ raise ReadOnlyRoleError(problems)
164
+ return ReadOnlyCheck(
165
+ skipped=False, role=role, governed_tables=tuple(governed), probed_other_table=probed
166
+ )
@@ -0,0 +1,213 @@
1
+ """The query registry and the `define_query` tool (design §1.10 decision 2).
2
+
3
+ The model registers SQL under a `query_id`; components only ever name the id. A registration
4
+ is checked by the guard, scoped by the row filter and run read-only first, and the model gets
5
+ back the result's shape: column names and kinds, and the row count. Never a value.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import re
11
+ from collections.abc import Iterable, Iterator, Mapping, Sequence
12
+ from datetime import datetime
13
+ from typing import Any, Literal
14
+
15
+ from pydantic import BaseModel, ConfigDict, Field
16
+
17
+ from agent2dashboard.ports import Principal, ToolDef
18
+ from agent2dashboard.query.errors import InvalidQueryDefinition
19
+ from agent2dashboard.query.filters import (
20
+ DimensionFilter,
21
+ QueryContext,
22
+ bind_filters,
23
+ check_dimensions,
24
+ filters_used,
25
+ permissive_context,
26
+ )
27
+ from agent2dashboard.query.service import QueryService
28
+
29
+ __all__ = [
30
+ "DEFINE_QUERY_TOOL",
31
+ "DefineQueryResult",
32
+ "QueryColumn",
33
+ "QueryRegistry",
34
+ "RegisteredQuery",
35
+ "define_query",
36
+ ]
37
+
38
+ QUERY_ID_PATTERN = r"^[a-z][a-z0-9_]{0,63}$"
39
+ _QUERY_ID = re.compile(QUERY_ID_PATTERN)
40
+ MAX_QUERIES = 32
41
+
42
+
43
+ class QueryColumn(BaseModel):
44
+ model_config = ConfigDict(frozen=True)
45
+
46
+ name: str
47
+ kind: Literal["number", "text", "date"]
48
+
49
+
50
+ class RegisteredQuery(BaseModel):
51
+ """One entry of a conversation's query registry (stored in `dashboard.queries`)."""
52
+
53
+ model_config = ConfigDict(frozen=True)
54
+
55
+ query_id: str = Field(pattern=QUERY_ID_PATTERN)
56
+ sql: str
57
+ filters_used: tuple[str, ...] = ()
58
+ """Filter keys the SQL reads: `time` and dimension keys."""
59
+ dimensions: tuple[DimensionFilter, ...] = ()
60
+ """The dimension filters declared with the query, to bind their values later."""
61
+ columns: tuple[QueryColumn, ...]
62
+
63
+ def column(self, name: str) -> QueryColumn | None:
64
+ return next((c for c in self.columns if c.name == name), None)
65
+
66
+ def context(
67
+ self, values: Mapping[str, Any], governed: Any, now: datetime | None = None
68
+ ) -> QueryContext:
69
+ """Bind the dashboard's filter values (`$/filters`) for a run of this query."""
70
+ return bind_filters(self.dimensions, values, governed, now)
71
+
72
+
73
+ class QueryRegistry:
74
+ """A conversation's registered queries, by id. Defining an id again replaces it."""
75
+
76
+ def __init__(self, queries: Iterable[RegisteredQuery] = ()) -> None:
77
+ self._queries: dict[str, RegisteredQuery] = {}
78
+ for query in queries:
79
+ self._queries[query.query_id] = query
80
+
81
+ def register(self, query: RegisteredQuery) -> None:
82
+ if query.query_id not in self._queries and len(self._queries) >= MAX_QUERIES:
83
+ raise InvalidQueryDefinition(f"At most {MAX_QUERIES} queries per dashboard.")
84
+ self._queries[query.query_id] = query
85
+
86
+ def get(self, query_id: str) -> RegisteredQuery | None:
87
+ return self._queries.get(query_id)
88
+
89
+ def __contains__(self, query_id: object) -> bool:
90
+ return query_id in self._queries
91
+
92
+ def __iter__(self) -> Iterator[RegisteredQuery]:
93
+ return iter(self._queries.values())
94
+
95
+ def __len__(self) -> int:
96
+ return len(self._queries)
97
+
98
+ def to_json(self) -> list[dict[str, Any]]:
99
+ return [query.model_dump(mode="json") for query in self._queries.values()]
100
+
101
+ @classmethod
102
+ def from_json(cls, data: Sequence[Mapping[str, Any]] | None) -> QueryRegistry:
103
+ return cls(RegisteredQuery.model_validate(item) for item in data or ())
104
+
105
+
106
+ class DefineQueryResult(BaseModel):
107
+ """What the model sees: the result's shape, never its values."""
108
+
109
+ query_id: str
110
+ columns: tuple[QueryColumn, ...]
111
+ row_count: int
112
+ truncated: bool
113
+ filters_used: tuple[str, ...]
114
+
115
+
116
+ DEFINE_QUERY_TOOL = ToolDef(
117
+ name="define_query",
118
+ description=(
119
+ "Register a read-only SQL SELECT over the governed tables under `query_id`, for "
120
+ "dashboard components to reference by id. The query is checked and run once; you get "
121
+ "back its column names, their kinds (number, text, date) and the row count, never the "
122
+ "values. Use {{time_from}} / {{time_to}} for the dashboard period (half-open: "
123
+ "`col >= {{time_from}} AND col < {{time_to}}`) and {{filter.<key>}} for a dimension "
124
+ "filter declared in `filters`, written `({{filter.<key>}} IS NULL OR col = "
125
+ "{{filter.<key>}})`. Give every column a distinct name. Defining an id again replaces it."
126
+ ),
127
+ input_schema={
128
+ "type": "object",
129
+ "properties": {
130
+ "query_id": {"type": "string", "pattern": QUERY_ID_PATTERN},
131
+ "sql": {"type": "string", "minLength": 1},
132
+ "filters": {
133
+ "type": "array",
134
+ "description": "Dimension filters the SQL reads as {{filter.<key>}}.",
135
+ "items": {
136
+ "type": "object",
137
+ "properties": {
138
+ "key": {"type": "string", "pattern": r"^[a-z][a-z0-9_]{0,31}$"},
139
+ "table": {"type": "string"},
140
+ "column": {"type": "string"},
141
+ "label": {"type": "string"},
142
+ },
143
+ "required": ["key", "table", "column"],
144
+ "additionalProperties": False,
145
+ },
146
+ },
147
+ },
148
+ "required": ["query_id", "sql"],
149
+ "additionalProperties": False,
150
+ },
151
+ )
152
+
153
+
154
+ async def define_query(
155
+ *,
156
+ service: QueryService,
157
+ registry: QueryRegistry,
158
+ principal: Principal,
159
+ query_id: str,
160
+ sql: str,
161
+ filters: Sequence[Any] | None = None,
162
+ now: datetime | None = None,
163
+ ) -> DefineQueryResult:
164
+ """The `define_query` tool handler: guard, row filter, read-only run, register.
165
+
166
+ Raises a `QueryError` (`SqlRejected`, `QueryFailed`, `InvalidFilters`,
167
+ `InvalidQueryDefinition`) or `RowFilterDenied`; every message is fit to return to the
168
+ model as the tool error. Nothing is registered when it raises.
169
+ """
170
+ if not isinstance(query_id, str) or not _QUERY_ID.fullmatch(query_id):
171
+ raise InvalidQueryDefinition(
172
+ "query_id must be lower_snake_case: a letter, then letters, digits or _ (at most 64)."
173
+ )
174
+ governed = service.data.governed
175
+ dimensions = check_dimensions(filters, governed)
176
+ stored_sql = sql.strip().rstrip(";").strip()
177
+ outcome = await service.run(
178
+ stored_sql, principal=principal, context=permissive_context(dimensions, governed, now)
179
+ )
180
+ names = list(outcome.result.columns)
181
+ duplicates = sorted({n for n in names if names.count(n) > 1})
182
+ if duplicates:
183
+ raise InvalidQueryDefinition(
184
+ f"Columns {', '.join(duplicates)} appear more than once; give each column a "
185
+ "distinct alias."
186
+ )
187
+ if "?column?" in names:
188
+ raise InvalidQueryDefinition("Name every computed column with `AS <name>`.")
189
+ used = filters_used(stored_sql)
190
+ unused = [d.key for d in dimensions if d.key not in used]
191
+ if unused:
192
+ raise InvalidQueryDefinition(
193
+ f"Filters {', '.join(unused)} are declared but the query doesn't use them."
194
+ )
195
+ columns = tuple(
196
+ QueryColumn(name=name, kind=kind) for name, kind in zip(names, outcome.kinds, strict=True)
197
+ )
198
+ registry.register(
199
+ RegisteredQuery(
200
+ query_id=query_id,
201
+ sql=stored_sql,
202
+ filters_used=used,
203
+ dimensions=dimensions,
204
+ columns=columns,
205
+ )
206
+ )
207
+ return DefineQueryResult(
208
+ query_id=query_id,
209
+ columns=columns,
210
+ row_count=len(outcome.result.rows),
211
+ truncated=outcome.result.truncated,
212
+ filters_used=used,
213
+ )
@@ -0,0 +1,135 @@
1
+ """Row-level security by rewriting (design §3.4).
2
+
3
+ Every reference to a scoped table, wherever it stands (FROM, JOIN, a CTE body, a subquery, a
4
+ branch of a UNION, a parenthesised join), becomes `(SELECT * FROM t WHERE <predicate>) AS t`,
5
+ keeping the reference's own alias. Names that resolve to a CTE are left alone: the CTE's body
6
+ is rewritten instead. The host's predicate parameters (`:name`) are bound as parameters too,
7
+ renamed `rls_<n>` so they can't collide with the filter tokens.
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ import re
13
+ from collections.abc import Sequence
14
+ from typing import Any
15
+
16
+ import sqlglot
17
+ from sqlglot import exp
18
+ from sqlglot.errors import SqlglotError
19
+
20
+ from agent2dashboard.errors import AgentDashboardError
21
+ from agent2dashboard.ports import RowScope
22
+ from agent2dashboard.query.filters import GuardedQuery
23
+ from agent2dashboard.query.sql_guard import (
24
+ FORBIDDEN_NODES,
25
+ RESERVED_MARKER,
26
+ normalized_name,
27
+ real_tables,
28
+ )
29
+
30
+ __all__ = ["InvalidRowScope", "apply_scopes", "compile_query"]
31
+
32
+ _RLS_MARKER = RESERVED_MARKER + "rls_{}__"
33
+ _SCOPED = "a2d_scoped" # meta flag on tables the rewrite produced or the host's predicate reads
34
+ _MARKER_RE = re.compile(re.escape(RESERVED_MARKER) + r"(token|rls)_(\d+)__")
35
+
36
+
37
+ class InvalidRowScope(AgentDashboardError):
38
+ """A host `RowScope` the SDK can't apply (unparseable predicate, missing parameter). A
39
+ host bug, never shown to the model."""
40
+
41
+
42
+ def _predicate(scope: RowScope, names: dict[tuple[int, str], int], index: int) -> exp.Expression:
43
+ try:
44
+ parsed = sqlglot.parse_one(f"SELECT 1 WHERE {scope.predicate_sql}", dialect="postgres")
45
+ except SqlglotError as exc:
46
+ raise InvalidRowScope(f"Row scope for {scope.table} does not parse: {exc}") from exc
47
+ where = parsed.args.get("where") if isinstance(parsed, exp.Select) else None
48
+ if where is None or parsed.args.get("from_") or parsed.args.get("from"):
49
+ raise InvalidRowScope(f"Row scope for {scope.table} is not a single condition.")
50
+ condition = where.this
51
+ for node in list(condition.walk()):
52
+ if isinstance(node, exp.Placeholder):
53
+ name = node.name
54
+ if not name or name not in scope.params:
55
+ raise InvalidRowScope(
56
+ f"Row scope for {scope.table} uses :{name or '?'} but has no such param."
57
+ )
58
+ number = names.setdefault((index, name), len(names))
59
+ node.replace(exp.column(_RLS_MARKER.format(number)))
60
+ elif isinstance(node, exp.Parameter) or (
61
+ isinstance(node, FORBIDDEN_NODES) and not isinstance(node, exp.Placeholder)
62
+ ):
63
+ raise InvalidRowScope(
64
+ f"Row scope for {scope.table} contains {type(node).__name__.upper()}."
65
+ )
66
+ for table in condition.find_all(exp.Table):
67
+ table.meta[_SCOPED] = True
68
+ return condition
69
+
70
+
71
+ def apply_scopes(
72
+ tree: exp.Expression, scopes: Sequence[RowScope]
73
+ ) -> tuple[exp.Expression, dict[str, Any]]:
74
+ """A copy of `tree` with every reference to a scoped table narrowed, and the parameters
75
+ the predicates need (by `rls_<n>` name)."""
76
+ by_table: dict[str, tuple[int, RowScope]] = {}
77
+ for index, scope in enumerate(scopes):
78
+ if scope.table in by_table:
79
+ raise InvalidRowScope(f"Two row scopes for {scope.table}.")
80
+ by_table[scope.table] = (index, scope)
81
+ tree = tree.copy()
82
+ names: dict[tuple[int, str], int] = {}
83
+ while True:
84
+ target = next(
85
+ (
86
+ t
87
+ for t in real_tables(tree)
88
+ if not t.meta.get(_SCOPED) and normalized_name(t.this) in by_table
89
+ ),
90
+ None,
91
+ )
92
+ if target is None:
93
+ break
94
+ index, scope = by_table[normalized_name(target.this)]
95
+ inner = target.copy()
96
+ for arg in ("alias", "joins"):
97
+ inner.set(arg, None)
98
+ inner.meta[_SCOPED] = True
99
+ alias = target.args.get("alias")
100
+ subquery = exp.Subquery(
101
+ this=exp.select("*").from_(inner).where(_predicate(scope, names, index)),
102
+ alias=alias.copy()
103
+ if alias is not None
104
+ else exp.TableAlias(this=exp.to_identifier(target.name, quoted=target.this.quoted)),
105
+ )
106
+ if target.args.get("joins"):
107
+ subquery.set("joins", [join.copy() for join in target.args["joins"]])
108
+ target.replace(subquery)
109
+ params = {
110
+ f"rls_{number}": scopes[index].params[name] for (index, name), number in names.items()
111
+ }
112
+ return tree, params
113
+
114
+
115
+ def compile_query(guarded: GuardedQuery, scopes: Sequence[RowScope]) -> tuple[str, dict[str, Any]]:
116
+ """The SQL for SQLAlchemy `text()` and its parameters. Without scopes this is the caller's
117
+ own text; with scopes the rewritten tree is generated back to SQL."""
118
+ params: dict[str, Any] = dict(guarded.params)
119
+ relevant = [s for s in scopes if s.table in guarded.tables]
120
+ if not relevant:
121
+ return guarded.text_sql, params
122
+ tree, rls_params = apply_scopes(guarded.tree, relevant)
123
+ params.update(rls_params)
124
+ generated = tree.sql(dialect="postgres").replace(":", r"\:")
125
+
126
+ def substitute(match: re.Match[str]) -> str:
127
+ kind, number = match.group(1), int(match.group(2))
128
+ if kind == "token":
129
+ return f"CAST(:token_{number} AS {guarded.bounds[number].sql_type})"
130
+ return f":rls_{number}"
131
+
132
+ sql = _MARKER_RE.sub(substitute, generated)
133
+ if RESERVED_MARKER in sql: # a marker sqlglot quoted or reshaped: never run it
134
+ raise InvalidRowScope("Could not compile the scoped query.")
135
+ return sql, params