: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(slack_app): migrate Slack model pins into the central tasks config (#98291)
Vojta Bartoš69f6a37cf6ad
diff --git a/products/slack_app/backend/migrations/0016_backfill_model_pins_to_tasks.py b/products/slack_app/backend/migrations/0016_backfill_model_pins_to_tasks.pynew file mode 100644index 000000000000..a8f47aff4e9c--- /dev/null+++ b/products/slack_app/backend/migrations/0016_backfill_model_pins_to_tasks.py@@ -0,0 +1,153 @@+from django.db import migrations+from django.db.models import F+++def backfill_model_pins(apps, schema_editor):+ """Move personal Slack model pins into the central per-(user, project) tasks config.++ The App Home now writes model preferences only to that config (the Slack-local pin+ store is being retired), so pins that predate the switch are copied over and cleared+ here. A pin lands in every connected project where its owner is a member, matching+ how it used to apply regardless of routing. Conflicts resolve most-recent-wins on+ ``updated_at``, so a central preference set, or deliberately cleared, after the pin+ keeps its value; rows are walked oldest first so a user pinned in several workspaces+ deterministically ends on their newest pin.++ The Slack identity resolves the same two ways the inbound event path maps it, with+ the same organization scope: the newest account link whose user belongs to a+ connected organization, else a profile-cache email match against those members. A+ pin that maps to no user or to no member project is left in place — it cannot+ influence a run (mentions from unresolved users are dropped) and goes away with the+ column.++ Model ids and efforts are copied as stored, without catalogue validation: run+ resolution is lenient about stale ids, and a migration must not depend on a live+ model catalogue.+ """+ SlackSettings = apps.get_model("slack_app", "SlackSettings")+ SlackUserProfileCache = apps.get_model("slack_app", "SlackUserProfileCache")+ Integration = apps.get_model("posthog", "Integration")+ OrganizationMembership = apps.get_model("posthog", "OrganizationMembership")+ Team = apps.get_model("posthog", "Team")+ UserIntegration = apps.get_model("posthog", "UserIntegration")+ UserTasksConfig = apps.get_model("tasks", "UserTasksConfig")++ def connected_teams(workspace_id):+ """(team_id, organization_id) pairs of every project this workspace connects."""+ return list(+ Integration.objects.filter(kind="slack", integration_id=workspace_id).values_list(+ "team_id", "team__organization_id"+ )+ )++ def resolve_user(workspace_id, slack_user_id, org_ids):+ """The PostHog user behind a Slack identity, scoped like the inbound event+ resolver: the newest account link whose user belongs to a connected+ organization, else a profile-cache email match against those members."""+ links = list(+ UserIntegration.objects.filter(+ kind="slack",+ integration_id=slack_user_id,+ config__slack_team_id=workspace_id,+ user__is_active=True,+ )+ .order_by("-created_at")+ .select_related("user")+ )+ member_ids = set(+ OrganizationMembership.objects.filter(+ user_id__in=[link.user_id for link in links], organization_id__in=org_ids+ ).values_list("user_id", flat=True)+ )+ for link in links:+ if link.user_id in member_ids:+ return link.user++ # Freshest cache row first; rows predating `refreshed_at` sort last.+ email = (+ SlackUserProfileCache.objects.filter(+ integration__kind="slack",+ integration__integration_id=workspace_id,+ slack_user_id=slack_user_id,+ )+ .exclude(email=None)+ .exclude(email="")+ .order_by(F("refreshed_at").desc(nulls_last=True), "-updated_at")+ .values_list("email", flat=True)+ .first()+ )+ if not email:+ return None+ membership = (+ OrganizationMembership.objects.filter(+ organization_id__in=org_ids, user__email__iexact=email, user__is_active=True+ )+ .select_related("user")+ .first()+ )+ return membership.user if membership else None++ def member_canonical_team_ids(teams, user):+ """Teams among ``teams`` whose organization the user belongs to, keyed on the+ project root team like the config rows themselves."""+ member_org_ids = set(+ OrganizationMembership.objects.filter(+ user=user, organization_id__in={org_id for _, org_id in teams}+ ).values_list("organization_id", flat=True)+ )+ member_team_ids = {team_id for team_id, org_id in teams if org_id in member_org_ids}+ pairs = Team.objects.filter(id__in=member_team_ids).values_list("id", "parent_team_id")+ return sorted({parent_id or team_id for team_id, parent_id in pairs})++ # Oldest first, so when one user holds pins in several workspaces the newest+ # pin is applied last and wins.+ rows = SlackSettings.objects.filter(+ slack_user_id__isnull=False,+ ai_preferences__isnull=False,+ ).order_by("updated_at", "id")+ migrated_keys = set()+ for row in rows.iterator():+ prefs = row.ai_preferences or {}+ # Both halves of the pair or the row was never a configured pin.+ payload = {key: prefs[key] for key in ("runtime_adapter", "model", "reasoning_effort") if prefs.get(key)}+ if "runtime_adapter" not in payload or "model" not in payload:+ continue+ teams = connected_teams(row.slack_workspace_id)+ user = resolve_user(row.slack_workspace_id, row.slack_user_id, {org_id for _, org_id in teams})+ if user is None:+ continue+ team_ids = member_canonical_team_ids(teams, user)+ if not team_ids:+ # No destination: keep the pin rather than discarding a preference+ # this migration could not place anywhere.+ continue+ for team_id in team_ids:+ key = (team_id, user.id)+ config = UserTasksConfig._base_manager.filter(team_id=team_id, user_id=user.id).first()+ # A pre-existing config newer than the pin wins; one written by this+ # run does not, so a user's newest pin ends up applied.+ if config is not None and key not in migrated_keys and config.updated_at >= row.updated_at:+ continue+ if config is None:+ UserTasksConfig._base_manager.create(team_id=team_id, user_id=user.id, ai_run_preferences=payload)+ else:+ config.ai_run_preferences = payload+ config.save(update_fields=["ai_run_preferences", "updated_at"])+ migrated_keys.add(key)+ # Accounted for on every reachable project; clear the pin so display and+ # runs stop preferring a store that no longer takes writes.+ row.ai_preferences = None+ row.save(update_fields=["ai_preferences", "updated_at"])+++class Migration(migrations.Migration):+ dependencies = [+ ("slack_app", "0015_backfill_slack_thread_conversation_type"),+ # UserTasksConfig and the posthog identity models the mapping reads.+ ("tasks", "0115_teamtasksconfig_usertasksconfig"),+ ("posthog", "0001_squash_2026_09_07_initial"),+ ]++ operations = [+ migrations.RunPython(backfill_model_pins, migrations.RunPython.noop, elidable=True),+ ]diff --git a/products/slack_app/backend/migrations/max_migration.txt b/products/slack_app/backend/migrations/max_migration.txtindex bf80ca89111b..bf614416c3b7 100644--- a/products/slack_app/backend/migrations/max_migration.txt+++ b/products/slack_app/backend/migrations/max_migration.txt@@ -1 +1 @@-0015_backfill_slack_thread_conversation_type+0016_backfill_model_pins_to_tasksdiff --git a/products/slack_app/backend/tests/test_backfill_model_pins_migration.py b/products/slack_app/backend/tests/test_backfill_model_pins_migration.pynew file mode 100644index 000000000000..80f2bc681ddb--- /dev/null+++ b/products/slack_app/backend/tests/test_backfill_model_pins_migration.py@@ -0,0 +1,219 @@+from importlib import import_module++import pytest++from django.apps import apps as live_apps+from django.utils.timezone import now++from posthog.models.integration import Integration+from posthog.models.organization import Organization+from posthog.models.team.team import Team+from posthog.models.user import User+from posthog.models.user_integration import UserIntegration++from products.slack_app.backend.models import SlackSettings, SlackUserProfileCache+from products.tasks.backend.facade.ai_run_defaults import get_user_ai_run_preferences, update_user_ai_run_preferences++# The function is exercised against the live app registry: at HEAD the historical+# models are identical, and this keeps the test at the cheapest level that still+# catches a mapping or conflict-policy regression.+_migration = import_module("products.slack_app.backend.migrations.0016_backfill_model_pins_to_tasks")++WORKSPACE = "T_BACKFILL"+PIN = {"runtime_adapter": "claude", "model": "claude-opus-4-8", "reasoning_effort": "high"}+++def _run():+ _migration.backfill_model_pins(live_apps, None)+++def setup(db):+ organization = Organization.objects.create(name="Org")+ team_a = Team.objects.create(organization=organization, name="A")+ team_b = Team.objects.create(organization=organization, name="B")+ other_org = Organization.objects.create(name="Other")+ team_outside = Team.objects.create(organization=other_org, name="Outside")+ for team in (team_a, team_b, team_outside):+ Integration.objects.create(+ team=team, kind="slack", integration_id=WORKSPACE, sensitive_config={"access_token": "x"}+ )+ user = User.objects.create_and_join(organization, "[email protected]", None)+ return user, team_a, team_b, team_outside+++def _link(user, slack_user_id="U001", workspace=WORKSPACE):+ UserIntegration.objects.create(+ user=user,+ kind=UserIntegration.IntegrationKind.SLACK,+ integration_id=slack_user_id,+ config={"slack_team_id": workspace},+ )+++def _pin_row(slack_user_id="U001", ai_preferences="use-pin"):+ return SlackSettings.objects.create(+ slack_workspace_id=WORKSPACE,+ slack_user_id=slack_user_id,+ ai_preferences=PIN if ai_preferences == "use-pin" else ai_preferences,+ )+++class TestBackfillModelPinsMigration:+ def test_link_mapped_pin_lands_in_every_member_project_and_is_cleared(self, setup):+ user, team_a, team_b, team_outside = setup+ _link(user)+ row = _pin_row()++ _run()++ assert get_user_ai_run_preferences(team_a.id, user.id) == PIN+ assert get_user_ai_run_preferences(team_b.id, user.id) == PIN+ # The workspace also connects a project in an org the user isn't in; the+ # pin must not follow it there.+ assert get_user_ai_run_preferences(team_outside.id, user.id) == {}+ row.refresh_from_db()+ assert row.ai_preferences is None++ def test_email_mapped_pin_lands_without_a_link(self, setup):+ user, team_a, _team_b, _team_outside = setup+ integration = Integration.objects.filter(team=team_a, kind="slack").get()+ SlackUserProfileCache.objects.create(+ integration=integration, slack_user_id="U001", email="[email protected]"+ )+ _pin_row()++ _run()++ assert get_user_ai_run_preferences(team_a.id, user.id) == PIN++ def test_newer_central_config_is_kept_but_the_pin_still_clears(self, setup):+ user, team_a, _team_b, _team_outside = setup+ _link(user)+ row = _pin_row()+ update_user_ai_run_preferences(+ team_a.id, user.id, runtime_adapter="codex", model="gpt-5.5", reasoning_effort=None+ )++ _run()++ assert get_user_ai_run_preferences(team_a.id, user.id)["model"] == "gpt-5.5"+ row.refresh_from_db()+ assert row.ai_preferences is None++ def test_newer_pin_overwrites_older_central_config(self, setup):+ user, team_a, _team_b, _team_outside = setup+ _link(user)+ update_user_ai_run_preferences(+ team_a.id, user.id, runtime_adapter="codex", model="gpt-5.5", reasoning_effort=None+ )+ _pin_row()++ _run()++ assert get_user_ai_run_preferences(team_a.id, user.id) == PIN++ @pytest.mark.parametrize(+ "ai_preferences",+ [+ pytest.param({"reasoning_effort": "high"}, id="half-set-row"),+ pytest.param({}, id="empty-payload"),+ ],+ )+ def test_rows_without_the_atomic_pair_migrate_nothing(self, setup, ai_preferences):+ user, team_a, _team_b, _team_outside = setup+ _link(user)+ _pin_row(ai_preferences=ai_preferences)++ _run()++ assert get_user_ai_run_preferences(team_a.id, user.id) == {}++ def test_unmapped_identity_is_left_untouched(self, setup):+ user, team_a, _team_b, _team_outside = setup+ row = _pin_row(slack_user_id="U_NOBODY")++ _run()++ assert get_user_ai_run_preferences(team_a.id, user.id) == {}+ row.refresh_from_db()+ assert row.ai_preferences == PIN++ def test_environment_team_pin_lands_on_the_project_root(self, setup):+ user, team_a, _team_b, _team_outside = setup+ env_team = Team.objects.create(+ organization=team_a.organization, project=team_a.project, parent_team=team_a, name="env"+ )+ Integration.objects.create(+ team=env_team, kind="slack", integration_id="T_ENV", sensitive_config={"access_token": "x"}+ )+ _link(user)+ UserIntegration.objects.filter(user=user).update(config={"slack_team_id": "T_ENV"})+ SlackSettings.objects.create(slack_workspace_id="T_ENV", slack_user_id="U001", ai_preferences=PIN)++ _run()++ # Config rows are keyed on the project root, matching the resolver.+ assert get_user_ai_run_preferences(team_a.id, user.id) == PIN++ def test_newer_inaccessible_link_does_not_shadow_the_accessible_one(self, setup):+ user, team_a, _team_b, _team_outside = setup+ _link(user)+ # A newer link on the same Slack identity, held by a user outside every+ # connected org — the runtime resolver skips it, so the migration must too.+ stranger = User.objects.create_and_join(+ Organization.objects.create(name="Elsewhere"), "[email protected]", None+ )+ _link(stranger)+ _pin_row()++ _run()++ assert get_user_ai_run_preferences(team_a.id, user.id) == PIN+ assert get_user_ai_run_preferences(team_a.id, stranger.id) == {}++ def test_pin_with_only_an_inaccessible_link_is_left_untouched(self, setup):+ user, team_a, _team_b, _team_outside = setup+ stranger = User.objects.create_and_join(+ Organization.objects.create(name="Elsewhere"), "[email protected]", None+ )+ _link(stranger)+ row = _pin_row()++ _run()++ row.refresh_from_db()+ assert row.ai_preferences == PIN+ assert get_user_ai_run_preferences(team_a.id, user.id) == {}++ def test_stale_profile_cache_email_loses_to_the_fresh_row(self, setup):+ user, team_a, team_b, _team_outside = setup+ old_owner = User.objects.create_and_join(team_a.organization, "[email protected]", None)+ integrations = list(Integration.objects.filter(integration_id=WORKSPACE, team__in=[team_a, team_b]))+ SlackUserProfileCache.objects.create(+ integration=integrations[0], slack_user_id="U001", email="[email protected]", refreshed_at=None+ )+ SlackUserProfileCache.objects.create(+ integration=integrations[1], slack_user_id="U001", email="[email protected]", refreshed_at=now()+ )+ _pin_row()++ _run()++ assert get_user_ai_run_preferences(team_a.id, user.id) == PIN+ assert get_user_ai_run_preferences(team_a.id, old_owner.id) == {}++ def test_newest_pin_wins_across_workspaces(self, setup):+ user, team_a, _team_b, _team_outside = setup+ Integration.objects.create(+ team=team_a, kind="slack", integration_id="T_SECOND", sensitive_config={"access_token": "x"}+ )+ _link(user)+ _link(user, slack_user_id="U9", workspace="T_SECOND")+ _pin_row() # older+ newer = {"runtime_adapter": "codex", "model": "gpt-5.5"}+ SlackSettings.objects.create(slack_workspace_id="T_SECOND", slack_user_id="U9", ai_preferences=newer)++ _run()++ assert get_user_ai_run_preferences(team_a.id, user.id) == newer