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(web-analytics): add dagster job to migrate flat custom bot rules (#98661)

Lucas Ricoy71eb67908536
diff --git a/posthog/dags/locations/web_analytics.py b/posthog/dags/locations/web_analytics.py
index 6f5a4c4b5963..20dc94474570 100644
--- a/posthog/dags/locations/web_analytics.py
+++ b/posthog/dags/locations/web_analytics.py
@@ -8,6 +8,7 @@ from products.web_analytics.dags import (
cache_warming,
clear_oom_pins,
eager_web_analytics_precompute,
+ migrate_custom_bot_rules,
web_analytics_watchdog,
web_dimensional_precompute,
web_pre_aggregated_accuracy,
@@ -62,6 +63,7 @@ defs = dagster.Definitions(
marketing_precompute.marketing_precompute_job,
cache_favicons.cache_authorized_domain_favicons_job,
clear_oom_pins.web_analytics_clear_precompute_oom_pins_job,
+ migrate_custom_bot_rules.web_analytics_migrate_custom_bot_rules_job,
],
schedules=schedules,
loggers=loggers,
diff --git a/products/web_analytics/backend/custom_bot_rules_migration.py b/products/web_analytics/backend/custom_bot_rules_migration.py
new file mode 100644
index 000000000000..5e04520a0d1e
--- /dev/null
+++ b/products/web_analytics/backend/custom_bot_rules_migration.py
@@ -0,0 +1,88 @@
+from django.db import connection
+
+from posthog.dataclasses import frozen
+
+
+@frozen
+class FlatRuleTeam:
+ team_id: int
+ flat_rules: int
+
+
+# Rewrites pre-combiner flat bot rules ({key, matcher, pattern} on the rule itself) into the
+# multi-condition shape ({combiner, items}) the current code reads. Everything happens inside one
+# UPDATE per team: only the customBotDefinitions key of team.modifiers changes, so concurrent
+# writes to other modifier keys cannot be clobbered and their query cache keys do not churn.
+# Entries already in the new shape and non-object entries pass through untouched, which makes the
+# statement idempotent. The condition id gets a "-condition" suffix because the settings editor
+# keys rules and conditions in one id-keyed drag-and-drop context.
+# The CASE guard is load-bearing: AND does not guarantee evaluation order in PostgreSQL, so
+# without it jsonb_array_elements can run against a non-array value (a hand-edited or corrupt
+# modifiers entry) and abort the whole statement for every team.
+_FLAT_ENTRY_PREDICATE = """
+CASE WHEN jsonb_typeof(modifiers->'customBotDefinitions') = 'array' THEN
+ EXISTS (
+ SELECT 1
+ FROM jsonb_array_elements(modifiers->'customBotDefinitions') AS entry
+ WHERE jsonb_typeof(entry) = 'object' AND NOT (entry ? 'items') AND entry ? 'key'
+ )
+ELSE false END
+"""
+
+_FIND_TEAMS_SQL = f"""
+SELECT id,
+ (
+ SELECT count(*)
+ FROM jsonb_array_elements(modifiers->'customBotDefinitions') AS entry
+ WHERE jsonb_typeof(entry) = 'object' AND NOT (entry ? 'items') AND entry ? 'key'
+ ) AS flat_rules
+FROM posthog_team
+WHERE {_FLAT_ENTRY_PREDICATE}
+ORDER BY id
+"""
+
+_MIGRATE_TEAM_SQL = f"""
+UPDATE posthog_team
+SET modifiers = jsonb_set(
+ modifiers,
+ '{{customBotDefinitions}}',
+ (
+ SELECT jsonb_agg(
+ CASE
+ WHEN jsonb_typeof(entry) != 'object' OR entry ? 'items' OR NOT (entry ? 'key') THEN entry
+ ELSE jsonb_build_object(
+ 'id', entry->'id',
+ 'name', entry->'name',
+ 'combiner', 'AND',
+ 'items', jsonb_build_array(
+ jsonb_build_object(
+ 'id', (entry->>'id') || '-condition',
+ 'key', entry->'key',
+ 'matcher', entry->'matcher',
+ 'pattern', entry->'pattern'
+ )
+ )
+ ) || CASE
+ WHEN entry ? 'category' THEN jsonb_build_object('category', entry->'category')
+ ELSE '{{}}'::jsonb
+ END
+ END
+ )
+ FROM jsonb_array_elements(modifiers->'customBotDefinitions') AS entry
+ )
+)
+WHERE id = %s
+ AND {_FLAT_ENTRY_PREDICATE}
+"""
+
+
+def find_teams_with_flat_rules() -> list[FlatRuleTeam]:
+ with connection.cursor() as cursor:
+ cursor.execute(_FIND_TEAMS_SQL)
+ return [FlatRuleTeam(team_id=row[0], flat_rules=row[1]) for row in cursor.fetchall()]
+
+
+def migrate_team(team_id: int) -> bool:
+ with connection.cursor() as cursor:
+ cursor.execute(_MIGRATE_TEAM_SQL, [team_id])
+ return cursor.rowcount == 1
diff --git a/products/web_analytics/backend/management/commands/migrate_custom_bot_rules.py b/products/web_analytics/backend/management/commands/migrate_custom_bot_rules.py
new file mode 100644
index 000000000000..5b8a911fc1c9
--- /dev/null
+++ b/products/web_analytics/backend/management/commands/migrate_custom_bot_rules.py
@@ -0,0 +1,33 @@
+from typing import Any
+
+from django.core.management.base import BaseCommand
+
+from products.web_analytics.backend.custom_bot_rules_migration import find_teams_with_flat_rules, migrate_team
+
+
+class Command(BaseCommand):
+ help = (
+ "Rewrite pre-combiner flat custom bot rules stored on team.modifiers into the "
+ "multi-condition shape. Dry run by default; pass --execute to apply."
+ )
+
+ def add_arguments(self, parser: Any) -> None:
+ parser.add_argument("--execute", action="store_true", help="Apply the rewrite. Without it, only report.")
+
+ def handle(self, *args: Any, **options: Any) -> None:
+ teams = find_teams_with_flat_rules()
+ if not teams:
+ self.stdout.write("No teams with flat custom bot rules found.")
+ return
+
+ total_rules = sum(team.flat_rules for team in teams)
+ self.stdout.write(f"{len(teams)} team(s) with {total_rules} flat rule(s):")
+ for team in teams:
+ self.stdout.write(f" team {team.team_id}: {team.flat_rules} flat rule(s)")
+
+ if not options["execute"]:
+ self.stdout.write("Dry run - nothing changed. Re-run with --execute to apply.")
+ return
+
+ migrated = sum(1 for team in teams if migrate_team(team.team_id))
+ self.stdout.write(f"Migrated {migrated}/{len(teams)} team(s).")
diff --git a/products/web_analytics/backend/management/commands/test/test_migrate_custom_bot_rules.py b/products/web_analytics/backend/management/commands/test/test_migrate_custom_bot_rules.py
new file mode 100644
index 000000000000..3ce28998f266
--- /dev/null
+++ b/products/web_analytics/backend/management/commands/test/test_migrate_custom_bot_rules.py
@@ -0,0 +1,87 @@
+from posthog.test.base import BaseTest
+
+from posthog.models.team import Team
+
+from products.web_analytics.backend.custom_bot_rules_migration import (
+ FlatRuleTeam,
+ find_teams_with_flat_rules,
+ migrate_team,
+)
+from products.web_analytics.backend.hogql_queries.custom_bot_definitions import parse_rules
+
+FLAT_RULE = {"id": "r1", "name": "Acme", "key": "$raw_user_agent", "matcher": "contains", "pattern": "AcmeBot"}
+FLAT_RULE_WITH_CATEGORY = {
+ "id": "r2",
+ "name": "Office",
+ "key": "$ip",
+ "matcher": "cidr",
+ "pattern": "192.0.2.0/24",
+ "category": "monitoring",
+}
+NEW_SHAPE_RULE = {
+ "id": "r3",
+ "name": "Headless",
+ "combiner": "AND",
+ "items": [{"id": "r3-w", "key": "$screen_width", "matcher": "exact", "pattern": "800"}],
+}
+
+
+class TestMigrateCustomBotRules(BaseTest):
+ def _set_rules(self, rules: list) -> None:
+ self.team.modifiers = {"customBotDefinitions": rules, "bounceRateDurationSeconds": 42}
+ self.team.save(update_fields=["modifiers"])
+
+ def test_rewrites_flat_rules_and_leaves_everything_else_alone(self):
+ # The rewrite must produce exactly what the current reader parses, touch only the
+ # customBotDefinitions key, and pass new-shape and garbage entries through unchanged —
+ # a clobbered sibling modifier or a mangled entry would silently change query behavior.
+ self._set_rules([FLAT_RULE, FLAT_RULE_WITH_CATEGORY, NEW_SHAPE_RULE, "garbage"])
+
+ assert find_teams_with_flat_rules() == [FlatRuleTeam(team_id=self.team.pk, flat_rules=2)]
+ assert migrate_team(self.team.pk)
+
+ self.team.refresh_from_db()
+ assert self.team.modifiers["bounceRateDurationSeconds"] == 42
+ stored = self.team.modifiers["customBotDefinitions"]
+ assert stored[2] == NEW_SHAPE_RULE
+ assert stored[3] == "garbage"
+ assert stored[0] == {
+ "id": "r1",
+ "name": "Acme",
+ "combiner": "AND",
+ "items": [{"id": "r1-condition", "key": "$raw_user_agent", "matcher": "contains", "pattern": "AcmeBot"}],
+ }
+ assert stored[1]["category"] == "monitoring"
+
+ parsed = parse_rules(stored)
+ assert [rule.name for rule in parsed] == ["Acme", "Office", "Headless"]
+
+ def test_is_idempotent(self):
+ self._set_rules([FLAT_RULE])
+ assert migrate_team(self.team.pk)
+ self.team.refresh_from_db()
+ first_pass = self.team.modifiers["customBotDefinitions"]
+
+ # A converted team must not qualify again, and re-running must not change the data.
+ assert find_teams_with_flat_rules() == []
+ assert not migrate_team(self.team.pk)
+ self.team.refresh_from_db()
+ assert self.team.modifiers["customBotDefinitions"] == first_pass
+
+ def test_ignores_teams_without_flat_rules(self):
+ self._set_rules([NEW_SHAPE_RULE])
+
+ assert find_teams_with_flat_rules() == []
+ assert not migrate_team(self.team.pk)
+
+ def test_non_array_value_does_not_abort_the_scan(self):
+ # jsonb_array_elements raises on a non-array, and without the CASE guard one such row
+ # would abort the fleet-wide scan and block every other team's migration.
+ self.team.modifiers = {"customBotDefinitions": {"not": "an array"}}
+ self.team.save(update_fields=["modifiers"])
+ other = Team.objects.create(
+ organization=self.organization, name="flat", modifiers={"customBotDefinitions": [FLAT_RULE]}
+ )
+
+ assert find_teams_with_flat_rules() == [FlatRuleTeam(team_id=other.pk, flat_rules=1)]
+ assert not migrate_team(self.team.pk)
diff --git a/products/web_analytics/dags/migrate_custom_bot_rules.py b/products/web_analytics/dags/migrate_custom_bot_rules.py
new file mode 100644
index 000000000000..ffe34a785488
--- /dev/null
+++ b/products/web_analytics/dags/migrate_custom_bot_rules.py
@@ -0,0 +1,54 @@
+"""Operator job to rewrite flat custom bot rules into the multi-condition shape.
+
+The multi-condition bot rules change dropped support for the original flat rule shape
+({key, matcher, pattern} on the rule itself), so teams with flat rules stored on
+team.modifiers have those rules silently skipped at query time until they are rewritten.
+
+Run manually from the Dagster UI. With no run config it only lists the affected teams
+(dry run); the rewrite requires explicitly setting `execute: true`. Each team is one
+atomic UPDATE that touches only the customBotDefinitions key of team.modifiers, so other
+modifier keys and their query cache keys are unaffected, and re-running is a no-op.
+"""
+
+import dagster
+
+from posthog.dags.common import JobOwners
+
+from products.web_analytics.backend.custom_bot_rules_migration import find_teams_with_flat_rules, migrate_team
+
+
+class MigrateCustomBotRulesConfig(dagster.Config):
+ execute: bool = False
+
+
+def migrate_custom_bot_rules_op(context: dagster.OpExecutionContext, config: MigrateCustomBotRulesConfig) -> None:
+ teams = find_teams_with_flat_rules()
+ if not teams:
+ context.log.info("No teams with flat custom bot rules found")
+ return
+
+ total_rules = sum(team.flat_rules for team in teams)
+ context.log.info(f"{len(teams)} team(s) with {total_rules} flat rule(s)")
+ for team in teams:
+ context.log.info(f"team {team.team_id}: {team.flat_rules} flat rule(s)")
+
+ if not config.execute:
+ context.log.info("Dry run: no `execute: true` in run config, nothing changed")
+ return
+
+ migrated = sum(1 for team in teams if migrate_team(team.team_id))
+ context.log.info(f"Migrated {migrated}/{len(teams)} team(s)")
+
+
+ name="web_analytics_migrate_custom_bot_rules",
+ description=(
+ "Rewrite flat custom bot rules stored on team.modifiers into the multi-condition "
+ "shape. Without run config this is a dry run that lists affected teams; set "
+ "`execute: true` to apply the rewrite."
+ ),
+ tags={"owner": JobOwners.TEAM_WEB_ANALYTICS.value},
+)
+def web_analytics_migrate_custom_bot_rules_job() -> None:
+ migrate_custom_bot_rules_op()
diff --git a/products/web_analytics/dags/tests/test_migrate_custom_bot_rules.py b/products/web_analytics/dags/tests/test_migrate_custom_bot_rules.py
new file mode 100644
index 000000000000..26e629e00b3a
--- /dev/null
+++ b/products/web_analytics/dags/tests/test_migrate_custom_bot_rules.py
@@ -0,0 +1,31 @@
+import pytest
+
+import dagster
+
+from posthog.models.organization import Organization
+from posthog.models.team import Team
+
+from products.web_analytics.dags.migrate_custom_bot_rules import web_analytics_migrate_custom_bot_rules_job
+
+FLAT_RULE = {"id": "r1", "name": "Acme", "key": "$raw_user_agent", "matcher": "contains", "pattern": "AcmeBot"}
+
+
+def _run(config: dict | None) -> dagster.ExecuteInProcessResult:
+ run_config = {"ops": {"migrate_custom_bot_rules_op": {"config": config}}} if config else None
+ return web_analytics_migrate_custom_bot_rules_job.execute_in_process(run_config=run_config, raise_on_error=False)
+
+
[email protected]("config,expect_migrated", [(None, False), ({"execute": True}, True)])
+def test_job_migrates_only_when_execute_is_set(config, expect_migrated):
+ org = Organization.objects.create(name="test-org-bot-rules")
+ team = Team.objects.create(
+ organization=org, name="test-team-bot-rules", modifiers={"customBotDefinitions": [FLAT_RULE]}
+ )
+
+ result = _run(config)
+ assert result.success
+
+ team.refresh_from_db()
+ migrated = "items" in team.modifiers["customBotDefinitions"][0]
+ assert migrated is expect_migrated