deer-flow/backend/tests/test_multi_pod_inbound_dedupe.py
Nan Gao 6c4c74a504
fix(channels): share chat-to-thread bindings through the database (#6558)
* fix(channels): share chat-to-thread bindings through the database

ChannelManager kept its IM chat-to-thread bindings
(channel_name:chat_id[:topic_id] -> thread_id) in a per-process JSON file,
channels/store.json, loaded once and rewritten whole on every change. With
several Gateway processes a binding created on one replica was invisible to
the others (the next message for the same chat opened a second thread) and
concurrent writers clobbered each other's file.

- New channel_thread_bindings table (migration 0036_channel_thread_bindings)
  and harness package deerflow.persistence.channel_thread_bindings: key PK
  (the legacy composite string), channel_name, chat_id, nullable topic_id,
  thread_id, user_id, epoch created_at/updated_at; index (channel_name,
  chat_id). Dialect upsert keeps created_at; prefix remove and batched
  ON CONFLICT DO NOTHING import.
- app.channels.store.ChannelStore is an async protocol: SqlChannelStore for
  sqlite/postgres, JsonChannelStore (file I/O via asyncio.to_thread) for
  database.backend: memory. resolve_channel_store picks at ChannelService
  construction; ChannelService.start() imports an existing store.json once
  into an empty table and renames it store.json.migrated (a concurrently
  importing peer neither duplicates nor clobbers; a populated table leaves
  the file alone).
- Callers updated: manager, connection_identity.lookup_thread_id, Feishu
  (send() awaits the mapping writer; the synchronous lark callback bridges
  its two store calls to the Gateway loop with a bounded wait), Discord
  (channels_dir).
- Head pins in the 0027_0028/0029/0032/0034/0035 migration tests point at
  the new head; docs (channels and migrations AGENTS.md, CONFIGURATION.md,
  README) and CHANGELOG updated.

* docs(changelog): link the channel thread bindings entry to #6558

* fix(channels): reject only the Gateway loop in the Feishu store bridge

lark-oapi 1.5.5 invokes the message callback synchronously from its async
frame handler, on the private event loop that FeishuChannel._run_ws starts
for the SDK thread. The bridge's guard treated any running loop as unsafe,
so every real inbound message skipped the stored-topic lookup and the
pending-mapping restore: a reply whose parent card was mapped but whose
root was not fell back to the unknown root, and could consume an
unrelated pending clarification.

Only a wait issued from the Gateway loop itself (the loop that executes
the submitted coroutine) is refused now; the SDK's own loop may block for
the bounded wait, as that thread blocked on the JSON rewrite before.
Tests drive _on_message from a worker thread running its own loop, the
production shape, for both the lookup and the write path, and pin the
Gateway-loop refusal.

* fix(channels): defer unresolved Feishu lookups and harden the store.json import

Review follow-ups on the chat-to-thread binding store (#6558):

- Import: a legacy entry whose key, channel_name, chat_id, topic_id,
  thread_id or user_id exceeds its column width is skipped and counted
  with the malformed ones instead of failing the whole batch on
  PostgreSQL (SQLite silently accepted the same row, so the backends
  diverged on one file). The corrupt-file warning now says what each
  caller does: the JSON store starts fresh, the import is skipped and
  the file kept.
- Feishu bridge: store calls run on the Gateway loop under a 3s
  asyncio.wait_for (the SDK loop also services ws keepalives; the old
  10s bound could stall it per message), and the lark-thread wait is
  that budget plus 1s. A deadline or store error is StoreLookupUnresolved,
  never a miss: _on_message no longer routes such a reply onto its
  unknown root (which created a second thread and later overwrote the
  parent alias). The message joins a per-chat FIFO drained on the
  Gateway loop with backoff for up to 30s, then is dropped with a
  warning. _on_message is split into parse / resolve / dispatch so the
  deferred path dispatches the same way; later messages for the chat
  queue behind the deferred one.

* fix(tests): expect follow_redirects in the Jina client kwargs after #5808

#5808 made JinaClient pass follow_redirects=True to httpx.AsyncClient and
updated test_jina_client.py, but test_jina_response_limit.py and
test_jina_retry_after.py still pin the exact client kwargs to proxy and
trust_env, so every backend-unit-tests shard that lands on them fails on
main (the backend unit-test workflow only runs on pull requests, which is
why the push to main did not surface it). Update the two expectations to
include the new keyword.

(cherry picked from commit d5aa23156ce19ce36d95df03953442f83ae6d050)

* Revert "fix(tests): expect follow_redirects in the Jina client kwargs after #5808"

This reverts commit 5bee00bfb09c65a30f77fb4df47a1f82c47ecef7.

* fix(channels): bound deferred Feishu routing by the inbound queue capacity

Review follow-up on #6558: a store outage let every subsequent message for
a chat join the deferred queue with no capacity check (the bus reservation
was only taken after routing succeeded), and each queued message started a
fresh 30s retry budget when it reached the head, so a burst could be
retained for N x 30s and grow without bound.

- Intake is reserved BEFORE routing for every store-backed message
  (bus.reserve_inbound is thread-safe and already used from SDK threads),
  so deferred and live messages share the one configured bound,
  channels.inbound_queue_maxsize; a message that cannot be admitted is
  dropped at once with a warning, never queued or routed as a miss.
- The reservation travels with the message into dispatch (committed by
  _prepare_inbound), is released on the batch path (the flush reserves at
  publish time), on drop after the budget, on a failed deferral, on
  dispatch failure and for every leftover when the drain task is cancelled
  by stop().
- The retry budget runs from the message's arrival: a queued message whose
  budget is spent when it reaches the head is dropped without a lookup.
- The bounded resolver returns the unresolved outcome instead of raising
  it through the tracked task, which logged an ERROR for an expected,
  handled store timeout.
- Upstream's new blocking-io test constructs the store by its old class
  name; it now uses JsonChannelStore.

---------

Co-authored-by: Willem Jiang <willem.jiang@gmail.com>
2026-10-10 14:00:00 +08:00

171 lines
7.4 KiB
Python

"""Integration test: two ChannelManagers share one Postgres dedupe table.
Mirrors ``test_multi_worker_run_ownership.py``'s "two managers sharing a DB"
pattern. Skipped unless a real Postgres backend is configured via
``DEDUPE_TEST_POSTGRES_URL`` (the dev container runs sqlite), so it only runs
where cross-pod dedupe actually matters — CI with Postgres, or a local run with
a throwaway Postgres. See issue #4120.
"""
from __future__ import annotations
import os
import uuid
from urllib.parse import parse_qsl, urlencode, urlsplit, urlunsplit
import pytest
import pytest_asyncio
from app.channels.dedupe_store import INBOUND_DEDUPE_TTL_SECONDS, PostgresInboundDedupeStore
POSTGRES_URL = os.environ.get("DEDUPE_TEST_POSTGRES_URL")
# libpq/psycopg-only query parameters that asyncpg's ``connect()`` rejects. CI
# hands over ``TEST_POSTGRES_URI`` as ``postgresql://...?sslmode=disable``; left
# in place these raise ``TypeError: connect() got an unexpected keyword argument
# 'sslmode'`` once the URL is routed to the asyncpg driver, so strip them here.
_LIBPQ_ONLY_QUERY_KEYS = {"sslmode", "channel_binding"}
def _asyncpg_url(url: str | None) -> str | None:
"""Normalize a sync ``postgresql://`` URL to the async driver SQLAlchemy needs.
``init_engine`` builds an *async* engine, so a bare ``postgresql://`` would fall
back to the synchronous psycopg2 driver and fail. Accept either form so the test
runs whether CI hands over ``TEST_POSTGRES_URI`` (``postgresql://...``) or a
caller passes ``postgresql+asyncpg://...`` directly. libpq-only query params
(e.g. ``sslmode``) are dropped because asyncpg does not understand them.
"""
if not url:
return url
if url.startswith("postgresql://"):
url = "postgresql+asyncpg://" + url[len("postgresql://") :]
parts = urlsplit(url)
if parts.query:
kept = [(k, v) for k, v in parse_qsl(parts.query, keep_blank_values=True) if k not in _LIBPQ_ONLY_QUERY_KEYS]
url = urlunsplit(parts._replace(query=urlencode(kept)))
return url
pytestmark = pytest.mark.skipif(
not POSTGRES_URL,
reason="requires DEDUPE_TEST_POSTGRES_URL (real Postgres for cross-pod dedupe)",
)
@pytest_asyncio.fixture(autouse=True)
async def _postgres_engine():
"""Initialize the Postgres engine within the test's event loop.
Doing this inside the loop (not at import time) avoids the "connection
attached to a different loop" error that arises when the engine is built in
a loop that pytest-asyncio later closes.
"""
from deerflow.persistence.engine import close_engine, init_engine
await init_engine("postgres", url=_asyncpg_url(POSTGRES_URL))
try:
yield
finally:
await close_engine()
@pytest.mark.asyncio
async def test_two_stores_share_dedupe_state_across_pods():
from deerflow.persistence.base import Base
from deerflow.persistence.engine import get_engine, get_session_factory
from deerflow.persistence.webhook_delivery.model import WebhookDeliveryRow
engine = get_engine()
sf = get_session_factory()
# Ensure the table exists regardless of whether the alembic migration ran.
async with engine.begin() as conn:
await conn.run_sync(Base.metadata.create_all, tables=[WebhookDeliveryRow.__table__], checkfirst=True)
store_a = PostgresInboundDedupeStore(session_factory=sf)
store_b = PostgresInboundDedupeStore(session_factory=sf)
unique = uuid.uuid4().hex
key = ("github", "repo", "repo", f"d-{unique}:uA:agentX")
try:
# First pod records the delivery and proceeds.
assert await store_a.try_record(key) is False
# A redelivery landing on the second pod hits the same table -> duplicate.
assert await store_b.try_record(key) is True
finally:
await store_a.release(key)
@pytest.mark.asyncio
async def test_manager_injects_shared_store_and_dedupes_cross_pod():
"""End-to-end: two ChannelManagers wired to the *same* Postgres store drop a
redelivery routed to the second manager, exactly as the production dispatch
loop would (``if await self._is_duplicate_inbound(msg): continue``)."""
from app.channels.manager import ChannelManager
from app.channels.message_bus import InboundMessage, MessageBus
from app.channels.store import JsonChannelStore
from deerflow.persistence.engine import get_session_factory
sf = get_session_factory()
shared_store = PostgresInboundDedupeStore(session_factory=sf)
manager_a = ChannelManager(bus=MessageBus(), store=JsonChannelStore(), inbound_dedupe_store=shared_store)
manager_b = ChannelManager(bus=MessageBus(), store=JsonChannelStore(), inbound_dedupe_store=shared_store)
msg = InboundMessage(
channel_name="github",
chat_id="repo",
user_id="alice",
text="@bot review",
topic_id="7:agent",
workspace_id="repo",
metadata={"message_id": "d-crosspod:agent"},
)
try:
# First manager records the delivery and lets it through.
assert await manager_a._is_duplicate_inbound(msg) is False
# Same redelivery on the second manager hits the shared table -> dropped.
assert await manager_b._is_duplicate_inbound(msg) is True
finally:
await manager_a._release_inbound_dedupe_key(msg)
@pytest.mark.asyncio
async def test_expired_unreleased_row_is_reclaimed_on_next_redelivery():
"""P1 end-to-end: a row past the TTL that was never released must be
reclaimed so the next redelivery is re-admitted (not dropped forever)."""
from sqlalchemy import text
from deerflow.persistence.base import Base
from deerflow.persistence.engine import get_engine, get_session_factory
from deerflow.persistence.webhook_delivery.model import WebhookDeliveryRow
engine = get_engine()
sf = get_session_factory()
async with engine.begin() as conn:
await conn.run_sync(Base.metadata.create_all, tables=[WebhookDeliveryRow.__table__], checkfirst=True)
store = PostgresInboundDedupeStore(session_factory=sf)
unique = uuid.uuid4().hex
channel, workspace_id, chat_id, message_id = ("github", "repo", "repo", f"d-{unique}:expired")
key = (channel, workspace_id, chat_id, message_id)
try:
# Seed an already-expired, unreleased row for this key.
async with sf() as session:
async with session.begin():
await session.execute(
text("INSERT INTO webhook_deliveries (channel, workspace_id, chat_id, message_id, first_seen) VALUES (:c, :w, :ch, :m, now() - make_interval(secs => :age))"),
{"c": channel, "w": workspace_id, "ch": chat_id, "m": message_id, "age": INBOUND_DEDUPE_TTL_SECONDS + 1},
)
# The expired row is reclaimed -> redelivery re-admitted (not a duplicate).
assert await store.try_record(key) is False
# Its first_seen is refreshed to ~now (well within the TTL).
async with sf() as session:
row = (
await session.execute(
text("SELECT (now() - first_seen) < make_interval(secs => :ttl) AS fresh FROM webhook_deliveries WHERE channel = :c AND workspace_id = :w AND chat_id = :ch AND message_id = :m"),
{"c": channel, "w": workspace_id, "ch": chat_id, "m": message_id, "ttl": INBOUND_DEDUPE_TTL_SECONDS},
)
).fetchone()
assert row is not None and row[0] is True
finally:
await store.release(key)