Skip to content

: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.

feat(error-tracking): add the issue change log model (#112807)

Hugues Pouillotc0279517345e
diff --git a/.semgrep/rules/security/idor-team-scoped-models.yaml b/.semgrep/rules/security/idor-team-scoped-models.yaml
index 2d6243378695..8deca3e24070 100644
--- a/.semgrep/rules/security/idor-team-scoped-models.yaml
+++ b/.semgrep/rules/security/idor-team-scoped-models.yaml
@@ -185,6 +185,7 @@ rules:
|ErrorTrackingBypassRule
|ErrorTrackingGroupingRule
|ErrorTrackingIssue
+ |ErrorTrackingIssueChange
|ErrorTrackingIssueFingerprintV2
|ErrorTrackingRelease
|ErrorTrackingRecommendation
@@ -633,6 +634,7 @@ rules:
|ErrorTrackingBypassRule
|ErrorTrackingGroupingRule
|ErrorTrackingIssue
+ |ErrorTrackingIssueChange
|ErrorTrackingIssueFingerprintV2
|ErrorTrackingRelease
|ErrorTrackingRecommendation
diff --git a/products/error_tracking/backend/logic/issue_changes.py b/products/error_tracking/backend/logic/issue_changes.py
new file mode 100644
index 000000000000..3ca61b582886
--- /dev/null
+++ b/products/error_tracking/backend/logic/issue_changes.py
@@ -0,0 +1,197 @@
+"""Typed contents of issue change rows: the snapshot and the per-kind data payload.
+
+Values are raw model values, not display labels: consumers that render messages
+map them to labels themselves. Cymbal writes the same JSON shapes from Rust, and
+tests/fixtures/issue_change_data.json pins them for both sides.
+"""
+
+from datetime import datetime
+from typing import Any, ClassVar, Literal
+from uuid import UUID
+
+from posthog.dataclasses import frozen
+
+from products.error_tracking.backend.models import (
+ ErrorTrackingIssue,
+ ErrorTrackingIssueAssignment,
+ ErrorTrackingIssueChange,
+)
+
+Kind = ErrorTrackingIssueChange.Kind
+Status = ErrorTrackingIssue.Status
+Severity = ErrorTrackingIssue.Severity
+
+# Same cap the alert delivery inputs apply, so a long exception message cannot bloat every row.
+MAX_ISSUE_NAME_LENGTH = 500
+
+
+def _truncate_name(name: str | None) -> str | None:
+ return name[:MAX_ISSUE_NAME_LENGTH] if name else name
+
+
+@frozen
+class AssigneeRef:
+ type: Literal["user", "role"]
+ id: str
+
+ @classmethod
+ def from_assignment(cls, assignment: ErrorTrackingIssueAssignment | None) -> "AssigneeRef | None":
+ if assignment is None:
+ return None
+ if assignment.user_id is not None:
+ return cls(type="user", id=str(assignment.user_id))
+ if assignment.role_id is not None:
+ return cls(type="role", id=str(assignment.role_id))
+ return None
+
+ @classmethod
+ def from_json(cls, value: dict[str, Any] | None) -> "AssigneeRef | None":
+ if value is None:
+ return None
+ if value["type"] not in ("user", "role"):
+ raise ValueError(f"Unknown assignee type: {value['type']}")
+ return cls(type=value["type"], id=str(value["id"]))
+
+ def to_json(self) -> dict[str, str]:
+ return {"type": self.type, "id": self.id}
+
+
+@frozen
+class IssueSnapshot:
+ status: Status
+ severity: Severity | None
+ name: str | None
+ assignee: AssigneeRef | None
+ first_seen: datetime
+
+ @classmethod
+ def build(
+ cls, issue: ErrorTrackingIssue, *, assignee: AssigneeRef | None, first_seen: datetime | None
+ ) -> "IssueSnapshot":
+ """Build the snapshot after a change.
+
+ The caller loads the assignee and the earliest fingerprint `first_seen`
+ (`ErrorTrackingIssue.objects.with_first_seen()`), so a bulk change needs one query
+ for each instead of one per issue. After a merge, the earliest fingerprint can
+ predate the issue row, so `created_at` is only the fallback.
+ """
+ return cls(
+ status=Status(issue.status),
+ severity=Severity(issue.severity) if issue.severity else None,
+ name=_truncate_name(issue.name),
+ assignee=assignee,
+ first_seen=first_seen or issue.created_at,
+ )
+
+ def to_json(self) -> dict[str, Any]:
+ return {
+ "status": str(self.status),
+ "severity": str(self.severity) if self.severity else None,
+ "name": self.name,
+ "assignee": self.assignee.to_json() if self.assignee else None,
+ "first_seen": self.first_seen.isoformat(),
+ }
+
+
+@frozen
+class Created:
+ kind: ClassVar[Kind] = Kind.CREATED
+
+ def to_data(self) -> dict[str, Any]:
+ return {}
+
+
+@frozen
+class StatusChanged:
+ kind: ClassVar[Kind] = Kind.STATUS_CHANGED
+ previous: Status
+
+ def to_data(self) -> dict[str, Any]:
+ return {"previous": str(self.previous)}
+
+
+@frozen
+class AssigneeChanged:
+ kind: ClassVar[Kind] = Kind.ASSIGNEE_CHANGED
+ previous: AssigneeRef | None
+
+ def to_data(self) -> dict[str, Any]:
+ return {"previous": self.previous.to_json() if self.previous else None}
+
+
+@frozen
+class SeverityChanged:
+ kind: ClassVar[Kind] = Kind.SEVERITY_CHANGED
+ previous: Severity | None
+
+ def to_data(self) -> dict[str, Any]:
+ return {"previous": str(self.previous) if self.previous else None}
+
+
+@frozen
+class NameChanged:
+ kind: ClassVar[Kind] = Kind.NAME_CHANGED
+ previous: str | None
+
+ def to_data(self) -> dict[str, Any]:
+ return {"previous": _truncate_name(self.previous)}
+
+
+@frozen
+class Merged:
+ """Written on the target issue. The merged issues are deleted, so they get no row."""
+
+ kind: ClassVar[Kind] = Kind.MERGED
+ merged_issue_ids: tuple[UUID, ...]
+
+ def to_data(self) -> dict[str, Any]:
+ return {"merged_issue_ids": [str(issue_id) for issue_id in self.merged_issue_ids]}
+
+
+@frozen
+class Split:
+ """Written on the original issue. Each new issue also gets a `created` row."""
+
+ kind: ClassVar[Kind] = Kind.SPLIT
+ new_issue_ids: tuple[UUID, ...]
+
+ def to_data(self) -> dict[str, Any]:
+ return {"new_issue_ids": [str(issue_id) for issue_id in self.new_issue_ids]}
+
+
+@frozen
+class Spiking:
+ kind: ClassVar[Kind] = Kind.SPIKING
+ computed_baseline: float
+ current_bucket_value: int
+
+ def to_data(self) -> dict[str, Any]:
+ return {"computed_baseline": self.computed_baseline, "current_bucket_value": self.current_bucket_value}
+
+
+IssueChangeData = Created | StatusChanged | AssigneeChanged | SeverityChanged | NameChanged | Merged | Split | Spiking
+
+
+def parse_change_data(kind: str, data: dict[str, Any]) -> IssueChangeData:
+ match Kind(kind):
+ case Kind.CREATED:
+ return Created()
+ case Kind.STATUS_CHANGED:
+ return StatusChanged(previous=Status(data["previous"]))
+ case Kind.ASSIGNEE_CHANGED:
+ return AssigneeChanged(previous=AssigneeRef.from_json(data["previous"]))
+ case Kind.SEVERITY_CHANGED:
+ return SeverityChanged(previous=Severity(data["previous"]) if data["previous"] else None)
+ case Kind.NAME_CHANGED:
+ return NameChanged(previous=data["previous"])
+ case Kind.MERGED:
+ return Merged(merged_issue_ids=tuple(UUID(issue_id) for issue_id in data["merged_issue_ids"]))
+ case Kind.SPLIT:
+ return Split(new_issue_ids=tuple(UUID(issue_id) for issue_id in data["new_issue_ids"]))
+ case Kind.SPIKING:
+ return Spiking(
+ computed_baseline=float(data["computed_baseline"]),
+ current_bucket_value=int(data["current_bucket_value"]),
+ )
+ # Unreachable while every kind has a case above. It turns a kind added without one into an error.
+ raise ValueError(f"Unhandled issue change kind: {kind}")
diff --git a/products/error_tracking/backend/migrations/0042_errortrackingissuechange.py b/products/error_tracking/backend/migrations/0042_errortrackingissuechange.py
new file mode 100644
index 000000000000..28c7ec742397
--- /dev/null
+++ b/products/error_tracking/backend/migrations/0042_errortrackingissuechange.py
@@ -0,0 +1,126 @@
+# Generated by Django 5.2.17 on 2026-10-06 17:47
+
+import django.db.models.deletion
+import django.db.models.functions.datetime
+from django.db import migrations, models
+
+import posthog.uuidt
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ (
+ "error_tracking",
+ "0041_errortrackingalertdestination_consecutive_failures_and_more",
+ ),
+ ("posthog", "1392_organization_member_notice"),
+ ]
+
+ operations = [
+ migrations.CreateModel(
+ name="ErrorTrackingIssueChange",
+ fields=[
+ (
+ "id",
+ models.UUIDField(
+ default=posthog.uuidt.uuid7,
+ editable=False,
+ primary_key=True,
+ serialize=False,
+ ),
+ ),
+ ("issue_id", models.UUIDField()),
+ (
+ "kind",
+ models.TextField(
+ choices=[
+ ("created", "Created"),
+ ("status_changed", "Status changed"),
+ ("assignee_changed", "Assignee changed"),
+ ("severity_changed", "Severity changed"),
+ ("name_changed", "Name changed"),
+ ("merged", "Merged"),
+ ("split", "Split"),
+ ("spiking", "Spiking"),
+ ]
+ ),
+ ),
+ ("data", models.JSONField(db_default={}, default=dict)),
+ ("snapshot", models.JSONField(db_default={}, default=dict)),
+ ("operation_id", models.UUIDField()),
+ ("bulk", models.BooleanField(db_default=False, default=False)),
+ (
+ "actor_type",
+ models.TextField(
+ choices=[
+ ("ingestion", "Ingestion"),
+ ("user", "User"),
+ ("automation", "Automation"),
+ ]
+ ),
+ ),
+ ("actor_user_id", models.IntegerField(blank=True, null=True)),
+ ("actor_automation_id", models.UUIDField(blank=True, null=True)),
+ ("causation_id", models.UUIDField(blank=True, null=True)),
+ ("depth", models.PositiveSmallIntegerField(db_default=0, default=0)),
+ ("event_uuid", models.UUIDField(blank=True, null=True)),
+ ("event_timestamp", models.DateTimeField(blank=True, null=True)),
+ (
+ "created_at",
+ models.DateTimeField(
+ auto_now_add=True,
+ db_default=django.db.models.functions.datetime.Now(),
+ ),
+ ),
+ ("dispatched_at", models.DateTimeField(blank=True, null=True)),
+ (
+ "team",
+ models.ForeignKey(
+ db_constraint=False,
+ db_index=False,
+ on_delete=django.db.models.deletion.CASCADE,
+ related_name="+",
+ to="posthog.team",
+ ),
+ ),
+ ],
+ options={
+ "db_table": "posthog_errortrackingissuechange",
+ "indexes": [
+ models.Index(
+ condition=models.Q(("dispatched_at__isnull", True)),
+ fields=["created_at"],
+ name="idx_et_issue_change_pending",
+ ),
+ models.Index(
+ fields=["team", "issue_id", "created_at"],
+ name="idx_et_issue_change_issue",
+ ),
+ models.Index(fields=["created_at"], name="idx_et_issue_change_created"),
+ ],
+ "constraints": [
+ models.CheckConstraint(
+ condition=models.Q(
+ models.Q(
+ ("actor_automation_id__isnull", True),
+ ("actor_type", "ingestion"),
+ ("actor_user_id__isnull", True),
+ ),
+ models.Q(
+ ("actor_automation_id__isnull", True),
+ ("actor_type", "user"),
+ ("actor_user_id__isnull", False),
+ ),
+ models.Q(
+ ("actor_automation_id__isnull", False),
+ ("actor_type", "automation"),
+ ("actor_user_id__isnull", True),
+ ),
+ _connector="OR",
+ ),
+ name="et_issue_change_actor_matches_type",
+ )
+ ],
+ },
+ ),
+ ]
diff --git a/products/error_tracking/backend/migrations/max_migration.txt b/products/error_tracking/backend/migrations/max_migration.txt
index 04b711453104..2b8017f52962 100644
--- a/products/error_tracking/backend/migrations/max_migration.txt
+++ b/products/error_tracking/backend/migrations/max_migration.txt
@@ -1 +1 @@
-0041_errortrackingalertdestination_consecutive_failures_and_more
+0042_errortrackingissuechange
diff --git a/products/error_tracking/backend/models.py b/products/error_tracking/backend/models.py
index 561fda9d8b3f..407117058622 100644
--- a/products/error_tracking/backend/models.py
+++ b/products/error_tracking/backend/models.py
@@ -9,6 +9,7 @@ from django.conf import settings
from django.contrib.postgres.fields import ArrayField
from django.core.validators import MaxValueValidator, MinValueValidator
from django.db import models, transaction
+from django.db.models.functions import Now
from django.utils import timezone
import structlog
@@ -1084,3 +1085,87 @@ class ErrorTrackingAlertThread(TeamScopedRootMixin, UUIDTModel):
fields=["alert", "issue", "destination"], name="unique_error_tracking_alert_thread"
),
]
+
+
+class ErrorTrackingIssueChange(TeamScopedRootMixin, UUIDModel):
+ """One change to an issue, written in the same transaction as the change itself.
+
+ Rows are an outbox: a dispatcher claims rows where `dispatched_at` is null and
+ fans them out to alerts and automations, so a change that commits is never lost.
+ The row id is also the notification id, so delivery retries stay idempotent per change.
+
+ `snapshot` holds the watched issue fields after the change, so consumers never read
+ the issue row, which can change again or be merged away before dispatch. `data`
+ holds only what the snapshot cannot: its shape depends on `kind` and is defined by
+ the payload types in logic/issue_changes.py.
+ """
+
+ class Kind(models.TextChoices):
+ CREATED = "created", "Created"
+ STATUS_CHANGED = "status_changed", "Status changed"
+ ASSIGNEE_CHANGED = "assignee_changed", "Assignee changed"
+ SEVERITY_CHANGED = "severity_changed", "Severity changed"
+ NAME_CHANGED = "name_changed", "Name changed"
+ MERGED = "merged", "Merged"
+ SPLIT = "split", "Split"
+ # An observation, not a change: nothing on the issue changes. It is here because
+ # spike alerts open notification threads like the changes above.
+ SPIKING = "spiking", "Spiking"
+
+ class ActorType(models.TextChoices):
+ INGESTION = "ingestion", "Ingestion"
+ USER = "user", "User"
+ AUTOMATION = "automation", "Automation"
+
+ # db_constraint=False keeps inserts lock-free on posthog_team (a hot table);
+ # team scoping is enforced at the ORM layer via TeamScopedRootMixin.
+ # idx_et_issue_change_issue leads with team, so the default foreign key index is redundant.
+ team = models.ForeignKey(
+ "posthog.Team", on_delete=models.CASCADE, related_name="+", db_constraint=False, db_index=False
+ )
+ # Not a foreign key: the history of a merged issue must outlive the issue row.
+ issue_id = models.UUIDField()
+ kind = models.TextField(choices=Kind)
+ data = models.JSONField(default=dict, db_default={})
+ snapshot = models.JSONField(default=dict, db_default={})
+ # One id per user action, ingestion transaction or automation run. Rows of one
+ # operation are delivered together, e.g. a resolve and an assign in one request.
+ operation_id = models.UUIDField()
+ bulk = models.BooleanField(default=False, db_default=False)
+ actor_type = models.TextField(choices=ActorType)
+ # Plain ids, not foreign keys: the history must outlive deleted users and automations.
+ actor_user_id = models.IntegerField(null=True, blank=True)
+ actor_automation_id = models.UUIDField(null=True, blank=True)
+ # The change that caused this one, when an automation reacts to an earlier change.
+ causation_id = models.UUIDField(null=True, blank=True)
+ # Length of the automation chain that led here. Dispatch stops chains past a limit.
+ depth = models.PositiveSmallIntegerField(default=0, db_default=0)
+ # Reference to the exception that caused an ingestion change. The event itself stays in ClickHouse.
+ event_uuid = models.UUIDField(null=True, blank=True)
+ event_timestamp = models.DateTimeField(null=True, blank=True)
+ created_at = models.DateTimeField(auto_now_add=True, db_default=Now())
+ dispatched_at = models.DateTimeField(null=True, blank=True)
+
+ class Meta:
+ db_table = "posthog_errortrackingissuechange"
+ constraints = [
+ models.CheckConstraint(
+ condition=(
+ models.Q(actor_type="ingestion", actor_user_id__isnull=True, actor_automation_id__isnull=True)
+ | models.Q(actor_type="user", actor_user_id__isnull=False, actor_automation_id__isnull=True)
+ | models.Q(actor_type="automation", actor_user_id__isnull=True, actor_automation_id__isnull=False)
+ ),
+ name="et_issue_change_actor_matches_type",
+ ),
+ ]
+ indexes = [
+ # Outbox claim. Stays small because rows are dispatched within seconds.
+ models.Index(
+ fields=["created_at"],
+ name="idx_et_issue_change_pending",
+ condition=models.Q(dispatched_at__isnull=True),
+ ),
+ models.Index(fields=["team", "issue_id", "created_at"], name="idx_et_issue_change_issue"),
+ # Retention cleanup.
+ models.Index(fields=["created_at"], name="idx_et_issue_change_created"),
+ ]
diff --git a/products/error_tracking/backend/tests/fixtures/issue_change_data.json b/products/error_tracking/backend/tests/fixtures/issue_change_data.json
new file mode 100644
index 000000000000..09c0c985fc4c
--- /dev/null
+++ b/products/error_tracking/backend/tests/fixtures/issue_change_data.json
@@ -0,0 +1,13 @@
+[
+ { "kind": "created", "data": {} },
+ { "kind": "status_changed", "data": { "previous": "resolved" } },
+ { "kind": "assignee_changed", "data": { "previous": { "type": "user", "id": "42" } } },
+ { "kind": "assignee_changed", "data": { "previous": { "type": "role", "id": "0190a1b2-c3d4-7000-8000-000000000001" } } },
+ { "kind": "assignee_changed", "data": { "previous": null } },
+ { "kind": "severity_changed", "data": { "previous": "high" } },
+ { "kind": "severity_changed", "data": { "previous": null } },
+ { "kind": "name_changed", "data": { "previous": "TypeError: x is undefined" } },
+ { "kind": "merged", "data": { "merged_issue_ids": ["0190a1b2-c3d4-7000-8000-000000000002", "0190a1b2-c3d4-7000-8000-000000000003"] } },
+ { "kind": "split", "data": { "new_issue_ids": ["0190a1b2-c3d4-7000-8000-000000000004"] } },
+ { "kind": "spiking", "data": { "computed_baseline": 12.5, "current_bucket_value": 140 } }
+]
diff --git a/products/error_tracking/backend/tests/test_issue_changes.py b/products/error_tracking/backend/tests/test_issue_changes.py
new file mode 100644
index 000000000000..22b16cf822c5
--- /dev/null
+++ b/products/error_tracking/backend/tests/test_issue_changes.py
@@ -0,0 +1,84 @@
+import json
+import uuid
+from datetime import UTC, datetime
+from pathlib import Path
+
+from django.test import SimpleTestCase
+
+from parameterized import parameterized
+
+from products.error_tracking.backend.logic.issue_changes import (
+ MAX_ISSUE_NAME_LENGTH,
+ AssigneeRef,
+ IssueSnapshot,
+ parse_change_data,
+)
+from products.error_tracking.backend.models import (
+ ErrorTrackingIssue,
+ ErrorTrackingIssueAssignment,
+ ErrorTrackingIssueChange,
+)
+
+ROLE_ID = uuid.UUID("0190a1b2-c3d4-7000-8000-000000000001")
+FIRST_SEEN = datetime(2026, 1, 2, 3, 4, 5, tzinfo=UTC)
+ISSUE_CREATED_AT = datetime(2026, 3, 1, tzinfo=UTC)
+CHANGE_DATA_FIXTURES = json.loads((Path(__file__).parent / "fixtures" / "issue_change_data.json").read_text())
+
+
+class TestIssueSnapshot(SimpleTestCase):
+ @parameterized.expand(
+ [
+ ("no_assignee", None, "TypeError: boom", None, "TypeError: boom", FIRST_SEEN, FIRST_SEEN),
+ (
+ "user",
+ ErrorTrackingIssueAssignment(user_id=42),
+ "TypeError: boom",
+ {"type": "user", "id": "42"},
+ "TypeError: boom",
+ FIRST_SEEN,
+ FIRST_SEEN,
+ ),
+ (
+ "role",
+ ErrorTrackingIssueAssignment(role_id=ROLE_ID),
+ None,
+ {"type": "role", "id": str(ROLE_ID)},
+ None,
+ FIRST_SEEN,
+ FIRST_SEEN,
+ ),
+ ("long_name", None, "x" * 2000, None, "x" * MAX_ISSUE_NAME_LENGTH, FIRST_SEEN, FIRST_SEEN),
+ ("no_fingerprint_first_seen", None, "TypeError: boom", None, "TypeError: boom", None, ISSUE_CREATED_AT),
+ ]
+ )
+ def test_to_json(
+ self, _name, assignment, issue_name, expected_assignee, expected_name, first_seen, expected_first_seen
+ ) -> None:
+ issue = ErrorTrackingIssue(
+ status=ErrorTrackingIssue.Status.RESOLVED,
+ severity=ErrorTrackingIssue.Severity.HIGH,
+ name=issue_name,
+ created_at=ISSUE_CREATED_AT,
+ )
+
+ snapshot = IssueSnapshot.build(issue, assignee=AssigneeRef.from_assignment(assignment), first_seen=first_seen)
+
+ assert snapshot.to_json() == {
+ "status": "resolved",
+ "severity": "high",
+ "name": expected_name,
+ "assignee": expected_assignee,
+ "first_seen": expected_first_seen.isoformat(),
+ }
+
+
+class TestIssueChangeData(SimpleTestCase):
+ @parameterized.expand([(f"{i}_{fixture['kind']}", fixture) for i, fixture in enumerate(CHANGE_DATA_FIXTURES)])
+ def test_round_trips_shared_fixture(self, _name, fixture) -> None:
+ parsed = parse_change_data(fixture["kind"], fixture["data"])
+
+ assert parsed.kind == fixture["kind"]
+ assert parsed.to_data() == fixture["data"]
+
+ def test_every_kind_has_a_shared_fixture(self) -> None:
+ assert {fixture["kind"] for fixture in CHANGE_DATA_FIXTURES} == set(ErrorTrackingIssueChange.Kind.values)