From 684dc446a97aac7da2ead407530cd69e0a46273e Mon Sep 17 00:00:00 2001 From: Juan Manuel Castillo Pinto <33883620+jmmana@users.noreply.github.com> Date: Thu, 3 Dec 2026 20:51:30 -0500 Subject: [PATCH 1/2] Compare opt-in filtered aggregate cohorts in MCP --- docs/DESIGN.md | 10 ++++++ docs/es/THREAT_MODEL.md | 6 ++++ src/sqlguardllm/cli.py | 10 +++++- src/sqlguardllm/mcp_server.py | 19 +++++++++-- src/sqlguardllm/session_limits.py | 42 ++++++++++++++++++++++-- tests/engines/test_row_budget_engines.py | 40 ++++++++++++++++++++++ tests/test_mcp.py | 35 ++++++++++++++++++++ 7 files changed, 157 insertions(+), 5 deletions(-) diff --git a/docs/DESIGN.md b/docs/DESIGN.md index af0e2a8..19bbd46 100644 --- a/docs/DESIGN.md +++ b/docs/DESIGN.md @@ -393,6 +393,16 @@ most 513 rows, including one extra to detect an oversized set. History is process-local and expires after `window_seconds`. Verified-catalog queries on a cohort source are refused. +To permit filtered cohorts, include an eligible source in +`"cohort_id_filter_sources": ["salaries"]` in the same configuration. This +option requires an `aggregate_only` policy on SQLite or PostgreSQL and a +stable integer identifier on a trusted base table. It permits one direct +comparison (`=`, `<>`, `<`, `<=`, `>`, or `>=`) between that identifier +and an integer literal. MCP validates the predicate in the checked SQL and +uses it for both the membership read and the aggregate in the same snapshot. +Other caller-selected filters are refused. The same cohort history covers +filtered and unfiltered queries. + ### Aggregate cohort history for embedded applications `sqlguardllm.session_limits.AggregateCohorts` is an experimental Python diff --git a/docs/es/THREAT_MODEL.md b/docs/es/THREAT_MODEL.md index a13db91..e41e50a 100644 --- a/docs/es/THREAT_MODEL.md +++ b/docs/es/THREAT_MODEL.md @@ -68,6 +68,12 @@ si obtienen las identidades de las filas y el agregado de la misma instantánea. El historial compara los conjuntos dentro de una sesión, un origen y una ventana. Los servidores MCP y proxy incorporados aplican sus restricciones de conjunto fijo. +En SQLite y PostgreSQL, las fuentes de agregados con historial pueden habilitar +una [comparación directa sobre su identificador entero](../DESIGN.md#mcp-row-budgets). +La lectura de integrantes y el cálculo del agregado usan la misma instantánea. +MCP aplica el umbral de diferencia a los conjuntos con y sin filtro que se +consultaron en la sesión. + ## Diferenciales de parser encontrados Lugares donde el árbol de sqlglot no decía lo que haría el motor real. Cada uno se corrigió y tiene un caso en el corpus. diff --git a/src/sqlguardllm/cli.py b/src/sqlguardllm/cli.py index 9d40b83..a4900a6 100644 --- a/src/sqlguardllm/cli.py +++ b/src/sqlguardllm/cli.py @@ -856,10 +856,12 @@ def _read_row_budgets(path: Path) -> RowBudgets: "keyset_page_limit", "fixed_aggregate_sources", "cohorts", + "cohort_id_filter_sources", }: raise ValueError( "expected row_budget and window_seconds, with optional reject_offset and " - "keyset_columns, keyset_page_limit and fixed_aggregate_sources" + "keyset_columns, keyset_page_limit, fixed_aggregate_sources, cohorts " + "and cohort_id_filter_sources" ) limits = data["row_budget"] if not isinstance(limits, dict) or not limits: @@ -872,6 +874,11 @@ def _read_row_budgets(path: Path) -> RowBudgets: isinstance(source, str) for source in fixed_aggregate_sources ): raise ValueError("fixed_aggregate_sources must be an array of table names") + id_filters = data.get("cohort_id_filter_sources", []) + if not isinstance(id_filters, list) or not all( + isinstance(source, str) for source in id_filters + ): + raise ValueError("cohort_id_filter_sources must be an array of table names") raw_cohorts = data.get("cohorts", {}) cohorts: dict[str, tuple[str, int]] = {} if not isinstance(raw_cohorts, dict): @@ -893,6 +900,7 @@ def _read_row_budgets(path: Path) -> RowBudgets: keyset_page_limit=data.get("keyset_page_limit", 0), fixed_aggregate_sources=fixed_aggregate_sources, cohorts=cohorts, + cohort_id_filter_sources=id_filters, ) except (OSError, ValueError) as exc: raise _UsageError(f"invalid row budget file: {exc}") from None diff --git a/src/sqlguardllm/mcp_server.py b/src/sqlguardllm/mcp_server.py index fc232c9..d796ff2 100644 --- a/src/sqlguardllm/mcp_server.py +++ b/src/sqlguardllm/mcp_server.py @@ -1014,13 +1014,28 @@ def _run_query( def budget_session() -> str | None: return self._session_id() if self._explicit_resolver else self._session_object(ctx) + if ( + self.row_budgets is not None + and self.row_budgets.uses_cohort_id_filters(decision.tables) + and ( + self.engine.dialect.name not in {"sqlite", "postgresql"} + or not all( + self._marker(self.compiled.aggregate_only.keys(), self._resolve(source)) + for source in decision.tables + ) + ) + ): + raise ToolError( + "cohort_unavailable: filtered cohorts require aggregate_only " + "on SQLite or PostgreSQL" + ) if self.row_budgets is not None and not self.row_budgets.permits_aggregate_shape( sql, self.dialect, decision.tables ): message = ( - "Este origen requiere agregados sobre el conjunto completo de filas permitido." + "La forma de este agregado no está permitida para este origen." if self.language == "es" - else "This source requires aggregates over the full set of permitted rows." + else "This aggregate shape is not allowed for this source." ) raise ToolError(f"aggregate_shape_restricted: {message}") if self.row_budgets is not None and not self.row_budgets.permits_offset( diff --git a/src/sqlguardllm/session_limits.py b/src/sqlguardllm/session_limits.py index 7eb828b..7bb9b44 100644 --- a/src/sqlguardllm/session_limits.py +++ b/src/sqlguardllm/session_limits.py @@ -99,6 +99,7 @@ def __init__( fixed_aggregate_sources: Iterable[str] = (), cohorts: Mapping[str, tuple[str, int]] | None = None, cohort_max_members: int = 512, + cohort_id_filter_sources: Iterable[str] = (), ) -> None: if type(reject_offset) is not bool: raise ValueError("reject_offset must be true or false") @@ -139,6 +140,9 @@ def __init__( raise ValueError("cohorts must name fixed_aggregate_sources and an id column") self._cohort_columns[name] = column minimums[name] = minimum + self._cohort_id_filters = {source.casefold() for source in cohort_id_filter_sources} + if not self._cohort_id_filters <= self._cohort_columns.keys(): + raise ValueError("cohort_id_filter_sources must name sources configured in cohorts") self._cohort_max = cohort_max_members self._cohorts = ( AggregateCohorts(minimums, window_seconds, max_members=cohort_max_members) @@ -266,7 +270,7 @@ def matches_cursor(columns: exp.Expr, bounds: exp.Expr) -> bool: return True def permits_aggregate_shape(self, sql: str, dialect: str, tables: Iterable[str]) -> bool: - """Require direct whole-cohort aggregates on explicitly configured sources.""" + """Require direct aggregate projections and an eligible cohort selector.""" if not self._fixed_aggregate_sources: return True if not self._covered_tables(tables).intersection(self._fixed_aggregate_sources): @@ -276,7 +280,9 @@ def permits_aggregate_shape(self, sql: str, dialect: str, tables: Iterable[str]) except SqlglotError: return False if not isinstance(statement, exp.Select) or any( - value for key, value in statement.args.items() if key not in {"from_", "expressions"} + value + for key, value in statement.args.items() + if key not in {"from_", "expressions", "where"} ): return False source = statement.args.get("from_") @@ -291,6 +297,9 @@ def permits_aggregate_shape(self, sql: str, dialect: str, tables: Iterable[str]) return False if table.name.casefold() not in self._fixed_aggregate_sources: return False + where = statement.args.get("where") + if where is not None and not self._permits_cohort_filter(where, table, dialect): + return False for projection in statement.expressions: target = projection.this if isinstance(projection, exp.Alias) else projection if not isinstance(target, (exp.Count, exp.Sum, exp.Avg)): @@ -307,6 +316,31 @@ def permits_aggregate_shape(self, sql: str, dialect: str, tables: Iterable[str]) return False return bool(statement.expressions) + def _permits_cohort_filter(self, where: exp.Where, table: exp.Table, dialect: str) -> bool: + source = table.name.casefold() + if dialect not in {"sqlite", "postgres"} or source not in self._cohort_id_filters: + return False + predicate = where.this.unnest() + if not isinstance(predicate, (exp.EQ, exp.NEQ, exp.LT, exp.LTE, exp.GT, exp.GTE)): + return False + column = predicate.this.unnest() + literal = predicate.expression.unnest() + if not isinstance(column, exp.Column) or not isinstance(column.this, exp.Identifier): + return False + expected = self._cohort_columns[source].lower() + name = column.name if column.this.quoted and dialect == "postgres" else column.name.lower() + return bool( + name == expected + and (not column.table or column.table.casefold() == table.alias_or_name.casefold()) + and not column.db + and not column.catalog + and isinstance(literal, exp.Literal) + and literal.is_int + ) + + def uses_cohort_id_filters(self, tables: Iterable[str]) -> bool: + return bool(self._covered_tables(tables) & self._cohort_id_filters) + @property def has_cohorts(self) -> bool: """Whether cross-request cohort checks are configured.""" @@ -335,6 +369,10 @@ def membership_sql(self, sql: str, dialect: str, source: str) -> str | None: query = exp.select(exp.column(self._cohort_columns[source])).from_(origin.this.copy()) where = statement.args.get("where") if where is not None: + if source in self._cohort_id_filters and not self._permits_cohort_filter( + where, origin.this, dialect + ): + return None query = query.where(where.this.copy()) # Read one extra id to distinguish an exact fit from an incomplete cohort. return query.limit(self.cohort_limit(source) + 1).sql(dialect=dialect) diff --git a/tests/engines/test_row_budget_engines.py b/tests/engines/test_row_budget_engines.py index 6f3a138..eccabe7 100644 --- a/tests/engines/test_row_budget_engines.py +++ b/tests/engines/test_row_budget_engines.py @@ -121,6 +121,46 @@ async def verify_fixed_aggregate() -> None: ) anyio.run(verify_fixed_aggregate) + with engine.begin() as conn: + conn.exec_driver_sql( + f"INSERT INTO public.{table} SELECT id, 'x' FROM generate_series(4, 8) AS id" + ) + filtered_server = create_server( + Policy( + dialect="postgres", + tables={f"public.{table}"}, + aggregate_only={f"public.{table}": 2}, + ), + engine, + row_budgets=RowBudgets( + {table: 8}, + 60, + fixed_aggregate_sources=[table], + cohorts={table: ("id", 2)}, + cohort_id_filter_sources=[table], + ), + single_session=True, + ) + + async def verify_filtered_cohort() -> None: + sql = f"SELECT COUNT(*) FROM public.{table}" + with anyio.fail_after(30): + async with Client(filtered_server) as client: + total = await client.call_tool("query", {"sql": sql}) + near = await client.call_tool("query", {"sql": sql + " WHERE id <= 7"}) + separate = await client.call_tool("query", {"sql": sql + " WHERE id <= 5"}) + assert total.structured_content is not None + assert total.structured_content["rows"] == [[8]] + assert near.is_error and near.structured_content is None + assert any( + item.text.startswith("differencing:") + for item in near.content + if isinstance(item, TextContent) + ) + assert separate.structured_content is not None + assert separate.structured_content["rows"] == [[5]] + + anyio.run(verify_filtered_cohort) finally: with engine.begin() as conn: conn.exec_driver_sql(f"DROP TABLE IF EXISTS public.{table}") diff --git a/tests/test_mcp.py b/tests/test_mcp.py index 3810776..c2a461c 100644 --- a/tests/test_mcp.py +++ b/tests/test_mcp.py @@ -1025,6 +1025,41 @@ def record_read(_conn: Any, _cursor: Any, statement: str, *_args: Any) -> None: engine.dispose() +def test_filtered_cohorts_compare_actual_sqlite_memberships(url: str, db_path: Path) -> None: + for ident in range(4, 9): + _add_salary(db_path, ident) + budgets = RowBudgets( + {"salaries": 100}, + 60, + fixed_aggregate_sources=["salaries"], + cohorts={"salaries": ("id", 2)}, + cohort_id_filter_sources=["salaries"], + ) + server = create_server(make_policy(), url, row_budgets=budgets, single_session=True) + sql = "SELECT COUNT(*) FROM salaries" + assert call(server, "query", {"sql": sql})["rows"] == [[8]] + assert call_error(server, "query", {"sql": sql + " WHERE id <= 7"}).startswith("differencing:") + assert call(server, "query", {"sql": sql + " WHERE id <= 5"})["rows"] == [[5]] + assert call_error(server, "query", {"sql": sql + " WHERE amount > 10"}).startswith( + "aggregate_shape_restricted:" + ) + + +def test_filtered_cohorts_require_aggregate_only(url: str) -> None: + budgets = RowBudgets( + {"salaries": 100}, + 60, + fixed_aggregate_sources=["salaries"], + cohorts={"salaries": ("id", 2)}, + cohort_id_filter_sources=["salaries"], + ) + server = create_server( + make_policy(aggregate_only={}), url, row_budgets=budgets, single_session=True + ) + query = {"sql": "SELECT COUNT(*) FROM salaries WHERE id <= 2"} + assert call_error(server, "query", query).startswith("cohort_unavailable:") + + def test_cohort_config_must_name_a_fixed_source() -> None: with pytest.raises(ValueError, match="fixed_aggregate_sources"): RowBudgets({"salaries": 5}, 60, cohorts={"salaries": ("id", 2)}) From dfdaa28c8964915da7eaf5135450e28b5564dc4d Mon Sep 17 00:00:00 2001 From: Juan Manuel Castillo Pinto <33883620+jmmana@users.noreply.github.com> Date: Thu, 3 Dec 2026 20:55:26 -0500 Subject: [PATCH 2/2] Match the stable cohort refusal code inside MCP transport errors --- tests/engines/test_row_budget_engines.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/tests/engines/test_row_budget_engines.py b/tests/engines/test_row_budget_engines.py index eccabe7..2993d9c 100644 --- a/tests/engines/test_row_budget_engines.py +++ b/tests/engines/test_row_budget_engines.py @@ -153,10 +153,10 @@ async def verify_filtered_cohort() -> None: assert total.structured_content["rows"] == [[8]] assert near.is_error and near.structured_content is None assert any( - item.text.startswith("differencing:") + "differencing:" in item.text for item in near.content if isinstance(item, TextContent) - ) + ), near.content assert separate.structured_content is not None assert separate.structured_content["rows"] == [[5]]