Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 9 additions & 5 deletions doc/code/analytics/0_attack_results.md
Original file line number Diff line number Diff line change
Expand Up @@ -581,23 +581,27 @@ 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
cohort. The combined-text check happens after fetching the probe. These caps bound
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
Expand All @@ -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.

Expand Down
3 changes: 2 additions & 1 deletion doc/contributing/11_memory_models.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
46 changes: 36 additions & 10 deletions pyrit/analytics/_profile_aggregation.py
Original file line number Diff line number Diff line change
@@ -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

Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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.
Expand All @@ -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,
Expand All @@ -130,26 +144,36 @@ 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
if dimension.name is AttackAnalyticsDimensionName.CONVERTER_TYPE
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.
Expand All @@ -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(
Expand Down
18 changes: 16 additions & 2 deletions pyrit/memory/attack_analytics.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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
Expand Down Expand Up @@ -169,7 +171,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
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down
Loading
Loading