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(conversations): stop persisting ticket-specific knowledge gaps (#97210)

Alex V4d45bdbf5ebe
diff --git a/products/conversations/backend/temporal/ai_reply/activities/persist_knowledge_gap.py b/products/conversations/backend/temporal/ai_reply/activities/persist_knowledge_gap.py
index dffe14617368..f60d253c640c 100644
--- a/products/conversations/backend/temporal/ai_reply/activities/persist_knowledge_gap.py
+++ b/products/conversations/backend/temporal/ai_reply/activities/persist_knowledge_gap.py
@@ -22,7 +22,7 @@ logger = structlog.get_logger(__name__)
@activity.defn
@close_db_connections
async def support_persist_knowledge_gap_activity(input: PersistKnowledgeGapInput) -> None:
- """Record knowledge gaps from the support pipeline as suggestions for the BK product."""
+ """Record gaps scheduled by workflow histories without the deferral patch."""
if not input.missing:
return
created = await database_sync_to_async(_persist_sync, thread_sensitive=False)(input)
diff --git a/products/conversations/backend/temporal/ai_reply/constants.py b/products/conversations/backend/temporal/ai_reply/constants.py
index 1bd42ff35c05..10f91670b1c8 100644
--- a/products/conversations/backend/temporal/ai_reply/constants.py
+++ b/products/conversations/backend/temporal/ai_reply/constants.py
@@ -3,6 +3,9 @@ from uuid import UUID
MAX_ATTEMPTS = 5
+# Histories without this marker must retain the legacy persistence command during replay.
+DEFER_KNOWLEDGE_GAPS_UNTIL_RESOLUTION_PATCH = "defer-knowledge-gaps-until-resolution-2026-09"
+
# Stable namespace for deterministic per-ticket trace ids (uuid5).
AI_REPLY_TRACE_NAMESPACE = UUID("a1b2c3d4-5678-4e9f-ab12-cd34ef567890")
SCORE_THRESHOLD = 0.5
diff --git a/products/conversations/backend/temporal/pipeline.py b/products/conversations/backend/temporal/pipeline.py
index 750e27290a00..7eda6f0432a3 100644
--- a/products/conversations/backend/temporal/pipeline.py
+++ b/products/conversations/backend/temporal/pipeline.py
@@ -22,6 +22,7 @@ from products.conversations.backend.temporal.ai_reply.activities.safety_filter i
from products.conversations.backend.temporal.ai_reply.activities.validate import support_validate_activity
from products.conversations.backend.temporal.ai_reply.constants import (
AI_REPLY_TRACE_NAMESPACE,
+ DEFER_KNOWLEDGE_GAPS_UNTIL_RESOLUTION_PATCH,
MAX_ATTEMPTS,
MAX_SAFETY_REVIEWED_CHARS,
SCORE_THRESHOLD,
@@ -47,7 +48,6 @@ from products.conversations.backend.temporal.ai_reply.schemas import (
with workflow.unsafe.imports_passed_through():
pass
-
# ---------------------------------------------------------------------------
# Workflow
# ---------------------------------------------------------------------------
@@ -110,7 +110,7 @@ class SupportReplyWorkflow:
async def _persist_gaps(gap_missing: list[str], gap_ticket_type: str, gap_outcome: str) -> None:
"""Best-effort: record knowledge gaps without breaking the pipeline."""
- if not gap_missing:
+ if not gap_missing or workflow.patched(DEFER_KNOWLEDGE_GAPS_UNTIL_RESOLUTION_PATCH):
return
try:
await workflow.execute_activity(
diff --git a/products/conversations/backend/temporal/tests/test_pipeline.py b/products/conversations/backend/temporal/tests/test_pipeline.py
index 5fc690404064..e8f6980e03b8 100644
--- a/products/conversations/backend/temporal/tests/test_pipeline.py
+++ b/products/conversations/backend/temporal/tests/test_pipeline.py
@@ -12,6 +12,9 @@ from posthog.models import Organization, Team
from products.conversations.backend.models.ticket import Ticket
from products.conversations.backend.temporal.ai_reply.activities.classify import _classify
from products.conversations.backend.temporal.ai_reply.activities.draft import _draft_async
+from products.conversations.backend.temporal.ai_reply.activities.persist_knowledge_gap import (
+ support_persist_knowledge_gap_activity,
+)
from products.conversations.backend.temporal.ai_reply.activities.persist_reply import _persist_reply_sync
from products.conversations.backend.temporal.ai_reply.activities.record_triage import _record_triage_sync
from products.conversations.backend.temporal.ai_reply.activities.refine_queries import _refine_queries
@@ -84,11 +87,14 @@ DRAFT_MODULE = f"{ACTIVITIES}.draft"
VALIDATE_MODULE = f"{ACTIVITIES}.validate"
REVIEW_REPLY_MODULE = f"{ACTIVITIES}.review_reply"
PERSIST_REPLY_MODULE = f"{ACTIVITIES}.persist_reply"
+PERSIST_KNOWLEDGE_GAP_MODULE = f"{ACTIVITIES}.persist_knowledge_gap"
RECORD_TRIAGE_MODULE = f"{ACTIVITIES}.record_triage"
+PIPELINE_MODULE = "products.conversations.backend.temporal.pipeline"
@pytest.mark.django_db
@pytest.mark.asyncio
+@patch(f"{PERSIST_KNOWLEDGE_GAP_MODULE}._persist_sync")
@patch(f"{RECORD_TRIAGE_MODULE}._record_triage_sync")
@patch(f"{PERSIST_REPLY_MODULE}._persist_reply_sync")
@patch(f"{REVIEW_REPLY_MODULE}._review_reply", new_callable=AsyncMock)
@@ -110,6 +116,7 @@ async def test_workflow_persists_on_high_score(
mock_review,
mock_persist,
mock_record_triage,
+ mock_persist_gaps,
workflow_input,
sample_chunk_ids,
):
@@ -126,7 +133,12 @@ async def test_workflow_persists_on_high_score(
citations=["aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee"],
confidence=0.9,
)
- mock_validate.return_value = ValidateOutput(grounded=True, coverage=0.9, confidence=0.85, missing=[])
+ mock_validate.return_value = ValidateOutput(
+ grounded=True,
+ coverage=0.9,
+ confidence=0.85,
+ missing=["setup prerequisites"],
+ )
mock_review.return_value = ReviewReplyOutput(safe=True)
async with await WorkflowEnvironment.start_time_skipping() as env:
@@ -144,6 +156,7 @@ async def test_workflow_persists_on_high_score(
support_validate_activity,
support_review_reply_activity,
support_persist_reply_activity,
+ support_persist_knowledge_gap_activity,
support_record_triage_activity,
],
):
@@ -158,6 +171,7 @@ async def test_workflow_persists_on_high_score(
assert "confidence=0.85" in result
assert "attempts=1" in result
mock_persist.assert_called_once()
+ mock_persist_gaps.assert_not_called()
@pytest.mark.django_db
@@ -241,10 +255,14 @@ async def test_workflow_widens_on_low_score(
assert "persisted" in result
assert validate_count["n"] == 3
assert mock_refine.call_count >= 3
+ refine_missing = [call.args[0].missing for call in mock_refine.call_args_list]
+ assert refine_missing[0] == []
+ assert ["pricing info"] in refine_missing[1:]
@pytest.mark.django_db
@pytest.mark.asyncio
+@patch(f"{PERSIST_KNOWLEDGE_GAP_MODULE}._persist_sync")
@patch(f"{RECORD_TRIAGE_MODULE}._record_triage_sync")
@patch(f"{PERSIST_REPLY_MODULE}._persist_reply_sync")
@patch(f"{REVIEW_REPLY_MODULE}._review_reply", new_callable=AsyncMock)
@@ -255,7 +273,7 @@ async def test_workflow_widens_on_low_score(
@patch(f"{CLASSIFY_MODULE}._classify", new_callable=AsyncMock)
@patch(f"{SAFETY_FILTER_MODULE}._safety_filter", new_callable=AsyncMock)
@patch(f"{BUILD_CONTEXT_MODULE}._build_context_sync")
-async def test_workflow_escalates_after_max_attempts(
+async def test_workflow_replays_pre_patch_gap_persistence(
mock_build,
mock_safety,
mock_classify,
@@ -266,11 +284,12 @@ async def test_workflow_escalates_after_max_attempts(
mock_review,
mock_persist,
mock_record_triage,
+ mock_persist_gaps,
workflow_input,
sample_chunk_ids,
):
from temporalio.testing import WorkflowEnvironment
- from temporalio.worker import Worker
+ from temporalio.worker import Replayer, UnsandboxedWorkflowRunner, Worker
mock_build.return_value = BuildContextOutput(ticket_context="Complex question", ticket_title="Complex")
mock_safety.return_value = SafetyFilterOutput(safe=True)
@@ -300,19 +319,32 @@ async def test_workflow_escalates_after_max_attempts(
support_validate_activity,
support_review_reply_activity,
support_persist_reply_activity,
+ support_persist_knowledge_gap_activity,
support_record_triage_activity,
],
+ workflow_runner=UnsandboxedWorkflowRunner(),
):
- result = await env.client.execute_workflow(
- SupportReplyWorkflow.run,
- workflow_input,
- id="test-escalate-max-attempts",
- task_queue="test-queue",
- )
+ with patch(f"{PIPELINE_MODULE}.workflow.patched", return_value=False):
+ handle = await env.client.start_workflow(
+ SupportReplyWorkflow.run,
+ workflow_input,
+ id="test-replay-pre-patch-gap-persistence",
+ task_queue="test-queue",
+ )
+ result = await handle.result()
+ pre_patch_history = await handle.fetch_history()
assert "escalated_with_best" in result
assert mock_validate.call_count == MAX_ATTEMPTS
mock_persist.assert_called_once()
+ mock_persist_gaps.assert_called_once()
+ last_triage = mock_record_triage.call_args_list[-1][0][0].patch
+ assert last_triage["missing"] == ["everything"]
+
+ await Replayer(
+ workflows=[SupportReplyWorkflow],
+ workflow_runner=UnsandboxedWorkflowRunner(),
+ ).replay_workflow(pre_patch_history)
@pytest.mark.django_db