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): record manual issue changes in the change log (#112827)

Hugues Pouillot8438c1f10949
diff --git a/products/error_tracking/backend/logic/issue_changes.py b/products/error_tracking/backend/logic/issue_changes.py
index 3ca61b582886..5fade146142a 100644
--- a/products/error_tracking/backend/logic/issue_changes.py
+++ b/products/error_tracking/backend/logic/issue_changes.py
@@ -1,22 +1,35 @@
-"""Typed contents of issue change rows: the snapshot and the per-kind data payload.
+"""Issue change rows: the snapshot, the per-kind data payload, and the writer.
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 collections.abc import Sequence
from datetime import datetime
from typing import Any, ClassVar, Literal
from uuid import UUID
+from django.db.models import Min
+
+import structlog
+
from posthog.dataclasses import frozen
+from posthog.models.user import User
+from posthog.models.utils import uuid7
+from posthog.ph_client import feature_enabled_or_false
from products.error_tracking.backend.models import (
ErrorTrackingIssue,
ErrorTrackingIssueAssignment,
ErrorTrackingIssueChange,
+ ErrorTrackingIssueFingerprintV2,
)
+logger = structlog.get_logger(__name__)
+
+ISSUE_CHANGE_LOG_FLAG = "error-tracking-issue-change-log"
+
Kind = ErrorTrackingIssueChange.Kind
Status = ErrorTrackingIssue.Status
Severity = ErrorTrackingIssue.Severity
@@ -195,3 +208,94 @@ def parse_change_data(kind: str, data: dict[str, Any]) -> IssueChangeData:
)
# 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}")
+
+
+def issue_change_log_enabled(team_id: int) -> bool:
+ try:
+ return feature_enabled_or_false(
+ ISSUE_CHANGE_LOG_FLAG,
+ str(team_id),
+ groups={"project": str(team_id)},
+ group_properties={"project": {"id": str(team_id)}},
+ # Every manual mutation checks this flag, and the remote fallback can block a request for
+ # its full timeout. Local evaluation needs the flag to target projects only through the
+ # project group's `id` property supplied above; any other condition evaluates to off.
+ only_evaluate_locally=True,
+ send_feature_flag_events=False,
+ )
+ except Exception:
+ # An unreleased feature stays off when the flags service is unreachable,
+ # rather than defaulting on or failing the mutation.
+ logger.exception("error_tracking_issue_change_log_flag_check_failed", team_id=team_id)
+ return False
+
+
+@frozen
+class ChangeOperation:
+ """One user action, ingestion transaction or automation run. Its rows share `operation_id`."""
+
+ id: UUID
+ team_id: int
+ actor_type: ErrorTrackingIssueChange.ActorType
+ actor_user_id: int | None
+ bulk: bool
+
+ @classmethod
+ def for_user(cls, team_id: int, user: User, *, bulk: bool = False) -> "ChangeOperation | None":
+ """Start an operation, or return None when the change log is off for the team.
+
+ Call it before the mutation opens its transaction, so the flag check never holds row locks.
+ """
+ if not issue_change_log_enabled(team_id):
+ return None
+ return cls(
+ id=uuid7(),
+ team_id=team_id,
+ actor_type=ErrorTrackingIssueChange.ActorType.USER,
+ actor_user_id=user.id,
+ bulk=bulk,
+ )
+
+
+@frozen
+class IssueChange:
+ # The issue as it is after the change. The snapshot is built from it.
+ issue: ErrorTrackingIssue
+ data: IssueChangeData
+
+
+def record_issue_changes(operation: ChangeOperation | None, changes: Sequence[IssueChange]) -> None:
+ """Write the change rows. Call it inside the transaction that applies the changes."""
+ if operation is None or not changes:
+ return
+ issue_ids = {change.issue.id for change in changes}
+ assignees = {
+ assignment.issue_id: AssigneeRef.from_assignment(assignment)
+ for assignment in ErrorTrackingIssueAssignment.objects.filter(team_id=operation.team_id, issue_id__in=issue_ids)
+ }
+ first_seen_by_issue: dict[UUID, datetime | None] = dict(
+ ErrorTrackingIssueFingerprintV2.objects.filter(team_id=operation.team_id, issue_id__in=issue_ids)
+ .values("issue_id")
+ .annotate(earliest_first_seen=Min("first_seen"))
+ .values_list("issue_id", "earliest_first_seen")
+ )
+ ErrorTrackingIssueChange.objects.for_team(operation.team_id).bulk_create(
+ [
+ ErrorTrackingIssueChange(
+ team_id=operation.team_id,
+ issue_id=change.issue.id,
+ kind=change.data.kind,
+ data=change.data.to_data(),
+ snapshot=IssueSnapshot.build(
+ change.issue,
+ assignee=assignees.get(change.issue.id),
+ first_seen=first_seen_by_issue.get(change.issue.id),
+ ).to_json(),
+ operation_id=operation.id,
+ bulk=operation.bulk,
+ actor_type=operation.actor_type,
+ actor_user_id=operation.actor_user_id,
+ )
+ for change in changes
+ ]
+ )
diff --git a/products/error_tracking/backend/logic/issue_mutations.py b/products/error_tracking/backend/logic/issue_mutations.py
index 51af7c59a038..ef45554f4e0a 100644
--- a/products/error_tracking/backend/logic/issue_mutations.py
+++ b/products/error_tracking/backend/logic/issue_mutations.py
@@ -21,6 +21,20 @@ from products.access_control.backend.facade.api import role_belongs_to_organizat
from products.cohorts.backend.facade.api import cohort_exists_for_team
from products.error_tracking.backend.logic import ErrorTrackingIssueNotFoundError, get_issue
from products.error_tracking.backend.logic.assignees import assignee_property
+from products.error_tracking.backend.logic.issue_changes import (
+ AssigneeChanged,
+ AssigneeRef,
+ ChangeOperation,
+ Created,
+ IssueChange,
+ Merged,
+ NameChanged,
+ SeverityChanged,
+ Split,
+ Status,
+ StatusChanged,
+ record_issue_changes,
+)
from products.error_tracking.backend.logic.lifecycle_events import (
ISSUE_ASSIGNED_EVENT,
ISSUE_MERGED_EVENT,
@@ -68,6 +82,29 @@ def _get_issue(team_id: int, issue_id: UUID | str, *, select_related: tuple[str,
raise ErrorTrackingIssueNotFoundError from err
+def _lock_issues(
+ team_id: int, issue_ids: list[UUID] | list[str], *, select_related: tuple[str, ...] = ()
+) -> list[ErrorTrackingIssue]:
+ """Row-lock issues so that each change records the value it actually replaced.
+
+ Ingestion reopens issues concurrently, so a value read before the lock can be stale.
+ The id order matches the merge lock, so concurrent mutations cannot deadlock. `of`
+ keeps the lock on the issue rows, never on the team or organization rows a join reads.
+ """
+ qs = ErrorTrackingIssue.objects.select_for_update(of=("self",)).filter(team_id=team_id, id__in=issue_ids)
+ if select_related:
+ qs = qs.select_related(*select_related)
+ return list(qs.order_by("id"))
+
+
+def _refresh_under_lock(issue: ErrorTrackingIssue) -> None:
+ locked = _lock_issues(issue.team_id, [issue.id])
+ if not locked:
+ raise ErrorTrackingIssueNotFoundError
+ for field in _CLICKHOUSE_VISIBLE_ISSUE_STATE_FIELDS:
+ setattr(issue, field, getattr(locked[0], field))
+
+
def _status_from_string(status: str) -> "ErrorTrackingIssue.Status | None":
match status:
case "active":
@@ -108,53 +145,72 @@ def update_issue(
# 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
- severity_before = issue.severity
- name_before = issue.name
- description_before = issue.description
- status_after = fields.get("status")
- severity_after = fields.get("severity")
- name_after = fields.get("name")
- status_updated = "status" in fields and status_after != status_before
- severity_updated = "severity" in fields and severity_after != severity_before
- name_updated = "name" in fields and name_after != name_before
- description_updated = "description" in fields and fields["description"] != description_before
- state_updated = _has_clickhouse_visible_state_change(issue, fields)
-
- for key in ("status", "severity", "name", "description"):
- if key in fields:
- setattr(issue, key, fields[key])
-
- changes = []
- if status_updated:
- changes.append(
- Change(
- type="ErrorTrackingIssue",
- field="status",
- before=status_before,
- after=status_after,
- action="changed",
+ operation = ChangeOperation.for_user(team_id, user)
+
+ with transaction.atomic():
+ _refresh_under_lock(issue)
+ status_before = issue.status
+ severity_before = issue.severity
+ name_before = issue.name
+ description_before = issue.description
+ status_after = fields.get("status")
+ severity_after = fields.get("severity")
+ name_after = fields.get("name")
+ status_updated = "status" in fields and status_after != status_before
+ severity_updated = "severity" in fields and severity_after != severity_before
+ name_updated = "name" in fields and name_after != name_before
+ description_updated = "description" in fields and fields["description"] != description_before
+ state_updated = _has_clickhouse_visible_state_change(issue, fields)
+
+ for key in ("status", "severity", "name", "description"):
+ if key in fields:
+ setattr(issue, key, fields[key])
+
+ issue_changes: list[IssueChange] = []
+ if status_updated:
+ issue_changes.append(IssueChange(issue=issue, data=StatusChanged(previous=Status(status_before))))
+ if severity_updated:
+ issue_changes.append(
+ IssueChange(
+ issue=issue,
+ data=SeverityChanged(
+ previous=ErrorTrackingIssue.Severity(severity_before) if severity_before else None
+ ),
+ )
)
- )
- if severity_updated:
- changes.append(
- Change(
- type="ErrorTrackingIssue",
- field="severity",
- before=severity_before,
- after=severity_after,
- action="changed",
+ if name_updated:
+ issue_changes.append(IssueChange(issue=issue, data=NameChanged(previous=name_before)))
+
+ changes = []
+ if status_updated:
+ changes.append(
+ Change(
+ type="ErrorTrackingIssue",
+ field="status",
+ before=status_before,
+ after=status_after,
+ action="changed",
+ )
+ )
+ if severity_updated:
+ changes.append(
+ Change(
+ type="ErrorTrackingIssue",
+ field="severity",
+ before=severity_before,
+ after=severity_after,
+ action="changed",
+ )
+ )
+ if name_updated:
+ changes.append(
+ Change(type="ErrorTrackingIssue", field="name", before=name_before, after=name_after, action="changed")
)
- )
- if name_updated:
- changes.append(
- Change(type="ErrorTrackingIssue", field="name", before=name_before, after=name_after, action="changed")
- )
- with transaction.atomic():
if state_updated:
issue.state_updated_at = timezone.now()
issue.save()
+ record_issue_changes(operation, issue_changes)
if changes:
log_activity(
@@ -196,6 +252,7 @@ def merge_issues(
issue = _get_issue(team_id, issue_id, select_related=("team__organization",))
# 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)]
+ operation = ChangeOperation.for_user(team_id, user)
# One transaction around the merge and everything it reports: the activity entries and the
# lifecycle events must be registered in the same commit that moves the fingerprints, since
# a retry finds the sources gone, sees no transition and emits nothing.
@@ -203,6 +260,12 @@ def merge_issues(
outcome = issue.merge(issue_ids=ids)
if outcome.result != ErrorTrackingIssueMergeResult.MERGED:
return IssueMergeOutcome(result=outcome.result, merged_issue_count=len(outcome.merged_issue_ids))
+ # The merge holds the target's row lock, so this reads the state the snapshot must show.
+ _refresh_under_lock(issue)
+ issue_changes = [IssueChange(issue=issue, data=Merged(merged_issue_ids=tuple(outcome.merged_issue_ids)))]
+ if outcome.reopened and outcome.previous_status is not None:
+ issue_changes.append(IssueChange(issue=issue, data=StatusChanged(previous=Status(outcome.previous_status))))
+ record_issue_changes(operation, issue_changes)
merged_id_strings = [str(merged_issue_id) for merged_issue_id in outcome.merged_issue_ids]
log_activity(
@@ -265,8 +328,19 @@ def split_issue(
team_id: int, issue_id: UUID, fingerprints: list[dict], *, user: User, was_impersonated: bool
) -> list[UUID]:
issue = _get_issue(team_id, issue_id, select_related=("team__organization",))
- new_issues = issue.split(fingerprints=fingerprints)
- new_issue_ids = [new_issue.id for new_issue in new_issues]
+ operation = ChangeOperation.for_user(team_id, user)
+ with transaction.atomic():
+ _refresh_under_lock(issue)
+ new_issues = issue.split(fingerprints=fingerprints)
+ new_issue_ids = [new_issue.id for new_issue in new_issues]
+ if new_issues:
+ record_issue_changes(
+ operation,
+ [
+ IssueChange(issue=issue, data=Split(new_issue_ids=tuple(new_issue_ids))),
+ *(IssueChange(issue=new_issue, data=Created()) for new_issue in new_issues),
+ ],
+ )
if new_issues:
log_activity(
@@ -311,12 +385,18 @@ def set_issue_cohort(team_id: int, issue_id: UUID, cohort_id: int) -> None:
def assign_issue(
team_id: int, issue_id: UUID, assignee: dict[str, Any] | None, *, user: User, was_impersonated: bool
) -> bool:
+ operation = ChangeOperation.for_user(team_id, user)
with transaction.atomic():
- issue = _get_issue(team_id, issue_id, select_related=("team__organization",))
- transition = _assign_one(issue, assignee, issue.team.organization, user, team_id, was_impersonated)
- if transition is not None:
- produce_issue_lifecycle_events_on_commit([transition])
+ locked = _lock_issues(team_id, [issue_id], select_related=("team__organization",))
+ if not locked:
+ raise ErrorTrackingIssueNotFoundError
+ issue = locked[0]
+ outcome = _assign_one(issue, assignee, issue.team.organization, user, team_id, was_impersonated)
+ transition = outcome.transition if outcome is not None else None
+ if outcome is not None:
+ produce_issue_lifecycle_events_on_commit([outcome.transition])
_stamp_issue_state(team_id=team_id, issue_ids=[issue.id])
+ record_issue_changes(operation, [outcome.change])
if transition is not None:
sync_issues_to_clickhouse(issue_ids=[issue.id], team_id=team_id)
@@ -333,12 +413,12 @@ def bulk_update_issues(
user: User,
was_impersonated: bool,
) -> int:
- issues = list(
- ErrorTrackingIssue.objects.filter(team_id=team_id, id__in=issue_ids).select_related("team__organization")
- )
changed_issue_ids: list[UUID] = []
+ issue_changes: list[IssueChange] = []
+ operation = ChangeOperation.for_user(team_id, user, bulk=True)
with transaction.atomic():
+ issues = _lock_issues(team_id, issue_ids, select_related=("team__organization",))
if action == "set_status":
new_status = _status_from_string(status) if status is not None else None
if new_status is None:
@@ -380,6 +460,10 @@ def bulk_update_issues(
opener_allowed=False,
)
)
+ previous_status = Status(issue.status)
+ # The queryset update below writes the same status; the snapshot reads it from this instance.
+ issue.status = new_status
+ issue_changes.append(IssueChange(issue=issue, data=StatusChanged(previous=previous_status)))
produce_issue_lifecycle_events_on_commit(transitions)
if changed_issue_ids:
ErrorTrackingIssue.objects.filter(team_id=team_id, id__in=changed_issue_ids).update(
@@ -388,14 +472,16 @@ def bulk_update_issues(
elif action == "assign":
transitions = []
for issue in issues:
- transition = _assign_one(
+ outcome = _assign_one(
issue, assignee, issue.team.organization, user, team_id, was_impersonated, opener_allowed=False
)
- if transition is not None:
- transitions.append(transition)
+ if outcome is not None:
+ transitions.append(outcome.transition)
+ issue_changes.append(outcome.change)
changed_issue_ids.append(issue.id)
produce_issue_lifecycle_events_on_commit(transitions)
_stamp_issue_state(team_id=team_id, issue_ids=changed_issue_ids)
+ record_issue_changes(operation, issue_changes)
sync_issues_to_clickhouse(issue_ids=changed_issue_ids, team_id=team_id)
return len(changed_issue_ids)
@@ -410,6 +496,12 @@ def _assignment_repr(assignment: ErrorTrackingIssueAssignment | None) -> dict[st
}
+@frozen
+class _AssignOutcome:
+ transition: PendingLifecycleEvent
+ change: IssueChange
+
+
def _assign_one(
issue: ErrorTrackingIssue,
assignee: dict[str, Any] | None,
@@ -419,8 +511,8 @@ def _assign_one(
was_impersonated: bool,
*,
opener_allowed: bool = True,
-) -> PendingLifecycleEvent | None:
- """Apply one assignment change; returns its lifecycle transition for the caller to queue, or None if nothing changed."""
+) -> _AssignOutcome | None:
+ """Apply one assignment change; returns its lifecycle transition and change row for the caller, or None if nothing changed."""
assignment_before = ErrorTrackingIssueAssignment.objects.filter(issue_id=issue.id).first()
serialized_assignment_before = _assignment_repr(assignment_before)
@@ -502,4 +594,7 @@ def _assign_one(
],
),
)
- return transition
+ return _AssignOutcome(
+ transition=transition,
+ change=IssueChange(issue=issue, data=AssigneeChanged(previous=AssigneeRef.from_assignment(assignment_before))),
+ )
diff --git a/products/error_tracking/backend/tests/test_issue_change_recording.py b/products/error_tracking/backend/tests/test_issue_change_recording.py
new file mode 100644
index 000000000000..477788e6ff27
--- /dev/null
+++ b/products/error_tracking/backend/tests/test_issue_change_recording.py
@@ -0,0 +1,189 @@
+from concurrent.futures import ThreadPoolExecutor
+from datetime import UTC, datetime
+from queue import Queue
+from time import monotonic
+
+from posthog.test.base import BaseTest, NonAtomicBaseTest
+from unittest.mock import patch
+
+from django.db import close_old_connections, connection, transaction
+
+from products.error_tracking.backend.logic.issue_mutations import (
+ assign_issue,
+ bulk_update_issues,
+ merge_issues,
+ split_issue,
+ update_issue,
+)
+from products.error_tracking.backend.models import (
+ ErrorTrackingIssue,
+ ErrorTrackingIssueChange,
+ ErrorTrackingIssueFingerprintV2,
+)
+
+EARLY = datetime(2026, 1, 1, tzinfo=UTC)
+LATE = datetime(2026, 2, 1, tzinfo=UTC)
+
+
+@patch("products.error_tracking.backend.logic.issue_changes.issue_change_log_enabled", return_value=True)
+class TestIssueChangeRecording(BaseTest):
+ def _create_issue(self, fingerprints: dict[str, datetime], **fields) -> ErrorTrackingIssue:
+ issue = ErrorTrackingIssue.objects.create(team=self.team, **fields)
+ for fingerprint, first_seen in fingerprints.items():
+ ErrorTrackingIssueFingerprintV2.objects.create(team=self.team, issue=issue, fingerprint=fingerprint)
+ ErrorTrackingIssueFingerprintV2.objects.filter(fingerprint=fingerprint).update(first_seen=first_seen)
+ return issue
+
+ def _changes(self) -> list[ErrorTrackingIssueChange]:
+ return list(ErrorTrackingIssueChange.objects.for_team(self.team.id).order_by("kind", "issue_id"))
+
+ def test_update_records_one_row_per_changed_field_in_one_operation(self, _flag) -> None:
+ issue = self._create_issue({"fp": EARLY}, name="Old name")
+
+ update_issue(
+ self.team.id,
+ issue.id,
+ fields={"status": "resolved", "severity": "high", "name": "New name"},
+ user=self.user,
+ was_impersonated=False,
+ )
+
+ changes = self._changes()
+ assert [(change.kind, change.data) for change in changes] == [
+ ("name_changed", {"previous": "Old name"}),
+ ("severity_changed", {"previous": None}),
+ ("status_changed", {"previous": "active"}),
+ ]
+ assert {change.operation_id for change in changes} == {changes[0].operation_id}
+ assert changes[0].snapshot == {
+ "status": "resolved",
+ "severity": "high",
+ "name": "New name",
+ "assignee": None,
+ "first_seen": EARLY.isoformat(),
+ }
+ assert (changes[0].actor_type, changes[0].actor_user_id, changes[0].bulk) == ("user", self.user.id, False)
+
+ def test_bulk_status_change_records_the_new_status_as_one_bulk_operation(self, _flag) -> None:
+ issues = [self._create_issue({f"fp{i}": EARLY}) for i in range(2)]
+
+ bulk_update_issues(
+ self.team.id,
+ [str(issue.id) for issue in issues],
+ action="set_status",
+ status="suppressed",
+ assignee=None,
+ user=self.user,
+ was_impersonated=False,
+ )
+
+ changes = self._changes()
+ assert len(changes) == 2
+ assert {change.operation_id for change in changes} == {changes[0].operation_id}
+ assert all(change.bulk for change in changes)
+ assert [change.data["previous"] for change in changes] == ["active", "active"]
+ assert [change.snapshot["status"] for change in changes] == ["suppressed", "suppressed"]
+
+ def test_merge_records_the_merge_and_reopened_status_with_the_earliest_first_seen(self, _flag) -> None:
+ target = self._create_issue({"target_fp": LATE}, status=ErrorTrackingIssue.Status.RESOLVED)
+ source = self._create_issue({"source_fp": EARLY})
+
+ merge_issues(self.team.id, target.id, [str(source.id)], user=self.user, was_impersonated=False)
+
+ changes = self._changes()
+ assert [(change.issue_id, change.kind, change.data) for change in changes] == [
+ (target.id, "merged", {"merged_issue_ids": [str(source.id)]}),
+ (target.id, "status_changed", {"previous": "resolved"}),
+ ]
+ assert {change.operation_id for change in changes} == {changes[0].operation_id}
+ assert all(change.snapshot["status"] == "active" for change in changes)
+ assert all(change.snapshot["first_seen"] == EARLY.isoformat() for change in changes)
+
+ def test_split_records_the_split_and_a_created_row_per_new_issue(self, _flag) -> None:
+ issue = self._create_issue({"fp_one": EARLY, "fp_two": LATE})
+
+ [new_issue_id] = split_issue(
+ self.team.id,
+ issue.id,
+ [{"fingerprint": "fp_two", "name": "Split issue"}],
+ user=self.user,
+ was_impersonated=False,
+ )
+
+ changes = self._changes()
+ assert [(change.issue_id, change.kind, change.data) for change in changes] == [
+ (new_issue_id, "created", {}),
+ (issue.id, "split", {"new_issue_ids": [str(new_issue_id)]}),
+ ]
+ assert changes[0].snapshot["name"] == "Split issue"
+ assert changes[0].snapshot["first_seen"] == LATE.isoformat()
+
+ def test_assign_and_unassign_record_the_previous_assignee(self, _flag) -> None:
+ issue = self._create_issue({"fp": EARLY})
+
+ assign_issue(
+ self.team.id, issue.id, {"type": "user", "id": self.user.id}, user=self.user, was_impersonated=False
+ )
+ assign_issue(self.team.id, issue.id, None, user=self.user, was_impersonated=False)
+
+ changes = list(ErrorTrackingIssueChange.objects.for_team(self.team.id).order_by("created_at", "id"))
+ assigned = {"type": "user", "id": str(self.user.id)}
+ assert [(change.data, change.snapshot["assignee"]) for change in changes] == [
+ ({"previous": None}, assigned),
+ ({"previous": assigned}, None),
+ ]
+
+ def test_writes_nothing_when_the_flag_is_off(self, flag) -> None:
+ flag.return_value = False
+ issue = self._create_issue({"fp": EARLY})
+
+ update_issue(self.team.id, issue.id, fields={"status": "resolved"}, user=self.user, was_impersonated=False)
+
+ assert self._changes() == []
+
+
+@patch("products.error_tracking.backend.logic.issue_changes.issue_change_log_enabled", return_value=True)
+class TestIssueChangeRecordingConcurrency(NonAtomicBaseTest):
+ def test_update_records_a_concurrent_committed_status_before_taking_the_row_lock(self, _flag) -> None:
+ issue = ErrorTrackingIssue.objects.create(team=self.team, status=ErrorTrackingIssue.Status.RESOLVED)
+ backend_pid: Queue[int] = Queue()
+
+ def update() -> None:
+ close_old_connections()
+ try:
+ with connection.cursor() as cursor:
+ cursor.execute("SET lock_timeout = '10s'")
+ cursor.execute("SET statement_timeout = '15s'")
+ cursor.execute("SELECT pg_backend_pid()")
+ backend_pid.put(cursor.fetchone()[0])
+ update_issue(
+ self.team.id,
+ issue.id,
+ fields={"status": "suppressed"},
+ user=self.user,
+ was_impersonated=False,
+ )
+ finally:
+ close_old_connections()
+
+ with ThreadPoolExecutor(max_workers=1) as executor:
+ with transaction.atomic():
+ ErrorTrackingIssue.objects.filter(team_id=self.team.id, id=issue.id).update(
+ status=ErrorTrackingIssue.Status.ACTIVE
+ )
+ pending = executor.submit(update)
+ pid = backend_pid.get(timeout=10)
+ deadline = monotonic() + 10
+ with connection.cursor() as cursor:
+ while True:
+ if pending.done():
+ pending.result()
+ self.fail("update completed before waiting for the concurrent status commit")
+ cursor.execute("SELECT cardinality(pg_blocking_pids(%s)) > 0", [pid])
+ if cursor.fetchone()[0]:
+ break
+ self.assertLess(monotonic(), deadline, "update did not wait for the issue row lock")
+ pending.result(timeout=10)
+
+ [change] = ErrorTrackingIssueChange.objects.for_team(self.team.id).all()
+ assert (change.data, change.snapshot["status"]) == ({"previous": "active"}, "suppressed")