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.

fix(devex): keep tasks and signals contracts off the django setup path (#100055)

Julian Bezf3b718dbc29f
diff --git a/posthog/test/repo_invariants/test_startup_import_budget.py b/posthog/test/repo_invariants/test_startup_import_budget.py
index 95c0367c91a1..cb2f25521383 100644
--- a/posthog/test/repo_invariants/test_startup_import_budget.py
+++ b/posthog/test/repo_invariants/test_startup_import_budget.py
@@ -41,6 +41,7 @@ FORBIDDEN_AT_SETUP = [
"posthog.hogql.query", # query execution entrypoint — drags the layers below in
"posthog.hogql_queries", # the query-runner layer (every insight runner)
"posthog.api.services.query", # API query service — viewset-request-time only
+ "products.signals.backend.tasks", # celery task module — workers load it by autodiscovery; at setup it drags the signals and tasks contracts in
]
# Runs in a clean interpreter: pytest has already imported half the world, so we cannot
diff --git a/products/review_hog/backend/receivers.py b/products/review_hog/backend/receivers.py
index 6107f774f81e..f24752e4a458 100644
--- a/products/review_hog/backend/receivers.py
+++ b/products/review_hog/backend/receivers.py
@@ -47,7 +47,6 @@ from products.review_hog.backend.models import ReviewUserSettings
from products.signals.backend.enums import ReportPriority
from products.signals.backend.models import SignalReportArtefact
from products.signals.backend.report_generation.priority import persisted_report_priority
-from products.signals.backend.report_generation.resolve_reviewers import resolve_org_github_login_to_users
from products.stamphog.backend.facade.inbox_hooks import register_inbox_acting_reviewer_resolver
# This module loads during django.setup() (AppConfig.ready() wires the receiver), and
@@ -228,6 +227,13 @@ def _resolve_assigned_reviewers(team_id: int, signal_report_id: Any) -> list[Any
]
if not logins:
return []
+
+ # Function-local: pulls the signals contracts module (pydantic dataclasses), which the
+ # startup-import-budget test forbids at django.setup() — see the module-top comment.
+ from products.signals.backend.report_generation.resolve_reviewers import ( # noqa: PLC0415
+ resolve_org_github_login_to_users,
+ )
+
login_to_user = resolve_org_github_login_to_users(team_id, logins)
return [login_to_user[login] for login in logins if login in login_to_user]
diff --git a/products/signals/backend/receivers.py b/products/signals/backend/receivers.py
index 1c23f0b60cc8..396de5c62078 100644
--- a/products/signals/backend/receivers.py
+++ b/products/signals/backend/receivers.py
@@ -4,10 +4,12 @@ Kept in one place so cross-cutting side effects of report state changes have a s
rather than being sprinkled across every dismissal entrypoint (Slack, REST, bulk, …).
"""
+from __future__ import annotations
+
import json
from datetime import datetime, timedelta
from functools import partial
-from typing import Any
+from typing import TYPE_CHECKING, Any
from django.db import transaction
from django.db.models import QuerySet
@@ -20,22 +22,18 @@ import posthoganalytics
from posthog.event_usage import groups
-from products.signals.backend.implementation_pr import PrCloseReason
from products.signals.backend.models import SignalReport, SignalReportArtefact
-from products.signals.backend.report_assignments import sync_task_pull_request_to_assignments
from products.signals.backend.report_embeddings import (
emit_report_embedding,
emit_report_tombstone,
render_report_document,
)
from products.signals.backend.scout_harness.suggestions import mark_stale_if_fleet_changed
-from products.signals.backend.tasks import (
- close_dismissed_report_pr,
- close_report_tracker_issue,
- link_report_tracker_issues,
-)
from products.tasks.backend.facade.task_run_signals import connect_task_run_post_save
+if TYPE_CHECKING:
+ from products.signals.backend.implementation_pr import PrCloseReason
+
logger = structlog.get_logger(__name__)
_SNOOZE_SOURCE_STATUSES = frozenset({SignalReport.Status.READY, SignalReport.Status.RESOLVED})
@@ -59,7 +57,11 @@ def sync_task_run_pr_to_assignments(sender: type, instance: Any, created: bool,
if update_fields is not None and "output" not in update_fields:
return
output = instance.output if isinstance(instance.output, dict) else {}
+ # Function-local: the assignment sync reaches the tasks facade and the task module reaches
+ # the signals contracts, both forbidden at django.setup() by the startup-import-budget test.
from products.signals.backend.pull_requests import apply_report_completion
+ from products.signals.backend.report_assignments import sync_task_pull_request_to_assignments # noqa: PLC0415
+ from products.signals.backend.tasks import link_report_tracker_issues # noqa: PLC0415
from products.tasks.backend.facade.api import read_pr_urls
pr_urls = read_pr_urls(output)
@@ -268,6 +270,10 @@ def close_pr_when_report_dismissed(
hooking the model here covers them all without each caller opting in. A resolve closes the PR
only when the state API flagged it (see ``_pr_close_reason``).
"""
+ # Function-local: the task module reaches the signals contracts, which the
+ # startup-import-budget test forbids at django.setup().
+ from products.signals.backend.tasks import close_dismissed_report_pr, close_report_tracker_issue # noqa: PLC0415
+
prior_status = getattr(instance, "_prior_status", None)
reason = _pr_close_reason(
instance,
diff --git a/products/signals/backend/test/test_dismissal_pr_close.py b/products/signals/backend/test/test_dismissal_pr_close.py
index bc58add10493..088ff1b96471 100644
--- a/products/signals/backend/test/test_dismissal_pr_close.py
+++ b/products/signals/backend/test/test_dismissal_pr_close.py
@@ -55,7 +55,7 @@ class TestClosePrWhenReportDismissed(BaseTest):
self, _name, source_status, new_status, transition_kwargs, expected_reason
):
report = self._create_report(report_status=source_status)
- with patch("products.signals.backend.receivers.close_dismissed_report_pr") as mock_task:
+ with patch("products.signals.backend.tasks.close_dismissed_report_pr") as mock_task:
self._save_transition(report, new_status, **transition_kwargs)
mock_task.delay.assert_called_once_with(
report_id=str(report.id),
@@ -65,7 +65,7 @@ class TestClosePrWhenReportDismissed(BaseTest):
def test_full_save_on_dismiss_enqueues_close_task(self):
report = self._create_report()
- with patch("products.signals.backend.receivers.close_dismissed_report_pr") as mock_task:
+ with patch("products.signals.backend.tasks.close_dismissed_report_pr") as mock_task:
with self.captureOnCommitCallbacks(execute=True):
report.transition_to(SignalReport.Status.SUPPRESSED)
report.save()
@@ -77,27 +77,27 @@ class TestClosePrWhenReportDismissed(BaseTest):
def test_full_save_without_status_change_does_not_enqueue(self):
report = self._create_report(report_status=SignalReport.Status.SUPPRESSED)
- with patch("products.signals.backend.receivers.close_dismissed_report_pr") as mock_task:
+ with patch("products.signals.backend.tasks.close_dismissed_report_pr") as mock_task:
with self.captureOnCommitCallbacks(execute=True):
report.title = "edited"
report.save()
mock_task.delay.assert_not_called()
def test_born_suppressed_report_does_not_enqueue(self):
- with patch("products.signals.backend.receivers.close_dismissed_report_pr") as mock_task:
+ with patch("products.signals.backend.tasks.close_dismissed_report_pr") as mock_task:
with self.captureOnCommitCallbacks(execute=True):
self._create_report(report_status=SignalReport.Status.SUPPRESSED)
mock_task.delay.assert_not_called()
def test_restore_from_suppressed_does_not_enqueue(self):
report = self._create_report(report_status=SignalReport.Status.SUPPRESSED)
- with patch("products.signals.backend.receivers.close_dismissed_report_pr") as mock_task:
+ with patch("products.signals.backend.tasks.close_dismissed_report_pr") as mock_task:
self._save_transition(report, SignalReport.Status.POTENTIAL)
mock_task.delay.assert_not_called()
def test_pipeline_reset_to_potential_does_not_enqueue(self):
report = self._create_report(report_status=SignalReport.Status.IN_PROGRESS)
- with patch("products.signals.backend.receivers.close_dismissed_report_pr") as mock_task:
+ with patch("products.signals.backend.tasks.close_dismissed_report_pr") as mock_task:
self._save_transition(report, SignalReport.Status.POTENTIAL, error="not actionable")
mock_task.delay.assert_not_called()
@@ -105,7 +105,7 @@ class TestClosePrWhenReportDismissed(BaseTest):
# The PR-merge webhook resolves through transition_to directly. Its PR is merged, so the
# receiver must not try to close it.
report = self._create_report()
- with patch("products.signals.backend.receivers.close_dismissed_report_pr") as mock_task:
+ with patch("products.signals.backend.tasks.close_dismissed_report_pr") as mock_task:
self._save_transition(report, SignalReport.Status.RESOLVED)
mock_task.delay.assert_not_called()
@@ -120,7 +120,7 @@ class TestClosePrWhenReportDismissed(BaseTest):
pr_state=SignalReportAssignment.PrState.OPEN,
)
- with patch("products.signals.backend.receivers.close_report_tracker_issue") as mock_task:
+ with patch("products.signals.backend.tasks.close_report_tracker_issue") as mock_task:
with self.captureOnCommitCallbacks(execute=True):
update_assignments_for_pull_request(
team_ids=[self.team.id],
@@ -136,7 +136,7 @@ class TestClosePrWhenReportDismissed(BaseTest):
# open with nothing left to answer it.
report = self._create_report()
- with patch("products.signals.backend.receivers.close_report_tracker_issue") as mock_task:
+ with patch("products.signals.backend.tasks.close_report_tracker_issue") as mock_task:
self._save_transition(report, SignalReport.Status.DELETED)
mock_task.delay.assert_called_once_with(report_id=str(report.id), team_id=self.team.id, completed=False)
@@ -153,7 +153,7 @@ class TestClosePrWhenReportDismissed(BaseTest):
pr_state=SignalReportAssignment.PrState.OPEN,
)
- with patch("products.signals.backend.receivers.close_dismissed_report_pr") as mock_task:
+ with patch("products.signals.backend.tasks.close_dismissed_report_pr") as mock_task:
with self.captureOnCommitCallbacks(execute=True):
update_assignments_for_pull_request(
team_ids=[self.team.id],
@@ -169,7 +169,7 @@ class TestClosePrWhenReportDismissed(BaseTest):
def test_unrelated_save_of_suppressed_report_does_not_enqueue(self):
report = self._create_report(report_status=SignalReport.Status.SUPPRESSED)
- with patch("products.signals.backend.receivers.close_dismissed_report_pr") as mock_task:
+ with patch("products.signals.backend.tasks.close_dismissed_report_pr") as mock_task:
with self.captureOnCommitCallbacks(execute=True):
report.title = "edited"
report.save(update_fields=["title"])
diff --git a/products/signals/backend/test/test_signal_report_api.py b/products/signals/backend/test/test_signal_report_api.py
index 8a59593bffc3..92ab11c7dc0e 100644
--- a/products/signals/backend/test/test_signal_report_api.py
+++ b/products/signals/backend/test/test_signal_report_api.py
@@ -2140,7 +2140,7 @@ class TestSignalReportSuppressionAPI(APIBaseTest):
# The inbox PR is superseded by a fix that landed elsewhere, so the receiver must close it
# with the resolve-specific comment rather than leave it open.
report = self._create_report()
- with patch("products.signals.backend.receivers.close_dismissed_report_pr") as mock_task:
+ with patch("products.signals.backend.tasks.close_dismissed_report_pr") as mock_task:
with self.captureOnCommitCallbacks(execute=True):
response = self.client.post(
self._state_url(str(report.id)),
@@ -2446,7 +2446,7 @@ class TestSignalReportSuppressionAPI(APIBaseTest):
report.save(update_fields=["status_before_suppression"])
with (
- patch("products.signals.backend.receivers.close_dismissed_report_pr") as mock_close_pr,
+ patch("products.signals.backend.tasks.close_dismissed_report_pr") as mock_close_pr,
self.captureOnCommitCallbacks(execute=True),
):
response = self.client.post(
diff --git a/products/signals/backend/test/test_signal_report_assignment_api.py b/products/signals/backend/test/test_signal_report_assignment_api.py
index 6bf65b3f2549..a6fa1fc76a18 100644
--- a/products/signals/backend/test/test_signal_report_assignment_api.py
+++ b/products/signals/backend/test/test_signal_report_assignment_api.py
@@ -415,7 +415,7 @@ class TestSignalReportAssignmentAPI(APIBaseTest):
TaskRun = apps.get_model("tasks", "TaskRun")
pr_urls = ["https://github.com/example/app/pull/1", "https://github.com/example/app/pull/2"]
- with patch("products.signals.backend.receivers.link_report_tracker_issues.delay") as link_tracker:
+ with patch("products.signals.backend.tasks.link_report_tracker_issues.delay") as link_tracker:
with self.captureOnCommitCallbacks(execute=True):
TaskRun.objects.create(
team=self.team,
diff --git a/products/tasks/backend/facade/contracts.py b/products/tasks/backend/facade/contracts.py
index a551ec559971..e933feaa20d0 100644
--- a/products/tasks/backend/facade/contracts.py
+++ b/products/tasks/backend/facade/contracts.py
@@ -23,6 +23,10 @@ from uuid import UUID
from pydantic import Field
from pydantic.dataclasses import dataclass
+# Re-exported: the exception is defined in an import-light module so ``storage.py`` can raise it
+# without dragging this module onto the ``django.setup()`` path.
+from products.tasks.backend.storage_errors import TaskRunLogAppendUnserialized as TaskRunLogAppendUnserialized
+
class DesktopAccessReason(StrEnum):
STARTUP_PLAN = "startup_plan"
@@ -402,10 +406,6 @@ class TaskAnalysisError(Exception):
"""A task analysis could not be created or recorded; ``message`` is safe to surface."""
-class TaskRunLogAppendUnserialized(Exception):
- """The per-log append lock could not be taken; the caller should retry the append."""
-
-
@dataclass(frozen=True)
class TaskValidationError:
"""A structured validation-error payload the presentation layer renders as a 400/404.
diff --git a/products/tasks/backend/storage.py b/products/tasks/backend/storage.py
index 401853336954..d4380a6149c1 100644
--- a/products/tasks/backend/storage.py
+++ b/products/tasks/backend/storage.py
@@ -9,8 +9,8 @@ import structlog
from posthog.redis import get_client
from posthog.storage import object_storage
-from products.tasks.backend.facade.contracts import TaskRunLogAppendUnserialized
from products.tasks.backend.metrics import LOG_APPEND_UNSERIALIZED_TOTAL
+from products.tasks.backend.storage_errors import TaskRunLogAppendUnserialized
logger = structlog.get_logger(__name__)
diff --git a/products/tasks/backend/storage_errors.py b/products/tasks/backend/storage_errors.py
new file mode 100644
index 000000000000..91dfc0924dd0
--- /dev/null
+++ b/products/tasks/backend/storage_errors.py
@@ -0,0 +1,11 @@
+"""Errors raised by the tasks object-storage helpers.
+
+Kept apart from ``facade/contracts.py`` so ``storage.py`` — which ``models.py`` imports, and
+therefore every process pays at ``django.setup()`` — does not pull the contracts module's
+pydantic dataclasses onto the startup path. ``facade/contracts.py`` re-exports the name, so
+consumers keep importing it from the facade.
+"""
+
+
+class TaskRunLogAppendUnserialized(Exception):
+ """The per-log append lock could not be taken; the caller should retry the append."""
diff --git a/products/tasks/backend/tests/test_webhooks.py b/products/tasks/backend/tests/test_webhooks.py
index 4361d423dcfb..99bbbbf036bd 100644
--- a/products/tasks/backend/tests/test_webhooks.py
+++ b/products/tasks/backend/tests/test_webhooks.py
@@ -1229,7 +1229,7 @@ class TestGitHubPRWebhookResolvesSignalReports(TestCase):
team=self.team, report=self.report, actor_kind=actor_kind, actor_agent="test-agent"
)
- with patch("products.signals.backend.receivers.close_dismissed_report_pr") as close_task:
+ with patch("products.signals.backend.tasks.close_dismissed_report_pr") as close_task:
with self.captureOnCommitCallbacks(execute=True):
response = self._post_pr_webhook(action="closed", merged=merged)