: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
chore(error_tracking): complete facade presentation wave (#64880)
Hugues Pouillot2063736de527
diff --git a/products/error_tracking/backend/facade/api.py b/products/error_tracking/backend/facade/api.pyindex c40ec03251f9..20fed966b25a 100644--- a/products/error_tracking/backend/facade/api.py+++ b/products/error_tracking/backend/facade/api.py@@ -8,16 +8,17 @@ from typing import Anyfrom uuid import UUIDimport posthoganalytics-from rest_framework.exceptions import ValidationErrorfrom posthog.event_usage import groupsfrom .. import logic, weekly_digest+from ..models import resolve_fingerprints_for_issuesfrom . import contractsIssueNotFoundError = logic.ErrorTrackingIssueNotFoundErrorExternalReferenceValidationError = logic.ErrorTrackingExternalReferenceValidationErrorReleaseHashInUseError = logic.ErrorTrackingReleaseHashInUseError+InvalidBytecodeError = logic.ErrorTrackingInvalidBytecodeErrordef _to_issue_assignee(assignment) -> contracts.ErrorTrackingIssueAssignee | None:@@ -116,10 +117,36 @@ def get_issue(issue_id: UUID, team_id: int) -> contracts.ErrorTrackingIssue:return _to_issue(issue)+def list_issues_detailed(+ team_id: int, *, limit: int | None = None, offset: int = 0+) -> tuple[list[contracts.ErrorTrackingIssue], int]:+ qs = logic.get_issue_detail_queryset(team_id)+ total = qs.count()+ rows = qs if limit is None else qs[offset : offset + limit]+ return [_to_issue(issue) for issue in rows], total++def issue_exists(team_id: int) -> bool:return logic.issue_exists(team_id=team_id)+def issue_exists_by_id(team_id: int, issue_id: UUID | str) -> bool:+ return logic.issue_exists_by_id(team_id=team_id, issue_id=issue_id)+++def get_issue_basics(team_id: int, issue_id: UUID | str) -> contracts.ErrorTrackingIssueBasics | None:+ issue = logic.get_issue_basics(team_id=team_id, issue_id=issue_id)+ if issue is None:+ return None+ return contracts.ErrorTrackingIssueBasics(+ id=issue.id, name=issue.name, description=issue.description, status=issue.status+ )+++def resolve_fingerprints(team_id: int, issue_ids: list[str]) -> list[str]:+ return resolve_fingerprints_for_issues(team_id=team_id, issue_ids=issue_ids)++def _to_settings(settings) -> contracts.ErrorTrackingSettings:return contracts.ErrorTrackingSettings(project_rate_limit_value=settings.project_rate_limit_value,@@ -313,22 +340,16 @@ def get_assignment_rule(team_id: int, rule_id: str) -> contracts.ErrorTrackingAsdef 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+ rule = logic.create_assignment_rule(+ team_id, filters=filters, assignee_type=assignee["type"], assignee_id=assignee["id"]+ )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+ rule = logic.update_assignment_rule(team_id, rule_id, filters=filters, assignee=assignee)return _to_assignment_rule(rule) if rule is not None else None@@ -368,20 +389,14 @@ def get_grouping_rule(team_id: int, rule_id: str) -> contracts.ErrorTrackingGroudef 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+ rule = logic.create_grouping_rule(team_id, filters=filters, assignee=assignee, description=description)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+ rule = logic.update_grouping_rule(team_id, rule_id, filters=filters)return _to_grouping_rule(rule) if rule is not None else None@@ -417,20 +432,14 @@ def get_suppression_rule(team_id: int, rule_id: str) -> contracts.ErrorTrackingSdef 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+ rule = logic.create_suppression_rule(team_id, filters=filters, sampling_rate=sampling_rate)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+ rule = logic.update_suppression_rule(team_id, rule_id, filters=filters, sampling_rate=sampling_rate)return _to_suppression_rule(rule) if rule is not None else Nonediff --git a/products/error_tracking/backend/facade/contracts.py b/products/error_tracking/backend/facade/contracts.pyindex f959f3ca92b5..8d51144f16f3 100644--- a/products/error_tracking/backend/facade/contracts.py+++ b/products/error_tracking/backend/facade/contracts.py@@ -133,6 +133,24 @@ class ErrorTrackingRelease:project: str+@dataclass(frozen=True)+class ErrorTrackingSymbolSet:+ id: UUID+ ref: str+ team_id: int+ created_at: datetime+ last_used: datetime | None+ failure_reason: str | None+ has_uploaded_file: bool+ release: ErrorTrackingRelease | None+++@dataclass(frozen=True)+class ErrorTrackingSymbolSetDownload:+ has_file: bool+ url: str | None++@dataclass(frozen=True)class ErrorTrackingStackFrame:id: UUID@@ -190,3 +208,24 @@ class ErrorTrackingSuppressionRule:sampling_rate: floatcreated_at: datetimeupdated_at: datetime+++@dataclass(frozen=True)+class ErrorTrackingIssueBasics:+ id: UUID+ name: str | None+ description: str | None+ status: str+++@dataclass(frozen=True)+class ErrorTrackingRecommendation:+ id: UUID+ type: str+ meta: dict+ completed: bool+ status: str+ computed_at: datetime | None+ dismissed_at: datetime | None+ created_at: datetime+ updated_at: datetimediff --git a/products/error_tracking/backend/facade/issues.py b/products/error_tracking/backend/facade/issues.pynew file mode 100644index 000000000000..16def5c799a9--- /dev/null+++ b/products/error_tracking/backend/facade/issues.py@@ -0,0 +1,62 @@+"""Facade for error tracking issue write operations.++Kept separate from ``facade/api.py`` so the assignment/cohort side-effect imports+(ee RBAC roles, cohorts models, realtime notifications, email tasks) stay off the+django.setup() path of the read-oriented main facade.+"""++from typing import Any+from uuid import UUID++from ..logic import issue_mutations as _mutations+from . import api, contracts++CohortNotFoundError = _mutations.CohortNotFoundError+AssigneeValidationError = _mutations.AssigneeValidationError+InvalidIssueStatusError = _mutations.InvalidIssueStatusError+++def update_issue(+ team_id: int, issue_id: UUID, *, fields: dict[str, Any], user: Any, was_impersonated: bool+) -> contracts.ErrorTrackingIssue:+ issue = _mutations.update_issue(team_id, issue_id, fields=fields, user=user, was_impersonated=was_impersonated)+ return api._to_issue(issue)+++def merge_issues(team_id: int, issue_id: UUID, source_ids: list[str]) -> None:+ _mutations.merge_issues(team_id, issue_id, source_ids)+++def split_issue(team_id: int, issue_id: UUID, fingerprints: list[dict]) -> list[UUID]:+ return _mutations.split_issue(team_id, issue_id, fingerprints)+++def set_issue_cohort(team_id: int, issue_id: UUID, cohort_id: int) -> None:+ _mutations.set_issue_cohort(team_id, issue_id, cohort_id)+++def assign_issue(+ team_id: int, issue_id: UUID, assignee: dict[str, Any] | None, *, user: Any, was_impersonated: bool+) -> None:+ _mutations.assign_issue(team_id, issue_id, assignee, user=user, was_impersonated=was_impersonated)+++def bulk_update_issues(+ team_id: int,+ issue_ids: list[str],+ *,+ action: str | None,+ status: str | None,+ assignee: dict[str, Any] | None,+ user: Any,+ was_impersonated: bool,+) -> None:+ _mutations.bulk_update_issues(+ team_id,+ issue_ids,+ action=action,+ status=status,+ assignee=assignee,+ user=user,+ was_impersonated=was_impersonated,+ )diff --git a/products/error_tracking/backend/facade/queries.py b/products/error_tracking/backend/facade/queries.pyindex 7e376b87c045..ec4f08c512ac 100644--- a/products/error_tracking/backend/facade/queries.py+++ b/products/error_tracking/backend/facade/queries.py@@ -7,6 +7,13 @@ imports stay out of ``facade/api.py`` so config-only consumers don't drag them othe ``django.setup()`` path."""+from typing import Any++from posthog.schema import ErrorTrackingQuery++from posthog.clickhouse.query_tagging import Feature, Product, tags_context+from posthog.models.team.team import Team+from products.error_tracking.backend.hogql_queries.error_tracking_breakdowns_query_runner import (ErrorTrackingBreakdownsQueryRunner,)@@ -23,4 +30,11 @@ __all__ = ["ErrorTrackingIssueCorrelationQueryRunner","ErrorTrackingQueryRunner","ErrorTrackingSimilarIssuesQueryRunner",+ "run_error_tracking_query",]+++def run_error_tracking_query(team: Team, query: ErrorTrackingQuery) -> dict[str, Any]:+ """Execute an ErrorTrackingQuery with product query tagging and return the JSON-dumped response."""+ with tags_context(product=Product.ERROR_TRACKING, feature=Feature.QUERY):+ return ErrorTrackingQueryRunner(team=team, query=query).calculate().model_dump(mode="json")diff --git a/products/error_tracking/backend/facade/recommendations.py b/products/error_tracking/backend/facade/recommendations.pynew file mode 100644index 000000000000..58e1388a368b--- /dev/null+++ b/products/error_tracking/backend/facade/recommendations.py@@ -0,0 +1,54 @@+"""Facade for error tracking recommendations.++Kept separate from ``facade/api.py`` so the recommendation compute modules' heavy+imports (ClickHouse, cross-product models) stay off the django.setup() path of+config-only consumers of the main facade.+"""++from uuid import UUID++from ..logic.recommendations import (+ refresh as _refresh,+ store as _store,+)+from . import contracts++RecommendationNotFoundError = _store.RecommendationNotFoundError+UnknownRecommendationTypeError = _store.UnknownRecommendationTypeError+++def _to_recommendation(obj) -> contracts.ErrorTrackingRecommendation:+ enriched = _store.enrich_meta(obj)+ return contracts.ErrorTrackingRecommendation(+ id=obj.id,+ type=obj.type,+ meta=enriched,+ completed=_store.is_completed(obj, enriched),+ status=obj.status,+ computed_at=obj.computed_at,+ dismissed_at=obj.dismissed_at,+ created_at=obj.created_at,+ updated_at=obj.updated_at,+ )+++def refresh_team_recommendations(team_id: int) -> int:+ return _refresh.refresh_team_recommendations(team_id)+++def list_recommendations(team_id: int) -> list[contracts.ErrorTrackingRecommendation]:+ return [_to_recommendation(obj) for obj in _store.list_recommendations(team_id)]+++def refresh_recommendation(+ team_id: int, recommendation_id: UUID, *, force: bool+) -> contracts.ErrorTrackingRecommendation:+ return _to_recommendation(_store.refresh_recommendation(team_id, recommendation_id, force=force))+++def dismiss_recommendation(team_id: int, recommendation_id: UUID) -> contracts.ErrorTrackingRecommendation:+ return _to_recommendation(_store.dismiss_recommendation(team_id, recommendation_id))+++def restore_recommendation(team_id: int, recommendation_id: UUID) -> contracts.ErrorTrackingRecommendation:+ return _to_recommendation(_store.restore_recommendation(team_id, recommendation_id))diff --git a/products/error_tracking/backend/facade/symbol_sets.py b/products/error_tracking/backend/facade/symbol_sets.pynew file mode 100644index 000000000000..0a08e9a093c3--- /dev/null+++ b/products/error_tracking/backend/facade/symbol_sets.py@@ -0,0 +1,114 @@+"""Facade for error tracking symbol set operations.++Kept separate from ``facade/api.py`` so the object-storage and upload-analytics imports+stay off the django.setup() path of the read-oriented main facade.+"""++from typing import Any++from ..logic import symbol_sets as _logic+from . import contracts++SymbolSetNotFoundError = _logic.SymbolSetNotFoundError+++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_symbol_set(symbol_set) -> contracts.ErrorTrackingSymbolSet:+ return contracts.ErrorTrackingSymbolSet(+ id=symbol_set.id,+ ref=symbol_set.ref,+ team_id=symbol_set.team_id,+ created_at=symbol_set.created_at,+ last_used=symbol_set.last_used,+ failure_reason=symbol_set.failure_reason,+ has_uploaded_file=bool(symbol_set.storage_ptr),+ release=_to_release(symbol_set.release) if symbol_set.release else None,+ )+++def list_symbol_sets(+ team_id: int,+ *,+ ref: str | None,+ search: str | None,+ symbol_set_status: str | None,+ order_by: str | None,+ limit: int | None,+ offset: int,+) -> tuple[list[contracts.ErrorTrackingSymbolSet], int]:+ rows, total = _logic.list_symbol_sets(+ team_id,+ ref=ref,+ search=search,+ symbol_set_status=symbol_set_status,+ order_by=order_by,+ limit=limit,+ offset=offset,+ )+ return [_to_symbol_set(row) for row in rows], total+++def get_symbol_set(team_id: int, symbol_set_id: str) -> contracts.ErrorTrackingSymbolSet | None:+ symbol_set = _logic.get_symbol_set(team_id, symbol_set_id)+ return _to_symbol_set(symbol_set) if symbol_set is not None else None+++def delete_symbol_set(team_id: int, symbol_set_id: str) -> bool:+ return _logic.delete_symbol_set(team_id, symbol_set_id)+++def bulk_delete_symbol_sets(team_id: int, ids: list[str]) -> int:+ return _logic.bulk_delete_symbol_sets(team_id, ids)+++def get_download(team_id: int, symbol_set_id: str) -> contracts.ErrorTrackingSymbolSetDownload:+ has_file, url = _logic.get_download_url(team_id, symbol_set_id)+ return contracts.ErrorTrackingSymbolSetDownload(has_file=has_file, url=url)+++def create_deprecated_symbol_set(team: Any, chunk_id: str, release_id: str | None, data: bytearray) -> None:+ _logic.create_deprecated_symbol_set(team, chunk_id, release_id, data)+++def start_deprecated_upload(team: Any, chunk_id: str, release_id: str | None) -> tuple[object, str]:+ return _logic.start_deprecated_upload(team, chunk_id, release_id)+++def finish_upload(team_id: int, symbol_set_id: str, content_hash: str) -> None:+ _logic.finish_upload(team_id, symbol_set_id, content_hash)+++def bulk_start_upload(+ team: Any,+ *,+ symbol_sets: list[dict],+ chunk_ids: list[str],+ release_id: str | None,+ force: bool,+ skip_on_conflict: bool,+ distinct_id: str | None,+) -> dict[str, dict[str, str]]:+ return _logic.bulk_start_upload(+ team,+ symbol_sets=symbol_sets,+ chunk_ids=chunk_ids,+ release_id=release_id,+ force=force,+ skip_on_conflict=skip_on_conflict,+ distinct_id=distinct_id,+ )+++def bulk_finish_upload(team: Any, content_hashes: dict[str, str]) -> None:+ _logic.bulk_finish_upload(team, content_hashes)diff --git a/products/error_tracking/backend/logic/__init__.py b/products/error_tracking/backend/logic/__init__.pyindex dd2e1cc1edce..8ba8fe07024d 100644--- a/products/error_tracking/backend/logic/__init__.py+++ b/products/error_tracking/backend/logic/__init__.py@@ -114,6 +114,18 @@ def issue_exists(team_id: int) -> bool:return ErrorTrackingIssue.objects.filter(team_id=team_id).exists()+def issue_exists_by_id(team_id: int, issue_id: UUID | str) -> bool:+ return ErrorTrackingIssue.objects.filter(team_id=team_id, id=issue_id).exists()+++def get_issue_basics(team_id: int, issue_id: UUID | str) -> ErrorTrackingIssue | None:+ return (+ ErrorTrackingIssue.objects.filter(team_id=team_id, id=issue_id)+ .only("id", "name", "description", "status")+ .first()+ )++def get_issue_id_for_fingerprint(team_id: int, fingerprint: str) -> UUID | None:return (ErrorTrackingIssueFingerprintV2.objects.filter(team_id=team_id, fingerprint=fingerprint)diff --git a/products/error_tracking/backend/logic/issue_mutations.py b/products/error_tracking/backend/logic/issue_mutations.pynew file mode 100644index 000000000000..dee1743a8520--- /dev/null+++ b/products/error_tracking/backend/logic/issue_mutations.py@@ -0,0 +1,260 @@+"""Write-path operations for error tracking issues.++These encapsulate the transaction boundaries, activity logging, ClickHouse sync and+assignment side effects that previously lived in the presentation layer, so the views+can stay thin (parse -> facade -> serialize).+"""++from typing import Any+from uuid import UUID++from django.db import transaction++from posthog.models.activity_logging.activity_log import Change, Detail, log_activity+from posthog.models.organization import OrganizationMembership+from posthog.models.user import User+from posthog.tasks.email import send_error_tracking_issue_assigned++from products.cohorts.backend.models.cohort import Cohort+from products.error_tracking.backend.logic import ErrorTrackingIssueNotFoundError, get_issue+from products.error_tracking.backend.models import (+ ErrorTrackingIssue,+ ErrorTrackingIssueAssignment,+ ErrorTrackingIssueCohort,+ sync_issues_to_clickhouse,+)+from products.error_tracking.backend.notifications import dispatch_issue_assigned_realtime++from ee.models.rbac.role import Role+++class CohortNotFoundError(Exception):+ pass+++class AssigneeValidationError(Exception):+ pass+++class InvalidIssueStatusError(Exception):+ pass+++def _get_issue(team_id: int, issue_id: UUID | str, *, select_related: tuple[str, ...] = ()) -> ErrorTrackingIssue:+ qs = ErrorTrackingIssue.objects.all()+ if select_related:+ qs = qs.select_related(*select_related)+ try:+ return qs.get(team_id=team_id, id=issue_id)+ except ErrorTrackingIssue.DoesNotExist as err:+ raise ErrorTrackingIssueNotFoundError from err+++def _status_from_string(status: str) -> "ErrorTrackingIssue.Status | None":+ match status:+ case "active":+ return ErrorTrackingIssue.Status.ACTIVE+ case "resolved":+ return ErrorTrackingIssue.Status.RESOLVED+ case "suppressed":+ return ErrorTrackingIssue.Status.SUPPRESSED+ return None+++def update_issue(+ team_id: int, issue_id: UUID, *, fields: dict[str, Any], user: User, was_impersonated: bool+) -> ErrorTrackingIssue:+ # Fetch via the detail queryset so the returned instance is response-ready+ # (first_seen, assignment, external issues, cohorts) without a second read.+ issue = get_issue(issue_id=issue_id, team_id=team_id)+ status_before = issue.status+ name_before = issue.name+ status_after = fields.get("status")+ name_after = fields.get("name")+ status_updated = "status" in fields and status_after != status_before+ name_updated = "name" in fields and name_after != name_before++ for key in ("status", "name", "description"):+ if key in fields:+ setattr(issue, key, fields[key])+ issue.save()++ changes = []+ if status_updated:+ changes.append(+ Change(+ type="ErrorTrackingIssue", field="status", before=status_before, after=status_after, action="changed"+ )+ )+ if name_updated:+ changes.append(+ Change(type="ErrorTrackingIssue", field="name", before=name_before, after=name_after, action="changed")+ )++ if changes:+ log_activity(+ organization_id=issue.team.organization.id,+ team_id=team_id,+ user=user,+ was_impersonated=was_impersonated,+ item_id=str(issue.id),+ scope="ErrorTrackingIssue",+ activity="updated",+ detail=Detail(name=issue.name, changes=changes),+ )+ sync_issues_to_clickhouse(issue_ids=[issue.id], team_id=team_id)++ return issue+++def merge_issues(team_id: int, issue_id: UUID, source_ids: list[str]) -> None:+ issue = _get_issue(team_id, issue_id)+ # Make sure we don't delete the issue being merged into (defensive of frontend bugs)+ ids = [x for x in source_ids if x != str(issue.id)]+ issue.merge(issue_ids=ids)+++def split_issue(team_id: int, issue_id: UUID, fingerprints: list[dict]) -> list[UUID]:+ issue = _get_issue(team_id, issue_id)+ new_issues = issue.split(fingerprints=fingerprints)+ return [new_issue.id for new_issue in new_issues]+++def set_issue_cohort(team_id: int, issue_id: UUID, cohort_id: int) -> None:+ issue = _get_issue(team_id, issue_id)+ cohort = Cohort.objects.filter(team_id=team_id, id=cohort_id).first()+ if cohort is None:+ raise CohortNotFoundError+ # Upsert cohort_id as a cohort might have been soft deleted.+ # nosemgrep: idor-lookup-without-team (cohort scoped to team before use)+ ErrorTrackingIssueCohort.objects.update_or_create(issue=issue, defaults={"cohort_id": cohort.id})+++def assign_issue(+ team_id: int, issue_id: UUID, assignee: dict[str, Any] | None, *, user: User, was_impersonated: bool+) -> None:+ issue = _get_issue(team_id, issue_id, select_related=("team__organization",))+ _assign_one(issue, assignee, issue.team.organization, user, team_id, was_impersonated)+ sync_issues_to_clickhouse(issue_ids=[issue.id], team_id=team_id)+++def bulk_update_issues(+ team_id: int,+ issue_ids: list[str],+ *,+ action: str | None,+ status: str | None,+ assignee: dict[str, Any] | None,+ user: User,+ was_impersonated: bool,+) -> None:+ issues = ErrorTrackingIssue.objects.filter(team_id=team_id, id__in=issue_ids).select_related("team__organization")++ with transaction.atomic():+ if action == "set_status":+ new_status = _status_from_string(status) if status is not None else None+ if new_status is None:+ raise InvalidIssueStatusError+ for issue in issues:+ log_activity(+ organization_id=issue.team.organization_id,+ team_id=team_id,+ user=user,+ was_impersonated=was_impersonated,+ item_id=issue.id,+ scope="ErrorTrackingIssue",+ activity="updated",+ detail=Detail(+ name=issue.name,+ changes=[+ Change(+ type="ErrorTrackingIssue",+ action="changed",+ field="status",+ before=issue.status,+ after=new_status,+ )+ ],+ ),+ )+ issues.update(status=new_status)+ elif action == "assign":+ for issue in issues:+ _assign_one(issue, assignee, issue.team.organization, user, team_id, was_impersonated)++ sync_issues_to_clickhouse(issue_ids=[issue.id for issue in issues], team_id=team_id)+++def _assignment_repr(assignment: ErrorTrackingIssueAssignment | None) -> dict[str, Any] | None:+ if assignment is None:+ return None+ return {+ "id": assignment.user_id if assignment.user_id else str(assignment.role_id) if assignment.role_id else None,+ "type": "role" if assignment.role_id else "user",+ }+++def _assign_one(+ issue: ErrorTrackingIssue,+ assignee: dict[str, Any] | None,+ organization: Any,+ user: User,+ team_id: int,+ was_impersonated: bool,+) -> None:+ assignment_before = ErrorTrackingIssueAssignment.objects.filter(issue_id=issue.id).first()+ serialized_assignment_before = _assignment_repr(assignment_before)++ if assignee:+ if assignee["type"] == "user":+ if not OrganizationMembership.objects.filter(user_id=assignee["id"], organization=organization).exists():+ raise AssigneeValidationError("Assignee user does not belong to this organization.")+ elif assignee["type"] == "role":+ if not Role.objects.filter(id=assignee["id"], organization=organization).exists():+ raise AssigneeValidationError("Assignee role does not belong to this organization.")++ # nosemgrep: idor-lookup-without-team (assignee validated against org above)+ assignment_after, _ = ErrorTrackingIssueAssignment.objects.update_or_create(+ issue_id=issue.id,+ defaults={+ "team_id": issue.team_id,+ "user_id": None if assignee["type"] != "user" else assignee["id"],+ "role_id": None if assignee["type"] != "role" else assignee["id"],+ },+ )++ send_error_tracking_issue_assigned.delay(assignment_after.id, user.id)++ dispatch_issue_assigned_realtime(+ assignment=assignment_after,+ assignee=assignee,+ assigner=user,+ )++ serialized_assignment_after = _assignment_repr(assignment_after)+ else:+ if assignment_before:+ assignment_before.delete()+ serialized_assignment_after = None++ log_activity(+ organization_id=organization.id,+ team_id=team_id,+ user=user,+ was_impersonated=was_impersonated,+ item_id=str(issue.id),+ scope="ErrorTrackingIssue",+ activity="assigned",+ detail=Detail(+ name=issue.name,+ changes=[+ Change(+ type="ErrorTrackingIssue",+ field="assignee",+ before=serialized_assignment_before,+ after=serialized_assignment_after,+ action="changed",+ )+ ],+ ),+ )diff --git a/products/error_tracking/backend/logic/recommendations/store.py b/products/error_tracking/backend/logic/recommendations/store.pynew file mode 100644index 000000000000..ca4c3db3a3ce--- /dev/null+++ b/products/error_tracking/backend/logic/recommendations/store.py@@ -0,0 +1,74 @@+from typing import Any+from uuid import UUID++from django.utils import timezone++from products.error_tracking.backend.logic.recommendations import RECOMMENDATIONS_BY_TYPE+from products.error_tracking.backend.logic.recommendations.refresh import claim_for_compute, revert_to_ready+from products.error_tracking.backend.models import ErrorTrackingRecommendation+from products.error_tracking.backend.tasks import compute_error_tracking_recommendation+++class RecommendationNotFoundError(Exception):+ pass+++class UnknownRecommendationTypeError(Exception):+ pass+++def list_recommendations(team_id: int) -> list[ErrorTrackingRecommendation]:+ return list(ErrorTrackingRecommendation.objects.filter(team_id=team_id).select_related("team").order_by("type"))+++def _get(team_id: int, recommendation_id: UUID) -> ErrorTrackingRecommendation:+ try:+ return ErrorTrackingRecommendation.objects.select_related("team").get(team_id=team_id, id=recommendation_id)+ except ErrorTrackingRecommendation.DoesNotExist as err:+ raise RecommendationNotFoundError() from err+++def refresh_recommendation(team_id: int, recommendation_id: UUID, *, force: bool) -> ErrorTrackingRecommendation:+ recommendation = _get(team_id, recommendation_id)+ if recommendation.type not in RECOMMENDATIONS_BY_TYPE:+ raise UnknownRecommendationTypeError(recommendation.type)+ if force and claim_for_compute(recommendation.id, team_id, timezone.now()):+ try:+ compute_error_tracking_recommendation.delay(str(recommendation.id), team_id)+ except Exception:+ revert_to_ready(recommendation.id, team_id)+ raise+ recommendation.refresh_from_db()+ return recommendation+++def dismiss_recommendation(team_id: int, recommendation_id: UUID) -> ErrorTrackingRecommendation:+ recommendation = _get(team_id, recommendation_id)+ recommendation.dismissed_at = timezone.now()+ recommendation.save(update_fields=["dismissed_at", "updated_at"])+ return recommendation+++def restore_recommendation(team_id: int, recommendation_id: UUID) -> ErrorTrackingRecommendation:+ recommendation = _get(team_id, recommendation_id)+ recommendation.dismissed_at = None+ recommendation.save(update_fields=["dismissed_at", "updated_at"])+ return recommendation+++def enrich_meta(obj: ErrorTrackingRecommendation) -> dict[str, Any]:+ rec = RECOMMENDATIONS_BY_TYPE.get(obj.type)+ if not rec:+ return obj.meta+ return rec.enrich(obj.team, obj.meta)+++def is_completed(obj: ErrorTrackingRecommendation, enriched_meta: dict[str, Any]) -> bool:+ # A recommendation that has never finished computing can't be considered completed,+ # even if its empty default meta would otherwise satisfy is_completed().+ if obj.computed_at is None:+ return False+ rec = RECOMMENDATIONS_BY_TYPE.get(obj.type)+ if not rec:+ return False+ return rec.is_completed(enriched_meta)diff --git a/products/error_tracking/backend/logic/symbol_sets.py b/products/error_tracking/backend/logic/symbol_sets.pynew file mode 100644index 000000000000..77e4e2655c83--- /dev/null+++ b/products/error_tracking/backend/logic/symbol_sets.py@@ -0,0 +1,526 @@+"""Symbol set storage, ORM and upload operations for error tracking.++These encapsulate the object-storage interactions, transaction boundaries and upload+analytics that previously lived in the presentation layer, so the views can stay thin+(parse -> facade -> serialize). The DRF ``ValidationError`` codes raised here are part of+the CLI-facing upload contract and are surfaced verbatim by the views.+"""++import hashlib+from dataclasses import dataclass++from django.conf import settings+from django.db import transaction+from django.db.models import Q++import structlog+import posthoganalytics+from rest_framework.exceptions import ValidationError++from posthog.event_usage import groups+from posthog.models.team.team import Team+from posthog.models.utils import uuid7+from posthog.storage import object_storage++from products.error_tracking.backend.models import ErrorTrackingRelease, ErrorTrackingStackFrame, ErrorTrackingSymbolSet++logger = structlog.get_logger(__name__)++ONE_HUNDRED_MEGABYTES = 1024 * 1024 * 100+PRESIGNED_MULTIPLE_UPLOAD_TIMEOUT = 60 * 5+++class SymbolSetNotFoundError(Exception):+ pass+++@dataclass+class SymbolSetUpload:+ chunk_id: str+ release_id: str | None+ content_hash: str | None+++def _extract_failure_code(error_codes: object) -> str | None:+ if isinstance(error_codes, str):+ return error_codes++ if isinstance(error_codes, list):+ for error_code in error_codes:+ failure_code = _extract_failure_code(error_code)+ if failure_code:+ return failure_code++ if isinstance(error_codes, dict):+ for error_code in error_codes.values():+ failure_code = _extract_failure_code(error_code)+ if failure_code:+ return failure_code++ return None+++def _get_failure_code(exception: Exception) -> str | None:+ if isinstance(exception, ValidationError):+ return _extract_failure_code(exception.get_codes())++ return None+++def generate_symbol_set_file_key() -> str:+ return f"{settings.OBJECT_STORAGE_ERROR_TRACKING_SOURCE_MAPS_FOLDER}/{str(uuid7())}"+++def generate_symbol_set_upload_presigned_url(file_key: str, *, accelerate: bool = False):+ if accelerate:+ return object_storage.get_accelerated_presigned_post(+ file_key=file_key,+ conditions=[["content-length-range", 0, ONE_HUNDRED_MEGABYTES]],+ expiration=PRESIGNED_MULTIPLE_UPLOAD_TIMEOUT,+ )+ return object_storage.get_presigned_post(+ file_key=file_key,+ conditions=[["content-length-range", 0, ONE_HUNDRED_MEGABYTES]],+ expiration=PRESIGNED_MULTIPLE_UPLOAD_TIMEOUT,+ )+++def upload_content(content: bytearray) -> tuple[str, str]:+ content_hash = hashlib.sha512(content).hexdigest()++ if not settings.OBJECT_STORAGE_ENABLED:+ raise ValidationError(+ code="object_storage_required",+ detail="Object storage must be available to allow source map uploads.",+ )++ if len(content) > ONE_HUNDRED_MEGABYTES:+ raise ValidationError(+ code="file_too_large", detail="Combined source map and symbol set must be less than 100MB"+ )++ upload_path = generate_symbol_set_file_key()+ object_storage.write(upload_path, bytes(content))+ return (upload_path, content_hash)+++def create_symbol_set(+ chunk_id: str, team: Team, release_id: str | None, storage_ptr: str, content_hash: str | None = None+) -> ErrorTrackingSymbolSet:+ if release_id:+ objects = ErrorTrackingRelease.objects.all().filter(team=team, id=release_id)+ if len(objects) < 1:+ raise ValueError(f"Unknown release: {release_id}")+ release = objects[0]+ else:+ release = None++ with transaction.atomic():+ try:+ symbol_set = ErrorTrackingSymbolSet.objects.get(team=team, ref=chunk_id)+ if symbol_set.release is None:+ symbol_set.release = release+ elif symbol_set.release != release:+ raise ValidationError("Symbol set has already been uploaded for a different release")+ symbol_set.storage_ptr = storage_ptr+ symbol_set.content_hash = content_hash+ symbol_set.save()++ except ErrorTrackingSymbolSet.DoesNotExist:+ symbol_set = ErrorTrackingSymbolSet.objects.create(+ team=team,+ ref=chunk_id,+ release=release,+ storage_ptr=storage_ptr,+ content_hash=content_hash,+ )++ # Delete any existing frames associated with this symbol set+ ErrorTrackingStackFrame.objects.filter(team=team, symbol_set=symbol_set).delete()++ return symbol_set+++def bulk_create_symbol_sets(+ new_symbol_sets: list[SymbolSetUpload],+ team: Team,+ force: bool = False,+ skip_on_conflict: bool = False,+ distinct_id: str | None = None,+) -> dict[str, dict[str, str]]:+ accelerate = bool(+ distinct_id+ and posthoganalytics.feature_enabled(+ "error-tracking-s3-accelerate",+ distinct_id,+ groups={"organization": str(team.organization.id)},+ send_feature_flag_events=False,+ )+ )++ chunk_ids = [x.chunk_id for x in new_symbol_sets]++ # Check for dupes+ duplicates = [x for x in chunk_ids if chunk_ids.count(x) > 1]+ if duplicates:+ raise ValidationError(+ code="invalid_chunk_ids",+ detail=f"Duplicate chunk IDs provided: {', '.join(duplicates)}",+ )++ # Check we're using all valid release IDs+ release_ids = {ss.release_id for ss in new_symbol_sets if ss.release_id}+ fetched_releases = {str(r.id) for r in ErrorTrackingRelease.objects.all().filter(team=team, pk__in=release_ids)}+ for release_id in release_ids:+ if release_id not in fetched_releases:+ raise ValidationError(+ code="invalid_release_id",+ detail=f"Unknown release ID provided: {release_id}",+ )++ id_url_map: dict[str, dict[str, str]] = {}+ new_symbol_set_map = {x.chunk_id: x for x in new_symbol_sets}++ with transaction.atomic():+ existing_symbol_sets = list(ErrorTrackingSymbolSet.objects.filter(team=team, ref__in=chunk_ids))+ existing_symbol_set_refs = [s.ref for s in existing_symbol_sets]+ missing_sets = list(set(chunk_ids) - set(existing_symbol_set_refs))++ symbol_sets_to_be_created = []+ for chunk_id in missing_sets:+ storage_ptr = generate_symbol_set_file_key()+ presigned_url = generate_symbol_set_upload_presigned_url(storage_ptr, accelerate=accelerate)+ id_url_map[chunk_id] = {"presigned_url": presigned_url}+ # Note that on creation, we /do not set/ the content hash. We use content hashes included in+ # the create request only to see if we can skip updated - we set the content hash when we+ # get upload confirmation, during `bulk_finish_upload`, not before+ to_create = ErrorTrackingSymbolSet(+ team=team,+ ref=chunk_id,+ storage_ptr=storage_ptr,+ release_id=new_symbol_set_map[chunk_id].release_id,+ )+ symbol_sets_to_be_created.append(to_create)++ # create missing symbol sets+ created_symbol_sets = ErrorTrackingSymbolSet.objects.bulk_create(symbol_sets_to_be_created)++ for symbol_set in created_symbol_sets:+ id_url_map[symbol_set.ref]["symbol_set_id"] = str(symbol_set.pk)++ # update existing symbol sets+ to_update = []+ for existing in existing_symbol_sets:+ upload = new_symbol_set_map[existing.ref]+ dirty = False++ # Allow adding an "orphan" symbol set to a release, but not+ # moving symbols sets between releases+ if upload.release_id:+ if existing.release_id is None:+ existing.release_id = upload.release_id+ dirty = True+ elif str(existing.release_id) != upload.release_id:+ raise ValidationError(+ code="release_id_mismatch",+ detail=f"Symbol set {existing.ref} already has a release ID",+ )++ if upload.content_hash is None:+ if existing.content_hash is not None:+ # Old CLI (no content hash) trying to re-upload a symbol set+ # that was already fully uploaded. We can't determine safety,+ # so reject rather than silently overwrite production data.+ raise ValidationError(+ code="content_hash_required",+ detail=f"Symbol set {existing.ref} already has content; provide a content_hash to update it.",+ )+ # Both sides have no hash: this is a pending upload being restarted.+ # Issue a fresh presigned URL so the client can retry.+ storage_ptr = generate_symbol_set_file_key()+ presigned_url = generate_symbol_set_upload_presigned_url(storage_ptr, accelerate=accelerate)+ id_url_map[existing.ref] = {+ "presigned_url": presigned_url,+ "symbol_set_id": str(existing.id),+ }+ existing.storage_ptr = storage_ptr+ dirty = True+ elif existing.content_hash is None:+ # Existing record has no hash (pending upload or uploaded by old CLI+ # without hash support). Allow the new upload to supply one.+ storage_ptr = generate_symbol_set_file_key()+ presigned_url = generate_symbol_set_upload_presigned_url(storage_ptr, accelerate=accelerate)+ id_url_map[existing.ref] = {+ "presigned_url": presigned_url,+ "symbol_set_id": str(existing.id),+ }+ existing.storage_ptr = storage_ptr+ dirty = True+ elif existing.content_hash == upload.content_hash:+ # Content is identical — no upload needed.+ # (We may still update the release below if it changed.)+ pass+ elif force:+ # force=True: content has changed and the caller explicitly+ # requested an overwrite. Issue a new presigned URL and clear+ # the old content hash so bulk_finish_upload stores the new one.+ storage_ptr = generate_symbol_set_file_key()+ presigned_url = generate_symbol_set_upload_presigned_url(storage_ptr, accelerate=accelerate)+ id_url_map[existing.ref] = {+ "presigned_url": presigned_url,+ "symbol_set_id": str(existing.id),+ }+ existing.storage_ptr = storage_ptr+ existing.content_hash = None # will be set by bulk_finish_upload+ dirty = True+ elif skip_on_conflict:+ # Content has changed, but the caller explicitly asked to keep+ # the already-uploaded symbol set.+ logger.warning(+ "symbol_set_content_changed_skipped",+ ref=existing.ref,+ team_id=team.id,+ )+ else:+ raise ValidationError(+ code="content_hash_mismatch",+ detail=f"Symbol set {existing.ref} already exists with different content.",+ )++ if dirty:+ to_update.append(existing)++ # We update only the symbol sets we modified the release of - for all others, this is a no-op (we assume they were uploaded+ # during a prior attempt or something).+ ErrorTrackingSymbolSet.objects.bulk_update(to_update, ["release", "content_hash", "storage_ptr"])++ return id_url_map+++def list_symbol_sets(+ team_id: int,+ *,+ ref: str | None,+ search: str | None,+ symbol_set_status: str | None,+ order_by: str | None,+ limit: int | None,+ offset: int,+) -> tuple[list[ErrorTrackingSymbolSet], int]:+ queryset = ErrorTrackingSymbolSet.objects.filter(team_id=team_id).select_related("release")++ if ref:+ queryset = queryset.filter(ref=ref)++ if search:+ queryset = queryset.filter(+ Q(ref__icontains=search)+ | Q(release__version__icontains=search)+ | Q(release__project__icontains=search)+ | Q(release__metadata__git__commit_id__icontains=search)+ )++ if symbol_set_status == "valid":+ queryset = queryset.filter(storage_ptr__isnull=False)+ elif symbol_set_status == "invalid":+ queryset = queryset.filter(storage_ptr__isnull=True)++ if order_by:+ queryset = queryset.order_by(order_by)++ total = queryset.count()+ rows = queryset if limit is None else queryset[offset : offset + limit]+ return list(rows), total+++def get_symbol_set(team_id: int, symbol_set_id: str) -> ErrorTrackingSymbolSet | None:+ return ErrorTrackingSymbolSet.objects.filter(team_id=team_id, id=symbol_set_id).select_related("release").first()+++def _get_or_raise(team_id: int, symbol_set_id: str) -> ErrorTrackingSymbolSet:+ symbol_set = (+ ErrorTrackingSymbolSet.objects.filter(team_id=team_id, id=symbol_set_id).select_related("release").first()+ )+ if symbol_set is None:+ raise SymbolSetNotFoundError+ return symbol_set+++def delete_symbol_set(team_id: int, symbol_set_id: str) -> bool:+ symbol_set = ErrorTrackingSymbolSet.objects.filter(team_id=team_id, id=symbol_set_id).first()+ if symbol_set is None:+ return False+ symbol_set.delete()+ return True+++def bulk_delete_symbol_sets(team_id: int, ids: list[str]) -> int:+ deleted_count, _ = ErrorTrackingSymbolSet.objects.filter(team_id=team_id, id__in=ids).delete()+ return deleted_count+++def get_download_url(team_id: int, symbol_set_id: str) -> tuple[bool, str | None]:+ """Returns ``(has_file, presigned_url)`` for a team-scoped symbol set.++ Raises ``SymbolSetNotFoundError`` if the symbol set does not exist for the team.+ ``has_file`` is False when no source map has been uploaded; ``presigned_url`` is None+ when the URL could not be generated.+ """+ symbol_set = _get_or_raise(team_id, symbol_set_id)+ if not symbol_set.storage_ptr:+ return False, None+ presigned_url = object_storage.get_presigned_url(file_key=symbol_set.storage_ptr, expiration=3600)+ return True, presigned_url+++def create_deprecated_symbol_set(team: Team, chunk_id: str, release_id: str | None, data: bytearray) -> None:+ (storage_ptr, content_hash) = upload_content(data)+ create_symbol_set(chunk_id, team, release_id, storage_ptr, content_hash)+++def start_deprecated_upload(team: Team, chunk_id: str, release_id: str | None) -> tuple[object, str]:+ if not settings.OBJECT_STORAGE_ENABLED:+ raise ValidationError(+ code="object_storage_required",+ detail="Object storage must be available to allow source map uploads.",+ )++ file_key = generate_symbol_set_file_key()+ presigned_url = object_storage.get_presigned_post(+ file_key=file_key,+ conditions=[["content-length-range", 0, ONE_HUNDRED_MEGABYTES]],+ )++ symbol_set = create_symbol_set(chunk_id, team, release_id, file_key)+ return presigned_url, str(symbol_set.pk)+++def finish_upload(team_id: int, symbol_set_id: str, content_hash: str) -> None:+ if not settings.OBJECT_STORAGE_ENABLED:+ raise ValidationError(+ code="object_storage_required",+ detail="Object storage must be available to allow source map uploads.",+ )++ symbol_set = _get_or_raise(team_id, symbol_set_id)+ s3_upload = object_storage.head_object(file_key=symbol_set.storage_ptr) if symbol_set.storage_ptr else None++ if s3_upload:+ content_length = s3_upload.get("ContentLength")++ if not content_length or content_length > ONE_HUNDRED_MEGABYTES:+ symbol_set.delete()++ raise ValidationError(+ code="file_too_large",+ detail="The uploaded symbol set file was too large.",+ )+ else:+ raise ValidationError(+ code="file_not_found",+ detail="No file has been uploaded for the symbol set.",+ )++ if not symbol_set.content_hash:+ symbol_set.content_hash = content_hash+ symbol_set.save()+++def bulk_start_upload(+ team: Team,+ *,+ symbol_sets: list[dict],+ chunk_ids: list[str],+ release_id: str | None,+ force: bool,+ skip_on_conflict: bool,+ distinct_id: str | None,+) -> dict[str, dict[str, str]]:+ uploads = [SymbolSetUpload(**data) for data in symbol_sets]+ uploads.extend([SymbolSetUpload(chunk_id, release_id, None) for chunk_id in chunk_ids])++ if not settings.OBJECT_STORAGE_ENABLED:+ raise ValidationError(+ code="object_storage_required",+ detail="Object storage must be available to allow source map uploads.",+ )++ return bulk_create_symbol_sets(+ uploads,+ team,+ force=force,+ skip_on_conflict=skip_on_conflict,+ distinct_id=distinct_id,+ )+++def bulk_finish_upload(team: Team, content_hashes: dict[str, str]) -> None:+ if not settings.OBJECT_STORAGE_ENABLED:+ raise ValidationError(+ code="object_storage_required",+ detail="Object storage must be available to allow source map uploads.",+ )++ file_count = len(content_hashes)+ symbol_set_ids = set(content_hashes.keys())+ total_file_size = 0+ try:+ symbol_sets = list(ErrorTrackingSymbolSet.objects.filter(team=team, id__in=symbol_set_ids))+ found_symbol_set_ids = {str(symbol_set.id) for symbol_set in symbol_sets}+ missing_symbol_set_ids = symbol_set_ids - found_symbol_set_ids+ if missing_symbol_set_ids:+ raise ValidationError(+ code="symbol_set_not_found",+ detail=f"Unknown symbol set IDs: {', '.join(sorted(missing_symbol_set_ids))}",+ )++ for symbol_set in symbol_sets:+ s3_upload = None+ if symbol_set.storage_ptr:+ s3_upload = object_storage.head_object(file_key=symbol_set.storage_ptr)++ if s3_upload:+ content_length = s3_upload.get("ContentLength")+ if content_length:+ total_file_size += content_length++ if not content_length or content_length > ONE_HUNDRED_MEGABYTES:+ symbol_set.delete()++ raise ValidationError(+ code="file_too_large",+ detail="The uploaded symbol set file was too large.",+ )+ else:+ raise ValidationError(+ code="file_not_found",+ detail="No file has been uploaded for the symbol set.",+ )++ content_hash = content_hashes[str(symbol_set.id)]+ symbol_set.content_hash = content_hash+ ErrorTrackingSymbolSet.objects.bulk_update(symbol_sets, ["content_hash"])+ except Exception as e:+ posthoganalytics.capture(+ "error_tracking_symbol_set_uploaded",+ properties={+ "file_size": total_file_size,+ "success": False,+ "file_count": file_count,+ "failure_reason": type(e).__name__,+ "failure_code": _get_failure_code(e),+ },+ groups=groups(team.organization, team),+ )+ raise++ posthoganalytics.capture(+ "error_tracking_symbol_set_uploaded",+ properties={+ "file_size": total_file_size,+ "success": True,+ "file_count": file_count,+ },+ groups=groups(team.organization, team),+ )diff --git a/products/error_tracking/backend/presentation/views/assignment_rules.py b/products/error_tracking/backend/presentation/views/assignment_rules.pyindex 1bac824f2511..7ce244d29916 100644--- a/products/error_tracking/backend/presentation/views/assignment_rules.py+++ b/products/error_tracking/backend/presentation/views/assignment_rules.py@@ -5,7 +5,7 @@ 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 NotFound+from rest_framework.exceptions import NotFound, ValidationErrorfrom rest_framework.response import Responsefrom posthog.schema import PropertyGroupFilterValue@@ -136,12 +136,15 @@ class ErrorTrackingAssignmentRuleViewSet(TeamAndOrgViewSetMixin, viewsets.Generireturn 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"),- )+ try:+ rule = error_tracking_api.update_assignment_rule(+ self.team.id,+ pk,+ filters=request.validated_data.get("filters"),+ assignee=request.validated_data.get("assignee"),+ )+ except error_tracking_api.InvalidBytecodeError as err:+ raise ValidationError(str(err)) from errif rule is None:raise NotFound()posthoganalytics.capture(@@ -178,11 +181,14 @@ class ErrorTrackingAssignmentRuleViewSet(TeamAndOrgViewSetMixin, viewsets.Generiresponses={201: OpenApiResponse(response=ErrorTrackingAssignmentRuleSerializer)},)def create(self, request: ValidatedRequest, *args, **kwargs) -> Response:- rule = error_tracking_api.create_assignment_rule(- self.team.id,- filters=request.validated_data["filters"],- assignee=request.validated_data["assignee"],- )+ try:+ rule = error_tracking_api.create_assignment_rule(+ self.team.id,+ filters=request.validated_data["filters"],+ assignee=request.validated_data["assignee"],+ )+ except error_tracking_api.InvalidBytecodeError as err:+ raise ValidationError(str(err)) from errposthoganalytics.capture("error_tracking_assignment_rule_created",groups=groups(self.team.organization, self.team),diff --git a/products/error_tracking/backend/presentation/views/grouping_rules.py b/products/error_tracking/backend/presentation/views/grouping_rules.pyindex 2bf914ce7b66..421c7b0e3778 100644--- a/products/error_tracking/backend/presentation/views/grouping_rules.py+++ b/products/error_tracking/backend/presentation/views/grouping_rules.py@@ -6,7 +6,7 @@ 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 NotFound+from rest_framework.exceptions import NotFound, ValidationErrorfrom rest_framework.response import Responsefrom posthog.schema import PropertyGroupFilterValue@@ -158,7 +158,12 @@ class ErrorTrackingGroupingRuleViewSet(TeamAndOrgViewSetMixin, viewsets.GenericVreturn 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"))+ try:+ rule = error_tracking_api.update_grouping_rule(+ self.team.id, pk, filters=request.validated_data.get("filters")+ )+ except error_tracking_api.InvalidBytecodeError as err:+ raise ValidationError(str(err)) from errif rule is None:raise NotFound()posthoganalytics.capture(@@ -195,12 +200,15 @@ class ErrorTrackingGroupingRuleViewSet(TeamAndOrgViewSetMixin, viewsets.GenericVresponses={201: OpenApiResponse(response=ErrorTrackingGroupingRuleSerializer)},)def create(self, request: ValidatedRequest, *args, **kwargs) -> Response:- 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"),- )+ try:+ 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"),+ )+ except error_tracking_api.InvalidBytecodeError as err:+ raise ValidationError(str(err)) from errposthoganalytics.capture("error_tracking_grouping_rule_created",groups=groups(self.team.organization, self.team),diff --git a/products/error_tracking/backend/presentation/views/issues.py b/products/error_tracking/backend/presentation/views/issues.pyindex 97ad67d1db91..f4cbb0e8f033 100644--- a/products/error_tracking/backend/presentation/views/issues.py+++ b/products/error_tracking/backend/presentation/views/issues.py@@ -1,7 +1,5 @@from uuid import UUID-from django.db import transaction-from django.db.models.query import QuerySetfrom django.http import JsonResponseimport structlog@@ -17,33 +15,26 @@ from posthog.api.forbid_destroy_model import ForbidDestroyModelfrom posthog.api.mixins import ValidatedRequest, validated_requestfrom posthog.api.routing import TeamAndOrgViewSetMixinfrom posthog.api.utils import action-from posthog.models.activity_logging.activity_log import Change, Detail, load_activity, log_activity+from posthog.models.activity_logging.activity_log import load_activityfrom posthog.models.activity_logging.activity_page import activity_page_response-from posthog.models.organization import OrganizationMembership-from posthog.tasks.email import send_error_tracking_issue_assigned--from products.cohorts.backend.models.cohort import Cohort-from products.error_tracking.backend.facade import api as facade_api-from products.error_tracking.backend.issue_serializers import ErrorTrackingIssueAssignmentSerializer-from products.error_tracking.backend.models import (- ErrorTrackingIssue,- ErrorTrackingIssueAssignment,- ErrorTrackingIssueCohort,- sync_issues_to_clickhouse,++from products.error_tracking.backend.facade import (+ api as facade_api,+ issues as issues_facade,)-from products.error_tracking.backend.notifications import dispatch_issue_assigned_realtime+from products.error_tracking.backend.presentation.pagination import paginate_via_facadefrom products.error_tracking.backend.presentation.views.external_references import (ErrorTrackingExternalReferenceSerializer,)IssueNotFoundError = facade_api.IssueNotFoundError-DEFAULT_EMBEDDING_MODEL_NAME = "text-embedding-3-large"-DEFAULT_EMBEDDING_VERSION = 1-DEFAULT_MIN_DISTANCE_THRESHOLD = 0.10-logger = structlog.get_logger(__name__)+# Statuses a client may set. Deprecated archived/pending_release values are rejected+# by being absent from the choices; reads of legacy rows still pass through.+WRITABLE_ISSUE_STATUSES = ["active", "resolved", "suppressed"]+class ErrorTrackingIssueAssigneeReadSerializer(serializers.Serializer):# User assignees carry an integer id, role assignees a UUID string. `CharField` would@@ -75,94 +66,9 @@ class ErrorTrackingIssueReadSerializer(serializers.Serializer):cohort = ErrorTrackingIssueCohortReadSerializer(allow_null=True)-DEPRECATED_ISSUE_STATUSES = frozenset({ErrorTrackingIssue.Status.ARCHIVED, ErrorTrackingIssue.Status.PENDING_RELEASE})-SUPPORTED_WRITE_STATUSES = (- ErrorTrackingIssue.Status.ACTIVE,- ErrorTrackingIssue.Status.RESOLVED,- ErrorTrackingIssue.Status.SUPPRESSED,-)---class ErrorTrackingIssueFullSerializer(serializers.ModelSerializer):- first_seen = serializers.DateTimeField()- assignee = ErrorTrackingIssueAssignmentSerializer(source="assignment")- external_issues = ErrorTrackingExternalReferenceSerializer(many=True)- cohort = serializers.SerializerMethodField()-- class Meta:- model = ErrorTrackingIssue- fields = ["id", "status", "name", "description", "first_seen", "assignee", "external_issues", "cohort"]-- def validate_status(self, value: str) -> str:- # Reads of legacy archived/pending_release rows still pass through; only block new writes.- if value in DEPRECATED_ISSUE_STATUSES:- raise serializers.ValidationError(f"Status '{value}' is no longer supported. Use 'resolved' instead.")- return value-- @extend_schema_field(- {- "type": "object",- "nullable": True,- "properties": {- "id": {"type": "integer"},- "name": {"type": "string"},- },- }- )- def get_cohort(self, instance):- first_cohort = instance.cohorts.filter(cohort__deleted=False).first()- return {"id": first_cohort.cohort_id, "name": first_cohort.cohort.name} if first_cohort is not None else None-- def update(self, instance, validated_data):- team = instance.team- status_after = validated_data.get("status")- status_before = instance.status- status_updated = "status" in validated_data and status_after != status_before-- name_after = validated_data.get("name")- name_before = instance.name- name_updated = "name" in validated_data and name_after != name_before-- updated_instance = super().update(instance, validated_data)-- changes = []- if status_updated:- changes.append(- Change(- type="ErrorTrackingIssue",- field="status",- before=status_before,- after=status_after,- action="changed",- )- )- if name_updated:- changes.append(- Change(type="ErrorTrackingIssue", field="name", before=name_before, after=name_after, action="changed")- )-- if changes:- log_activity(- organization_id=team.organization.id,- team_id=team.id,- user=self.context["request"].user,- was_impersonated=is_impersonated_session(self.context["request"]),- item_id=str(updated_instance.id),- scope="ErrorTrackingIssue",- activity="updated",- detail=Detail(- name=instance.name,- changes=changes,- ),- )- sync_issues_to_clickhouse(issue_ids=[updated_instance.id], team_id=team.id)-- return updated_instance--class ErrorTrackingIssueWriteSerializer(serializers.Serializer):status = serializers.ChoiceField(- choices=SUPPORTED_WRITE_STATUSES,+ choices=WRITABLE_ISSUE_STATUSES,required=False,help_text="Issue status to set. Deprecated archived and pending_release values are rejected.",)@@ -223,12 +129,11 @@ class ErrorTrackingIssueSplitResponseSerializer(serializers.Serializer):)-class ErrorTrackingIssueViewSet(TeamAndOrgViewSetMixin, ForbidDestroyModel, viewsets.ModelViewSet):+class ErrorTrackingIssueViewSet(TeamAndOrgViewSetMixin, ForbidDestroyModel, viewsets.GenericViewSet):scope_object = "error_tracking"# These override the base defaults, so keep the standard DRF actions too.scope_object_read_actions = ["list", "retrieve", "values", "exists"]scope_object_write_actions = [- "create","update","partial_update","patch",@@ -239,41 +144,16 @@ class ErrorTrackingIssueViewSet(TeamAndOrgViewSetMixin, ForbidDestroyModel, view"cohort","bulk",]- queryset = ErrorTrackingIssue.objects.with_first_seen().all()- serializer_class = ErrorTrackingIssueFullSerializer-- def safely_get_queryset(self, queryset):- return (- queryset.select_related("assignment")- .prefetch_related("external_issues__integration")- .prefetch_related("cohorts__cohort")- .filter(team_id=self.team.id)- )-- @extend_schema(request=ErrorTrackingIssueWriteSerializer, responses={200: ErrorTrackingIssueFullSerializer})- def update(self, request: request.Request, *args: object, **kwargs: object) -> Response:- return self._update_issue(request)-- @extend_schema(request=ErrorTrackingIssueWriteSerializer, responses={200: ErrorTrackingIssueFullSerializer})- def partial_update(self, request: request.Request, *args: object, **kwargs: object) -> Response:- return self._update_issue(request)-- def _update_issue(self, request: request.Request) -> Response:- issue = self.get_object()- request_serializer = ErrorTrackingIssueWriteSerializer(data=request.data)- request_serializer.is_valid(raise_exception=True)-- serializer = self.get_serializer(issue, data=request_serializer.validated_data, partial=True)- serializer.is_valid(raise_exception=True)- self.perform_update(serializer)- return Response(serializer.data)+ serializer_class = ErrorTrackingIssueReadSerializer- @action(methods=["GET"], detail=False)- def exists(self, request, **kwargs):- has_issues = ErrorTrackingIssue.objects.filter(team_id=self.team.id).exists()- return Response({"exists": has_issues})+ def list(self, request: request.Request, *args: object, **kwargs: object) -> Response:+ return paginate_via_facade(+ self,+ request,+ lambda limit, offset: facade_api.list_issues_detailed(self.team.id, limit=limit, offset=offset),+ )- def retrieve(self, request, *args, **kwargs):+ def retrieve(self, request: request.Request, *args: object, **kwargs: object) -> Response | JsonResponse:issue_id = UUID(str(kwargs["pk"]))fingerprint = self.request.GET.get("fingerprint")@@ -287,20 +167,46 @@ class ErrorTrackingIssueViewSet(TeamAndOrgViewSetMixin, ForbidDestroyModel, viewexcept IssueNotFoundError:raise NotFound("Issue not found")- serializer = ErrorTrackingIssueReadSerializer(issue)- return Response(serializer.data)+ return Response(ErrorTrackingIssueReadSerializer(issue).data)++ @extend_schema(request=ErrorTrackingIssueWriteSerializer, responses={200: ErrorTrackingIssueReadSerializer})+ def update(self, request: request.Request, *args: object, **kwargs: object) -> Response:+ return self._update_issue(request, kwargs["pk"])++ @extend_schema(request=ErrorTrackingIssueWriteSerializer, responses={200: ErrorTrackingIssueReadSerializer})+ def partial_update(self, request: request.Request, *args: object, **kwargs: object) -> Response:+ return self._update_issue(request, kwargs["pk"])++ def _update_issue(self, request: request.Request, pk: object) -> Response:+ request_serializer = ErrorTrackingIssueWriteSerializer(data=request.data)+ request_serializer.is_valid(raise_exception=True)+ try:+ issue = issues_facade.update_issue(+ self.team.id,+ UUID(str(pk)),+ fields=dict(request_serializer.validated_data),+ user=request.user,+ was_impersonated=is_impersonated_session(request),+ )+ except IssueNotFoundError:+ raise NotFound("Issue not found")+ return Response(ErrorTrackingIssueReadSerializer(issue).data)++ @action(methods=["GET"], detail=False)+ def exists(self, request: request.Request, **kwargs: object) -> Response:+ return Response({"exists": facade_api.issue_exists(self.team.id)})@validated_request(request_serializer=ErrorTrackingIssueMergeRequestSerializer,responses={200: OpenApiResponse(response=ErrorTrackingIssueMergeResponseSerializer)},)@action(methods=["POST"], detail=True)- def merge(self, request: ValidatedRequest, **kwargs):- issue: ErrorTrackingIssue = self.get_object()+ def merge(self, request: ValidatedRequest, *args: object, pk: object = None, **kwargs: object) -> Response:ids = [str(issue_id) for issue_id in request.validated_data["ids"]]- # Make sure we don't delete the issue being merged into (defensive of frontend bugs)- ids = [x for x in ids if x != str(issue.id)]- issue.merge(issue_ids=ids)+ try:+ issues_facade.merge_issues(self.team.id, UUID(str(pk)), ids)+ except IssueNotFoundError:+ raise NotFound("Issue not found")return Response({"success": True})@validated_request(@@ -308,112 +214,79 @@ class ErrorTrackingIssueViewSet(TeamAndOrgViewSetMixin, ForbidDestroyModel, viewresponses={200: OpenApiResponse(response=ErrorTrackingIssueSplitResponseSerializer)},)@action(methods=["POST"], detail=True)- def split(self, request: ValidatedRequest, **kwargs):- issue: ErrorTrackingIssue = self.get_object()+ def split(self, request: ValidatedRequest, *args: object, pk: object = None, **kwargs: object) -> Response:fingerprints = request.validated_data["fingerprints"]- new_issues = issue.split(fingerprints=fingerprints)- return Response({"success": True, "new_issue_ids": [str(i.id) for i in new_issues]})+ try:+ new_issue_ids = issues_facade.split_issue(self.team.id, UUID(str(pk)), fingerprints)+ except IssueNotFoundError:+ raise NotFound("Issue not found")+ return Response({"success": True, "new_issue_ids": [str(i) for i in new_issue_ids]})@action(methods=["PATCH"], detail=True)- def assign(self, request, **kwargs):+ def assign(self, request: request.Request, *args: object, pk: object = None, **kwargs: object) -> Response:assignee = request.data.get("assignee", None)- instance = self.get_object()-- assign_issue(- instance, assignee, self.organization, request.user, self.team_id, is_impersonated_session(request)- )- sync_issues_to_clickhouse(issue_ids=[instance.id], team_id=instance.team_id)-+ try:+ issues_facade.assign_issue(+ self.team.id,+ UUID(str(pk)),+ assignee,+ user=request.user,+ was_impersonated=is_impersonated_session(request),+ )+ except IssueNotFoundError:+ raise NotFound("Issue not found")+ except issues_facade.AssigneeValidationError as err:+ raise ValidationError(str(err))return Response({"success": True})@action(methods=["PUT"], detail=True)- def cohort(self, request, **kwargs):+ def cohort(self, request: request.Request, *args: object, pk: object = None, **kwargs: object) -> Response:cohort_id = request.data.get("cohortId", None)if cohort_id is None:raise ValidationError("Please provide a cohort id")- issue: ErrorTrackingIssue = self.get_object()- cohort = Cohort.objects.filter(team=self.team, id=cohort_id).first()- if cohort is None:- raise NotFound("Cohort not found")-try:- ## Upsert cohort_id as a cohort might have been soft deleted- # nosemgrep: idor-lookup-without-team (cohort scoped to team before use)- _ = ErrorTrackingIssueCohort.objects.update_or_create(issue=issue, defaults={"cohort_id": cohort.id})+ issues_facade.set_issue_cohort(self.team.id, UUID(str(pk)), cohort_id)+ except IssueNotFoundError:+ raise NotFound("Issue not found")+ except issues_facade.CohortNotFoundError:+ raise NotFound("Cohort not found")except Exception as e:posthoganalytics.capture_exception(- e, distinct_id=self.request.user.pk, properties={"issue_id": issue.id, "cohort_id": cohort.id}+ e, distinct_id=self.request.user.pk, properties={"issue_id": str(pk), "cohort_id": cohort_id})raise ValidationError("An error occurred while assigning this cohort")return Response({"success": True})@action(methods=["GET"], detail=False)- def values(self, request: request.Request, **kwargs):- queryset = self.get_queryset()+ def values(self, request: request.Request, **kwargs: object) -> Response:value = request.GET.get("value", None)key = request.GET.get("key")-- issue_values: QuerySet[ErrorTrackingIssue] = QuerySet()- if key and value:- if key == "name":- issue_values = queryset.filter(name__icontains=value).values_list("name", flat=True)- elif key == "issue_description":- issue_values = queryset.filter(description__icontains=value).values_list("description", flat=True)-+ issue_values = facade_api.get_issue_values(self.team.id, key, value)return Response({"results": [{"name": value} for value in issue_values], "refreshing": False})@action(methods=["POST"], detail=False)- def bulk(self, request, **kwargs):- action = request.data.get("action")- status = request.data.get("status")- issues = self.get_queryset().filter(id__in=request.data.get("ids", []))-- with transaction.atomic():- if action == "set_status":- new_status = get_status_from_string(status)- if new_status is None:- raise ValidationError("Invalid status")- for issue in issues:- _ = log_activity(- organization_id=self.organization.id,- team_id=self.team_id,- user=request.user,- was_impersonated=is_impersonated_session(request),- item_id=issue.id,- scope="ErrorTrackingIssue",- activity="updated",- detail=Detail(- name=issue.name,- changes=[- Change(- type="ErrorTrackingIssue",- action="changed",- field="status",- before=issue.status,- after=new_status,- )- ],- ),- )-- issues.update(status=new_status)- elif action == "assign":- assignee = request.data.get("assignee", None)-- for issue in issues:- assign_issue(- issue, assignee, self.organization, request.user, self.team_id, is_impersonated_session(request)- )-- sync_issues_to_clickhouse(issue_ids=[issue.id for issue in issues], team_id=self.team_id)-+ def bulk(self, request: request.Request, **kwargs: object) -> Response:+ try:+ issues_facade.bulk_update_issues(+ self.team.id,+ request.data.get("ids", []),+ action=request.data.get("action"),+ status=request.data.get("status"),+ assignee=request.data.get("assignee", None),+ user=request.user,+ was_impersonated=is_impersonated_session(request),+ )+ except issues_facade.InvalidIssueStatusError:+ raise ValidationError("Invalid status")+ except issues_facade.AssigneeValidationError as err:+ raise ValidationError(str(err))return Response({"success": True})@extend_schema(operation_id="error_tracking_issues_all_activity_retrieve")@action(methods=["GET"], url_path="activity", detail=False, required_scopes=["activity_log:read"])- def all_activity(self, request: request.Request, **kwargs):+ def all_activity(self, request: request.Request, **kwargs: object) -> Response:limit = int(request.query_params.get("limit", "10"))page = int(request.query_params.get("page", "1"))@@ -421,95 +294,18 @@ class ErrorTrackingIssueViewSet(TeamAndOrgViewSetMixin, ForbidDestroyModel, viewreturn activity_page_response(activity_page, limit, page, request)@action(methods=["GET"], detail=True, required_scopes=["activity_log:read"])- def activity(self, request: request.Request, **kwargs):+ def activity(self, request: request.Request, *args: object, pk: object = None, **kwargs: object) -> Response:limit = int(request.query_params.get("limit", "10"))page = int(request.query_params.get("page", "1"))- item_id = kwargs["pk"]- if not ErrorTrackingIssue.objects.filter(id=item_id, team_id=self.team_id).exists():+ if not facade_api.issue_exists_by_id(self.team_id, str(pk)):return Response(status=status.HTTP_404_NOT_FOUND)activity_page = load_activity(scope="ErrorTrackingIssue",team_id=self.team_id,- item_ids=[str(item_id)],+ item_ids=[str(pk)],limit=limit,page=page,)return activity_page_response(activity_page, limit, page, request)---def assign_issue(issue: ErrorTrackingIssue, assignee, organization, user, team_id, was_impersonated):- assignment_before = ErrorTrackingIssueAssignment.objects.filter(issue_id=issue.id).first()- serialized_assignment_before = (- ErrorTrackingIssueAssignmentSerializer(assignment_before).data if assignment_before else None- )-- if assignee:- if assignee["type"] == "user":- if not OrganizationMembership.objects.filter(user_id=assignee["id"], organization=organization).exists():- raise ValidationError("Assignee user does not belong to this organization.")- elif assignee["type"] == "role":- from ee.models.rbac.role import Role-- if not Role.objects.filter(id=assignee["id"], organization=organization).exists():- raise ValidationError("Assignee role does not belong to this organization.")-- # nosemgrep: idor-lookup-without-team (assignee validated against org above)- assignment_after, _ = ErrorTrackingIssueAssignment.objects.update_or_create(- issue_id=issue.id,- defaults={- "team_id": issue.team_id,- "user_id": None if assignee["type"] != "user" else assignee["id"],- "role_id": None if assignee["type"] != "role" else assignee["id"],- },- )-- send_error_tracking_issue_assigned.delay(assignment_after.id, user.id)-- dispatch_issue_assigned_realtime(- assignment=assignment_after,- assignee=assignee,- assigner=user,- )-- serialized_assignment_after = (- ErrorTrackingIssueAssignmentSerializer(assignment_after).data if assignment_after else None- )- else:- if assignment_before:- assignment_before.delete()- serialized_assignment_after = None-- log_activity(- organization_id=organization.id,- team_id=team_id,- user=user,- was_impersonated=was_impersonated,- item_id=str(issue.id),- scope="ErrorTrackingIssue",- activity="assigned",- detail=Detail(- name=issue.name,- changes=[- Change(- type="ErrorTrackingIssue",- field="assignee",- before=serialized_assignment_before,- after=serialized_assignment_after,- action="changed",- )- ],- ),- )---def get_status_from_string(status: str) -> ErrorTrackingIssue.Status | None:- match status:- case "active":- return ErrorTrackingIssue.Status.ACTIVE- case "resolved":- return ErrorTrackingIssue.Status.RESOLVED- case "suppressed":- return ErrorTrackingIssue.Status.SUPPRESSED- return Nonediff --git a/products/error_tracking/backend/presentation/views/query.py b/products/error_tracking/backend/presentation/views/query.pyindex 089e7788295e..ac0685de192d 100644--- a/products/error_tracking/backend/presentation/views/query.py+++ b/products/error_tracking/backend/presentation/views/query.py@@ -15,6 +15,10 @@ from posthog.api.utils import actionfrom posthog.clickhouse.query_tagging import Feature, Product, tags_contextfrom posthog.hogql_queries.events_query_runner import EventsQueryRunner+from products.error_tracking.backend.facade import (+ api as facade_api,+ queries as query_facade,+)from products.error_tracking.backend.facade.query_utils import (CONTEXT_EVENT_SELECTS,EVENT_SELECTS,@@ -37,8 +41,6 @@ from products.error_tracking.backend.facade.query_utils import (normalize_volume_resolution,pick_fields,)-from products.error_tracking.backend.hogql_queries.error_tracking_query_runner import ErrorTrackingQueryRunner-from products.error_tracking.backend.models import ErrorTrackingIssue, resolve_fingerprints_for_issuesfrom products.error_tracking.backend.presentation.views.query_serializers import (ErrorTrackingIssueDetailSerializer,ErrorTrackingIssueEventsQueryRequestSerializer,@@ -98,8 +100,7 @@ class ErrorTrackingQueryViewSet(TeamAndOrgViewSetMixin, viewsets.ViewSet):withLastEvent=False,tags={"productKey": "error_tracking"},)- with tags_context(product=Product.ERROR_TRACKING, feature=Feature.QUERY):- data = ErrorTrackingQueryRunner(team=self.team, query=query).calculate().model_dump(mode="json")+ data = query_facade.run_error_tracking_query(self.team, query)raw_results_value = data.get("results")raw_results: list[object] = raw_results_value if isinstance(raw_results_value, list) else []results = [pick_fields(cast(dict[str, object], issue), LIST_ISSUE_FIELDS) for issue in raw_results[:limit]]@@ -128,10 +129,10 @@ class ErrorTrackingQueryViewSet(TeamAndOrgViewSetMixin, viewsets.ViewSet):volume_resolution = cast(int, params.get("volumeResolution", 0))if include_sparkline and volume_resolution <= 0:volume_resolution = 12- issue_model = ErrorTrackingIssue.objects.filter(team=self.team, id=issue_id).first()- if issue_model is None:+ issue_basics = facade_api.get_issue_basics(self.team.id, issue_id)+ if issue_basics is None:return Response(status=status.HTTP_404_NOT_FOUND)- fingerprints = resolve_fingerprints_for_issues(team_id=self.team.pk, issue_ids=[issue_id])+ fingerprints = facade_api.resolve_fingerprints(self.team.pk, [issue_id])query = ErrorTrackingQuery(kind="ErrorTrackingQuery",issueId=issue_id,@@ -147,17 +148,16 @@ class ErrorTrackingQueryViewSet(TeamAndOrgViewSetMixin, viewsets.ViewSet):withLastEvent=False,tags={"productKey": "error_tracking"},)- with tags_context(product=Product.ERROR_TRACKING, feature=Feature.QUERY):- data = ErrorTrackingQueryRunner(team=self.team, query=query).calculate().model_dump(mode="json")+ data = query_facade.run_error_tracking_query(self.team, query)raw_results_value = data.get("results")raw_results: list[object] = raw_results_value if isinstance(raw_results_value, list) else []if not raw_results:payload: dict[str, object] = compact_dict({- "id": str(issue_model.id),- "name": issue_model.name,- "description": issue_model.description,- "status": issue_model.status,+ "id": str(issue_basics.id),+ "name": issue_basics.name,+ "description": issue_basics.description,+ "status": issue_basics.status,})payload["impact"] = {}@@ -227,10 +227,10 @@ class ErrorTrackingQueryViewSet(TeamAndOrgViewSetMixin, viewsets.ViewSet):issue_id = str(params["issueId"])limit = cast(int, params.get("limit", 1))offset = cast(int, params.get("offset", 0))- if not ErrorTrackingIssue.objects.filter(team=self.team, id=issue_id).exists():+ if not facade_api.issue_exists_by_id(self.team.id, issue_id):return Response(status=status.HTTP_404_NOT_FOUND)date_range = build_date_range(params.get("dateRange"))- fingerprints = resolve_fingerprints_for_issues(team_id=self.team.pk, issue_ids=[issue_id])+ fingerprints = facade_api.resolve_fingerprints(self.team.pk, [issue_id])if not fingerprints:return Response({"results": [], "hasMore": False, "limit": limit, "offset": offset})query = EventsQuery(diff --git a/products/error_tracking/backend/presentation/views/recommendations.py b/products/error_tracking/backend/presentation/views/recommendations.pyindex 67d86798a3c3..5a22cfbdf249 100644--- a/products/error_tracking/backend/presentation/views/recommendations.py+++ b/products/error_tracking/backend/presentation/views/recommendations.py@@ -1,130 +1,74 @@-from typing import override--from django.utils import timezone-from drf_spectacular.utils import extend_schema-from rest_framework import mixins, serializers, status, viewsets+from rest_framework import serializers, status, viewsetsfrom rest_framework.decorators import action+from rest_framework.exceptions import NotFoundfrom rest_framework.request import Requestfrom rest_framework.response import Responsefrom posthog.api.routing import TeamAndOrgViewSetMixin-from products.error_tracking.backend.logic.recommendations import RECOMMENDATIONS_BY_TYPE-from products.error_tracking.backend.logic.recommendations.refresh import (- claim_for_compute,- refresh_team_recommendations,- revert_to_ready,-)-from products.error_tracking.backend.models import ErrorTrackingRecommendation-from products.error_tracking.backend.tasks import compute_error_tracking_recommendation+from products.error_tracking.backend.facade import recommendations as recommendations_facade-class ErrorTrackingRecommendationSerializer(serializers.ModelSerializer):- meta = serializers.SerializerMethodField(help_text="Recommendation payload, shape depends on type.")- completed = serializers.SerializerMethodField(+class ErrorTrackingRecommendationSerializer(serializers.Serializer):+ id = serializers.UUIDField(help_text="Recommendation UUID.")+ type = serializers.CharField(help_text="Recommendation type identifier (e.g. 'alerts').")+ meta = serializers.JSONField(help_text="Recommendation payload, shape depends on type.")+ completed = serializers.BooleanField(help_text="Whether the recommendation's recommended action has been satisfied.")-- class Meta:- model = ErrorTrackingRecommendation- fields = [- "id",- "type",- "meta",- "completed",- "status",- "computed_at",- "dismissed_at",- "created_at",- "updated_at",- ]- read_only_fields = fields- extra_kwargs = {- "id": {"help_text": "Recommendation UUID."},- "type": {"help_text": "Recommendation type identifier (e.g. 'alerts')."},- "status": {"help_text": "'ready' if meta is fresh, 'computing' if a refresh is in progress."},- "computed_at": {"help_text": "Timestamp meta was last successfully computed."},- "dismissed_at": {"help_text": "Timestamp the user dismissed this recommendation, if any."},- "created_at": {"help_text": "Timestamp the recommendation row was first created."},- "updated_at": {"help_text": "Timestamp the recommendation row was last updated."},- }-- def _enriched_meta(self, obj: ErrorTrackingRecommendation) -> dict:- rec = RECOMMENDATIONS_BY_TYPE.get(obj.type)- if not rec:- return obj.meta- cached = self.context.setdefault("_enriched_meta", {})- if obj.id not in cached:- cached[obj.id] = rec.enrich(obj.team, obj.meta)- return cached[obj.id]-- def get_meta(self, obj: ErrorTrackingRecommendation) -> dict:- return self._enriched_meta(obj)-- def get_completed(self, obj: ErrorTrackingRecommendation) -> bool:- # A recommendation that has never finished computing can't be considered- # completed, even if its empty default meta would otherwise satisfy- # is_completed() (e.g. an empty issues list).- if obj.computed_at is None:- return False- rec = RECOMMENDATIONS_BY_TYPE.get(obj.type)- if not rec:- return False- return rec.is_completed(self._enriched_meta(obj))+ status = serializers.CharField(help_text="'ready' if meta is fresh, 'computing' if a refresh is in progress.")+ computed_at = serializers.DateTimeField(allow_null=True, help_text="Timestamp meta was last successfully computed.")+ dismissed_at = serializers.DateTimeField(+ allow_null=True, help_text="Timestamp the user dismissed this recommendation, if any."+ )+ created_at = serializers.DateTimeField(help_text="Timestamp the recommendation row was first created.")+ updated_at = serializers.DateTimeField(help_text="Timestamp the recommendation row was last updated.")-class ErrorTrackingRecommendationViewSet(- TeamAndOrgViewSetMixin,- mixins.ListModelMixin,- viewsets.GenericViewSet,-):+class ErrorTrackingRecommendationViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):scope_object = "error_tracking"scope_object_write_actions = ["refresh", "dismiss", "restore"]- queryset = ErrorTrackingRecommendation.objects.all().order_by("type")serializer_class = ErrorTrackingRecommendationSerializer- @override- def safely_get_queryset(self, queryset):- return queryset.filter(team_id=self.team.id)-- @overridedef list(self, request: Request, *args, **kwargs) -> Response:# When the frontend is polling for status updates we skip the kick# so each poll is a cheap read of the current state.is_poll = request.query_params.get("poll", "false").lower() == "true"if not is_poll:- refresh_team_recommendations(self.team.id)- return super().list(request, *args, **kwargs)+ recommendations_facade.refresh_team_recommendations(self.team.id)+ recommendations = recommendations_facade.list_recommendations(self.team.id)+ page = self.paginate_queryset(recommendations)+ if page is not None:+ return self.get_paginated_response(self.get_serializer(page, many=True).data)+ return Response(self.get_serializer(recommendations, many=True).data)@extend_schema(request=None, responses=ErrorTrackingRecommendationSerializer)@action(detail=True, methods=["post"])- def refresh(self, request: Request, *args, **kwargs) -> Response:- recommendation = self.get_object()- if recommendation.type not in RECOMMENDATIONS_BY_TYPE:- return Response({"detail": "Unknown recommendation type."}, status=status.HTTP_400_BAD_REQUEST)+ def refresh(self, request: Request, *args, pk=None, **kwargs) -> Response:force = request.query_params.get("force", "true").lower() != "false"- if force and claim_for_compute(recommendation.id, self.team.id, timezone.now()):- try:- compute_error_tracking_recommendation.delay(str(recommendation.id), self.team.id)- except Exception:- revert_to_ready(recommendation.id, self.team.id)- raise- recommendation.refresh_from_db()- return Response(ErrorTrackingRecommendationSerializer(recommendation).data, status=status.HTTP_200_OK)+ try:+ recommendation = recommendations_facade.refresh_recommendation(self.team.id, pk, force=force)+ except recommendations_facade.RecommendationNotFoundError:+ raise NotFound()+ except recommendations_facade.UnknownRecommendationTypeError:+ return Response({"detail": "Unknown recommendation type."}, status=status.HTTP_400_BAD_REQUEST)+ return Response(self.get_serializer(recommendation).data, status=status.HTTP_200_OK)@extend_schema(request=None, responses=ErrorTrackingRecommendationSerializer)@action(detail=True, methods=["post"])- def dismiss(self, request: Request, *args, **kwargs) -> Response:- recommendation = self.get_object()- recommendation.dismissed_at = timezone.now()- recommendation.save(update_fields=["dismissed_at", "updated_at"])- return Response(ErrorTrackingRecommendationSerializer(recommendation).data, status=status.HTTP_200_OK)+ def dismiss(self, request: Request, *args, pk=None, **kwargs) -> Response:+ try:+ recommendation = recommendations_facade.dismiss_recommendation(self.team.id, pk)+ except recommendations_facade.RecommendationNotFoundError:+ raise NotFound()+ return Response(self.get_serializer(recommendation).data, status=status.HTTP_200_OK)@extend_schema(request=None, responses=ErrorTrackingRecommendationSerializer)@action(detail=True, methods=["post"])- def restore(self, request: Request, *args, **kwargs) -> Response:- recommendation = self.get_object()- recommendation.dismissed_at = None- recommendation.save(update_fields=["dismissed_at", "updated_at"])- return Response(ErrorTrackingRecommendationSerializer(recommendation).data, status=status.HTTP_200_OK)+ def restore(self, request: Request, *args, pk=None, **kwargs) -> Response:+ try:+ recommendation = recommendations_facade.restore_recommendation(self.team.id, pk)+ except recommendations_facade.RecommendationNotFoundError:+ raise NotFound()+ return Response(self.get_serializer(recommendation).data, status=status.HTTP_200_OK)diff --git a/products/error_tracking/backend/presentation/views/suppression_rules.py b/products/error_tracking/backend/presentation/views/suppression_rules.pyindex d019557cfdde..1181360e2c9a 100644--- a/products/error_tracking/backend/presentation/views/suppression_rules.py+++ b/products/error_tracking/backend/presentation/views/suppression_rules.py@@ -3,7 +3,7 @@ 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 NotFound+from rest_framework.exceptions import NotFound, ValidationErrorfrom rest_framework.response import Responsefrom posthog.schema import PropertyGroupFilterValue@@ -106,12 +106,15 @@ class ErrorTrackingSuppressionRuleViewSet(TeamAndOrgViewSetMixin, viewsets.Generreturn 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"),- )+ try:+ 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"),+ )+ except error_tracking_api.InvalidBytecodeError as err:+ raise ValidationError(str(err)) from errif rule is None:raise NotFound()posthoganalytics.capture(@@ -151,11 +154,14 @@ class ErrorTrackingSuppressionRuleViewSet(TeamAndOrgViewSetMixin, viewsets.Generfilters = 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"],- )+ try:+ rule = error_tracking_api.create_suppression_rule(+ self.team.id,+ filters=filters,+ sampling_rate=request.validated_data["sampling_rate"],+ )+ except error_tracking_api.InvalidBytecodeError as err:+ raise ValidationError(str(err)) from errposthoganalytics.capture("error_tracking_suppression_rule_created",groups=groups(self.team.organization, self.team),diff --git a/products/error_tracking/backend/presentation/views/symbol_sets.py b/products/error_tracking/backend/presentation/views/symbol_sets.pyindex 72c2921fad80..ccc8db92490d 100644--- a/products/error_tracking/backend/presentation/views/symbol_sets.py+++ b/products/error_tracking/backend/presentation/views/symbol_sets.py@@ -1,141 +1,27 @@-import hashlib-from dataclasses import dataclass--from django.conf import settings-from django.db import transaction-from django.db.models import Q--import structlogimport posthoganalytics-from drf_spectacular.utils import extend_schema, extend_schema_field+from drf_spectacular.utils import extend_schemafrom rest_framework import pagination, serializers, status, viewsets-from rest_framework.exceptions import ValidationError+from rest_framework.exceptions import NotFound, ValidationErrorfrom rest_framework.parsers import FileUploadParser, JSONParser, MultiPartParserfrom rest_framework.request import Requestfrom rest_framework.response import Response+from rest_framework_dataclasses.serializers import DataclassSerializerfrom posthog.api.routing import TeamAndOrgViewSetMixinfrom posthog.api.utils import actionfrom posthog.event_usage import groups-from posthog.models.team.team import Team-from posthog.models.utils import uuid7from posthog.rate_limit import SymbolSetUploadBurstRateThrottle, SymbolSetUploadSustainedRateThrottle-from posthog.storage import object_storage--from products.error_tracking.backend.models import ErrorTrackingRelease, ErrorTrackingStackFrame, ErrorTrackingSymbolSet--logger = structlog.get_logger(__name__)--ONE_HUNDRED_MEGABYTES = 1024 * 1024 * 100-JS_DATA_MAGIC = b"posthog_error_tracking"-JS_DATA_VERSION = 1-JS_DATA_TYPE_SOURCE_AND_MAP = 2-PRESIGNED_MULTIPLE_UPLOAD_TIMEOUT = 60 * 5---def _extract_failure_code(error_codes: object) -> str | None:- if isinstance(error_codes, str):- return error_codes- if isinstance(error_codes, list):- for error_code in error_codes:- failure_code = _extract_failure_code(error_code)- if failure_code:- return failure_code+from products.error_tracking.backend.facade import (+ contracts,+ symbol_sets as symbol_sets_facade,+)+from products.error_tracking.backend.presentation.pagination import paginate_via_facade- if isinstance(error_codes, dict):- for error_code in error_codes.values():- failure_code = _extract_failure_code(error_code)- if failure_code:- return failure_code-- return None---def _get_failure_code(exception: Exception) -> str | None:- if isinstance(exception, ValidationError):- return _extract_failure_code(exception.get_codes())-- return None---class ErrorTrackingSymbolSetSerializer(serializers.ModelSerializer):- id = serializers.UUIDField(read_only=True, help_text="Unique symbol set ID.")- ref = serializers.CharField(read_only=True, help_text="Reference used to match stack frames to this symbol set.")- team_id = serializers.IntegerField(read_only=True, help_text="Project/team ID that owns this symbol set.")- created_at = serializers.DateTimeField(read_only=True, help_text="When this symbol set row was created.")- last_used = serializers.DateTimeField(- read_only=True,- allow_null=True,- help_text="When this symbol set was last used to resolve a stack frame.",- )- failure_reason = serializers.CharField(- read_only=True,- allow_blank=True,- allow_null=True,- help_text="Reason symbol lookup failed, if the source map is missing or invalid.",- )- has_uploaded_file = serializers.SerializerMethodField(- help_text="Whether this symbol set has an uploaded source map file available to download."- )- release = serializers.SerializerMethodField(help_text="Release associated with this symbol set, if any.")+class ErrorTrackingSymbolSetSerializer(DataclassSerializer):class Meta:- model = ErrorTrackingSymbolSet- fields = [- "id",- "ref",- "team_id",- "created_at",- "last_used",- "failure_reason",- "has_uploaded_file",- "release",- ]- read_only_fields = [- "id",- "ref",- "team_id",- "created_at",- "last_used",- "failure_reason",- "has_uploaded_file",- "release",- ]-- @extend_schema_field(- serializers.BooleanField(- help_text="Whether this symbol set has an uploaded source map file available to download."- )- )- def get_has_uploaded_file(self, obj: ErrorTrackingSymbolSet) -> bool:- return bool(obj.storage_ptr)-- @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 contracts- from products.error_tracking.backend.presentation.views.releases import ErrorTrackingReleaseSerializer-- if obj.release:- 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).data- return None---@dataclass-class SymbolSetUpload:- chunk_id: str- release_id: str | None- content_hash: str | None+ dataclass = contracts.ErrorTrackingSymbolSetclass ErrorTrackingSymbolSetUploadSerializer(serializers.Serializer):@@ -239,9 +125,8 @@ class ErrorTrackingSymbolSetPagination(pagination.LimitOffsetPagination):max_limit = 100-class ErrorTrackingSymbolSetViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):+class ErrorTrackingSymbolSetViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):scope_object = "error_tracking"- queryset = ErrorTrackingSymbolSet.objects.all()serializer_class = ErrorTrackingSymbolSetSerializerpagination_class = ErrorTrackingSymbolSetPaginationparser_classes = [MultiPartParser, FileUploadParser]@@ -257,114 +142,83 @@ class ErrorTrackingSymbolSetViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSe"create",]- def _get_list_params(self, request: Request) -> dict[str, str]:- serializer = ErrorTrackingSymbolSetListQuerySerializer(data=request.query_params)- serializer.is_valid(raise_exception=True)- return dict(serializer.validated_data)-- def safely_get_queryset(self, queryset):- queryset = queryset.filter(team_id=self.team.id).select_related("release")- if self.action != "list":- return queryset-- params = self._get_list_params(self.request)- ref = params.get("ref")- search = params.get("search")- symbol_set_status = params.get("status")- order_by = params.get("order_by")-- if ref:- queryset = queryset.filter(ref=ref)-- if search:- queryset = queryset.filter(- Q(ref__icontains=search)- | Q(release__version__icontains=search)- | Q(release__project__icontains=search)- | Q(release__metadata__git__commit_id__icontains=search)- )-- if symbol_set_status == "valid":- queryset = queryset.filter(storage_ptr__isnull=False)- elif symbol_set_status == "invalid":- queryset = queryset.filter(storage_ptr__isnull=True)-- if order_by:- queryset = queryset.order_by(order_by)-- return queryset+ @extend_schema(parameters=[ErrorTrackingSymbolSetListQuerySerializer])+ def list(self, request: Request, *args, **kwargs) -> Response:+ query = ErrorTrackingSymbolSetListQuerySerializer(data=request.query_params)+ query.is_valid(raise_exception=True)+ params = dict(query.validated_data)+ return paginate_via_facade(+ self,+ request,+ lambda limit, offset: symbol_sets_facade.list_symbol_sets(+ self.team.id,+ ref=params.get("ref"),+ search=params.get("search"),+ symbol_set_status=params.get("status"),+ order_by=params.get("order_by"),+ limit=limit,+ offset=offset,+ ),+ )- def destroy(self, request, *args, **kwargs):- symbol_set = self.get_object()- symbol_set.delete()- return Response(status=status.HTTP_204_NO_CONTENT)+ def retrieve(self, request: Request, *args, pk=None, **kwargs) -> Response:+ symbol_set = symbol_sets_facade.get_symbol_set(self.team.id, pk)+ if symbol_set is None:+ raise NotFound()+ return Response(self.get_serializer(symbol_set).data)- # ModelViewSet provides update/partial_update by default, but the serializer is entirely- # read-only — there's nothing a client could set via PUT/PATCH. Hide them from the spec- # so generated typed clients don't surface unusable methods.+ # The serializer is entirely read-only, so PUT/PATCH cannot change anything. Keep the routes+ # (a client may still call them) but hide them from the spec so generated clients don't surface+ # unusable methods.@extend_schema(exclude=True)- def update(self, request, *args, **kwargs):- return super().update(request, *args, **kwargs)+ def update(self, request: Request, *args, pk=None, **kwargs) -> Response:+ return self._retrieve_unchanged(pk)@extend_schema(exclude=True)- def partial_update(self, request, *args, **kwargs):- return super().partial_update(request, *args, **kwargs)+ def partial_update(self, request: Request, *args, pk=None, **kwargs) -> Response:+ return self._retrieve_unchanged(pk)++ def _retrieve_unchanged(self, pk) -> Response:+ symbol_set = symbol_sets_facade.get_symbol_set(self.team.id, pk)+ if symbol_set is None:+ raise NotFound()+ return Response(self.get_serializer(symbol_set).data)++ def destroy(self, request: Request, *args, pk=None, **kwargs) -> Response:+ if not symbol_sets_facade.delete_symbol_set(self.team.id, pk):+ raise NotFound()+ return Response(status=status.HTTP_204_NO_CONTENT)@extend_schema(request=ErrorTrackingSymbolSetBulkDeleteSerializer)@action(methods=["POST"], detail=False, parser_classes=[JSONParser])- def bulk_delete(self, request, **kwargs):+ def bulk_delete(self, request: Request, **kwargs) -> Response:ids = request.data.get("ids", [])if not ids:return Response({"detail": "ids is required"}, status=status.HTTP_400_BAD_REQUEST)if not isinstance(ids, list):return Response({"detail": "ids must be a list"}, status=status.HTTP_400_BAD_REQUEST)- symbol_sets = ErrorTrackingSymbolSet.objects.filter(team=self.team, id__in=ids)- deleted_count, _ = symbol_sets.delete()+ deleted_count = symbol_sets_facade.bulk_delete_symbol_sets(self.team.id, ids)return Response({"deleted": deleted_count}, status=status.HTTP_200_OK)- @extend_schema(- responses={200: _SymbolSetDownloadResponseSerializer},- )+ @extend_schema(responses={200: _SymbolSetDownloadResponseSerializer})@action(methods=["GET"], detail=True, parser_classes=[JSONParser])- def download(self, request: Request, **kwargs) -> Response:+ def download(self, request: Request, *args, pk=None, **kwargs) -> Response:"""Return a presigned URL for downloading the symbol set's source map."""- return self._download_symbol_set(self.get_object())-- def _download_symbol_set(self, symbol_set: ErrorTrackingSymbolSet) -> Response:- if not symbol_set.storage_ptr:- return Response(- {"detail": "Symbol set has no uploaded file."},- status=status.HTTP_404_NOT_FOUND,- )-- presigned_url = object_storage.get_presigned_url(- file_key=symbol_set.storage_ptr,- expiration=3600,- )+ try:+ result = symbol_sets_facade.get_download(self.team.id, pk)+ except symbol_sets_facade.SymbolSetNotFoundError:+ raise NotFound()- if not presigned_url:+ if not result.has_file:+ return Response({"detail": "Symbol set has no uploaded file."}, status=status.HTTP_404_NOT_FOUND)+ if not result.url:return Response(- {"detail": "Could not generate download URL."},- status=status.HTTP_500_INTERNAL_SERVER_ERROR,+ {"detail": "Could not generate download URL."}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)-- return Response({"url": presigned_url}, status=status.HTTP_200_OK)-- @extend_schema(parameters=[ErrorTrackingSymbolSetListQuerySerializer])- def list(self, request: Request, *args, **kwargs) -> Response:- queryset = self.filter_queryset(self.get_queryset())- page = self.paginate_queryset(queryset)- if page is not None:- serializer = self.get_serializer(page, many=True)- return self.get_paginated_response(serializer.data)-- # Fallback for non-paginated responses- serializer = self.get_serializer(queryset, many=True)- return Response(serializer.data)+ return Response({"url": result.url}, status=status.HTTP_200_OK)@extend_schema(exclude=True) # deprecated; serializer has no settable fields, hidden from typed clients- def create(self, request, *args, **kwargs) -> Response:- # pull the symbol set reference from the query params+ def create(self, request: Request, *args, **kwargs) -> Response:chunk_id = request.query_params.get("chunk_id", None)multipart = request.query_params.get("multipart", False)release_id = request.query_params.get("release_id", None)@@ -387,15 +241,14 @@ class ErrorTrackingSymbolSetViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSe# file added to the request data by the FileUploadParserdata = request.data["file"].read()- (storage_ptr, content_hash) = upload_content(bytearray(data))- create_symbol_set(chunk_id, self.team, release_id, storage_ptr, content_hash)+ symbol_sets_facade.create_deprecated_symbol_set(self.team, chunk_id, release_id, bytearray(data))return Response({"ok": True}, status=status.HTTP_201_CREATED)# DEPRECATED: we should eventually remove this once everyone is using a new enough version of the CLI@extend_schema(exclude=True)@action(methods=["POST"], detail=False)- def start_upload(self, request, **kwargs):+ def start_upload(self, request: Request, **kwargs) -> Response:chunk_id = request.query_params.get("chunk_id", None)release_id = request.query_params.get("release_id", None)@@ -405,30 +258,18 @@ class ErrorTrackingSymbolSetViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSeproperties={"team_id": self.team.id, "endpoint": "start_upload"},)- if not settings.OBJECT_STORAGE_ENABLED:- raise ValidationError(- code="object_storage_required",- detail="Object storage must be available to allow source map uploads.",- )-if not chunk_id:return Response({"detail": "chunk_id query parameter is required"}, status=status.HTTP_400_BAD_REQUEST)- file_key = generate_symbol_set_file_key()- presigned_url = object_storage.get_presigned_post(- file_key=file_key,- conditions=[["content-length-range", 0, ONE_HUNDRED_MEGABYTES]],- )-- symbol_set = create_symbol_set(chunk_id, self.team, release_id, file_key)+ presigned_url, symbol_set_id = symbol_sets_facade.start_deprecated_upload(self.team, chunk_id, release_id)return Response(- {"presigned_url": presigned_url, "symbol_set_id": str(symbol_set.pk)}, status=status.HTTP_201_CREATED+ {"presigned_url": presigned_url, "symbol_set_id": symbol_set_id}, status=status.HTTP_201_CREATED)@extend_schema(request=ErrorTrackingSymbolSetFinishUploadSerializer)@action(methods=["PUT"], detail=True, parser_classes=[JSONParser])- def finish_upload(self, request, **kwargs):+ def finish_upload(self, request: Request, *args, pk=None, **kwargs) -> Response:content_hash = request.data.get("content_hash")if not content_hash:@@ -437,57 +278,27 @@ class ErrorTrackingSymbolSetViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSedetail="A content hash must be provided to complete symbol set upload.",)- if not settings.OBJECT_STORAGE_ENABLED:- raise ValidationError(- code="object_storage_required",- detail="Object storage must be available to allow source map uploads.",- )-- symbol_set = self.get_object()- s3_upload = object_storage.head_object(file_key=symbol_set.storage_ptr)-- if s3_upload:- content_length = s3_upload.get("ContentLength")-- if not content_length or content_length > ONE_HUNDRED_MEGABYTES:- symbol_set.delete()-- raise ValidationError(- code="file_too_large",- detail="The uploaded symbol set file was too large.",- )- else:- raise ValidationError(- code="file_not_found",- detail="No file has been uploaded for the symbol set.",- )-- if not symbol_set.content_hash:- symbol_set.content_hash = content_hash- symbol_set.save()+ try:+ symbol_sets_facade.finish_upload(self.team.id, pk, content_hash)+ except symbol_sets_facade.SymbolSetNotFoundError:+ raise NotFound()return Response({"success": True}, status=status.HTTP_200_OK)@extend_schema(request=ErrorTrackingSymbolSetBulkStartUploadSerializer)@action(methods=["POST"], detail=False, parser_classes=[JSONParser])- def bulk_start_upload(self, request, **kwargs):+ def bulk_start_upload(self, request: Request, **kwargs) -> Response:if request.user.pk:- posthoganalytics.identify_context(request.user.pk)+ posthoganalytics.identify_context(str(request.user.pk))upload_serializer = ErrorTrackingSymbolSetBulkStartUploadSerializer(data=request.data)- _ = upload_serializer.is_valid(raise_exception=True)+ upload_serializer.is_valid(raise_exception=True)upload_data = upload_serializer.validated_data- # Earlier clients send chunk_ids, all associated with one release.- chunk_ids: list[str] = upload_data.get("chunk_ids") or []- release_id: str | None = upload_data.get("release_id", None)-- # force=True allows overwriting an existing symbol set whose content has changed.- # skip_on_conflict=True leaves the existing symbol set unchanged and continues.force: bool = upload_data["force"]skip_on_conflict: bool = upload_data["skip_on_conflict"]- _ = posthoganalytics.capture(+ posthoganalytics.capture("error_tracking_symbol_set_upload_started",properties={"team_id": self.team.id,@@ -498,31 +309,22 @@ class ErrorTrackingSymbolSetViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSegroups=groups(self.team.organization, self.team),)- symbol_sets = [SymbolSetUpload(**data) for data in upload_data.get("symbol_sets", [])]-- symbol_sets.extend([SymbolSetUpload(x, release_id, None) for x in chunk_ids])-- if not settings.OBJECT_STORAGE_ENABLED:- raise ValidationError(- code="object_storage_required",- detail="Object storage must be available to allow source map uploads.",- )-- chunk_id_url_map = bulk_create_symbol_sets(- symbol_sets,+ id_map = symbol_sets_facade.bulk_start_upload(self.team,+ symbol_sets=list(upload_data.get("symbol_sets", [])),+ chunk_ids=list(upload_data.get("chunk_ids") or []),+ release_id=upload_data.get("release_id", None),force=force,skip_on_conflict=skip_on_conflict,distinct_id=str(request.user.pk) if request.user.pk else None,)- return Response({"id_map": chunk_id_url_map}, status=status.HTTP_201_CREATED)+ return Response({"id_map": id_map}, status=status.HTTP_201_CREATED)@extend_schema(request=ErrorTrackingSymbolSetBulkFinishUploadSerializer)@action(methods=["POST"], detail=False, parser_classes=[JSONParser])- def bulk_finish_upload(self, request, **kwargs):+ def bulk_finish_upload(self, request: Request, **kwargs) -> Response:if request.user.pk:- posthoganalytics.identify_context(request.user.pk)- # Get the map of symbol_set_id:content_hashes+ posthoganalytics.identify_context(str(request.user.pk))content_hashes = request.data.get("content_hashes", {})if content_hashes is None:return Response({"detail": "content_hashes are required"}, status=status.HTTP_400_BAD_REQUEST)@@ -533,320 +335,6 @@ class ErrorTrackingSymbolSetViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSe# we can early exit here.return Response({"success": True}, status=status.HTTP_201_CREATED)- if not settings.OBJECT_STORAGE_ENABLED:- raise ValidationError(- code="object_storage_required",- detail="Object storage must be available to allow source map uploads.",- )-- file_count = len(content_hashes)- symbol_set_ids = set(content_hashes.keys())- total_file_size = 0- try:- symbol_sets = list(ErrorTrackingSymbolSet.objects.filter(team=self.team, id__in=symbol_set_ids))- found_symbol_set_ids = {str(symbol_set.id) for symbol_set in symbol_sets}- missing_symbol_set_ids = symbol_set_ids - found_symbol_set_ids- if missing_symbol_set_ids:- raise ValidationError(- code="symbol_set_not_found",- detail=f"Unknown symbol set IDs: {', '.join(sorted(missing_symbol_set_ids))}",- )-- for symbol_set in symbol_sets:- s3_upload = None- if symbol_set.storage_ptr:- s3_upload = object_storage.head_object(file_key=symbol_set.storage_ptr)-- if s3_upload:- content_length = s3_upload.get("ContentLength")- if content_length:- total_file_size += content_length-- if not content_length or content_length > ONE_HUNDRED_MEGABYTES:- symbol_set.delete()-- raise ValidationError(- code="file_too_large",- detail="The uploaded symbol set file was too large.",- )- else:- raise ValidationError(- code="file_not_found",- detail="No file has been uploaded for the symbol set.",- )-- content_hash = content_hashes[str(symbol_set.id)]- symbol_set.content_hash = content_hash- ErrorTrackingSymbolSet.objects.bulk_update(symbol_sets, ["content_hash"])- except Exception as e:- posthoganalytics.capture(- "error_tracking_symbol_set_uploaded",- properties={- "file_size": total_file_size,- "success": False,- "file_count": file_count,- "failure_reason": type(e).__name__,- "failure_code": _get_failure_code(e),- },- groups=groups(self.team.organization, self.team),- )- raise-- posthoganalytics.capture(- "error_tracking_symbol_set_uploaded",- properties={- "file_size": total_file_size,- "success": True,- "file_count": file_count,- },- groups=groups(self.team.organization, self.team),- )+ symbol_sets_facade.bulk_finish_upload(self.team, content_hashes)return Response({"success": True}, status=status.HTTP_201_CREATED)---def create_symbol_set(- chunk_id: str, team: Team, release_id: str | None, storage_ptr: str, content_hash: str | None = None-):- if release_id:- objects = ErrorTrackingRelease.objects.all().filter(team=team, id=release_id)- if len(objects) < 1:- raise ValueError(f"Unknown release: {release_id}")- release = objects[0]- else:- release = None-- with transaction.atomic():- try:- symbol_set = ErrorTrackingSymbolSet.objects.get(team=team, ref=chunk_id)- if symbol_set.release is None:- symbol_set.release = release- elif symbol_set.release != release:- raise ValidationError(f"Symbol set has already been uploaded for a different release")- symbol_set.storage_ptr = storage_ptr- symbol_set.content_hash = content_hash- symbol_set.save()-- except ErrorTrackingSymbolSet.DoesNotExist:- symbol_set = ErrorTrackingSymbolSet.objects.create(- team=team,- ref=chunk_id,- release=release,- storage_ptr=storage_ptr,- content_hash=content_hash,- )-- # Delete any existing frames associated with this symbol set- ErrorTrackingStackFrame.objects.filter(team=team, symbol_set=symbol_set).delete()-- return symbol_set---def bulk_create_symbol_sets(- new_symbol_sets: list[SymbolSetUpload],- team: Team,- force: bool = False,- skip_on_conflict: bool = False,- distinct_id: str | None = None,-) -> dict[str, dict[str, str]]:- accelerate = bool(- distinct_id- and posthoganalytics.feature_enabled(- "error-tracking-s3-accelerate",- distinct_id,- groups={"organization": str(team.organization.id)},- send_feature_flag_events=False,- )- )-- chunk_ids = [x.chunk_id for x in new_symbol_sets]-- # Check for dupes- duplicates = [x for x in chunk_ids if chunk_ids.count(x) > 1]- if duplicates:- raise ValidationError(- code="invalid_chunk_ids",- detail=f"Duplicate chunk IDs provided: {', '.join(duplicates)}",- )-- # Check we're using all valid release IDs- release_ids = {ss.release_id for ss in new_symbol_sets if ss.release_id}- fetched_releases = {str(r.id) for r in ErrorTrackingRelease.objects.all().filter(team=team, pk__in=release_ids)}- for release_id in release_ids:- if release_id not in fetched_releases:- raise ValidationError(- code="invalid_release_id",- detail=f"Unknown release ID provided: {release_id}",- )-- id_url_map: dict[str, dict[str, str]] = {}- new_symbol_set_map = {x.chunk_id: x for x in new_symbol_sets}-- with transaction.atomic():- existing_symbol_sets = list(ErrorTrackingSymbolSet.objects.filter(team=team, ref__in=chunk_ids))- existing_symbol_set_refs = [s.ref for s in existing_symbol_sets]- missing_sets = list(set(chunk_ids) - set(existing_symbol_set_refs))-- symbol_sets_to_be_created = []- for chunk_id in missing_sets:- storage_ptr = generate_symbol_set_file_key()- presigned_url = generate_symbol_set_upload_presigned_url(storage_ptr, accelerate=accelerate)- id_url_map[chunk_id] = {"presigned_url": presigned_url}- # Note that on creation, we /do not set/ the content hash. We use content hashes included in- # the create request only to see if we can skip updated - we set the content hash when we- # get upload confirmation, during `bulk_finish_upload`, not before- to_create = ErrorTrackingSymbolSet(- team=team,- ref=chunk_id,- storage_ptr=storage_ptr,- release_id=new_symbol_set_map[chunk_id].release_id,- )- symbol_sets_to_be_created.append(to_create)-- # create missing symbol sets- created_symbol_sets = ErrorTrackingSymbolSet.objects.bulk_create(symbol_sets_to_be_created)-- for symbol_set in created_symbol_sets:- id_url_map[symbol_set.ref]["symbol_set_id"] = str(symbol_set.pk)-- # update existing symbol sets- to_update = []- for existing in existing_symbol_sets:- upload = new_symbol_set_map[existing.ref]- dirty = False-- # Allow adding an "orphan" symbol set to a release, but not- # moving symbols sets between releases- if upload.release_id:- if existing.release_id is None:- existing.release_id = upload.release_id- dirty = True- elif str(existing.release_id) != upload.release_id:- raise ValidationError(- code="release_id_mismatch",- detail=f"Symbol set {existing.ref} already has a release ID",- )-- if upload.content_hash is None:- if existing.content_hash is not None:- # Old CLI (no content hash) trying to re-upload a symbol set- # that was already fully uploaded. We can't determine safety,- # so reject rather than silently overwrite production data.- raise ValidationError(- code="content_hash_required",- detail=f"Symbol set {existing.ref} already has content; provide a content_hash to update it.",- )- # Both sides have no hash: this is a pending upload being restarted.- # Issue a fresh presigned URL so the client can retry.- storage_ptr = generate_symbol_set_file_key()- presigned_url = generate_symbol_set_upload_presigned_url(storage_ptr, accelerate=accelerate)- id_url_map[existing.ref] = {- "presigned_url": presigned_url,- "symbol_set_id": str(existing.id),- }- existing.storage_ptr = storage_ptr- dirty = True- elif existing.content_hash is None:- # Existing record has no hash (pending upload or uploaded by old CLI- # without hash support). Allow the new upload to supply one.- storage_ptr = generate_symbol_set_file_key()- presigned_url = generate_symbol_set_upload_presigned_url(storage_ptr, accelerate=accelerate)- id_url_map[existing.ref] = {- "presigned_url": presigned_url,- "symbol_set_id": str(existing.id),- }- existing.storage_ptr = storage_ptr- dirty = True- elif existing.content_hash == upload.content_hash:- # Content is identical — no upload needed.- # (We may still update the release below if it changed.)- pass- elif force:- # force=True: content has changed and the caller explicitly- # requested an overwrite. Issue a new presigned URL and clear- # the old content hash so bulk_finish_upload stores the new one.- storage_ptr = generate_symbol_set_file_key()- presigned_url = generate_symbol_set_upload_presigned_url(storage_ptr, accelerate=accelerate)- id_url_map[existing.ref] = {- "presigned_url": presigned_url,- "symbol_set_id": str(existing.id),- }- existing.storage_ptr = storage_ptr- existing.content_hash = None # will be set by bulk_finish_upload- dirty = True- elif skip_on_conflict:- # Content has changed, but the caller explicitly asked to keep- # the already-uploaded symbol set.- logger.warning(- "symbol_set_content_changed_skipped",- ref=existing.ref,- team_id=team.id,- )- else:- raise ValidationError(- code="content_hash_mismatch",- detail=f"Symbol set {existing.ref} already exists with different content.",- )-- if dirty:- to_update.append(existing)-- # We update only the symbol sets we modified the release of - for all others, this is a no-op (we assume they were uploaded- # during a prior attempt or something).- _ = ErrorTrackingSymbolSet.objects.bulk_update(to_update, ["release", "content_hash", "storage_ptr"])-- return id_url_map---def upload_content(content: bytearray) -> tuple[str, str]:- content_hash = hashlib.sha512(content).hexdigest()-- if not settings.OBJECT_STORAGE_ENABLED:- raise ValidationError(- code="object_storage_required",- detail="Object storage must be available to allow source map uploads.",- )-- if len(content) > ONE_HUNDRED_MEGABYTES:- raise ValidationError(- code="file_too_large", detail="Combined source map and symbol set must be less than 100MB"- )-- upload_path = generate_symbol_set_file_key()- object_storage.write(upload_path, bytes(content))- return (upload_path, content_hash)---def construct_js_data_object(minified: bytes, source_map: bytes) -> bytearray:- # See rust/cymbal/hacks/js_data.rs- data = bytearray()- data.extend(JS_DATA_MAGIC)- data.extend(JS_DATA_VERSION.to_bytes(4, "little"))- data.extend((JS_DATA_TYPE_SOURCE_AND_MAP).to_bytes(4, "little"))- # TODO - this doesn't seem right?- s_bytes = minified.decode("utf-8").encode("utf-8")- data.extend(len(s_bytes).to_bytes(8, "little"))- data.extend(s_bytes)- sm_bytes = source_map.decode("utf-8").encode("utf-8")- data.extend(len(sm_bytes).to_bytes(8, "little"))- data.extend(sm_bytes)- return data---def generate_symbol_set_file_key():- return f"{settings.OBJECT_STORAGE_ERROR_TRACKING_SOURCE_MAPS_FOLDER}/{str(uuid7())}"---def generate_symbol_set_upload_presigned_url(file_key: str, *, accelerate: bool = False):- if accelerate:- return object_storage.get_accelerated_presigned_post(- file_key=file_key,- conditions=[["content-length-range", 0, ONE_HUNDRED_MEGABYTES]],- expiration=PRESIGNED_MULTIPLE_UPLOAD_TIMEOUT,- )- return object_storage.get_presigned_post(- file_key=file_key,- conditions=[["content-length-range", 0, ONE_HUNDRED_MEGABYTES]],- expiration=PRESIGNED_MULTIPLE_UPLOAD_TIMEOUT,- )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 0a62acb1d0ee..277e803d5e67 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@@ -517,7 +517,7 @@ class TestErrorTracking(APIBaseTest):symbol_set.refresh_from_db()self.assertEqual(symbol_set.storage_ptr, "symbolsets/source_1")- @patch("products.error_tracking.backend.presentation.views.symbol_sets.object_storage.get_presigned_url")+ @patch("products.error_tracking.backend.logic.symbol_sets.object_storage.get_presigned_url")def test_download_symbol_set(self, patched_get_presigned_url: Mock) -> None:patched_get_presigned_url.return_value = "https://example.com/source.map"symbol_set = ErrorTrackingSymbolSet.objects.create(@@ -640,8 +640,8 @@ class TestErrorTracking(APIBaseTest):# cannot assign issues from other teamsself.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND)- @patch("products.error_tracking.backend.presentation.views.issues.dispatch_issue_assigned_realtime")- @patch("products.error_tracking.backend.presentation.views.issues.send_error_tracking_issue_assigned")+ @patch("products.error_tracking.backend.logic.issue_mutations.dispatch_issue_assigned_realtime")+ @patch("products.error_tracking.backend.logic.issue_mutations.send_error_tracking_issue_assigned")def test_assign_issue_dispatches_realtime_after_assignment(self, _send_email, mock_realtime):issue = self.create_issue()other_user = User.objects.create_and_join(self.organization, "[email protected]", "password")@@ -1059,7 +1059,7 @@ class TestErrorTracking(APIBaseTest):assert ErrorTrackingSymbolSet.objects.get(id=symbol_set_one.id).content_hash == "hash_one"assert ErrorTrackingSymbolSet.objects.get(id=symbol_set_two.id).content_hash == "hash_two"- @patch("products.error_tracking.backend.presentation.views.symbol_sets.posthoganalytics.capture")+ @patch("products.error_tracking.backend.logic.symbol_sets.posthoganalytics.capture")def test_bulk_finish_upload_rejects_unknown_symbol_set_ids(self, patched_capture: Mock) -> None:response = self.client.post(f"/api/environments/{self.team.id}/error_tracking/symbol_sets/bulk_finish_upload",@@ -1078,7 +1078,7 @@ class TestErrorTracking(APIBaseTest):"failure_code": "symbol_set_not_found",}- @patch("products.error_tracking.backend.presentation.views.symbol_sets.posthoganalytics.capture")+ @patch("products.error_tracking.backend.logic.symbol_sets.posthoganalytics.capture")@patch("posthog.storage.object_storage.head_object")def test_bulk_finish_upload_preserves_pending_symbol_set_when_file_is_not_found(self, patched_object_storage, patched_capture: Mockdiff --git a/products/error_tracking/backend/tests/api/test_query_api.py b/products/error_tracking/backend/tests/api/test_query_api.pyindex 3e53adebae52..c9a8fef5df43 100644--- a/products/error_tracking/backend/tests/api/test_query_api.py+++ b/products/error_tracking/backend/tests/api/test_query_api.py@@ -230,9 +230,7 @@ class TestErrorTrackingQueryAPI(ClickhouseTestMixin, APIBaseTest):observed_tags.append((tags.product, tags.feature))return FakeQueryResponse({"results": [], "hasMore": False, "limit": 25, "offset": 0})- with patch(- "products.error_tracking.backend.presentation.views.query.ErrorTrackingQueryRunner.calculate", calculate- ):+ with patch("products.error_tracking.backend.facade.queries.ErrorTrackingQueryRunner.calculate", calculate):response = self.client.post(f"/api/environments/{self.team.id}/error_tracking/query/issues",data={"limit": 1},@@ -249,9 +247,7 @@ class TestErrorTrackingQueryAPI(ClickhouseTestMixin, APIBaseTest):observed_volume_resolutions.append(runner.query.volumeResolution)return FakeQueryResponse({"results": [], "hasMore": False, "limit": 25, "offset": 0})- with patch(- "products.error_tracking.backend.presentation.views.query.ErrorTrackingQueryRunner.calculate", calculate- ):+ with patch("products.error_tracking.backend.facade.queries.ErrorTrackingQueryRunner.calculate", calculate):response = self.client.post(f"/api/environments/{self.team.id}/error_tracking/query/issues",data={"volumeResolution": 0},@@ -283,7 +279,7 @@ class TestErrorTrackingQueryAPI(ClickhouseTestMixin, APIBaseTest):with (patch(- "products.error_tracking.backend.presentation.views.query.ErrorTrackingQueryRunner.calculate",+ "products.error_tracking.backend.facade.queries.ErrorTrackingQueryRunner.calculate",calculate_issue,),patch(@@ -322,7 +318,7 @@ class TestErrorTrackingQueryAPI(ClickhouseTestMixin, APIBaseTest):with (patch(- "products.error_tracking.backend.presentation.views.query.ErrorTrackingQueryRunner.calculate",+ "products.error_tracking.backend.facade.queries.ErrorTrackingQueryRunner.calculate",calculate_issue,),patch(@@ -362,7 +358,7 @@ class TestErrorTrackingQueryAPI(ClickhouseTestMixin, APIBaseTest):with (patch(- "products.error_tracking.backend.presentation.views.query.ErrorTrackingQueryRunner.calculate",+ "products.error_tracking.backend.facade.queries.ErrorTrackingQueryRunner.calculate",calculate_issue,),patch(diff --git a/products/error_tracking/frontend/generated/api.schemas.ts b/products/error_tracking/frontend/generated/api.schemas.tsindex a7dcdc4c45ba..461adea28430 100644--- a/products/error_tracking/frontend/generated/api.schemas.ts+++ b/products/error_tracking/frontend/generated/api.schemas.ts@@ -519,58 +519,40 @@ export interface PatchedErrorTrackingGroupingRuleApi {readonly updated_at?: string}-/**- * * `archived` - Archived- * * `active` - Active- * * `resolved` - Resolved- * * `pending_release` - Pending release- * * `suppressed` - Suppressed- */-export type ErrorTrackingIssueFullStatusEnumApi =- (typeof ErrorTrackingIssueFullStatusEnumApi)[keyof typeof ErrorTrackingIssueFullStatusEnumApi]--export const ErrorTrackingIssueFullStatusEnumApi = {- Archived: 'archived',- Active: 'active',- Resolved: 'resolved',- PendingRelease: 'pending_release',- Suppressed: 'suppressed',-} as const--export interface ErrorTrackingIssueAssignmentApi {+export interface ErrorTrackingIssueAssigneeReadApi {readonly id: number | string | null- readonly type: string+ type: string+}++export interface ErrorTrackingIssueCohortReadApi {+ id: number+ name: string}/**- * @nullable+ * Read-only serializer for issue contract types returned by the facade.*/-export type ErrorTrackingIssueFullApiCohort = {- readonly id?: number- readonly name?: string-} | null--export interface ErrorTrackingIssueFullApi {- readonly id: string- status?: ErrorTrackingIssueFullStatusEnumApi+export interface ErrorTrackingIssueReadApi {+ id: string+ status: string/** @nullable */- name?: string | null+ name: string | null/** @nullable */- description?: string | null- first_seen: string- assignee: ErrorTrackingIssueAssignmentApi- external_issues: ErrorTrackingExternalReferenceResultApi[]+ description: string | null/** @nullable */- readonly cohort: ErrorTrackingIssueFullApiCohort+ first_seen: string | null+ assignee: ErrorTrackingIssueAssigneeReadApi | null+ external_issues: ErrorTrackingExternalReferenceResultApi[]+ cohort: ErrorTrackingIssueCohortReadApi | null}-export interface PaginatedErrorTrackingIssueFullListApi {+export interface PaginatedErrorTrackingIssueReadListApi {count: number/** @nullable */next?: string | null/** @nullable */previous?: string | null- results: ErrorTrackingIssueFullApi[]+ results: ErrorTrackingIssueReadApi[]}/**@@ -626,25 +608,20 @@ export interface PatchedErrorTrackingIssueWriteApi {}/**- * @nullable+ * Read-only serializer for issue contract types returned by the facade.*/-export type PatchedErrorTrackingIssueFullApiCohort = {- readonly id?: number- readonly name?: string-} | null--export interface PatchedErrorTrackingIssueFullApi {- readonly id?: string- status?: ErrorTrackingIssueFullStatusEnumApi+export interface PatchedErrorTrackingIssueReadApi {+ id?: string+ status?: string/** @nullable */name?: string | null/** @nullable */description?: string | null- first_seen?: string- assignee?: ErrorTrackingIssueAssignmentApi- external_issues?: ErrorTrackingExternalReferenceResultApi[]/** @nullable */- readonly cohort?: PatchedErrorTrackingIssueFullApiCohort+ first_seen?: string | null+ assignee?: ErrorTrackingIssueAssigneeReadApi | null+ external_issues?: ErrorTrackingExternalReferenceResultApi[]+ cohort?: ErrorTrackingIssueCohortReadApi | null}export interface ErrorTrackingIssueMergeRequestApi {@@ -1223,51 +1200,31 @@ export interface ErrorTrackingIssuesListResponseApi {nextOffset?: number}-/**- * * `ready` - Ready- * * `computing` - Computing- */-export type ErrorTrackingRecommendationStatusEnumApi =- (typeof ErrorTrackingRecommendationStatusEnumApi)[keyof typeof ErrorTrackingRecommendationStatusEnumApi]--export const ErrorTrackingRecommendationStatusEnumApi = {- Ready: 'ready',- Computing: 'computing',-} as const--/**- * Recommendation payload, shape depends on type.- */-export type ErrorTrackingRecommendationApiMeta = { [key: string]: unknown }-export interface ErrorTrackingRecommendationApi {/** Recommendation UUID. */- readonly id: string+ id: string/** Recommendation type identifier (e.g. 'alerts'). */- readonly type: string+ type: string/** Recommendation payload, shape depends on type. */- readonly meta: ErrorTrackingRecommendationApiMeta+ meta: unknown/** Whether the recommendation's recommended action has been satisfied. */- readonly completed: boolean- /** 'ready' if meta is fresh, 'computing' if a refresh is in progress.- *- * * `ready` - Ready- * * `computing` - Computing */- readonly status: ErrorTrackingRecommendationStatusEnumApi+ completed: boolean+ /** 'ready' if meta is fresh, 'computing' if a refresh is in progress. */+ status: string/*** Timestamp meta was last successfully computed.* @nullable*/- readonly computed_at: string | null+ computed_at: string | null/*** Timestamp the user dismissed this recommendation, if any.* @nullable*/- readonly dismissed_at: string | null+ dismissed_at: string | null/** Timestamp the recommendation row was first created. */- readonly created_at: string+ created_at: string/** Timestamp the recommendation row was last updated. */- readonly updated_at: string+ updated_at: string}export interface PaginatedErrorTrackingRecommendationListApi {@@ -1609,38 +1566,17 @@ export interface PatchedErrorTrackingSuppressionRuleApi {readonly updated_at?: string}-/**- * Release associated with this symbol set, if any.- * @nullable- */-export type ErrorTrackingSymbolSetApiRelease = { [key: string]: unknown } | null-export interface ErrorTrackingSymbolSetApi {- /** Unique symbol set ID. */- readonly id: string- /** Reference used to match stack frames to this symbol set. */- readonly ref: string- /** Project/team ID that owns this symbol set. */- readonly team_id: number- /** When this symbol set row was created. */- readonly created_at: string- /**- * When this symbol set was last used to resolve a stack frame.- * @nullable- */- readonly last_used: string | null- /**- * Reason symbol lookup failed, if the source map is missing or invalid.- * @nullable- */- readonly failure_reason: string | null- /** Whether this symbol set has an uploaded source map file available to download. */- readonly has_uploaded_file: boolean- /**- * Release associated with this symbol set, if any.- * @nullable- */- readonly release: ErrorTrackingSymbolSetApiRelease+ id: string+ ref: string+ team_id: number+ created_at: string+ /** @nullable */+ last_used: string | null+ /** @nullable */+ failure_reason: string | null+ has_uploaded_file: boolean+ release: ErrorTrackingReleaseApi | null}export interface PaginatedErrorTrackingSymbolSetListApi {diff --git a/products/error_tracking/frontend/generated/api.ts b/products/error_tracking/frontend/generated/api.tsindex ab0f15587b03..63a1ff830b80 100644--- a/products/error_tracking/frontend/generated/api.ts+++ b/products/error_tracking/frontend/generated/api.ts@@ -26,10 +26,10 @@ import type {ErrorTrackingIssueDetailApi,ErrorTrackingIssueEventsQueryRequestApi,ErrorTrackingIssueEventsResponseApi,- ErrorTrackingIssueFullApi,ErrorTrackingIssueMergeRequestApi,ErrorTrackingIssueMergeResponseApi,ErrorTrackingIssueQueryRequestApi,+ ErrorTrackingIssueReadApi,ErrorTrackingIssueSplitRequestApi,ErrorTrackingIssueSplitResponseApi,ErrorTrackingIssueWriteApi,@@ -63,7 +63,7 @@ import type {PaginatedErrorTrackingAssignmentRuleListApi,PaginatedErrorTrackingExternalReferenceResultListApi,PaginatedErrorTrackingFingerprintListApi,- PaginatedErrorTrackingIssueFullListApi,+ PaginatedErrorTrackingIssueReadListApi,PaginatedErrorTrackingRecommendationListApi,PaginatedErrorTrackingReleaseListApi,PaginatedErrorTrackingSpikeEventListApi,@@ -74,7 +74,7 @@ import type {PatchedErrorTrackingAssignmentRuleUpdateRequestApi,PatchedErrorTrackingGroupingRuleApi,PatchedErrorTrackingGroupingRuleUpdateRequestApi,- PatchedErrorTrackingIssueFullApi,+ PatchedErrorTrackingIssueReadApi,PatchedErrorTrackingIssueWriteApi,PatchedErrorTrackingReleaseUpdateRequestApi,PatchedErrorTrackingSettingsApi,@@ -586,30 +586,13 @@ export const errorTrackingIssuesList = async (projectId: string,params?: ErrorTrackingIssuesListParams,options?: RequestInit-): Promise<PaginatedErrorTrackingIssueFullListApi> => {- return apiMutator<PaginatedErrorTrackingIssueFullListApi>(getErrorTrackingIssuesListUrl(projectId, params), {+): Promise<PaginatedErrorTrackingIssueReadListApi> => {+ return apiMutator<PaginatedErrorTrackingIssueReadListApi>(getErrorTrackingIssuesListUrl(projectId, params), {...options,method: 'GET',})}-export const getErrorTrackingIssuesCreateUrl = (projectId: string) => {- return `/api/projects/${projectId}/error_tracking/issues/`-}--export const errorTrackingIssuesCreate = async (- projectId: string,- errorTrackingIssueFullApi: NonReadonly<ErrorTrackingIssueFullApi>,- options?: RequestInit-): Promise<ErrorTrackingIssueFullApi> => {- return apiMutator<ErrorTrackingIssueFullApi>(getErrorTrackingIssuesCreateUrl(projectId), {- ...options,- method: 'POST',- headers: { 'Content-Type': 'application/json', ...options?.headers },- body: JSON.stringify(errorTrackingIssueFullApi),- })-}-export const getErrorTrackingIssuesRetrieveUrl = (projectId: string, id: string) => {return `/api/projects/${projectId}/error_tracking/issues/${id}/`}@@ -618,8 +601,8 @@ export const errorTrackingIssuesRetrieve = async (projectId: string,id: string,options?: RequestInit-): Promise<ErrorTrackingIssueFullApi> => {- return apiMutator<ErrorTrackingIssueFullApi>(getErrorTrackingIssuesRetrieveUrl(projectId, id), {+): Promise<ErrorTrackingIssueReadApi> => {+ return apiMutator<ErrorTrackingIssueReadApi>(getErrorTrackingIssuesRetrieveUrl(projectId, id), {...options,method: 'GET',})@@ -634,8 +617,8 @@ export const errorTrackingIssuesUpdate = async (id: string,errorTrackingIssueWriteApi?: ErrorTrackingIssueWriteApi,options?: RequestInit-): Promise<ErrorTrackingIssueFullApi> => {- return apiMutator<ErrorTrackingIssueFullApi>(getErrorTrackingIssuesUpdateUrl(projectId, id), {+): Promise<ErrorTrackingIssueReadApi> => {+ return apiMutator<ErrorTrackingIssueReadApi>(getErrorTrackingIssuesUpdateUrl(projectId, id), {...options,method: 'PUT',headers: { 'Content-Type': 'application/json', ...options?.headers },@@ -652,8 +635,8 @@ export const errorTrackingIssuesPartialUpdate = async (id: string,patchedErrorTrackingIssueWriteApi?: PatchedErrorTrackingIssueWriteApi,options?: RequestInit-): Promise<ErrorTrackingIssueFullApi> => {- return apiMutator<ErrorTrackingIssueFullApi>(getErrorTrackingIssuesPartialUpdateUrl(projectId, id), {+): Promise<ErrorTrackingIssueReadApi> => {+ return apiMutator<ErrorTrackingIssueReadApi>(getErrorTrackingIssuesPartialUpdateUrl(projectId, id), {...options,method: 'PATCH',headers: { 'Content-Type': 'application/json', ...options?.headers },@@ -701,14 +684,14 @@ export const getErrorTrackingIssuesAssignPartialUpdateUrl = (projectId: string,export const errorTrackingIssuesAssignPartialUpdate = async (projectId: string,id: string,- patchedErrorTrackingIssueFullApi?: NonReadonly<PatchedErrorTrackingIssueFullApi>,+ patchedErrorTrackingIssueReadApi?: NonReadonly<PatchedErrorTrackingIssueReadApi>,options?: RequestInit): Promise<void> => {return apiMutator<void>(getErrorTrackingIssuesAssignPartialUpdateUrl(projectId, id), {...options,method: 'PATCH',headers: { 'Content-Type': 'application/json', ...options?.headers },- body: JSON.stringify(patchedErrorTrackingIssueFullApi),+ body: JSON.stringify(patchedErrorTrackingIssueReadApi),})}@@ -719,14 +702,14 @@ export const getErrorTrackingIssuesCohortUpdateUrl = (projectId: string, id: strexport const errorTrackingIssuesCohortUpdate = async (projectId: string,id: string,- errorTrackingIssueFullApi: NonReadonly<ErrorTrackingIssueFullApi>,+ errorTrackingIssueReadApi: NonReadonly<ErrorTrackingIssueReadApi>,options?: RequestInit): Promise<void> => {return apiMutator<void>(getErrorTrackingIssuesCohortUpdateUrl(projectId, id), {...options,method: 'PUT',headers: { 'Content-Type': 'application/json', ...options?.headers },- body: JSON.stringify(errorTrackingIssueFullApi),+ body: JSON.stringify(errorTrackingIssueReadApi),})}@@ -786,14 +769,14 @@ export const getErrorTrackingIssuesBulkCreateUrl = (projectId: string) => {export const errorTrackingIssuesBulkCreate = async (projectId: string,- errorTrackingIssueFullApi: NonReadonly<ErrorTrackingIssueFullApi>,+ errorTrackingIssueReadApi: NonReadonly<ErrorTrackingIssueReadApi>,options?: RequestInit): Promise<void> => {return apiMutator<void>(getErrorTrackingIssuesBulkCreateUrl(projectId), {...options,method: 'POST',headers: { 'Content-Type': 'application/json', ...options?.headers },- body: JSON.stringify(errorTrackingIssueFullApi),+ body: JSON.stringify(errorTrackingIssueReadApi),})}diff --git a/products/error_tracking/frontend/generated/api.zod.ts b/products/error_tracking/frontend/generated/api.zod.tsindex 0b90f9adfc4a..2fa795bf767d 100644--- a/products/error_tracking/frontend/generated/api.zod.ts+++ b/products/error_tracking/frontend/generated/api.zod.ts@@ -162,36 +162,6 @@ export const ErrorTrackingGroupingRulesReorderPartialUpdateBody = /* @__PURE__ *disabled_data: zod.unknown().optional(),})-export const ErrorTrackingIssuesCreateBody = /* @__PURE__ */ zod.object({- status: zod- .enum(['archived', 'active', 'resolved', 'pending_release', 'suppressed'])- .optional()- .describe(- '\* `archived` - Archived\n\* `active` - Active\n\* `resolved` - Resolved\n\* `pending_release` - Pending release\n\* `suppressed` - Suppressed'- ),- name: zod.string().nullish(),- description: zod.string().nullish(),- first_seen: zod.iso.datetime({ offset: true }),- assignee: zod.object({- id: zod.union([zod.number(), zod.string(), zod.null()]),- type: zod.string(),- }),- external_issues: zod.array(- zod.object({- id: zod.uuid(),- integration: zod.object({- id: zod.number(),- kind: zod.string(),- display_name: zod.string(),- }),- integration_id: zod.number(),- config: zod.unknown(),- issue: zod.uuid(),- external_url: zod.string(),- })- ),-})-export const ErrorTrackingIssuesUpdateBody = /* @__PURE__ */ zod.object({status: zod.enum(['active', 'resolved', 'suppressed'])@@ -216,24 +186,65 @@ export const ErrorTrackingIssuesPartialUpdateBody = /* @__PURE__ */ zod.object({description: zod.string().nullish().describe('Optional issue description.'),})-export const ErrorTrackingIssuesAssignPartialUpdateBody = /* @__PURE__ */ zod.object({- status: zod- .enum(['archived', 'active', 'resolved', 'pending_release', 'suppressed'])- .optional()- .describe(- '\* `archived` - Archived\n\* `active` - Active\n\* `resolved` - Resolved\n\* `pending_release` - Pending release\n\* `suppressed` - Suppressed'- ),- name: zod.string().nullish(),- description: zod.string().nullish(),- first_seen: zod.iso.datetime({ offset: true }).optional(),- assignee: zod- .object({- id: zod.union([zod.number(), zod.string(), zod.null()]),- type: zod.string(),- })- .optional(),- external_issues: zod- .array(+export const ErrorTrackingIssuesAssignPartialUpdateBody = /* @__PURE__ */ zod+ .object({+ id: zod.uuid().optional(),+ status: zod.string().optional(),+ name: zod.string().nullish(),+ description: zod.string().nullish(),+ first_seen: zod.iso.datetime({ offset: true }).nullish(),+ assignee: zod+ .union([+ zod.object({+ id: zod.union([zod.number(), zod.string(), zod.null()]),+ type: zod.string(),+ }),+ zod.null(),+ ])+ .optional(),+ external_issues: zod+ .array(+ zod.object({+ id: zod.uuid(),+ integration: zod.object({+ id: zod.number(),+ kind: zod.string(),+ display_name: zod.string(),+ }),+ integration_id: zod.number(),+ config: zod.unknown(),+ issue: zod.uuid(),+ external_url: zod.string(),+ })+ )+ .optional(),+ cohort: zod+ .union([+ zod.object({+ id: zod.number(),+ name: zod.string(),+ }),+ zod.null(),+ ])+ .optional(),+ })+ .describe('Read-only serializer for issue contract types returned by the facade.')++export const ErrorTrackingIssuesCohortUpdateBody = /* @__PURE__ */ zod+ .object({+ id: zod.uuid(),+ status: zod.string(),+ name: zod.string().nullable(),+ description: zod.string().nullable(),+ first_seen: zod.iso.datetime({ offset: true }).nullable(),+ assignee: zod.union([+ zod.object({+ id: zod.union([zod.number(), zod.string(), zod.null()]),+ type: zod.string(),+ }),+ zod.null(),+ ]),+ external_issues: zod.array(zod.object({id: zod.uuid(),integration: zod.object({@@ -246,39 +257,16 @@ export const ErrorTrackingIssuesAssignPartialUpdateBody = /* @__PURE__ */ zod.obissue: zod.uuid(),external_url: zod.string(),})- )- .optional(),-})--export const ErrorTrackingIssuesCohortUpdateBody = /* @__PURE__ */ zod.object({- status: zod- .enum(['archived', 'active', 'resolved', 'pending_release', 'suppressed'])- .optional()- .describe(- '\* `archived` - Archived\n\* `active` - Active\n\* `resolved` - Resolved\n\* `pending_release` - Pending release\n\* `suppressed` - Suppressed'),- name: zod.string().nullish(),- description: zod.string().nullish(),- first_seen: zod.iso.datetime({ offset: true }),- assignee: zod.object({- id: zod.union([zod.number(), zod.string(), zod.null()]),- type: zod.string(),- }),- external_issues: zod.array(- zod.object({- id: zod.uuid(),- integration: zod.object({+ cohort: zod.union([+ zod.object({id: zod.number(),- kind: zod.string(),- display_name: zod.string(),+ name: zod.string(),}),- integration_id: zod.number(),- config: zod.unknown(),- issue: zod.uuid(),- external_url: zod.string(),- })- ),-})+ zod.null(),+ ]),+ })+ .describe('Read-only serializer for issue contract types returned by the facade.')export const ErrorTrackingIssuesMergeCreateBody = /* @__PURE__ */ zod.object({ids: zod.array(zod.uuid()).describe('IDs of the issues to merge into the current issue.'),@@ -303,35 +291,43 @@ export const ErrorTrackingIssuesSplitCreateBody = /* @__PURE__ */ zod.object({.describe('Fingerprints to split into new issues. Each fingerprint becomes its own new issue.'),})-export const ErrorTrackingIssuesBulkCreateBody = /* @__PURE__ */ zod.object({- status: zod- .enum(['archived', 'active', 'resolved', 'pending_release', 'suppressed'])- .optional()- .describe(- '\* `archived` - Archived\n\* `active` - Active\n\* `resolved` - Resolved\n\* `pending_release` - Pending release\n\* `suppressed` - Suppressed'+export const ErrorTrackingIssuesBulkCreateBody = /* @__PURE__ */ zod+ .object({+ id: zod.uuid(),+ status: zod.string(),+ name: zod.string().nullable(),+ description: zod.string().nullable(),+ first_seen: zod.iso.datetime({ offset: true }).nullable(),+ assignee: zod.union([+ zod.object({+ id: zod.union([zod.number(), zod.string(), zod.null()]),+ type: zod.string(),+ }),+ zod.null(),+ ]),+ external_issues: zod.array(+ zod.object({+ id: zod.uuid(),+ integration: zod.object({+ id: zod.number(),+ kind: zod.string(),+ display_name: zod.string(),+ }),+ integration_id: zod.number(),+ config: zod.unknown(),+ issue: zod.uuid(),+ external_url: zod.string(),+ })),- name: zod.string().nullish(),- description: zod.string().nullish(),- first_seen: zod.iso.datetime({ offset: true }),- assignee: zod.object({- id: zod.union([zod.number(), zod.string(), zod.null()]),- type: zod.string(),- }),- external_issues: zod.array(- zod.object({- id: zod.uuid(),- integration: zod.object({+ cohort: zod.union([+ zod.object({id: zod.number(),- kind: zod.string(),- display_name: zod.string(),+ name: zod.string(),}),- integration_id: zod.number(),- config: zod.unknown(),- issue: zod.uuid(),- external_url: zod.string(),- })- ),-})+ zod.null(),+ ]),+ })+ .describe('Read-only serializer for issue contract types returned by the facade.')/*** Fetch one error tracking issue with impact counts, top in_app frame, latest release, and optional sparkline.diff --git a/products/error_tracking/mcp/tools.yaml b/products/error_tracking/mcp/tools.yamlindex 6836023ceec8..4dc2d7ad2ba1 100644--- a/products/error_tracking/mcp/tools.yaml+++ b/products/error_tracking/mcp/tools.yaml@@ -154,9 +154,6 @@ tools:error-tracking-issues-cohort-update:operation: error_tracking_issues_cohort_updateenabled: false- error-tracking-issues-create:- operation: error_tracking_issues_create- enabled: falseerror-tracking-issues-destroy:operation: error_tracking_issues_destroyenabled: falsediff --git a/pyproject.toml b/pyproject.tomlindex 2dff60f4a8e3..9b3d39d57e12 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -532,20 +532,6 @@ ignore_imports = ["products.user_interviews.backend.presentation.views -> products.user_interviews.backend.models","products.user_interviews.backend.presentation.views -> products.user_interviews.backend.invite_email","products.user_interviews.backend.presentation.webhooks -> products.user_interviews.backend.models",- # 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.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",- "products.error_tracking.backend.presentation.views.issues -> products.error_tracking.backend.notifications",- "products.error_tracking.backend.presentation.views.query -> products.error_tracking.backend.hogql_queries.error_tracking_query_runner",- "products.error_tracking.backend.presentation.views.query -> products.error_tracking.backend.models",- "products.error_tracking.backend.presentation.views.recommendations -> products.error_tracking.backend.logic.recommendations",- "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.symbol_sets -> products.error_tracking.backend.models",# 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 3d7f21768ca6..85cc135d6a92 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -18712,9 +18712,14 @@ export namespace Schemas {sessions?: number;}- export interface ErrorTrackingIssueAssignment {+ export interface ErrorTrackingIssueAssigneeRead {readonly id: number | string | null;- readonly type: string;+ type: string;+ }++ export interface ErrorTrackingIssueCohortRead {+ id: number;+ name: string;}export interface ErrorTrackingTopFrame {@@ -18930,46 +18935,6 @@ export namespace Schemas {nextOffset?: number;}- /**- * @nullable- */- export type ErrorTrackingIssueFullCohort = {- readonly id?: number;- readonly name?: string;- } | null;-- /**- * * `archived` - Archived- * * `active` - Active- * * `resolved` - Resolved- * * `pending_release` - Pending release- * * `suppressed` - Suppressed- */- export type ErrorTrackingIssueFullStatusEnum = typeof ErrorTrackingIssueFullStatusEnum[keyof typeof ErrorTrackingIssueFullStatusEnum];--- export const ErrorTrackingIssueFullStatusEnum = {- Archived: 'archived',- Active: 'active',- Resolved: 'resolved',- PendingRelease: 'pending_release',- Suppressed: 'suppressed',- } as const;-- export interface ErrorTrackingIssueFull {- readonly id: string;- status?: ErrorTrackingIssueFullStatusEnum;- /** @nullable */- name?: string | null;- /** @nullable */- description?: string | null;- first_seen: string;- assignee: ErrorTrackingIssueAssignment;- external_issues: ErrorTrackingExternalReferenceResult[];- /** @nullable */- readonly cohort: ErrorTrackingIssueFullCohort;- }-export interface ErrorTrackingIssueListItem {/** Error tracking issue ID. */id: string;@@ -19056,6 +19021,23 @@ export namespace Schemas {includeSparkline?: boolean;}+ /**+ * Read-only serializer for issue contract types returned by the facade.+ */+ export interface ErrorTrackingIssueRead {+ id: string;+ status: string;+ /** @nullable */+ name: string | null;+ /** @nullable */+ description: string | null;+ /** @nullable */+ first_seen: string | null;+ assignee: ErrorTrackingIssueAssigneeRead | null;+ external_issues: ErrorTrackingExternalReferenceResult[];+ cohort: ErrorTrackingIssueCohortRead | null;+ }+export interface ErrorTrackingIssueSplitFingerprint {/** Fingerprint to split into a new issue. */fingerprint: string;@@ -19253,51 +19235,31 @@ export namespace Schemas {ErrorTrackingList: 'error_tracking_list',} as const;- /**- * Recommendation payload, shape depends on type.- */- export type ErrorTrackingRecommendationMeta = { [key: string]: unknown };-- /**- * * `ready` - Ready- * * `computing` - Computing- */- export type ErrorTrackingRecommendationStatusEnum = typeof ErrorTrackingRecommendationStatusEnum[keyof typeof ErrorTrackingRecommendationStatusEnum];--- export const ErrorTrackingRecommendationStatusEnum = {- Ready: 'ready',- Computing: 'computing',- } as const;-export interface ErrorTrackingRecommendation {/** Recommendation UUID. */- readonly id: string;+ id: string;/** Recommendation type identifier (e.g. 'alerts'). */- readonly type: string;+ type: string;/** Recommendation payload, shape depends on type. */- readonly meta: ErrorTrackingRecommendationMeta;+ meta: unknown;/** Whether the recommendation's recommended action has been satisfied. */- readonly completed: boolean;- /** 'ready' if meta is fresh, 'computing' if a refresh is in progress.- *- * * `ready` - Ready- * * `computing` - Computing */- readonly status: ErrorTrackingRecommendationStatusEnum;+ completed: boolean;+ /** 'ready' if meta is fresh, 'computing' if a refresh is in progress. */+ status: string;/*** Timestamp meta was last successfully computed.* @nullable*/- readonly computed_at: string | null;+ computed_at: string | null;/*** Timestamp the user dismissed this recommendation, if any.* @nullable*/- readonly dismissed_at: string | null;+ dismissed_at: string | null;/** Timestamp the recommendation row was first created. */- readonly created_at: string;+ created_at: string;/** Timestamp the recommendation row was last updated. */- readonly updated_at: string;+ updated_at: string;}/**@@ -19548,38 +19510,17 @@ export namespace Schemas {sampling_rate?: number;}- /**- * Release associated with this symbol set, if any.- * @nullable- */- export type ErrorTrackingSymbolSetRelease = { [key: string]: unknown } | null;-export interface ErrorTrackingSymbolSet {- /** Unique symbol set ID. */- readonly id: string;- /** Reference used to match stack frames to this symbol set. */- readonly ref: string;- /** Project/team ID that owns this symbol set. */- readonly team_id: number;- /** When this symbol set row was created. */- readonly created_at: string;- /**- * When this symbol set was last used to resolve a stack frame.- * @nullable- */- readonly last_used: string | null;- /**- * Reason symbol lookup failed, if the source map is missing or invalid.- * @nullable- */- readonly failure_reason: string | null;- /** Whether this symbol set has an uploaded source map file available to download. */- readonly has_uploaded_file: boolean;- /**- * Release associated with this symbol set, if any.- * @nullable- */- readonly release: ErrorTrackingSymbolSetRelease;+ id: string;+ ref: string;+ team_id: number;+ created_at: string;+ /** @nullable */+ last_used: string | null;+ /** @nullable */+ failure_reason: string | null;+ has_uploaded_file: boolean;+ release: ErrorTrackingRelease | null;}export interface ErrorTrackingSymbolSetBulkDelete {@@ -29780,13 +29721,13 @@ export namespace Schemas {results: ErrorTrackingFingerprint[];}- export interface PaginatedErrorTrackingIssueFullList {+ export interface PaginatedErrorTrackingIssueReadList {count: number;/** @nullable */next?: string | null;/** @nullable */previous?: string | null;- results: ErrorTrackingIssueFull[];+ results: ErrorTrackingIssueRead[];}export interface PaginatedErrorTrackingRecommendationList {@@ -35238,25 +35179,20 @@ export namespace Schemas {}/**- * @nullable+ * Read-only serializer for issue contract types returned by the facade.*/- export type PatchedErrorTrackingIssueFullCohort = {- readonly id?: number;- readonly name?: string;- } | null;-- export interface PatchedErrorTrackingIssueFull {- readonly id?: string;- status?: ErrorTrackingIssueFullStatusEnum;+ export interface PatchedErrorTrackingIssueRead {+ id?: string;+ status?: string;/** @nullable */name?: string | null;/** @nullable */description?: string | null;- first_seen?: string;- assignee?: ErrorTrackingIssueAssignment;- external_issues?: ErrorTrackingExternalReferenceResult[];/** @nullable */- readonly cohort?: PatchedErrorTrackingIssueFullCohort;+ first_seen?: string | null;+ assignee?: ErrorTrackingIssueAssigneeRead | null;+ external_issues?: ErrorTrackingExternalReferenceResult[];+ cohort?: ErrorTrackingIssueCohortRead | null;}export interface PatchedErrorTrackingIssueWrite {diff --git a/services/mcp/src/generated/error_tracking/api.ts b/services/mcp/src/generated/error_tracking/api.tsindex 779f4d0a8e65..b9ce0409e653 100644--- a/services/mcp/src/generated/error_tracking/api.ts+++ b/services/mcp/src/generated/error_tracking/api.ts@@ -2984,7 +2984,7 @@ export const ErrorTrackingGroupingRulesUpdateBody = /* @__PURE__ */ zod.object({})export const ErrorTrackingIssuesPartialUpdateParams = /* @__PURE__ */ zod.object({- id: zod.string().describe('A UUID string identifying this error tracking issue.'),+ id: zod.string(),project_id: zod.string().describe(@@ -3005,7 +3005,7 @@ export const ErrorTrackingIssuesPartialUpdateBody = /* @__PURE__ */ zod.object({})export const ErrorTrackingIssuesMergeCreateParams = /* @__PURE__ */ zod.object({- id: zod.string().describe('A UUID string identifying this error tracking issue.'),+ id: zod.string(),project_id: zod.string().describe(@@ -3018,7 +3018,7 @@ export const ErrorTrackingIssuesMergeCreateBody = /* @__PURE__ */ zod.object({})export const ErrorTrackingIssuesSplitCreateParams = /* @__PURE__ */ zod.object({- id: zod.string().describe('A UUID string identifying this error tracking issue.'),+ id: zod.string(),project_id: zod.string().describe(@@ -5570,7 +5570,7 @@ export const ErrorTrackingSymbolSetsListQueryParams = /* @__PURE__ */ zod.object})export const ErrorTrackingSymbolSetsRetrieveParams = /* @__PURE__ */ zod.object({- id: zod.string().describe('A UUID string identifying this error tracking symbol set.'),+ id: zod.string(),project_id: zod.string().describe(@@ -5582,7 +5582,7 @@ export const ErrorTrackingSymbolSetsRetrieveParams = /* @__PURE__ */ zod.object(* Return a presigned URL for downloading the symbol set's source map.*/export const ErrorTrackingSymbolSetsDownloadRetrieveParams = /* @__PURE__ */ zod.object({- id: zod.string().describe('A UUID string identifying this error tracking symbol set.'),+ id: zod.string(),project_id: zod.string().describe(diff --git a/services/mcp/src/tools/generated/error_tracking.ts b/services/mcp/src/tools/generated/error_tracking.tsindex 581007392d11..8ff2bca9efa5 100644--- a/services/mcp/src/tools/generated/error_tracking.ts+++ b/services/mcp/src/tools/generated/error_tracking.ts@@ -180,7 +180,7 @@ const ErrorTrackingIssuesPartialUpdateSchema = ErrorTrackingIssuesPartialUpdatePconst errorTrackingIssuesPartialUpdate = (): ToolBase<typeof ErrorTrackingIssuesPartialUpdateSchema,- WithPostHogUrl<Schemas.ErrorTrackingIssueFull>+ WithPostHogUrl<Schemas.ErrorTrackingIssueRead>> =>withUiApp('error-issue', {name: 'error-tracking-issues-partial-update',@@ -197,7 +197,7 @@ const errorTrackingIssuesPartialUpdate = (): ToolBase<if (params.description !== undefined) {body['description'] = params.description}- const result = await context.api.request<Schemas.ErrorTrackingIssueFull>({+ const result = await context.api.request<Schemas.ErrorTrackingIssueRead>({method: 'PATCH',path: `/api/projects/${encodeURIComponent(String(projectId))}/error_tracking/issues/${encodeURIComponent(String(params.id))}/`,body,diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/error-tracking-issues-merge-create.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/error-tracking-issues-merge-create.jsonindex 2a348ba10d39..52e1529903f8 100644--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/error-tracking-issues-merge-create.json+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/error-tracking-issues-merge-create.json@@ -2,7 +2,6 @@"$schema": "https://json-schema.org/draft/2020-12/schema","properties": {"id": {- "description": "A UUID string identifying this error tracking issue.","type": "string"},"ids": {diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/error-tracking-issues-partial-update.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/error-tracking-issues-partial-update.jsonindex 058204176695..1d623256733c 100644--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/error-tracking-issues-partial-update.json+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/error-tracking-issues-partial-update.json@@ -13,7 +13,6 @@"description": "Optional issue description."},"id": {- "description": "A UUID string identifying this error tracking issue.","type": "string"},"name": {diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/error-tracking-issues-split-create.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/error-tracking-issues-split-create.jsonindex 1ce2e5c3ab0b..8c10b5ab8364 100644--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/error-tracking-issues-split-create.json+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/error-tracking-issues-split-create.json@@ -24,7 +24,6 @@"type": "array"},"id": {- "description": "A UUID string identifying this error tracking issue.","type": "string"}},diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/error-tracking-symbol-sets-download-retrieve.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/error-tracking-symbol-sets-download-retrieve.jsonindex 2141e0070472..f9bfd8020ef3 100644--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/error-tracking-symbol-sets-download-retrieve.json+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/error-tracking-symbol-sets-download-retrieve.json@@ -2,7 +2,6 @@"$schema": "https://json-schema.org/draft/2020-12/schema","properties": {"id": {- "description": "A UUID string identifying this error tracking symbol set.","type": "string"}},diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/error-tracking-symbol-sets-retrieve.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/error-tracking-symbol-sets-retrieve.jsonindex 2141e0070472..f9bfd8020ef3 100644--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/error-tracking-symbol-sets-retrieve.json+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/error-tracking-symbol-sets-retrieve.json@@ -2,7 +2,6 @@"$schema": "https://json-schema.org/draft/2020-12/schema","properties": {"id": {- "description": "A UUID string identifying this error tracking symbol set.","type": "string"}},