: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
fix(prompts): validate reference targets before a label activates a version (#105091)
Juraj Majerik70be676d7f1d
diff --git a/posthog/api/llm_prompt.py b/posthog/api/llm_prompt.pyindex 5515748bc5a1..2086294fae9a 100644--- a/posthog/api/llm_prompt.py+++ b/posthog/api/llm_prompt.py@@ -3,7 +3,7 @@ from typing import Any, castfrom uuid import UUIDfrom django.conf import settings-from django.db import IntegrityError+from django.db import IntegrityError, OperationalErrorfrom django.db.models import Func, IntegerField, Q, QuerySet, TextFieldfrom django.db.models.functions import Cast@@ -728,6 +728,16 @@ class LLMPromptViewSet({"detail": "This label was changed by someone else at the same time. Try again."},status=status.HTTP_409_CONFLICT,)+ except OperationalError as err:+ # Reference validation locks the referenced prompts' rows, so two+ # moves over mutually referencing labels can deadlock; Postgres+ # aborts one. A retry serializes behind the survivor.+ if "deadlock detected" not in str(err):+ raise+ return Response(+ {"detail": "Another label or reference change touched the same prompts at the same time. Try again."},+ status=status.HTTP_409_CONFLICT,+ )except LLMPromptLabelLimitError as err:return Response({diff --git a/posthog/api/services/llm_prompt.py b/posthog/api/services/llm_prompt.pyindex cbbd06dc1763..341c3ff508cd 100644--- a/posthog/api/services/llm_prompt.py+++ b/posthog/api/services/llm_prompt.py@@ -27,6 +27,7 @@ from products.ai_observability.backend.prompt_references import (parse_prompt_references,record_prompt_references,validate_prompt_references,+ validate_reference_targets,)SYNC_ARCHIVE_VERSION_INVALIDATION_LIMIT = 100@@ -463,6 +464,13 @@ def set_prompt_label(if target is None:raise LLMPromptNotFoundError()+ # Labeling activates the target's content for fetches, and this is the+ # one write path where that content was validated in the past rather+ # than now: its references may have gone dead since (the referenced+ # prompt archived while only inactive versions pointed at it).+ if isinstance(target.prompt, str) and parse_prompt_references(target.prompt):+ validate_reference_targets(team.id, prompt_name=prompt_name, prompt_payload=target.prompt)+# A referenced label is part of other prompts' assembled content, so it# must keep pointing at a version those prompts can splice in. An# unreferenced label can move freely.diff --git a/posthog/api/test/test_llm_prompt.py b/posthog/api/test/test_llm_prompt.pyindex d527c2acefd6..4e8401a9392b 100644--- a/posthog/api/test/test_llm_prompt.py+++ b/posthog/api/test/test_llm_prompt.py@@ -4,7 +4,7 @@ from typing import Anyfrom posthog.test.base import APIBaseTestfrom unittest.mock import patch-from django.db import connection+from django.db import OperationalError, connectionfrom django.test import SimpleTestCase, override_settingsfrom django.test.utils import CaptureQueriesContextfrom django.utils import timezone@@ -2351,3 +2351,44 @@ class TestLLMPromptDependenciesAPI(APIBaseTest):f"/api/environments/{self.team.id}/llm_prompts/?label=production&content=full&resolve=false")assert raw.json()["results"][0]["prompt"] == "@@@prompt:name=guardrails|label=shared@@@"++ def test_label_cannot_activate_a_version_whose_references_went_dead(self):+ self._make_prompt("dep")+ self.client.post(+ f"/api/environments/{self.team.id}/llm_prompts/",+ data={"name": "base", "prompt": "@@@prompt:name=dep|version=1@@@"},+ format="json",+ )+ # v2 drops the reference, so archiving dep is legal: only the inactive v1 points at it.+ self.client.patch(+ f"/api/environments/{self.team.id}/llm_prompts/name/base/",+ data={"prompt": "standalone", "base_version": 1},+ format="json",+ )+ assert (+ self.client.post(f"/api/environments/{self.team.id}/llm_prompts/name/dep/archive/").status_code+ == status.HTTP_204_NO_CONTENT+ )++ response = self.client.put(+ f"/api/environments/{self.team.id}/llm_prompts/name/base/labels/production/",+ data={"version": 1},+ format="json",+ )++ assert response.status_code == status.HTTP_400_BAD_REQUEST+ assert response.json()["code"] == "reference_not_found"++ def test_label_move_deadlock_is_a_retryable_conflict(self):+ self._make_prompt("base")+ with patch(+ "posthog.api.llm_prompt.set_prompt_label",+ side_effect=OperationalError("deadlock detected"),+ ):+ response = self.client.put(+ f"/api/environments/{self.team.id}/llm_prompts/name/base/labels/production/",+ data={"version": 1},+ format="json",+ )+ assert response.status_code == status.HTTP_409_CONFLICT+ assert "Try again" in response.json()["detail"]diff --git a/products/ai_observability/backend/prompt_references.py b/products/ai_observability/backend/prompt_references.pyindex ae40e6c2ca70..1a0949ba4b88 100644--- a/products/ai_observability/backend/prompt_references.py+++ b/products/ai_observability/backend/prompt_references.py@@ -136,10 +136,34 @@ def validate_prompt_references(team_id: int, *, prompt_name: str, prompt_payloadif not references:return- # Resolution splices content at every occurrence, so the assembled-size- # check has to weigh a repeated tag once per occurrence.- occurrence_counts = Counter(all_references)+ referenced_by = get_active_referencing_parent_names(team_id, prompt_name)+ if referenced_by:+ raise _reference_error(+ f"This prompt is referenced by {', '.join(referenced_by)}. "+ "A referenced prompt cannot contain references of its own.",+ "referenced_prompt_cannot_reference",+ )++ validate_reference_targets(team_id, prompt_name=prompt_name, prompt_payload=prompt_payload)+++def validate_reference_targets(team_id: int, *, prompt_name: str, prompt_payload: Any) -> None:+ """Reject content whose reference targets cannot resolve right now.++ The resolvability half of validate_prompt_references, without the+ incoming-reference depth check: pointing a label at a version whose+ content holds references is legal while nothing references that label,+ but the targets must still exist. Runs inside the caller's transaction+ for the same lock-ordering reasons.+ """+ text = normalize_prompt_to_string(prompt_payload)+ all_references = parse_prompt_references(text)+ references = sorted(set(all_references), key=lambda r: (r.name, r.version or 0, r.label or ""))+ if not references:+ return+ # Checked here rather than only at publish so content written before the+ # cap existed cannot activate more references through a label.if len(references) > MAX_PROMPT_REFERENCES:raise _reference_error(f"A prompt can reference at most {MAX_PROMPT_REFERENCES} other prompts. "@@ -147,13 +171,9 @@ def validate_prompt_references(team_id: int, *, prompt_name: str, prompt_payload"too_many_references",)- referenced_by = get_active_referencing_parent_names(team_id, prompt_name)- if referenced_by:- raise _reference_error(- f"This prompt is referenced by {', '.join(referenced_by)}. "- "A referenced prompt cannot contain references of its own.",- "referenced_prompt_cannot_reference",- )+ # Resolution splices content at every occurrence, so the assembled-size+ # check has to weigh a repeated tag once per occurrence.+ occurrence_counts = Counter(all_references)# True assembled size: the tags are replaced by content at resolution,# so their bytes leave the total.