: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
chore(signals): route core, tasks and slack_app callers through the facade (#125847)
Julian Bez0a52c22e7795
diff --git a/posthog/dags/locations/signals.py b/posthog/dags/locations/signals.pyindex d6c504a9f79a..67f63b65594c 100644--- a/posthog/dags/locations/signals.py+++ b/posthog/dags/locations/signals.py@@ -1,12 +1,13 @@import dagster-from products.signals.dags.inbox_ranking.common import is_inbox_ranking_mirror_registered, is_inbox_ranking_registered-from products.signals.dags.inbox_ranking.dataset import dag as inbox_ranking_dataset-from products.signals.dags.inbox_ranking.mirror import dag as inbox_ranking_mirror-from products.signals.dags.inbox_ranking.training import (- dag as inbox_ranking_training,- promote as inbox_ranking_promote,- served as inbox_ranking_served,+from products.signals.backend.facade.dags import (+ inbox_ranking_dataset,+ inbox_ranking_mirror,+ inbox_ranking_promote,+ inbox_ranking_served,+ inbox_ranking_training,+ is_inbox_ranking_mirror_registered,+ is_inbox_ranking_registered,)from . import loggers, resourcesdiff --git a/posthog/dags/locations/signals_ml.py b/posthog/dags/locations/signals_ml.pyindex 8b590e09b978..cc00ef88aeae 100644--- a/posthog/dags/locations/signals_ml.py+++ b/posthog/dags/locations/signals_ml.py@@ -1,10 +1,10 @@import dagster-from products.signals.dags.inbox_ranking.common import is_inbox_ranking_registered-from products.signals.dags.inbox_ranking.nn import (- dag as inbox_ranking_nn,- experiments as inbox_ranking_nn_experiments,- pairs as inbox_ranking_nn_pairs,+from products.signals.backend.facade.dags_ml import (+ inbox_ranking_nn,+ inbox_ranking_nn_experiments,+ inbox_ranking_nn_pairs,+ is_inbox_ranking_registered,)from . import loggers, resourcesdiff --git a/posthog/management/commands/start_temporal_worker.py b/posthog/management/commands/start_temporal_worker.pyindex ee8cc1f6eaaa..e78ae4a0e0b3 100644--- a/posthog/management/commands/start_temporal_worker.py+++ b/posthog/management/commands/start_temporal_worker.py@@ -308,12 +308,10 @@ from products.security.backend.facade.temporal import (ACTIVITIES as SECURITY_ACTIVITIES,WORKFLOWS as SECURITY_WORKFLOWS,)-from products.signals.backend.emission.temporal_settings import (+from products.signals.backend.facade.temporal import (+ ACTIVITIES as SIGNALS_PRODUCT_ACTIVITIES,EMIT_SIGNALS_ACTIVITIES as DATA_IMPORT_EMIT_SIGNALS_ACTIVITIES,EMIT_SIGNALS_WORKFLOWS as DATA_IMPORT_EMIT_SIGNALS_WORKFLOWS,-)-from products.signals.backend.temporal import (- ACTIVITIES as SIGNALS_PRODUCT_ACTIVITIES,SELF_DRIVING_ACTIVITIES,SELF_DRIVING_WORKFLOWS,WORKFLOWS as SIGNALS_PRODUCT_WORKFLOWS,diff --git a/posthog/push_notifications.py b/posthog/push_notifications.pyindex e9a4dd4420a5..d3f3ca689f77 100644--- a/posthog/push_notifications.py+++ b/posthog/push_notifications.py@@ -56,12 +56,9 @@ def mobile_push_delivery_allowed(user: User, data: dict[str, Any] | None) -> boo"posthog-code-mobile-push", user.distinct_id or f"user_{user.id}", send_feature_flag_events=False):return False- from products.access_control.backend.facade.user_access_control import (- UserAccessControl, # noqa: PLC0415 — keep access control off the startup path+ from products.signals.backend.facade.reports import ( # noqa: PLC0415 — keep signals off the startup path+ user_may_receive_report_push,)- from products.signals.backend.models import SignalReport # noqa: PLC0415 — keep signals off the startup path- from products.signals.backend.report_access import may_read_reports # noqa: PLC0415- from products.signals.backend.scout_authorship import report_is_hidden_from_inbox # noqa: PLC0415category: MobilePushCategory = ("reports" if payload.get("notificationKind") == "report_visible" else "report_updates"@@ -72,23 +69,7 @@ def mobile_push_delivery_allowed(user: User, data: dict[str, Any] | None) -> booreport_id = payload.get("report_id")if not isinstance(project_id, (int, str)) or not isinstance(report_id, str):return False- report = (- SignalReport.objects.filter(team_id=project_id, id=report_id)- .exclude(status__in=[SignalReport.Status.DELETED, SignalReport.Status.SUPPRESSED])- .select_related("team")- .first()- )- return bool(- report- and not report_is_hidden_from_inbox(report.team_id, str(report.id))- and User.objects.filter(- id=user.id,- is_active=True,- organization_membership__organization_id=report.team.organization_id,- ).exists()- and UserAccessControl(user=user, team=report.team).has_project_access- and may_read_reports(user=user, team=report.team)- )+ return user_may_receive_report_push(user=user, team_id=project_id, report_id=report_id)if not mobile_push_preference_enabled(user, "tasks") or not payload.get("taskId"):return Falsediff --git a/posthog/tasks/scheduled.py b/posthog/tasks/scheduled.pyindex 1af0bbea153f..b181d8eaa90b 100644--- a/posthog/tasks/scheduled.py+++ b/posthog/tasks/scheduled.py@@ -119,7 +119,7 @@ from products.mcp_registry.backend.facade.tasks import MCP_REGISTRY_SYNC_CRONTABfrom products.notebooks.backend.facade.tasks import cleanup_widget_snapshotsfrom products.pulse.backend.tasks import mark_stale_pulse_briefs_failedfrom products.reminders.backend.tasks import process_due_reminders-from products.signals.backend.tasks import (+from products.signals.backend.facade.tasks import (pause_inactive_signal_scouts,prune_expired_scratchpad_entries_task,reconcile_report_inbox_state_cache,diff --git a/posthog/tasks/test/test_usage_report.py b/posthog/tasks/test/test_usage_report.pyindex da2470dbf3b4..d68f07cf35c7 100644--- a/posthog/tasks/test/test_usage_report.py+++ b/posthog/tasks/test/test_usage_report.py@@ -102,6 +102,7 @@ from products.dashboards.backend.models.dashboard import Dashboardfrom products.data_modeling.backend.facade.models import DataWarehouseSavedQueryfrom products.feature_flags.backend.models.feature_flag import FeatureFlagfrom products.replay_vision.backend.models.replay_scanner import ReplayScanner, ScannerModel, ScannerType+from products.signals.backend.facade.billing import TeamSignalsCreditsfrom products.warehouse_sources.backend.facade.models import (DataWarehouseTable,ExternalDataJob,@@ -5200,8 +5201,12 @@ class TestAIEventsUsageReport(ClickhouseDestroyTablesMixin, TestCase, Clickhouseorg_ids = [str(org_a.id), str(org_b.id)]with patch(- "posthog.tasks.usage_report.get_signals_billing_credits_by_team",- return_value=[(team_a1.id, 1500), (team_a2.id, 1500), (team_b.id, 1500)],+ "posthog.tasks.usage_report.signals_billing_credits_by_team",+ return_value=[+ TeamSignalsCredits(team_id=team_a1.id, credits=1500),+ TeamSignalsCredits(team_id=team_a2.id, credits=1500),+ TeamSignalsCredits(team_id=team_b.id, credits=1500),+ ],) as signals_credits:totals = get_self_driving_credits_used_in_period_for_orgs(org_ids, period.start, period.end)diff --git a/posthog/tasks/usage_report.py b/posthog/tasks/usage_report.pyindex 0320f0c0ed8a..2e0bc9d563f5 100644--- a/posthog/tasks/usage_report.py+++ b/posthog/tasks/usage_report.py@@ -77,7 +77,7 @@ from products.replay_vision.backend.billing import ()from products.replay_vision.backend.models.replay_scanner import ReplayScannerfrom products.replay_vision.backend.quota import unreported_spend_by_org-from products.signals.backend.billing import credited_refund_credits_for_org, get_signals_billing_credits_by_team+from products.signals.backend.facade.billing import credited_refund_credits_for_org, signals_billing_credits_by_teamfrom products.surveys.backend.models import Surveyfrom products.surveys.backend.util import (SurveyEventProperties,@@ -2168,7 +2168,7 @@ def get_teams_with_signals_credits_used_in_period(Outcome-based, not LLM spend: see `products/signals/backend/billing.py`."""- return get_signals_billing_credits_by_team(begin, end)+ return [(row.team_id, row.credits) for row in signals_billing_credits_by_team(begin, end)]def get_signals_credited_refund_credits_for_org(@@ -2189,14 +2189,14 @@ def get_self_driving_credits_used_in_period_for_orgs("""Live self-driving credits used in `[begin, end)` for each org, from one read. Orgs with no usage are absent."""if not organization_ids:return {}- rows = get_signals_billing_credits_by_team(begin, end, organization_ids=list(organization_ids))+ rows = signals_billing_credits_by_team(begin, end, organization_ids=list(organization_ids))if not rows:return {}- team_orgs = dict(Team.objects.filter(id__in=[team_id for team_id, _ in rows]).values_list("id", "organization_id"))+ team_orgs = dict(Team.objects.filter(id__in=[row.team_id for row in rows]).values_list("id", "organization_id"))totals: dict[str, int] = defaultdict(int)- for team_id, credits in rows:- if (organization_id := team_orgs.get(team_id)) is not None:- totals[str(organization_id)] += credits+ for row in rows:+ if (organization_id := team_orgs.get(row.team_id)) is not None:+ totals[str(organization_id)] += row.creditsreturn dict(totals)@@ -2209,9 +2209,7 @@ def get_self_driving_credits_used_in_period_for_org(fresher number than the cron-patched `todays_usage`. Re-exported from this posthog-layermodule for the same boundary reason as the helper above."""- return sum(- credits for _, credits in get_signals_billing_credits_by_team(begin, end, organization_id=organization_id)- )+ return sum(row.credits for row in signals_billing_credits_by_team(begin, end, organization_id=organization_id))@timed_log()diff --git a/posthog/temporal/ai_observability/__init__.py b/posthog/temporal/ai_observability/__init__.pyindex 03414e86b9ae..06558daf707c 100644--- a/posthog/temporal/ai_observability/__init__.py+++ b/posthog/temporal/ai_observability/__init__.py@@ -98,7 +98,7 @@ from posthog.temporal.ai_observability.trace_summarization import (summarize_and_save_activity,)-from products.signals.backend.temporal.emit_eval_signal import emit_eval_signal_activity+from products.signals.backend.facade.temporal import emit_eval_signal_activityEVAL_WORKFLOWS = [RunEvaluationWorkflow,diff --git a/posthog/temporal/ai_observability/eval_reports/emit_signal.py b/posthog/temporal/ai_observability/eval_reports/emit_signal.pyindex 14318805a484..8a5767dfce62 100644--- a/posthog/temporal/ai_observability/eval_reports/emit_signal.py+++ b/posthog/temporal/ai_observability/eval_reports/emit_signal.py@@ -38,8 +38,8 @@ from posthog.temporal.common.base import PostHogWorkflowfrom products.access_control.backend.models.access_control import AccessControlfrom products.access_control.backend.models.property_access_control import PropertyAccessControlfrom products.ai_observability.backend.models.evaluation_reports import EvaluationReportRun-from products.signals.backend.models import SignalSourceConfig-from products.signals.backend.temporal.llm import call_llm+from products.signals.backend.facade.llm import call_llm+from products.signals.backend.facade.taxonomy import SignalSourceProduct, SignalSourceTypelogger = structlog.get_logger(__name__)@@ -175,10 +175,12 @@ async def emit_eval_report_signal_activity(inputs: EmitEvalReportSignalInputs) -"""def _is_eval_report_source_enabled() -> Team | None:- if not SignalSourceConfig.is_source_enabled(+ from products.signals.backend.facade.api import is_signal_source_enabled++ if not is_signal_source_enabled(inputs.team_id,- SignalSourceConfig.SourceProduct.LLM_ANALYTICS,- SignalSourceConfig.SourceType.EVALUATION_REPORT,+ SignalSourceProduct.LLM_ANALYTICS,+ SignalSourceType.EVALUATION_REPORT,):return None# Inbox copies cannot enforce the source's property or evaluation permissions.diff --git a/posthog/temporal/ai_observability/run_evaluation.py b/posthog/temporal/ai_observability/run_evaluation.pyindex e61fb893e609..a5a49f9ad858 100644--- a/posthog/temporal/ai_observability/run_evaluation.py+++ b/posthog/temporal/ai_observability/run_evaluation.py@@ -56,7 +56,7 @@ from posthog.temporal.ai_observability.team_capture import (from posthog.temporal.common.base import PostHogWorkflowfrom products.ai_observability.backend.models.provider_keys import LLMProviderKey-from products.signals.backend.temporal.emit_eval_signal import (+from products.signals.backend.facade.temporal import (EmitEvalSignalInputs,EmitEvalSignalWorkflow,emit_eval_signal_activity,diff --git a/posthog/temporal/health_checks/framework.py b/posthog/temporal/health_checks/framework.pyindex f64709f80478..0d10bdb6a7ab 100644--- a/posthog/temporal/health_checks/framework.py+++ b/posthog/temporal/health_checks/framework.py@@ -14,7 +14,7 @@ from posthog.temporal.health_checks.detectors import DEFAULT_EXECUTION_POLICY, Hfrom posthog.temporal.health_checks.models import DEFAULT_ACTIVE_SINCE_DAYS, HealthCheckResultfrom posthog.temporal.health_checks.registry import _DETECT_FNS, HEALTH_CHECKS, ensure_registry_loaded-from products.signals.backend.enums import ReportPriority+from products.signals.backend.facade.taxonomy import ReportPriorityif TYPE_CHECKING:from django.db.models import Modeldiff --git a/posthog/temporal/health_checks/signal_emitter.py b/posthog/temporal/health_checks/signal_emitter.pyindex 48aff5d4c4dd..bd48ef8a7ce0 100644--- a/posthog/temporal/health_checks/signal_emitter.py+++ b/posthog/temporal/health_checks/signal_emitter.py@@ -10,7 +10,7 @@ from posthog.models.health_issue import HealthIssuefrom posthog.temporal.health_checks.alerts import _check_class_for_kindfrom posthog.temporal.health_checks.framework import _SEVERITY_PRIORITY-from products.signals.backend.contracts import SignalRemediation+from products.signals.backend.facade.taxonomy import SignalRemediationlogger = structlog.get_logger(__name__)diff --git a/posthog/temporal/schedule.py b/posthog/temporal/schedule.pyindex 9dee010db1e7..f561fc3c8b23 100644--- a/posthog/temporal/schedule.py+++ b/posthog/temporal/schedule.py@@ -139,14 +139,12 @@ from products.replay_vision.backend.temporal.reconciler import create_replay_visfrom products.replay_vision.backend.temporal.vision_alerts.schedule import create_vision_alert_check_schedulefrom products.review_hog.backend.facade.temporal import create_review_hog_finding_outcomes_schedulefrom products.security.backend.facade.temporal import create_sync_access_rules_schedule-from products.signals.backend.activity_summary.schedule import create_activity_summary_tick_schedule-from products.signals.backend.anomaly_scores.schedule import (+from products.signals.backend.facade.temporal import (+ create_activity_summary_tick_schedule,create_anomaly_scoring_due_list_refresh_schedule,create_anomaly_scoring_tick_schedule,-)-from products.signals.backend.emission.conversations_schedule import create_conversations_signals_coordinator_schedule-from products.signals.backend.ranking.schedule import create_inbox_ranking_scoring_schedule-from products.signals.backend.temporal.agentic.schedule import (+ create_conversations_signals_coordinator_schedule,+ create_inbox_ranking_scoring_schedule,create_scout_suggestions_coordinator_schedule,create_signals_scout_coordinator_schedule,)diff --git a/posthog/urls.py b/posthog/urls.pyindex 15f4b88859ed..5b3593fa9e6d 100644--- a/posthog/urls.py+++ b/posthog/urls.py@@ -59,8 +59,10 @@ from products.notebooks.backend.facade.sql_v2 import ()from products.product_tours.backend.api import product_toursfrom products.security.backend.presentation.hub_api import urlpatterns as security_hub_urlpatterns-from products.signals.backend import views as signals_views-from products.signals.backend.views import SignalUserAutonomyConfigView as signals_user_autonomy_view+from products.signals.backend.facade.urls import (+ internal_urlpatterns as signals_internal_urlpatterns,+ user_urlpatterns as signals_user_urlpatterns,+)from products.slack_app.backend.api import (posthog_code_event_handler,posthog_code_interactivity_handler,@@ -166,11 +168,7 @@ urlpatterns = [path("api/unsubscribe", unsubscribe.unsubscribe),path("api/alerts/github", github.SecretAlert.as_view()),opt_slash_path("api/revoke_leaked_key", leaked_key.PublicLeakedKeyReport.as_view()),- path(- "api/users/<str:user_id>/signal_autonomy/",- signals_user_autonomy_view.as_view(),- name="user_signal_autonomy",- ),+ *signals_user_urlpatterns,path("api/projects/<int:team_id>/messaging/customerio/webhook/", csrf_exempt(CustomerIOWebhookView.as_view())),path("api/sdk_health/", sdk_health),# Conversations serves its widget and channel API from backend/api/, which its routes module@@ -274,10 +272,7 @@ urlpatterns = ["api/projects/<str:team_id>/internal/hog_flows/batch_jobs/<str:batch_job_id>/status",csrf_exempt(hog_flow.InternalHogFlowViewSet.as_view({"put": "internal_update_batch_job_status"})),),- path(- "api/projects/<str:team_id>/internal/signals/emit",- csrf_exempt(signals_views.InternalSignalViewSet.as_view({"post": "emit"})),- ),+ *signals_internal_urlpatterns,# Ticket route for the CDP worker's workflow actions (auth: scoped service JWT)path("api/projects/<str:team_id>/internal/conversations/tickets/<uuid:ticket_id>",diff --git a/products/signals/backend/facade/billing.py b/products/signals/backend/facade/billing.pynew file mode 100644index 000000000000..fb94a9057f5e--- /dev/null+++ b/products/signals/backend/facade/billing.py@@ -0,0 +1,37 @@+"""Signals credit usage, for the usage report and the quota checks in core."""++import uuid+from collections.abc import Collection+from datetime import datetime++from posthog.dataclasses import frozen++from products.signals.backend import billing+++@frozen+class TeamSignalsCredits:+ team_id: int+ credits: int+++def signals_billing_credits_by_team(+ begin: datetime,+ end: datetime,+ *,+ organization_id: str | uuid.UUID | None = None,+ organization_ids: Collection[str | uuid.UUID] | None = None,+) -> list[TeamSignalsCredits]:+ """Billable signals credits in ``[begin, end)`` for each team with non-zero usage.++ Covers every organization unless ``organization_id`` or ``organization_ids`` narrows the scan.+ """+ rows = billing.get_signals_billing_credits_by_team(+ begin, end, organization_id=organization_id, organization_ids=organization_ids+ )+ return [TeamSignalsCredits(team_id=team_id, credits=credits) for team_id, credits in rows]+++def credited_refund_credits_for_org(organization_id: str | uuid.UUID, begin: datetime, end: datetime) -> int:+ """Credits that credited-path refunds returned for the org's pull request runs created in ``[begin, end)``."""+ return billing.credited_refund_credits_for_org(organization_id, begin, end)diff --git a/products/signals/backend/facade/dags.py b/products/signals/backend/facade/dags.pynew file mode 100644index 000000000000..a65c89d166de--- /dev/null+++ b/products/signals/backend/facade/dags.py@@ -0,0 +1,20 @@+"""Dagster definitions for the inbox ranking pipeline that the core ``signals`` location loads."""++from products.signals.dags.inbox_ranking.common import is_inbox_ranking_mirror_registered, is_inbox_ranking_registered+from products.signals.dags.inbox_ranking.dataset import dag as inbox_ranking_dataset+from products.signals.dags.inbox_ranking.mirror import dag as inbox_ranking_mirror+from products.signals.dags.inbox_ranking.training import (+ dag as inbox_ranking_training,+ promote as inbox_ranking_promote,+ served as inbox_ranking_served,+)++__all__ = [+ "inbox_ranking_dataset",+ "inbox_ranking_mirror",+ "inbox_ranking_promote",+ "inbox_ranking_served",+ "inbox_ranking_training",+ "is_inbox_ranking_mirror_registered",+ "is_inbox_ranking_registered",+]diff --git a/products/signals/backend/facade/dags_ml.py b/products/signals/backend/facade/dags_ml.pynew file mode 100644index 000000000000..a737874f7124--- /dev/null+++ b/products/signals/backend/facade/dags_ml.py@@ -0,0 +1,18 @@+"""Dagster definitions for the inbox ranking model training that the core ``signals_ml`` location loads.++Kept apart from ``dags.py`` so that the ML location imports only the modules it registers.+"""++from products.signals.dags.inbox_ranking.common import is_inbox_ranking_registered+from products.signals.dags.inbox_ranking.nn import (+ dag as inbox_ranking_nn,+ experiments as inbox_ranking_nn_experiments,+ pairs as inbox_ranking_nn_pairs,+)++__all__ = [+ "inbox_ranking_nn",+ "inbox_ranking_nn_experiments",+ "inbox_ranking_nn_pairs",+ "is_inbox_ranking_registered",+]diff --git a/products/signals/backend/facade/llm.py b/products/signals/backend/facade/llm.pynew file mode 100644index 000000000000..ed06835701a4--- /dev/null+++ b/products/signals/backend/facade/llm.py@@ -0,0 +1,5 @@+"""The signals LLM client, for emitters in other products that summarize their input before they emit."""++from products.signals.backend.temporal.llm import call_llm++__all__ = ["call_llm"]diff --git a/products/signals/backend/facade/report_tasks.py b/products/signals/backend/facade/report_tasks.pynew file mode 100644index 000000000000..83baf862e05b--- /dev/null+++ b/products/signals/backend/facade/report_tasks.py@@ -0,0 +1,88 @@+"""Report and task links for the tasks product, which creates and runs the tasks a report starts.++The cap and record writes do not open a transaction. The tasks product creates the task row in+the same transaction, so the caller owns it. Each function calls its implementation through the+module attribute, so a test that patches the implementation also changes what callers see.+"""++from products.signals.backend import report_task_actions, task_run_artefacts, tracker_issues+from products.signals.backend.models import SignalReport, SignalReportArtefact+from products.signals.backend.task_run_artefacts import ReportTaskCapExceeded++__all__ = [+ "ReportTaskCapExceeded",+ "create_tracker_issue_for_report",+ "delete_report_task_artefact",+ "enforce_report_implementation_rerun_cap",+ "enforce_report_task_cap",+ "is_pull_request_run_request",+ "is_report_implementation_task",+ "record_report_task",+ "release_quota_cancelled_implementation",+ "report_task_ids",+]+++def is_pull_request_run_request(description: str | None) -> bool:+ return report_task_actions.is_pull_request_run_request(description)+++def enforce_report_task_cap(+ *,+ team_id: int,+ report_id: str,+ relationship: str | None,+ description: str | None = None,+ created_by_id: int | None = None,+) -> None:+ """Raise ``ReportTaskCapExceeded`` at the limit.++ Call it inside the transaction that creates the task, because it locks the report row until+ commit. That lock makes concurrent creates for one report wait for each other.+ """+ task_run_artefacts.enforce_report_task_cap(+ team_id=team_id,+ report_id=report_id,+ relationship=relationship,+ description=description,+ created_by_id=created_by_id,+ )+++def record_report_task(*, team_id: int, report_id: str, task_id: str, relationship: str | None = None) -> str:+ """Record that the task belongs to the report. Return the id of the work-log artefact it writes."""+ artefact = task_run_artefacts.record_report_task(+ team_id=team_id, report_id=report_id, task_id=task_id, relationship=relationship+ )+ return str(artefact.id)+++def delete_report_task_artefact(*, team_id: int, artefact_id: str) -> None:+ """Delete the work-log artefact that ``record_report_task`` wrote, when the task fails to start."""+ SignalReportArtefact.objects.filter(team_id=team_id, id=artefact_id).delete()+++def report_task_ids(*, team_id: int, report_id: str) -> list[str]:+ """The ids of the tasks linked to the report, from the work log and the legacy gate rows."""+ return [str(entry.task_id) for entry in SignalReport.associated_task_runs(report_id=report_id, team_id=team_id)]+++def is_report_implementation_task(*, team_id: int, report_id: str, task_id: str) -> bool:+ return task_run_artefacts.is_report_implementation_task(team_id=team_id, report_id=report_id, task_id=task_id)+++def enforce_report_implementation_rerun_cap(*, team_id: int, report_id: str, task_id: str) -> None:+ task_run_artefacts.enforce_report_implementation_rerun_cap(team_id=team_id, report_id=report_id, task_id=task_id)+++def release_quota_cancelled_implementation(*, team_id: int, task_id: str) -> list[str]:+ """Remove the implementation records of a quota-cancelled task so its reports can run again.++ Return the ids of the affected reports.+ """+ return task_run_artefacts.release_quota_cancelled_implementation(team_id=team_id, task_id=task_id)+++def create_tracker_issue_for_report(*, team_id: int, report_id: str, repository: str) -> None:+ """Open the tracker issue for the report's upcoming pull request. A provider failure does not raise."""+ tracker_issues.create_tracker_issue_for_report(team_id=team_id, report_id=report_id, repository=repository)diff --git a/products/signals/backend/facade/reports.py b/products/signals/backend/facade/reports.pynew file mode 100644index 000000000000..76888b8ab2e9--- /dev/null+++ b/products/signals/backend/facade/reports.py@@ -0,0 +1,66 @@+"""Report reads for surfaces outside signals that show or announce a single report."""++from datetime import datetime++from posthog.dataclasses import frozen+from posthog.models import User++from products.access_control.backend.facade.user_access_control import UserAccessControl+from products.signals.backend.models import SignalReport+from products.signals.backend.report_access import may_read_reports+from products.signals.backend.scout_authorship import report_is_hidden_from_inbox++__all__ = [+ "ReportCard",+ "get_report_card",+ "may_read_reports",+ "user_may_receive_report_push",+]+++@frozen+class ReportCard:+ title: str | None+ status: str+ signal_count: int+ updated_at: datetime+++def get_report_card(*, team_id: int, report_id: str) -> ReportCard | None:+ """The report's preview fields, or ``None`` when the team has no such report or it is deleted."""+ report = (+ SignalReport.objects.filter(team_id=team_id, pk=report_id).exclude(status=SignalReport.Status.DELETED).first()+ )+ if report is None:+ return None+ return ReportCard(+ title=report.title,+ status=report.status,+ signal_count=report.signal_count,+ updated_at=report.updated_at,+ )+++def user_may_receive_report_push(*, user: User, team_id: int | str, report_id: str) -> bool:+ """Whether the user may still get a push notification about the report.++ The report must be visible in the inbox, and the user must be an active member of its+ organization with access to the project and to reports.+ """+ report = (+ SignalReport.objects.filter(team_id=team_id, id=report_id)+ .exclude(status__in=[SignalReport.Status.DELETED, SignalReport.Status.SUPPRESSED])+ .select_related("team")+ .first()+ )+ return bool(+ report+ and not report_is_hidden_from_inbox(report.team_id, str(report.id))+ and User.objects.filter(+ id=user.id,+ is_active=True,+ organization_membership__organization_id=report.team.organization_id,+ ).exists()+ and UserAccessControl(user=user, team=report.team).has_project_access+ and may_read_reports(user=user, team=report.team)+ )diff --git a/products/signals/backend/facade/research.py b/products/signals/backend/facade/research.pynew file mode 100644index 000000000000..7f0bb2b4c409--- /dev/null+++ b/products/signals/backend/facade/research.py@@ -0,0 +1,19 @@+"""Report research output shapes, for agents in other products that produce output the signals pipeline consumes."""++from products.signals.backend.report_generation.research import (+ ActionabilityAssessment,+ ActionabilityChoice,+ PriorityAssessment,+ ReportPresentationOutput,+ ReportResearchOutput,+ SignalFinding,+)++__all__ = [+ "ActionabilityAssessment",+ "ActionabilityChoice",+ "PriorityAssessment",+ "ReportPresentationOutput",+ "ReportResearchOutput",+ "SignalFinding",+]diff --git a/products/signals/backend/facade/self_driving.py b/products/signals/backend/facade/self_driving.pynew file mode 100644index 000000000000..224c77129ec4--- /dev/null+++ b/products/signals/backend/facade/self_driving.py@@ -0,0 +1,44 @@+"""Self-driving quota and free trial gates for products that start pull request work from a report.++Each function calls its implementation through the module attribute, so a test that patches the+implementation also changes what callers of this facade see.+"""++from typing import TYPE_CHECKING++from products.signals.backend import free_trial, quota+from products.signals.backend.free_trial import FreeTrialPullRequestRefused+from products.signals.backend.quota import SelfDrivingQuotaGate++if TYPE_CHECKING:+ from posthog.models import Team++__all__ = [+ "FreeTrialPullRequestRefused",+ "SelfDrivingQuotaGate",+ "capture_signal_report_free_trial_paused",+ "capture_signal_report_quota_paused",+ "record_quota_check_failed_open",+ "self_driving_free_trial_enabled",+ "self_driving_quota_gate",+]+++def self_driving_quota_gate(team: "Team") -> SelfDrivingQuotaGate:+ return quota.self_driving_quota_gate(team)+++def capture_signal_report_quota_paused(team: "Team", *, report_id: str | None, stage: str, enforced: bool) -> None:+ quota.capture_signal_report_quota_paused(team, report_id=report_id, stage=stage, enforced=enforced)+++def record_quota_check_failed_open() -> None:+ quota.record_quota_check_failed_open()+++def self_driving_free_trial_enabled(team: "Team") -> bool:+ return free_trial.self_driving_free_trial_enabled(team)+++def capture_signal_report_free_trial_paused(team: "Team", *, report_id: str | None, stage: str) -> None:+ free_trial.capture_signal_report_free_trial_paused(team, report_id=report_id, stage=stage)diff --git a/products/signals/backend/facade/tasks.py b/products/signals/backend/facade/tasks.pynew file mode 100644index 000000000000..9bc3c2853c77--- /dev/null+++ b/products/signals/backend/facade/tasks.py@@ -0,0 +1,29 @@+"""Celery tasks that core's beat schedule registers.++Importing this module loads the signals task module. Import it only from code that runs after+``django.setup()``, such as ``posthog/tasks/scheduled.py``.+"""++from products.signals.backend.tasks import (+ pause_inactive_signal_scouts,+ prune_expired_scratchpad_entries_task,+ reconcile_report_inbox_state_cache,+ refresh_signal_repository_activity,+ refresh_signal_scout_background_bands,+ sweep_first_report_notifications,+ sweep_implementation_dispatches,+ sweep_monitoring_tracker_issues,+ sync_pending_signals_refund_credits,+)++__all__ = [+ "pause_inactive_signal_scouts",+ "prune_expired_scratchpad_entries_task",+ "reconcile_report_inbox_state_cache",+ "refresh_signal_repository_activity",+ "refresh_signal_scout_background_bands",+ "sweep_first_report_notifications",+ "sweep_implementation_dispatches",+ "sweep_monitoring_tracker_issues",+ "sync_pending_signals_refund_credits",+]diff --git a/products/signals/backend/facade/temporal.py b/products/signals/backend/facade/temporal.pynew file mode 100644index 000000000000..162622d3749d--- /dev/null+++ b/products/signals/backend/facade/temporal.py@@ -0,0 +1,39 @@+"""Temporal workflows, activities and schedule builders that core registers."""++from products.signals.backend.activity_summary.schedule import create_activity_summary_tick_schedule+from products.signals.backend.anomaly_scores.schedule import (+ create_anomaly_scoring_due_list_refresh_schedule,+ create_anomaly_scoring_tick_schedule,+)+from products.signals.backend.emission.conversations_schedule import create_conversations_signals_coordinator_schedule+from products.signals.backend.emission.temporal_settings import EMIT_SIGNALS_ACTIVITIES, EMIT_SIGNALS_WORKFLOWS+from products.signals.backend.ranking.schedule import create_inbox_ranking_scoring_schedule+from products.signals.backend.temporal import ACTIVITIES, SELF_DRIVING_ACTIVITIES, SELF_DRIVING_WORKFLOWS, WORKFLOWS+from products.signals.backend.temporal.agentic.schedule import (+ create_scout_suggestions_coordinator_schedule,+ create_signals_scout_coordinator_schedule,+)+from products.signals.backend.temporal.emit_eval_signal import (+ EmitEvalSignalInputs,+ EmitEvalSignalWorkflow,+ emit_eval_signal_activity,+)++__all__ = [+ "ACTIVITIES",+ "EMIT_SIGNALS_ACTIVITIES",+ "EMIT_SIGNALS_WORKFLOWS",+ "SELF_DRIVING_ACTIVITIES",+ "SELF_DRIVING_WORKFLOWS",+ "WORKFLOWS",+ "EmitEvalSignalInputs",+ "EmitEvalSignalWorkflow",+ "create_activity_summary_tick_schedule",+ "create_anomaly_scoring_due_list_refresh_schedule",+ "create_anomaly_scoring_tick_schedule",+ "create_conversations_signals_coordinator_schedule",+ "create_inbox_ranking_scoring_schedule",+ "create_scout_suggestions_coordinator_schedule",+ "create_signals_scout_coordinator_schedule",+ "emit_eval_signal_activity",+]diff --git a/products/signals/backend/facade/urls.py b/products/signals/backend/facade/urls.pynew file mode 100644index 000000000000..9b706bda8d1a--- /dev/null+++ b/products/signals/backend/facade/urls.py@@ -0,0 +1,25 @@+"""URL patterns that core mounts outside the project router.++Core splices each list into ``posthog/urls.py`` at a fixed position, because the order of+``urlpatterns`` decides which pattern matches first.+"""++from django.urls import URLPattern, path+from django.views.decorators.csrf import csrf_exempt++from products.signals.backend.views import InternalSignalViewSet, SignalUserAutonomyConfigView++user_urlpatterns: list[URLPattern] = [+ path(+ "api/users/<str:user_id>/signal_autonomy/",+ SignalUserAutonomyConfigView.as_view(),+ name="user_signal_autonomy",+ ),+]++internal_urlpatterns: list[URLPattern] = [+ path(+ "api/projects/<str:team_id>/internal/signals/emit",+ csrf_exempt(InternalSignalViewSet.as_view({"post": "emit"})),+ ),+]diff --git a/products/slack_app/backend/slack_link_unfurl.py b/products/slack_app/backend/slack_link_unfurl.pyindex 770b8c08138b..e31ece46de5c 100644--- a/products/slack_app/backend/slack_link_unfurl.py+++ b/products/slack_app/backend/slack_link_unfurl.py@@ -57,8 +57,7 @@ from products.feature_flags.backend.facade.filters import condition_rollout_percfrom products.feature_flags.backend.models.feature_flag import FeatureFlagfrom products.notebooks.backend.models import Notebookfrom products.product_analytics.backend.facade.models import Insight-from products.signals.backend.models import SignalReport-from products.signals.backend.report_access import may_read_reports+from products.signals.backend.facade.reports import get_report_card, may_read_reportsfrom products.slack_app.backend.analytics import capture_slack_eventfrom products.slack_app.backend.logic.feature_tips.features import SlackFeaturefrom products.slack_app.backend.logic.feature_tips.state import record_feature_used@@ -1151,11 +1150,7 @@ def _error_card(ctx: _UnfurlContext, ref: str, url: str) -> _UnfurlCard | _SkipRdef _report_card(ctx: _UnfurlContext, ref: str, url: str) -> _UnfurlCard | _SkipReason:- report = (- SignalReport.objects.filter(team_id=ctx.team.pk, pk=ref).exclude(status=SignalReport.Status.DELETED).first()- if _uuid(ref)- else None- )+ report = get_report_card(team_id=ctx.team.pk, report_id=ref) if _uuid(ref) else Noneif not report:return "not_found"if not may_read_reports(user=ctx.user, team=ctx.team):diff --git a/products/tasks/backend/facade/api.py b/products/tasks/backend/facade/api.pyindex 457852e19612..6f870c1b2ec2 100644--- a/products/tasks/backend/facade/api.py+++ b/products/tasks/backend/facade/api.py@@ -3591,7 +3591,7 @@ def enforce_self_driving_free_trial(Resolve enabled before taking database locks, since flag evaluation can use the network."""- from products.signals.backend.free_trial import ( # noqa: PLC0415 — cross-product read kept off the api import path+ from products.signals.backend.facade.self_driving import ( # noqa: PLC0415 — cross-product read kept off the api import pathFreeTrialPullRequestRefused,capture_signal_report_free_trial_paused,self_driving_free_trial_enabled,@@ -3606,7 +3606,7 @@ def enforce_self_driving_free_trial(def enforce_self_driving_pr_quota(team: Team, *, report_id: str | None = None, stage: str = "manual_create") -> None:from posthog.exceptions import QuotaLimitExceeded # noqa: PLC0415 — keep billing deps off the api import path- from products.signals.backend.quota import ( # noqa: PLC0415 — cross-product read kept off the api import path+ from products.signals.backend.facade.self_driving import ( # noqa: PLC0415 — cross-product read kept off the api import pathcapture_signal_report_quota_paused,self_driving_quota_gate,)@@ -7949,11 +7949,9 @@ def create_task("""from posthog.models import Team # noqa: PLC0415- from products.signals.backend.report_task_actions import ( # noqa: PLC0415 — cross-product read kept off the api import path- is_pull_request_run_request,- )- from products.signals.backend.task_run_artefacts import ( # noqa: PLC0415 — cross-product write kept off the api import path+ from products.signals.backend.facade.report_tasks import ( # noqa: PLC0415 — cross-product write kept off the api import pathenforce_report_task_cap,+ is_pull_request_run_request,record_report_task,)from products.tasks.backend.logic.services.title_generator import generate_task_title # noqa: PLC0415@@ -8157,7 +8155,11 @@ def create_task()except Exception:if report_reservation is not None:- report_reservation.delete()+ from products.signals.backend.facade.report_tasks import ( # noqa: PLC0415 — cross-product write kept off the api import path+ delete_report_task_artefact,+ )++ delete_report_task_artefact(team_id=warm_task.team_id, artefact_id=report_reservation)raisereturn _task_detail_to_dto(_task_detail_queryset().get(pk=warm_task.pk))@@ -8343,7 +8345,9 @@ def create_task()if signal_report_id and signal_report_task_relationship in (None, "implementation") and task.repository:- from products.signals.backend.tracker_issues import create_tracker_issue_for_report+ from products.signals.backend.facade.report_tasks import ( # noqa: PLC0415 — cross-product write kept off the api import path+ create_tracker_issue_for_report,+ )create_tracker_issue_for_report(team_id=team_id,@@ -9140,12 +9144,10 @@ def _report_task_github_integration_id(team: Team, *, code_access_allowed: bool)def _reserve_report_warm_activation(team: Team, task: Task, *, relationship: str | None, description: str | None = None-) -> Model:- from products.signals.backend.report_task_actions import ( # noqa: PLC0415 — cross-product read kept off the api import path- is_pull_request_run_request,- )- from products.signals.backend.task_run_artefacts import ( # noqa: PLC0415 — cross-product write kept off the api import path+) -> str:+ from products.signals.backend.facade.report_tasks import ( # noqa: PLC0415 — cross-product write kept off the api import pathenforce_report_task_cap,+ is_pull_request_run_request,record_report_task,)@@ -9170,12 +9172,11 @@ def _is_unlinked_report_warm_task(task: Task) -> bool:return Falseif not task.runs.filter(team_id=task.team_id, state__has_key="prewarmed").exists():return False- from products.signals.backend.models import ( # noqa: PLC0415 — cross-product read kept off the api import path- SignalReport,+ from products.signals.backend.facade.report_tasks import ( # noqa: PLC0415 — cross-product read kept off the api import path+ report_task_ids,)- linked = SignalReport.associated_task_runs(report_id=str(task.signal_report_id), team_id=task.team_id)- return not any(str(entry.task_id) == str(task.id) for entry in linked)+ return str(task.id) not in report_task_ids(team_id=task.team_id, report_id=str(task.signal_report_id))def task_run_awaits_report_activation(run_id: str | UUID, task_id: str | UUID, team_id: int) -> bool:@@ -9572,7 +9573,7 @@ def run_task(The caller applies the usage gate. Only server-requested Signals research may set pipeline_rerun."""- from products.signals.backend.task_run_artefacts import ( # noqa: PLC0415 — cross-product read kept off the api import path+ from products.signals.backend.facade.report_tasks import ( # noqa: PLC0415 — cross-product read kept off the api import pathenforce_report_implementation_rerun_cap,is_report_implementation_task,)diff --git a/products/tasks/backend/logic/services/mts_example/README.md b/products/tasks/backend/logic/services/mts_example/README.mdindex 71e11d108eff..37c348608421 100644--- a/products/tasks/backend/logic/services/mts_example/README.md+++ b/products/tasks/backend/logic/services/mts_example/README.md@@ -18,7 +18,7 @@ discovery → research ×N (up to 10) → actionability → priority? → presen## Output shape-Returns `ReportResearchOutput` from `products.signals.backend.report_generation.research` — consumed as-is by the Signals pipeline.+Returns `ReportResearchOutput` from `products.signals.backend.facade.research` — consumed as-is by the Signals pipeline.## Run itdiff --git a/products/tasks/backend/logic/services/mts_example/prompts.py b/products/tasks/backend/logic/services/mts_example/prompts.pyindex d0535a3f0b47..183d2cd3ae3a 100644--- a/products/tasks/backend/logic/services/mts_example/prompts.py+++ b/products/tasks/backend/logic/services/mts_example/prompts.py@@ -2,7 +2,7 @@ from __future__ import annotationsimport json-from products.signals.backend.report_generation.research import (+from products.signals.backend.facade.research import (ActionabilityAssessment,PriorityAssessment,ReportPresentationOutput,diff --git a/products/tasks/backend/logic/services/mts_example/runner.py b/products/tasks/backend/logic/services/mts_example/runner.pyindex e3be9a945c93..4abd98efc8ff 100644--- a/products/tasks/backend/logic/services/mts_example/runner.py+++ b/products/tasks/backend/logic/services/mts_example/runner.py@@ -3,7 +3,7 @@ from __future__ import annotationsimport uuidimport logging-from products.signals.backend.report_generation.research import (+from products.signals.backend.facade.research import (ActionabilityAssessment,ActionabilityChoice,PriorityAssessment,diff --git a/products/tasks/backend/management/commands/demo_mts_example.py b/products/tasks/backend/management/commands/demo_mts_example.pyindex 20fd07e6ec9e..356863394cbb 100644--- a/products/tasks/backend/management/commands/demo_mts_example.py+++ b/products/tasks/backend/management/commands/demo_mts_example.py@@ -11,7 +11,7 @@ from django.core.management.base import BaseCommand, CommandErrorfrom posthog.models.team.team import Teamfrom posthog.models.user import User-from products.signals.backend.report_generation.research import ReportResearchOutput+from products.signals.backend.facade.research import ReportResearchOutputfrom products.tasks.backend.logic.services.custom_prompt_internals import CustomPromptSandboxContextfrom products.tasks.backend.logic.services.mts_example import run_cursed_identifier_researchdiff --git a/products/tasks/backend/temporal/process_task/activities/enforce_self_driving_quota.py b/products/tasks/backend/temporal/process_task/activities/enforce_self_driving_quota.pyindex c2e24dbfa1f8..e62090f6ccc3 100644--- a/products/tasks/backend/temporal/process_task/activities/enforce_self_driving_quota.py+++ b/products/tasks/backend/temporal/process_task/activities/enforce_self_driving_quota.py@@ -6,7 +6,7 @@ from temporalio import activityfrom posthog.models import Teamfrom posthog.temporal.common.utils import asyncify-from products.signals.backend.quota import (+from products.signals.backend.facade.self_driving import (capture_signal_report_quota_paused,record_quota_check_failed_open,self_driving_quota_gate,@@ -155,7 +155,7 @@ def enforce_self_driving_run_quota(input: EnforceSelfDrivingRunQuotaInput) -> st)return SELF_DRIVING_QUOTA_CANCELLED- from products.signals.backend.task_run_artefacts import ( # noqa: PLC0415 — cross-product write kept off the activity import path+ from products.signals.backend.facade.report_tasks import ( # noqa: PLC0415 — cross-product write kept off the activity import pathrelease_quota_cancelled_implementation,)