:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
refactor(error-tracking): thin views onto the facade (#64262)
Hugues Pouillot841ddeaa5253
diff --git a/products/error_tracking/backend/facade/__init__.py b/products/error_tracking/backend/facade/__init__.pyindex de0421fe2892..6fc78f3730e2 100644--- a/products/error_tracking/backend/facade/__init__.py+++ b/products/error_tracking/backend/facade/__init__.py@@ -2,16 +2,29 @@ from . import contractsfrom .api import (ExternalReferenceValidationError,IssueNotFoundError,+ ReleaseHashInUseError,auto_select_project_for_user,+ batch_get_stack_frames,build_ingestion_failures_url,count_issues_created_since,+ create_assignment_rule,create_external_reference,+ create_grouping_rule,+ create_release,+ create_suppression_rule,+ delete_assignment_rule,+ delete_grouping_rule,+ delete_release,+ delete_suppression_rule,+ get_assignment_rule,+ get_client_safe_suppression_rules,get_crash_free_sessions,get_daily_exception_counts,get_exception_counts,get_exception_summary_for_team,get_external_reference,get_fingerprint,+ get_grouping_rule,get_issue,get_issue_assignment_for_notification,get_issue_counts_by_team,@@ -19,29 +32,64 @@ from .api import (get_issue_values,get_new_issues_for_team,get_org_ids_with_exceptions,+ get_release,+ get_release_by_hash,+ get_settings,+ get_spike_detection_config,+ get_stack_frame,+ get_suppression_rule,get_symbol_set_counts_by_team,get_top_issues_for_team,+ has_filter_values,is_supported_external_issue_provider,issue_exists,+ list_assignment_rules,list_external_references,list_fingerprints,+ list_grouping_rules,list_issues,+ list_releases,+ list_spike_events,+ list_stack_frames,+ list_suppression_rules,+ reorder_assignment_rules,+ reorder_grouping_rules,+ reorder_suppression_rules,+ update_assignment_rule,+ update_grouping_rule,+ update_release,+ update_settings,+ update_spike_detection_config,+ update_suppression_rule,)__all__ = ["ExternalReferenceValidationError","IssueNotFoundError",+ "ReleaseHashInUseError","auto_select_project_for_user",+ "batch_get_stack_frames","build_ingestion_failures_url",+ "contracts","count_issues_created_since",+ "create_assignment_rule","create_external_reference",+ "create_grouping_rule",+ "create_release",+ "create_suppression_rule",+ "delete_assignment_rule",+ "delete_grouping_rule",+ "delete_release",+ "delete_suppression_rule",+ "get_assignment_rule",+ "get_client_safe_suppression_rules","get_crash_free_sessions","get_daily_exception_counts","get_exception_counts","get_exception_summary_for_team",- "contracts","get_external_reference","get_fingerprint",+ "get_grouping_rule","get_issue","get_issue_assignment_for_notification","get_issue_counts_by_team",@@ -49,11 +97,33 @@ __all__ = ["get_issue_values","get_new_issues_for_team","get_org_ids_with_exceptions",+ "get_release",+ "get_release_by_hash",+ "get_settings",+ "get_spike_detection_config",+ "get_stack_frame",+ "get_suppression_rule","get_symbol_set_counts_by_team","get_top_issues_for_team",+ "has_filter_values","is_supported_external_issue_provider","issue_exists",+ "list_assignment_rules","list_external_references","list_fingerprints",+ "list_grouping_rules","list_issues",+ "list_releases",+ "list_spike_events",+ "list_stack_frames",+ "list_suppression_rules",+ "reorder_assignment_rules",+ "reorder_grouping_rules",+ "reorder_suppression_rules",+ "update_assignment_rule",+ "update_grouping_rule",+ "update_release",+ "update_settings",+ "update_spike_detection_config",+ "update_suppression_rule",]diff --git a/products/error_tracking/backend/facade/api.py b/products/error_tracking/backend/facade/api.pyindex 873556ec3d6e..c40ec03251f9 100644--- a/products/error_tracking/backend/facade/api.py+++ b/products/error_tracking/backend/facade/api.py@@ -8,6 +8,7 @@ from typing import Anyfrom uuid import UUIDimport posthoganalytics+from rest_framework.exceptions import ValidationErrorfrom posthog.event_usage import groups@@ -16,6 +17,7 @@ from . import contractsIssueNotFoundError = logic.ErrorTrackingIssueNotFoundErrorExternalReferenceValidationError = logic.ErrorTrackingExternalReferenceValidationError+ReleaseHashInUseError = logic.ErrorTrackingReleaseHashInUseErrordef _to_issue_assignee(assignment) -> contracts.ErrorTrackingIssueAssignee | None:@@ -118,6 +120,332 @@ def issue_exists(team_id: int) -> bool:return logic.issue_exists(team_id=team_id)+def _to_settings(settings) -> contracts.ErrorTrackingSettings:+ return contracts.ErrorTrackingSettings(+ project_rate_limit_value=settings.project_rate_limit_value,+ project_rate_limit_bucket_size_minutes=settings.project_rate_limit_bucket_size_minutes,+ per_issue_rate_limit_value=settings.per_issue_rate_limit_value,+ per_issue_rate_limit_bucket_size_minutes=settings.per_issue_rate_limit_bucket_size_minutes,+ )+++def get_settings(team_id: int) -> contracts.ErrorTrackingSettings:+ return _to_settings(logic.get_or_create_settings(team_id))+++def update_settings(team_id: int, fields: dict[str, int | None]) -> contracts.ErrorTrackingSettings:+ return _to_settings(logic.update_settings(team_id=team_id, fields=fields))+++def _to_spike_detection_config(config) -> contracts.ErrorTrackingSpikeDetectionConfig:+ return contracts.ErrorTrackingSpikeDetectionConfig(+ snooze_duration_minutes=config.snooze_duration_minutes,+ multiplier=config.multiplier,+ threshold=config.threshold,+ )+++def get_spike_detection_config(team_id: int) -> contracts.ErrorTrackingSpikeDetectionConfig:+ return _to_spike_detection_config(logic.get_or_create_spike_detection_config(team_id))+++def update_spike_detection_config(team_id: int, fields: dict[str, int]) -> contracts.ErrorTrackingSpikeDetectionConfig:+ return _to_spike_detection_config(logic.update_spike_detection_config(team_id=team_id, fields=fields))+++def _to_spike_event(event) -> contracts.ErrorTrackingSpikeEvent:+ issue = event.issue+ return contracts.ErrorTrackingSpikeEvent(+ id=event.id,+ issue=contracts.ErrorTrackingSpikeEventIssue(id=issue.id, name=issue.name, description=issue.description),+ detected_at=event.detected_at,+ computed_baseline=event.computed_baseline,+ current_bucket_value=event.current_bucket_value,+ )+++def list_spike_events(+ *,+ team_id: int,+ issue_ids: list[str] | None = None,+ date_from: str | None = None,+ date_to: str | None = None,+ order_by: str | None = None,+ limit: int | None = None,+ offset: int = 0,+) -> tuple[list[contracts.ErrorTrackingSpikeEvent], int]:+ qs = logic.list_spike_events(+ team_id=team_id, issue_ids=issue_ids, date_from=date_from, date_to=date_to, order_by=order_by+ )+ total = qs.count()+ rows = qs if limit is None else qs[offset : offset + limit]+ return [_to_spike_event(event) for event in rows], total+++def _to_release(release) -> contracts.ErrorTrackingRelease:+ return contracts.ErrorTrackingRelease(+ id=release.id,+ hash_id=release.hash_id,+ team_id=release.team_id,+ created_at=release.created_at,+ metadata=release.metadata,+ version=release.version,+ project=release.project,+ )+++def _to_stack_frame(frame) -> contracts.ErrorTrackingStackFrame:+ symbol_set = frame.symbol_set+ release = symbol_set.release if symbol_set else None+ return contracts.ErrorTrackingStackFrame(+ id=frame.id,+ raw_id=f"{frame.raw_id}/{frame.part}",+ created_at=frame.created_at,+ contents=frame.contents,+ resolved=frame.resolved,+ context=frame.context,+ symbol_set_ref=symbol_set.ref if symbol_set else None,+ release=_to_release(release) if release else None,+ )+++def list_stack_frames(+ team_id: int, *, limit: int | None = None, offset: int = 0+) -> tuple[list[contracts.ErrorTrackingStackFrame], int]:+ qs = logic.stack_frame_queryset(team_id)+ total = qs.count()+ rows = qs if limit is None else qs[offset : offset + limit]+ return [_to_stack_frame(frame) for frame in rows], total+++def get_stack_frame(team_id: int, frame_id: str) -> contracts.ErrorTrackingStackFrame | None:+ frame = logic.get_stack_frame(team_id, frame_id)+ return _to_stack_frame(frame) if frame is not None else None+++def batch_get_stack_frames(+ team_id: int, raw_ids: list[str] | None = None, symbol_set: str | None = None+) -> list[contracts.ErrorTrackingStackFrame]:+ return [_to_stack_frame(frame) for frame in logic.batch_get_stack_frames(team_id, raw_ids, symbol_set)]+++def list_releases(+ team_id: int, *, limit: int | None = None, offset: int = 0+) -> tuple[list[contracts.ErrorTrackingRelease], int]:+ qs = logic.list_releases(team_id)+ total = qs.count()+ rows = qs if limit is None else qs[offset : offset + limit]+ return [_to_release(release) for release in rows], total+++def get_release(team_id: int, release_id: str) -> contracts.ErrorTrackingRelease | None:+ release = logic.get_release(team_id, release_id)+ return _to_release(release) if release is not None else None+++def get_release_by_hash(team_id: int, hash_id: str) -> contracts.ErrorTrackingRelease | None:+ release = logic.get_release_by_hash(team_id, hash_id)+ return _to_release(release) if release is not None else None+++def create_release(+ team_id: int,+ *,+ version: str,+ project: str,+ hash_id: str | None = None,+ metadata: dict | None = None,+) -> contracts.ErrorTrackingRelease:+ release = logic.create_release(team_id, version=version, project=project, hash_id=hash_id, metadata=metadata)+ return _to_release(release)+++def update_release(+ team_id: int,+ release_id: str,+ *,+ metadata: dict | None = None,+ hash_id: str | None = None,+ version: str | None = None,+ project: str | None = None,+) -> contracts.ErrorTrackingRelease | None:+ release = logic.update_release(+ team_id, release_id, metadata=metadata, hash_id=hash_id, version=version, project=project+ )+ return _to_release(release) if release is not None else None+++def delete_release(team_id: int, release_id: str) -> bool:+ return logic.delete_release(team_id, release_id)+++def has_filter_values(filters: dict) -> bool:+ return logic.has_filter_values(filters)+++def _to_rule_assignee(rule) -> contracts.ErrorTrackingRuleAssignee | None:+ if rule.user_id:+ return contracts.ErrorTrackingRuleAssignee(type="user", id=rule.user_id)+ if rule.role_id:+ return contracts.ErrorTrackingRuleAssignee(type="role", id=rule.role_id)+ return None+++def _to_assignment_rule(rule) -> contracts.ErrorTrackingAssignmentRule:+ return contracts.ErrorTrackingAssignmentRule(+ id=rule.id,+ filters=rule.filters,+ assignee=_to_rule_assignee(rule),+ order_key=rule.order_key,+ disabled_data=rule.disabled_data,+ created_at=rule.created_at,+ updated_at=rule.updated_at,+ )+++def list_assignment_rules(team_id: int) -> list[contracts.ErrorTrackingAssignmentRule]:+ return [_to_assignment_rule(rule) for rule in logic.list_assignment_rules(team_id)]+++def get_assignment_rule(team_id: int, rule_id: str) -> contracts.ErrorTrackingAssignmentRule | None:+ rule = logic.get_assignment_rule(team_id, rule_id)+ return _to_assignment_rule(rule) if rule is not None else None+++def create_assignment_rule(team_id: int, *, filters: dict, assignee: dict) -> contracts.ErrorTrackingAssignmentRule:+ try:+ rule = logic.create_assignment_rule(+ team_id, filters=filters, assignee_type=assignee["type"], assignee_id=assignee["id"]+ )+ except logic.ErrorTrackingInvalidBytecodeError as err:+ raise ValidationError(str(err)) from err+ return _to_assignment_rule(rule)+++def update_assignment_rule(+ team_id: int, rule_id: str, *, filters: dict | None = None, assignee: dict | None = None+) -> contracts.ErrorTrackingAssignmentRule | None:+ try:+ rule = logic.update_assignment_rule(team_id, rule_id, filters=filters, assignee=assignee)+ except logic.ErrorTrackingInvalidBytecodeError as err:+ raise ValidationError(str(err)) from err+ return _to_assignment_rule(rule) if rule is not None else None+++def delete_assignment_rule(team_id: int, rule_id: str) -> bool:+ return logic.delete_assignment_rule(team_id, rule_id)+++def reorder_assignment_rules(team_id: int, orders: dict[str, int]) -> None:+ logic.reorder_assignment_rules(team_id, orders)+++def _to_grouping_rule(rule, issue: tuple[UUID, str | None] | None = None) -> contracts.ErrorTrackingGroupingRule:+ return contracts.ErrorTrackingGroupingRule(+ id=rule.id,+ filters=rule.filters,+ assignee=_to_rule_assignee(rule),+ description=rule.description,+ issue=contracts.ErrorTrackingGroupingRuleIssue(id=issue[0], name=issue[1]) if issue else None,+ order_key=rule.order_key,+ disabled_data=rule.disabled_data,+ created_at=rule.created_at,+ updated_at=rule.updated_at,+ )+++def list_grouping_rules(team_id: int) -> list[contracts.ErrorTrackingGroupingRule]:+ rules = list(logic.list_grouping_rules(team_id))+ issue_map = logic.grouping_rule_issue_map(team_id, [str(rule.id) for rule in rules])+ return [_to_grouping_rule(rule, issue_map.get(str(rule.id))) for rule in rules]+++def get_grouping_rule(team_id: int, rule_id: str) -> contracts.ErrorTrackingGroupingRule | None:+ rule = logic.get_grouping_rule(team_id, rule_id)+ return _to_grouping_rule(rule) if rule is not None else None+++def create_grouping_rule(+ team_id: int, *, filters: dict, assignee: dict | None = None, description: str | None = None+) -> contracts.ErrorTrackingGroupingRule:+ try:+ rule = logic.create_grouping_rule(team_id, filters=filters, assignee=assignee, description=description)+ except logic.ErrorTrackingInvalidBytecodeError as err:+ raise ValidationError(str(err)) from err+ return _to_grouping_rule(rule)+++def update_grouping_rule(+ team_id: int, rule_id: str, *, filters: dict | None = None+) -> contracts.ErrorTrackingGroupingRule | None:+ try:+ rule = logic.update_grouping_rule(team_id, rule_id, filters=filters)+ except logic.ErrorTrackingInvalidBytecodeError as err:+ raise ValidationError(str(err)) from err+ return _to_grouping_rule(rule) if rule is not None else None+++def delete_grouping_rule(team_id: int, rule_id: str) -> bool:+ return logic.delete_grouping_rule(team_id, rule_id)+++def reorder_grouping_rules(team_id: int, orders: dict[str, int]) -> None:+ logic.reorder_grouping_rules(team_id, orders)+++def _to_suppression_rule(rule) -> contracts.ErrorTrackingSuppressionRule:+ return contracts.ErrorTrackingSuppressionRule(+ id=rule.id,+ filters=rule.filters,+ order_key=rule.order_key,+ disabled_data=rule.disabled_data,+ sampling_rate=rule.sampling_rate,+ created_at=rule.created_at,+ updated_at=rule.updated_at,+ )+++def list_suppression_rules(team_id: int) -> list[contracts.ErrorTrackingSuppressionRule]:+ return [_to_suppression_rule(rule) for rule in logic.list_suppression_rules(team_id)]+++def get_suppression_rule(team_id: int, rule_id: str) -> contracts.ErrorTrackingSuppressionRule | None:+ rule = logic.get_suppression_rule(team_id, rule_id)+ return _to_suppression_rule(rule) if rule is not None else None+++def create_suppression_rule(+ team_id: int, *, filters: dict, sampling_rate: float+) -> contracts.ErrorTrackingSuppressionRule:+ try:+ rule = logic.create_suppression_rule(team_id, filters=filters, sampling_rate=sampling_rate)+ except logic.ErrorTrackingInvalidBytecodeError as err:+ raise ValidationError(str(err)) from err+ return _to_suppression_rule(rule)+++def update_suppression_rule(+ team_id: int, rule_id: str, *, filters: dict | None = None, sampling_rate: float | None = None+) -> contracts.ErrorTrackingSuppressionRule | None:+ try:+ rule = logic.update_suppression_rule(team_id, rule_id, filters=filters, sampling_rate=sampling_rate)+ except logic.ErrorTrackingInvalidBytecodeError as err:+ raise ValidationError(str(err)) from err+ return _to_suppression_rule(rule) if rule is not None else None+++def delete_suppression_rule(team_id: int, rule_id: str) -> bool:+ return logic.delete_suppression_rule(team_id, rule_id)+++def reorder_suppression_rules(team_id: int, orders: dict[str, int]) -> None:+ logic.reorder_suppression_rules(team_id, orders)+++def get_client_safe_suppression_rules(team_id: int) -> list[dict]:+ return logic.get_client_safe_suppression_rules(team_id)++def get_issue_id_for_fingerprint(team_id: int, fingerprint: str) -> UUID | None:return logic.get_issue_id_for_fingerprint(team_id=team_id, fingerprint=fingerprint)diff --git a/products/error_tracking/backend/facade/contracts.py b/products/error_tracking/backend/facade/contracts.pyindex 858e9b142775..f959f3ca92b5 100644--- a/products/error_tracking/backend/facade/contracts.py+++ b/products/error_tracking/backend/facade/contracts.py@@ -89,3 +89,104 @@ class ErrorTrackingIssueAssignmentNotification:assigned_user_id: int | Nonerole_id: UUID | None = Nonerole_member_user_ids: list[int] = field(default_factory=list)+++@dataclass(frozen=True)+class ErrorTrackingSettings:+ project_rate_limit_value: int | None+ project_rate_limit_bucket_size_minutes: int | None+ per_issue_rate_limit_value: int | None+ per_issue_rate_limit_bucket_size_minutes: int | None+++@dataclass(frozen=True)+class ErrorTrackingSpikeDetectionConfig:+ snooze_duration_minutes: int+ multiplier: int+ threshold: int+++@dataclass(frozen=True)+class ErrorTrackingSpikeEventIssue:+ id: UUID+ name: str | None+ description: str | None+++@dataclass(frozen=True)+class ErrorTrackingSpikeEvent:+ id: UUID+ issue: ErrorTrackingSpikeEventIssue+ detected_at: datetime+ computed_baseline: float+ current_bucket_value: int+++@dataclass(frozen=True)+class ErrorTrackingRelease:+ id: UUID+ hash_id: str+ team_id: int+ created_at: datetime+ metadata: dict | None+ version: str+ project: str+++@dataclass(frozen=True)+class ErrorTrackingStackFrame:+ id: UUID+ raw_id: str+ created_at: datetime+ contents: dict+ resolved: bool+ context: dict | None+ symbol_set_ref: str | None+ release: ErrorTrackingRelease | None+++@dataclass(frozen=True)+class ErrorTrackingRuleAssignee:+ type: str+ id: int | UUID+++@dataclass(frozen=True)+class ErrorTrackingAssignmentRule:+ id: UUID+ filters: dict+ assignee: ErrorTrackingRuleAssignee | None+ order_key: int+ disabled_data: dict | None+ created_at: datetime+ updated_at: datetime+++@dataclass(frozen=True)+class ErrorTrackingGroupingRuleIssue:+ id: UUID+ name: str | None+++@dataclass(frozen=True)+class ErrorTrackingGroupingRule:+ id: UUID+ filters: dict+ assignee: ErrorTrackingRuleAssignee | None+ description: str | None+ issue: ErrorTrackingGroupingRuleIssue | None+ order_key: int+ disabled_data: dict | None+ created_at: datetime+ updated_at: datetime+++@dataclass(frozen=True)+class ErrorTrackingSuppressionRule:+ id: UUID+ filters: dict+ order_key: int+ disabled_data: dict | None+ sampling_rate: float+ created_at: datetime+ updated_at: datetimediff --git a/products/error_tracking/backend/logic/__init__.py b/products/error_tracking/backend/logic/__init__.pyindex f0ddca06322b..dd2e1cc1edce 100644--- a/products/error_tracking/backend/logic/__init__.py+++ b/products/error_tracking/backend/logic/__init__.py@@ -1,8 +1,8 @@from datetime import datetime-from typing import Any+from typing import Any, TypeVar, castfrom uuid import UUID-from django.db.models import Count, QuerySet+from django.db.models import Count, Q, QuerySetfrom posthog.models.integration import (GitHubIntegration,@@ -11,15 +11,57 @@ from posthog.models.integration import (JiraIntegration,LinearIntegration,)+from posthog.models.utils import UUIDTfrom products.error_tracking.backend.models import (+ ErrorTrackingAssignmentRule,ErrorTrackingExternalReference,+ ErrorTrackingGroupingRule,ErrorTrackingIssue,ErrorTrackingIssueAssignment,ErrorTrackingIssueFingerprintV2,+ ErrorTrackingRelease,+ ErrorTrackingSettings,+ ErrorTrackingSpikeDetectionConfig,+ ErrorTrackingSpikeEvent,+ ErrorTrackingStackFrame,+ ErrorTrackingSuppressionRule,ErrorTrackingSymbolSet,)+SERVER_ONLY_PROPERTIES = frozenset({"$exception_sources", "$exception_functions"})+++class ErrorTrackingReleaseHashInUseError(Exception):+ pass+++class ErrorTrackingInvalidBytecodeError(Exception):+ pass+++SPIKE_EVENT_ORDER_FIELDS = (+ "detected_at",+ "-detected_at",+ "computed_baseline",+ "-computed_baseline",+ "current_bucket_value",+ "-current_bucket_value",+)++SETTINGS_FIELDS = (+ "project_rate_limit_value",+ "project_rate_limit_bucket_size_minutes",+ "per_issue_rate_limit_value",+ "per_issue_rate_limit_bucket_size_minutes",+)++SPIKE_DETECTION_CONFIG_FIELDS = (+ "snooze_duration_minutes",+ "multiplier",+ "threshold",+)+class ErrorTrackingIssueNotFoundError(Exception):pass@@ -216,3 +258,421 @@ def build_external_issue_url(reference: ErrorTrackingExternalReference) -> str:return f"{jira.site_url()}/browse/{issue_key}"return ""+++def get_or_create_settings(team_id: int) -> ErrorTrackingSettings:+ settings, _ = ErrorTrackingSettings.objects.get_or_create(team_id=team_id)+ return settings+++def update_settings(team_id: int, fields: dict[str, int | None]) -> ErrorTrackingSettings:+ settings = get_or_create_settings(team_id)+ updates = {key: value for key, value in fields.items() if key in SETTINGS_FIELDS}+ for key, value in updates.items():+ setattr(settings, key, value)+ if updates:+ settings.save(update_fields=list(updates))+ return settings+++def get_or_create_spike_detection_config(team_id: int) -> ErrorTrackingSpikeDetectionConfig:+ config, _ = ErrorTrackingSpikeDetectionConfig.objects.get_or_create(team_id=team_id)+ return config+++def update_spike_detection_config(team_id: int, fields: dict[str, int]) -> ErrorTrackingSpikeDetectionConfig:+ config = get_or_create_spike_detection_config(team_id)+ updates = {key: value for key, value in fields.items() if key in SPIKE_DETECTION_CONFIG_FIELDS}+ for key, value in updates.items():+ setattr(config, key, value)+ if updates:+ config.save(update_fields=list(updates))+ return config+++def list_spike_events(+ team_id: int,+ issue_ids: list[str] | None = None,+ date_from: str | None = None,+ date_to: str | None = None,+ order_by: str | None = None,+) -> QuerySet[ErrorTrackingSpikeEvent]:+ qs = ErrorTrackingSpikeEvent.objects.filter(team_id=team_id).select_related("issue")+ if issue_ids:+ qs = qs.filter(issue_id__in=issue_ids)+ if date_from:+ qs = qs.filter(detected_at__gte=date_from)+ if date_to:+ qs = qs.filter(detected_at__lte=date_to)+ if order_by in SPIKE_EVENT_ORDER_FIELDS:+ return qs.order_by(order_by)+ return qs.order_by("-detected_at")+++def split_stack_frame_raw_id(raw_id: str) -> tuple[str, int]:+ parts = raw_id.split("/")+ if len(parts) != 2:+ return raw_id, 0+ try:+ return parts[0], int(parts[1])+ except ValueError:+ return raw_id, 0+++def stack_frame_queryset(team_id: int) -> QuerySet[ErrorTrackingStackFrame]:+ return ErrorTrackingStackFrame.objects.filter(team_id=team_id).select_related("symbol_set__release")+++def get_stack_frame(team_id: int, frame_id: str) -> ErrorTrackingStackFrame | None:+ return stack_frame_queryset(team_id).filter(id=frame_id).first()+++def batch_get_stack_frames(+ team_id: int, raw_ids: list[str] | None = None, symbol_set: str | None = None+) -> QuerySet[ErrorTrackingStackFrame]:+ qs = stack_frame_queryset(team_id)+ if raw_ids:+ id_query = Q()+ for raw_id in raw_ids:+ hash_id, part = split_stack_frame_raw_id(raw_id)+ id_query |= Q(raw_id=hash_id, part=part)+ qs = qs.filter(id_query)+ if symbol_set:+ qs = qs.filter(symbol_set=symbol_set)+ return qs+++def list_releases(team_id: int) -> QuerySet[ErrorTrackingRelease]:+ return ErrorTrackingRelease.objects.filter(team_id=team_id).order_by("-created_at")+++def get_release(team_id: int, release_id: str) -> ErrorTrackingRelease | None:+ return ErrorTrackingRelease.objects.filter(team_id=team_id, id=release_id).first()+++def get_release_by_hash(team_id: int, hash_id: str) -> ErrorTrackingRelease | None:+ return ErrorTrackingRelease.objects.filter(team_id=team_id, hash_id=hash_id).first()+++def release_hash_exists(team_id: int, hash_id: str) -> bool:+ return ErrorTrackingRelease.objects.filter(team_id=team_id, hash_id=hash_id).exists()+++def create_release(+ team_id: int,+ *,+ version: str,+ project: str,+ hash_id: str | None = None,+ metadata: dict | None = None,+) -> ErrorTrackingRelease:+ release_id = UUIDT()+ resolved_hash_id = hash_id or str(release_id)+ if release_hash_exists(team_id, resolved_hash_id):+ raise ErrorTrackingReleaseHashInUseError(resolved_hash_id)+ return ErrorTrackingRelease.objects.create(+ id=release_id,+ team_id=team_id,+ hash_id=resolved_hash_id,+ metadata=metadata,+ project=str(project),+ version=str(version),+ )+++def update_release(+ team_id: int,+ release_id: str,+ *,+ metadata: dict | None = None,+ hash_id: str | None = None,+ version: str | None = None,+ project: str | None = None,+) -> ErrorTrackingRelease | None:+ release = get_release(team_id, release_id)+ if release is None:+ return None+ if metadata:+ release.metadata = metadata+ if version:+ release.version = str(version)+ if project:+ release.project = str(project)+ if hash_id and hash_id != release.hash_id:+ if release_hash_exists(team_id, hash_id):+ raise ErrorTrackingReleaseHashInUseError(hash_id)+ release.hash_id = str(hash_id)+ release.save()+ return release+++def delete_release(team_id: int, release_id: str) -> bool:+ deleted, _ = ErrorTrackingRelease.objects.filter(team_id=team_id, id=release_id).delete()+ return deleted > 0+++# --- Rule bytecode compilation ---------------------------------------------+# The HogQL compiler is a heavy import, so it loads lazily inside these helpers+# rather than at module import time (this module is reachable from facade.api,+# which config-only consumers import).+++def _validate_rule_bytecode(bytecode: list[Any]) -> None:+ from products.error_tracking.backend.hogvm_stl import RUST_HOGVM_STL # noqa: PLC0415++ from common.hogvm.python.operation import Operation # noqa: PLC0415 — keeps the heavy dep off the import path++ for i, op in enumerate(bytecode):+ if not isinstance(op, Operation):+ continue+ if op == Operation.CALL_GLOBAL:+ name = bytecode[i + 1]+ if not isinstance(name, str):+ raise ErrorTrackingInvalidBytecodeError(f"Expected string for global function name, got {type(name)}")+ if name not in RUST_HOGVM_STL:+ raise ErrorTrackingInvalidBytecodeError(f"Unknown global function: {name}")+++def compile_filter_bytecode(team_id: int, filters: dict) -> list[Any]:+ from posthog.schema import PropertyGroupFilterValue # noqa: PLC0415++ from posthog.hogql import ast # noqa: PLC0415+ from posthog.hogql.compiler.bytecode import create_bytecode # noqa: PLC0415+ from posthog.hogql.property import property_to_expr # noqa: PLC0415++ from posthog.models.team.team import Team # noqa: PLC0415++ team = Team.objects.get(id=team_id)+ expr = property_to_expr(PropertyGroupFilterValue(**filters), team, strict=True)+ bytecode = create_bytecode(ast.ReturnStatement(expr=expr)).bytecode+ _validate_rule_bytecode(bytecode)+ return bytecode+++def match_all_bytecode() -> list[Any]:+ from posthog.hogql import ast # noqa: PLC0415+ from posthog.hogql.compiler.bytecode import create_bytecode # noqa: PLC0415++ return create_bytecode(ast.ReturnStatement(expr=ast.Constant(value=True))).bytecode+++_ReorderableRule = TypeVar(+ "_ReorderableRule",+ ErrorTrackingAssignmentRule,+ ErrorTrackingGroupingRule,+ ErrorTrackingSuppressionRule,+)+++def _reorder_rules(model: type[_ReorderableRule], team_id: int, orders: dict[str, int]) -> None:+ rules = list(model.objects.filter(team_id=team_id, id__in=orders.keys()))+ for rule in rules:+ rule.order_key = orders[str(rule.id)]+ model.objects.filter(team_id=team_id).bulk_update(rules, ["order_key"])+++def has_filter_values(json_filters: dict) -> bool:+ """Whether a filter dict contains any actual filter values, recursively.++ Non-dict entries count as "has values" so the request reaches pydantic+ validation and is rejected with a 400 rather than raising AttributeError.+ """+ values = json_filters.get("values", [])+ if not values:+ return False+ for value in values:+ if not isinstance(value, dict):+ return True+ if "key" in value or has_filter_values(value):+ return True+ return False+++def _rule_bytecode(team_id: int, filters: dict) -> list[Any]:+ if has_filter_values(filters):+ return compile_filter_bytecode(team_id, filters)+ return match_all_bytecode()+++def list_assignment_rules(team_id: int) -> QuerySet[ErrorTrackingAssignmentRule]:+ return ErrorTrackingAssignmentRule.objects.filter(team_id=team_id).order_by("order_key")+++def get_assignment_rule(team_id: int, rule_id: str) -> ErrorTrackingAssignmentRule | None:+ return ErrorTrackingAssignmentRule.objects.filter(team_id=team_id, id=rule_id).first()+++def create_assignment_rule(+ team_id: int, *, filters: dict, assignee_type: str, assignee_id: int | UUID+) -> ErrorTrackingAssignmentRule:+ return ErrorTrackingAssignmentRule.objects.create(+ team_id=team_id,+ filters=filters,+ bytecode=_rule_bytecode(team_id, filters),+ order_key=0,+ user_id=cast(int, assignee_id) if assignee_type == "user" else None,+ role_id=cast(UUID, assignee_id) if assignee_type == "role" else None,+ )+++def update_assignment_rule(+ team_id: int,+ rule_id: str,+ *,+ filters: dict | None = None,+ assignee: dict | None = None,+) -> ErrorTrackingAssignmentRule | None:+ rule = get_assignment_rule(team_id, rule_id)+ if rule is None:+ return None+ if filters:+ rule.filters = filters+ rule.bytecode = _rule_bytecode(team_id, filters)+ if assignee:+ rule.user_id = assignee["id"] if assignee["type"] == "user" else None+ rule.role_id = assignee["id"] if assignee["type"] == "role" else None+ rule.disabled_data = None+ rule.save()+ return rule+++def delete_assignment_rule(team_id: int, rule_id: str) -> bool:+ deleted, _ = ErrorTrackingAssignmentRule.objects.filter(team_id=team_id, id=rule_id).delete()+ return deleted > 0+++def reorder_assignment_rules(team_id: int, orders: dict[str, int]) -> None:+ _reorder_rules(ErrorTrackingAssignmentRule, team_id, orders)+++def list_grouping_rules(team_id: int) -> QuerySet[ErrorTrackingGroupingRule]:+ return ErrorTrackingGroupingRule.objects.filter(team_id=team_id).order_by("order_key")+++def grouping_rule_issue_map(team_id: int, rule_ids: list[str]) -> dict[str, tuple[UUID, str | None]]:+ """Map grouping rule id -> (issue_id, issue_name) via the custom-rule fingerprint."""+ if not rule_ids:+ return {}+ fingerprints = (+ ErrorTrackingIssueFingerprintV2.objects.select_related("issue")+ .filter(team_id=team_id, fingerprint__in=[f"custom-rule:{rid}" for rid in rule_ids])+ .only("fingerprint", "issue_id", "issue__id", "issue__name")+ )+ return {fp.fingerprint.removeprefix("custom-rule:"): (fp.issue.id, fp.issue.name) for fp in fingerprints}+++def get_grouping_rule(team_id: int, rule_id: str) -> ErrorTrackingGroupingRule | None:+ return ErrorTrackingGroupingRule.objects.filter(team_id=team_id, id=rule_id).first()+++def create_grouping_rule(+ team_id: int, *, filters: dict, assignee: dict | None = None, description: str | None = None+) -> ErrorTrackingGroupingRule:+ return ErrorTrackingGroupingRule.objects.create(+ team_id=team_id,+ filters=filters,+ bytecode=compile_filter_bytecode(team_id, filters),+ order_key=0,+ user_id=assignee["id"] if assignee and assignee["type"] == "user" else None,+ role_id=assignee["id"] if assignee and assignee["type"] == "role" else None,+ description=description,+ )+++def update_grouping_rule(+ team_id: int, rule_id: str, *, filters: dict | None = None+) -> ErrorTrackingGroupingRule | None:+ rule = get_grouping_rule(team_id, rule_id)+ if rule is None:+ return None+ if filters:+ rule.filters = filters+ rule.bytecode = compile_filter_bytecode(team_id, filters)+ rule.disabled_data = None+ rule.save()+ return rule+++def delete_grouping_rule(team_id: int, rule_id: str) -> bool:+ deleted, _ = ErrorTrackingGroupingRule.objects.filter(team_id=team_id, id=rule_id).delete()+ return deleted > 0+++def reorder_grouping_rules(team_id: int, orders: dict[str, int]) -> None:+ _reorder_rules(ErrorTrackingGroupingRule, team_id, orders)+++def list_suppression_rules(team_id: int) -> QuerySet[ErrorTrackingSuppressionRule]:+ return ErrorTrackingSuppressionRule.objects.filter(team_id=team_id).order_by("order_key")+++def get_suppression_rule(team_id: int, rule_id: str) -> ErrorTrackingSuppressionRule | None:+ return ErrorTrackingSuppressionRule.objects.filter(team_id=team_id, id=rule_id).first()+++def create_suppression_rule(team_id: int, *, filters: dict, sampling_rate: float) -> ErrorTrackingSuppressionRule:+ return ErrorTrackingSuppressionRule.objects.create(+ team_id=team_id,+ filters=filters,+ bytecode=_rule_bytecode(team_id, filters),+ order_key=0,+ sampling_rate=sampling_rate,+ )+++def update_suppression_rule(+ team_id: int,+ rule_id: str,+ *,+ filters: dict | None = None,+ sampling_rate: float | None = None,+) -> ErrorTrackingSuppressionRule | None:+ rule = get_suppression_rule(team_id, rule_id)+ if rule is None:+ return None+ if filters is not None:+ rule.filters = filters+ rule.bytecode = _rule_bytecode(team_id, filters)+ if sampling_rate is not None:+ rule.sampling_rate = sampling_rate+ rule.disabled_data = None+ rule.save()+ return rule+++def delete_suppression_rule(team_id: int, rule_id: str) -> bool:+ deleted, _ = ErrorTrackingSuppressionRule.objects.filter(team_id=team_id, id=rule_id).delete()+ return deleted > 0+++def reorder_suppression_rules(team_id: int, orders: dict[str, int]) -> None:+ _reorder_rules(ErrorTrackingSuppressionRule, team_id, orders)+++def get_client_safe_filters(filters: dict) -> dict | None:+ """Return the filters if every leaf is client-safe, otherwise None.++ A filter that references a server-only property cannot be evaluated+ client-side, so the whole rule is excluded.+ """+ for value in filters.get("values", []):+ if "key" in value:+ if value.get("key") in SERVER_ONLY_PROPERTIES:+ return None+ elif "values" in value:+ if get_client_safe_filters(value) is None:+ return None+ return filters+++def get_client_safe_suppression_rules(team_id: int) -> list[dict]:+ rules = ErrorTrackingSuppressionRule.objects.filter(team_id=team_id).values_list("filters", "sampling_rate")+ result = []+ for filters, sampling_rate in rules:+ safe = get_client_safe_filters(filters)+ if safe is not None:+ rule_data = {**safe}+ if sampling_rate < 1.0:+ rule_data["samplingRate"] = sampling_rate+ result.append(rule_data)+ return resultdiff --git a/products/error_tracking/backend/presentation/pagination.py b/products/error_tracking/backend/presentation/pagination.pynew file mode 100644index 000000000000..31318517e0b3--- /dev/null+++ b/products/error_tracking/backend/presentation/pagination.py@@ -0,0 +1,46 @@+from collections.abc import Callable+from typing import Any++from rest_framework.generics import GenericAPIView+from rest_framework.pagination import LimitOffsetPagination+from rest_framework.request import Request+from rest_framework.response import Response++# A facade fetcher takes (limit, offset) and returns (page_items, total_count).+# limit is None when pagination is disabled, in which case the whole result set is returned.+FacadeFetcher = Callable[[int | None, int], tuple[list[Any], int]]+++def paginate_via_facade(view: GenericAPIView, request: Request, fetch_page: FacadeFetcher) -> Response:+ """Render a DRF ``LimitOffsetPagination`` envelope from a facade function that pushes+ ``LIMIT``/``OFFSET``/``COUNT`` into SQL.++ The facade evaluates its queryset into frozen contracts to honor the product boundary, so it+ cannot hand a lazy queryset back to ``paginate_queryset`` — doing so on a materialized list would+ load the entire result set into memory just to slice one page. Instead the facade slices the+ queryset *before* mapping to contracts and returns ``(page_items, total_count)``; this helper+ reads the limit/offset from the request and assembles the standard ``{count, next, previous,+ results}`` envelope, keeping the response shape identical to a queryset-backed list view.++ Reusable across product list views (releases, stack frames, spike events — and the symbol-set+ list once it is thinned).+ """+ paginator = view.paginator+ if not isinstance(paginator, LimitOffsetPagination):+ items, _total = fetch_page(None, 0)+ return Response(view.get_serializer(items, many=True).data)++ limit = paginator.get_limit(request)+ if limit is None:+ items, _total = fetch_page(None, 0)+ return Response(view.get_serializer(items, many=True).data)++ offset = paginator.get_offset(request)+ items, total = fetch_page(limit, offset)+ # Set the count/limit/offset/request the paginator would normally derive in paginate_queryset,+ # so get_paginated_response and the next/previous links resolve correctly.+ paginator.count = total+ paginator.limit = limit+ paginator.offset = offset+ paginator.request = request+ return paginator.get_paginated_response(view.get_serializer(items, many=True).data)diff --git a/products/error_tracking/backend/presentation/views/assignment_rules.py b/products/error_tracking/backend/presentation/views/assignment_rules.pyindex 77234cd10ad7..1bac824f2511 100644--- a/products/error_tracking/backend/presentation/views/assignment_rules.py+++ b/products/error_tracking/backend/presentation/views/assignment_rules.py@@ -5,21 +5,17 @@ import posthoganalyticsfrom drf_spectacular.utils import OpenApiResponse, extend_schema_fieldfrom pydantic import ValidationError as PydanticValidationErrorfrom rest_framework import serializers, status, viewsets+from rest_framework.exceptions import NotFoundfrom rest_framework.response import Responsefrom posthog.schema import PropertyGroupFilterValuefrom posthog.api.mixins import ValidatedRequest, validated_requestfrom posthog.api.routing import TeamAndOrgViewSetMixin+from posthog.api.utils import actionfrom posthog.event_usage import groups-from products.error_tracking.backend.models import ErrorTrackingAssignmentRule-from products.error_tracking.backend.presentation.views.utils import (- RuleReorderingMixin,- generate_byte_code,- generate_match_all_bytecode,- has_filter_values,-)+from products.error_tracking.backend.facade import api as error_tracking_apilogger = structlog.get_logger(__name__)@@ -97,13 +93,14 @@ class ErrorTrackingAssignmentRuleUpdateRequestSerializer(serializers.Serializer))-class ErrorTrackingAssignmentRuleSerializer(serializers.ModelSerializer):+class ErrorTrackingAssignmentRuleSerializer(serializers.Serializer):+ id = serializers.UUIDField(read_only=True)+ filters = serializers.JSONField()assignee = serializers.SerializerMethodField()-- class Meta:- model = ErrorTrackingAssignmentRule- fields = ["id", "filters", "assignee", "order_key", "disabled_data", "created_at", "updated_at"]- read_only_fields = ["team_id", "created_at", "updated_at"]+ order_key = serializers.IntegerField()+ disabled_data = serializers.JSONField(allow_null=True)+ created_at = serializers.DateTimeField(read_only=True)+ updated_at = serializers.DateTimeField(read_only=True)@extend_schema_field({@@ -116,97 +113,84 @@ class ErrorTrackingAssignmentRuleSerializer(serializers.ModelSerializer):})def get_assignee(self, obj):- if obj.user_id:- return {"type": "user", "id": obj.user_id}- elif obj.role_id:- return {"type": "role", "id": obj.role_id}- return None+ if obj.assignee is None:+ return None+ return {"type": obj.assignee.type, "id": obj.assignee.id}-class ErrorTrackingAssignmentRuleViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet, RuleReorderingMixin):+class ErrorTrackingAssignmentRuleViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):scope_object = "error_tracking"- queryset = ErrorTrackingAssignmentRule.objects.order_by("order_key").all()serializer_class = ErrorTrackingAssignmentRuleSerializer- def safely_get_queryset(self, queryset):- return queryset.filter(team_id=self.team.id)-- def _apply_rule_update(self, request: ValidatedRequest) -> Response:- assignment_rule = self.get_object()- json_filters = request.validated_data.get("filters")- assignee = request.validated_data.get("assignee")-- if json_filters:- assignment_rule.filters = json_filters- if has_filter_values(json_filters):- assignment_rule.bytecode = generate_byte_code(self.team, PropertyGroupFilterValue(**json_filters))- else:- assignment_rule.bytecode = generate_match_all_bytecode()-- if assignee:- assignment_rule.user_id = None if assignee["type"] != "user" else assignee["id"]- assignment_rule.role_id = None if assignee["type"] != "role" else assignee["id"]-- assignment_rule.disabled_data = None- assignment_rule.save()-+ def list(self, request, *args, **kwargs) -> Response:+ rules = error_tracking_api.list_assignment_rules(self.team.id)+ page = self.paginate_queryset(rules)+ if page is not None:+ return self.get_paginated_response(self.get_serializer(page, many=True).data)+ return Response(self.get_serializer(rules, many=True).data)++ def retrieve(self, request, *args, pk=None, **kwargs) -> Response:+ rule = error_tracking_api.get_assignment_rule(self.team.id, pk)+ if rule is None:+ raise NotFound()+ return Response(self.get_serializer(rule).data)++ def _apply_rule_update(self, request: ValidatedRequest, pk: str) -> Response:+ rule = error_tracking_api.update_assignment_rule(+ self.team.id,+ pk,+ filters=request.validated_data.get("filters"),+ assignee=request.validated_data.get("assignee"),+ )+ if rule is None:+ raise NotFound()posthoganalytics.capture("error_tracking_assignment_rule_edited",groups=groups(self.team.organization, self.team),)-return Response({"ok": True}, status=status.HTTP_204_NO_CONTENT)@validated_request(request_serializer=ErrorTrackingAssignmentRuleUpdateRequestSerializer,responses={204: None},)- def update(self, request: ValidatedRequest, *args, **kwargs) -> Response:- return self._apply_rule_update(request)+ def update(self, request: ValidatedRequest, *args, pk=None, **kwargs) -> Response:+ return self._apply_rule_update(request, pk)@validated_request(request_serializer=ErrorTrackingAssignmentRuleUpdateRequestSerializer,responses={204: None},)- def partial_update(self, request: ValidatedRequest, *args, **kwargs) -> Response:- return self._apply_rule_update(request)-- def destroy(self, request, *args, **kwargs) -> Response:- response = super().destroy(request, *args, **kwargs)+ def partial_update(self, request: ValidatedRequest, *args, pk=None, **kwargs) -> Response:+ return self._apply_rule_update(request, pk)+ def destroy(self, request, *args, pk=None, **kwargs) -> Response:+ if not error_tracking_api.delete_assignment_rule(self.team.id, pk):+ raise NotFound()posthoganalytics.capture("error_tracking_assignment_rule_deleted",groups=groups(self.team.organization, self.team),)-- return response+ return Response(status=status.HTTP_204_NO_CONTENT)@validated_request(request_serializer=ErrorTrackingAssignmentRuleCreateRequestSerializer,responses={201: OpenApiResponse(response=ErrorTrackingAssignmentRuleSerializer)},)def create(self, request: ValidatedRequest, *args, **kwargs) -> Response:- json_filters = request.validated_data["filters"]- assignee = request.validated_data["assignee"]-- if has_filter_values(json_filters):- bytecode = generate_byte_code(self.team, PropertyGroupFilterValue(**json_filters))- else:- bytecode = generate_match_all_bytecode()-- assignment_rule = ErrorTrackingAssignmentRule.objects.create(- team=self.team,- filters=json_filters,- bytecode=bytecode,- order_key=0,- user_id=None if assignee["type"] != "user" else assignee["id"],- role_id=None if assignee["type"] != "role" else assignee["id"],+ rule = error_tracking_api.create_assignment_rule(+ self.team.id,+ filters=request.validated_data["filters"],+ assignee=request.validated_data["assignee"],)-posthoganalytics.capture("error_tracking_assignment_rule_created",groups=groups(self.team.organization, self.team),)+ return Response(self.get_serializer(rule).data, status=status.HTTP_201_CREATED)- serializer = ErrorTrackingAssignmentRuleSerializer(assignment_rule)- return Response(serializer.data, status=status.HTTP_201_CREATED)+ @action(methods=["PATCH"], detail=False)+ def reorder(self, request, **kwargs) -> Response:+ orders: dict[str, int] = request.data.get("orders", {})+ error_tracking_api.reorder_assignment_rules(self.team.id, orders)+ return Response({"ok": True}, status=status.HTTP_204_NO_CONTENT)diff --git a/products/error_tracking/backend/presentation/views/grouping_rules.py b/products/error_tracking/backend/presentation/views/grouping_rules.pyindex ae37398f3037..2bf914ce7b66 100644--- a/products/error_tracking/backend/presentation/views/grouping_rules.py+++ b/products/error_tracking/backend/presentation/views/grouping_rules.py@@ -6,20 +6,17 @@ import posthoganalyticsfrom drf_spectacular.utils import OpenApiResponse, extend_schema, extend_schema_field, extend_schema_serializerfrom pydantic import ValidationError as PydanticValidationErrorfrom rest_framework import serializers, status, viewsets+from rest_framework.exceptions import NotFoundfrom rest_framework.response import Responsefrom posthog.schema import PropertyGroupFilterValuefrom posthog.api.mixins import ValidatedRequest, validated_requestfrom posthog.api.routing import TeamAndOrgViewSetMixin+from posthog.api.utils import actionfrom posthog.event_usage import groups-from products.error_tracking.backend.models import ErrorTrackingGroupingRule, ErrorTrackingIssueFingerprintV2-from products.error_tracking.backend.presentation.views.utils import (- RuleReorderingMixin,- generate_byte_code,- has_filter_values,-)+from products.error_tracking.backend.facade import api as error_tracking_apilogger = structlog.get_logger(__name__)@@ -35,7 +32,7 @@ class ErrorTrackingGroupingRuleFiltersField(serializers.JSONField):except PydanticValidationError as err:logger.warning("Invalid grouping rule filters payload", exc_info=err)raise serializers.ValidationError("Invalid filters payload.") from err- if not has_filter_values(value):+ if not error_tracking_api.has_filter_values(value):raise serializers.ValidationError("Filters must contain at least one filter value.")return value@@ -102,24 +99,16 @@ class ErrorTrackingGroupingRuleUpdateRequestSerializer(serializers.Serializer):)-class ErrorTrackingGroupingRuleSerializer(serializers.ModelSerializer):+class ErrorTrackingGroupingRuleSerializer(serializers.Serializer):+ id = serializers.UUIDField(read_only=True)+ filters = serializers.JSONField()assignee = serializers.SerializerMethodField()+ description = serializers.CharField(allow_null=True, allow_blank=True)issue = serializers.SerializerMethodField()-- class Meta:- model = ErrorTrackingGroupingRule- fields = [- "id",- "filters",- "assignee",- "description",- "issue",- "order_key",- "disabled_data",- "created_at",- "updated_at",- ]- read_only_fields = ["team_id", "created_at", "updated_at"]+ order_key = serializers.IntegerField()+ disabled_data = serializers.JSONField(allow_null=True)+ created_at = serializers.DateTimeField(read_only=True)+ updated_at = serializers.DateTimeField(read_only=True)@extend_schema_field({@@ -132,21 +121,17 @@ class ErrorTrackingGroupingRuleSerializer(serializers.ModelSerializer):})def get_assignee(self, obj):- if obj.user_id:- return {"type": "user", "id": obj.user_id}- elif obj.role_id:- return {"type": "role", "id": obj.role_id}- return None+ if obj.assignee is None:+ return None+ return {"type": obj.assignee.type, "id": obj.assignee.id}@extend_schema_field(serializers.DictField(child=serializers.CharField(), allow_null=True, help_text="Issue linked to this rule"))def get_issue(self, obj) -> Optional[dict]:- issue_map = self.context.get("issue_map", {})- issue = issue_map.get(str(obj.id))- if issue:- return {"id": str(issue.id), "name": issue.name}- return None+ if obj.issue is None:+ return None+ return {"id": str(obj.issue.id), "name": obj.issue.name}@extend_schema_serializer(many=False)@@ -154,108 +139,76 @@ class ErrorTrackingGroupingRuleListResponseSerializer(serializers.Serializer):results = ErrorTrackingGroupingRuleSerializer(many=True)-def _build_issue_map(team_id: int, rule_ids: list[str]) -> dict:- """Build a mapping of rule_id -> ErrorTrackingIssue for grouping rules."""- if not rule_ids:- return {}- fingerprints = (- ErrorTrackingIssueFingerprintV2.objects.select_related("issue")- .filter(- team_id=team_id,- fingerprint__in=[f"custom-rule:{rid}" for rid in rule_ids],- )- .only("fingerprint", "issue_id", "issue__id", "issue__name")- )- return {fp.fingerprint.removeprefix("custom-rule:"): fp.issue for fp in fingerprints}---class ErrorTrackingGroupingRuleViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet, RuleReorderingMixin):+class ErrorTrackingGroupingRuleViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):scope_object = "error_tracking"- queryset = ErrorTrackingGroupingRule.objects.order_by("order_key").all()serializer_class = ErrorTrackingGroupingRuleSerializer+ # The list endpoint returns all rules unpaginated ({"results": [...]}); without this the+ # default paginator makes the schema advertise limit/offset params the view doesn't honor.pagination_class = None- def safely_get_queryset(self, queryset):- return queryset.filter(team_id=self.team.id)-@extend_schema(responses={200: OpenApiResponse(response=ErrorTrackingGroupingRuleListResponseSerializer)})def list(self, request, *args, **kwargs) -> Response:- queryset = list(self.filter_queryset(self.get_queryset()))- rule_ids = [str(r.id) for r in queryset]- issue_map = _build_issue_map(self.team.id, rule_ids)- context = {**self.get_serializer_context(), "issue_map": issue_map}- serializer = self.get_serializer(queryset, many=True, context=context)- return Response({"results": serializer.data})-- def _apply_rule_update(self, request: ValidatedRequest) -> Response:- grouping_rule = self.get_object()- json_filters = request.validated_data.get("filters")-- if json_filters:- parsed_filters = PropertyGroupFilterValue(**json_filters)- grouping_rule.filters = json_filters- grouping_rule.bytecode = generate_byte_code(self.team, parsed_filters)-- grouping_rule.disabled_data = None- grouping_rule.save()-+ rules = error_tracking_api.list_grouping_rules(self.team.id)+ return Response({"results": self.get_serializer(rules, many=True).data})++ def retrieve(self, request, *args, pk=None, **kwargs) -> Response:+ rule = error_tracking_api.get_grouping_rule(self.team.id, pk)+ if rule is None:+ raise NotFound()+ return Response(self.get_serializer(rule).data)++ def _apply_rule_update(self, request: ValidatedRequest, pk: str) -> Response:+ rule = error_tracking_api.update_grouping_rule(self.team.id, pk, filters=request.validated_data.get("filters"))+ if rule is None:+ raise NotFound()posthoganalytics.capture("error_tracking_grouping_rule_edited",groups=groups(self.team.organization, self.team),)-return Response({"ok": True}, status=status.HTTP_204_NO_CONTENT)@validated_request(request_serializer=ErrorTrackingGroupingRuleUpdateRequestSerializer,responses={204: None},)- def update(self, request: ValidatedRequest, *args, **kwargs) -> Response:- return self._apply_rule_update(request)+ def update(self, request: ValidatedRequest, *args, pk=None, **kwargs) -> Response:+ return self._apply_rule_update(request, pk)@validated_request(request_serializer=ErrorTrackingGroupingRuleUpdateRequestSerializer,responses={204: None},)- def partial_update(self, request: ValidatedRequest, *args, **kwargs) -> Response:- return self._apply_rule_update(request)-- def destroy(self, request, *args, **kwargs) -> Response:- response = super().destroy(request, *args, **kwargs)+ def partial_update(self, request: ValidatedRequest, *args, pk=None, **kwargs) -> Response:+ return self._apply_rule_update(request, pk)+ def destroy(self, request, *args, pk=None, **kwargs) -> Response:+ if not error_tracking_api.delete_grouping_rule(self.team.id, pk):+ raise NotFound()posthoganalytics.capture("error_tracking_grouping_rule_deleted",groups=groups(self.team.organization, self.team),)-- return response+ return Response(status=status.HTTP_204_NO_CONTENT)@validated_request(request_serializer=ErrorTrackingGroupingRuleCreateRequestSerializer,responses={201: OpenApiResponse(response=ErrorTrackingGroupingRuleSerializer)},)def create(self, request: ValidatedRequest, *args, **kwargs) -> Response:- json_filters = request.validated_data["filters"]- assignee = request.validated_data.get("assignee")- description = request.validated_data.get("description")-- parsed_filters = PropertyGroupFilterValue(**json_filters)- bytecode = generate_byte_code(self.team, parsed_filters)-- grouping_rule = ErrorTrackingGroupingRule.objects.create(- team=self.team,- filters=json_filters,- bytecode=bytecode,- order_key=0,- user_id=None if (not assignee or assignee["type"] != "user") else assignee["id"],- role_id=None if (not assignee or assignee["type"] != "role") else assignee["id"],- description=description,+ rule = error_tracking_api.create_grouping_rule(+ self.team.id,+ filters=request.validated_data["filters"],+ assignee=request.validated_data.get("assignee"),+ description=request.validated_data.get("description"),)-posthoganalytics.capture("error_tracking_grouping_rule_created",groups=groups(self.team.organization, self.team),)+ return Response(self.get_serializer(rule).data, status=status.HTTP_201_CREATED)- serializer = ErrorTrackingGroupingRuleSerializer(grouping_rule)- return Response(serializer.data, status=status.HTTP_201_CREATED)+ @action(methods=["PATCH"], detail=False)+ def reorder(self, request, **kwargs) -> Response:+ orders: dict[str, int] = request.data.get("orders", {})+ error_tracking_api.reorder_grouping_rules(self.team.id, orders)+ return Response({"ok": True}, status=status.HTTP_204_NO_CONTENT)diff --git a/products/error_tracking/backend/presentation/views/releases.py b/products/error_tracking/backend/presentation/views/releases.pyindex 0826327fbcaf..14b71f55305e 100644--- a/products/error_tracking/backend/presentation/views/releases.py+++ b/products/error_tracking/backend/presentation/views/releases.py@@ -1,98 +1,146 @@-from django.shortcuts import get_object_or_404--import structlog+from drf_spectacular.utils import OpenApiResponse, extend_schema, extend_schema_fieldfrom rest_framework import serializers, status, viewsets-from rest_framework.exceptions import ValidationError+from rest_framework.exceptions import NotFound, ValidationErrorfrom rest_framework.response import Response+from rest_framework_dataclasses.serializers import DataclassSerializerfrom posthog.api.routing import TeamAndOrgViewSetMixinfrom posthog.api.utils import action-from posthog.models.utils import UUIDT-from products.error_tracking.backend.models import ErrorTrackingRelease+from products.error_tracking.backend.facade import (+ api as error_tracking_api,+ contracts,+)+from products.error_tracking.backend.presentation.pagination import paginate_via_facade-logger = structlog.get_logger(__name__)+MAX_HASH_ID_LENGTH = 128-class ErrorTrackingReleaseSerializer(serializers.ModelSerializer):- class Meta:- model = ErrorTrackingRelease- fields = ["id", "hash_id", "team_id", "created_at", "metadata", "version", "project"]- read_only_fields = ["team_id"]+@extend_schema_field({"type": "object", "additionalProperties": True, "nullable": True})+class ReleaseMetadataField(serializers.JSONField):+ pass-class ErrorTrackingReleaseViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):+class ErrorTrackingReleaseSerializer(DataclassSerializer):+ class Meta:+ dataclass = contracts.ErrorTrackingRelease+++class ErrorTrackingReleaseCreateRequestSerializer(serializers.Serializer):+ version = serializers.CharField(help_text="Human-readable release version, e.g. a semver string or build number.")+ project = serializers.CharField(help_text="Identifier of the project this release belongs to.")+ hash_id = serializers.CharField(+ required=False,+ allow_null=True,+ max_length=MAX_HASH_ID_LENGTH,+ help_text="Optional client-supplied release hash (e.g. a git commit SHA). Generated server-side when omitted.",+ )+ metadata = ReleaseMetadataField(+ required=False, allow_null=True, help_text="Optional free-form metadata object stored alongside the release."+ )+++class ErrorTrackingReleaseUpdateRequestSerializer(serializers.Serializer):+ version = serializers.CharField(+ required=False, allow_null=True, help_text="Human-readable release version. Omit to preserve the current value."+ )+ project = serializers.CharField(+ required=False, allow_null=True, help_text="Project identifier. Omit to preserve the current value."+ )+ hash_id = serializers.CharField(+ required=False,+ allow_null=True,+ max_length=MAX_HASH_ID_LENGTH,+ help_text="Release hash (e.g. a git commit SHA). Omit to preserve the current value.",+ )+ metadata = ReleaseMetadataField(+ required=False, allow_null=True, help_text="Free-form metadata object. Omit to preserve the current value."+ )+++class ErrorTrackingReleaseViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):scope_object = "error_tracking"- queryset = ErrorTrackingRelease.objects.all()scope_object_read_actions = ["list", "retrieve", "by_hash"]serializer_class = ErrorTrackingReleaseSerializer- def safely_get_queryset(self, queryset):- queryset = queryset.filter(team_id=self.team.id).order_by("-created_at")-- return queryset-- def validate_hash_id(self, hash_id: str, assert_new: bool) -> str:- if len(hash_id) > 128:+ def _validated_hash_id(self, hash_id) -> str | None:+ if not hash_id:+ return None+ hash_id = str(hash_id)+ if len(hash_id) > MAX_HASH_ID_LENGTH:raise ValidationError("Hash id length cannot exceed 128 bytes")-- if assert_new and ErrorTrackingRelease.objects.filter(team=self.team, hash_id=hash_id).exists():- raise ValidationError(f"Hash id {hash_id} already in use")-return hash_id- def update(self, request, *args, **kwargs) -> Response:- release = self.get_object()-- metadata = request.data.get("metadata")- hash_id = request.data.get("hash_id")- version = request.data.get("version")- project = request.data.get("project")-- if metadata:- release.metadata = metadata-- if version:- version = str(version)- release.version = version-- if project:- project = str(project)- release.project = project-- if hash_id and hash_id != release.hash_id:- hash_id = str(hash_id)- hash_id = self.validate_hash_id(hash_id, True)- release.hash_id = hash_id+ def list(self, request, *args, **kwargs) -> Response:+ return paginate_via_facade(+ self,+ request,+ lambda limit, offset: error_tracking_api.list_releases(self.team.id, limit=limit, offset=offset),+ )- release.save()- return Response({"ok": True}, status=status.HTTP_204_NO_CONTENT)+ def retrieve(self, request, *args, pk=None, **kwargs) -> Response:+ release = error_tracking_api.get_release(self.team.id, pk)+ if release is None:+ raise NotFound()+ return Response(self.get_serializer(release).data)+ @extend_schema(+ request=ErrorTrackingReleaseCreateRequestSerializer,+ responses={201: OpenApiResponse(response=ErrorTrackingReleaseSerializer)},+ )def create(self, request, *args, **kwargs) -> Response:- id = UUIDT() # We use this in the hash if one isn't set, and also as the id of the model- metadata = request.data.get("metadata")- hash_id = str(request.data.get("hash_id") or id)- hash_id = self.validate_hash_id(hash_id, True)version = request.data.get("version")project = request.data.get("project")-if not version:raise ValidationError("Version is required")-if not project:raise ValidationError("Project is required")+ hash_id = self._validated_hash_id(request.data.get("hash_id"))+ try:+ release = error_tracking_api.create_release(+ self.team.id,+ version=str(version),+ project=str(project),+ hash_id=hash_id,+ metadata=request.data.get("metadata"),+ )+ except error_tracking_api.ReleaseHashInUseError as err:+ raise ValidationError(f"Hash id {err} already in use")+ return Response(self.get_serializer(release).data, status=status.HTTP_201_CREATED)++ def _apply_update(self, pk: str, data) -> Response:+ hash_id = self._validated_hash_id(data.get("hash_id"))+ try:+ release = error_tracking_api.update_release(+ self.team.id,+ pk,+ metadata=data.get("metadata"),+ hash_id=hash_id,+ version=data.get("version"),+ project=data.get("project"),+ )+ except error_tracking_api.ReleaseHashInUseError as err:+ raise ValidationError(f"Hash id {err} already in use")+ if release is None:+ raise NotFound()+ return Response({"ok": True}, status=status.HTTP_204_NO_CONTENT)- version = str(version)+ @extend_schema(request=ErrorTrackingReleaseUpdateRequestSerializer, responses={204: None})+ def update(self, request, *args, pk=None, **kwargs) -> Response:+ return self._apply_update(pk, request.data)- release = ErrorTrackingRelease.objects.create(- id=id, team=self.team, hash_id=hash_id, metadata=metadata, project=project, version=version- )+ @extend_schema(request=ErrorTrackingReleaseUpdateRequestSerializer, responses={204: None})+ def partial_update(self, request, *args, pk=None, **kwargs) -> Response:+ return self._apply_update(pk, request.data)- serializer = ErrorTrackingReleaseSerializer(release)- return Response(serializer.data, status=status.HTTP_201_CREATED)+ def destroy(self, request, *args, pk=None, **kwargs) -> Response:+ if not error_tracking_api.delete_release(self.team.id, pk):+ raise NotFound()+ return Response(status=status.HTTP_204_NO_CONTENT)@action(detail=False, methods=["get"], url_path="hash/(?P<hash_id>[^/.]+)")- def by_hash(self, request, hash_id=None, **kwargs):- obj = get_object_or_404(self.get_queryset(), hash_id=hash_id)- serializer = self.get_serializer(obj)- return Response(serializer.data)+ def by_hash(self, request, hash_id=None, **kwargs) -> Response:+ release = error_tracking_api.get_release_by_hash(self.team.id, hash_id)+ if release is None:+ raise NotFound()+ return Response(self.get_serializer(release).data)diff --git a/products/error_tracking/backend/presentation/views/settings.py b/products/error_tracking/backend/presentation/views/settings.pyindex 1cbac2b1fbf0..5f6e8183c6b8 100644--- a/products/error_tracking/backend/presentation/views/settings.py+++ b/products/error_tracking/backend/presentation/views/settings.py@@ -5,10 +5,10 @@ from rest_framework.response import Responsefrom posthog.api.routing import TeamAndOrgViewSetMixin-from products.error_tracking.backend.models import ErrorTrackingSettings+from products.error_tracking.backend.facade import api as error_tracking_api-class ErrorTrackingSettingsSerializer(serializers.ModelSerializer):+class ErrorTrackingSettingsSerializer(serializers.Serializer):project_rate_limit_value = serializers.IntegerField(min_value=1,allow_null=True,@@ -34,31 +34,17 @@ class ErrorTrackingSettingsSerializer(serializers.ModelSerializer):help_text="Bucket window over which the per-issue rate limit applies, in minutes.",)- class Meta:- model = ErrorTrackingSettings- fields = [- "project_rate_limit_value",- "project_rate_limit_bucket_size_minutes",- "per_issue_rate_limit_value",- "per_issue_rate_limit_bucket_size_minutes",- ]-class ErrorTrackingSettingsViewSet(TeamAndOrgViewSetMixin, viewsets.ViewSet):scope_object = "error_tracking"scope_object_read_actions = ["retrieve_settings"]scope_object_write_actions = ["update_settings"]- def _get_or_create_settings(self) -> ErrorTrackingSettings:- settings, _ = ErrorTrackingSettings.objects.get_or_create(team=self.team)- return settings-@extend_schema(responses={200: ErrorTrackingSettingsSerializer})@action(detail=False, methods=["get"])def retrieve_settings(self, request, *args, **kwargs):- settings = self._get_or_create_settings()- serializer = ErrorTrackingSettingsSerializer(settings)- return Response(serializer.data)+ settings = error_tracking_api.get_settings(self.team.id)+ return Response(ErrorTrackingSettingsSerializer(settings).data)@extend_schema(request=ErrorTrackingSettingsSerializer,@@ -66,8 +52,7 @@ class ErrorTrackingSettingsViewSet(TeamAndOrgViewSetMixin, viewsets.ViewSet):)@action(detail=False, methods=["patch"])def update_settings(self, request, *args, **kwargs):- settings = self._get_or_create_settings()- serializer = ErrorTrackingSettingsSerializer(settings, data=request.data, partial=True)+ serializer = ErrorTrackingSettingsSerializer(data=request.data, partial=True)serializer.is_valid(raise_exception=True)- serializer.save()- return Response(serializer.data, status=status.HTTP_200_OK)+ settings = error_tracking_api.update_settings(self.team.id, dict(serializer.validated_data))+ return Response(ErrorTrackingSettingsSerializer(settings).data, status=status.HTTP_200_OK)diff --git a/products/error_tracking/backend/presentation/views/spike_detection_config.py b/products/error_tracking/backend/presentation/views/spike_detection_config.pyindex 150deaf38b9b..60948b6f1cbc 100644--- a/products/error_tracking/backend/presentation/views/spike_detection_config.py+++ b/products/error_tracking/backend/presentation/views/spike_detection_config.py@@ -1,4 +1,3 @@-import structlogfrom drf_spectacular.utils import extend_schemafrom rest_framework import serializers, status, viewsetsfrom rest_framework.decorators import action@@ -6,12 +5,10 @@ from rest_framework.response import Responsefrom posthog.api.routing import TeamAndOrgViewSetMixin-from products.error_tracking.backend.models import ErrorTrackingSpikeDetectionConfig+from products.error_tracking.backend.facade import api as error_tracking_api-logger = structlog.get_logger(__name__)--class ErrorTrackingSpikeDetectionConfigSerializer(serializers.ModelSerializer):+class ErrorTrackingSpikeDetectionConfigSerializer(serializers.Serializer):snooze_duration_minutes = serializers.IntegerField(min_value=1,help_text="Time to wait before alerting again for the same issue after a spike is detected.",@@ -25,23 +22,14 @@ class ErrorTrackingSpikeDetectionConfigSerializer(serializers.ModelSerializer):help_text="The minimum number of exceptions required in a 5-minute window before a spike can be detected.",)- class Meta:- model = ErrorTrackingSpikeDetectionConfig- fields = ["snooze_duration_minutes", "multiplier", "threshold"]-class ErrorTrackingSpikeDetectionConfigViewSet(TeamAndOrgViewSetMixin, viewsets.ViewSet):scope_object = "error_tracking"- def _get_or_create_config(self):- config, _ = ErrorTrackingSpikeDetectionConfig.objects.get_or_create(team=self.team)- return config-@extend_schema(responses={200: ErrorTrackingSpikeDetectionConfigSerializer})def list(self, request, *args, **kwargs):- config = self._get_or_create_config()- serializer = ErrorTrackingSpikeDetectionConfigSerializer(config)- return Response(serializer.data)+ config = error_tracking_api.get_spike_detection_config(self.team.id)+ return Response(ErrorTrackingSpikeDetectionConfigSerializer(config).data)@extend_schema(request=ErrorTrackingSpikeDetectionConfigSerializer,@@ -49,8 +37,7 @@ class ErrorTrackingSpikeDetectionConfigViewSet(TeamAndOrgViewSetMixin, viewsets.)@action(detail=False, methods=["patch"])def update_config(self, request, *args, **kwargs):- config = self._get_or_create_config()- serializer = ErrorTrackingSpikeDetectionConfigSerializer(config, data=request.data, partial=True)+ serializer = ErrorTrackingSpikeDetectionConfigSerializer(data=request.data, partial=True)serializer.is_valid(raise_exception=True)- serializer.save()- return Response(serializer.data, status=status.HTTP_200_OK)+ config = error_tracking_api.update_spike_detection_config(self.team.id, dict(serializer.validated_data))+ return Response(ErrorTrackingSpikeDetectionConfigSerializer(config).data, status=status.HTTP_200_OK)diff --git a/products/error_tracking/backend/presentation/views/spike_events.py b/products/error_tracking/backend/presentation/views/spike_events.pyindex d64c33d85703..ce156048c3cd 100644--- a/products/error_tracking/backend/presentation/views/spike_events.py+++ b/products/error_tracking/backend/presentation/views/spike_events.py@@ -1,66 +1,41 @@-from rest_framework import mixins, serializers, viewsets+from rest_framework import viewsets+from rest_framework_dataclasses.serializers import DataclassSerializerfrom posthog.api.routing import TeamAndOrgViewSetMixin-from products.error_tracking.backend.models import ErrorTrackingIssue, ErrorTrackingSpikeEvent+from products.error_tracking.backend.facade import (+ api as error_tracking_api,+ contracts,+)+from products.error_tracking.backend.presentation.pagination import paginate_via_facade-class ErrorTrackingSpikeEventIssueSerializer(serializers.ModelSerializer):+class ErrorTrackingSpikeEventSerializer(DataclassSerializer):class Meta:- model = ErrorTrackingIssue- fields = ["id", "name", "description"]- read_only_fields = fields+ dataclass = contracts.ErrorTrackingSpikeEvent-class ErrorTrackingSpikeEventSerializer(serializers.ModelSerializer):- issue = ErrorTrackingSpikeEventIssueSerializer(read_only=True)-- class Meta:- model = ErrorTrackingSpikeEvent- fields = [- "id",- "issue",- "detected_at",- "computed_baseline",- "current_bucket_value",- ]- read_only_fields = fields---class ErrorTrackingSpikeEventViewSet(TeamAndOrgViewSetMixin, mixins.ListModelMixin, viewsets.GenericViewSet):+class ErrorTrackingSpikeEventViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):scope_object = "error_tracking"serializer_class = ErrorTrackingSpikeEventSerializer- queryset = ErrorTrackingSpikeEvent.objects.all()-- ALLOWED_ORDER_FIELDS = [- "detected_at",- "-detected_at",- "computed_baseline",- "-computed_baseline",- "current_bucket_value",- "-current_bucket_value",- ]-- def safely_get_queryset(self, queryset):- qs = queryset.filter(team_id=self.team.id).select_related("issue")-- issue_ids_param = self.request.query_params.get("issue_ids")- if issue_ids_param:- ids = [uid.strip() for uid in issue_ids_param.split(",") if uid.strip()]- if ids:- qs = qs.filter(issue_id__in=ids)-- date_from = self.request.query_params.get("date_from")- date_to = self.request.query_params.get("date_to")- if date_from:- qs = qs.filter(detected_at__gte=date_from)- if date_to:- qs = qs.filter(detected_at__lte=date_to)-- order_by = self.request.query_params.get("order_by")- if order_by and order_by in self.ALLOWED_ORDER_FIELDS:- qs = qs.order_by(order_by)- else:- qs = qs.order_by("-detected_at")- return qs+ def list(self, request, *args, **kwargs):+ issue_ids_param = request.query_params.get("issue_ids")+ issue_ids = [uid.strip() for uid in issue_ids_param.split(",") if uid.strip()] if issue_ids_param else None+ date_from = request.query_params.get("date_from")+ date_to = request.query_params.get("date_to")+ order_by = request.query_params.get("order_by")++ return paginate_via_facade(+ self,+ request,+ lambda limit, offset: error_tracking_api.list_spike_events(+ team_id=self.team.id,+ issue_ids=issue_ids or None,+ date_from=date_from,+ date_to=date_to,+ order_by=order_by,+ limit=limit,+ offset=offset,+ ),+ )diff --git a/products/error_tracking/backend/presentation/views/stack_frames.py b/products/error_tracking/backend/presentation/views/stack_frames.pyindex c5269fc68275..96138b246c58 100644--- a/products/error_tracking/backend/presentation/views/stack_frames.py+++ b/products/error_tracking/backend/presentation/views/stack_frames.py@@ -1,65 +1,67 @@-from django.db.models import Q--import structlog-from drf_spectacular.utils import extend_schema_field+from drf_spectacular.utils import OpenApiResponse, extend_schemafrom rest_framework import serializers, viewsets+from rest_framework.exceptions import NotFoundfrom rest_framework.response import Response+from rest_framework_dataclasses.serializers import DataclassSerializerfrom posthog.api.forbid_destroy_model import ForbidDestroyModelfrom posthog.api.routing import TeamAndOrgViewSetMixinfrom posthog.api.utils import action-from products.error_tracking.backend.models import ErrorTrackingStackFrame-from products.error_tracking.backend.presentation.views.releases import ErrorTrackingReleaseSerializer+from products.error_tracking.backend.facade import (+ api as error_tracking_api,+ contracts,+)+from products.error_tracking.backend.presentation.pagination import paginate_via_facade-logger = structlog.get_logger(__name__)+class ErrorTrackingStackFrameSerializer(DataclassSerializer):+ class Meta:+ dataclass = contracts.ErrorTrackingStackFrame-class ErrorTrackingStackFrameSerializer(serializers.ModelSerializer):- symbol_set_ref = serializers.CharField(source="symbol_set.ref", default=None)- release = ErrorTrackingReleaseSerializer(source="symbol_set.release", read_only=True)- raw_id = serializers.SerializerMethodField()- class Meta:- model = ErrorTrackingStackFrame- fields = ["id", "raw_id", "created_at", "contents", "resolved", "context", "symbol_set_ref", "release"]+class ErrorTrackingStackFrameBatchGetRequestSerializer(serializers.Serializer):+ raw_ids = serializers.ListField(+ child=serializers.CharField(),+ help_text="Raw frame IDs in 'hash/part' format to resolve in a single request.",+ )+ symbol_set = serializers.CharField(+ required=False,+ allow_null=True,+ help_text="Optional symbol set reference to scope the lookup to a single symbol set.",+ )- @extend_schema_field(serializers.CharField(help_text="Raw frame ID in 'hash/part' format"))- def get_raw_id(self, obj):- return obj.raw_id + "/" + str(obj.part)+class ErrorTrackingStackFrameBatchGetResponseSerializer(serializers.Serializer):+ results = ErrorTrackingStackFrameSerializer(many=True, help_text="Resolved stack frames for the requested raw IDs.")-class ErrorTrackingStackFrameViewSet(TeamAndOrgViewSetMixin, ForbidDestroyModel, viewsets.ReadOnlyModelViewSet):++class ErrorTrackingStackFrameViewSet(TeamAndOrgViewSetMixin, ForbidDestroyModel, viewsets.GenericViewSet):scope_object = "error_tracking"scope_object_read_actions = ["list", "retrieve", "batch_get"]scope_object_write_actions: list = []- queryset = ErrorTrackingStackFrame.objects.all()serializer_class = ErrorTrackingStackFrameSerializer+ def list(self, request, *args, **kwargs):+ return paginate_via_facade(+ self,+ request,+ lambda limit, offset: error_tracking_api.list_stack_frames(self.team.id, limit=limit, offset=offset),+ )++ def retrieve(self, request, *args, pk=None, **kwargs):+ frame = error_tracking_api.get_stack_frame(self.team.id, pk)+ if frame is None:+ raise NotFound()+ return Response(self.get_serializer(frame).data)++ @extend_schema(+ request=ErrorTrackingStackFrameBatchGetRequestSerializer,+ responses={200: OpenApiResponse(response=ErrorTrackingStackFrameBatchGetResponseSerializer)},+ )@action(methods=["POST"], detail=False)def batch_get(self, request, **kwargs):raw_ids = request.data.get("raw_ids", [])symbol_set = request.data.get("symbol_set", None)-- queryset = self.queryset.filter(team_id=self.team.id).select_related("symbol_set__release")-- if raw_ids:- query_id_objects = Q()- for raw_id in raw_ids:- hash_id, part = get_raw_id_part(raw_id)- query_id_objects |= Q(raw_id=hash_id, part=part)-- queryset = queryset.filter(query_id_objects)-- if symbol_set:- queryset = queryset.filter(symbol_set=symbol_set)-- serializer = self.get_serializer(queryset, many=True)- return Response({"results": serializer.data})---def get_raw_id_part(raw_id):- res = raw_id.split("/")- if len(res) != 2:- return raw_id, 0- return res[0], int(res[1])+ frames = error_tracking_api.batch_get_stack_frames(self.team.id, raw_ids, symbol_set)+ return Response({"results": self.get_serializer(frames, many=True).data})diff --git a/products/error_tracking/backend/presentation/views/suppression_rules.py b/products/error_tracking/backend/presentation/views/suppression_rules.pyindex 1e13d2aa3dc7..d019557cfdde 100644--- a/products/error_tracking/backend/presentation/views/suppression_rules.py+++ b/products/error_tracking/backend/presentation/views/suppression_rules.py@@ -1,35 +1,31 @@-from typing import override-import structlogimport posthoganalyticsfrom drf_spectacular.utils import OpenApiResponse, extend_schema_fieldfrom pydantic import ValidationError as PydanticValidationErrorfrom rest_framework import serializers, status, viewsets+from rest_framework.exceptions import NotFoundfrom rest_framework.response import Responsefrom posthog.schema import PropertyGroupFilterValuefrom posthog.api.mixins import ValidatedRequest, validated_requestfrom posthog.api.routing import TeamAndOrgViewSetMixin+from posthog.api.utils import actionfrom posthog.event_usage import groups-from posthog.models.team.team import Team-from products.error_tracking.backend.models import ErrorTrackingSuppressionRule-from products.error_tracking.backend.presentation.views.utils import (- RuleReorderingMixin,- generate_byte_code,- generate_match_all_bytecode,- has_filter_values,-)+from products.error_tracking.backend.facade import api as error_tracking_apilogger = structlog.get_logger(__name__)-class ErrorTrackingSuppressionRuleSerializer(serializers.ModelSerializer):- class Meta:- model = ErrorTrackingSuppressionRule- fields = ["id", "filters", "order_key", "disabled_data", "sampling_rate", "created_at", "updated_at"]- read_only_fields = ["team_id", "created_at", "updated_at"]+class ErrorTrackingSuppressionRuleSerializer(serializers.Serializer):+ id = serializers.UUIDField(read_only=True)+ filters = serializers.JSONField()+ order_key = serializers.IntegerField()+ disabled_data = serializers.JSONField(allow_null=True)+ sampling_rate = serializers.FloatField()+ created_at = serializers.DateTimeField(read_only=True)+ updated_at = serializers.DateTimeField(read_only=True)@extend_schema_field(PropertyGroupFilterValue) # type: ignore[arg-type]@@ -40,7 +36,7 @@ class ErrorTrackingSuppressionRuleFiltersField(serializers.JSONField):if not isinstance(value, dict):raise serializers.ValidationError("Expected an object.")- if has_filter_values(value):+ if error_tracking_api.has_filter_values(value):try:PropertyGroupFilterValue(**value)except (PydanticValidationError, TypeError) as err:@@ -92,129 +88,82 @@ class ErrorTrackingSuppressionRuleUpdateRequestSerializer(serializers.Serializer)-class ErrorTrackingSuppressionRuleViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet, RuleReorderingMixin):+class ErrorTrackingSuppressionRuleViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):scope_object = "error_tracking"- queryset = ErrorTrackingSuppressionRule.objects.order_by("order_key").all()serializer_class = ErrorTrackingSuppressionRuleSerializer- @override- def safely_get_queryset(self, queryset):- return queryset.filter(team_id=self.team.id)-- def _apply_rule_update(self, request: ValidatedRequest) -> Response:- suppression_rule = self.get_object()- json_filters = request.validated_data.get("filters")-- if json_filters is not None:- if has_filter_values(json_filters):- parsed_filters = PropertyGroupFilterValue(**json_filters)- suppression_rule.filters = json_filters- suppression_rule.bytecode = generate_byte_code(self.team, parsed_filters)- else:- suppression_rule.filters = json_filters- suppression_rule.bytecode = generate_match_all_bytecode()- if "sampling_rate" in request.validated_data:- suppression_rule.sampling_rate = request.validated_data["sampling_rate"]- suppression_rule.disabled_data = None- suppression_rule.save()-+ def list(self, request, *args, **kwargs) -> Response:+ rules = error_tracking_api.list_suppression_rules(self.team.id)+ page = self.paginate_queryset(rules)+ if page is not None:+ return self.get_paginated_response(self.get_serializer(page, many=True).data)+ return Response(self.get_serializer(rules, many=True).data)++ def retrieve(self, request, *args, pk=None, **kwargs) -> Response:+ rule = error_tracking_api.get_suppression_rule(self.team.id, pk)+ if rule is None:+ raise NotFound()+ return Response(self.get_serializer(rule).data)++ def _apply_rule_update(self, request: ValidatedRequest, pk: str) -> Response:+ rule = error_tracking_api.update_suppression_rule(+ self.team.id,+ pk,+ filters=request.validated_data.get("filters"),+ sampling_rate=request.validated_data.get("sampling_rate"),+ )+ if rule is None:+ raise NotFound()posthoganalytics.capture("error_tracking_suppression_rule_edited",groups=groups(self.team.organization, self.team),)-return Response({"ok": True}, status=status.HTTP_204_NO_CONTENT)- @override@validated_request(request_serializer=ErrorTrackingSuppressionRuleUpdateRequestSerializer,responses={204: None},)- def update(self, request: ValidatedRequest, *args, **kwargs) -> Response:- return self._apply_rule_update(request)+ def update(self, request: ValidatedRequest, *args, pk=None, **kwargs) -> Response:+ return self._apply_rule_update(request, pk)- @override@validated_request(request_serializer=ErrorTrackingSuppressionRuleUpdateRequestSerializer,responses={204: None},)- def partial_update(self, request: ValidatedRequest, *args, **kwargs) -> Response:- return self._apply_rule_update(request)-- @override- def destroy(self, request, *args, **kwargs) -> Response:- response = super().destroy(request, *args, **kwargs)+ def partial_update(self, request: ValidatedRequest, *args, pk=None, **kwargs) -> Response:+ return self._apply_rule_update(request, pk)+ def destroy(self, request, *args, pk=None, **kwargs) -> Response:+ if not error_tracking_api.delete_suppression_rule(self.team.id, pk):+ raise NotFound()posthoganalytics.capture("error_tracking_suppression_rule_deleted",groups=groups(self.team.organization, self.team),)-- return response+ return Response(status=status.HTTP_204_NO_CONTENT)@validated_request(request_serializer=ErrorTrackingSuppressionRuleCreateRequestSerializer,responses={201: OpenApiResponse(response=ErrorTrackingSuppressionRuleSerializer)},)def create(self, request: ValidatedRequest, *args, **kwargs) -> Response:- json_filters = request.validated_data.get("filters")-- if json_filters is None:- json_filters = {"type": "AND", "values": []}-- if has_filter_values(json_filters):- bytecode = generate_byte_code(self.team, PropertyGroupFilterValue(**json_filters))- else:- bytecode = generate_match_all_bytecode()-- sampling_rate = request.validated_data["sampling_rate"]-- suppression_rule = ErrorTrackingSuppressionRule.objects.create(- team=self.team,- filters=json_filters,- bytecode=bytecode,- order_key=0,- sampling_rate=sampling_rate,+ filters = request.validated_data.get("filters")+ if filters is None:+ filters = {"type": "AND", "values": []}+ rule = error_tracking_api.create_suppression_rule(+ self.team.id,+ filters=filters,+ sampling_rate=request.validated_data["sampling_rate"],)-posthoganalytics.capture("error_tracking_suppression_rule_created",groups=groups(self.team.organization, self.team),)+ return Response(self.get_serializer(rule).data, status=status.HTTP_201_CREATED)- serializer = ErrorTrackingSuppressionRuleSerializer(suppression_rule)- return Response(serializer.data, status=status.HTTP_201_CREATED)---# Properties that require server-side symbol resolution to have meaningful-# values. Client-side these will contain minified/bundled names.-SERVER_ONLY_PROPERTIES = frozenset({"$exception_sources", "$exception_functions"})---def _get_client_safe_filters(filters: dict) -> dict | None:- """Return the filters if every leaf is client-safe, otherwise None.-- If any filter in the tree uses a server-only property, the entire rule- is not evaluated client-side.- """- for value in filters.get("values", []):- if "key" in value:- if value.get("key") in SERVER_ONLY_PROPERTIES:- return None- elif "values" in value:- if _get_client_safe_filters(value) is None:- return None- return filters---def get_client_safe_suppression_rules(team: Team) -> list[dict]:- rules = list(ErrorTrackingSuppressionRule.objects.filter(team=team).values_list("filters", "sampling_rate"))- result = []- for filters, sampling_rate in rules:- safe = _get_client_safe_filters(filters)- if safe is not None:- rule_data = {**safe}- if sampling_rate < 1.0:- rule_data["samplingRate"] = sampling_rate- result.append(rule_data)- return result+ @action(methods=["PATCH"], detail=False)+ def reorder(self, request, **kwargs) -> Response:+ orders: dict[str, int] = request.data.get("orders", {})+ error_tracking_api.reorder_suppression_rules(self.team.id, orders)+ return Response({"ok": True}, status=status.HTTP_204_NO_CONTENT)diff --git a/products/error_tracking/backend/presentation/views/symbol_sets.py b/products/error_tracking/backend/presentation/views/symbol_sets.pyindex c719c83baf2f..72c2921fad80 100644--- a/products/error_tracking/backend/presentation/views/symbol_sets.py+++ b/products/error_tracking/backend/presentation/views/symbol_sets.py@@ -113,10 +113,21 @@ class ErrorTrackingSymbolSetSerializer(serializers.ModelSerializer):@extend_schema_field(serializers.DictField(allow_null=True, help_text="Release associated with this symbol set"))def get_release(self, obj):+ from products.error_tracking.backend.facade import contractsfrom products.error_tracking.backend.presentation.views.releases import ErrorTrackingReleaseSerializerif obj.release:- return ErrorTrackingReleaseSerializer(obj.release).data+ release = obj.release+ dto = contracts.ErrorTrackingRelease(+ id=release.id,+ hash_id=release.hash_id,+ team_id=release.team_id,+ created_at=release.created_at,+ metadata=release.metadata,+ version=release.version,+ project=release.project,+ )+ return ErrorTrackingReleaseSerializer(dto).datareturn Nonediff --git a/products/error_tracking/backend/presentation/views/utils.py b/products/error_tracking/backend/presentation/views/utils.pydeleted file mode 100644index 04d6452517d6..000000000000--- a/products/error_tracking/backend/presentation/views/utils.py+++ /dev/null@@ -1,86 +0,0 @@-from typing import Any, Protocol, TypeVar--import structlog-from rest_framework import status-from rest_framework.exceptions import ValidationError-from rest_framework.response import Response--from posthog.schema import PropertyGroupFilterValue--from posthog.hogql import ast-from posthog.hogql.compiler.bytecode import create_bytecode-from posthog.hogql.property import property_to_expr--from posthog.api.utils import action-from posthog.models.team.team import Team--from products.error_tracking.backend.hogvm_stl import RUST_HOGVM_STL--from common.hogvm.python.operation import Operation--logger = structlog.get_logger(__name__)---class HasGetQueryset(Protocol):- def get_queryset(self): ...---T = TypeVar("T", bound=HasGetQueryset)---class RuleReorderingMixin:- @action(methods=["PATCH"], detail=False)- def reorder(self: T, request, **kwargs):- orders: dict[str, int] = request.data.get("orders", {})- rules = self.get_queryset().filter(id__in=orders.keys())-- for rule in rules:- rule.order_key = orders[str(rule.id)]-- self.get_queryset().bulk_update(rules, ["order_key"])-- return Response({"ok": True}, status=status.HTTP_204_NO_CONTENT)---def generate_byte_code(team: Team, props: PropertyGroupFilterValue):- expr = property_to_expr(props, team, strict=True)- # The rust HogVM expects a return statement, so we wrap the compiled filter expression in one- with_return = ast.ReturnStatement(expr=expr)- bytecode = create_bytecode(with_return).bytecode- validate_bytecode(bytecode)- return bytecode---def generate_match_all_bytecode():- """Generate bytecode that always returns true (matches all events)."""- with_return = ast.ReturnStatement(expr=ast.Constant(value=True))- return create_bytecode(with_return).bytecode---def has_filter_values(json_filters: dict) -> bool:- """Check whether a filter dict contains any actual filter values, recursively.-- Non-dict entries are treated as "has values" so the request reaches pydantic- validation and gets rejected with a 400 instead of raising AttributeError.- """- values = json_filters.get("values", [])- if not values:- return False- for v in values:- if not isinstance(v, dict):- return True- if "key" in v or has_filter_values(v):- return True- return False---def validate_bytecode(bytecode: list[Any]) -> None:- for i, op in enumerate(bytecode):- if not isinstance(op, Operation):- continue- if op == Operation.CALL_GLOBAL:- name = bytecode[i + 1]- if not isinstance(name, str):- raise ValidationError(f"Expected string for global function name, got {type(name)}")- if name not in RUST_HOGVM_STL:- raise ValidationError(f"Unknown global function: {name}")diff --git a/products/error_tracking/backend/remote_config.py b/products/error_tracking/backend/remote_config.pyindex 49c33e9c7e1c..688412e5dd1c 100644--- a/products/error_tracking/backend/remote_config.py+++ b/products/error_tracking/backend/remote_config.py@@ -1,10 +1,10 @@from posthog.models.team.team import Team-from products.error_tracking.backend.presentation.views.suppression_rules import get_client_safe_suppression_rules+from products.error_tracking.backend.logic import get_client_safe_suppression_rulesdef build_error_tracking_config(team: Team) -> dict:return {"autocaptureExceptions": bool(team.autocapture_exceptions_opt_in),- "suppressionRules": get_client_safe_suppression_rules(team),+ "suppressionRules": get_client_safe_suppression_rules(team.id),}diff --git a/products/error_tracking/backend/test/test_facade_api.py b/products/error_tracking/backend/test/test_facade_api.pyindex fe0866679280..228f8a5eb046 100644--- a/products/error_tracking/backend/test/test_facade_api.py+++ b/products/error_tracking/backend/test/test_facade_api.py@@ -160,3 +160,39 @@ class TestErrorTrackingFacadeAPI(BaseTest):assert result.issue.id == issue.idassert result.issue.team_id == self.team.idassert result.issue.name == "Assigned issue"++ def test_get_settings_creates_defaults(self):+ settings = api.get_settings(self.team.id)++ assert isinstance(settings, contracts.ErrorTrackingSettings)+ assert settings.project_rate_limit_value is None+ assert settings.per_issue_rate_limit_value is None++ def test_update_settings_persists_and_is_partial(self):+ api.update_settings(+ self.team.id,+ {"project_rate_limit_value": 100, "project_rate_limit_bucket_size_minutes": 5},+ )+ updated = api.update_settings(self.team.id, {"per_issue_rate_limit_value": 7})++ assert updated.project_rate_limit_value == 100+ assert updated.project_rate_limit_bucket_size_minutes == 5+ assert updated.per_issue_rate_limit_value == 7+ # a fresh read reflects the same persisted state, scoped to the team+ assert api.get_settings(self.team.id) == updated++ def test_update_settings_scoped_by_team(self):+ other_team = Team.objects.create(organization=self.organization, name="Other team")+ api.update_settings(self.team.id, {"project_rate_limit_value": 42})++ assert api.get_settings(other_team.id).project_rate_limit_value is None++ def test_spike_detection_config_get_and_update(self):+ config = api.get_spike_detection_config(self.team.id)+ assert isinstance(config, contracts.ErrorTrackingSpikeDetectionConfig)++ updated = api.update_spike_detection_config(self.team.id, {"multiplier": 9, "threshold": 50})++ assert updated.multiplier == 9+ assert updated.threshold == 50+ assert api.get_spike_detection_config(self.team.id) == updateddiff --git a/products/error_tracking/backend/tests/api/test_assignment_rules.py b/products/error_tracking/backend/tests/api/test_assignment_rules.pyindex b974d1090792..4f5dc8504d0d 100644--- a/products/error_tracking/backend/tests/api/test_assignment_rules.py+++ b/products/error_tracking/backend/tests/api/test_assignment_rules.py@@ -6,8 +6,8 @@ from posthog.test.base import APIBaseTestfrom parameterized import parameterizedfrom rest_framework import status+from products.error_tracking.backend.logic import match_all_bytecodefrom products.error_tracking.backend.models import ErrorTrackingAssignmentRule-from products.error_tracking.backend.presentation.views.utils import generate_match_all_bytecodeVALID_FILTERS = {"type": "AND",@@ -258,7 +258,7 @@ class TestAssignmentRuleAPI(APIBaseTest):rule = ErrorTrackingAssignmentRule.objects.get(id=response.json()["id"])assert rule.disabled_data is None- assert rule.bytecode == generate_match_all_bytecode()+ assert rule.bytecode == match_all_bytecode()@parameterized.expand([@@ -287,7 +287,7 @@ class TestAssignmentRuleAPI(APIBaseTest):rule.refresh_from_db()assert rule.filters == empty_filtersassert rule.disabled_data is None- assert rule.bytecode == generate_match_all_bytecode()+ assert rule.bytecode == match_all_bytecode()def test_update_accepts_frontend_payload_shape_with_extra_fields(self) -> None:rule = self._create_rule()diff --git a/products/error_tracking/backend/tests/api/test_error_tracking_api.py b/products/error_tracking/backend/tests/api/test_error_tracking_api.pyindex ad1ae04c6808..fca5295ca4fd 100644--- a/products/error_tracking/backend/tests/api/test_error_tracking_api.py+++ b/products/error_tracking/backend/tests/api/test_error_tracking_api.py@@ -4,6 +4,9 @@ from freezegun import freeze_timefrom posthog.test.base import APIBaseTest, ClickhouseTestMixinfrom unittest.mock import ANY, Mock, patch+from django.db import connection+from django.test.utils import CaptureQueriesContext+from boto3 import resourcefrom botocore.config import Configfrom parameterized import parameterized@@ -551,6 +554,14 @@ class TestErrorTracking(APIBaseTest):self.assertEqual(len(response.json()["results"]), 1)self.assertEqual(response.json()["results"][0]["symbol_set_ref"], symbol_set.ref)+ # a malformed raw_id (non-integer part) is handled gracefully, not a 500+ data = {"raw_ids": ["abc/not-an-int"]}+ response = self.client.post(+ f"/api/environments/{self.team.id}/error_tracking/stack_frames/batch_get", data=data+ )+ self.assertEqual(response.status_code, status.HTTP_200_OK)+ self.assertEqual(response.json()["results"], [])+def test_assigning_issues(self):issue = self.create_issue()@@ -1124,6 +1135,27 @@ class TestErrorTracking(APIBaseTest):response = self.client.get(f"/api/environments/{self.team.id}/error_tracking/releases/hash/nonexistent-hash")assert response.status_code == status.HTTP_404_NOT_FOUND+ def test_releases_list_paginates_in_sql(self) -> None:+ for i in range(5):+ ErrorTrackingRelease.objects.create(team=self.team, hash_id=f"hash-{i}", version=f"1.0.{i}", project="proj")++ with CaptureQueriesContext(connection) as ctx:+ response = self.client.get(+ f"/api/environments/{self.team.id}/error_tracking/releases", data={"limit": 2, "offset": 1}+ )++ assert response.status_code == status.HTTP_200_OK+ body = response.json()+ assert body["count"] == 5+ assert len(body["results"]) == 2++ # The page is sliced in SQL (LIMIT 2), not by materializing all rows and slicing in Python.+ table = ErrorTrackingRelease._meta.db_table+ limited_selects = [+ q["sql"] for q in ctx.captured_queries if table in q["sql"] and "LIMIT 2" in q["sql"].upper()+ ]+ assert limited_selects, "expected a LIMIT 2 SELECT on the release table"+class TestIssueStateSync(ClickhouseTestMixin, APIBaseTest):def _create_issue(self, fingerprints=None, **kwargs) -> ErrorTrackingIssue:diff --git a/products/error_tracking/backend/tests/api/test_suppression_rules.py b/products/error_tracking/backend/tests/api/test_suppression_rules.pyindex 9943dc305932..d770f7334fa0 100644--- a/products/error_tracking/backend/tests/api/test_suppression_rules.py+++ b/products/error_tracking/backend/tests/api/test_suppression_rules.py@@ -5,14 +5,12 @@ from django.test import TestCasefrom parameterized import parameterizedfrom rest_framework import status-from posthog.schema import PropertyGroupFilterValue--from products.error_tracking.backend.models import ErrorTrackingSuppressionRule-from products.error_tracking.backend.presentation.views.suppression_rules import (- _get_client_safe_filters,+from products.error_tracking.backend.logic import (+ compile_filter_bytecode,+ get_client_safe_filters,get_client_safe_suppression_rules,)-from products.error_tracking.backend.presentation.views.utils import generate_byte_code+from products.error_tracking.backend.models import ErrorTrackingSuppressionRulefrom common.hogvm.python.execute import execute_bytecode@@ -150,7 +148,7 @@ class TestGetClientSafeFilters(TestCase):])def test_get_client_safe_filters(self, _name: str, filters: dict, expected: dict | None) -> None:- assert _get_client_safe_filters(filters) == expected+ assert get_client_safe_filters(filters) == expectedclass TestGetClientSafeSuppressionRules(APIBaseTest):@@ -158,7 +156,7 @@ class TestGetClientSafeSuppressionRules(APIBaseTest):filters = {"values": [{"operator": "is", "key": "$exception_types", "value": "TypeError"}]}ErrorTrackingSuppressionRule.objects.create(team=self.team, filters=filters, bytecode=[], order_key=0)- result = get_client_safe_suppression_rules(self.team)+ result = get_client_safe_suppression_rules(self.team.id)assert len(result) == 1assert result[0] == filters@@ -173,7 +171,7 @@ class TestGetClientSafeSuppressionRules(APIBaseTest):}ErrorTrackingSuppressionRule.objects.create(team=self.team, filters=filters, bytecode=[], order_key=0)- result = get_client_safe_suppression_rules(self.team)+ result = get_client_safe_suppression_rules(self.team.id)assert result == []@@ -187,7 +185,7 @@ class TestGetClientSafeSuppressionRules(APIBaseTest):}ErrorTrackingSuppressionRule.objects.create(team=self.team, filters=filters, bytecode=[], order_key=0)- result = get_client_safe_suppression_rules(self.team)+ result = get_client_safe_suppression_rules(self.team.id)assert result == []@@ -201,12 +199,12 @@ class TestGetClientSafeSuppressionRules(APIBaseTest):}ErrorTrackingSuppressionRule.objects.create(team=self.team, filters=filters, bytecode=[], order_key=0)- result = get_client_safe_suppression_rules(self.team)+ result = get_client_safe_suppression_rules(self.team.id)assert result == []def test_returns_empty_list_when_no_rules_exist(self) -> None:- result = get_client_safe_suppression_rules(self.team)+ result = get_client_safe_suppression_rules(self.team.id)assert result == []@@ -231,7 +229,7 @@ class TestGetClientSafeSuppressionRules(APIBaseTest):ErrorTrackingSuppressionRule.objects.create(team=self.team, filters=has_server_only, bytecode=[], order_key=1)ErrorTrackingSuppressionRule.objects.create(team=self.team, filters=also_safe, bytecode=[], order_key=2)- result = get_client_safe_suppression_rules(self.team)+ result = get_client_safe_suppression_rules(self.team.id)assert len(result) == 2assert safe_filters in result@@ -243,7 +241,7 @@ class TestGetClientSafeSuppressionRules(APIBaseTest):team=self.team, filters=filters, bytecode=[], order_key=0, sampling_rate=0.5)- result = get_client_safe_suppression_rules(self.team)+ result = get_client_safe_suppression_rules(self.team.id)assert len(result) == 1assert result[0] == {**filters, "samplingRate": 0.5}@@ -254,7 +252,7 @@ class TestGetClientSafeSuppressionRules(APIBaseTest):team=self.team, filters=filters, bytecode=[], order_key=0, sampling_rate=1.0)- result = get_client_safe_suppression_rules(self.team)+ result = get_client_safe_suppression_rules(self.team.id)assert len(result) == 1assert "samplingRate" not in result[0]@@ -344,9 +342,9 @@ class TestClientServerFilterConsistency(APIBaseTest):def test_client_safe_bytecode_matches_server(self, _name: str, filters: dict, cases: list[tuple[dict, bool]]) -> None:- assert _get_client_safe_filters(filters) is not None+ assert get_client_safe_filters(filters) is not None- bytecode = generate_byte_code(self.team, PropertyGroupFilterValue(**filters))+ bytecode = compile_filter_bytecode(self.team.id, filters)for event_props, expected in cases:assert self._eval(bytecode, event_props) == expected, f"Expected {expected} for props {event_props}"diff --git a/products/error_tracking/frontend/generated/api.schemas.ts b/products/error_tracking/frontend/generated/api.schemas.tsindex 2259eddd4555..a7dcdc4c45ba 100644--- a/products/error_tracking/frontend/generated/api.schemas.ts+++ b/products/error_tracking/frontend/generated/api.schemas.ts@@ -20,12 +20,8 @@ export interface ErrorTrackingAssignmentRuleApi {filters: unknown/** @nullable */readonly assignee: ErrorTrackingAssignmentRuleApiAssignee- /**- * @minimum -2147483648- * @maximum 2147483647- */order_key: number- disabled_data?: unknown+ disabled_data: unknownreadonly created_at: stringreadonly updated_at: string}@@ -368,10 +364,6 @@ export interface PatchedErrorTrackingAssignmentRuleApi {filters?: unknown/** @nullable */readonly assignee?: PatchedErrorTrackingAssignmentRuleApiAssignee- /**- * @minimum -2147483648- * @maximum 2147483647- */order_key?: numberdisabled_data?: unknownreadonly created_at?: string@@ -447,18 +439,14 @@ export interface ErrorTrackingGroupingRuleApi {/** @nullable */readonly assignee: ErrorTrackingGroupingRuleApiAssignee/** @nullable */- description?: string | null+ description: string | null/*** Issue linked to this rule* @nullable*/readonly issue: ErrorTrackingGroupingRuleApiIssue- /**- * @minimum -2147483648- * @maximum 2147483647- */order_key: number- disabled_data?: unknown+ disabled_data: unknownreadonly created_at: stringreadonly updated_at: string}@@ -525,10 +513,6 @@ export interface PatchedErrorTrackingGroupingRuleApi {* @nullable*/readonly issue?: PatchedErrorTrackingGroupingRuleApiIssue- /**- * @minimum -2147483648- * @maximum 2147483647- */order_key?: numberdisabled_data?: unknownreadonly created_at?: string@@ -1295,12 +1279,18 @@ export interface PaginatedErrorTrackingRecommendationListApi {results: ErrorTrackingRecommendationApi[]}+/**+ * @nullable+ */+export type ErrorTrackingReleaseApiMetadata = { [key: string]: unknown } | null+export interface ErrorTrackingReleaseApi {- readonly id: string+ id: stringhash_id: string- readonly team_id: number- readonly created_at: string- metadata?: unknown+ team_id: number+ created_at: string+ /** @nullable */+ metadata: ErrorTrackingReleaseApiMetadataversion: stringproject: string}@@ -1314,14 +1304,88 @@ export interface PaginatedErrorTrackingReleaseListApi {results: ErrorTrackingReleaseApi[]}-export interface PatchedErrorTrackingReleaseApi {- readonly id?: string- hash_id?: string- readonly team_id?: number- readonly created_at?: string- metadata?: unknown- version?: string- project?: string+/**+ * Optional free-form metadata object stored alongside the release.+ * @nullable+ */+export type ErrorTrackingReleaseCreateRequestApiMetadata = { [key: string]: unknown } | null++export interface ErrorTrackingReleaseCreateRequestApi {+ /** Human-readable release version, e.g. a semver string or build number. */+ version: string+ /** Identifier of the project this release belongs to. */+ project: string+ /**+ * Optional client-supplied release hash (e.g. a git commit SHA). Generated server-side when omitted.+ * @maxLength 128+ * @nullable+ */+ hash_id?: string | null+ /**+ * Optional free-form metadata object stored alongside the release.+ * @nullable+ */+ metadata?: ErrorTrackingReleaseCreateRequestApiMetadata+}++/**+ * Free-form metadata object. Omit to preserve the current value.+ * @nullable+ */+export type ErrorTrackingReleaseUpdateRequestApiMetadata = { [key: string]: unknown } | null++export interface ErrorTrackingReleaseUpdateRequestApi {+ /**+ * Human-readable release version. Omit to preserve the current value.+ * @nullable+ */+ version?: string | null+ /**+ * Project identifier. Omit to preserve the current value.+ * @nullable+ */+ project?: string | null+ /**+ * Release hash (e.g. a git commit SHA). Omit to preserve the current value.+ * @maxLength 128+ * @nullable+ */+ hash_id?: string | null+ /**+ * Free-form metadata object. Omit to preserve the current value.+ * @nullable+ */+ metadata?: ErrorTrackingReleaseUpdateRequestApiMetadata+}++/**+ * Free-form metadata object. Omit to preserve the current value.+ * @nullable+ */+export type PatchedErrorTrackingReleaseUpdateRequestApiMetadata = { [key: string]: unknown } | null++export interface PatchedErrorTrackingReleaseUpdateRequestApi {+ /**+ * Human-readable release version. Omit to preserve the current value.+ * @nullable+ */+ version?: string | null+ /**+ * Project identifier. Omit to preserve the current value.+ * @nullable+ */+ project?: string | null+ /**+ * Release hash (e.g. a git commit SHA). Omit to preserve the current value.+ * @maxLength 128+ * @nullable+ */+ hash_id?: string | null+ /**+ * Free-form metadata object. Omit to preserve the current value.+ * @nullable+ */+ metadata?: PatchedErrorTrackingReleaseUpdateRequestApiMetadata}export interface ErrorTrackingSettingsApi {@@ -1415,19 +1479,19 @@ export interface PatchedErrorTrackingSpikeDetectionConfigApi {}export interface ErrorTrackingSpikeEventIssueApi {- readonly id: string+ id: string/** @nullable */- readonly name: string | null+ name: string | null/** @nullable */- readonly description: string | null+ description: string | null}export interface ErrorTrackingSpikeEventApi {- readonly id: string- readonly issue: ErrorTrackingSpikeEventIssueApi- readonly detected_at: string- readonly computed_baseline: number- readonly current_bucket_value: number+ id: string+ issue: ErrorTrackingSpikeEventIssueApi+ detected_at: string+ computed_baseline: number+ current_bucket_value: number}export interface PaginatedErrorTrackingSpikeEventListApi {@@ -1439,16 +1503,24 @@ export interface PaginatedErrorTrackingSpikeEventListApi {results: ErrorTrackingSpikeEventApi[]}+export type ErrorTrackingStackFrameApiContents = { [key: string]: unknown }++/**+ * @nullable+ */+export type ErrorTrackingStackFrameApiContext = { [key: string]: unknown } | null+export interface ErrorTrackingStackFrameApi {- readonly id: string- /** Raw frame ID in 'hash/part' format */- readonly raw_id: string- readonly created_at: string- contents: unknown+ id: string+ raw_id: string+ created_at: string+ contents: ErrorTrackingStackFrameApiContentsresolved: boolean- context?: unknown- symbol_set_ref?: string- readonly release: ErrorTrackingReleaseApi+ /** @nullable */+ context: ErrorTrackingStackFrameApiContext+ /** @nullable */+ symbol_set_ref: string | null+ release: ErrorTrackingReleaseApi | null}export interface PaginatedErrorTrackingStackFrameListApi {@@ -1460,16 +1532,27 @@ export interface PaginatedErrorTrackingStackFrameListApi {results: ErrorTrackingStackFrameApi[]}+export interface ErrorTrackingStackFrameBatchGetRequestApi {+ /** Raw frame IDs in 'hash/part' format to resolve in a single request. */+ raw_ids: string[]+ /**+ * Optional symbol set reference to scope the lookup to a single symbol set.+ * @nullable+ */+ symbol_set?: string | null+}++export interface ErrorTrackingStackFrameBatchGetResponseApi {+ /** Resolved stack frames for the requested raw IDs. */+ results: ErrorTrackingStackFrameApi[]+}+export interface ErrorTrackingSuppressionRuleApi {readonly id: stringfilters: unknown- /**- * @minimum -2147483648- * @maximum 2147483647- */order_key: number- disabled_data?: unknown- sampling_rate?: number+ disabled_data: unknown+ sampling_rate: numberreadonly created_at: stringreadonly updated_at: string}@@ -1519,10 +1602,6 @@ export interface PatchedErrorTrackingSuppressionRuleUpdateRequestApi {export interface PatchedErrorTrackingSuppressionRuleApi {readonly id?: stringfilters?: unknown- /**- * @minimum -2147483648- * @maximum 2147483647- */order_key?: numberdisabled_data?: unknownsampling_rate?: numberdiff --git a/products/error_tracking/frontend/generated/api.ts b/products/error_tracking/frontend/generated/api.tsindex 790fdb264e03..ab0f15587b03 100644--- a/products/error_tracking/frontend/generated/api.ts+++ b/products/error_tracking/frontend/generated/api.ts@@ -39,11 +39,15 @@ import type {ErrorTrackingRecommendationApi,ErrorTrackingRecommendationsListParams,ErrorTrackingReleaseApi,+ ErrorTrackingReleaseCreateRequestApi,+ ErrorTrackingReleaseUpdateRequestApi,ErrorTrackingReleasesListParams,ErrorTrackingSettingsApi,ErrorTrackingSpikeDetectionConfigApi,ErrorTrackingSpikeEventsListParams,ErrorTrackingStackFrameApi,+ ErrorTrackingStackFrameBatchGetRequestApi,+ ErrorTrackingStackFrameBatchGetResponseApi,ErrorTrackingStackFramesListParams,ErrorTrackingSuppressionRuleApi,ErrorTrackingSuppressionRuleCreateRequestApi,@@ -72,7 +76,7 @@ import type {PatchedErrorTrackingGroupingRuleUpdateRequestApi,PatchedErrorTrackingIssueFullApi,PatchedErrorTrackingIssueWriteApi,- PatchedErrorTrackingReleaseApi,+ PatchedErrorTrackingReleaseUpdateRequestApi,PatchedErrorTrackingSettingsApi,PatchedErrorTrackingSpikeDetectionConfigApi,PatchedErrorTrackingSuppressionRuleApi,@@ -989,14 +993,14 @@ export const getErrorTrackingReleasesCreateUrl = (projectId: string) => {export const errorTrackingReleasesCreate = async (projectId: string,- errorTrackingReleaseApi: NonReadonly<ErrorTrackingReleaseApi>,+ errorTrackingReleaseCreateRequestApi: ErrorTrackingReleaseCreateRequestApi,options?: RequestInit): Promise<ErrorTrackingReleaseApi> => {return apiMutator<ErrorTrackingReleaseApi>(getErrorTrackingReleasesCreateUrl(projectId), {...options,method: 'POST',headers: { 'Content-Type': 'application/json', ...options?.headers },- body: JSON.stringify(errorTrackingReleaseApi),+ body: JSON.stringify(errorTrackingReleaseCreateRequestApi),})}@@ -1022,14 +1026,14 @@ export const getErrorTrackingReleasesUpdateUrl = (projectId: string, id: string)export const errorTrackingReleasesUpdate = async (projectId: string,id: string,- errorTrackingReleaseApi: NonReadonly<ErrorTrackingReleaseApi>,+ errorTrackingReleaseUpdateRequestApi?: ErrorTrackingReleaseUpdateRequestApi,options?: RequestInit-): Promise<ErrorTrackingReleaseApi> => {- return apiMutator<ErrorTrackingReleaseApi>(getErrorTrackingReleasesUpdateUrl(projectId, id), {+): Promise<void> => {+ return apiMutator<void>(getErrorTrackingReleasesUpdateUrl(projectId, id), {...options,method: 'PUT',headers: { 'Content-Type': 'application/json', ...options?.headers },- body: JSON.stringify(errorTrackingReleaseApi),+ body: JSON.stringify(errorTrackingReleaseUpdateRequestApi),})}@@ -1040,14 +1044,14 @@ export const getErrorTrackingReleasesPartialUpdateUrl = (projectId: string, id:export const errorTrackingReleasesPartialUpdate = async (projectId: string,id: string,- patchedErrorTrackingReleaseApi?: NonReadonly<PatchedErrorTrackingReleaseApi>,+ patchedErrorTrackingReleaseUpdateRequestApi?: PatchedErrorTrackingReleaseUpdateRequestApi,options?: RequestInit-): Promise<ErrorTrackingReleaseApi> => {- return apiMutator<ErrorTrackingReleaseApi>(getErrorTrackingReleasesPartialUpdateUrl(projectId, id), {+): Promise<void> => {+ return apiMutator<void>(getErrorTrackingReleasesPartialUpdateUrl(projectId, id), {...options,method: 'PATCH',headers: { 'Content-Type': 'application/json', ...options?.headers },- body: JSON.stringify(patchedErrorTrackingReleaseApi),+ body: JSON.stringify(patchedErrorTrackingReleaseUpdateRequestApi),})}@@ -1239,15 +1243,18 @@ export const getErrorTrackingStackFramesBatchGetCreateUrl = (projectId: string)export const errorTrackingStackFramesBatchGetCreate = async (projectId: string,- errorTrackingStackFrameApi: NonReadonly<ErrorTrackingStackFrameApi>,+ errorTrackingStackFrameBatchGetRequestApi: ErrorTrackingStackFrameBatchGetRequestApi,options?: RequestInit-): Promise<void> => {- return apiMutator<void>(getErrorTrackingStackFramesBatchGetCreateUrl(projectId), {- ...options,- method: 'POST',- headers: { 'Content-Type': 'application/json', ...options?.headers },- body: JSON.stringify(errorTrackingStackFrameApi),- })+): Promise<ErrorTrackingStackFrameBatchGetResponseApi> => {+ return apiMutator<ErrorTrackingStackFrameBatchGetResponseApi>(+ getErrorTrackingStackFramesBatchGetCreateUrl(projectId),+ {+ ...options,+ method: 'POST',+ headers: { 'Content-Type': 'application/json', ...options?.headers },+ body: JSON.stringify(errorTrackingStackFrameBatchGetRequestApi),+ }+ )}export const getErrorTrackingSuppressionRulesListUrl = (diff --git a/products/error_tracking/frontend/generated/api.zod.ts b/products/error_tracking/frontend/generated/api.zod.tsindex 188746ce84ab..0b90f9adfc4a 100644--- a/products/error_tracking/frontend/generated/api.zod.ts+++ b/products/error_tracking/frontend/generated/api.zod.ts@@ -87,16 +87,9 @@ export const ErrorTrackingAssignmentRulesPartialUpdateBody = /* @__PURE__ */ zod.describe('User or role to assign matching issues to.'),})-export const errorTrackingAssignmentRulesReorderPartialUpdateBodyOrderKeyMin = -2147483648-export const errorTrackingAssignmentRulesReorderPartialUpdateBodyOrderKeyMax = 2147483647-export const ErrorTrackingAssignmentRulesReorderPartialUpdateBody = /* @__PURE__ */ zod.object({filters: zod.unknown().optional(),- order_key: zod- .number()- .min(errorTrackingAssignmentRulesReorderPartialUpdateBodyOrderKeyMin)- .max(errorTrackingAssignmentRulesReorderPartialUpdateBodyOrderKeyMax)- .optional(),+ order_key: zod.number().optional(),disabled_data: zod.unknown().optional(),})@@ -162,17 +155,10 @@ export const ErrorTrackingGroupingRulesPartialUpdateBody = /* @__PURE__ */ zod.o),})-export const errorTrackingGroupingRulesReorderPartialUpdateBodyOrderKeyMin = -2147483648-export const errorTrackingGroupingRulesReorderPartialUpdateBodyOrderKeyMax = 2147483647-export const ErrorTrackingGroupingRulesReorderPartialUpdateBody = /* @__PURE__ */ zod.object({filters: zod.unknown().optional(),description: zod.string().nullish(),- order_key: zod- .number()- .min(errorTrackingGroupingRulesReorderPartialUpdateBodyOrderKeyMin)- .max(errorTrackingGroupingRulesReorderPartialUpdateBodyOrderKeyMax)- .optional(),+ order_key: zod.number().optional(),disabled_data: zod.unknown().optional(),})@@ -774,25 +760,52 @@ export const ErrorTrackingQueryIssuesListCreateBody = /* @__PURE__ */ zod.object.describe('Search stack-frame source\/file path text.'),})+export const errorTrackingReleasesCreateBodyHashIdMax = 128+export const ErrorTrackingReleasesCreateBody = /* @__PURE__ */ zod.object({- hash_id: zod.string(),- metadata: zod.unknown().optional(),- version: zod.string(),- project: zod.string(),+ version: zod.string().describe('Human-readable release version, e.g. a semver string or build number.'),+ project: zod.string().describe('Identifier of the project this release belongs to.'),+ hash_id: zod+ .string()+ .max(errorTrackingReleasesCreateBodyHashIdMax)+ .nullish()+ .describe('Optional client-supplied release hash (e.g. a git commit SHA). Generated server-side when omitted.'),+ metadata: zod+ .record(zod.string(), zod.unknown())+ .nullish()+ .describe('Optional free-form metadata object stored alongside the release.'),})+export const errorTrackingReleasesUpdateBodyHashIdMax = 128+export const ErrorTrackingReleasesUpdateBody = /* @__PURE__ */ zod.object({- hash_id: zod.string(),- metadata: zod.unknown().optional(),- version: zod.string(),- project: zod.string(),+ version: zod.string().nullish().describe('Human-readable release version. Omit to preserve the current value.'),+ project: zod.string().nullish().describe('Project identifier. Omit to preserve the current value.'),+ hash_id: zod+ .string()+ .max(errorTrackingReleasesUpdateBodyHashIdMax)+ .nullish()+ .describe('Release hash (e.g. a git commit SHA). Omit to preserve the current value.'),+ metadata: zod+ .record(zod.string(), zod.unknown())+ .nullish()+ .describe('Free-form metadata object. Omit to preserve the current value.'),})+export const errorTrackingReleasesPartialUpdateBodyHashIdMax = 128+export const ErrorTrackingReleasesPartialUpdateBody = /* @__PURE__ */ zod.object({- hash_id: zod.string().optional(),- metadata: zod.unknown().optional(),- version: zod.string().optional(),- project: zod.string().optional(),+ version: zod.string().nullish().describe('Human-readable release version. Omit to preserve the current value.'),+ project: zod.string().nullish().describe('Project identifier. Omit to preserve the current value.'),+ hash_id: zod+ .string()+ .max(errorTrackingReleasesPartialUpdateBodyHashIdMax)+ .nullish()+ .describe('Release hash (e.g. a git commit SHA). Omit to preserve the current value.'),+ metadata: zod+ .record(zod.string(), zod.unknown())+ .nullish()+ .describe('Free-form metadata object. Omit to preserve the current value.'),})export const ErrorTrackingSettingsUpdateSettingsPartialUpdateBody = /* @__PURE__ */ zod.object({@@ -841,10 +854,11 @@ export const ErrorTrackingSpikeDetectionConfigUpdateConfigPartialUpdateBody = /*})export const ErrorTrackingStackFramesBatchGetCreateBody = /* @__PURE__ */ zod.object({- contents: zod.unknown(),- resolved: zod.boolean(),- context: zod.unknown().optional(),- symbol_set_ref: zod.string().optional(),+ raw_ids: zod.array(zod.string()).describe("Raw frame IDs in 'hash\/part' format to resolve in a single request."),+ symbol_set: zod+ .string()+ .nullish()+ .describe('Optional symbol set reference to scope the lookup to a single symbol set.'),})export const errorTrackingSuppressionRulesCreateBodySamplingRateDefault = 1@@ -911,16 +925,9 @@ export const ErrorTrackingSuppressionRulesPartialUpdateBody = /* @__PURE__ */ zo),})-export const errorTrackingSuppressionRulesReorderPartialUpdateBodyOrderKeyMin = -2147483648-export const errorTrackingSuppressionRulesReorderPartialUpdateBodyOrderKeyMax = 2147483647-export const ErrorTrackingSuppressionRulesReorderPartialUpdateBody = /* @__PURE__ */ zod.object({filters: zod.unknown().optional(),- order_key: zod- .number()- .min(errorTrackingSuppressionRulesReorderPartialUpdateBodyOrderKeyMin)- .max(errorTrackingSuppressionRulesReorderPartialUpdateBodyOrderKeyMax)- .optional(),+ order_key: zod.number().optional(),disabled_data: zod.unknown().optional(),sampling_rate: zod.number().optional(),})diff --git a/pyproject.toml b/pyproject.tomlindex 55a25c88be85..fa22527a748e 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -530,8 +530,6 @@ ignore_imports = [# TODO: error_tracking presentation wave — these views still reach internals directly.# Thin each view to parse -> facade -> serialize and delete its entry. backend:contract-check# stays off until this list (and the frozen-migration DDL leak) is resolved.- "products.error_tracking.backend.presentation.views.assignment_rules -> products.error_tracking.backend.models",- "products.error_tracking.backend.presentation.views.grouping_rules -> products.error_tracking.backend.models","products.error_tracking.backend.presentation.views.issues -> products.cohorts.backend.models.cohort","products.error_tracking.backend.presentation.views.issues -> products.error_tracking.backend.issue_serializers","products.error_tracking.backend.presentation.views.issues -> products.error_tracking.backend.models",@@ -542,14 +540,7 @@ ignore_imports = ["products.error_tracking.backend.presentation.views.recommendations -> products.error_tracking.backend.logic.recommendations.refresh","products.error_tracking.backend.presentation.views.recommendations -> products.error_tracking.backend.models","products.error_tracking.backend.presentation.views.recommendations -> products.error_tracking.backend.tasks",- "products.error_tracking.backend.presentation.views.releases -> products.error_tracking.backend.models",- "products.error_tracking.backend.presentation.views.settings -> products.error_tracking.backend.models",- "products.error_tracking.backend.presentation.views.spike_detection_config -> products.error_tracking.backend.models",- "products.error_tracking.backend.presentation.views.spike_events -> products.error_tracking.backend.models",- "products.error_tracking.backend.presentation.views.stack_frames -> products.error_tracking.backend.models",- "products.error_tracking.backend.presentation.views.suppression_rules -> products.error_tracking.backend.models","products.error_tracking.backend.presentation.views.symbol_sets -> products.error_tracking.backend.models",- "products.error_tracking.backend.presentation.views.utils -> products.error_tracking.backend.hogvm_stl",# logs presentation isolation (temporary): the moved viewsets still reach in-product# internals directly. Removed by the follow-up that thins each viewset to go through# the facade.diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex 3f8e803960c2..8475bfcc14fb 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -18223,12 +18223,8 @@ export namespace Schemas {filters: unknown;/** @nullable */readonly assignee: ErrorTrackingAssignmentRuleAssignee;- /**- * @minimum -2147483648- * @maximum 2147483647- */order_key: number;- disabled_data?: unknown;+ disabled_data: unknown;readonly created_at: string;readonly updated_at: string;}@@ -18367,18 +18363,14 @@ export namespace Schemas {/** @nullable */readonly assignee: ErrorTrackingGroupingRuleAssignee;/** @nullable */- description?: string | null;+ description: string | null;/*** Issue linked to this rule* @nullable*/readonly issue: ErrorTrackingGroupingRuleIssue;- /**- * @minimum -2147483648- * @maximum 2147483647- */order_key: number;- disabled_data?: unknown;+ disabled_data: unknown;readonly created_at: string;readonly updated_at: string;}@@ -19011,14 +19003,74 @@ export namespace Schemas {readonly updated_at: string;}+ /**+ * @nullable+ */+ export type ErrorTrackingReleaseMetadata = { [key: string]: unknown } | null;+export interface ErrorTrackingRelease {- readonly id: string;+ id: string;hash_id: string;- readonly team_id: number;- readonly created_at: string;- metadata?: unknown;+ team_id: number;+ created_at: string;+ /** @nullable */+ metadata: ErrorTrackingReleaseMetadata;+ version: string;+ project: string;+ }++ /**+ * Optional free-form metadata object stored alongside the release.+ * @nullable+ */+ export type ErrorTrackingReleaseCreateRequestMetadata = { [key: string]: unknown } | null;++ export interface ErrorTrackingReleaseCreateRequest {+ /** Human-readable release version, e.g. a semver string or build number. */version: string;+ /** Identifier of the project this release belongs to. */project: string;+ /**+ * Optional client-supplied release hash (e.g. a git commit SHA). Generated server-side when omitted.+ * @maxLength 128+ * @nullable+ */+ hash_id?: string | null;+ /**+ * Optional free-form metadata object stored alongside the release.+ * @nullable+ */+ metadata?: ErrorTrackingReleaseCreateRequestMetadata;+ }++ /**+ * Free-form metadata object. Omit to preserve the current value.+ * @nullable+ */+ export type ErrorTrackingReleaseUpdateRequestMetadata = { [key: string]: unknown } | null;++ export interface ErrorTrackingReleaseUpdateRequest {+ /**+ * Human-readable release version. Omit to preserve the current value.+ * @nullable+ */+ version?: string | null;+ /**+ * Project identifier. Omit to preserve the current value.+ * @nullable+ */+ project?: string | null;+ /**+ * Release hash (e.g. a git commit SHA). Omit to preserve the current value.+ * @maxLength 128+ * @nullable+ */+ hash_id?: string | null;+ /**+ * Free-form metadata object. Omit to preserve the current value.+ * @nullable+ */+ metadata?: ErrorTrackingReleaseUpdateRequestMetadata;}export interface ErrorTrackingSettings {@@ -19117,43 +19169,62 @@ export namespace Schemas {}export interface ErrorTrackingSpikeEventIssue {- readonly id: string;+ id: string;/** @nullable */- readonly name: string | null;+ name: string | null;/** @nullable */- readonly description: string | null;+ description: string | null;}export interface ErrorTrackingSpikeEvent {- readonly id: string;- readonly issue: ErrorTrackingSpikeEventIssue;- readonly detected_at: string;- readonly computed_baseline: number;- readonly current_bucket_value: number;+ id: string;+ issue: ErrorTrackingSpikeEventIssue;+ detected_at: string;+ computed_baseline: number;+ current_bucket_value: number;}+ export type ErrorTrackingStackFrameContents = { [key: string]: unknown };++ /**+ * @nullable+ */+ export type ErrorTrackingStackFrameContext = { [key: string]: unknown } | null;+export interface ErrorTrackingStackFrame {- readonly id: string;- /** Raw frame ID in 'hash/part' format */- readonly raw_id: string;- readonly created_at: string;- contents: unknown;+ id: string;+ raw_id: string;+ created_at: string;+ contents: ErrorTrackingStackFrameContents;resolved: boolean;- context?: unknown;- symbol_set_ref?: string;- readonly release: ErrorTrackingRelease;+ /** @nullable */+ context: ErrorTrackingStackFrameContext;+ /** @nullable */+ symbol_set_ref: string | null;+ release: ErrorTrackingRelease | null;+ }++ export interface ErrorTrackingStackFrameBatchGetRequest {+ /** Raw frame IDs in 'hash/part' format to resolve in a single request. */+ raw_ids: string[];+ /**+ * Optional symbol set reference to scope the lookup to a single symbol set.+ * @nullable+ */+ symbol_set?: string | null;+ }++ export interface ErrorTrackingStackFrameBatchGetResponse {+ /** Resolved stack frames for the requested raw IDs. */+ results: ErrorTrackingStackFrame[];}export interface ErrorTrackingSuppressionRule {readonly id: string;filters: unknown;- /**- * @minimum -2147483648- * @maximum 2147483647- */order_key: number;- disabled_data?: unknown;- sampling_rate?: number;+ disabled_data: unknown;+ sampling_rate: number;readonly created_at: string;readonly updated_at: string;}@@ -34473,10 +34544,6 @@ export namespace Schemas {filters?: unknown;/** @nullable */readonly assignee?: PatchedErrorTrackingAssignmentRuleAssignee;- /**- * @minimum -2147483648- * @maximum 2147483647- */order_key?: number;disabled_data?: unknown;readonly created_at?: string;@@ -34516,10 +34583,6 @@ export namespace Schemas {* @nullable*/readonly issue?: PatchedErrorTrackingGroupingRuleIssue;- /**- * @minimum -2147483648- * @maximum 2147483647- */order_key?: number;disabled_data?: unknown;readonly created_at?: string;@@ -34572,14 +34635,34 @@ export namespace Schemas {description?: string | null;}- export interface PatchedErrorTrackingRelease {- readonly id?: string;- hash_id?: string;- readonly team_id?: number;- readonly created_at?: string;- metadata?: unknown;- version?: string;- project?: string;+ /**+ * Free-form metadata object. Omit to preserve the current value.+ * @nullable+ */+ export type PatchedErrorTrackingReleaseUpdateRequestMetadata = { [key: string]: unknown } | null;++ export interface PatchedErrorTrackingReleaseUpdateRequest {+ /**+ * Human-readable release version. Omit to preserve the current value.+ * @nullable+ */+ version?: string | null;+ /**+ * Project identifier. Omit to preserve the current value.+ * @nullable+ */+ project?: string | null;+ /**+ * Release hash (e.g. a git commit SHA). Omit to preserve the current value.+ * @maxLength 128+ * @nullable+ */+ hash_id?: string | null;+ /**+ * Free-form metadata object. Omit to preserve the current value.+ * @nullable+ */+ metadata?: PatchedErrorTrackingReleaseUpdateRequestMetadata;}export interface PatchedErrorTrackingSettings {@@ -34630,10 +34713,6 @@ export namespace Schemas {export interface PatchedErrorTrackingSuppressionRule {readonly id?: string;filters?: unknown;- /**- * @minimum -2147483648- * @maximum 2147483647- */order_key?: number;disabled_data?: unknown;sampling_rate?: number;diff --git a/services/mcp/src/generated/error_tracking/api.ts b/services/mcp/src/generated/error_tracking/api.tsindex b1e45008a678..67b51435b73a 100644--- a/services/mcp/src/generated/error_tracking/api.ts+++ b/services/mcp/src/generated/error_tracking/api.ts@@ -2004,7 +2004,7 @@ export const ErrorTrackingGroupingRulesCreateBody = /* @__PURE__ */ zod.object({})export const ErrorTrackingGroupingRulesUpdateParams = /* @__PURE__ */ zod.object({- id: zod.string().describe('A UUID string identifying this error tracking grouping rule.'),+ id: zod.string(),project_id: zod.string().describe(@@ -4537,7 +4537,7 @@ export const ErrorTrackingSuppressionRulesCreateBody = /* @__PURE__ */ zod.objec})export const ErrorTrackingSuppressionRulesUpdateParams = /* @__PURE__ */ zod.object({- id: zod.string().describe('A UUID string identifying this error tracking suppression rule.'),+ id: zod.string(),project_id: zod.string().describe(diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/error-tracking-grouping-rules-update.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/error-tracking-grouping-rules-update.jsonindex f096bcb9f4d0..d3f149f1273a 100644--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/error-tracking-grouping-rules-update.json+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/error-tracking-grouping-rules-update.json@@ -1787,7 +1787,6 @@"description": "Property-group filters that define which exceptions should be grouped into the same issue. Omit to preserve the existing filters."},"id": {- "description": "A UUID string identifying this error tracking grouping rule.","type": "string"}},diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/error-tracking-suppression-rules-update.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/error-tracking-suppression-rules-update.jsonindex a24bed23289c..ff17df9d8855 100644--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/error-tracking-suppression-rules-update.json+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/error-tracking-suppression-rules-update.json@@ -1780,7 +1780,6 @@"type": "object"},"id": {- "description": "A UUID string identifying this error tracking suppression rule.","type": "string"},"sampling_rate": {