: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): drop autocapture settings mirror (#72146)
Aleksander Błaszkiewiczd8806f1a45e1
diff --git a/posthog/models/test/test_hog_function.py b/posthog/models/test/test_hog_function.pyindex cbfb6e8776be..108485e56f21 100644--- a/posthog/models/test/test_hog_function.py+++ b/posthog/models/test/test_hog_function.py@@ -283,9 +283,9 @@ class TestHogFunctionsBackgroundReloading(TestCase, QueryMatchingTest):{"key": "$host", "operator": "regex", "value": "^(localhost|127\\.0\\.0\\.1)($|:)"},{"key": "$pageview", "operator": "regex", "value": "test"},]- # 1 read old secret tokens (pre_save), 1 update team, 1 load hog flows, 1 load hog functions, 1 update hog functions, 1 sync_autocapture_opt_in+ # 1 read old secret tokens (pre_save), 1 update team, 1 load hog flows, 1 load hog functions, 1 update hog functions# Note: RemoteConfig refresh queries are now deferred via async signals- with self.assertNumQueries(6):+ with self.assertNumQueries(5):self.team.save()hog_function_1.refresh_from_db()hog_function_2.refresh_from_db()diff --git a/posthog/test/setup_receivers_baseline.txt b/posthog/test/setup_receivers_baseline.txtindex 9bef458e9e80..4ca0d1097a72 100644--- a/posthog/test/setup_receivers_baseline.txt+++ b/posthog/test/setup_receivers_baseline.txt@@ -163,7 +163,6 @@ post_save:products.data_modeling.backend.signals.sync_saved_query_name_to_nodepost_save:products.data_modeling.backend.signals.trigger_view_semantic_enrichmentpost_save:products.data_warehouse.backend.models.revenue_analytics_config.create_external_data_source_revenue_analytics_configpost_save:products.early_access_features.backend.signals.create_waitlist_survey_on_concept_stage-post_save:products.error_tracking.backend.signals.mirror_autocapture_opt_in_to_settingspost_save:products.event_definitions.backend.models.event_definition._invalidate_default_event_info_on_savepost_save:products.event_definitions.backend.models.property_definition._invalidate_has_person_email_on_savepost_save:products.exports.backend.models.subscription.subscription_saveddiff --git a/products/error_tracking/backend/apps.py b/products/error_tracking/backend/apps.pyindex b144155ed0ef..0003cff61efd 100644--- a/products/error_tracking/backend/apps.py+++ b/products/error_tracking/backend/apps.py@@ -5,6 +5,3 @@ 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.pydeleted file mode 100644index f5544cee7bee..000000000000--- a/products/error_tracking/backend/management/commands/backfill_error_tracking_autocapture_opt_in.py+++ /dev/null@@ -1,165 +0,0 @@-"""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.pydeleted file mode 100644index afedcc17ed64..000000000000--- a/products/error_tracking/backend/management/commands/test/test_backfill_error_tracking_autocapture_opt_in.py+++ /dev/null@@ -1,73 +0,0 @@-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/0021_remove_errortrackingsettings_autocapture_exceptions_opt_in.py b/products/error_tracking/backend/migrations/0021_remove_errortrackingsettings_autocapture_exceptions_opt_in.pynew file mode 100644index 000000000000..c75f57b8c321--- /dev/null+++ b/products/error_tracking/backend/migrations/0021_remove_errortrackingsettings_autocapture_exceptions_opt_in.py@@ -0,0 +1,21 @@+from django.db import migrations+++class Migration(migrations.Migration):+ dependencies = [+ ("error_tracking", "0020_errortrackingsettings_autocapture_exceptions_opt_in"),+ ]++ # State-only removal: the column stays in Postgres so a rollback deploy keeps working.+ # A later migration may DROP COLUMN once a full deploy cycle has passed.+ operations = [+ migrations.SeparateDatabaseAndState(+ state_operations=[+ migrations.RemoveField(+ model_name="errortrackingsettings",+ name="autocapture_exceptions_opt_in",+ ),+ ],+ database_operations=[],+ ),+ ]diff --git a/products/error_tracking/backend/migrations/max_migration.txt b/products/error_tracking/backend/migrations/max_migration.txtindex 38423e4bdc25..4e8591f54105 100644--- a/products/error_tracking/backend/migrations/max_migration.txt+++ b/products/error_tracking/backend/migrations/max_migration.txt@@ -1 +1 @@-0020_errortrackingsettings_autocapture_exceptions_opt_in+0021_remove_errortrackingsettings_autocapture_exceptions_opt_indiff --git a/products/error_tracking/backend/models.py b/products/error_tracking/backend/models.pyindex 0877398af33c..3949727e3757 100644--- a/products/error_tracking/backend/models.py+++ b/products/error_tracking/backend/models.py@@ -763,27 +763,11 @@ 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.pydeleted file mode 100644index f1f2b043e26e..000000000000--- a/products/error_tracking/backend/signals.py+++ /dev/null@@ -1,15 +0,0 @@-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.pydeleted file mode 100644index ab553257ddef..000000000000--- a/products/error_tracking/backend/tests/test_autocapture_opt_in_sync.py+++ /dev/null@@ -1,44 +0,0 @@-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 Nonediff --git a/products/error_tracking/frontend/scenes/ErrorTrackingConfigurationScene/exception_autocapture/ExceptionAutocaptureSettings.tsx b/products/error_tracking/frontend/scenes/ErrorTrackingConfigurationScene/exception_autocapture/ExceptionAutocaptureSettings.tsxindex 249f4aa5b5ec..b2565a843519 100644--- a/products/error_tracking/frontend/scenes/ErrorTrackingConfigurationScene/exception_autocapture/ExceptionAutocaptureSettings.tsx+++ b/products/error_tracking/frontend/scenes/ErrorTrackingConfigurationScene/exception_autocapture/ExceptionAutocaptureSettings.tsx@@ -2,11 +2,13 @@ import { useActions, useValues } from 'kea'import { LemonSwitch } from '@posthog/lemon-ui'+import { AccessControlAction } from 'lib/components/AccessControlAction'import { eventUsageLogic } from 'lib/utils/eventUsageLogic'import { teamLogic } from 'scenes/teamLogic'import { userLogic } from 'scenes/userLogic'import { ProductIntentContext, ProductKey } from '~/queries/schema/schema-general'+import { AccessControlLevel, AccessControlResourceType } from '~/types'import { DisableSurvey } from './DisableSurvey'import { disableSurveyLogic } from './disableSurveyLogic'@@ -20,30 +22,36 @@ export function ExceptionAutocaptureToggle(): JSX.Element {return (<>- <LemonSwitch- id="posthog-autocapture-exceptions-switch"- onChange={(checked) => {- if (checked) {- addProductIntent({- product_type: ProductKey.ERROR_TRACKING,- intent_context: ProductIntentContext.ERROR_TRACKING_EXCEPTION_AUTOCAPTURE_ENABLED,+ <AccessControlAction+ resourceType={AccessControlResourceType.Project}+ minAccessLevel={AccessControlLevel.Admin}+ userAccessLevel={currentTeam?.user_access_level}+ >+ <LemonSwitch+ id="posthog-autocapture-exceptions-switch"+ onChange={(checked) => {+ if (checked) {+ addProductIntent({+ product_type: ProductKey.ERROR_TRACKING,+ intent_context: ProductIntentContext.ERROR_TRACKING_EXCEPTION_AUTOCAPTURE_ENABLED,+ })+ }+ updateCurrentTeam({+ autocapture_exceptions_opt_in: checked,})- }- updateCurrentTeam({- autocapture_exceptions_opt_in: checked,- })- reportAutocaptureExceptionsToggled(checked)- if (checked) {- hideSurvey()- } else {- showSurvey()- }- }}- checked={!!currentTeam?.autocapture_exceptions_opt_in}- disabled={userLoading}- label="Enable exception autocapture"- bordered- />+ reportAutocaptureExceptionsToggled(checked)+ if (checked) {+ hideSurvey()+ } else {+ showSurvey()+ }+ }}+ checked={!!currentTeam?.autocapture_exceptions_opt_in}+ disabled={userLoading}+ label="Enable exception autocapture"+ bordered+ />+ </AccessControlAction><DisableSurvey /></>)