: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
feat(error-tracking): move autocapture opt-in to settings (phase 1) (#70701)
Aleksander Błaszkiewiczbac5cbc1ea26
diff --git a/products/error_tracking/backend/apps.py b/products/error_tracking/backend/apps.pyindex 0003cff61efd..b144155ed0ef 100644--- a/products/error_tracking/backend/apps.py+++ b/products/error_tracking/backend/apps.py@@ -5,3 +5,6 @@ class ErrorTrackingConfig(AppConfig):default_auto_field = "django.db.models.BigAutoField"name = "products.error_tracking.backend"label = "error_tracking"++ def ready(self) -> None:+ from . import signals # noqa: F401 — register post_save receiverdiff --git a/products/error_tracking/backend/management/commands/backfill_error_tracking_autocapture_opt_in.py b/products/error_tracking/backend/management/commands/backfill_error_tracking_autocapture_opt_in.pynew file mode 100644index 000000000000..f5544cee7bee--- /dev/null+++ b/products/error_tracking/backend/management/commands/backfill_error_tracking_autocapture_opt_in.py@@ -0,0 +1,165 @@+"""Backfill exception-autocapture opt-in from Team into ErrorTrackingSettings.++The toggle is moving off `Team.autocapture_exceptions_opt_in` onto+`ErrorTrackingSettings.autocapture_exceptions_opt_in` (Phase 1 of the move). A `post_save`+signal on Team dual-writes new changes; this command backfills teams that opted in before+that signal was deployed. Only teams that have opted in need a row: a missing row or a null+column both read as disabled, which already matches every team that never opted in, so+those teams are deliberately left untouched.++The candidate id list is only a starting point. To avoid clobbering a live disable with a+stale snapshot, each batch re-reads the teams that are *still* opted in under a `Team` row+lock (`select_for_update`) and upserts only those inside the same transaction. The lock+serializes the batch against a concurrent disabling `Team.save()`: the disable either commits+first (so the re-read skips the team) or blocks until the batch commits (so its own signal+then corrects the row we just wrote). `Team` stays the single source of truth.++Idempotent — re-running writes the same `True` and is a no-op on a clean dataset.++Usage:+ # Dry-run (default) — counts teams, writes nothing+ python manage.py backfill_error_tracking_autocapture_opt_in++ # Live run+ python manage.py backfill_error_tracking_autocapture_opt_in --live-run++ # Specific team+ python manage.py backfill_error_tracking_autocapture_opt_in --live-run --team-id 2++ # Resume from a specific team_id (inclusive)+ python manage.py backfill_error_tracking_autocapture_opt_in --live-run --start-from-team-id 1234+"""++from __future__ import annotations++import time+import logging++from django.core.management.base import BaseCommand, CommandError+from django.db import transaction++import structlog++from posthog.models import Team++from products.error_tracking.backend.models import ErrorTrackingSettings++logger = structlog.get_logger(__name__)++DEFAULT_BATCH_SIZE = 100+++class Command(BaseCommand):+ help = "Backfill exception-autocapture opt-in from Team onto ErrorTrackingSettings for opted-in teams."++ def add_arguments(self, parser):+ parser.add_argument(+ "--live-run",+ action="store_true",+ help="Actually write rows (default is dry-run).",+ )+ parser.add_argument(+ "--batch-size",+ type=int,+ default=DEFAULT_BATCH_SIZE,+ help=f"Teams per batch (default {DEFAULT_BATCH_SIZE}). Each batch re-reads live state before writing.",+ )+ parser.add_argument(+ "--team-id",+ type=int,+ default=None,+ help="Backfill only this team.",+ )+ parser.add_argument(+ "--start-from-team-id",+ type=int,+ default=None,+ help="Resume from this team_id (inclusive). Skips all teams with id < this value. Ignored when --team-id is set.",+ )+ parser.add_argument(+ "--end-team-id",+ type=int,+ default=None,+ help="Only include teams with team_id <= this value (inclusive). Ignored when --team-id is set.",+ )++ def handle(+ self,+ *,+ live_run: bool,+ batch_size: int,+ team_id: int | None,+ start_from_team_id: int | None,+ end_team_id: int | None,+ **options,+ ):+ logger.setLevel(logging.INFO)++ if batch_size < 1:+ raise CommandError(f"--batch-size must be a positive integer, got {batch_size}.")++ mode = "LIVE" if live_run else "DRY-RUN (use --live-run to apply)"+ candidate_ids = self._candidate_team_ids(+ team_id=team_id,+ start_from_team_id=start_from_team_id,+ end_team_id=end_team_id,+ )+ logger.info("backfill_starting", mode=mode, batch_size=batch_size, candidate_teams=len(candidate_ids))++ if not candidate_ids:+ logger.info("backfill_no_rows_found")+ return++ if not live_run:+ logger.info("backfill_dry_run_complete", teams=len(candidate_ids))+ return++ start_time = time.monotonic()+ synced = 0+ for offset in range(0, len(candidate_ids), batch_size):+ chunk = candidate_ids[offset : offset + batch_size]+ synced += self._sync_batch(chunk)+ logger.info("backfill_progress", processed=offset + len(chunk), synced=synced, last_team_id=chunk[-1])++ elapsed = time.monotonic() - start_time+ logger.info("backfill_complete", synced=synced, elapsed_s=round(elapsed, 2))++ def _sync_batch(self, team_ids: list[int]) -> int:+ # Lock the Team rows while re-reading live state, then upsert in the same transaction. The+ # lock serializes this batch against a concurrent disabling Team.save(): the disable either+ # commits first (so we read False and skip the team) or blocks until we commit (so its signal+ # then flips the row we wrote to False). A team no longer opted in and still row-less is+ # already correct (row-less == disabled), so skipping it is right.+ with transaction.atomic():+ still_opted_in = list(+ Team.objects.select_for_update()+ .filter(id__in=team_ids, autocapture_exceptions_opt_in=True)+ .values_list("id", flat=True)+ )+ if not still_opted_in:+ return 0++ ErrorTrackingSettings.objects.bulk_create(+ [ErrorTrackingSettings(team_id=tid, autocapture_exceptions_opt_in=True) for tid in still_opted_in],+ update_conflicts=True,+ unique_fields=["team"],+ update_fields=["autocapture_exceptions_opt_in"],+ )+ return len(still_opted_in)++ def _candidate_team_ids(+ self,+ *,+ team_id: int | None,+ start_from_team_id: int | None,+ end_team_id: int | None,+ ) -> list[int]:+ qs = Team.objects.filter(autocapture_exceptions_opt_in=True)+ if team_id is not None:+ qs = qs.filter(id=team_id)+ else:+ if start_from_team_id is not None:+ qs = qs.filter(id__gte=start_from_team_id)+ if end_team_id is not None:+ qs = qs.filter(id__lte=end_team_id)+ return sorted(qs.values_list("id", flat=True))diff --git a/products/error_tracking/backend/management/commands/test/test_backfill_error_tracking_autocapture_opt_in.py b/products/error_tracking/backend/management/commands/test/test_backfill_error_tracking_autocapture_opt_in.pynew file mode 100644index 000000000000..afedcc17ed64--- /dev/null+++ b/products/error_tracking/backend/management/commands/test/test_backfill_error_tracking_autocapture_opt_in.py@@ -0,0 +1,73 @@+from posthog.test.base import BaseTest++from django.core.management.base import CommandError++from parameterized import parameterized++from posthog.models import Team++from products.error_tracking.backend.management.commands.backfill_error_tracking_autocapture_opt_in import Command+from products.error_tracking.backend.models import ErrorTrackingSettings+++class TestBackfillErrorTrackingAutocaptureOptIn(BaseTest):+ def _run(self, *, live_run: bool = True, batch_size: int = 2) -> None:+ # Small batch so a multi-team run spans several batches and exercises the chunking loop.+ Command().handle(+ live_run=live_run, batch_size=batch_size, team_id=None, start_from_team_id=None, end_team_id=None+ )++ def _historical_opted_in_team(self) -> Team:+ # Simulate a team that opted in before the dual-write signal existed: True on Team, no settings+ # row. A queryset update bypasses the post_save signal that would otherwise create the row.+ team = Team.objects.create(organization=self.organization)+ Team.objects.filter(id=team.id).update(autocapture_exceptions_opt_in=True)+ return team++ def test_live_run_backfills_only_opted_in_teams(self):+ no_row = self._historical_opted_in_team()+ existing_row = self._historical_opted_in_team()+ ErrorTrackingSettings.objects.create(team=existing_row, project_rate_limit_value=42)+ not_opted_in = Team.objects.create(organization=self.organization, autocapture_exceptions_opt_in=False)+ never_set = Team.objects.create(organization=self.organization)++ self._run(live_run=True)++ assert ErrorTrackingSettings.objects.get(team=no_row).autocapture_exceptions_opt_in is True++ updated = ErrorTrackingSettings.objects.get(team=existing_row)+ assert updated.autocapture_exceptions_opt_in is True+ # A pre-existing settings row must keep its other fields.+ assert updated.project_rate_limit_value == 42++ assert not ErrorTrackingSettings.objects.filter(team=not_opted_in).exists()+ assert not ErrorTrackingSettings.objects.filter(team=never_set).exists()++ def test_dry_run_writes_nothing(self):+ team = self._historical_opted_in_team()++ self._run(live_run=False)++ assert not ErrorTrackingSettings.objects.filter(team=team).exists()++ @parameterized.expand([("zero", 0), ("negative", -5)])+ def test_invalid_batch_size_fails_fast(self, _name: str, batch_size: int):+ # A non-positive batch size would crash range() or silently sync nothing; the manual pre-cutover+ # step must reject it with a clear error rather than reporting no synced rows.+ team = self._historical_opted_in_team()++ with self.assertRaises(CommandError):+ self._run(live_run=True, batch_size=batch_size)++ assert not ErrorTrackingSettings.objects.filter(team=team).exists()++ def test_disable_after_snapshot_is_not_clobbered(self):+ # Team is in the candidate id list (snapshotted as opted-in) but has since disabled. The batch+ # must re-read live state and skip it, rather than writing a stale True over the live False.+ team = self._historical_opted_in_team()+ Team.objects.filter(id=team.id).update(autocapture_exceptions_opt_in=False)++ synced = Command()._sync_batch([team.id])++ assert synced == 0+ assert not ErrorTrackingSettings.objects.filter(team=team).exists()diff --git a/products/error_tracking/backend/migrations/0020_errortrackingsettings_autocapture_exceptions_opt_in.py b/products/error_tracking/backend/migrations/0020_errortrackingsettings_autocapture_exceptions_opt_in.pynew file mode 100644index 000000000000..33e007589011--- /dev/null+++ b/products/error_tracking/backend/migrations/0020_errortrackingsettings_autocapture_exceptions_opt_in.py@@ -0,0 +1,17 @@+# Generated by Django 5.2.14 on 2026-07-14 11:03++from django.db import migrations, models+++class Migration(migrations.Migration):+ dependencies = [+ ("error_tracking", "0019_errortrackingbypassrule"),+ ]++ operations = [+ migrations.AddField(+ model_name="errortrackingsettings",+ name="autocapture_exceptions_opt_in",+ field=models.BooleanField(blank=True, null=True),+ ),+ ]diff --git a/products/error_tracking/backend/migrations/max_migration.txt b/products/error_tracking/backend/migrations/max_migration.txtindex bccd12207561..38423e4bdc25 100644--- a/products/error_tracking/backend/migrations/max_migration.txt+++ b/products/error_tracking/backend/migrations/max_migration.txt@@ -1 +1 @@-0019_errortrackingbypassrule+0020_errortrackingsettings_autocapture_exceptions_opt_indiff --git a/products/error_tracking/backend/models.py b/products/error_tracking/backend/models.pyindex 1553812f0b6d..026ef5c6e6d8 100644--- a/products/error_tracking/backend/models.py+++ b/products/error_tracking/backend/models.py@@ -731,11 +731,27 @@ class ErrorTrackingSettings(models.Model):project_rate_limit_bucket_size_minutes = models.IntegerField(null=True, blank=True)per_issue_rate_limit_value = models.IntegerField(null=True, blank=True)per_issue_rate_limit_bucket_size_minutes = models.IntegerField(null=True, blank=True)+ # Nullable mirrors the source Team.autocapture_exceptions_opt_in during the move; null == disabled.+ autocapture_exceptions_opt_in = models.BooleanField(null=True, blank=True)class Meta:db_table = "posthog_errortrackingsettings"+def sync_autocapture_opt_in(team_id: int, opt_in: bool | None) -> None:+ """Mirror Team.autocapture_exceptions_opt_in onto ErrorTrackingSettings while the setting is being moved.++ Only opted-in teams get a row — a missing row reads as disabled, so teams that never opted in stay+ row-less. Disabling an already-opted-in team syncs the existing row instead of creating one.+ """+ if opt_in:+ ErrorTrackingSettings.objects.update_or_create(+ team_id=team_id, defaults={"autocapture_exceptions_opt_in": True}+ )+ else:+ ErrorTrackingSettings.objects.filter(team_id=team_id).update(autocapture_exceptions_opt_in=opt_in)++class ErrorTrackingSpikeEvent(UUIDModel):team = models.ForeignKey("posthog.Team", on_delete=models.CASCADE)issue = models.ForeignKey(ErrorTrackingIssue, on_delete=models.CASCADE, related_name="spike_events")diff --git a/products/error_tracking/backend/signals.py b/products/error_tracking/backend/signals.pynew file mode 100644index 000000000000..f1f2b043e26e--- /dev/null+++ b/products/error_tracking/backend/signals.py@@ -0,0 +1,15 @@+from django.db.models.signals import post_save+from django.dispatch import receiver++from posthog.models import Team++from products.error_tracking.backend.models import sync_autocapture_opt_in+++@receiver(post_save, sender=Team)+def mirror_autocapture_opt_in_to_settings(sender, instance: Team, update_fields=None, **kwargs) -> None:+ # Dual-write while autocapture opt-in moves off Team onto ErrorTrackingSettings. Skip saves that+ # explicitly list their fields and don't touch this one; full saves (update_fields=None) fall through.+ if update_fields is not None and "autocapture_exceptions_opt_in" not in update_fields:+ return+ sync_autocapture_opt_in(team_id=instance.pk, opt_in=instance.autocapture_exceptions_opt_in)diff --git a/products/error_tracking/backend/tests/test_autocapture_opt_in_sync.py b/products/error_tracking/backend/tests/test_autocapture_opt_in_sync.pynew file mode 100644index 000000000000..ab553257ddef--- /dev/null+++ b/products/error_tracking/backend/tests/test_autocapture_opt_in_sync.py@@ -0,0 +1,44 @@+from posthog.test.base import BaseTest++from posthog.models import Team++from products.error_tracking.backend.models import ErrorTrackingSettings+++class TestAutocaptureOptInSync(BaseTest):+ def _settings(self, team: Team) -> ErrorTrackingSettings | None:+ return ErrorTrackingSettings.objects.filter(team=team).first()++ def test_opting_in_mirrors_to_settings_row(self):+ team = Team.objects.create(organization=self.organization, autocapture_exceptions_opt_in=True)++ settings = self._settings(team)+ assert settings is not None+ assert settings.autocapture_exceptions_opt_in is True++ def test_opting_out_syncs_existing_row_without_deleting_it(self):+ team = Team.objects.create(organization=self.organization, autocapture_exceptions_opt_in=True)+ ErrorTrackingSettings.objects.filter(team=team).update(project_rate_limit_value=42)++ team.autocapture_exceptions_opt_in = False+ team.save()++ settings = self._settings(team)+ assert settings is not None+ assert settings.autocapture_exceptions_opt_in is False+ # Other settings on the row must survive a disable.+ assert settings.project_rate_limit_value == 42++ def test_never_opting_in_creates_no_row(self):+ team = Team.objects.create(organization=self.organization, autocapture_exceptions_opt_in=False)++ assert self._settings(team) is None++ def test_save_not_touching_the_field_does_not_recreate_row(self):+ team = Team.objects.create(organization=self.organization, autocapture_exceptions_opt_in=True)+ ErrorTrackingSettings.objects.filter(team=team).delete()++ team.name = "renamed"+ team.save(update_fields=["name"])++ assert self._settings(team) is None