From c94f10ffc85ffb1cc18a553c2c8e942c3255ff2f Mon Sep 17 00:00:00 2001 From: Behnam Ousat Date: Tue, 1 Dec 2026 17:44:25 -0800 Subject: [PATCH 1/2] FIX: Keep Azure SQL analytics heatmaps within the report budget On SQL Server, heatmaps compiled one large matrix statement whose compile time alone (6-9 s) exceeded the 5 s report budget, and stored JSON null harm categories made OPENJSON fail with error 13609. - Let SQL Server use the compact-profile path for harm-category and attack-type charts; the SDK aggregates raw harm arrays. - Check attack/converter identifier completeness once per identifier on SQL Server too, not by parsing each result's embedded JSON. - Pass only arrays to OPENJSON when expanding harm/converter memberships. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- doc/code/analytics/0_attack_results.md | 14 ++-- doc/contributing/11_memory_models.md | 3 +- pyrit/analytics/_profile_aggregation.py | 4 +- pyrit/memory/attack_analytics.py | 4 +- pyrit/memory/attack_analytics_query.py | 82 ++++++++++++++++------ tests/unit/memory/test_attack_analytics.py | 60 ++++++++++++++++ 6 files changed, 137 insertions(+), 30 deletions(-) diff --git a/doc/code/analytics/0_attack_results.md b/doc/code/analytics/0_attack_results.md index e9df9d06b1..e71cec75ec 100644 --- a/doc/code/analytics/0_attack_results.md +++ b/doc/code/analytics/0_attack_results.md @@ -581,12 +581,15 @@ statistics keep their separate population. ## Bounded profile aggregation and backend limits -For eligible SQLite category, attack-type, and converter-type charts, memory +For eligible SQLite category, attack-type, and converter-type charts, and SQL +Server category and attack-type charts, memory probes at most 4,097 pre-counted metadata profiles. It accepts at most 4,096, subject to 4,096-character source limits and a 1,000,000-character combined-text limit. The SDK expands their deduplicated memberships and sums saved-outcome weights, yielding between bounded batches. Converter arrays already contain the reader's canonical names, including supported legacy names and missing members. +On SQL Server this path also avoids compiling the full matrix statement, whose +compile time alone can exceed the report budget. Overflow selects the **complete SQL fallback**, never partial totals or sampling. `profiles=None` means SQL supplied the chart; `profiles=[]` is a valid empty @@ -594,10 +597,11 @@ cohort. The combined-text check happens after fetching the probe. These caps bou transferred profiles and SDK work, not SQL scans, intermediate SQL work, or peak network bytes. -Profile SQL decodes each distinct raw membership array once, removes duplicate +Profile SQL on SQLite decodes each distinct raw membership array once, removes duplicate members without changing their spellings, and sums weights of equivalent -profiles before applying the same caps. Every saved result still contributes -its full weight. For complete normalized attack/converter metadata, SQLite +profiles before applying the same caps. SQL Server returns raw category arrays +for the SDK to decode. Every saved result still contributes +its full weight. For complete normalized attack/converter metadata, memory checks completeness per identifier instead of per result; incomplete and legacy rows retain their embedded metadata. Identifier decoding is shared only within the query for an exact reference/document pair, so different embedded @@ -616,7 +620,7 @@ global settings, or response caching. SQLite reports preserve reader warnings about rollback journaling and never enable WAL themselves. Choose journaling and deployment settings explicitly outside the -SDK. SQL Server uses the reader's SQL path and requires its configured SNAPSHOT +SDK. SQL Server uses the reader's SQL path for other charts and requires its configured SNAPSHOT support. Cross-backend collation details, malformed historical metadata, and live Azure SQL validation remain storage/deployment concerns. diff --git a/doc/contributing/11_memory_models.md b/doc/contributing/11_memory_models.md index bc5d0585af..edd5d1bd2e 100644 --- a/doc/contributing/11_memory_models.md +++ b/doc/contributing/11_memory_models.md @@ -231,7 +231,8 @@ restores them when the session closes. SQL Server reports require SNAPSHOT support; analytics never changes server isolation settings or enables SQLite WAL automatically. Query errors propagate rather than returning empty reports. -The optional SQLite compact-profile probe returns typed raw `RawAnalyticsProfile` +The optional compact-profile probe (SQLite, and SQL Server for category and +attack-type charts) returns typed raw `RawAnalyticsProfile` dictionaries with `source0` and optional `source1`/display fields, stored `outcome`, and result-ID `weight` for a caller to aggregate, not statistics. For converter axes, the bounded probe emits canonical name arrays so supported diff --git a/pyrit/analytics/_profile_aggregation.py b/pyrit/analytics/_profile_aggregation.py index aeeadcae07..a0fb2d71ed 100644 --- a/pyrit/analytics/_profile_aggregation.py +++ b/pyrit/analytics/_profile_aggregation.py @@ -1,7 +1,7 @@ # Copyright (c) Microsoft Corporation. # Licensed under the MIT license. -"""Finish bounded SQLite metadata profiles using the complete SQL path's membership rules.""" +"""Finish bounded metadata profiles using the complete SQL path's membership rules.""" from __future__ import annotations @@ -36,7 +36,7 @@ class _Profile: class ProfileAggregation: """ - Expand only the reader-approved SQLite profiles, never an unbounded result set. + Expand only the reader-approved profiles, never an unbounded result set. Memory caps profile count and text size and falls back to complete SQL grouping on overflow. Converter sources already contain canonical names, including diff --git a/pyrit/memory/attack_analytics.py b/pyrit/memory/attack_analytics.py index 3432a43779..275a4d3117 100644 --- a/pyrit/memory/attack_analytics.py +++ b/pyrit/memory/attack_analytics.py @@ -78,7 +78,7 @@ class RawAnalyticsGroup: class RawAnalyticsProfile(TypedDict): - """One pre-counted, bounded metadata tuple for the optional SQLite fast path.""" + """One pre-counted, bounded metadata tuple for the optional compact-profile fast path.""" source0: str | None outcome: str @@ -169,7 +169,7 @@ async def report_async( query (AttackAnalyticsQuery): Validated cohort, dimensions, and output limits. control (QueryControl): Shared deadline/cancellation signal for the whole operation. use_compact_profiles (bool): Allow the SDK to finish aggregation from bounded - SQLite profiles. False keeps chart aggregation entirely in SQL. + profiles where the compiler supports them. False keeps chart aggregation entirely in SQL. Returns: RawAnalyticsReport: Raw counts and bounded projections, or profiles that diff --git a/pyrit/memory/attack_analytics_query.py b/pyrit/memory/attack_analytics_query.py index 99647d2dfa..2350a19e72 100644 --- a/pyrit/memory/attack_analytics_query.py +++ b/pyrit/memory/attack_analytics_query.py @@ -11,7 +11,7 @@ harm categories. ``_group_compiler`` describes the indexed/legacy fact split. SQL returns bounded chart/page projections, but the database still considers the -entire filtered cohort. The optional SQLite profile query instead transfers a +entire filtered cohort. The optional compact profile query instead transfers a strictly capped set of pre-counted profiles to the SDK; it never samples results. No statement joins scores, messages, or conversation histories. """ @@ -212,9 +212,13 @@ def compact_profiles( self, *, query: AttackAnalyticsQuery, limit: int, max_value_length: int ) -> Select[*tuple[Any, ...]] | None: """ - Offer the SQLite fast path before expanding categorical arrays. + Offer the fast path that leaves categorical array expansion to the SDK. - Only harm category, attack type, and converter type use this path. The + Only harm category, attack type, and converter type use this path. SQLite + canonicalizes arrays first, including converter identifier objects. SQL + Server returns raw harm arrays and excludes converters, whose legacy + objects only SQLite canonicalizes; this also avoids compiling the full + matrix statement, which can exceed the report budget on SQL Server. The reader asks for one extra profile to detect overflow, checks per-value and combined text limits, and falls back to SQL grouping if any limit is exceeded. Oversized strings are replaced with NULL only in this rejected @@ -230,11 +234,18 @@ def compact_profiles( ``oversized`` flag, or None when the general SQL path is required. """ dimensions = [query.group_by] + ([query.compare_by] if query.compare_by is not None else []) - if self.dialect != "sqlite" or not all( - dimension.name in self._COMPACT_MATRIX_DIMENSIONS for dimension in dimensions - ): + if not all(dimension.name in self._COMPACT_MATRIX_DIMENSIONS for dimension in dimensions): return None compiler = self._group_compiler(dimensions) + if self.dialect == "mssql": + if any(dimension.name is AttackAnalyticsDimensionName.CONVERTER_TYPE for dimension in dimensions): + return None + return self._bounded_profiles( + profiles=compiler._compact_profile_inputs(dimensions), + dimensions=len(dimensions), + limit=limit, + max_value_length=max_value_length, + ) profiles = self._materialize_sqlite(compiler._compact_profile_inputs(dimensions)) origin: FromClause = profiles arrays: dict[str, ColumnElement[Any]] = {} @@ -270,13 +281,27 @@ def compact_profiles( .group_by(*keys) .cte("distinct_analytics_profiles") ) + return self._bounded_profiles( + profiles=canonical, dimensions=len(dimensions), limit=limit, max_value_length=max_value_length + ) + + @staticmethod + def _bounded_profiles( + *, profiles: CTE, dimensions: int, limit: int, max_value_length: int + ) -> Select[*tuple[Any, ...]]: + """ + Flag and blank oversized text so the reader can reject the probe before decoding it. + + Returns: + Select[Any]: At most ``limit`` profiles with an ``oversized`` flag. + """ oversized = or_( *[ and_( - canonical.c[f"source{index}"].isnot(None), - func.length(canonical.c[f"source{index}"]) > max_value_length, + profiles.c[f"source{index}"].isnot(None), + func.length(profiles.c[f"source{index}"]) > max_value_length, ) - for index in range(len(dimensions)) + for index in range(dimensions) ] ) return select( @@ -286,9 +311,9 @@ def compact_profiles( if key.startswith(("source", "display")) else value ) - for key, value in canonical.c.items() + for key, value in profiles.c.items() ], - oversized.label("oversized"), + case((oversized, True), else_=False).label("oversized"), ).limit(limit) def _compact_profile_inputs(self, dimensions: list[AttackAnalyticsDimension]) -> CTE: @@ -336,7 +361,7 @@ def _compact_profile_inputs(self, dimensions: list[AttackAnalyticsDimension]) -> ) for index, (dimension, source) in enumerate(zip(dimensions, sources, strict=True)) ] - return self._profiles(projected) + return self._profiles(projected, force_projection=True) def _profile_array( self, *, profile: CTE, raw: ColumnElement[Any], name: str, converters: bool @@ -1144,8 +1169,7 @@ def _predicate(self, predicate: AttackAnalyticsFilter, *, index: int) -> ColumnE ) self._filter_projections[index] = projected[0] raw = projected[0] - items = JsonArrayItems(raw).table_valued(column("key"), column("value"), column("type")) - items = items.alias(f"filter_items_{index}") + items = self._array_items(raw=raw, name=f"filter_items_{index}") kind, value, _ = self._array_key(source=source, raw=raw, items=items) matches: list[ColumnElement[bool]] = [] if values: @@ -1436,12 +1460,13 @@ def _group_compiler(self, dimensions: list[AttackAnalyticsDimension]) -> AttackA for name, value in values.items() } identifier_dimensions = [dimension for dimension in dimensions if dimension.name in self._IDENTIFIER_DIMENSIONS] - if self.dialect == "sqlite" and all( + if all( dimension.name in {AttackAnalyticsDimensionName.ATTACK_TYPE, AttackAnalyticsDimensionName.CONVERTER_TYPE} for dimension in identifier_dimensions ): # These normalized values always win over embedded JSON. Resolve - # completeness once per identifier, not again for every saved result. + # completeness once per identifier, not again for every saved result; + # other rows keep their embedded JSON in the legacy branches. for dimension in identifier_dimensions: valid_atomic = valid_atomic.where( AttackIdentifierEntry.class_name.isnot(None) @@ -1495,7 +1520,7 @@ def _group_compiler(self, dimensions: list[AttackAnalyticsDimension]) -> AttackA dialect=self.dialect, filters=AttackAnalyticsFilters(), root=facts, label_columns=label_columns ) - def _profiles(self, sources: list[_Source], *, counts: bool = True) -> CTE: + def _profiles(self, sources: list[_Source], *, counts: bool = True, force_projection: bool = False) -> CTE: """ Coalesce equal raw source tuples before expanding any array memberships. @@ -1503,6 +1528,8 @@ def _profiles(self, sources: list[_Source], *, counts: bool = True) -> CTE: sources (list[_Source]): Axis expressions, including scalar display labels and kinds. counts (bool): Include outcome and weight for charts. False selects only distinct raw metadata for facets, with no outcome aggregation. + force_projection (bool): Project every grouping key on SQL Server, for sources + read from a CTE that SQL Server inlines with its JSON subqueries. Returns: CTE: One row per raw source/display tuple and outcome, with ``weight`` @@ -1518,7 +1545,9 @@ def _profiles(self, sources: list[_Source], *, counts: bool = True) -> CTE: values.append(self._grouping_text(source.label).label(f"display{index}")) if source.kind is not None: values.append(self._grouping_text(source.kind).label(f"source_kind{index}")) - origin, values = self._grouping_projection(origin=self._from, values=values, name="profile_values") + origin, values = self._grouping_projection( + origin=self._from, values=values, name="profile_values", force=force_projection + ) if not counts: return select(*values).select_from(origin).where(*conditions).distinct().cte("analytics_profiles") weight = func.sum(self.root.c.analytics_weight) if "analytics_weight" in self.root.c else func.count() @@ -1574,8 +1603,7 @@ def _memberships(self, *, profiles: CTE, sources: list[_Source], dimensions: lis source = sources[index] raw = profiles.c[f"source{index}"] if source.array: - items = JsonArrayItems(raw).table_valued(column("key"), column("value"), column("type")) - items = items.alias(f"{name}_items{index}") + items = self._array_items(raw=raw, name=f"{name}_items{index}") origin = JsonArrayJoin(origin, items, true(), isouter=True) kind, value, label = self._array_key(source=source, raw=raw, items=items) else: @@ -1628,6 +1656,20 @@ def _scalar_key( kind = case((value.is_(None), "missing"), else_="value") return kind, self._collate(func.coalesce(key, "")), label + def _array_items(self, *, raw: ColumnElement[Any], name: str) -> FromClause: + """ + Expand a saved array's members, yielding no rows for SQL NULL or a non-array value. + + SQL Server's OPENJSON raises on scalar JSON such as a stored ``null``, even + when the row is already classified as missing, so it only receives arrays. + ``_array_key`` still classifies non-arrays from the raw value. + + Returns: + FromClause: A correlated expansion exposing key, value, and type. + """ + document = case((JsonIsArray(raw) == true(), raw)) if self.dialect == "mssql" else raw + return JsonArrayItems(document).table_valued(column("key"), column("value"), column("type")).alias(name) + def _array_key( self, *, source: _Source, raw: ColumnElement[Any], items: FromClause ) -> tuple[ColumnElement[Any], ColumnElement[Any], ColumnElement[Any]]: diff --git a/tests/unit/memory/test_attack_analytics.py b/tests/unit/memory/test_attack_analytics.py index 70763fc488..60db9f1666 100644 --- a/tests/unit/memory/test_attack_analytics.py +++ b/tests/unit/memory/test_attack_analytics.py @@ -1412,6 +1412,66 @@ def test_mssql_array_group_keys_do_not_contain_subqueries_or_bare_bit_predicates assert "NOT LIKE '['" not in sql +def test_mssql_array_expansions_only_pass_arrays_to_openjson() -> None: + # OPENJSON raises on a stored JSON null, so expansions must not receive raw columns. + query = AttackAnalyticsQuery( + filters=AttackAnalyticsFilters( + dimensions=[ + AttackAnalyticsFilter( + dimension=AttackAnalyticsDimension(name="targeted_harm_category"), + values=[AttackAnalyticsValue(kind="missing"), AttackAnalyticsValue(value="privacy")], + ) + ] + ), + group_by=AttackAnalyticsDimension(name="targeted_harm_category"), + compare_by=AttackAnalyticsDimension(name="objective_target"), + ) + compiler = AttackAnalyticsQueryCompiler(dialect="mssql", filters=query.filters) + sql = str( + compiler.matrix(query).compile( + dialect=mssql.dialect(deprecate_large_types=True), compile_kwargs={"literal_binds": True} + ) + ) + assert "OPENJSON(CASE WHEN" in sql + assert not re.search(r"OPENJSON\([\w.]+\)", sql) + + +def test_mssql_compact_profiles_avoid_membership_expansion() -> None: + query = AttackAnalyticsQuery( + group_by=AttackAnalyticsDimension(name="targeted_harm_category"), + compare_by=AttackAnalyticsDimension(name="attack_type"), + ) + statement = AttackAnalyticsQueryCompiler(dialect="mssql", filters=query.filters).compact_profiles( + query=query, limit=10, max_value_length=5 + ) + assert statement is not None + sql = str( + statement.compile(dialect=mssql.dialect(deprecate_large_types=True), compile_kwargs={"literal_binds": True}) + ) + assert "OUTER APPLY OPENJSON" not in sql + assert "THEN 1 ELSE 0 END AS oversized" in sql + + +@pytest.mark.parametrize("compare_by", ["converter_type", "objective_target"]) +def test_mssql_compact_profiles_decline_unsupported_axes(compare_by: str) -> None: + query = AttackAnalyticsQuery( + group_by=AttackAnalyticsDimension(name="targeted_harm_category"), + compare_by=AttackAnalyticsDimension(name=compare_by), + ) + compiler = AttackAnalyticsQueryCompiler(dialect="mssql", filters=query.filters) + assert compiler.compact_profiles(query=query, limit=10, max_value_length=5) is None + + +def test_mssql_attack_type_compaction_checks_completeness_per_identifier() -> None: + # Per-result completeness parses each saved result's embedded identifier JSON. + query = AttackAnalyticsQuery(group_by=AttackAnalyticsDimension(name="attack_type")) + compiler = AttackAnalyticsQueryCompiler(dialect="mssql", filters=query.filters) + with patch.object( + AttackAnalyticsQueryCompiler, "_complete_identifier_source", side_effect=AssertionError("per-result check") + ): + compiler.groups(query).compile(dialect=mssql.dialect(deprecate_large_types=True)) + + def test_mssql_compaction_keeps_exact_label_keys_before_membership_grouping() -> None: query = AttackAnalyticsQuery( group_by=AttackAnalyticsDimension(name="label", label_key="team"), From 15192795eda106253ef3090985ffd34125faa998 Mon Sep 17 00:00:00 2001 From: Behnam Ousat Date: Wed, 2 Dec 2026 09:24:31 -0800 Subject: [PATCH 2/2] FIX: Use SQL Server LOWER for compact analytics chart keys Python str.lower differs from SQL Server LOWER (for example final sigma, dotted capital I, and characters newer than the collation's Unicode tables), so compact-profile chart keys could disagree with SQL grouping and drilldown. SQL Server profiles now return LOWER(source) as key0/key1 and the SDK uses those keys. LOWER over serialized JSON cannot fold \u-escaped members, so such probes fall back to the SQL path. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- pyrit/analytics/_profile_aggregation.py | 42 +++++++++++--- pyrit/memory/attack_analytics.py | 14 +++++ pyrit/memory/attack_analytics_query.py | 15 +++-- .../analytics/test_profile_aggregation.py | 57 ++++++++++++++++++- tests/unit/memory/test_attack_analytics.py | 2 + 5 files changed, 117 insertions(+), 13 deletions(-) diff --git a/pyrit/analytics/_profile_aggregation.py b/pyrit/analytics/_profile_aggregation.py index a0fb2d71ed..ec17da0294 100644 --- a/pyrit/analytics/_profile_aggregation.py +++ b/pyrit/analytics/_profile_aggregation.py @@ -93,25 +93,39 @@ def _profile( if record["oversized"]: raise AnalyticsDataException("Oversized metadata profiles require complete SQL aggregation.") sources = [record["source0"]] + database_keys = [record.get("key0")] if len(dimensions) == 2: if "source1" not in record: raise AnalyticsDataException("A comparison profile is missing its second dimension.") sources.append(record["source1"]) + database_keys.append(record.get("key1")) + has_database_keys = "key0" in record values = [] - for raw, dimension, options in zip(sources, dimensions, cache, strict=True): + for raw, database_key, dimension, options in zip(sources, database_keys, dimensions, cache, strict=True): if raw not in options: - options[raw] = cls._values(raw=raw, dimension=dimension) + options[raw] = cls._values( + raw=raw, dimension=dimension, database_key=database_key, has_database_key=has_database_keys + ) values.append(options[raw]) return _Profile(values=values, outcome=record["outcome"], weight=record["weight"]) @classmethod - def _values(cls, *, raw: str | None, dimension: AttackAnalyticsDimension) -> dict[ValueKey, RawAnalyticsOption]: + def _values( + cls, + *, + raw: str | None, + dimension: AttackAnalyticsDimension, + database_key: str | None = None, + has_database_key: bool = False, + ) -> dict[ValueKey, RawAnalyticsOption]: """ Decode scalar attack names or canonical category/converter name arrays. JSON null and null members mean missing metadata. Empty harm arrays are missing; empty converter arrays mean a known pipeline with no converters. Scalar attack names and real blank strings are not JSON absence markers. + A database-lowered key (SQL Server ``LOWER`` of ``raw``) replaces Python + lowercasing so keys match that backend's SQL grouping and drilldown. Returns: dict[ValueKey, RawAnalyticsOption]: One representative option per typed key. @@ -120,7 +134,7 @@ def _values(cls, *, raw: str | None, dimension: AttackAnalyticsDimension) -> dic AnalyticsDataException: If an unsupported dimension or malformed array reaches this path. """ if dimension.name is AttackAnalyticsDimensionName.ATTACK_TYPE: - return cls._options([raw]) + return cls._options([raw], keys=[database_key] if has_database_key else None) if dimension.name not in { AttackAnalyticsDimensionName.TARGETED_HARM_CATEGORY, AttackAnalyticsDimensionName.CONVERTER_TYPE, @@ -130,10 +144,17 @@ def _values(cls, *, raw: str | None, dimension: AttackAnalyticsDimension) -> dic return cls._options([None]) try: values = json.loads(raw) + keys = json.loads(database_key) if has_database_key and database_key is not None else None except json.JSONDecodeError as error: raise AnalyticsDataException("Stored category/converter metadata is invalid JSON.") from error if not isinstance(values, list): raise AnalyticsDataException("Stored category/converter metadata is not an array.") + if has_database_key and ( + not isinstance(keys, list) + or len(keys) != len(values) + or not all(key is None or isinstance(key, str) for key in keys) + ): + raise AnalyticsDataException("Database-lowered category keys do not match their stored array.") if not values: kind = ( AttackAnalyticsValueKind.NO_CONVERTERS @@ -141,15 +162,18 @@ def _values(cls, *, raw: str | None, dimension: AttackAnalyticsDimension) -> dic else AttackAnalyticsValueKind.MISSING ) return {(kind.value, ""): RawAnalyticsOption(key=AttackAnalyticsValue(kind=kind), label=None)} - return cls._options(values) + return cls._options(values, keys=keys) @classmethod - def _options(cls, values: list[object]) -> dict[ValueKey, RawAnalyticsOption]: + def _options( + cls, values: list[object], *, keys: list[str | None] | None = None + ) -> dict[ValueKey, RawAnalyticsOption]: """ Match SQLite's registered UnicodeLower function, which uses Python str.lower. Do not use ASCII translation or casefold. Keys fold Unicode but display labels retain the binary-smallest original spelling, matching SQL MIN. + ``keys`` supplies already-lowered keys from another backend, by position. Returns: dict[ValueKey, RawAnalyticsOption]: Deduplicated memberships. @@ -158,14 +182,16 @@ def _options(cls, values: list[object]) -> dict[ValueKey, RawAnalyticsOption]: AnalyticsDataException: If a member is not text/NULL or its folded key exceeds the contract. """ options: dict[ValueKey, RawAnalyticsOption] = {} - for label in values: + if keys is None: + keys = [label.lower() if isinstance(label, str) else None for label in values] + for label, folded in zip(values, keys, strict=True): if label is not None and not isinstance(label, str): raise AnalyticsDataException("Stored category/converter metadata contains a non-string value.") try: key = ( AttackAnalyticsValue(kind=AttackAnalyticsValueKind.MISSING) if label is None - else AttackAnalyticsValue(value=label.lower()) + else AttackAnalyticsValue(value=folded) ) except ValidationError as error: raise AnalyticsDataException( diff --git a/pyrit/memory/attack_analytics.py b/pyrit/memory/attack_analytics.py index 275a4d3117..cf0a68025a 100644 --- a/pyrit/memory/attack_analytics.py +++ b/pyrit/memory/attack_analytics.py @@ -87,6 +87,8 @@ class RawAnalyticsProfile(TypedDict): source1: NotRequired[str | None] display0: NotRequired[str | None] display1: NotRequired[str | None] + key0: NotRequired[str | None] + key1: NotRequired[str | None] @dataclass @@ -339,6 +341,14 @@ async def _read_compact_profiles_async( text_length = sum(len(value) for record in records for value in record.values() if isinstance(value, str)) if text_length > self.MAX_COMPACT_TOTAL_LENGTH: return None + # LOWER over serialized JSON cannot fold \u-escaped members; let SQL fold their decoded values. + if any( + "\\u" in value + for record in records + for name, value in record.items() + if name.startswith("key") and isinstance(value, str) + ): + return None return [self._raw_profile(record) for record in records] @classmethod @@ -367,6 +377,10 @@ def _raw_profile(cls, record: RowMapping) -> RawAnalyticsProfile: profile["display0"] = cls._raw_profile_text(record["display0"]) if "display1" in record: profile["display1"] = cls._raw_profile_text(record["display1"]) + if "key0" in record: + profile["key0"] = cls._raw_profile_text(record["key0"]) + if "key1" in record: + profile["key1"] = cls._raw_profile_text(record["key1"]) return profile @staticmethod diff --git a/pyrit/memory/attack_analytics_query.py b/pyrit/memory/attack_analytics_query.py index 2350a19e72..802e793dcc 100644 --- a/pyrit/memory/attack_analytics_query.py +++ b/pyrit/memory/attack_analytics_query.py @@ -218,8 +218,10 @@ def compact_profiles( canonicalizes arrays first, including converter identifier objects. SQL Server returns raw harm arrays and excludes converters, whose legacy objects only SQLite canonicalizes; this also avoids compiling the full - matrix statement, which can exceed the report budget on SQL Server. The - reader asks for one extra profile to detect overflow, checks per-value + matrix statement, which can exceed the report budget on SQL Server. SQL + Server also returns ``key{index}``, its own ``LOWER`` of each source, so + chart keys match SQL grouping and drilldown rather than Python lowercasing. + The reader asks for one extra profile to detect overflow, checks per-value and combined text limits, and falls back to SQL grouping if any limit is exceeded. Oversized strings are replaced with NULL only in this rejected probe; they must never be interpreted as missing metadata. @@ -240,8 +242,13 @@ def compact_profiles( if self.dialect == "mssql": if any(dimension.name is AttackAnalyticsDimensionName.CONVERTER_TYPE for dimension in dimensions): return None + profiles = compiler._compact_profile_inputs(dimensions) + keyed = select( + *profiles.c, + *[UnicodeLower(profiles.c[f"source{index}"]).label(f"key{index}") for index in range(len(dimensions))], + ).cte("keyed_analytics_profiles") return self._bounded_profiles( - profiles=compiler._compact_profile_inputs(dimensions), + profiles=keyed, dimensions=len(dimensions), limit=limit, max_value_length=max_value_length, @@ -308,7 +315,7 @@ def _bounded_profiles( *[ ( case((func.length(value) > max_value_length, None), else_=value).label(key) - if key.startswith(("source", "display")) + if key.startswith(("source", "display", "key")) else value ) for key, value in profiles.c.items() diff --git a/tests/unit/analytics/test_profile_aggregation.py b/tests/unit/analytics/test_profile_aggregation.py index 38165ea2bb..314fab6f93 100644 --- a/tests/unit/analytics/test_profile_aggregation.py +++ b/tests/unit/analytics/test_profile_aggregation.py @@ -11,7 +11,7 @@ from unittest.mock import patch import pytest -from sqlalchemy import text, update +from sqlalchemy import literal, select, text, update from pyrit.analytics._profile_aggregation import ProfileAggregation from pyrit.exceptions.analytics_exception import AnalyticsDataException, AnalyticsTimeoutException @@ -415,6 +415,61 @@ def test_profile_decoder_rejects_lowercase_expansion_beyond_key_limit() -> None: ProfileAggregation._values(raw="\u0130" * 4096, dimension=AttackAnalyticsDimension(name="attack_type")) +async def test_database_keys_replace_python_lowercasing() -> None: + # SQL Server LOWER maps a final sigma to σ, where Python's str.lower gives ς. + records: list[RawAnalyticsProfile] = [ + { + "source0": '["\u039f\u03a3"]', + "key0": '["\u03bf\u03c3"]', + "source1": "\u039f\u03a3Attack", + "key1": "\u03bf\u03c3attack", + "weight": 2, + "outcome": "success", + "oversized": False, + } + ] + query = AttackAnalyticsQuery( + group_by=AttackAnalyticsDimension(name="targeted_harm_category"), + compare_by=AttackAnalyticsDimension(name="attack_type"), + ) + report = _report(records) + await ProfileAggregation.populate_async(report=report, query=query, control=control()) + assert [(row.key.value, row.label) for row in report.rows] == [("\u03bf\u03c3", "\u039f\u03a3")] + assert [(column.key.value, column.label) for column in report.columns] == [ + ("\u03bf\u03c3attack", "\u039f\u03a3Attack") + ] + assert [cell.counts for cell in report.cells] == [{"success": 2}] + + +def test_database_keys_must_align_with_the_stored_array() -> None: + with pytest.raises(AnalyticsDataException, match="do not match"): + ProfileAggregation._values( + raw='["A", "B"]', + dimension=AttackAnalyticsDimension(name="targeted_harm_category"), + database_key='["a"]', + has_database_key=True, + ) + + +async def test_escaped_database_keys_fall_back_to_sql(sqlite_instance: SQLiteMemory) -> None: + probe = select( + literal('["\\u00c9"]').label("source0"), + literal('["\\u00e9"]').label("key0"), + literal("success").label("outcome"), + literal(1).label("weight"), + literal(False).label("oversized"), + ) + reader = AttackAnalyticsReader(memory=sqlite_instance) + query = AttackAnalyticsQuery(group_by=AttackAnalyticsDimension(name="targeted_harm_category")) + compiler = AttackAnalyticsQueryCompiler(dialect="sqlite", filters=query.filters) + async with await sqlite_instance.get_session_async() as session: + with patch.object(compiler, "compact_profiles", return_value=probe): + profiles = await reader._read_compact_profiles_async( + session=session, compiler=compiler, query=query, control=control() + ) + assert profiles is None + + def _report(profiles: list[RawAnalyticsProfile]) -> RawAnalyticsReport: return RawAnalyticsReport( counts={}, diff --git a/tests/unit/memory/test_attack_analytics.py b/tests/unit/memory/test_attack_analytics.py index 60db9f1666..4717b58d57 100644 --- a/tests/unit/memory/test_attack_analytics.py +++ b/tests/unit/memory/test_attack_analytics.py @@ -1450,6 +1450,8 @@ def test_mssql_compact_profiles_avoid_membership_expansion() -> None: ) assert "OUTER APPLY OPENJSON" not in sql assert "THEN 1 ELSE 0 END AS oversized" in sql + assert "LOWER(analytics_profiles.source0) AS key0" in sql + assert "LOWER(analytics_profiles.source1) AS key1" in sql @pytest.mark.parametrize("compare_by", ["converter_type", "objective_target"])