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(navigation): add a dagster job that moves custom products to stars (#117213)

Rafael Audibert0a7789cd59f0
diff --git a/posthog/dags/backfill_starred_products.py b/posthog/dags/backfill_starred_products.py
new file mode 100644
index 000000000000..3a1bac33a9df
--- /dev/null
+++ b/posthog/dags/backfill_starred_products.py
@@ -0,0 +1,168 @@
+"""
+One-off Dagster job that moves sidebar custom products (`UserProductList`) to starred products.
+
+For every user who has not finished the starred products setup:
+ - In each project with at most `MAX_PRODUCTS_TO_STAR` enabled custom products, star them all.
+ - In a project with more, star nothing. A list that long is a catalog, not a choice.
+ - Mark the setup as completed, so a re-run skips the user and the setup card no longer shows.
+
+Safe to re-run: users who finished the setup are skipped, and products the user already starred
+are not starred twice. Run it manually from the Dagster UI. Set
+ops.backfill_starred_products_op.config.dry_run=True to preview.
+"""
+
+from collections import defaultdict
+
+from django.db.models.functions import Lower
+
+import dagster
+
+from posthog.dags.common import JobOwners
+from posthog.dataclasses import frozen
+from posthog.models.file_system.starred_products import (
+ mark_starred_products_setup_completed,
+ star_products,
+ starred_products_setup_completed,
+)
+from posthog.models.file_system.user_product_list import UserProductList
+from posthog.models.team import Team
+from posthog.models.user import User
+from posthog.products import Products
+
+MAX_PRODUCTS_TO_STAR = 6
+
+
+@frozen
+class StarredProductsBackfillOutcome:
+ projects_starred: int
+ projects_over_limit: int
+ stars_created: int
+
+
+def backfill_starred_products_for_user(user: User, *, dry_run: bool) -> StarredProductsBackfillOutcome:
+ known_paths = set(Products.get_product_paths())
+ # Custom products belong to an environment, but the sidebar shows the stars of the whole project.
+ # So each project gets one deduplicated list, and the limit applies to that list.
+ paths_by_project_id: dict[int, list[str]] = defaultdict(list)
+ team_ids_by_project_id: dict[int, set[int]] = defaultdict(set)
+ for project_id, team_id, product_path in (
+ UserProductList.objects.filter(user=user, enabled=True)
+ .order_by("team__project_id", Lower("product_path"))
+ .values_list("team__project_id", "team_id", "product_path")
+ ):
+ team_ids_by_project_id[project_id].add(team_id)
+ # A product removed from the catalog can't be starred, so it doesn't count towards the limit.
+ if product_path in known_paths and product_path not in paths_by_project_id[project_id]:
+ paths_by_project_id[project_id].append(product_path)
+
+ projects_starred = projects_over_limit = stars_created = 0
+ for project_id, paths in paths_by_project_id.items():
+ if not paths:
+ continue
+ if len(paths) > MAX_PRODUCTS_TO_STAR:
+ projects_over_limit += 1
+ continue
+ projects_starred += 1
+ if not dry_run:
+ # The main environment shares its id with the project. Fall back to the oldest one the user has.
+ team_ids = team_ids_by_project_id[project_id]
+ team_id = project_id if project_id in team_ids else min(team_ids)
+ stars_created += star_products(user, Team.objects.only("id", "project_id").get(id=team_id), paths)
+
+ if not dry_run:
+ mark_starred_products_setup_completed(user)
+
+ return StarredProductsBackfillOutcome(
+ projects_starred=projects_starred, projects_over_limit=projects_over_limit, stars_created=stars_created
+ )
+
+
+ out=dagster.DynamicOut(list[int]),
+ config_schema={
+ "user_ids": dagster.Field(
+ dagster.Array(dagster.Int),
+ default_value=[],
+ is_required=False,
+ description="Specific user IDs to process. If empty, processes every user with custom products.",
+ ),
+ "batch_size": dagster.Field(dagster.Int, default_value=500, is_required=False),
+ },
+)
+def get_custom_products_user_ids_op(context: dagster.OpExecutionContext):
+ user_ids: list[int] = context.op_config["user_ids"] or list(
+ UserProductList.objects.filter(enabled=True).order_by("user_id").values_list("user_id", flat=True).distinct()
+ )
+ batch_size: int = context.op_config["batch_size"]
+ context.log.info(f"Processing {len(user_ids)} users in batches of {batch_size}")
+ for i in range(0, len(user_ids), batch_size):
+ yield dagster.DynamicOutput(user_ids[i : i + batch_size], mapping_key=f"batch_{i // batch_size}")
+
+
+ config_schema={
+ "dry_run": dagster.Field(
+ dagster.Bool,
+ default_value=False,
+ description="If True, count what would change but don't write anything.",
+ ),
+ },
+)
+def backfill_starred_products_op(context: dagster.OpExecutionContext, user_ids: list[int]) -> dict[str, int]:
+ dry_run: bool = context.op_config["dry_run"]
+ totals = {
+ "users_migrated": 0,
+ "skipped_already_completed": 0,
+ "skipped_errored": 0,
+ "projects_starred": 0,
+ "projects_over_limit": 0,
+ "stars_created": 0,
+ }
+
+ # is_active is read by User.from_db, so leaving it out costs a query per user.
+ for user in User.objects.filter(id__in=user_ids).only("id", "ui_configuration", "is_active"):
+ if starred_products_setup_completed(user):
+ totals["skipped_already_completed"] += 1
+ continue
+ try:
+ outcome = backfill_starred_products_for_user(user, dry_run=dry_run)
+ except Exception as e:
+ context.log.warning(f"user {user.id}: failed to backfill starred products ({e!r}); skipping")
+ totals["skipped_errored"] += 1
+ continue
+ totals["users_migrated"] += 1
+ totals["projects_starred"] += outcome.projects_starred
+ totals["projects_over_limit"] += outcome.projects_over_limit
+ totals["stars_created"] += outcome.stars_created
+
+ context.log.info(f"Batch: dry_run={dry_run}, {totals}")
+ context.add_output_metadata(
+ {"dry_run": dagster.MetadataValue.bool(dry_run)}
+ | {key: dagster.MetadataValue.int(value) for key, value in totals.items()}
+ )
+ return totals
+
+
+def aggregate_starred_products_backfill_op(context: dagster.OpExecutionContext, results: list[dict[str, int]]) -> None:
+ totals: dict[str, int] = defaultdict(int)
+ for result in results:
+ for key, value in result.items():
+ totals[key] += value
+ context.log.info(f"Job complete: {dict(totals)}")
+ context.add_output_metadata({key: dagster.MetadataValue.int(value) for key, value in totals.items()})
+
+
+ description=(
+ "Move sidebar custom products to starred products for users who have not finished the starred "
+ f"products setup. Projects with more than {MAX_PRODUCTS_TO_STAR} custom products get no stars. "
+ "Every migrated user is marked as having finished the setup. "
+ "Set ops.backfill_starred_products_op.config.dry_run=True to preview."
+ ),
+ tags={"owner": JobOwners.TEAM_GROWTH.value},
+)
+def backfill_starred_products_job():
+ user_ids = get_custom_products_user_ids_op()
+ results = user_ids.map(backfill_starred_products_op)
+ aggregate_starred_products_backfill_op(results.collect())
diff --git a/posthog/dags/locations/analytics_platform.py b/posthog/dags/locations/analytics_platform.py
index db0f1e788a55..6c0c25273bad 100644
--- a/posthog/dags/locations/analytics_platform.py
+++ b/posthog/dags/locations/analytics_platform.py
@@ -3,6 +3,7 @@ import dagster
from posthog.dags import sessions, sessions_v1_cleanup
from posthog.dags.backfill_internal_test_users_cohort import backfill_internal_test_users_cohort_job
from posthog.dags.backfill_persons_on_events_mode import backfill_persons_on_events_mode_job
+from posthog.dags.backfill_starred_products import backfill_starred_products_job
from posthog.dags.sessions import (
experimental_sessions_backfill_job,
experimental_sessions_v3_backfill,
@@ -19,6 +20,7 @@ defs = dagster.Definitions(
experimental_sessions_backfill_job,
backfill_internal_test_users_cohort_job,
backfill_persons_on_events_mode_job,
+ backfill_starred_products_job,
],
loggers=loggers,
resources=resources,
diff --git a/posthog/dags/tests/test_backfill_starred_products.py b/posthog/dags/tests/test_backfill_starred_products.py
new file mode 100644
index 000000000000..e7f3315a53e3
--- /dev/null
+++ b/posthog/dags/tests/test_backfill_starred_products.py
@@ -0,0 +1,89 @@
+from posthog.test.base import BaseTest
+
+from dagster import build_op_context
+from parameterized import parameterized
+
+from posthog.dags.backfill_starred_products import MAX_PRODUCTS_TO_STAR, backfill_starred_products_op
+from posthog.models.file_system.file_system_shortcut import FileSystemShortcut
+from posthog.models.file_system.starred_products import starred_products_setup_completed
+from posthog.models.file_system.user_product_list import UserProductList
+from posthog.models.team import Team
+from posthog.models.user import User
+from posthog.products import Products
+
+
+class TestBackfillStarredProducts(BaseTest):
+ def _starred_paths(self, user: User, team: Team) -> list[str]:
+ return list(
+ FileSystemShortcut.objects.filter(user=user, team=team).order_by("order").values_list("path", flat=True)
+ )
+
+ def _add_custom_products(self, user: User, team: Team, paths: list[str], *, enabled: bool = True) -> None:
+ UserProductList.objects.bulk_create(
+ [UserProductList(user=user, team=team, product_path=path, enabled=enabled) for path in paths]
+ )
+
+ def test_stars_small_lists_skips_long_lists_and_completes_setup(self) -> None:
+ paths = sorted(Products.get_product_paths(), key=str.lower)[: MAX_PRODUCTS_TO_STAR + 1]
+ user = User.objects.create_user(email="[email protected]", password="password", first_name="User")
+ user.ui_configuration = {"version": 1, "sidebar": {"density": "compact"}}
+ user.save()
+ long_list_team = Team.objects.create(organization=self.organization, name="Long list")
+ self._add_custom_products(user, self.team, paths[:MAX_PRODUCTS_TO_STAR])
+ self._add_custom_products(user, self.team, [paths[MAX_PRODUCTS_TO_STAR]], enabled=False)
+ self._add_custom_products(user, long_list_team, paths)
+
+ result = backfill_starred_products_op(build_op_context(), [user.id])
+
+ assert self._starred_paths(user, self.team) == paths[:MAX_PRODUCTS_TO_STAR]
+ assert self._starred_paths(user, long_list_team) == []
+ user.refresh_from_db()
+ assert starred_products_setup_completed(user)
+ assert (user.ui_configuration or {})["sidebar"]["density"] == "compact"
+ assert result["users_migrated"] == 1
+ assert result["projects_starred"] == 1
+ assert result["projects_over_limit"] == 1
+
+ @parameterized.expand([("dry_run", True), ("already_completed", False)])
+ def test_writes_nothing(self, _name: str, dry_run: bool) -> None:
+ user = User.objects.create_user(email="[email protected]", password="password", first_name="User")
+ if not dry_run:
+ user.ui_configuration = {"version": 1, "sidebar": {"starred_products_setup_completed": True}}
+ user.save()
+ self._add_custom_products(user, self.team, ["Session replay"])
+
+ backfill_starred_products_op(build_op_context(op_config={"dry_run": dry_run}), [user.id])
+
+ assert self._starred_paths(user, self.team) == []
+ user.refresh_from_db()
+ assert starred_products_setup_completed(user) is not dry_run
+
+ def test_keeps_existing_stars_without_duplicating_them(self) -> None:
+ user = User.objects.create_user(email="[email protected]", password="password", first_name="User")
+ FileSystemShortcut.objects.create(team=self.team, user=user, path="Session replay", type="session_replay")
+ self._add_custom_products(user, self.team, ["Error tracking", "Session replay"])
+
+ backfill_starred_products_op(build_op_context(), [user.id])
+
+ assert self._starred_paths(user, self.team) == ["Session replay", "Error tracking"]
+
+ @parameterized.expand([("at_the_limit", 2, 6), ("over_the_limit", 3, 0)])
+ def test_applies_the_limit_to_each_project_across_its_environments(
+ self, _name: str, extra_in_second_environment: int, expected_stars: int
+ ) -> None:
+ paths = sorted(Products.get_product_paths(), key=str.lower)
+ user = User.objects.create_user(email="[email protected]", password="password", first_name="User")
+ second_environment = Team.objects.create(organization=self.organization, project=self.project, name="Staging")
+ self._add_custom_products(user, self.team, paths[:4])
+ # Two products overlap, so they count once.
+ self._add_custom_products(user, second_environment, paths[2 : 4 + extra_in_second_environment])
+
+ backfill_starred_products_op(build_op_context(), [user.id])
+
+ starred = list(
+ FileSystemShortcut.objects.filter(user=user, team__project_id=self.project.id).values_list(
+ "path", flat=True
+ )
+ )
+ assert sorted(starred, key=str.lower) == paths[: 4 + extra_in_second_environment][:expected_stars]
+ assert len(starred) == len(set(starred))
diff --git a/posthog/models/file_system/starred_products.py b/posthog/models/file_system/starred_products.py
index de26a0eeff56..1d5a898a583d 100644
--- a/posthog/models/file_system/starred_products.py
+++ b/posthog/models/file_system/starred_products.py
@@ -37,7 +37,7 @@ def _simple_sidebar_enabled(user: User, team: "Team") -> bool:
)
-def _mark_setup_completed(user: User) -> None:
+def mark_starred_products_setup_completed(user: User) -> None:
# Merge into the stored value under a short row lock, so a concurrent settings change is kept.
# NO KEY UPDATE is the lock the UPDATE takes anyway, and it does not block inserts of child rows.
with transaction.atomic():
@@ -53,31 +53,19 @@ def _mark_setup_completed(user: User) -> None:
user.save(update_fields=["ui_configuration"])
-def star_custom_products(user: User, team: "Team", product_paths: list[str], *, had_custom_products: bool) -> None:
- """Star products that were just added to a user's custom products, for simple sidebar users.
-
- The simple sidebar shows starred products instead of custom products, so every write that adds
- custom products calls this to keep the two in step. `had_custom_products` says whether the user
- had any custom products, in any project, before the write:
+def star_products(user: User, team: "Team", product_paths: list[str]) -> int:
+ """Star products on the user's sidebar for a team, after their existing stars. Returns how many were added.
- - A user with none is brand new, so their products are starred and the setup is marked done.
- - A user who finished the setup gets the new products starred too.
- - A user with custom products who has not done the setup yet is left alone. The setup card
- offers their whole list, so starring one suggestion must not complete it for them.
+ Unknown paths and products the user already starred are skipped, so a repeated call adds nothing.
"""
- if not product_paths:
- return
- completed = starred_products_setup_completed(user)
- if not completed and had_custom_products:
- return
- if not _simple_sidebar_enabled(user, team):
- return
-
products_by_path = {product.path: product for product in Products.products()}
with transaction.atomic():
# Concurrent writes for the same user would otherwise both miss the star and add it twice.
lock_user_shortcuts(team.pk, user.pk)
- user_shortcuts = FileSystemShortcut.objects.filter(surface_q(DEFAULT_SURFACE), team=team, user=user)
+ # The sidebar lists the stars of every environment in the project, so check them all.
+ user_shortcuts = FileSystemShortcut.objects.filter(
+ surface_q(DEFAULT_SURFACE), team__project_id=team.project_id, user=user
+ )
starred_paths = set(
user_shortcuts.filter(ref__isnull=True).exclude(type="folder").values_list("path", flat=True)
)
@@ -101,6 +89,30 @@ def star_custom_products(user: User, team: "Team", product_paths: list[str], *,
)
)
FileSystemShortcut.objects.bulk_create(to_create)
+ return len(to_create)
+
+
+def star_custom_products(user: User, team: "Team", product_paths: list[str], *, had_custom_products: bool) -> None:
+ """Star products that were just added to a user's custom products, for simple sidebar users.
+
+ The simple sidebar shows starred products instead of custom products, so every write that adds
+ custom products calls this to keep the two in step. `had_custom_products` says whether the user
+ had any custom products, in any project, before the write:
+
+ - A user with none is brand new, so their products are starred and the setup is marked done.
+ - A user who finished the setup gets the new products starred too.
+ - A user with custom products who has not done the setup yet is left alone. The setup card
+ offers their whole list, so starring one suggestion must not complete it for them.
+ """
+ if not product_paths:
+ return
+ completed = starred_products_setup_completed(user)
+ if not completed and had_custom_products:
+ return
+ if not _simple_sidebar_enabled(user, team):
+ return
+
+ star_products(user, team, product_paths)
if not completed:
- _mark_setup_completed(user)
+ mark_starred_products_setup_completed(user)