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): ingest Teams shared-channel thread replies (#64888)

Alex V78e1b61253ee
diff --git a/products/conversations/backend/api/tests/test_teams_shared_channel_polling.py b/products/conversations/backend/api/tests/test_teams_shared_channel_polling.py
index 083413975159..7fced76aafe3 100644
--- a/products/conversations/backend/api/tests/test_teams_shared_channel_polling.py
+++ b/products/conversations/backend/api/tests/test_teams_shared_channel_polling.py
@@ -16,7 +16,11 @@ from products.conversations.backend.support_teams import (
refresh_graph_token,
store_teams_service_url,
)
-from products.conversations.backend.tasks import poll_team_shared_channels, poll_teams_shared_channels
+from products.conversations.backend.tasks import (
+ _sync_shared_channel_thread_replies,
+ poll_team_shared_channels,
+ poll_teams_shared_channels,
+)
from products.conversations.backend.teams import (
graph_message_to_activity,
graph_reply_to_activity,
@@ -99,7 +103,9 @@ class TestGraphReplyToActivity(BaseTest):
("normal_reply", _graph_message(reply_to_id="root-1"), True),
("deleted_reply", _graph_message(reply_to_id="root-1", deleted=True), False),
("app_authored", _graph_message(reply_to_id="root-1", user_id=None), False),
- ("wrong_root", _graph_message(reply_to_id="other-root"), False),
+ # The /replies endpoint is already scoped to the root thread, so a replyToId
+ # that differs from the root (nested quote-reply) is still ingested.
+ ("nested_reply_to_id", _graph_message(reply_to_id="other-root"), True),
("empty_body", _graph_message(reply_to_id="root-1", content=" "), False),
]
)
@@ -367,6 +373,156 @@ class TestPollSharedChannelThreadReplies(BaseTest):
ticket.refresh_from_db()
self.assertIsNotNone(ticket.teams_thread_replies_synced_at)
+ def _prime_and_create_root_ticket(self, mock_get: MagicMock) -> Ticket:
+ """Prime the channel, create a single root-message ticket, and reset its
+ reply watermark to a fixed early time (the empty post-creation sweep otherwise
+ stamps it with ``now()``, which would skip fixed-timestamp test replies)."""
+ from datetime import UTC, datetime
+
+ mock_get.side_effect = [
+ _channel_verify_resp(),
+ _resp(json_data={"value": [], "@odata.deltaLink": "DELTA1"}),
+ ]
+ poll_team_shared_channels(self.team.id)
+
+ mock_get.side_effect = [
+ _resp(json_data={"value": [_graph_message(msg_id="root-1")], "@odata.deltaLink": "DELTA2"}),
+ _resp(json_data={"value": []}),
+ ]
+ poll_team_shared_channels(self.team.id)
+ ticket = Ticket.objects.filter(team=self.team).get()
+ ticket.teams_thread_replies_synced_at = datetime(2024, 1, 1, 0, 0, 0, tzinfo=UTC)
+ ticket.save(update_fields=["teams_thread_replies_synced_at"])
+ return ticket
+
+ @patch("products.conversations.backend.tasks.requests.get")
+ def test_reply_with_mismatched_reply_to_id_is_ingested(self, mock_get: MagicMock, *_: Any) -> None:
+ from posthog.models.comment import Comment
+
+ ticket = self._prime_and_create_root_ticket(mock_get)
+
+ mock_get.side_effect = [
+ _resp(json_data={"value": [], "@odata.deltaLink": "DELTA3"}),
+ _resp(
+ json_data={
+ "value": [
+ _graph_message(
+ msg_id="reply-nested",
+ reply_to_id="some-other-message",
+ content="<p>nested quote reply</p>",
+ created_at="2024-06-01T12:00:00Z",
+ )
+ ]
+ }
+ ),
+ ]
+ poll_team_shared_channels(self.team.id)
+
+ self.assertEqual(Comment.objects.filter(team=self.team, item_id=str(ticket.id)).count(), 2)
+
+ @patch("products.conversations.backend.tasks.requests.get")
+ def test_reply_within_watermark_lookback_is_ingested(self, mock_get: MagicMock, *_: Any) -> None:
+ from datetime import UTC, datetime
+
+ from posthog.models.comment import Comment
+
+ ticket = self._prime_and_create_root_ticket(mock_get)
+ # Watermark slightly ahead of the reply's createdDateTime: without the lookback
+ # buffer the reply would be skipped as "already synced".
+ ticket.teams_thread_replies_synced_at = datetime(2024, 6, 1, 12, 0, 0, tzinfo=UTC)
+ ticket.save(update_fields=["teams_thread_replies_synced_at"])
+
+ mock_get.side_effect = [
+ _resp(json_data={"value": [], "@odata.deltaLink": "DELTA3"}),
+ _resp(
+ json_data={
+ "value": [
+ _graph_message(
+ msg_id="reply-skew",
+ reply_to_id="root-1",
+ content="<p>arrived a touch before the watermark</p>",
+ created_at="2024-06-01T11:58:00Z",
+ )
+ ]
+ }
+ ),
+ ]
+ poll_team_shared_channels(self.team.id)
+
+ self.assertEqual(Comment.objects.filter(team=self.team, item_id=str(ticket.id)).count(), 2)
+
+ @patch("products.conversations.backend.tasks.requests.get")
+ def test_reply_dedupe_holds_across_runs(self, mock_get: MagicMock, *_: Any) -> None:
+ from posthog.models.comment import Comment
+
+ ticket = self._prime_and_create_root_ticket(mock_get)
+
+ reply_page = {
+ "value": [
+ _graph_message(
+ msg_id="reply-dupe",
+ reply_to_id="root-1",
+ content="<p>same reply twice</p>",
+ created_at="2024-06-01T12:00:00Z",
+ )
+ ]
+ }
+ for delta in ("DELTA3", "DELTA4"):
+ mock_get.side_effect = [
+ _resp(json_data={"value": [], "@odata.deltaLink": delta}),
+ _resp(json_data=reply_page),
+ ]
+ poll_team_shared_channels(self.team.id)
+
+ self.assertEqual(Comment.objects.filter(team=self.team, item_id=str(ticket.id)).count(), 2)
+
+ @patch("products.conversations.backend.tasks.TEAMS_REPLIES_MAX_TICKETS_PER_CHANNEL", 0)
+ @patch("products.conversations.backend.tasks.requests.get")
+ def test_delta_surfaced_ticket_synced_outside_round_robin(self, mock_get: MagicMock, *_: Any) -> None:
+ from posthog.models.comment import Comment
+
+ ticket = self._prime_and_create_root_ticket(mock_get)
+ conversation_id = ticket.teams_conversation_id
+ assert conversation_id is not None
+
+ reply_page = _resp(
+ json_data={
+ "value": [
+ _graph_message(
+ msg_id="reply-delta",
+ reply_to_id="root-1",
+ content="<p>surfaced by delta</p>",
+ created_at="2024-06-01T12:00:00Z",
+ )
+ ]
+ }
+ )
+
+ # Round-robin selection is empty (max=0): without the surfaced id nothing syncs.
+ mock_get.side_effect = None
+ mock_get.return_value = reply_page
+ _sync_shared_channel_thread_replies(
+ team=self.team,
+ tenant_id="tenant-abc",
+ token="graph-token",
+ teams_team_id=TEAMS_TEAM_ID,
+ channel_id=CHANNEL_ID,
+ service_url=TRUSTED_SERVICE_URL,
+ )
+ self.assertEqual(Comment.objects.filter(team=self.team, item_id=str(ticket.id)).count(), 1)
+
+ # Passing the surfaced conversation id pulls the reply despite the empty window.
+ _sync_shared_channel_thread_replies(
+ team=self.team,
+ tenant_id="tenant-abc",
+ token="graph-token",
+ teams_team_id=TEAMS_TEAM_ID,
+ channel_id=CHANNEL_ID,
+ service_url=TRUSTED_SERVICE_URL,
+ surfaced_conversation_ids={conversation_id},
+ )
+ self.assertEqual(Comment.objects.filter(team=self.team, item_id=str(ticket.id)).count(), 2)
+
class TestStoreTeamsServiceUrl(BaseTest):
def setUp(self) -> None:
diff --git a/products/conversations/backend/tasks.py b/products/conversations/backend/tasks.py
index 2c7a0cfd24ea..e97fefb12b1a 100644
--- a/products/conversations/backend/tasks.py
+++ b/products/conversations/backend/tasks.py
@@ -910,6 +910,14 @@ TEAMS_REPLIES_MAX_PAGES_PER_TICKET = 5
TEAMS_REPLIES_MAX_TICKETS_PER_CHANNEL = 20
# Only poll threads on tickets created within this window.
TEAMS_REPLIES_TICKET_AGE_DAYS = 30
+# Re-scan a small window behind the watermark so replies aren't silently dropped when
+# Graph's createdDateTime and our stored watermark disagree by a few seconds (clock skew
+# between the polling worker and Graph). Dedup downstream makes the overlap harmless.
+TEAMS_REPLIES_WATERMARK_LOOKBACK = timedelta(minutes=5)
+# Safety cap on delta-triggered reply fetches per run. Delta only surfaces threads with
+# fresh activity (so this is naturally traffic-bounded), but a pathological burst across
+# many threads shouldn't fan out into unbounded Graph /replies calls in a single run.
+TEAMS_REPLIES_MAX_DELTA_TRIGGERED_PER_CHANNEL = 50
def _sync_one_ticket_thread_replies(
@@ -925,9 +933,16 @@ def _sync_one_ticket_thread_replies(
"""Ingest new thread replies for one shared-channel ticket via Graph."""
root_message_id = parse_teams_root_message_id(ticket.teams_conversation_id)
if not root_message_id:
+ logger.debug(
+ "poll_teams_shared_channel_replies_no_root",
+ team_id=team.id,
+ channel_id=channel_id,
+ ticket_id=str(ticket.id),
+ )
return
- watermark = ticket.teams_thread_replies_synced_at or ticket.created_at
+ raw_watermark = ticket.teams_thread_replies_synced_at or ticket.created_at
+ watermark = raw_watermark - TEAMS_REPLIES_WATERMARK_LOOKBACK
latest_synced_at = ticket.teams_thread_replies_synced_at
url: str | None = (
@@ -935,6 +950,10 @@ def _sync_one_ticket_thread_replies(
)
headers = {"Authorization": f"Bearer {token}"}
pages = 0
+ replies_fetched = 0
+ # "matched" = reply resolved to this ticket (covers both new comments and dedup
+ # hits); create_or_update_teams_ticket doesn't distinguish, so we don't claim to.
+ replies_matched = 0
while url and pages < TEAMS_REPLIES_MAX_PAGES_PER_TICKET:
pages += 1
@@ -961,6 +980,7 @@ def _sync_one_ticket_thread_replies(
data = resp.json()
replies = data.get("value") or []
+ replies_fetched += len(replies)
page_had_failure = False
for reply in replies:
@@ -989,6 +1009,8 @@ def _sync_one_ticket_thread_replies(
page_had_failure = True
continue
+ if result:
+ replies_matched += 1
if result and msg_created and (latest_synced_at is None or msg_created > latest_synced_at):
latest_synced_at = msg_created
@@ -997,11 +1019,60 @@ def _sync_one_ticket_thread_replies(
url = data.get("@odata.nextLink")
+ if replies_fetched:
+ logger.info(
+ "poll_teams_shared_channel_replies_synced",
+ team_id=team.id,
+ channel_id=channel_id,
+ ticket_id=str(ticket.id),
+ root_message_id=root_message_id,
+ replies_fetched=replies_fetched,
+ replies_matched=replies_matched,
+ watermark=raw_watermark.isoformat(),
+ )
+
new_watermark = latest_synced_at or timezone.now()
if new_watermark != ticket.teams_thread_replies_synced_at:
Ticket.objects.filter(id=ticket.id, team=team).update(teams_thread_replies_synced_at=new_watermark)
+def _sync_ticket_thread_replies_safe(
+ *,
+ team: Team,
+ tenant_id: str,
+ token: str,
+ teams_team_id: str,
+ channel_id: str,
+ service_url: str,
+ ticket: Ticket,
+) -> None:
+ """Run ``_sync_one_ticket_thread_replies`` with the standard error handling."""
+ try:
+ _sync_one_ticket_thread_replies(
+ team=team,
+ tenant_id=tenant_id,
+ token=token,
+ teams_team_id=teams_team_id,
+ channel_id=channel_id,
+ service_url=service_url,
+ ticket=ticket,
+ )
+ except requests.RequestException:
+ logger.warning(
+ "poll_teams_shared_channel_replies_network_error",
+ team_id=team.id,
+ channel_id=channel_id,
+ ticket_id=str(ticket.id),
+ )
+ except Exception:
+ logger.exception(
+ "poll_teams_shared_channel_replies_unexpected",
+ team_id=team.id,
+ channel_id=channel_id,
+ ticket_id=str(ticket.id),
+ )
+
+
def _sync_shared_channel_thread_replies(
*,
team: Team,
@@ -1010,14 +1081,26 @@ def _sync_shared_channel_thread_replies(
teams_team_id: str,
channel_id: str,
service_url: str,
+ surfaced_conversation_ids: set[str] | None = None,
) -> None:
- """Pull new thread replies for every Teams ticket in a shared channel."""
+ """Pull new thread replies for every Teams ticket in a shared channel.
+
+ ``surfaced_conversation_ids`` are threads delta saw activity on this run; their
+ tickets are always synced (on top of the round-robin selection) so a fresh reply
+ is pulled the same minute even when the ticket isn't in the oldest-synced window.
+ """
sync = TeamConversationsTeamsChannelSync.objects.for_team(team.id).filter(channel_id=channel_id).first()
if not sync or not sync.primed:
+ logger.debug(
+ "poll_teams_shared_channel_replies_not_primed",
+ team_id=team.id,
+ channel_id=channel_id,
+ has_sync=bool(sync),
+ )
return
age_cutoff = timezone.now() - timedelta(days=TEAMS_REPLIES_TICKET_AGE_DAYS)
- tickets = (
+ tickets = list(
Ticket.objects.filter(
team=team,
channel_source=Channel.TEAMS,
@@ -1030,31 +1113,44 @@ def _sync_shared_channel_thread_replies(
.order_by(F("teams_thread_replies_synced_at").asc(nulls_first=True))[:TEAMS_REPLIES_MAX_TICKETS_PER_CHANNEL]
)
- for ticket in tickets:
- try:
- _sync_one_ticket_thread_replies(
+ selected_ids = {ticket.id for ticket in tickets}
+ delta_triggered = 0
+ if surfaced_conversation_ids:
+ surfaced_tickets = (
+ Ticket.objects.filter(
team=team,
- tenant_id=tenant_id,
- token=token,
- teams_team_id=teams_team_id,
- channel_id=channel_id,
- service_url=service_url,
- ticket=ticket,
- )
- except requests.RequestException:
- logger.warning(
- "poll_teams_shared_channel_replies_network_error",
- team_id=team.id,
- channel_id=channel_id,
- ticket_id=str(ticket.id),
- )
- except Exception:
- logger.exception(
- "poll_teams_shared_channel_replies_unexpected",
- team_id=team.id,
- channel_id=channel_id,
- ticket_id=str(ticket.id),
+ channel_source=Channel.TEAMS,
+ teams_channel_id=channel_id,
+ teams_conversation_id__in=surfaced_conversation_ids,
)
+ .exclude(status=Status.RESOLVED)
+ .exclude(id__in=selected_ids)
+ .order_by(F("teams_thread_replies_synced_at").asc(nulls_first=True))[
+ :TEAMS_REPLIES_MAX_DELTA_TRIGGERED_PER_CHANNEL
+ ]
+ )
+ for ticket in surfaced_tickets:
+ tickets.append(ticket)
+ delta_triggered += 1
+
+ logger.debug(
+ "poll_teams_shared_channel_replies_tickets_selected",
+ team_id=team.id,
+ channel_id=channel_id,
+ tickets_selected=len(tickets),
+ delta_triggered=delta_triggered,
+ )
+
+ for ticket in tickets:
+ _sync_ticket_thread_replies_safe(
+ team=team,
+ tenant_id=tenant_id,
+ token=token,
+ teams_team_id=teams_team_id,
+ channel_id=channel_id,
+ service_url=service_url,
+ ticket=ticket,
+ )
def _poll_one_shared_channel(
@@ -1065,13 +1161,16 @@ def _poll_one_shared_channel(
teams_team_id: str,
channel_id: str,
service_url: str,
-) -> None:
+) -> set[str]:
"""Pull new top-level messages for one shared channel via Graph messages/delta.
First run for a channel primes the delta cursor without ingesting (no history
dump); subsequent runs map each new root message onto the existing ticket path.
Idempotency is handled by ``create_or_update_teams_ticket`` (dedup on
channel + normalized conversation id), so re-delivering a message is a no-op.
+
+ Returns the set of conversation ids whose root message delta re-surfaced this run,
+ so the caller can prioritize their thread-reply sync.
"""
sync, created = TeamConversationsTeamsChannelSync.objects.for_team(team.id).get_or_create(
channel_id=channel_id,
@@ -1097,7 +1196,7 @@ def _poll_one_shared_channel(
status=ch_resp.status_code,
)
sync.delete()
- return
+ return set()
url: str | None = sync.delta_link or (
f"{GRAPH_API_BASE}/teams/{teams_team_id}/channels/{channel_id}/messages/delta"
@@ -1107,6 +1206,10 @@ def _poll_one_shared_channel(
new_delta_link: str | None = None
latest_message_at: datetime | None = None
pages = 0
+ # Root messages delta re-surfaced this run (Graph bumps a root's lastModifiedDateTime
+ # when a thread reply lands). Their tickets get a targeted reply sync below so the
+ # reply is pulled the same minute, independent of the round-robin reply sweep.
+ surfaced_conversation_ids: set[str] = set()
while url and pages < TEAMS_DELTA_MAX_PAGES_PER_RUN:
pages += 1
@@ -1119,10 +1222,10 @@ def _poll_one_shared_channel(
sync.last_polled_at = timezone.now()
sync.save(update_fields=["delta_link", "primed", "last_polled_at", "updated_at"])
logger.info("poll_teams_shared_channel_resync", team_id=team.id, channel_id=channel_id)
- return
+ return set()
if resp.status_code == 429:
logger.warning("poll_teams_shared_channel_throttled", team_id=team.id, channel_id=channel_id)
- return
+ return set()
if resp.status_code in (401, 402, 403):
# 401: token rejected (next run refreshes if stale). 402: metered/payment
# gate. 403: lost channel membership / missing scope. Skip, don't crash.
@@ -1132,7 +1235,7 @@ def _poll_one_shared_channel(
channel_id=channel_id,
status=resp.status_code,
)
- return
+ return set()
if resp.status_code != 200:
logger.warning(
"poll_teams_shared_channel_error",
@@ -1140,7 +1243,7 @@ def _poll_one_shared_channel(
channel_id=channel_id,
status=resp.status_code,
)
- return
+ return set()
data = resp.json()
messages = data.get("value") or []
@@ -1153,6 +1256,9 @@ def _poll_one_shared_channel(
activity = graph_message_to_activity(msg, channel_id, service_url)
if activity is None:
continue
+ conversation_id = (activity.get("conversation") or {}).get("id")
+ if conversation_id:
+ surfaced_conversation_ids.add(conversation_id)
try:
create_or_update_teams_ticket(
team=team,
@@ -1199,6 +1305,11 @@ def _poll_one_shared_channel(
sync.save(update_fields=update_fields)
+ # Delta only surfaces roots, never the replies themselves. A re-surfaced root signals
+ # thread activity, so the caller passes these ids to the reply sweep to pull their
+ # replies the same minute regardless of the round-robin selection.
+ return surfaced_conversation_ids
+
@shared_task(ignore_result=True)
@skip_team_scope_audit
@@ -1239,7 +1350,7 @@ def poll_team_shared_channels(team_id: int) -> None:
if not channel_id or not teams_team_id:
continue
try:
- _poll_one_shared_channel(
+ surfaced_conversation_ids = _poll_one_shared_channel(
team=team,
tenant_id=tenant_id,
token=token,
@@ -1254,6 +1365,7 @@ def poll_team_shared_channels(team_id: int) -> None:
teams_team_id=teams_team_id,
channel_id=channel_id,
service_url=service_url,
+ surfaced_conversation_ids=surfaced_conversation_ids,
)
except requests.RequestException:
logger.warning("poll_teams_shared_channel_network_error", team_id=team_id, channel_id=channel_id)
diff --git a/products/conversations/backend/teams.py b/products/conversations/backend/teams.py
index 5fbc8482b74f..8417aaf07729 100644
--- a/products/conversations/backend/teams.py
+++ b/products/conversations/backend/teams.py
@@ -912,29 +912,65 @@ def graph_reply_to_activity(
``"<channelId>;messageid=<rootId>"`` conversation id so ``create_or_update_teams_ticket``
finds the existing ticket with ``is_thread_reply=True``.
"""
+ msg_id = msg.get("id")
if msg.get("messageType") != "message":
+ logger.debug(
+ "teams_reply_skipped",
+ reason="not_a_message",
+ channel_id=channel_id,
+ root_message_id=root_message_id,
+ msg_id=msg_id,
+ message_type=msg.get("messageType"),
+ )
return None
if msg.get("deletedDateTime"):
+ logger.debug(
+ "teams_reply_skipped",
+ reason="deleted",
+ channel_id=channel_id,
+ root_message_id=root_message_id,
+ msg_id=msg_id,
+ )
return None
body = msg.get("body") or {}
content = body.get("content") or ""
if not content.strip():
+ logger.debug(
+ "teams_reply_skipped",
+ reason="empty_content",
+ channel_id=channel_id,
+ root_message_id=root_message_id,
+ msg_id=msg_id,
+ )
return None
from_field = msg.get("from") or {}
user = from_field.get("user") or {}
aad_object_id = user.get("id")
if not aad_object_id:
+ logger.debug(
+ "teams_reply_skipped",
+ reason="no_author",
+ channel_id=channel_id,
+ root_message_id=root_message_id,
+ msg_id=msg_id,
+ )
return None
- msg_id = msg.get("id")
if not msg_id:
+ logger.debug(
+ "teams_reply_skipped",
+ reason="no_msg_id",
+ channel_id=channel_id,
+ root_message_id=root_message_id,
+ )
return None
+ # Graph's /replies endpoint only returns replies belonging to this root thread, so
+ # we trust the endpoint scoping rather than re-validating replyToId (it can differ
+ # from the root id for nested quote-replies, which we still want to ingest).
reply_to_id = msg.get("replyToId")
- if reply_to_id and str(reply_to_id) != str(root_message_id):
- return None
return {
"id": msg_id,