: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: debounce support AI replies until customer goes quiet (#66602)
Alex V6a9e83de05aa
diff --git a/products/conversations/backend/temporal/coordinator.py b/products/conversations/backend/temporal/coordinator.pyindex 642476413b1d..012ccf11d7de 100644--- a/products/conversations/backend/temporal/coordinator.py+++ b/products/conversations/backend/temporal/coordinator.py@@ -2,13 +2,14 @@ from __future__ import annotationsimport jsonfrom dataclasses import dataclass-from datetime import timedelta+from datetime import datetime, timedeltafrom temporalio import activity, workflowfrom temporalio.common import RetryPolicy, WorkflowIDReusePolicyfrom temporalio.exceptions import WorkflowAlreadyStartedErrorwith workflow.unsafe.imports_passed_through():+ from django.db.models import Qfrom django.utils import timezoneimport structlog@@ -25,7 +26,18 @@ with workflow.unsafe.imports_passed_through():logger = structlog.get_logger(__name__)COORDINATOR_INTERVAL_MINUTES = 1-TICKET_LOOKBACK_MINUTES = 2++# Settle/debounce window: don't draft until the customer has been quiet (no new message) for this+# long. Lets someone raise a ticket and immediately fire off 1-2 follow-ups without the AI drafting+# off only the first message. The reference is max(ticket.created_at, latest customer comment), so a+# brand-new ticket also waits this long before its first draft — the latency we trade for completeness.+TICKET_SETTLE_MINUTES = 2++# Scan window. Keyed on last_message_at (the same axis the settle gate uses), so a ticket stays+# eligible until SETTLE after its *last* customer message, regardless of how long ago it was created+# — a late follow-up can't push the settle deadline past the scan window and silently drop the+# ticket. Only needs to exceed SETTLE + interval + a little slack for a slow tick.+TICKET_LOOKBACK_MINUTES = 5# Fanout caps so public ticket volume can't directly turn into unbounded sandbox/LLM work.# A single opted-in team that gets flooded with externally-created tickets can only spend@@ -85,11 +97,18 @@ def _is_rollout_enabled(ticket_id: str) -> bool:def _collect_eligible(lookback_minutes: int = TICKET_LOOKBACK_MINUTES) -> list[EligibleTicket]:"""Sync DB scan for eligible tickets. Runs in a worker thread."""- cutoff = timezone.now() - timedelta(minutes=lookback_minutes)- recent_tickets = Ticket.objects.filter(created_at__gte=cutoff).select_related("team__organization")-- # First pass: the cheap per-ticket gates that don't touch the comments table.- candidates: list[tuple[int, str]] = []+ now = timezone.now()+ cutoff = now - timedelta(minutes=lookback_minutes)+ # last_message_at is the debounce axis; fall back to created_at for tickets whose denormalized+ # timestamp hasn't landed yet (set via a post-commit signal, so there's a brief null window).+ recent_tickets = Ticket.objects.filter(+ Q(last_message_at__gte=cutoff) | Q(last_message_at__isnull=True, created_at__gte=cutoff)+ ).select_related("team__organization")++ # First pass: the cheap per-ticket gates that don't touch the comments table. We keep+ # created_at around so a ticket with no customer comments yet still settles from its own+ # creation time (the initial message), not just from follow-up comments.+ candidates: list[tuple[int, str, datetime]] = []for ticket in recent_tickets:team = ticket.team@@ -110,40 +129,54 @@ def _collect_eligible(lookback_minutes: int = TICKET_LOOKBACK_MINUTES) -> list[Eif MIN_READY_BK_SOURCES > 0 and not has_ready_sources(team.id):continue- candidates.append((team.id, str(ticket.id)))+ candidates.append((team.id, str(ticket.id), ticket.created_at))if not candidates:return []- # Dedupe in one query per team instead of two `.exists()` round-trips per ticket. A ticket- # is "already engaged" iff it has any comment that isn't from the customer: our own AI note- # ("AI") or a human/team reply ("support"/"team", or "human" from the compose flow). Keying- # the query on (team_id, scope, item_id) keeps it on the matching index.+ # One comment query per team instead of round-trips per ticket. Two things come out of it:+ # 1. Dedupe: a ticket is "already engaged" iff it has any non-customer comment — our own AI+ # note ("AI") or a human/team reply ("support"/"team"/"human"). Those are excluded below.+ # 2. Settle/debounce: the latest customer comment timestamp per ticket. Since engaged tickets+ # are dropped anyway, for everything we actually consider the latest customer comment is+ # simply the latest message on the ticket. Keying on (team_id, scope, item_id) hits the index.by_team: dict[int, list[str]] = {}- for team_id, ticket_id_str in candidates:+ for team_id, ticket_id_str, _created_at in candidates:by_team.setdefault(team_id, []).append(ticket_id_str)engaged: set[str] = set()+ latest_customer_msg: dict[str, datetime] = {}for team_id, ticket_ids in by_team.items():- for item_id, author_type in Comment.objects.filter(+ for item_id, author_type, comment_created_at in Comment.objects.filter(team_id=team_id,scope="conversations_ticket",item_id__in=ticket_ids,- ).values_list("item_id", "item_context__author_type"):+ ).values_list("item_id", "item_context__author_type", "created_at"):if author_type != "customer":engaged.add(item_id)-- # Rollout is sampled last (after the cheap gates and dedupe) so we don't burn the bucket on- # tickets that were never going to run. Per-team and global caps bound how many child- # workflows a single tick can fan out so externally-created ticket volume can't directly- # translate into unbounded LLM work; overflow rolls to the next tick (still in lookback).+ continue+ prev = latest_customer_msg.get(item_id)+ if prev is None or comment_created_at > prev:+ latest_customer_msg[item_id] = comment_created_at++ # Rollout is sampled last (after the cheap gates, dedupe, and settle window) so we don't burn+ # the bucket on tickets that were never going to run this tick. Per-team and global caps bound+ # how many child workflows a single tick can fan out so externally-created ticket volume can't+ # directly translate into unbounded LLM work; overflow rolls to the next tick (still in lookback).+ settle_cutoff = now - timedelta(minutes=TICKET_SETTLE_MINUTES)eligible: list[EligibleTicket] = []per_team_counts: dict[int, int] = {}- for team_id, ticket_id_str in candidates:+ for team_id, ticket_id_str, created_at in candidates:if len(eligible) >= MAX_TICKETS_PER_RUN:breakif ticket_id_str in engaged:continue+ # Settle: wait until the customer has gone quiet. Reference is the most recent customer+ # activity — max(ticket creation, latest customer comment). If that's newer than the+ # cutoff the ticket is still settling; skip it and let a later tick pick it up.+ last_activity = max(created_at, latest_customer_msg.get(ticket_id_str, created_at))+ if last_activity > settle_cutoff:+ continueif per_team_counts.get(team_id, 0) >= MAX_TICKETS_PER_TEAM_PER_RUN:continueif not _is_rollout_enabled(ticket_id_str):@@ -169,11 +202,10 @@ class SupportReplyCoordinatorWorkflow:Dispatch is fire-and-forget via ParentClosePolicy.ABANDON. Child workflow IDs aredeterministic per ticket (`support-reply-<ticket_id>`), so the same ticket can't be drafted- twice while a run is in flight (the lookback window of 6m intentionally overlaps the 5m- schedule interval): a running child conflicts on its id before its AI note lands and the DB- dedupe can see it. ALLOW_DUPLICATE_FAILED_ONLY still lets a later tick retry a ticket whose- prior pipeline run failed. ScheduleOverlapPolicy.SKIP only guards against a slow tick- overlapping the next one.+ twice while a run is in flight (the lookback window intentionally overlaps the schedule+ interval): a running child conflicts on its id before its AI note lands and the DB dedupe can+ see it. ALLOW_DUPLICATE_FAILED_ONLY still lets a later tick retry a ticket whose prior pipeline+ run failed. ScheduleOverlapPolicy.SKIP only guards against a slow tick overlapping the next one."""@staticmethoddiff --git a/products/conversations/backend/temporal/tests/test_coordinator.py b/products/conversations/backend/temporal/tests/test_coordinator.pyindex f5025d937c9b..486aac7d88a9 100644--- a/products/conversations/backend/temporal/tests/test_coordinator.py+++ b/products/conversations/backend/temporal/tests/test_coordinator.py@@ -1,10 +1,13 @@from __future__ import annotationsimport uuid+from datetime import timedeltaimport pytestfrom unittest.mock import MagicMock, patch+from django.utils import timezone+from parameterized import parameterizedfrom temporalio import workflow@@ -40,6 +43,7 @@ def _make_ticket(has_team_reply: bool = False,channel_source: str = "widget",ai_resolution_channels: list[str] | None = None,+ created_minutes_ago: int = 10,):ticket_id = ticket_id or str(uuid.uuid4())org = MagicMock()@@ -55,6 +59,8 @@ def _make_ticket(ticket.id = uuid.UUID(ticket_id)ticket.team = teamticket.channel_source = channel_source+ # Default well past the settle window so eligibility tests aren't gated on debounce.+ ticket.created_at = timezone.now() - timedelta(minutes=created_minutes_ago)return ticket, ticket_id, team@@ -109,12 +115,13 @@ class TestCollectEligible:mock_ticket_model.objects.filter.return_value.select_related.return_value = [ticket]mock_has_ready.return_value = has_ready- # Dedupe is one query per team: .filter().values_list("item_id", author_type) rows.- rows: list[tuple[str, str]] = []+ # One query per team: .filter().values_list("item_id", author_type, created_at) rows.+ now = timezone.now()+ rows: list[tuple[str, str, object]] = []if has_ai:- rows.append((ticket_id, "AI"))+ rows.append((ticket_id, "AI", now))if has_team_reply:- rows.append((ticket_id, "support"))+ rows.append((ticket_id, "support", now))mock_comment_model.objects.filter.return_value.values_list.return_value = rowsmock_rollout.return_value = rollout@@ -195,11 +202,112 @@ class TestCollectEligible:mock_ticket_model.objects.filter.return_value.select_related.return_value = [ticket]# AI note exists → engaged → skipped.- mock_comment_model.objects.filter.return_value.values_list.return_value = [(ticket_id, "AI")]+ mock_comment_model.objects.filter.return_value.values_list.return_value = [(ticket_id, "AI", timezone.now())]result = _collect_eligible()assert result == []+ @parameterized.expand(+ [+ # (name, ticket_created_min_ago, latest_customer_msg_min_ago | None, expected_eligible)+ ("fresh_ticket_no_comments_still_settling", 0, None, False),+ ("old_ticket_no_comments_settled", 30, None, True),+ ("recent_customer_followup_still_settling", 30, 0, False),+ ("old_customer_followup_settled", 30, 30, True),+ ]+ )+ @patch(f"{COORD_MODULE}._is_rollout_enabled", return_value=True)+ @patch(f"{COORD_MODULE}.has_ready_sources", return_value=True)+ @patch(f"{COORD_MODULE}.Comment")+ @patch(f"{COORD_MODULE}.Ticket")+ @patch(f"{COORD_MODULE}._is_master_flag_enabled", return_value=True)+ def test_settle_window_gates_until_customer_goes_quiet(+ self,+ _name,+ created_min_ago,+ last_msg_min_ago,+ expected_eligible,+ mock_master_flag,+ mock_ticket_model,+ mock_comment_model,+ mock_has_ready,+ mock_rollout,+ ):+ # Guards the debounce: a ticket whose customer just sent a message (or was just created)+ # must not be drafted until they've gone quiet for TICKET_SETTLE_MINUTES, so follow-up+ # messages get folded into the same draft. Drop the settle gate and the two "still_settling"+ # cases start returning the ticket immediately.+ ticket, ticket_id, team = _make_ticket(created_minutes_ago=created_min_ago)+ mock_ticket_model.objects.filter.return_value.select_related.return_value = [ticket]++ rows: list[tuple[str, str, object]] = []+ if last_msg_min_ago is not None:+ rows.append((ticket_id, "customer", timezone.now() - timedelta(minutes=last_msg_min_ago)))+ mock_comment_model.objects.filter.return_value.values_list.return_value = rows++ result = _collect_eligible()+ assert (len(result) == 1) == expected_eligible+++class TestCollectEligibleScanWindow:+ @parameterized.expand(+ [+ # (name, last_customer_msg_min_ago, expected_collected)+ # Ticket is always created far outside the lookback window; eligibility must follow the+ # last message, not creation time.+ ("recent_message_old_ticket_collected", 3, True),+ ("quiet_too_long_dropped", 30, False),+ ]+ )+ @pytest.mark.django_db+ @patch(f"{COORD_MODULE}._is_rollout_enabled", return_value=True)+ @patch(f"{COORD_MODULE}._is_master_flag_enabled", return_value=True)+ def test_scan_keys_on_last_message_not_created_at(+ self,+ _name,+ last_msg_min_ago,+ expected_collected,+ mock_master_flag,+ mock_rollout,+ ):+ # Models imported lazily: this module defines a @workflow.defn stub, so Temporal's sandbox+ # re-imports the whole file during validation and top-level Django ORM imports break it.+ from posthog.models import Organization, Team+ from posthog.models.comment import Comment++ from products.conversations.backend.models.ticket import Ticket as TicketModel++ # Guards the scan dimension: a ticket created long ago (well outside TICKET_LOOKBACK_MINUTES)+ # but with a recent customer message must still be collected — revert the queryset to+ # `created_at`-only and this 60-min-old ticket is silently dropped despite a fresh message.+ org = Organization.objects.create(name="Org")+ team = Team.objects.create(+ organization=org, name="Team", conversations_settings={"ai_suggestions_enabled": True}+ )+ ticket = TicketModel.objects.create_with_number(+ team=team,+ widget_session_id="aabbccdd-0000-0000-0000-000000000001",+ distinct_id="u1",+ channel_source="widget",+ )+ msg_at = timezone.now() - timedelta(minutes=last_msg_min_ago)+ # created_at is auto_now_add and last_message_at is set by a post-commit signal that doesn't+ # fire here, so pin both directly to decouple creation time from last-activity time.+ TicketModel.objects.filter(id=ticket.id).update(+ created_at=timezone.now() - timedelta(minutes=60), last_message_at=msg_at+ )+ comment = Comment.objects.create(+ team=team,+ scope="conversations_ticket",+ item_id=str(ticket.id),+ content="hi",+ item_context={"author_type": "customer", "is_private": False},+ )+ Comment.objects.filter(id=comment.id).update(created_at=msg_at)++ result = _collect_eligible()+ assert [t.ticket_id for t in result] == ([str(ticket.id)] if expected_collected else [])+class TestCoordinatorWorkflow:@pytest.mark.asyncio