: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
feat(conversations): store ai triage outcome on ticket (#65747)
Alex V590ddc817596
diff --git a/products/conversations/backend/migrations/0040_ticket_ai_triage.py b/products/conversations/backend/migrations/0040_ticket_ai_triage.pynew file mode 100644index 000000000000..9111e8608870--- /dev/null+++ b/products/conversations/backend/migrations/0040_ticket_ai_triage.py@@ -0,0 +1,17 @@+# Generated by Django 5.2.14 on 2026-06-24 09:33++from django.db import migrations, models+++class Migration(migrations.Migration):+ dependencies = [+ ("conversations", "0039_ticket_teams_thread_replies_synced_at"),+ ]++ operations = [+ migrations.AddField(+ model_name="ticket",+ name="ai_triage",+ field=models.JSONField(blank=True, default=dict),+ ),+ ]diff --git a/products/conversations/backend/migrations/max_migration.txt b/products/conversations/backend/migrations/max_migration.txtindex 110bb2a77d5d..a3a5e6323313 100644--- a/products/conversations/backend/migrations/max_migration.txt+++ b/products/conversations/backend/migrations/max_migration.txt@@ -1 +1 @@-0039_ticket_teams_thread_replies_synced_at+0040_ticket_ai_triagediff --git a/products/conversations/backend/models/ticket.py b/products/conversations/backend/models/ticket.pyindex 73ca1ad84c2c..50bd99186026 100644--- a/products/conversations/backend/models/ticket.py+++ b/products/conversations/backend/models/ticket.py@@ -48,6 +48,7 @@ class Ticket(UUIDTModel):anonymous_traits = models.JSONField(default=dict, blank=True)ai_resolved = models.BooleanField(default=False)escalation_reason = models.TextField(null=True, blank=True)+ ai_triage = models.JSONField(default=dict, blank=True)# Unread message countersunread_customer_count = models.IntegerField(default=0) # Messages customer hasn't seen (from team/AI)diff --git a/products/conversations/backend/temporal/__init__.py b/products/conversations/backend/temporal/__init__.pyindex de41933fc7f5..5ffc8561022a 100644--- a/products/conversations/backend/temporal/__init__.py+++ b/products/conversations/backend/temporal/__init__.py@@ -8,6 +8,7 @@ from products.conversations.backend.temporal.pipeline import (support_classify_activity,support_draft_activity,support_persist_reply_activity,+ support_record_triage_activity,support_refine_queries_activity,support_retrieve_activity,support_review_reply_activity,@@ -30,5 +31,6 @@ ACTIVITIES = [support_validate_activity,support_review_reply_activity,support_persist_reply_activity,+ support_record_triage_activity,support_collect_eligible_tickets_activity,]diff --git a/products/conversations/backend/temporal/pipeline.py b/products/conversations/backend/temporal/pipeline.pyindex 2098dbdb8c84..b81ff8b67edd 100644--- a/products/conversations/backend/temporal/pipeline.py+++ b/products/conversations/backend/temporal/pipeline.py@@ -15,6 +15,8 @@ from temporalio.exceptions import ApplicationError# sandbox crashes workflow validation. Only the activities touch them at runtime, so pass# them through the sandbox unmodified.with workflow.unsafe.imports_passed_through():+ from django.db import transaction+import structlogfrom anthropic import APIErrorfrom pydantic import BaseModel, Field, model_validator@@ -425,6 +427,13 @@ class PersistReplyInput:confidence: float+@dataclass+class RecordTriageInput:+ team_id: int+ ticket_id: str+ patch: dict[str, Any]++@dataclassclass SafetyFilterInput:team_id: int@@ -1053,6 +1062,25 @@ def _persist_reply_sync(team_id: int, ticket_id: str, reply: str, citations: lis)[email protected](name="support-record-triage")+@close_db_connections+async def support_record_triage_activity(input: RecordTriageInput) -> None:+ """Merge triage/outcome metadata into the ticket's ai_triage JSON field."""+ await database_sync_to_async(_record_triage_sync, thread_sensitive=False)(+ input.team_id, input.ticket_id, input.patch+ )+++def _record_triage_sync(team_id: int, ticket_id: str, patch: dict[str, Any]) -> None:+ with transaction.atomic():+ ticket = Ticket.objects.select_for_update().filter(team_id=team_id, id=ticket_id).first()+ if ticket is None:+ return+ merged = {**(ticket.ai_triage or {}), **patch}+ ticket.ai_triage = merged+ ticket.save(update_fields=["ai_triage", "updated_at"])++# ---------------------------------------------------------------------------# Workflow# ---------------------------------------------------------------------------@@ -1069,6 +1097,28 @@ class SupportReplyWorkflow:@workflow.runasync def run(self, input: SupportReplyInput) -> str:+ team_id = input.team_id+ ticket_id = input.ticket_id+ wf_info = workflow.info()+ _triage_base: dict[str, Any] = {+ "schema_version": 1,+ "workflow_id": wf_info.workflow_id,+ "run_id": wf_info.run_id,+ }++ async def _record_triage(patch: dict[str, Any]) -> None:+ # Best-effort observability metadata — must never break the support pipeline, so+ # swallow failures here rather than letting a triage write abort the run.+ try:+ await workflow.execute_activity(+ support_record_triage_activity,+ RecordTriageInput(team_id=team_id, ticket_id=ticket_id, patch={**_triage_base, **patch}),+ start_to_close_timeout=timedelta(seconds=30),+ retry_policy=RetryPolicy(maximum_attempts=3),+ )+ except Exception:+ workflow.logger.warning("support_reply: failed to record triage", status=patch.get("status"))+# Build contextctx_output = await workflow.execute_activity(support_build_context_activity,@@ -1077,141 +1127,212 @@ class SupportReplyWorkflow:retry_policy=RetryPolicy(maximum_attempts=3),)+ # Record lifecycle start+ await _record_triage(+ {+ "status": "in_progress",+ "started_at": workflow.now().isoformat(),+ }+ )+# Slice once so the safety filter and draft agent see the exact same ticket text.reviewed_context = ctx_output.ticket_context[:MAX_SAFETY_REVIEWED_CHARS]- # Input safety gate: block prompt-injection / exfiltration attempts before any LLM- # draft work. Mirrored from the signals product's safety_filter_activity pattern.- safety_output = await workflow.execute_activity(- support_safety_filter_activity,- SafetyFilterInput(team_id=input.team_id, ticket_context=reviewed_context),- start_to_close_timeout=timedelta(minutes=2),- retry_policy=RetryPolicy(maximum_attempts=3),- )- if not safety_output.safe:- workflow.logger.info(- "support_reply: ticket blocked by safety filter",- threat_type=safety_output.threat_type,- )- return "blocked_unsafe"-- # Triage once, up front (not per attempt): the type + seed queries bias the whole- # loop, and `unactionable` tickets (spam/bare feedback) skip the expensive draft loop.- classify_output = await workflow.execute_activity(- support_classify_activity,- ClassifyInput(team_id=input.team_id, ticket_context=reviewed_context),- start_to_close_timeout=timedelta(minutes=2),- retry_policy=RetryPolicy(maximum_attempts=3),- )- if classify_output.ticket_type == "unactionable":- # Distinct outcome from `escalated_no_reply` (which means "tried and exhausted- # retries"): this ticket had no answerable question, so downstream routing/metrics- # can treat spam/feedback differently from genuine failed attempts.- workflow.logger.info("support_reply: ticket classified unactionable; skipping draft loop")- return "skipped_unactionable"-- ticket_type = classify_output.ticket_type-- missing: list[str] = []- prior_citations: list[str] = []- prior_reply: str = ""- best_reply: str = ""- best_confidence: float = 0.0- best_citations: list[str] = []- best_sources: list[dict[str, str]] = []- best_missing: list[str] = []-- for attempt in range(MAX_ATTEMPTS):- widen = attempt > 0-- # Refine queries- refine_output = await workflow.execute_activity(- support_refine_queries_activity,- RefineQueriesInput(- team_id=input.team_id,- ticket_context=reviewed_context,- missing=missing,- ticket_type=ticket_type,- seed_queries=classify_output.seed_queries,- ),+ # --- Outcome tracking: set before each return, recorded in finally ---+ outcome: dict[str, Any] = {}+ try:+ # Input safety gate: block prompt-injection / exfiltration attempts before any LLM+ # draft work. Mirrored from the signals product's safety_filter_activity pattern.+ safety_output = await workflow.execute_activity(+ support_safety_filter_activity,+ SafetyFilterInput(team_id=input.team_id, ticket_context=reviewed_context),start_to_close_timeout=timedelta(minutes=2),retry_policy=RetryPolicy(maximum_attempts=3),)-- # Retrieve + rerank- retrieve_output = await workflow.execute_activity(- support_retrieve_activity,- RetrieveInput(- team_id=input.team_id,- queries=refine_output.queries,- prior_citation_chunk_ids=prior_citations,- widen=widen,- ),- start_to_close_timeout=timedelta(minutes=3),+ if not safety_output.safe:+ workflow.logger.info(+ "support_reply: ticket blocked by safety filter",+ threat_type=safety_output.threat_type,+ )+ outcome = {"result": "blocked_unsafe"}+ return "blocked_unsafe"++ # Triage once, up front (not per attempt): the type + seed queries bias the whole+ # loop, and `unactionable` tickets (spam/bare feedback) skip the expensive draft loop.+ classify_output = await workflow.execute_activity(+ support_classify_activity,+ ClassifyInput(team_id=input.team_id, ticket_context=reviewed_context),+ start_to_close_timeout=timedelta(minutes=2),retry_policy=RetryPolicy(maximum_attempts=3),)+ if classify_output.ticket_type == "unactionable":+ # Distinct outcome from `escalated_no_reply` (which means "tried and exhausted+ # retries"): this ticket had no answerable question, so downstream routing/metrics+ # can treat spam/feedback differently from genuine failed attempts.+ workflow.logger.info("support_reply: ticket classified unactionable; skipping draft loop")+ outcome = {"result": "skipped_unactionable", "ticket_type": "unactionable"}+ return "skipped_unactionable"++ ticket_type = classify_output.ticket_type+ needs_diagnostics = classify_output.needs_diagnostics and ctx_output.diagnostics_allowed++ missing: list[str] = []+ prior_citations: list[str] = []+ prior_reply: str = ""+ best_reply: str = ""+ best_confidence: float = 0.0+ best_citations: list[str] = []+ best_sources: list[dict[str, str]] = []+ best_missing: list[str] = []++ for attempt in range(MAX_ATTEMPTS):+ widen = attempt > 0++ # Refine queries+ refine_output = await workflow.execute_activity(+ support_refine_queries_activity,+ RefineQueriesInput(+ team_id=input.team_id,+ ticket_context=reviewed_context,+ missing=missing,+ ticket_type=ticket_type,+ seed_queries=classify_output.seed_queries,+ ),+ start_to_close_timeout=timedelta(minutes=2),+ retry_policy=RetryPolicy(maximum_attempts=3),+ )- # Don't short-circuit on empty in-process retrieval — the draft agent has- # read-only MCP tools (PostHog docs via docs-search, the team's business- # knowledge) and can find sources itself. Seed chunks are just a head start.- if not retrieve_output.chunk_ids:- workflow.logger.info("support_reply: no seed chunks; drafting via MCP tools only")-- # Draft via sandbox- draft_output = await workflow.execute_activity(- support_draft_activity,- DraftInput(- team_id=input.team_id,- ticket_context=reviewed_context,- chunk_ids=retrieve_output.chunk_ids,- prior_reply=prior_reply,- prior_missing=missing,- always_on_context=ctx_output.always_on_context,- ticket_type=ticket_type,- # Only widen scopes when the classifier flagged diagnostics AND the team- # opted in — the toggle is the human consent gate for project-wide reads.- needs_diagnostics=classify_output.needs_diagnostics and ctx_output.diagnostics_allowed,- ),- start_to_close_timeout=timedelta(minutes=15),- retry_policy=RetryPolicy(maximum_attempts=2),- )+ # Retrieve + rerank+ retrieve_output = await workflow.execute_activity(+ support_retrieve_activity,+ RetrieveInput(+ team_id=input.team_id,+ queries=refine_output.queries,+ prior_citation_chunk_ids=prior_citations,+ widen=widen,+ ),+ start_to_close_timeout=timedelta(minutes=3),+ retry_policy=RetryPolicy(maximum_attempts=3),+ )- # Validate- validate_output = await workflow.execute_activity(- support_validate_activity,- ValidateInput(- team_id=input.team_id,- ticket_context=reviewed_context,- reply=draft_output.reply,- citations=draft_output.citations,- chunk_ids=retrieve_output.chunk_ids,- sources=draft_output.sources,- ticket_type=ticket_type,- ),- start_to_close_timeout=timedelta(minutes=2),- retry_policy=RetryPolicy(maximum_attempts=3),- )+ # Don't short-circuit on empty in-process retrieval — the draft agent has+ # read-only MCP tools (PostHog docs via docs-search, the team's business+ # knowledge) and can find sources itself. Seed chunks are just a head start.+ if not retrieve_output.chunk_ids:+ workflow.logger.info("support_reply: no seed chunks; drafting via MCP tools only")++ # Draft via sandbox+ draft_output = await workflow.execute_activity(+ support_draft_activity,+ DraftInput(+ team_id=input.team_id,+ ticket_context=reviewed_context,+ chunk_ids=retrieve_output.chunk_ids,+ prior_reply=prior_reply,+ prior_missing=missing,+ always_on_context=ctx_output.always_on_context,+ ticket_type=ticket_type,+ # Only widen scopes when the classifier flagged diagnostics AND the team+ # opted in — the toggle is the human consent gate for project-wide reads.+ needs_diagnostics=needs_diagnostics,+ ),+ start_to_close_timeout=timedelta(minutes=15),+ retry_policy=RetryPolicy(maximum_attempts=2),+ )- # Track best-so-far by the validator's confidence (the trusted score, same- # signal the threshold gate uses) — not the draft's self-reported confidence —- # so an escalated note carries an honest confidence and the best-validated draft.- if validate_output.confidence >= best_confidence:- best_reply = draft_output.reply- best_confidence = validate_output.confidence- best_citations = draft_output.citations- best_sources = draft_output.sources- best_missing = validate_output.missing-- if validate_output.confidence >= SCORE_THRESHOLD:- # Output safety gate: check for PII leaks / exfil before the reply reaches- # the (untrusted) ticket author.+ # Validate+ validate_output = await workflow.execute_activity(+ support_validate_activity,+ ValidateInput(+ team_id=input.team_id,+ ticket_context=reviewed_context,+ reply=draft_output.reply,+ citations=draft_output.citations,+ chunk_ids=retrieve_output.chunk_ids,+ sources=draft_output.sources,+ ticket_type=ticket_type,+ ),+ start_to_close_timeout=timedelta(minutes=2),+ retry_policy=RetryPolicy(maximum_attempts=3),+ )++ # Track best-so-far by the validator's confidence (the trusted score, same+ # signal the threshold gate uses) — not the draft's self-reported confidence —+ # so an escalated note carries an honest confidence and the best-validated draft.+ if validate_output.confidence >= best_confidence:+ best_reply = draft_output.reply+ best_confidence = validate_output.confidence+ best_citations = draft_output.citations+ best_sources = draft_output.sources+ best_missing = validate_output.missing++ if validate_output.confidence >= SCORE_THRESHOLD:+ # Output safety gate: check for PII leaks / exfil before the reply reaches+ # the (untrusted) ticket author.+ review_output = await workflow.execute_activity(+ support_review_reply_activity,+ ReviewReplyInput(+ team_id=input.team_id,+ ticket_context=reviewed_context,+ reply=draft_output.reply,+ sources=draft_output.sources,+ ticket_type=ticket_type,+ ),+ start_to_close_timeout=timedelta(minutes=2),+ retry_policy=RetryPolicy(maximum_attempts=3),+ )+ if not review_output.safe:+ workflow.logger.info(+ "support_reply: reply blocked by output review",+ reason=review_output.reason,+ )+ outcome = {+ "result": "blocked_unsafe_reply",+ "ticket_type": ticket_type,+ "needs_diagnostics": needs_diagnostics,+ "diagnostics_allowed": ctx_output.diagnostics_allowed,+ "confidence": validate_output.confidence,+ "attempts": attempt + 1,+ }+ return "blocked_unsafe_reply"++ await workflow.execute_activity(+ support_persist_reply_activity,+ PersistReplyInput(+ team_id=input.team_id,+ ticket_id=input.ticket_id,+ reply=draft_output.reply,+ citations=draft_output.citations,+ confidence=validate_output.confidence,+ ),+ start_to_close_timeout=timedelta(minutes=1),+ retry_policy=RetryPolicy(maximum_attempts=3),+ )+ outcome = {+ "result": "persisted",+ "ticket_type": ticket_type,+ "needs_diagnostics": needs_diagnostics,+ "diagnostics_allowed": ctx_output.diagnostics_allowed,+ "confidence": validate_output.confidence,+ "attempts": attempt + 1,+ }+ return f"persisted (confidence={validate_output.confidence:.2f}, attempts={attempt + 1})"++ # Prepare for next iteration: refine the best-validated draft (not necessarily+ # the last one, which may have drifted) using the gaps the validator found in it.+ missing = best_missing+ prior_citations = best_citations+ prior_reply = best_reply++ # Exhausted attempts — persist best if we have one with non-zero confidence+ if best_reply and best_confidence > 0:review_output = await workflow.execute_activity(support_review_reply_activity,ReviewReplyInput(team_id=input.team_id,ticket_context=reviewed_context,- reply=draft_output.reply,- sources=draft_output.sources,+ reply=best_reply,+ sources=best_sources,ticket_type=ticket_type,),start_to_close_timeout=timedelta(minutes=2),@@ -1222,6 +1343,14 @@ class SupportReplyWorkflow:"support_reply: reply blocked by output review",reason=review_output.reason,)+ outcome = {+ "result": "blocked_unsafe_reply",+ "ticket_type": ticket_type,+ "needs_diagnostics": needs_diagnostics,+ "diagnostics_allowed": ctx_output.diagnostics_allowed,+ "confidence": best_confidence,+ "attempts": MAX_ATTEMPTS,+ }return "blocked_unsafe_reply"await workflow.execute_activity(@@ -1229,54 +1358,39 @@ class SupportReplyWorkflow:PersistReplyInput(team_id=input.team_id,ticket_id=input.ticket_id,- reply=draft_output.reply,- citations=draft_output.citations,- confidence=validate_output.confidence,+ reply=best_reply,+ citations=best_citations,+ confidence=best_confidence,),start_to_close_timeout=timedelta(minutes=1),retry_policy=RetryPolicy(maximum_attempts=3),)- return f"persisted (confidence={validate_output.confidence:.2f}, attempts={attempt + 1})"-- # Prepare for next iteration: refine the best-validated draft (not necessarily- # the last one, which may have drifted) using the gaps the validator found in it.- missing = best_missing- prior_citations = best_citations- prior_reply = best_reply-- # Exhausted attempts — persist best if we have one with non-zero confidence- if best_reply and best_confidence > 0:- review_output = await workflow.execute_activity(- support_review_reply_activity,- ReviewReplyInput(- team_id=input.team_id,- ticket_context=reviewed_context,- reply=best_reply,- sources=best_sources,- ticket_type=ticket_type,- ),- start_to_close_timeout=timedelta(minutes=2),- retry_policy=RetryPolicy(maximum_attempts=3),- )- if not review_output.safe:- workflow.logger.info(- "support_reply: reply blocked by output review",- reason=review_output.reason,+ outcome = {+ "result": "escalated_with_best",+ "ticket_type": ticket_type,+ "needs_diagnostics": needs_diagnostics,+ "diagnostics_allowed": ctx_output.diagnostics_allowed,+ "confidence": best_confidence,+ "attempts": MAX_ATTEMPTS,+ }+ return f"escalated_with_best (confidence={best_confidence:.2f})"++ outcome = {+ "result": "escalated_no_reply",+ "ticket_type": ticket_type,+ "needs_diagnostics": needs_diagnostics,+ "diagnostics_allowed": ctx_output.diagnostics_allowed,+ "attempts": MAX_ATTEMPTS,+ }+ return "escalated_no_reply"+ finally:+ # `outcome` is only set on the workflow's own terminal branches; on an unexpected+ # crash it stays empty, so we never mark a failed run as "done".+ if outcome:+ await _record_triage(+ {+ **outcome,+ "status": "done",+ "finished_at": workflow.now().isoformat(),+ })- return "blocked_unsafe_reply"-- await workflow.execute_activity(- support_persist_reply_activity,- PersistReplyInput(- team_id=input.team_id,- ticket_id=input.ticket_id,- reply=best_reply,- citations=best_citations,- confidence=best_confidence,- ),- start_to_close_timeout=timedelta(minutes=1),- retry_policy=RetryPolicy(maximum_attempts=3),- )- return f"escalated_with_best (confidence={best_confidence:.2f})"-- return "escalated_no_reply"diff --git a/products/conversations/backend/temporal/tests/test_pipeline.py b/products/conversations/backend/temporal/tests/test_pipeline.pyindex 2a31f2e7b930..a53ba1e34af8 100644--- a/products/conversations/backend/temporal/tests/test_pipeline.py+++ b/products/conversations/backend/temporal/tests/test_pipeline.py@@ -7,6 +7,9 @@ from unittest.mock import AsyncMock, MagicMock, patchfrom parameterized import parameterized+from posthog.models import Organization, Team++from products.conversations.backend.models.ticket import Ticketfrom products.conversations.backend.temporal.pipeline import (MAX_ATTEMPTS,BuildContextOutput,@@ -19,10 +22,12 @@ from products.conversations.backend.temporal.pipeline import (SupportReplyInput,SupportReplyWorkflow,ValidateOutput,+ _record_triage_sync,support_build_context_activity,support_classify_activity,support_draft_activity,support_persist_reply_activity,+ support_record_triage_activity,support_refine_queries_activity,support_retrieve_activity,support_review_reply_activity,@@ -46,6 +51,7 @@ PIPELINE_MODULE = "products.conversations.backend.temporal.pipeline"@pytest.mark.django_db@pytest.mark.asyncio+@patch(f"{PIPELINE_MODULE}._record_triage_sync")@patch(f"{PIPELINE_MODULE}._persist_reply_sync")@patch(f"{PIPELINE_MODULE}._review_reply", new_callable=AsyncMock)@patch(f"{PIPELINE_MODULE}._validate", new_callable=AsyncMock)@@ -65,6 +71,7 @@ async def test_workflow_persists_on_high_score(mock_validate,mock_review,mock_persist,+ mock_record_triage,workflow_input,sample_chunk_ids,):@@ -99,6 +106,7 @@ async def test_workflow_persists_on_high_score(support_validate_activity,support_review_reply_activity,support_persist_reply_activity,+ support_record_triage_activity,],):result = await env.client.execute_workflow(@@ -116,6 +124,7 @@ async def test_workflow_persists_on_high_score(@pytest.mark.django_db@pytest.mark.asyncio+@patch(f"{PIPELINE_MODULE}._record_triage_sync")@patch(f"{PIPELINE_MODULE}._persist_reply_sync")@patch(f"{PIPELINE_MODULE}._review_reply", new_callable=AsyncMock)@patch(f"{PIPELINE_MODULE}._validate", new_callable=AsyncMock)@@ -135,6 +144,7 @@ async def test_workflow_widens_on_low_score(mock_validate,mock_review,mock_persist,+ mock_record_triage,workflow_input,sample_chunk_ids,):@@ -180,6 +190,7 @@ async def test_workflow_widens_on_low_score(support_validate_activity,support_review_reply_activity,support_persist_reply_activity,+ support_record_triage_activity,],):result = await env.client.execute_workflow(@@ -196,6 +207,7 @@ async def test_workflow_widens_on_low_score(@pytest.mark.django_db@pytest.mark.asyncio+@patch(f"{PIPELINE_MODULE}._record_triage_sync")@patch(f"{PIPELINE_MODULE}._persist_reply_sync")@patch(f"{PIPELINE_MODULE}._review_reply", new_callable=AsyncMock)@patch(f"{PIPELINE_MODULE}._validate", new_callable=AsyncMock)@@ -215,6 +227,7 @@ async def test_workflow_escalates_after_max_attempts(mock_validate,mock_review,mock_persist,+ mock_record_triage,workflow_input,sample_chunk_ids,):@@ -249,6 +262,7 @@ async def test_workflow_escalates_after_max_attempts(support_validate_activity,support_review_reply_activity,support_persist_reply_activity,+ support_record_triage_activity,],):result = await env.client.execute_workflow(@@ -265,6 +279,7 @@ async def test_workflow_escalates_after_max_attempts(@pytest.mark.django_db@pytest.mark.asyncio+@patch(f"{PIPELINE_MODULE}._record_triage_sync")@patch(f"{PIPELINE_MODULE}._persist_reply_sync")@patch(f"{PIPELINE_MODULE}._review_reply", new_callable=AsyncMock)@patch(f"{PIPELINE_MODULE}._validate", new_callable=AsyncMock)@@ -284,6 +299,7 @@ async def test_workflow_drafts_via_mcp_when_no_seed_chunks(mock_validate,mock_review,mock_persist,+ mock_record_triage,workflow_input,):from temporalio.testing import WorkflowEnvironment@@ -313,6 +329,7 @@ async def test_workflow_drafts_via_mcp_when_no_seed_chunks(support_validate_activity,support_review_reply_activity,support_persist_reply_activity,+ support_record_triage_activity,],):result = await env.client.execute_workflow(@@ -587,6 +604,7 @@ class TestSafetyFilterActivity:patch(f"{PIPELINE_MODULE}._validate", new_callable=AsyncMock) as mock_validate,patch(f"{PIPELINE_MODULE}._review_reply", new_callable=AsyncMock) as mock_review,patch(f"{PIPELINE_MODULE}._persist_reply_sync") as mock_persist,+ patch(f"{PIPELINE_MODULE}._record_triage_sync"),):async with await WorkflowEnvironment.start_time_skipping() as env:async with Worker(@@ -603,6 +621,7 @@ class TestSafetyFilterActivity:support_validate_activity,support_review_reply_activity,support_persist_reply_activity,+ support_record_triage_activity,],):result = await env.client.execute_workflow(@@ -703,6 +722,7 @@ class TestReviewReplyActivity:return_value=ReviewReplyOutput(safe=False, reason="reply dumps raw emails"),),patch(f"{PIPELINE_MODULE}._persist_reply_sync") as mock_persist,+ patch(f"{PIPELINE_MODULE}._record_triage_sync"),):async with await WorkflowEnvironment.start_time_skipping() as env:async with Worker(@@ -719,6 +739,7 @@ class TestReviewReplyActivity:support_validate_activity,support_review_reply_activity,support_persist_reply_activity,+ support_record_triage_activity,],):result = await env.client.execute_workflow(@@ -892,6 +913,7 @@ class TestValidateActivity:@pytest.mark.django_db@pytest.mark.asyncio+@patch(f"{PIPELINE_MODULE}._record_triage_sync")@patch(f"{PIPELINE_MODULE}._persist_reply_sync")@patch(f"{PIPELINE_MODULE}._review_reply", new_callable=AsyncMock)@patch(f"{PIPELINE_MODULE}._validate", new_callable=AsyncMock)@@ -911,6 +933,7 @@ async def test_always_on_context_plumbed_to_draft(mock_validate,mock_review,mock_persist,+ mock_record_triage,workflow_input,sample_chunk_ids,):@@ -949,6 +972,7 @@ async def test_always_on_context_plumbed_to_draft(support_validate_activity,support_review_reply_activity,support_persist_reply_activity,+ support_record_triage_activity,],):await env.client.execute_workflow(@@ -964,6 +988,7 @@ async def test_always_on_context_plumbed_to_draft(@pytest.mark.django_db@pytest.mark.asyncio+@patch(f"{PIPELINE_MODULE}._record_triage_sync")@patch(f"{PIPELINE_MODULE}._persist_reply_sync")@patch(f"{PIPELINE_MODULE}._review_reply", new_callable=AsyncMock)@patch(f"{PIPELINE_MODULE}._validate", new_callable=AsyncMock)@@ -983,6 +1008,7 @@ async def test_workflow_short_circuits_unactionable(mock_validate,mock_review,mock_persist,+ mock_record_triage,workflow_input,):from temporalio.testing import WorkflowEnvironment@@ -1007,6 +1033,7 @@ async def test_workflow_short_circuits_unactionable(support_validate_activity,support_review_reply_activity,support_persist_reply_activity,+ support_record_triage_activity,],):result = await env.client.execute_workflow(@@ -1025,6 +1052,7 @@ async def test_workflow_short_circuits_unactionable(@pytest.mark.django_db@pytest.mark.asyncio+@patch(f"{PIPELINE_MODULE}._record_triage_sync")@patch(f"{PIPELINE_MODULE}._persist_reply_sync")@patch(f"{PIPELINE_MODULE}._review_reply", new_callable=AsyncMock)@patch(f"{PIPELINE_MODULE}._validate", new_callable=AsyncMock)@@ -1044,6 +1072,7 @@ async def test_classify_runs_once_and_threads_ticket_type(mock_validate,mock_review,mock_persist,+ mock_record_triage,workflow_input,sample_chunk_ids,):@@ -1083,6 +1112,7 @@ async def test_classify_runs_once_and_threads_ticket_type(support_validate_activity,support_review_reply_activity,support_persist_reply_activity,+ support_record_triage_activity,],):await env.client.execute_workflow(@@ -1107,6 +1137,7 @@ async def test_classify_runs_once_and_threads_ticket_type(@pytest.mark.django_db@pytest.mark.asyncio+@patch(f"{PIPELINE_MODULE}._record_triage_sync")@patch(f"{PIPELINE_MODULE}._persist_reply_sync")@patch(f"{PIPELINE_MODULE}._review_reply", new_callable=AsyncMock)@patch(f"{PIPELINE_MODULE}._validate", new_callable=AsyncMock)@@ -1126,6 +1157,7 @@ async def test_diagnostics_gated_off_when_team_not_opted_in(mock_validate,mock_review,mock_persist,+ mock_record_triage,workflow_input,sample_chunk_ids,):@@ -1165,6 +1197,7 @@ async def test_diagnostics_gated_off_when_team_not_opted_in(support_validate_activity,support_review_reply_activity,support_persist_reply_activity,+ support_record_triage_activity,],):await env.client.execute_workflow(@@ -1270,3 +1303,261 @@ class TestClassifyActivity:inside, _, _ = after.partition("</ticket_context>")assert injection in insideassert injection not in before+++class TestRecordTriageActivity:+ @parameterized.expand(+ [+ (+ "persisted",+ ClassifyOutput(ticket_type="how_to", needs_diagnostics=False, seed_queries=["setup"]),+ SafetyFilterOutput(safe=True),+ ValidateOutput(grounded=True, coverage=0.9, confidence=0.85, missing=[]),+ ReviewReplyOutput(safe=True),+ "persisted",+ ),+ (+ "blocked_unsafe",+ None,+ SafetyFilterOutput(safe=False, threat_type="instruction_injection", explanation="bad"),+ None,+ None,+ "blocked_unsafe",+ ),+ (+ "skipped_unactionable",+ ClassifyOutput(ticket_type="unactionable", needs_diagnostics=False, seed_queries=[]),+ SafetyFilterOutput(safe=True),+ None,+ None,+ "skipped_unactionable",+ ),+ (+ "blocked_unsafe_reply",+ ClassifyOutput(ticket_type="how_to", needs_diagnostics=False, seed_queries=[]),+ SafetyFilterOutput(safe=True),+ ValidateOutput(grounded=True, coverage=0.9, confidence=0.9, missing=[]),+ ReviewReplyOutput(safe=False, reason="PII leak"),+ "blocked_unsafe_reply",+ ),+ ],+ )+ @pytest.mark.django_db+ @pytest.mark.asyncio+ async def test_records_triage_outcome_per_terminal_path(+ self,+ _name,+ classify_output,+ safety_output,+ validate_output,+ review_output,+ expected_result,+ ):+ from temporalio.testing import WorkflowEnvironment+ from temporalio.worker import Worker++ with (+ patch(+ f"{PIPELINE_MODULE}._build_context_sync",+ return_value=BuildContextOutput(ticket_context="help", ticket_title="Help"),+ ),+ patch(f"{PIPELINE_MODULE}._safety_filter", new_callable=AsyncMock, return_value=safety_output),+ patch(+ f"{PIPELINE_MODULE}._classify",+ new_callable=AsyncMock,+ return_value=classify_output or ClassifyOutput(ticket_type="how_to", needs_diagnostics=False),+ ),+ patch(+ f"{PIPELINE_MODULE}._refine_queries",+ new_callable=AsyncMock,+ return_value=RefineQueriesOutput(queries=["q"]),+ ),+ patch(+ f"{PIPELINE_MODULE}._retrieve_sync",+ return_value=RetrieveOutput(chunk_ids=["aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee"]),+ ),+ patch(+ f"{PIPELINE_MODULE}._draft_async",+ new_callable=AsyncMock,+ return_value=DraftOutput(+ reply="answer",+ citations=["aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee"],+ confidence=0.9,+ ),+ ),+ patch(+ f"{PIPELINE_MODULE}._validate",+ new_callable=AsyncMock,+ return_value=validate_output or ValidateOutput(grounded=True, coverage=0.9, confidence=0.9, missing=[]),+ ),+ patch(+ f"{PIPELINE_MODULE}._review_reply",+ new_callable=AsyncMock,+ return_value=review_output or ReviewReplyOutput(safe=True),+ ),+ patch(f"{PIPELINE_MODULE}._persist_reply_sync"),+ patch(f"{PIPELINE_MODULE}._record_triage_sync") as mock_record_triage,+ ):+ async with await WorkflowEnvironment.start_time_skipping() as env:+ async with Worker(+ env.client,+ task_queue="test-queue",+ workflows=[SupportReplyWorkflow],+ activities=[+ support_build_context_activity,+ support_safety_filter_activity,+ support_classify_activity,+ support_refine_queries_activity,+ support_retrieve_activity,+ support_draft_activity,+ support_validate_activity,+ support_review_reply_activity,+ support_persist_reply_activity,+ support_record_triage_activity,+ ],+ ):+ result = await env.client.execute_workflow(+ SupportReplyWorkflow.run,+ SupportReplyInput(team_id=1, ticket_id="deadbeef-0000-0000-0000-000000000001"),+ id=f"test-triage-{_name}",+ task_queue="test-queue",+ )++ assert expected_result in result++ # At least 2 calls: in_progress at start, done at terminal+ assert mock_record_triage.call_count >= 2++ # First call is always the in_progress lifecycle marker+ first_call_patch = mock_record_triage.call_args_list[0][0][2]+ assert first_call_patch["status"] == "in_progress"+ assert "started_at" in first_call_patch+ assert "workflow_id" in first_call_patch+ assert "run_id" in first_call_patch+ assert first_call_patch["schema_version"] == 1++ # Last call is the terminal outcome+ last_call_patch = mock_record_triage.call_args_list[-1][0][2]+ assert last_call_patch["status"] == "done"+ assert last_call_patch["result"] == expected_result+ assert "finished_at" in last_call_patch++ @pytest.mark.django_db+ @pytest.mark.asyncio+ async def test_escalated_no_reply_records_triage(self):+ from temporalio.testing import WorkflowEnvironment+ from temporalio.worker import Worker++ with (+ patch(+ f"{PIPELINE_MODULE}._build_context_sync",+ return_value=BuildContextOutput(ticket_context="help", ticket_title="Help"),+ ),+ patch(+ f"{PIPELINE_MODULE}._safety_filter", new_callable=AsyncMock, return_value=SafetyFilterOutput(safe=True)+ ),+ patch(+ f"{PIPELINE_MODULE}._classify",+ new_callable=AsyncMock,+ return_value=ClassifyOutput(ticket_type="how_to", needs_diagnostics=False, seed_queries=[]),+ ),+ patch(+ f"{PIPELINE_MODULE}._refine_queries",+ new_callable=AsyncMock,+ return_value=RefineQueriesOutput(queries=["q"]),+ ),+ patch(f"{PIPELINE_MODULE}._retrieve_sync", return_value=RetrieveOutput(chunk_ids=[])),+ patch(+ f"{PIPELINE_MODULE}._draft_async",+ new_callable=AsyncMock,+ return_value=DraftOutput(reply="", citations=[], confidence=0.0),+ ),+ patch(+ f"{PIPELINE_MODULE}._validate",+ new_callable=AsyncMock,+ return_value=ValidateOutput(grounded=False, coverage=0.0, confidence=0.0, missing=["everything"]),+ ),+ patch(+ f"{PIPELINE_MODULE}._review_reply", new_callable=AsyncMock, return_value=ReviewReplyOutput(safe=True)+ ),+ patch(f"{PIPELINE_MODULE}._persist_reply_sync"),+ patch(f"{PIPELINE_MODULE}._record_triage_sync") as mock_record_triage,+ ):+ async with await WorkflowEnvironment.start_time_skipping() as env:+ async with Worker(+ env.client,+ task_queue="test-queue",+ workflows=[SupportReplyWorkflow],+ activities=[+ support_build_context_activity,+ support_safety_filter_activity,+ support_classify_activity,+ support_refine_queries_activity,+ support_retrieve_activity,+ support_draft_activity,+ support_validate_activity,+ support_review_reply_activity,+ support_persist_reply_activity,+ support_record_triage_activity,+ ],+ ):+ result = await env.client.execute_workflow(+ SupportReplyWorkflow.run,+ SupportReplyInput(team_id=1, ticket_id="deadbeef-0000-0000-0000-000000000001"),+ id="test-triage-escalated-no-reply",+ task_queue="test-queue",+ )++ assert result == "escalated_no_reply"++ last_call_patch = mock_record_triage.call_args_list[-1][0][2]+ assert last_call_patch["status"] == "done"+ assert last_call_patch["result"] == "escalated_no_reply"+ assert last_call_patch["attempts"] == MAX_ATTEMPTS+++class TestRecordTriageSync:+ def _make_ticket(self) -> Ticket:+ org = Organization.objects.create(name="triage-org")+ team = Team.objects.create(organization=org, name="triage-team")+ return Ticket.objects.create_with_number(+ team=team,+ widget_session_id="triage-session",+ distinct_id="triage-distinct",+ )++ @pytest.mark.django_db+ def test_merge_accumulates_lifecycle_writes(self):+ # Guards the clobber regression: the terminal "done" write must merge into the+ # earlier "in_progress" write, not replace ai_triage wholesale.+ ticket = self._make_ticket()++ _record_triage_sync(+ ticket.team_id,+ str(ticket.id),+ {"schema_version": 1, "status": "in_progress", "started_at": "t0"},+ )+ _record_triage_sync(+ ticket.team_id,+ str(ticket.id),+ {"status": "done", "result": "persisted", "finished_at": "t1"},+ )++ ticket.refresh_from_db()+ assert ticket.ai_triage == {+ "schema_version": 1,+ "started_at": "t0",+ "status": "done",+ "result": "persisted",+ "finished_at": "t1",+ }++ @pytest.mark.django_db+ def test_missing_ticket_is_noop(self):+ ticket = self._make_ticket()++ # Wrong team_id must not match (and must not raise) — tenant isolation on the write path.+ _record_triage_sync(ticket.team_id + 1, str(ticket.id), {"status": "done"})++ ticket.refresh_from_db()+ assert ticket.ai_triage == {}