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.

refactor(signals): share one reader for a report's latest artefact (#112766)

Rafael Audibertf4f6720b99f6
diff --git a/products/signals/backend/artefact_schemas.py b/products/signals/backend/artefact_schemas.py
index 0d3461fcaff4..2b180f920e73 100644
--- a/products/signals/backend/artefact_schemas.py
+++ b/products/signals/backend/artefact_schemas.py
@@ -1255,18 +1255,23 @@ NON_WRITABLE_ARTEFACT_TYPES: frozenset[str] = frozenset(
)
-def artefact_type_for(content: BaseModel) -> str:
- """The artefact type a content model persists as (exact class match).
+def artefact_type_for_model(model: type[BaseModel]) -> str:
+ """The artefact type a content model class persists as (exact class match).
Deriving the row's type from the model class makes a type/content mismatch unrepresentable.
Raises `ArtefactContentValidationError` for models that aren't artefact content schemas.
"""
- artefact_type = _ARTEFACT_TYPE_BY_MODEL.get(type(content))
+ artefact_type = _ARTEFACT_TYPE_BY_MODEL.get(model)
if artefact_type is None:
- raise ArtefactContentValidationError(f"{type(content).__name__} is not an artefact content model")
+ raise ArtefactContentValidationError(f"{model.__name__} is not an artefact content model")
return artefact_type
+def artefact_type_for(content: BaseModel) -> str:
+ """The artefact type a content model instance persists as. See `artefact_type_for_model`."""
+ return artefact_type_for_model(type(content))
+
+
def parse_artefact_content(artefact_type: str, content: str | dict | list) -> ArtefactContent:
"""Parse a raw payload (JSON text or deserialized JSON) into `artefact_type`'s content model.
diff --git a/products/signals/backend/auto_start.py b/products/signals/backend/auto_start.py
index 2b5740bd531f..1b7303556f9e 100644
--- a/products/signals/backend/auto_start.py
+++ b/products/signals/backend/auto_start.py
@@ -3,7 +3,7 @@ from __future__ import annotations
import json
import secrets
from datetime import datetime
-from typing import Literal, TypedDict, TypeVar
+from typing import Literal, TypedDict
from uuid import UUID
from django.conf import settings
@@ -13,7 +13,6 @@ from django.utils.text import slugify
import structlog
import posthoganalytics
-from pydantic import BaseModel, ValidationError
from posthog.dataclasses import frozen
from posthog.event_usage import groups
@@ -93,7 +92,6 @@ from products.tasks.backend.facade.usage import task_run_usage_limited
logger = structlog.get_logger(__name__)
-_M = TypeVar("_M", bound=BaseModel)
# The posture minted for an autostarted implementation run. Named once because two things depend
# on it: the token the sandbox holds, and the memory protocol rendered into the task description.
@@ -1588,26 +1586,6 @@ async def maybe_autostart_implementation_task(
return AutostartOutcome(status="started")
-async def _latest_artefact_as(
- report_id: str, artefact_type: str, model_cls: type[_M], *, written_after: datetime | None = None
-) -> _M | None:
- """Parse the latest artefact of ``artefact_type`` for a report (append-only, latest-wins).
-
- ``written_after`` ignores an artefact written before that moment, for a type whose content
- describes one research pass and must not be read on a later one.
- """
- artefacts = SignalReportArtefact.objects.filter(report_id=report_id, type=artefact_type)
- if written_after is not None:
- artefacts = artefacts.filter(created_at__gte=written_after)
- artefact = await artefacts.order_by("-created_at").afirst()
- if artefact is None:
- return None
- try:
- return model_cls.model_validate_json(artefact.content)
- except ValidationError:
- return None
-
-
async def _latest_reviewers_content(report_id: str) -> tuple[list[ReviewerContent], int | None]:
"""Latest suggested-reviewers list, plus the id of the user who last edited it (if any).
@@ -1698,8 +1676,8 @@ async def maybe_autostart_from_report_artefacts(
)
return AutostartOutcome(status="cancelled", reason="Report is missing or has no summary")
- actionability = await _latest_artefact_as(
- report_id, SignalReportArtefact.ArtefactType.ACTIONABILITY_JUDGMENT, ActionabilityAssessment
+ actionability = await SignalReportArtefact.alatest_content(
+ team_id=team_id, report_id=report_id, model=ActionabilityAssessment
)
if actionability is None:
logger.info(
@@ -1709,8 +1687,8 @@ async def maybe_autostart_from_report_artefacts(
reason="no actionability artefact",
)
return AutostartOutcome(status="blocked", reason="No actionability assessment")
- repo_selection = await _latest_artefact_as(
- report_id, SignalReportArtefact.ArtefactType.REPO_SELECTION, RepoSelectionResult
+ repo_selection = await SignalReportArtefact.alatest_content(
+ team_id=team_id, report_id=report_id, model=RepoSelectionResult
)
repository = repo_selection.repository if repo_selection is not None else None
if repo_selection is None or not repository:
@@ -1721,8 +1699,8 @@ async def maybe_autostart_from_report_artefacts(
reason="no repository selected",
)
return AutostartOutcome(status="blocked", reason="No repository selected")
- priority = await _latest_artefact_as(
- report_id, SignalReportArtefact.ArtefactType.PRIORITY_JUDGMENT, PriorityAssessment
+ priority = await SignalReportArtefact.alatest_content(
+ team_id=team_id, report_id=report_id, model=PriorityAssessment
)
# Only the pass that is the report's latest may supersede. `run_count` rises when the next pass
# *starts*, so it re-opens the supersede gate before that pass has concluded anything, and this
@@ -1730,11 +1708,8 @@ async def maybe_autostart_from_report_artefacts(
# earlier pass's decision then would open a replacement for a replacement, and the handover
# would close the pull request that is already under review. `last_run_at` is stamped when a
# pass starts, so a decision older than it belongs to a pass the report has moved on from.
- implementation_decision = await _latest_artefact_as(
- report_id,
- SignalReportArtefact.ArtefactType.IMPLEMENTATION_DECISION,
- ImplementationDecision,
- written_after=report.last_run_at,
+ implementation_decision = await SignalReportArtefact.alatest_content(
+ team_id=team_id, report_id=report_id, model=ImplementationDecision, created_after=report.last_run_at
)
# Empty / unresolved reviewers no longer short-circuit here: `maybe_autostart_implementation_task`
# falls back to the member who enabled signals for the team (for the system/scout path, gated by
diff --git a/products/signals/backend/models.py b/products/signals/backend/models.py
index c8957691db8e..cc6821e495a7 100644
--- a/products/signals/backend/models.py
+++ b/products/signals/backend/models.py
@@ -1,11 +1,12 @@
import json
import uuid
import logging
+import builtins
from collections import defaultdict
from collections.abc import Iterator, Sequence
from contextlib import ExitStack, contextmanager
from datetime import datetime, timedelta
-from typing import Any, cast
+from typing import Any, TypeVar, cast
from django.contrib.postgres.fields import ArrayField
from django.contrib.postgres.indexes import GinIndex
@@ -15,7 +16,7 @@ from django.utils import timezone
from django.utils.functional import Promise
from asgiref.sync import async_to_sync
-from pydantic import ValidationError
+from pydantic import BaseModel, ValidationError
from posthog.dataclasses import frozen
from posthog.migration_helpers import deprecate_field
@@ -37,6 +38,7 @@ from products.signals.backend.artefact_schemas import (
StatusArtefactContent,
TaskRunArtefact,
artefact_type_for,
+ artefact_type_for_model,
parse_artefact_content,
task_run_identifier_for_legacy_relationship,
)
@@ -1217,6 +1219,9 @@ def signal_report_artefact_type_choices() -> list[tuple[str, str | Promise]]:
return list(SignalReportArtefact.ArtefactType.choices)
+_ContentT = TypeVar("_ContentT", bound=BaseModel)
+
+
@frozen
class LatestActionability:
"""The `actionability` and `already_addressed` of a report's newest parseable judgment.
@@ -1538,6 +1543,75 @@ class SignalReportArtefact(UUIDModel):
cls._schedule_autostart_reevaluation(team_id=team_id, report_id=str(report_id))
return artefact
+ @classmethod
+ def _latest_of(
+ cls,
+ *,
+ team_id: int,
+ report_id: str,
+ model: builtins.type[BaseModel],
+ created_before: datetime | None,
+ created_after: datetime | None,
+ ) -> "models.QuerySet[SignalReportArtefact]":
+ artefacts = cls.objects.filter(team_id=team_id, report_id=report_id, type=artefact_type_for_model(model))
+ if created_before is not None:
+ artefacts = artefacts.filter(created_at__lte=created_before)
+ if created_after is not None:
+ artefacts = artefacts.filter(created_at__gte=created_after)
+ # `id` breaks a `created_at` tie, so two readers never disagree on which row is the latest.
+ return artefacts.order_by("-created_at", "-id").only("content")
+
+ @staticmethod
+ def _parse_as(artefact: "SignalReportArtefact | None", model: builtins.type[_ContentT]) -> _ContentT | None:
+ if artefact is None:
+ return None
+ try:
+ return model.model_validate_json(artefact.content)
+ except ValidationError:
+ return None
+
+ @classmethod
+ def latest_content(
+ cls,
+ *,
+ team_id: int,
+ report_id: str,
+ model: builtins.type[_ContentT],
+ created_before: datetime | None = None,
+ created_after: datetime | None = None,
+ ) -> _ContentT | None:
+ """The newest artefact of `model`'s type on the report, parsed, or None when there is none or
+ it doesn't parse. The read side of `append_status`: a status type's current value is its
+ newest row. `created_before` / `created_after` bound the rows considered, inclusively."""
+ artefact = cls._latest_of(
+ team_id=team_id,
+ report_id=report_id,
+ model=model,
+ created_before=created_before,
+ created_after=created_after,
+ ).first()
+ return cls._parse_as(artefact, model)
+
+ @classmethod
+ async def alatest_content(
+ cls,
+ *,
+ team_id: int,
+ report_id: str,
+ model: builtins.type[_ContentT],
+ created_before: datetime | None = None,
+ created_after: datetime | None = None,
+ ) -> _ContentT | None:
+ """Async `latest_content`."""
+ artefact = await cls._latest_of(
+ team_id=team_id,
+ report_id=report_id,
+ model=model,
+ created_before=created_before,
+ created_after=created_after,
+ ).afirst()
+ return cls._parse_as(artefact, model)
+
@classmethod
def append_finding(
cls,
diff --git a/products/signals/backend/pr_origin.py b/products/signals/backend/pr_origin.py
index e85a26b609cd..f40f4080ff43 100644
--- a/products/signals/backend/pr_origin.py
+++ b/products/signals/backend/pr_origin.py
@@ -14,13 +14,12 @@ from __future__ import annotations
import re
from bisect import bisect_right
-from datetime import date, datetime
-from typing import TypeVar
+from datetime import date
from django.conf import settings
import structlog
-from pydantic import BaseModel, ValidationError
+from pydantic import ValidationError
from posthog.dataclasses import frozen
from posthog.models import Team
@@ -60,8 +59,6 @@ _SECTION_END_RE = re.compile(rf"^(##[ \t]|---[ \t]*$|<!-- {ORIGIN_MARKER_PREFIX}
# validates their public links.
_ISSUE_TRACKER_PRODUCTS = frozenset({"linear", "github"})
-ArtefactModel = TypeVar("ArtefactModel", bound=BaseModel)
-
@frozen
class EntityPage:
@@ -142,25 +139,6 @@ def _source_lines(team_id: int, sources: list[OriginSource]) -> list[OriginSourc
return lines
-def _latest_artefact_as(
- team_id: int,
- report_id: str,
- artefact_type: str,
- model: type[ArtefactModel],
- created_before: datetime | None = None,
-) -> ArtefactModel | None:
- artefacts = SignalReportArtefact.objects.filter(team_id=team_id, report_id=report_id, type=artefact_type)
- if created_before is not None:
- artefacts = artefacts.filter(created_at__lte=created_before)
- artefact = artefacts.order_by("-created_at", "-id").first()
- if artefact is None:
- return None
- try:
- return model.model_validate_json(artefact.content)
- except ValidationError:
- return None
-
-
def _cause_commit(team_id: int, report_id: str, repository: str) -> OriginLink | None:
"""The first commit of the newest finding, which the research prompt orders causative first.
@@ -168,10 +146,8 @@ def _cause_commit(team_id: int, report_id: str, repository: str) -> OriginLink |
produce a hash that does not exist here. The commit links only when the suggested reviewers
carry the same commit under this pull request's repository.
"""
- finding = _latest_artefact_as(team_id, report_id, SignalReportArtefact.ArtefactType.SIGNAL_FINDING, SignalFinding)
- reviewers = _latest_artefact_as(
- team_id, report_id, SignalReportArtefact.ArtefactType.SUGGESTED_REVIEWERS, SuggestedReviewers
- )
+ finding = SignalReportArtefact.latest_content(team_id=team_id, report_id=report_id, model=SignalFinding)
+ reviewers = SignalReportArtefact.latest_content(team_id=team_id, report_id=report_id, model=SuggestedReviewers)
if finding is None or reviewers is None:
return None
commit_prefix = f"https://github.com/{repository}/commit/".lower()
@@ -209,12 +185,8 @@ def _run_start(team_id: int, report_id: str, task_id: str) -> RunStart | None:
task_run = TaskRunArtefact.model_validate_json(artefact.content)
except ValidationError:
continue
- judgment = _latest_artefact_as(
- team_id,
- report_id,
- SignalReportArtefact.ArtefactType.PRIORITY_JUDGMENT,
- PriorityAssessment,
- created_before=artefact.created_at,
+ judgment = SignalReportArtefact.latest_content(
+ team_id=team_id, report_id=report_id, model=PriorityAssessment, created_before=artefact.created_at
)
return RunStart(
automatic=task_run.automation_branch is not None,
diff --git a/products/signals/backend/scout_report/persistence.py b/products/signals/backend/scout_report/persistence.py
index fa4c21477d52..0a222afb4e9e 100644
--- a/products/signals/backend/scout_report/persistence.py
+++ b/products/signals/backend/scout_report/persistence.py
@@ -1283,22 +1283,6 @@ def set_scout_report_repository(
return True
-def _latest_status_artefact_content(
- report_id: str, artefact_type: str, model: type[ActionabilityAssessment] | type[PriorityAssessment]
-) -> ActionabilityAssessment | PriorityAssessment | None:
- row = (
- SignalReportArtefact.objects.filter(report_id=report_id, type=artefact_type)
- .order_by("-created_at", "-id")
- .first()
- )
- if row is None:
- return None
- try:
- return model.model_validate_json(row.content)
- except ValidationError:
- return None
-
-
def set_scout_report_decision(
*,
team_id: int,
@@ -1329,8 +1313,8 @@ def set_scout_report_decision(
raise InvalidScoutReportError(f"report {report_id} not found for team {team_id}")
# Compared under the lock: `edit_report` is non-idempotent, and a re-send must not log a
# second note or re-run auto-start for a decision that did not move.
- if actionability is not None and actionability != _latest_status_artefact_content(
- report_id, SignalReportArtefact.ArtefactType.ACTIONABILITY_JUDGMENT, ActionabilityAssessment
+ if actionability is not None and actionability != SignalReportArtefact.latest_content(
+ team_id=team_id, report_id=report_id, model=ActionabilityAssessment
):
SignalReportArtefact.append_status(
team_id=team_id, report_id=report_id, content=actionability, attribution=attribution
@@ -1345,8 +1329,8 @@ def set_scout_report_decision(
attribution=attribution,
)
changed.append("actionability")
- if priority is not None and priority != _latest_status_artefact_content(
- report_id, SignalReportArtefact.ArtefactType.PRIORITY_JUDGMENT, PriorityAssessment
+ if priority is not None and priority != SignalReportArtefact.latest_content(
+ team_id=team_id, report_id=report_id, model=PriorityAssessment
):
SignalReportArtefact.append_status(
team_id=team_id, report_id=report_id, content=priority, attribution=attribution
diff --git a/products/signals/backend/source_suggestions.py b/products/signals/backend/source_suggestions.py
index ca7bca5f5661..2820d19851a0 100644
--- a/products/signals/backend/source_suggestions.py
+++ b/products/signals/backend/source_suggestions.py
@@ -7,9 +7,6 @@ where each product declares what counts as its data, and it caches its answer pe
from __future__ import annotations
-import structlog
-from pydantic import ValidationError
-
from posthog.data_freshness import get_organization_data_freshness
from posthog.models import Team
from posthog.schema_enums import ProductKey
@@ -18,8 +15,6 @@ from products.signals.backend.artefact_schemas import SourceSuggestion
from products.signals.backend.enums import SuggestedSourceProduct
from products.signals.backend.models import SignalReportArtefact
-logger = structlog.get_logger(__name__)
-
def _opted_in(team: Team, product: SuggestedSourceProduct) -> bool:
# An opt-in counts before any data arrives, so a suggestion stops showing as soon as the team
@@ -51,20 +46,8 @@ def unused_suggestable_products(team: Team) -> list[SuggestedSourceProduct]:
def current_source_suggestion(team: Team, report_id: str) -> SourceSuggestion | None:
"""The report's latest suggestion, or None when it has none or the team now uses the product."""
- artefact = (
- SignalReportArtefact.objects.filter(
- team_id=team.id, report_id=report_id, type=SignalReportArtefact.ArtefactType.SOURCE_SUGGESTION
- )
- .order_by("-created_at")
- .only("id", "content")
- .first()
- )
- if artefact is None:
- return None
- try:
- suggestion = SourceSuggestion.model_validate_json(artefact.content)
- except ValidationError:
- logger.warning("signals.source_suggestion.invalid_content", report_id=report_id, artefact_id=str(artefact.id))
+ suggestion = SignalReportArtefact.latest_content(team_id=team.id, report_id=report_id, model=SourceSuggestion)
+ if suggestion is None:
return None
if suggestion.product not in unused_suggestable_products(team):
return None
diff --git a/products/signals/backend/test/test_signal_report_artefact_model.py b/products/signals/backend/test/test_signal_report_artefact_model.py
index dea91f13e0c2..d9030ed9f77f 100644
--- a/products/signals/backend/test/test_signal_report_artefact_model.py
+++ b/products/signals/backend/test/test_signal_report_artefact_model.py
@@ -301,6 +301,32 @@ class TestSignalReportArtefactHelpers(BaseTest):
# Current status is the latest row.
assert json.loads(rows[1].content)["priority"] == "P0"
+ def test_latest_content_breaks_a_created_at_tie_by_id(self):
+ report = self._report()
+ first = self._append_priority(report, "P2")
+ second = self._append_priority(report, "P0")
+ SignalReportArtefact.objects.filter(id__in=[first.id, second.id]).update(created_at=first.created_at)
+
+ latest = SignalReportArtefact.latest_content(
+ team_id=self.team.id, report_id=str(report.id), model=PriorityAssessment
+ )
+
+ expected = Priority.P0 if second.id > first.id else Priority.P2
+ assert latest is not None and latest.priority == expected
+
+ def test_latest_content_is_none_when_the_newest_row_does_not_parse(self):
+ report = self._report()
+ self._append_priority(report, "P2")
+ newest = self._append_priority(report, "P0")
+ SignalReportArtefact.objects.filter(id=newest.id).update(content=json.dumps({"explanation": "no priority"}))
+
+ assert (
+ SignalReportArtefact.latest_content(
+ team_id=self.team.id, report_id=str(report.id), model=PriorityAssessment
+ )
+ is None
+ )
+
def _append_actionability(
self, report: SignalReport, choice: str, *, already_addressed: bool = False
) -> SignalReportArtefact: