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(wizard): report competitor changes from wizard scans (#115758)

Rafael Audibert83cb2804079c
diff --git a/products/wizard/backend/logic/scans.py b/products/wizard/backend/logic/scans.py
index f1d420891c3d..94e2ecfc75e4 100644
--- a/products/wizard/backend/logic/scans.py
+++ b/products/wizard/backend/logic/scans.py
@@ -2,13 +2,42 @@ from datetime import datetime
from django.db import connection, transaction
+from posthog.dataclasses import frozen
+from posthog.event_usage import report_user_or_team_action
+from posthog.models import Team, User
from posthog.models.scoping.manager import resolve_effective_team_id
from products.wizard.backend.facade.contracts import RecordWizardScanInput, WizardScanResult, WizardScanTool
from products.wizard.backend.models import WizardDetectedTool, WizardScan
+from products.wizard.backend.observability.config import (
+ WIZARD_COMPETITOR_DETECTED_EVENT,
+ WIZARD_COMPETITOR_REMOVED_EVENT,
+)
from products.wizard.backend.tool_catalog.catalog import classify_tool
+@frozen
+class _CompetitorSighting:
+ kind: str
+ competes_with: tuple[str, ...]
+ first_detection: bool
+ # Seen again after a scan of the workspace no longer found it.
+ returned: bool
+ signal_sources: tuple[str, ...]
+
+
+@frozen
+class _CompetitorRemoval:
+ kind: str
+ competes_with: tuple[str, ...]
+
+
+@frozen
+class _ScanChanges:
+ sightings: tuple[_CompetitorSighting, ...]
+ removals: tuple[_CompetitorRemoval, ...]
+
+
def _signals_json(tool: WizardScanTool) -> list[dict[str, str | None]]:
return [{"source": signal.source, "name": signal.name, "file": signal.file} for signal in tool.signals]
@@ -62,7 +91,11 @@ def record_scan(params: RecordWizardScanInput) -> WizardScanResult:
.using("default")
.filter(workspace_fingerprint=params.workspace_fingerprint)
}
- _apply_scan(scan, tools, existing, complete=params.complete)
+ changes = _apply_scan(scan, tools, existing, complete=params.complete)
+ # robust: the scan is already stored, so an analytics failure must not turn the request into a 500.
+ # A lambda rather than functools.partial, because Django logs a robust callback's failure through
+ # its __qualname__, which a partial does not have.
+ transaction.on_commit(lambda: _report_competitor_changes(scan, changes), robust=True)
return WizardScanResult(id=scan.id, created=True)
@@ -79,13 +112,16 @@ def _lock_workspace(team_id: int, workspace_fingerprint: str) -> None:
def _apply_scan(
scan: WizardScan, tools: dict[str, WizardScanTool], existing: dict[str, WizardDetectedTool], *, complete: bool
-) -> None:
+) -> _ScanChanges:
scanned_at: datetime = scan.scanned_at
to_create: list[WizardDetectedTool] = []
to_update: list[WizardDetectedTool] = []
+ sightings: list[_CompetitorSighting] = []
+ removals: list[_CompetitorRemoval] = []
for kind, tool in tools.items():
row = existing.get(kind)
+ returned = row is not None and row.removed_at is not None
if row is None:
row = WizardDetectedTool(
team_id=scan.team_id,
@@ -103,12 +139,29 @@ def _apply_scan(
row.removed_in_scan = None
row.removed_at = None
_classify(row)
+ if row.competes_with:
+ sightings.append(
+ _CompetitorSighting(
+ kind=kind,
+ competes_with=tuple(row.competes_with),
+ first_detection=kind not in existing,
+ returned=returned,
+ signal_sources=tuple(sorted({signal.source for signal in tool.signals})),
+ )
+ )
for kind, row in existing.items():
if complete and kind not in tools and row.removed_at is None:
row.removed_in_scan = scan
row.removed_at = scanned_at
to_update.append(row)
+ if row.competes_with:
+ removals.append(
+ _CompetitorRemoval(
+ kind=kind,
+ competes_with=tuple(row.competes_with),
+ )
+ )
# Scoped explicitly, because the ambient team context is not always the scanned team.
tools_of_team = WizardDetectedTool.objects.for_team(scan.team_id)
@@ -125,3 +178,47 @@ def _apply_scan(
"removed_at",
],
)
+ return _ScanChanges(sightings=tuple(sightings), removals=tuple(removals))
+
+
+def _report_competitor_changes(scan: WizardScan, changes: _ScanChanges) -> None:
+ if not changes.sightings and not changes.removals:
+ return
+ team = Team.objects.select_related("organization").get(id=scan.team_id)
+ user = User.objects.filter(id=scan.created_by_id).first() if scan.created_by_id else None
+ scan_properties = {
+ "program": scan.program,
+ "wizard_version": scan.wizard_version,
+ "wizard_session_id": scan.session_id,
+ "workspace_fingerprint": scan.workspace_fingerprint,
+ }
+
+ def report(event: str, properties: dict[str, object]) -> None:
+ report_user_or_team_action(
+ event,
+ {**scan_properties, **properties},
+ user=user,
+ team=team,
+ # The user's current organization can differ from the scanned project's.
+ organization=team.organization,
+ )
+
+ for sighting in changes.sightings:
+ report(
+ WIZARD_COMPETITOR_DETECTED_EVENT,
+ {
+ "kind": sighting.kind,
+ "competes_with": list(sighting.competes_with),
+ "first_detection": sighting.first_detection,
+ "returned": sighting.returned,
+ "signal_sources": list(sighting.signal_sources),
+ },
+ )
+ for removal in changes.removals:
+ report(
+ WIZARD_COMPETITOR_REMOVED_EVENT,
+ {
+ "kind": removal.kind,
+ "competes_with": list(removal.competes_with),
+ },
+ )
diff --git a/products/wizard/backend/observability/config.py b/products/wizard/backend/observability/config.py
index 6da8cc58e836..b430c940bfa3 100644
--- a/products/wizard/backend/observability/config.py
+++ b/products/wizard/backend/observability/config.py
@@ -4,6 +4,8 @@ WIZARD_RUN_STAGE_ENTERED_EVENT = "wizard run stage entered"
WIZARD_RUN_FINISHED_EVENT = "wizard run finished"
WIZARD_WORKER_USAGE_RECORDED_EVENT = "wizard worker usage recorded"
WIZARD_RUN_ARTIFACT_CREATED_EVENT = "wizard run artifact created"
+WIZARD_COMPETITOR_DETECTED_EVENT = "wizard competitor detected"
+WIZARD_COMPETITOR_REMOVED_EVENT = "wizard competitor removed"
WIZARD_RUN_DURATION_BUCKETS = (30, 60, 120, 300, 600, 1200, 1800, 3600, 7200)
WIZARD_WORKER_LIFETIME_BUCKETS = (30, 60, 120, 300, 600, 1200, 1800, 2700, 3600, 4500)
diff --git a/products/wizard/backend/tests/scans/test_logic.py b/products/wizard/backend/tests/scans/test_logic.py
index 13730f936385..beb1bea68f4e 100644
--- a/products/wizard/backend/tests/scans/test_logic.py
+++ b/products/wizard/backend/tests/scans/test_logic.py
@@ -1,8 +1,9 @@
from datetime import UTC, datetime, timedelta
import pytest
+from unittest.mock import patch
-from posthog.models import Team
+from posthog.models import Organization, Team, User
from products.wizard.backend.facade import api as wizard_facade
from products.wizard.backend.facade.contracts import (
@@ -19,12 +20,18 @@ START = datetime(2026, 5, 19, 10, 0, tzinfo=UTC)
def _scan(
- team: Team, session_id: str, hours: int, kinds: list[str], workspace: str = WORKSPACE, complete: bool = True
+ team: Team,
+ session_id: str,
+ hours: int,
+ kinds: list[str],
+ workspace: str = WORKSPACE,
+ created_by_id: int | None = None,
+ complete: bool = True,
) -> WizardScanResult:
return wizard_facade.record_scan(
RecordWizardScanInput(
team_id=team.id,
- created_by_id=None,
+ created_by_id=created_by_id,
session_id=session_id,
program="posthog-integration",
wizard_version="2.0.0",
@@ -125,3 +132,63 @@ def test_partial_scan_adds_what_it_saw_and_removes_nothing(team: Team) -> None:
tools = _tools(team)
assert {kind for kind, row in tools.items() if row.removed_at is None} == {"Stripe", "Amplitude", "Sentry"}
+
+
+def test_reports_competitor_changes_once_per_scan(team: Team, django_capture_on_commit_callbacks) -> None:
+ scans = [
+ ("s1", 0, ["Amplitude", "Stripe"]),
+ ("s2", 1, []),
+ ("s2", 2, ["Amplitude"]),
+ ("s3", 3, ["Amplitude"]),
+ ("s4", 4, []),
+ ]
+ with patch("posthoganalytics.capture") as capture:
+ for session_id, hours, kinds in scans:
+ with django_capture_on_commit_callbacks(execute=True):
+ _scan(team, session_id, hours, kinds)
+
+ events = [
+ (
+ call.kwargs["event"],
+ call.kwargs["properties"]["kind"],
+ call.kwargs["properties"].get("first_detection"),
+ call.kwargs["properties"].get("returned"),
+ )
+ for call in capture.call_args_list
+ ]
+ assert events == [
+ ("wizard competitor detected", "Amplitude", True, False),
+ ("wizard competitor removed", "Amplitude", None, None),
+ ("wizard competitor detected", "Amplitude", False, True),
+ ("wizard competitor removed", "Amplitude", None, None),
+ ]
+ first_properties = capture.call_args_list[0].kwargs["properties"]
+ assert (first_properties["competes_with"], first_properties["wizard_version"]) == (["product_analytics"], "2.0.0")
+
+
+def test_failing_competitor_report_keeps_the_scan(team: Team, django_capture_on_commit_callbacks) -> None:
+ with (
+ patch("products.wizard.backend.logic.scans.report_user_or_team_action", side_effect=RuntimeError),
+ django_capture_on_commit_callbacks(execute=True),
+ ):
+ result = _scan(team, "s1", 0, ["Amplitude"])
+
+ assert result.created is True
+ assert set(_tools(team)) == {"Amplitude"}
+
+
+def test_competitor_events_belong_to_the_scanned_projects_organization(
+ team: Team, django_capture_on_commit_callbacks
+) -> None:
+ other_organization = Organization.objects.create(name="Other organization")
+ user = User.objects.create_and_join(other_organization, "[email protected]", None)
+ user.organizations.add(team.organization)
+ assert user.current_organization == other_organization
+
+ with patch("posthoganalytics.capture") as capture, django_capture_on_commit_callbacks(execute=True):
+ _scan(team, "s1", 0, ["Amplitude"], created_by_id=user.id)
+
+ assert capture.call_args.kwargs["groups"]["organization"] == str(team.organization_id)