diff --git a/backend/app/channels/AGENTS.md b/backend/app/channels/AGENTS.md index f43cad8f56..51406add1b 100644 --- a/backend/app/channels/AGENTS.md +++ b/backend/app/channels/AGENTS.md @@ -5,7 +5,7 @@ Bridges external messaging platforms (Feishu, Slack, Telegram, Discord, DingTalk WeChat `_read_outbound_bytes` reads cap+1 off-loop; overflow returns `None` before encryption/upload; caps <=0 are unlimited. Cursor writes drain before cancellation; token expiry drains cursor/auth clearing under `_auth_lock`. -**Architecture**: Channels communicate with Gateway through the `langgraph-sdk` HTTP client (same as the frontend), ensuring threads are created and managed server-side. The internal SDK client injects process-local internal auth plus a matching CSRF cookie/header pair so Gateway accepts state-changing thread/run requests from channel workers without relying on browser session cookies. +**Architecture**: Channels use `langgraph-sdk` HTTP to reach Gateway; Gateway owns thread lifecycle. The internal client adds process-local auth and matching CSRF cookie/header for state-changing requests, without browser cookies. **Components**: - `message_bus.py` - Inbound queue → dispatcher; outbound uses a dispatch-start listener snapshot. Unsubscribe neither cancels nor drains captured callbacks. @@ -15,7 +15,7 @@ Cursor writes drain before cancellation; token expiry drains cursor/auth clearin **What may be published from the stream is an allowlist, not a denylist** (`_accumulate_stream_text`): only assistant message types — LangChain serializes `AIMessage.type` as `"ai"` and `AIMessageChunk.type` as `"AIMessageChunk"`, plus the OpenAI-style `"assistant"` spelling for foreign runtimes — become displayable text. The previous rule rejected only payloads whose `type` contained `"tool"` and therefore published everything else, which leaked DeerFlow's hidden model context to every streaming IM channel: `DynamicContextMiddleware` injects recalled memory as a hidden `HumanMessage` (`type == "human"`) and rewrites the user's own turn into a new `HumanMessage`, `DurableContextMiddleware` injects a hidden `` `HumanMessage`, and LangGraph fans those state writes out on the `messages-tuple` stream. Proved live on a Buzz relay, which published a `` fact block and, in another run, a verbatim echo of the user's own message as the assistant's reply. Matching is by prefix (`ai` / `assistant`), never substring, because ordinary words contain `"ai"` (`chain`, `domain`). The message type is resolved by `_stream_payload_type`, which handles both the `model_dump()` shape DeerFlow's own gateway emits and LangChain's `to_json()` constructor shape (whose top-level `type` is the literal `"constructor"`, with the class name at the tail of the `id` path). A bare `str` payload is no longer accepted at all: it carries no type information, so it cannot be attributed to the assistant, and nothing in DeerFlow produces one (`runtime/serialization.py::serialize_messages_tuple` always emits `[message_dict, metadata]`). - `base.py` - Abstract `Channel` base class (start/stop/send lifecycle). Provider callbacks that submit coroutines from SDK threads must use `_submit_threadsafe_coroutine()` (or `_submit_threadsafe_coroutine_future()` to await the outcome through `asyncio.shield`): it creates and retains the real `asyncio.Task` on the owner loop instead of treating `run_coroutine_threadsafe()`'s proxy Future as a completion signal. Submission is closed atomically with shutdown, and `stop()` must call `_close_and_drain_threadsafe_futures()` before tearing down SDK resources. Blocking SDK teardown in `stop()` (a client `close()`, a thread `join()`) must run off the event loop through `asyncio.to_thread`, since every run and channel on the Gateway shares that loop and `stop()` also serves `POST /api/channels/{name}/restart`; Slack's `SocketModeClient.close()` is a shielded, tracked task so a cancelled stop leaves it running and a retried stop awaits the same close. Anchored by `tests/blocking_io/test_channel_stop_offloop.py`. **Proactive push** (`Channel.send_notification`): the scheduled-task outbox pushes markdown to a bound identity with no inbound frame. The base default raises `NotImplementedError` (after a `ChannelUnavailable` check when not running). Scheduler/Settings read the `proactive_notifications` flag in `capabilities.py`; providers without it get no rows (legacy rows end terminal `failed`); `test_channel_capabilities.py` pins it to the registry and overrides. Adding push: implement it (return after the ACK), raise `ChannelUnavailable` for transient failures (parks, no retry used; rejections count), flip the flag. **Only WeCom pushes today** (`WSClient.send_message`); its SDK raises `RuntimeError` for a dead socket and a rejection alike, so only the `Reply ack error` prefix counts; other `RuntimeError`s, `ConnectionError`/`TimeoutError`/`OSError` and the `websockets` close exception park. Before sending, the worker re-checks the binding (owner-scoped `resolve_connections`, before liveness): a gone target is `mark_failed(terminal=True)`; a lookup failure parks. Terminal rows ignore later status writes. Scheduler side: `_on_finalization` enqueues each notice in the outcome's transaction, so recovery notifies once (unique key; idle ends use `idle:`); one message per occurrence (stop > pause > finish > run outcome); plain trials and interrupts stay silent; text (`scheduler/notification_text.py`) is localized, without IDs or links. Lifespan starts `NotificationDeliveryWorker` after the channel service (detaching enqueue if it cannot) and stops it first. - `wecom.py` - WeCom WebSocket channel with proactive `send_notification`; `_ws_transport_up` maps disconnects to `ChannelUnavailable` (no retry used). `capabilities.py` - SDK-free `CHANNEL_CAPABILITIES`. -- `service.py` - Shutdown drains manager work before transports; timeouts retain instances for retry. Bounded Feishu/DingTalk/Telegram joins with live threads raise `ChannelStopTimeout`: retain, defer replacement/restart, log WARNING without traceback. Wedged instances report `is_running`/status false. Reload workers only return snapshots; restart owns cached fallback and publication after await under the channel lock. +- `service.py` - Shutdown drains manager work before transports; timeouts retain instances for retry. Bounded Feishu/DingTalk/Telegram joins with live threads raise `ChannelStopTimeout`: retain, defer replacement/restart, log WARNING without traceback. Wedged instances report `is_running`/status false. Reload workers only return snapshots; restart owns cached fallback and publication after await under the channel lock. A service-level `_stopping` fence rejects new starts and channel publication during shutdown (including after pre-start I/O); incomplete shutdown retains that fence until a successful retry. - `slack.py` / `feishu.py` / `telegram.py` / `discord.py` / `dingtalk.py` - Platform-specific implementations (`feishu.py` tracks the running card `message_id` in memory and patches the same card in place; `telegram.py` accepts inbound text/photos/documents, preserves media captions, hands token-free attachment bytes to the shared upload pipeline, edits the "Working on it..." stream target in place via `editMessageText`, and can optionally send final Markdown replies as Rich Messages through `channels.telegram.rich_messages` — the Rich path only fires when `rich_messages` is on **and** the text contains a rich construct (fenced code, emphasis, a table, a task list, `
`, block math, or a link), so structured command/error replies (none of these) stay plain text and their newlines and `` tokens survive; `discord.py` runs `_on_message` on discord.py's private loop, so connection-repository work (identity lookup with the reservation commit, `/connect` binding) goes to the Gateway loop through `_submit_threadsafe_coroutine` — the SQLAlchemy engine is bound there — and bind replies return through `_run_on_discord_loop`; typing registers before that hand-off settles, and a failed hand-off skips the ack and stops the indicator it started unless another message still relies on it; `discord.py` registers typing loops before inbound handling yields and `_start_typing()` refuses work once `_running` is false; each tick sends the indicator with discord.py 2.x's `await channel.typing()` (`trigger_typing()` was removed in 2.0, and each typing loop logs its first failed tick at WARNING, later ones at DEBUG); because `stop()` runs on the main loop while typing tasks belong to `_discord_loop`, normal cross-thread cancellation, awaiting, and map cleanup are scheduled there with a bounded wait, while `_run_client()` drains tasks in its `finally` block before an exception/disconnect can make that loop unusable; an already-stopped foreign loop must never have its tasks awaited from the main loop; to that end every outbound cross-loop call (`send` / `send_file` / `_get_channel_or_thread`) goes through `_run_on_discord_loop`, which bounds the await (`DISCORD_OUTBOUND_TIMEOUT_SECONDS` 30s; `DISCORD_UPLOAD_TIMEOUT_SECONDS` 120s for file uploads, whose unbounded-size payload needs room for a slow uplink plus 429 retry-after) and fails fast with a `RuntimeError` when the client loop is missing or not running — a dead client becomes a logged send failure instead of a permanently hung `ChannelManager` worker — and `is_running` reports client-thread aliveness (like `feishu.py`) so `ensure_channel_ready` can restart the channel after `_run_client()` exits on a fatal error; `dingtalk.py` optionally uses AI Card streaming for in-place updates when `card_template_id` is configured, and overrides `receive_file` to download inbound images (`picture`/`richText`) and documents (`file`) by `downloadCode` into the thread uploads bucket, mirroring `feishu.py`) - `buzz.py` - Buzz (Nostr relay) implementation: one NIP-42-authenticated websocket, pubkey-allowlist + mention/DM/thread-follow gating (thread-follow reads via the manager's `connection_identity.lookup_thread_id`, so bound authors' repo-only threads count), streaming replies via in-place kind-40003 edits; requires the `buzz` dependency extra. Its durable seen-event replay guard uses async `aseen()` / `arecord()` / `aflush()` boundaries: initial JSON reads and coalesced atomic writes run off the Gateway event loop, and `stop()` awaits the final flush before returning. **Subscription model** (operator-facing version in [IM_CHANNEL_CONNECTIONS.md](../../docs/IM_CHANNEL_CONNECTIONS.md#buzz-subscription-model)): the relay fans kind-9 chat events out **only** to channel-scoped subscriptions, proved against a live relay — `REQ {"kinds":[9]}` is accepted and answered with `EOSE` but never receives an event (the connector authenticated and then sat silent forever), `REQ {"kinds":[9],"#h":[uuid]}` works, and a multi-value `#h` matches nothing, so it is strictly one REQ per channel (the same shape as Buzz's own `buzz-acp` harness). Every connection therefore rebuilds three kinds of subscription after NIP-42 auth: `buzz-discovery` (`{"kinds":[39000]}`, a historical query returning exactly the channels this identity belongs to, one stored event each then `EOSE` — adding `#p` returns zero, do not "narrow" it), `buzz-membership` (`{"kinds":[44100,44101],"#p":[us],"since":}`, the relay-signed member-added/member-removed notifications whose `p` tag names the affected member and `h` tag the channel), and one `buzz-chat-` per discovered channel. Chat subscriptions open as each kind-39000 arrives; the discovery `EOSE` is the completeness barrier that retries any that failed and warns when discovery found nothing. A kind-44100 for our pubkey subscribes to the new channel **live** (then re-issues discovery so its name/type reach the DM-detection cache, but only when that channel's metadata is actually missing — an unconditional refresh is how a burst of 44100s multiplied into one discovery pass each); a kind-44101 issues `buzz_nostr.close_frame` for exactly that channel's subscription and drops its metadata. **The membership subscription is scoped to LIVE events** and this is load-bearing: buzz-relay *stores* 44100/44101 and serves history newest-first (default limit 2000), so an unscoped filter replayed the whole membership history on every connect — every stored add read as live, re-running discovery once each (M+1 discovery passes × N stored kind-39000 events per connect, observed live as two `channel discovery complete` lines and one channel logged `` because the 44100 path subscribed before its metadata arrived), re-subscribing channels we have since been removed from, and letting a stored 44101 transiently unsubscribe a channel we are still in. `since` is anchored at the moment the socket opened (`_session_started_at`) minus `MEMBERSHIP_LOOKBACK_SECONDS` (60) of slack, which covers both relay clock skew and a membership change published *during* the connect/auth handshake; the slack can only cost an idempotent replay of the last minute. **A relay `CLOSED` frame is recovered, not merely forgotten** — every subscription on the socket fails silently when dropped, so `_handle_closed` re-issues it, bounded by `MAX_RESUBSCRIBE_ATTEMPTS` (3) per subscription id per connection *and per auth epoch* (`_resubscribe_attempts` is reset on session start, on re-auth, and by `stop()`, so pre-auth rejections — which the auth branch already recovers wholesale — never spend the authenticated session's budget). The first retry is immediate (the common case is a one-off hiccup); later ones back off 1s then 2s, awaited inline in the read loop rather than in a background task that could outlive its own socket. **`auth-required:` before this socket has completed its NIP-42 handshake is the expected bootstrap sequence, not a refusal**, and `_handle_closed` short-circuits it ahead of every recovery path: the connector opens its control REQs immediately in case the relay serves unauthenticated reads, a closed relay answers `auth-required:` plus an `AUTH` challenge, and the auth branch re-opens everything. That case is logged at DEBUG and consumes neither the permanent-refusal branch nor the retry budget (a chat subscription is still dropped from `_chat_subscriptions`, since it genuinely is not subscribed and discovery is what re-opens it). Treating it as permanent produced an operator-facing warning claiming discovery/membership tracking was DOWN in the same run where discovery then completed, every channel was subscribed, and a brand-new channel's kind-44100 was picked up one second later. The boundary is the per-socket `_auth_completed` flag, set once the signed AUTH event has been sent and cleared on session entry, session exit, and `stop()`; the same reason *after* that stays loud, and says the subscription is down until the relay's next AUTH challenge or the next reconnect rather than borrowing the non-auth wording. Then `_is_transient_close` decides whether to retry at all: NIP-01/NIP-42 `auth-required:`/`restricted:`/`blocked:`/`mute:`/`invalid:`/`pow:` prefixes and buzz-relay's own removal/revocation prose are permanent (do not fight the relay over a channel that is no longer ours; a post-auth `auth-required:` is recovered by the AUTH branch, not by re-issuing), `rate-limited:`/`error:`/no-reason-at-all and anything unrecognized are transient — the default resolves toward "keep listening" because going silently deaf is the failure this exists to remove, and the attempt budget bounds a wrong guess. A chat `CLOSED` is only ever recovered for a channel already in `_chat_subscriptions`: a `CLOSED` is relay-supplied, so acting on an unknown one would let a relay induce a subscription just by naming a channel. Every subscription that goes unlistened is logged at WARNING, never INFO. Subscription ids are deterministic per channel precisely so one can be replaced or closed without disturbing the others on the socket, and `_chat_subscriptions` is per-socket state cleared on session end, on re-auth (a pre-auth REQ may have been rejected), and by `stop()`. Three bounds on remote-fed state: `MAX_CACHED_CHANNELS` (512) caps the kind-39000 metadata cache, the watermark map, and the resubscribe-attempt map; `MAX_CHANNEL_SUBSCRIPTIONS` (256, well under buzz-relay's own 1024-per-connection ceiling) caps live chat subscriptions — at the cap new channels are refused and named in a warning rather than evicting a working subscription. **Known bound (documented, not fixed):** the relay caps historical delivery at 2000 events per subscription, newest-first, even with a `since`, so >2000 unread messages in a *single* channel across a disconnect loses the oldest — the relay never sends them and the watermark advances past them. That is the one remaining path that can skip; everything else fails toward replay. **Trust model** (operator-facing version in [IM_CHANNEL_CONNECTIONS.md](../../docs/IM_CHANNEL_CONNECTIONS.md#buzz-trust-model)): every inbound `EVENT` is authenticated at the single `handle_relay_frame` choke point — the NIP-01 id is recomputed from the delivered payload and the BIP-340 Schnorr signature verified against the claimed `pubkey` (`buzz_nostr.verify_event`, pure and total: malformed input returns `False`, never raises) — so `ev["pubkey"]`, the authorization principal for both the allowlist and the `/connect` bind, cannot be forged by a relay the DeerFlow operator does not run. What remains trusted is the *authorship* of kind-39000 channel metadata: any member can sign one, and because per-channel subscriptions are now driven by discovery, a forged kind-39000 has two effects rather than one — it can mark a channel `type: "dm"` (relaxing `require_mention` for that channel) **and** it can induce a chat subscription for a channel of the forger's choosing, since the channels we listen to are exactly the channels we hold metadata for. Neither makes anything be *acted on*: `allowed_users` and per-event signature verification are independent gates, so an induced subscription only means the relay reads its own traffic back to a subscriber that drops it, bounded by `MAX_CHANNEL_SUBSCRIPTIONS` (which refuses rather than evicts, so it cannot displace a real channel). Same for a forged kind-44100, except its `p` tag is re-checked locally so it must at least name us. Closing this needs a configured trusted relay pubkey, which `relay_url` is not. `allowed_users` is deny-by-default (empty = nobody, unlike siblings' empty = everyone), so `start()` logs a WARNING when it is empty and each drop logs at DEBUG. The resubscribe cursor (`since`) is **per channel**, advances only for events that were actually processed, and never past `now + MAX_FUTURE_SKEW_SECONDS`, because it is peer-supplied (`created_at`) and a single future-dated event otherwise made the connector permanently deaf. Per channel rather than global is the safety-critical half: subscriptions are per channel, so one shared cursor is the newest event seen in *any* channel and a busy channel would drag it past a quiet channel's unread messages, skipping them on the next reconnect — measured on a live relay, three channels of one identity sat ~28h apart. Per-channel cursors can only ever cost duplicate delivery (absorbed by the manager's `event_id` dedupe), and an evicted cursor degrades to "no `since`", i.e. the relay's default backlog — both fail toward replay, never toward a miss. Streaming tracks every oversize chunk index (`_stream_targets` for chunk 0, `_stream_tails` for the rest), since the manager republishes cumulative text and reposting `chunks[1:]` per update flooded the channel; all of it is per-connection state cleared by `stop()`, and the remote-fed kind-39000 cache is capped at `MAX_CACHED_CHANNELS`. **`send()` refuses outright to publish text carrying a hidden model-context wrapper** (``, ``, `` — `_HIDDEN_CONTEXT_MARKERS`), logging at ERROR and clearing the stream bookkeeping on a blocked `is_final`. This is defense in depth behind the manager's allowlist, and it lives here rather than in a sibling connector because on Buzz a leak is permanent: every streaming update is an immutable public Nostr event, so a corrective edit only changes what clients render while the original leaked event stays on the relay. Matching is on the literal opening tag, so a reply that merely talks about memory is still published Buzz seen-event shutdown stays bounded and retryable: `aflush()` awaits any in-flight write, attempts at most one final snapshot, leaves a still-changing generation dirty for fail-open replay, and returns without a live persistence timer. A Gateway cancellation does not cancel the underlying worker-thread write; `BuzzChannel.stop()` tracks cleanup completion separately from transport admission so ChannelService can retry the retained channel without racing a second snapshot against that write. The store is quiesced before stop (including the already-stopped guard), so a timed-out relay task that records after stop only marks data dirty and cannot schedule detached file work; a repeated `stop()` still drains that dirty state, while `BuzzChannel.start()` explicitly resumes scheduling and flushes it automatically. diff --git a/backend/app/channels/service.py b/backend/app/channels/service.py index befda6cc06..5717b61c11 100644 --- a/backend/app/channels/service.py +++ b/backend/app/channels/service.py @@ -160,6 +160,7 @@ class ChannelService: self._channels: dict[str, Any] = {} # name -> Channel instance self._config = config self._running = False + self._stopping = False self._readiness_locks: dict[str, asyncio.Lock] = {} self._config_epochs: dict[str, int] = {} @@ -202,6 +203,8 @@ class ChannelService: """Start the manager and all enabled channels.""" if self._running: return + if self._stopping: + raise RuntimeError("cannot start ChannelService while shutdown is incomplete") await self.manager.start() self._running = True @@ -294,6 +297,7 @@ class ChannelService: async def stop(self) -> None: """Drain accepted messages while channels can still deliver replies.""" + self._stopping = True self._running = False # Reject new provider work first. Existing workers keep draining during # manager.stop(), and channel transports remain alive until that drain @@ -323,6 +327,7 @@ class ChannelService: if stop_errors: raise ExceptionGroup("one or more channels failed to stop", stop_errors) + self._stopping = False logger.info("ChannelService stopped") def _load_channel_config(self, name: str) -> dict[str, Any] | None: @@ -484,6 +489,10 @@ class ChannelService: async def _start_channel(self, name: str, config: dict[str, Any]) -> bool: """Instantiate and start a single channel.""" + if self._stopping or not self._running: + logger.warning("Refusing to start %s while ChannelService is stopped or stopping", name) + return False + import_path = _CHANNEL_REGISTRY.get(name) if not import_path: logger.warning("Unknown channel type") @@ -528,9 +537,21 @@ class ChannelService: config["seen_event_store_path"] = await asyncio.to_thread(_default_seen_store_path) if self._connection_repo is not None: config["connection_repo"] = self._connection_repo + # A stop may have started while this coroutine was suspended in + # pre-start I/O above. Fence publication again immediately before + # the new instance becomes service-owned. + if self._stopping or not self._running: + logger.warning("Refusing to publish %s channel while ChannelService is stopped or stopping", name) + return False channel = channel_cls(bus=self.bus, config=config) self._channels[name] = channel await channel.start() + # A concurrent service stop may finish while channel.start() is + # suspended, removing this instance before it subscribes. Drain + # the late-started transport rather than leaving an orphan. + if self._stopping or not self._running: + await self._stop_and_discard_channel(name, channel) + return False if not channel.is_running: logger.error("Channel did not enter a running state after start()") await self._stop_and_discard_channel(name, channel) diff --git a/backend/tests/blocking_io/test_buzz_channel_seen_events.py b/backend/tests/blocking_io/test_buzz_channel_seen_events.py index bfb1884492..b7c5927cb1 100644 --- a/backend/tests/blocking_io/test_buzz_channel_seen_events.py +++ b/backend/tests/blocking_io/test_buzz_channel_seen_events.py @@ -219,6 +219,7 @@ async def test_start_channel_resolves_seen_store_path_off_the_loop(tmp_path: Pat # path there. The test mirrors that boundary so only ``_start_channel``'s own # resolution is exercised on the loop. service = await asyncio.to_thread(ChannelService, channels_config={}) + service._running = True # Direct-start fixture models an active service. started = await service._start_channel("buzz", {"relay_url": "wss://buzz.example.com", "private_key": "unused-by-this-test"}) # ``_start_channel`` keeps a blanket ``except Exception`` around the whole diff --git a/backend/tests/test_channel_service_restart_stop_fence.py b/backend/tests/test_channel_service_restart_stop_fence.py new file mode 100644 index 0000000000..fb274f3cb6 --- /dev/null +++ b/backend/tests/test_channel_service_restart_stop_fence.py @@ -0,0 +1,142 @@ +from __future__ import annotations + +import asyncio + +import pytest + +from app.channels import service as channel_service +from app.channels.service import ChannelService +from deerflow import reflection + + +class _FakeChannel: + def __init__(self, *, bus: object, config: dict[str, object]) -> None: + self.is_running = False + + async def start(self) -> None: + self.is_running = True + + async def stop(self) -> None: + self.is_running = False + + +@pytest.mark.asyncio +async def test_restart_is_fenced_while_service_shutdown_is_in_progress( + monkeypatch: pytest.MonkeyPatch, +) -> None: + service = ChannelService(channels_config={"fake": {"enabled": True}}) + service._running = True + stop_entered = asyncio.Event() + release_stop = asyncio.Event() + + # Give stop() a real, already-owned transport to await. It snapshots + # _channels before awaiting this stop; a late restart must not publish a + # second transport that is absent from the snapshot. + existing = _FakeChannel(bus=service.bus, config={}) + existing.is_running = True + + async def blocking_channel_stop() -> None: + stop_entered.set() + await release_stop.wait() + existing.is_running = False + + async def manager_stop() -> None: + pass + + monkeypatch.setattr(existing, "stop", blocking_channel_stop) + monkeypatch.setattr(service.manager, "stop", manager_stop) + monkeypatch.setitem(channel_service._CHANNEL_REGISTRY, "fake", "tests.fake:FakeChannel") + monkeypatch.setattr(reflection, "resolve_class", lambda *_args, **_kwargs: _FakeChannel) + service._channels["existing"] = existing + + stop_task = asyncio.create_task(service.stop()) + await asyncio.wait_for(stop_entered.wait(), timeout=1) + + try: + restarted = await service.restart_channel("fake", reload_config=False) + finally: + release_stop.set() + await asyncio.wait_for(stop_task, timeout=1) + + assert restarted is False + assert service._channels == {} + assert service._running is False + assert service._stopping is False + + +@pytest.mark.asyncio +async def test_channel_cannot_publish_after_stop_finishes_during_prestart_io( + monkeypatch: pytest.MonkeyPatch, +) -> None: + service = ChannelService(channels_config={"buzz": {"enabled": True}}) + service._running = True + entered_io = asyncio.Event() + resume_io = asyncio.Event() + + async def held_to_thread(_function: object) -> str: + entered_io.set() + await resume_io.wait() + return "/tmp/buzz_seen_events.json" + + async def manager_stop() -> None: + pass + + monkeypatch.setattr(channel_service.asyncio, "to_thread", held_to_thread) + monkeypatch.setattr(service.manager, "stop", manager_stop) + monkeypatch.setitem(channel_service._CHANNEL_REGISTRY, "buzz", "tests.fake:FakeChannel") + monkeypatch.setattr(reflection, "resolve_class", lambda *_args, **_kwargs: _FakeChannel) + + start_task = asyncio.create_task(service._start_channel("buzz", {"enabled": True})) + await asyncio.wait_for(entered_io.wait(), timeout=1) + await service.stop() + assert service._stopping is False + assert service._running is False + + resume_io.set() + assert await asyncio.wait_for(start_task, timeout=1) is False + assert service._channels == {} + + +@pytest.mark.asyncio +async def test_channel_start_finishing_after_service_stop_is_drained( + monkeypatch: pytest.MonkeyPatch, +) -> None: + service = ChannelService(channels_config={"fake": {"enabled": True}}) + service._running = True + start_entered = asyncio.Event() + release_start = asyncio.Event() + started = [] + + class LateChannel(_FakeChannel): + async def start(self) -> None: + start_entered.set() + await release_start.wait() + self.is_running = True + service.bus.subscribe_outbound(self.on_outbound) + started.append(self) + + async def on_outbound(self, _message: object) -> None: + pass + + async def stop(self) -> None: + service.bus.unsubscribe_outbound(self.on_outbound) + self.is_running = False + + async def manager_stop() -> None: + pass + + monkeypatch.setattr(service.manager, "stop", manager_stop) + monkeypatch.setitem(channel_service._CHANNEL_REGISTRY, "fake", "tests.fake:LateChannel") + monkeypatch.setattr(reflection, "resolve_class", lambda *_args, **_kwargs: LateChannel) + + start_task = asyncio.create_task(service._start_channel("fake", {"enabled": True})) + await asyncio.wait_for(start_entered.wait(), timeout=1) + await service.stop() + assert service._channels == {} + release_start.set() + + assert await asyncio.wait_for(start_task, timeout=1) is False + assert len(started) == 1 + assert started[0].is_running is False + assert service._channels == {} + assert service.bus._outbound_listeners == [] diff --git a/backend/tests/test_qq_lifecycle.py b/backend/tests/test_qq_lifecycle.py index c909a7bbe6..21edbae804 100644 --- a/backend/tests/test_qq_lifecycle.py +++ b/backend/tests/test_qq_lifecycle.py @@ -341,6 +341,7 @@ async def test_service_registers_starts_and_disposes_qq(tmp_path, monkeypatch): AsyncMock(return_value={"url": "wss://api.sgroup.qq.com/websocket/"}), ) monkeypatch.setattr(qq.QQChannel, "_run_connection", connected) + service._running = True # Direct-start fixture models an active service. try: assert await service._start_channel("qq", config) channel = service.get_channel("qq")