fix(channels): preserve recovery order and adapter ownership
This commit is contained in:
1 parent
9c1b16b3cc
commit
182ada6825
12 files changed
+191
-29
No files matched your search
+3
-1
@@ -55,6 +55,8 @@ The gateway saves final scheduled messages before it accepts them into the outgo
|
|||||||
This includes explicit `message` calls in existing tasks. Each recipient has a separate delivery
|
This includes explicit `message` calls in existing tasks. Each recipient has a separate delivery
|
||||||
record. Progress, reasoning, and streaming events do not enter this queue. WebUI streaming and
|
record. Progress, reasoning, and streaming events do not enter this queue. WebUI streaming and
|
||||||
saved chat history keep their existing behavior.
|
saved chat history keep their existing behavior.
|
||||||
|
External channels receive one final scheduled reply instead of a streamed reply. Ordinary chat
|
||||||
|
streaming is unchanged.
|
||||||
|
|
||||||
If a channel reports that it has not sent any part of a message, the gateway retries every
|
If a channel reports that it has not sent any part of a message, the gateway retries every
|
||||||
30 seconds, for up to one hour after queue acceptance. It sends the saved message to the saved
|
30 seconds, for up to one hour after queue acceptance. It sends the saved message to the saved
|
||||||
@@ -78,7 +80,7 @@ Look for `Channel delivery` in the gateway log. The run ID links execution to ea
|
|||||||
| `unknown` | An interrupted or failed attempt might have reached the service; no automatic retry |
|
| `unknown` | An interrupted or failed attempt might have reached the service; no automatic retry |
|
||||||
|
|
||||||
The queue is stored in `delivery/outbox.sqlite3`, beside the active config file. Include this
|
The queue is stored in `delivery/outbox.sqlite3`, beside the active config file. Include this
|
||||||
directory in instance backups. It holds at most 256 pending messages, with a 1 MiB serialized limit
|
directory in instance backups; stop the gateway before copying it. It holds at most 256 pending messages, with a 1 MiB serialized limit
|
||||||
per message. A full queue or storage error rejects the enqueue operation instead of reporting it
|
per message. A full queue or storage error rejects the enqueue operation instead of reporting it
|
||||||
as accepted. Terminal records discard message text and keep status for up to seven days, capped
|
as accepted. Terminal records discard message text and keep status for up to seven days, capped
|
||||||
at 1,000 records. Existing job and session files are not converted. Older versions ignore this
|
at 1,000 records. Existing job and session files are not converted. Older versions ignore this
|
||||||
|
|||||||
@@ -13,6 +13,7 @@ from pathlib import Path
|
|||||||
from typing import Any, cast
|
from typing import Any, cast
|
||||||
from urllib.parse import urlparse
|
from urllib.parse import urlparse
|
||||||
|
|
||||||
|
from nanobot.bus.delivery import ChannelNotReadyError
|
||||||
from nanobot.bus.events import InboundMessage, OutboundMessage
|
from nanobot.bus.events import InboundMessage, OutboundMessage
|
||||||
from nanobot.bus.outbound_events import ContextCompactionEvent, ProgressEvent, RetryWaitEvent
|
from nanobot.bus.outbound_events import ContextCompactionEvent, ProgressEvent, RetryWaitEvent
|
||||||
from nanobot.bus.queue import MessageBus
|
from nanobot.bus.queue import MessageBus
|
||||||
@@ -167,6 +168,8 @@ class LinearChannel(BaseChannel):
|
|||||||
ephemeral=True,
|
ephemeral=True,
|
||||||
)
|
)
|
||||||
return
|
return
|
||||||
|
if self._client is None:
|
||||||
|
raise ChannelNotReadyError("Linear HTTP client is not initialized")
|
||||||
body = msg.content
|
body = msg.content
|
||||||
if msg.media:
|
if msg.media:
|
||||||
attachments = await self._attachment_markdown(msg)
|
attachments = await self._attachment_markdown(msg)
|
||||||
|
|||||||
@@ -37,6 +37,8 @@ from nanobot.channels.contracts import (
|
|||||||
from nanobot.channels.outbox import RETRY_SECONDS, DeliveryOutbox
|
from nanobot.channels.outbox import RETRY_SECONDS, DeliveryOutbox
|
||||||
from nanobot.channels.registry import channel_default_enabled
|
from nanobot.channels.registry import channel_default_enabled
|
||||||
from nanobot.config.schema import Config
|
from nanobot.config.schema import Config
|
||||||
|
from nanobot.security.workspace_access import WorkspaceScopeResolver
|
||||||
|
from nanobot.security.workspace_policy import resolve_allowed_path
|
||||||
from nanobot.utils.restart import (
|
from nanobot.utils.restart import (
|
||||||
RestartNotice,
|
RestartNotice,
|
||||||
consume_restart_notice_from_env,
|
consume_restart_notice_from_env,
|
||||||
@@ -799,6 +801,24 @@ class ChannelManager:
|
|||||||
if session is None or session.generation != request.session_generation:
|
if session is None or session.generation != request.session_generation:
|
||||||
self._outbox.finish(msg, "failed", "session_replaced")
|
self._outbox.finish(msg, "failed", "session_replaced")
|
||||||
return
|
return
|
||||||
|
if msg.media:
|
||||||
|
# An accepted local path can become a symlink during an outage.
|
||||||
|
# Recheck the current source policy before the adapter opens it.
|
||||||
|
scope = WorkspaceScopeResolver(
|
||||||
|
self.config.workspace_path, self.config.tools.restrict_to_workspace,
|
||||||
|
).for_turn(channel=request.session_key.split(":", 1)[0],
|
||||||
|
message_metadata={}, session_metadata=session.metadata)
|
||||||
|
try:
|
||||||
|
for path in msg.media:
|
||||||
|
if not path.startswith(("http://", "https://")):
|
||||||
|
resolve_allowed_path(
|
||||||
|
path, workspace=scope.project_path,
|
||||||
|
allowed_root=scope.project_path if scope.restrict_to_workspace else None,
|
||||||
|
extra_allowed_roots=[self._config_path.parent / "media"],
|
||||||
|
)
|
||||||
|
except (OSError, ValueError):
|
||||||
|
self._outbox.finish(msg, "failed", "attachment_access_denied")
|
||||||
|
return
|
||||||
if not self._outbox.claim(msg):
|
if not self._outbox.claim(msg):
|
||||||
return
|
return
|
||||||
try:
|
try:
|
||||||
|
|||||||
@@ -19,7 +19,7 @@ from pydantic import Field
|
|||||||
from websockets.asyncio.client import ClientConnection
|
from websockets.asyncio.client import ClientConnection
|
||||||
from websockets.asyncio.client import connect as ws_connect
|
from websockets.asyncio.client import connect as ws_connect
|
||||||
|
|
||||||
from nanobot.bus.delivery import ChannelNotReadyError
|
from nanobot.bus.delivery import ChannelNotReadyError, DeliveryRejectedError
|
||||||
from nanobot.bus.events import OutboundMessage
|
from nanobot.bus.events import OutboundMessage
|
||||||
from nanobot.bus.queue import MessageBus
|
from nanobot.bus.queue import MessageBus
|
||||||
from nanobot.channels.base import BaseChannel
|
from nanobot.channels.base import BaseChannel
|
||||||
@@ -448,8 +448,7 @@ class NapcatChannel(BaseChannel):
|
|||||||
|
|
||||||
kind, _, target = msg.chat_id.partition(":")
|
kind, _, target = msg.chat_id.partition(":")
|
||||||
if kind not in ("private", "group") or not target:
|
if kind not in ("private", "group") or not target:
|
||||||
logger.error("napcat: invalid chat_id '{}'", msg.chat_id)
|
raise DeliveryRejectedError("napcat: invalid chat_id")
|
||||||
return
|
|
||||||
|
|
||||||
segments: list[dict[str, Any]] = []
|
segments: list[dict[str, Any]] = []
|
||||||
for ref in msg.media or []:
|
for ref in msg.media or []:
|
||||||
|
|||||||
@@ -39,18 +39,24 @@ class DeliveryOutbox:
|
|||||||
fd = os.open(self.path, os.O_CREAT | os.O_RDWR, 0o600)
|
fd = os.open(self.path, os.O_CREAT | os.O_RDWR, 0o600)
|
||||||
os.close(fd)
|
os.close(fd)
|
||||||
db = sqlite3.connect(self.path)
|
db = sqlite3.connect(self.path)
|
||||||
|
db.execute("PRAGMA secure_delete=ON")
|
||||||
db.row_factory = sqlite3.Row
|
db.row_factory = sqlite3.Row
|
||||||
try:
|
try:
|
||||||
with db:
|
with db:
|
||||||
if not self._initialized:
|
if not self._initialized:
|
||||||
db.execute("""CREATE TABLE IF NOT EXISTS deliveries (
|
db.execute("""CREATE TABLE IF NOT EXISTS deliveries (
|
||||||
id TEXT PRIMARY KEY, run_id TEXT NOT NULL, channel TEXT NOT NULL,
|
id TEXT PRIMARY KEY, run_id TEXT NOT NULL, channel TEXT NOT NULL,
|
||||||
|
chat_id TEXT NOT NULL,
|
||||||
payload TEXT, status TEXT NOT NULL, created REAL NOT NULL,
|
payload TEXT, status TEXT NOT NULL, created REAL NOT NULL,
|
||||||
updated REAL NOT NULL, next_attempt REAL NOT NULL, error TEXT
|
updated REAL NOT NULL, next_attempt REAL NOT NULL, error TEXT
|
||||||
)""")
|
)""")
|
||||||
# A crash during send cannot tell us whether the service accepted it.
|
# A crash during send cannot tell us whether the service accepted it.
|
||||||
|
interrupted = db.execute("SELECT id, run_id, channel FROM deliveries WHERE status='sending'").fetchall()
|
||||||
db.execute("""UPDATE deliveries SET status='unknown', payload=NULL,
|
db.execute("""UPDATE deliveries SET status='unknown', payload=NULL,
|
||||||
error='interrupted_send', updated=? WHERE status='sending'""", (time.time(),))
|
error='interrupted_send', updated=? WHERE status='sending'""", (time.time(),))
|
||||||
|
for row in interrupted:
|
||||||
|
logger.warning("Channel delivery: run={} delivery={} channel={} status=unknown error=interrupted_send",
|
||||||
|
row["run_id"], row["id"], row["channel"])
|
||||||
yield db
|
yield db
|
||||||
self._initialized = True
|
self._initialized = True
|
||||||
finally:
|
finally:
|
||||||
@@ -79,16 +85,18 @@ class DeliveryOutbox:
|
|||||||
).fetchone()[0]
|
).fetchone()[0]
|
||||||
if count >= MAX_PENDING:
|
if count >= MAX_PENDING:
|
||||||
raise RuntimeError("Scheduled delivery queue is full; check channel connectivity")
|
raise RuntimeError("Scheduled delivery queue is full; check channel connectivity")
|
||||||
db.execute("INSERT INTO deliveries VALUES (?, ?, ?, ?, 'pending', ?, ?, ?, NULL)",
|
db.execute("INSERT INTO deliveries VALUES (?, ?, ?, ?, ?, 'pending', ?, ?, ?, NULL)",
|
||||||
(delivery_id, msg.delivery.run_id, msg.channel, payload, now, now, now))
|
(delivery_id, msg.delivery.run_id, msg.channel, msg.chat_id, payload, now, now, now))
|
||||||
msg.delivery_id = delivery_id
|
msg.delivery_id = delivery_id
|
||||||
self._log(msg, "pending")
|
self._log(msg, "pending")
|
||||||
|
|
||||||
@staticmethod
|
@staticmethod
|
||||||
def _prune(db: sqlite3.Connection, now: float) -> None:
|
def _prune(db: sqlite3.Connection, now: float) -> None:
|
||||||
db.execute("""UPDATE deliveries SET status='failed', payload=NULL,
|
expired = db.execute("""UPDATE deliveries SET status='failed', payload=NULL,
|
||||||
error='expired', updated=? WHERE status='pending' AND created<=?""",
|
error='expired', updated=? WHERE status='pending' AND created<=?""",
|
||||||
(now, now - MAX_AGE_SECONDS))
|
(now, now - MAX_AGE_SECONDS)).rowcount
|
||||||
|
if expired:
|
||||||
|
logger.warning("{} scheduled deliveries expired; check the instance delivery store", expired)
|
||||||
db.execute("DELETE FROM deliveries WHERE status NOT IN ('pending','sending') AND updated<?",
|
db.execute("DELETE FROM deliveries WHERE status NOT IN ('pending','sending') AND updated<?",
|
||||||
(now - RETENTION_SECONDS,))
|
(now - RETENTION_SECONDS,))
|
||||||
db.execute("""DELETE FROM deliveries WHERE id IN (
|
db.execute("""DELETE FROM deliveries WHERE id IN (
|
||||||
@@ -116,17 +124,23 @@ class DeliveryOutbox:
|
|||||||
with self._connect() as db:
|
with self._connect() as db:
|
||||||
self._prune(db, now)
|
self._prune(db, now)
|
||||||
changed = db.execute("""UPDATE deliveries SET status='sending', updated=?
|
changed = db.execute("""UPDATE deliveries SET status='sending', updated=?
|
||||||
WHERE id=? AND status='pending' AND next_attempt<=?""",
|
WHERE id=? AND status='pending' AND next_attempt<=?
|
||||||
|
AND NOT EXISTS (SELECT 1 FROM deliveries AS older
|
||||||
|
WHERE older.channel=deliveries.channel AND older.chat_id=deliveries.chat_id
|
||||||
|
AND older.rowid<deliveries.rowid AND older.status IN ('pending','sending'))""",
|
||||||
(now, msg.delivery_id, now)).rowcount
|
(now, msg.delivery_id, now)).rowcount
|
||||||
return changed == 1
|
return changed == 1
|
||||||
|
|
||||||
def finish(self, msg: OutboundMessage, status: DeliveryStatus, error: str | None = None) -> None:
|
def finish(self, msg: OutboundMessage, status: DeliveryStatus, error: str | None = None) -> None:
|
||||||
now = time.time()
|
now = time.time()
|
||||||
with self._connect() as db:
|
with self._connect() as db:
|
||||||
db.execute("""UPDATE deliveries SET status=?, error=?, updated=?, next_attempt=?,
|
changed = db.execute("""UPDATE deliveries SET status=?, error=?, updated=?, next_attempt=?,
|
||||||
payload=CASE WHEN ?='pending' THEN payload ELSE NULL END WHERE id=?""",
|
payload=CASE WHEN ?='pending' THEN payload ELSE NULL END
|
||||||
(status, error, now, now + RETRY_SECONDS, status, msg.delivery_id))
|
WHERE id=? AND status IN ('pending','sending')""",
|
||||||
self._log(msg, status, error)
|
(status, error, now, now + RETRY_SECONDS, status, msg.delivery_id)).rowcount
|
||||||
|
self._prune(db, now)
|
||||||
|
if changed:
|
||||||
|
self._log(msg, status, error)
|
||||||
|
|
||||||
@staticmethod
|
@staticmethod
|
||||||
def _log(msg: OutboundMessage, status: DeliveryStatus, error: str | None = None) -> None:
|
def _log(msg: OutboundMessage, status: DeliveryStatus, error: str | None = None) -> None:
|
||||||
|
|||||||
@@ -17,6 +17,7 @@ from typing import Any, TypedDict, cast
|
|||||||
import httpx
|
import httpx
|
||||||
from pydantic import Field, computed_field, field_validator
|
from pydantic import Field, computed_field, field_validator
|
||||||
|
|
||||||
|
from nanobot.bus.delivery import ChannelNotReadyError
|
||||||
from nanobot.bus.events import InboundMessage, OutboundMessage
|
from nanobot.bus.events import InboundMessage, OutboundMessage
|
||||||
from nanobot.bus.outbound_events import ProgressEvent
|
from nanobot.bus.outbound_events import ProgressEvent
|
||||||
from nanobot.bus.queue import MessageBus
|
from nanobot.bus.queue import MessageBus
|
||||||
@@ -571,6 +572,8 @@ class SignalChannel(BaseChannel):
|
|||||||
msg.event.notify or self.show_compaction_notices
|
msg.event.notify or self.show_compaction_notices
|
||||||
):
|
):
|
||||||
return
|
return
|
||||||
|
if not self._http:
|
||||||
|
raise ChannelNotReadyError("Signal client not connected")
|
||||||
is_progress_message = isinstance(msg.event, ProgressEvent)
|
is_progress_message = isinstance(msg.event, ProgressEvent)
|
||||||
try:
|
try:
|
||||||
plain_text, text_styles = _markdown_to_signal(msg.content)
|
plain_text, text_styles = _markdown_to_signal(msg.content)
|
||||||
|
|||||||
@@ -802,7 +802,7 @@ class TelegramChannel(BaseChannel):
|
|||||||
with suppress(asyncio.TimeoutError):
|
with suppress(asyncio.TimeoutError):
|
||||||
await asyncio.wait_for(self._app_ready.wait(), APP_RESTART_SEND_WAIT_SECONDS)
|
await asyncio.wait_for(self._app_ready.wait(), APP_RESTART_SEND_WAIT_SECONDS)
|
||||||
if not self._app_ready.is_set() or self._app is None:
|
if not self._app_ready.is_set() or self._app is None:
|
||||||
raise RuntimeError("Telegram application is restarting; message not delivered")
|
raise ChannelNotReadyError("Telegram application is restarting; message not delivered")
|
||||||
return self._app
|
return self._app
|
||||||
|
|
||||||
def _note_poll_ok(self) -> None:
|
def _note_poll_ok(self) -> None:
|
||||||
|
|||||||
@@ -12,6 +12,7 @@ try:
|
|||||||
except ImportError:
|
except ImportError:
|
||||||
pytest.skip("Telegram dependencies not installed (python-telegram-bot)", allow_module_level=True)
|
pytest.skip("Telegram dependencies not installed (python-telegram-bot)", allow_module_level=True)
|
||||||
|
|
||||||
|
from nanobot.bus.delivery import ChannelNotReadyError
|
||||||
from nanobot.bus.events import OutboundMessage
|
from nanobot.bus.events import OutboundMessage
|
||||||
from nanobot.bus.outbound_events import ProgressEvent
|
from nanobot.bus.outbound_events import ProgressEvent
|
||||||
from nanobot.bus.queue import MessageBus
|
from nanobot.bus.queue import MessageBus
|
||||||
@@ -621,14 +622,15 @@ async def test_send_during_rebuild_fails_instead_of_dropping(monkeypatch) -> Non
|
|||||||
channel._app = None
|
channel._app = None
|
||||||
|
|
||||||
msg = OutboundMessage(channel="telegram", chat_id="123", content="hello")
|
msg = OutboundMessage(channel="telegram", chat_id="123", content="hello")
|
||||||
with pytest.raises(RuntimeError, match="restarting"):
|
with pytest.raises(ChannelNotReadyError, match="restarting"):
|
||||||
await channel.send(msg)
|
await channel.send(msg)
|
||||||
with pytest.raises(RuntimeError, match="restarting"):
|
with pytest.raises(RuntimeError, match="restarting"):
|
||||||
await channel.send_delta("123", "hello", stream_id="s1")
|
await channel.send_delta("123", "hello", stream_id="s1")
|
||||||
|
|
||||||
# Stopped: nothing to deliver, so stay quiet.
|
# A stopped channel must not report a final message as delivered.
|
||||||
channel._running = False
|
channel._running = False
|
||||||
await channel.send(msg)
|
with pytest.raises(ChannelNotReadyError, match="not running"):
|
||||||
|
await channel.send(msg)
|
||||||
await channel.send_delta("123", "hello", stream_id="s1")
|
await channel.send_delta("123", "hello", stream_id="s1")
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -2082,7 +2082,13 @@ class WeixinChannel(BaseChannel):
|
|||||||
)
|
)
|
||||||
delivery_state.completed_parts.add(text_part)
|
delivery_state.completed_parts.add(text_part)
|
||||||
completed = True
|
completed = True
|
||||||
except WeixinQuotaError:
|
except WeixinQuotaError as error:
|
||||||
|
if msg.delivery_id is not None:
|
||||||
|
# The durable outbox owns scheduled results. Do not also retain
|
||||||
|
# one in the channel's independently replayed, volatile queue.
|
||||||
|
if not delivery_state.completed_parts:
|
||||||
|
raise ChannelNotReadyError("WeChat needs a fresh inbound context") from error
|
||||||
|
raise
|
||||||
if not is_progress:
|
if not is_progress:
|
||||||
self._defer_outbound(msg)
|
self._defer_outbound(msg)
|
||||||
self.logger.warning(
|
self.logger.warning(
|
||||||
|
|||||||
@@ -9,6 +9,7 @@ from unittest.mock import AsyncMock
|
|||||||
import httpx
|
import httpx
|
||||||
import pytest
|
import pytest
|
||||||
|
|
||||||
|
from nanobot.bus.delivery import ChannelNotReadyError
|
||||||
from nanobot.bus.outbound_events import ProgressEvent
|
from nanobot.bus.outbound_events import ProgressEvent
|
||||||
from nanobot.bus.queue import MessageBus
|
from nanobot.bus.queue import MessageBus
|
||||||
from nanobot.channels.weixin import runtime as weixin_mod
|
from nanobot.channels.weixin import runtime as weixin_mod
|
||||||
@@ -546,9 +547,7 @@ async def test_send_without_context_token_raises() -> None:
|
|||||||
channel._send_text = AsyncMock()
|
channel._send_text = AsyncMock()
|
||||||
|
|
||||||
with pytest.raises(RuntimeError, match="context_token missing"):
|
with pytest.raises(RuntimeError, match="context_token missing"):
|
||||||
await channel.send(
|
await channel.send(_make_outbound_msg(chat_id="unknown-user", content="pong"))
|
||||||
type("Msg", (), {"chat_id": "unknown-user", "content": "pong", "media": [], "metadata": {}})()
|
|
||||||
)
|
|
||||||
|
|
||||||
channel._send_text.assert_not_awaited()
|
channel._send_text.assert_not_awaited()
|
||||||
|
|
||||||
@@ -1482,6 +1481,26 @@ def _make_outbound_msg(chat_id: str = "wx-user", content: str = "", media: list
|
|||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize("partial", [False, True])
|
||||||
|
async def test_scheduled_quota_failure_has_only_one_recovery_owner(partial):
|
||||||
|
channel, _bus = _make_channel()
|
||||||
|
channel._client = object()
|
||||||
|
channel._token = "token"
|
||||||
|
channel._refresh_context_token_if_stale = AsyncMock(return_value="context")
|
||||||
|
channel._get_typing_ticket = AsyncMock(return_value="")
|
||||||
|
channel._send_media_part = AsyncMock()
|
||||||
|
channel._send_text = AsyncMock(side_effect=weixin_mod.WeixinQuotaError("sendmessage"))
|
||||||
|
msg = _make_outbound_msg(content="result", media=["image.png"] if partial else [])
|
||||||
|
msg.delivery_id = "scheduled-result"
|
||||||
|
|
||||||
|
expected = weixin_mod.WeixinQuotaError if partial else ChannelNotReadyError
|
||||||
|
with pytest.raises(expected):
|
||||||
|
await channel.send(msg)
|
||||||
|
|
||||||
|
assert channel._deferred_outbound == {}
|
||||||
|
assert channel._send_media_part.await_count == int(partial)
|
||||||
|
|
||||||
|
|
||||||
@pytest.mark.asyncio
|
@pytest.mark.asyncio
|
||||||
async def test_send_media_timeout_error_propagates_without_text_fallback() -> None:
|
async def test_send_media_timeout_error_propagates_without_text_fallback() -> None:
|
||||||
"""httpx.TimeoutException during media send must re-raise immediately,
|
"""httpx.TimeoutException during media send must re-raise immediately,
|
||||||
|
|||||||
@@ -53,6 +53,10 @@ def _bound_session_delivery_context(
|
|||||||
source_label=source_label,
|
source_label=source_label,
|
||||||
)
|
)
|
||||||
)
|
)
|
||||||
|
else:
|
||||||
|
# External scheduled results need one recoverable final message, not a
|
||||||
|
# transient stream whose completion marker cannot be replayed safely.
|
||||||
|
metadata.pop("_wants_stream", None)
|
||||||
|
|
||||||
return channel, chat_id, metadata
|
return channel, chat_id, metadata
|
||||||
|
|
||||||
|
|||||||
@@ -2,6 +2,7 @@
|
|||||||
|
|
||||||
import asyncio
|
import asyncio
|
||||||
import json
|
import json
|
||||||
|
import os
|
||||||
import sqlite3
|
import sqlite3
|
||||||
from functools import partial
|
from functools import partial
|
||||||
from unittest.mock import AsyncMock, MagicMock
|
from unittest.mock import AsyncMock, MagicMock
|
||||||
@@ -11,7 +12,12 @@ import pytest
|
|||||||
from nanobot.agent.loop import AgentLoop
|
from nanobot.agent.loop import AgentLoop
|
||||||
from nanobot.agent.tools.context import RequestContext, request_context
|
from nanobot.agent.tools.context import RequestContext, request_context
|
||||||
from nanobot.agent.tools.message import MessageTool
|
from nanobot.agent.tools.message import MessageTool
|
||||||
from nanobot.bus.delivery import DELIVERY_RUN_META, ChannelNotReadyError, DeliveryRequest
|
from nanobot.bus.delivery import (
|
||||||
|
DELIVERY_RUN_META,
|
||||||
|
ChannelNotReadyError,
|
||||||
|
DeliveryRejectedError,
|
||||||
|
DeliveryRequest,
|
||||||
|
)
|
||||||
from nanobot.bus.events import OutboundMessage
|
from nanobot.bus.events import OutboundMessage
|
||||||
from nanobot.bus.outbound_events import ProgressEvent
|
from nanobot.bus.outbound_events import ProgressEvent
|
||||||
from nanobot.bus.queue import MessageBus
|
from nanobot.bus.queue import MessageBus
|
||||||
@@ -19,6 +25,7 @@ from nanobot.channels import outbox as outbox_module
|
|||||||
from nanobot.channels.base import BaseChannel
|
from nanobot.channels.base import BaseChannel
|
||||||
from nanobot.channels.manager import ChannelManager
|
from nanobot.channels.manager import ChannelManager
|
||||||
from nanobot.channels.outbox import DeliveryOutbox
|
from nanobot.channels.outbox import DeliveryOutbox
|
||||||
|
from nanobot.channels.registry import load_channel_plugin
|
||||||
from nanobot.channels.whatsapp.runtime import WhatsAppChannel
|
from nanobot.channels.whatsapp.runtime import WhatsAppChannel
|
||||||
from nanobot.config.schema import Config
|
from nanobot.config.schema import Config
|
||||||
from nanobot.cron.bound_runner import run_bound_cron_job
|
from nanobot.cron.bound_runner import run_bound_cron_job
|
||||||
@@ -54,8 +61,8 @@ async def drain(manager):
|
|||||||
await asyncio.sleep(0.01)
|
await asyncio.sleep(0.01)
|
||||||
|
|
||||||
|
|
||||||
@pytest.mark.parametrize("legacy_message", [False, True])
|
@pytest.mark.parametrize("legacy_message,one_shot", [(False, False), (True, False), (True, True)])
|
||||||
async def test_cron_offline_restart_and_reconnect_do_not_rerun_model(tmp_path, monkeypatch, legacy_message):
|
async def test_cron_offline_restart_and_reconnect_do_not_rerun_model(tmp_path, monkeypatch, legacy_message, one_shot):
|
||||||
monkeypatch.setattr(outbox_module, "RETRY_SECONDS", 0)
|
monkeypatch.setattr(outbox_module, "RETRY_SECONDS", 0)
|
||||||
workspace = tmp_path / "workspace"
|
workspace = tmp_path / "workspace"
|
||||||
workspace.mkdir()
|
workspace.mkdir()
|
||||||
@@ -93,13 +100,18 @@ async def test_cron_offline_restart_and_reconnect_do_not_rerun_model(tmp_path, m
|
|||||||
manager.channels["whatsapp"] = channel
|
manager.channels["whatsapp"] = channel
|
||||||
manager._dispatch_task = asyncio.create_task(manager._dispatch_outbound())
|
manager._dispatch_task = asyncio.create_task(manager._dispatch_outbound())
|
||||||
# Legacy channel/to fields still normalize through the existing binding migration.
|
# Legacy channel/to fields still normalize through the existing binding migration.
|
||||||
job = cron.add_job("Reminder", CronSchedule(kind="every", every_ms=86400000),
|
schedule = CronSchedule(kind="at", at_ms=4102444800000) if one_shot else CronSchedule(kind="every", every_ms=86400000)
|
||||||
|
job = cron.add_job("Reminder", schedule,
|
||||||
"Use message to send Diagnostic result" if legacy_message else "Return Diagnostic result",
|
"Use message to send Diagnostic result" if legacy_message else "Return Diagnostic result",
|
||||||
deliver=True, channel="whatsapp", to="synthetic")
|
deliver=True, channel="whatsapp", to="synthetic", delete_after_run=one_shot,
|
||||||
|
channel_meta={"_wants_stream": True})
|
||||||
try:
|
try:
|
||||||
assert await asyncio.wait_for(cron.run_job(job.id), 15)
|
assert await asyncio.wait_for(cron.run_job(job.id), 15)
|
||||||
await drain(manager)
|
await drain(manager)
|
||||||
assert cron.list_jobs()[0].state.last_status == "ok"
|
if one_shot:
|
||||||
|
assert cron.list_jobs() == []
|
||||||
|
else:
|
||||||
|
assert cron.list_jobs()[0].state.last_status == "ok"
|
||||||
assert len(rows(manager._outbox)) == 1
|
assert len(rows(manager._outbox)) == 1
|
||||||
assert rows(manager._outbox)[0]["status"] == "pending"
|
assert rows(manager._outbox)[0]["status"] == "pending"
|
||||||
channel._client.send_message.assert_not_called()
|
channel._client.send_message.assert_not_called()
|
||||||
@@ -123,7 +135,8 @@ async def test_cron_offline_restart_and_reconnect_do_not_rerun_model(tmp_path, m
|
|||||||
assert channel._client.send_message.await_count == 1
|
assert channel._client.send_message.await_count == 1
|
||||||
assert len(calls) == count
|
assert len(calls) == count
|
||||||
# Existing jobs still load after delivery state is added beside them.
|
# Existing jobs still load after delivery state is added beside them.
|
||||||
assert CronService(cron.store_path).list_jobs()[0].payload.message == job.payload.message
|
old_jobs = CronService(cron.store_path).list_jobs()
|
||||||
|
assert old_jobs == [] if one_shot else old_jobs[0].payload.message == job.payload.message
|
||||||
finally:
|
finally:
|
||||||
await manager.stop_all()
|
await manager.stop_all()
|
||||||
cron.stop()
|
cron.stop()
|
||||||
@@ -172,6 +185,7 @@ async def test_legacy_broadcast_has_independent_targets_and_no_foreign_thread_me
|
|||||||
async def test_queue_acceptance_survives_restart_but_inflight_is_unknown(tmp_path):
|
async def test_queue_acceptance_survives_restart_but_inflight_is_unknown(tmp_path):
|
||||||
manager = make_manager(tmp_path)
|
manager = make_manager(tmp_path)
|
||||||
pending, inflight = message(), message(content="second")
|
pending, inflight = message(), message(content="second")
|
||||||
|
inflight.chat_id = "other-destination"
|
||||||
await manager.bus.publish_outbound(pending)
|
await manager.bus.publish_outbound(pending)
|
||||||
await manager.bus.publish_outbound(inflight)
|
await manager.bus.publish_outbound(inflight)
|
||||||
assert manager._outbox.claim(inflight)
|
assert manager._outbox.claim(inflight)
|
||||||
@@ -198,7 +212,8 @@ async def test_queue_bounds_expiry_and_untracked_events(tmp_path, monkeypatch):
|
|||||||
assert manager._outbox.ready() == []
|
assert manager._outbox.ready() == []
|
||||||
assert rows(manager._outbox)[0]["error"] == "expired"
|
assert rows(manager._outbox)[0]["error"] == "expired"
|
||||||
assert not manager._outbox.claim(first)
|
assert not manager._outbox.claim(first)
|
||||||
assert manager._outbox.path.stat().st_mode & 0o777 == 0o600
|
if os.name != "nt":
|
||||||
|
assert manager._outbox.path.stat().st_mode & 0o777 == 0o600
|
||||||
|
|
||||||
|
|
||||||
@pytest.mark.parametrize("operation", ["delete", "reset"])
|
@pytest.mark.parametrize("operation", ["delete", "reset"])
|
||||||
@@ -218,3 +233,78 @@ async def test_pending_result_cannot_send_after_source_session_is_replaced(tmp_p
|
|||||||
assert rows(manager._outbox)[0]["error"] == "session_replaced"
|
assert rows(manager._outbox)[0]["error"] == "session_replaced"
|
||||||
finally:
|
finally:
|
||||||
await sessions.state.aclose()
|
await sessions.state.aclose()
|
||||||
|
|
||||||
|
|
||||||
|
async def test_recovery_keeps_destination_order_and_does_not_block_other_chats(tmp_path, monkeypatch):
|
||||||
|
monkeypatch.setattr(outbox_module, "RETRY_SECONDS", 0)
|
||||||
|
manager = make_manager(tmp_path)
|
||||||
|
first, second, other = message(content="first"), message(content="second"), message(content="other")
|
||||||
|
other.chat_id = "another-chat"
|
||||||
|
for msg in (first, second, other):
|
||||||
|
await manager.bus.publish_outbound(msg)
|
||||||
|
await manager.bus.consume_outbound()
|
||||||
|
channel = MagicMock(spec=BaseChannel, send=AsyncMock(side_effect=ChannelNotReadyError()))
|
||||||
|
await manager._send_scheduled(channel, first)
|
||||||
|
channel.send.side_effect = None
|
||||||
|
await manager._send_scheduled(channel, second)
|
||||||
|
await manager._send_scheduled(channel, other)
|
||||||
|
assert [call.args[0].content for call in channel.send.await_args_list] == ["first", "other"]
|
||||||
|
manager.channels["whatsapp"] = channel
|
||||||
|
await manager._recover_scheduled()
|
||||||
|
await drain(manager)
|
||||||
|
assert [call.args[0].content for call in channel.send.await_args_list] == ["first", "other", "first", "second"]
|
||||||
|
# A stale queued copy must not downgrade the durable successful result.
|
||||||
|
manager._outbox.finish(first, "failed", "channel_disabled")
|
||||||
|
assert all(row["status"] == "sent" for row in rows(manager._outbox))
|
||||||
|
|
||||||
|
|
||||||
|
async def test_relocated_instance_finds_queue_and_disabled_channel_does_not_send(tmp_path):
|
||||||
|
original = tmp_path / "original"
|
||||||
|
manager = make_manager(original)
|
||||||
|
await manager.bus.publish_outbound(message())
|
||||||
|
moved = tmp_path / "moved"
|
||||||
|
original.rename(moved)
|
||||||
|
restarted = make_manager(moved)
|
||||||
|
await restarted._recover_scheduled()
|
||||||
|
assert rows(restarted._outbox)[0]["error"] == "channel_disabled"
|
||||||
|
assert not original.exists()
|
||||||
|
|
||||||
|
|
||||||
|
async def test_recovery_rechecks_attachment_workspace_boundary(tmp_path):
|
||||||
|
workspace = tmp_path / "workspace"
|
||||||
|
workspace.mkdir()
|
||||||
|
sessions = SessionManager(workspace, sessions_root=tmp_path / "sessions")
|
||||||
|
session = await sessions.state.get("whatsapp:synthetic")
|
||||||
|
manager = make_manager(tmp_path, sessions)
|
||||||
|
manager.config.agents.defaults.workspace = str(workspace)
|
||||||
|
manager.config.tools.restrict_to_workspace = True
|
||||||
|
attachment = workspace / "report.txt"
|
||||||
|
attachment.write_text("report")
|
||||||
|
msg = message(generation=session.generation)
|
||||||
|
msg.media = [str(attachment)]
|
||||||
|
channel = MagicMock(spec=BaseChannel, send=AsyncMock())
|
||||||
|
try:
|
||||||
|
await manager.bus.publish_outbound(msg)
|
||||||
|
attachment.unlink()
|
||||||
|
private = tmp_path / "private.txt"
|
||||||
|
private.write_text("not authorized")
|
||||||
|
attachment.symlink_to(private)
|
||||||
|
await manager._send_scheduled(channel, msg)
|
||||||
|
channel.send.assert_not_called()
|
||||||
|
assert rows(manager._outbox)[0]["error"] == "attachment_access_denied"
|
||||||
|
finally:
|
||||||
|
await sessions.state.aclose()
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize("name", [
|
||||||
|
"whatsapp", "telegram", "discord", "slack", "matrix", "mattermost", "feishu",
|
||||||
|
"qq", "wecom", "weixin", "napcat", "msteams", "linear", "signal", "dingtalk",
|
||||||
|
"mochat", "email",
|
||||||
|
])
|
||||||
|
async def test_unavailable_adapter_does_not_report_success(name, monkeypatch):
|
||||||
|
cls = load_channel_plugin(name).load_channel_class()
|
||||||
|
channel = cls(cls.default_config(), MessageBus())
|
||||||
|
if name == "dingtalk":
|
||||||
|
monkeypatch.setattr(channel, "_get_access_token", AsyncMock(return_value=None))
|
||||||
|
with pytest.raises((ChannelNotReadyError, DeliveryRejectedError)):
|
||||||
|
await channel.send(OutboundMessage(name, "synthetic", "result"))
|
||||||
Reference in new issue
Block a user