fix(channels): retain scheduled results across pre-send outages

This commit is contained in:
Xubin Ren committed 2026-10-17 12:49:03 +08:00
1 parent faf1efaf09
commit 9c1b16b3cc
27 files changed
+568 -51

No files matched your search

+38
View File
@@ -46,6 +46,44 @@ Write what the task should do, such as "Remind me to drink water". nanobot sends
For separate sends, specify the recipients in the instructions. The agent can still use `message` to send to other chats, send to several recipients, or attach files. Existing tasks that explicitly request this tool remain supported.
### Scheduled Result Delivery
Task completion and message delivery are separate. `Turn completed` and a successful task run
mean that execution finished. They do not confirm that a chat service received the result.
The gateway saves final scheduled messages before it accepts them into the outgoing queue.
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
saved chat history keep their existing behavior.
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
destination. It does not run the task or call the model again. A gateway restart resumes pending
messages. Deleting or resetting the source chat cancels pending messages from that chat generation.
Disabling a channel prevents its pending messages from being sent. Changing a task's chat affects
future runs; it does not redirect an already queued result.
If a request times out after sending starts, or the gateway stops during a send, delivery is
unknown. The gateway does not retry that message automatically: the service might already have
accepted it. Check the destination before sending the result again. This is not an exactly-once
delivery guarantee. Adapter or service-specific retries still follow their own protocol.
Look for `Channel delivery` in the gateway log. The run ID links execution to each delivery ID:
| Status | Meaning |
|---|---|
| `pending` | Saved locally; waiting for an attempt or a channel connection |
| `sent` | The channel adapter completed its send; not a recipient read receipt |
| `failed` | Not sent: expired, disabled channel, replaced source chat, or rejected destination/policy |
| `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
directory in instance backups. 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
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
queue; pending delivery resumes only when a version with queue support runs again.
For background checks that should stay quiet unless there is something useful to report, use heartbeat instead of a user-created scheduled automation.
Repetition alone does not select heartbeat. "Every day at 8am, remind me to drink water" needs a cron schedule. "Keep an eye on open issues and tell me when one needs attention" can use heartbeat if the check time is flexible. Heartbeat does not guarantee a requested time or interval.
+6 -1
View File
@@ -14,6 +14,7 @@ from nanobot.agent.tools.base import Tool, ToolResult, tool_parameters
from nanobot.agent.tools.context import ToolContext, current_request_context
from nanobot.agent.tools.path_utils import resolve_workspace_path
from nanobot.agent.tools.schema import ArraySchema, StringSchema, tool_parameters_schema
from nanobot.bus.delivery import DeliveryRequest
from nanobot.bus.events import OutboundMessage
from nanobot.config.paths import get_workspace_path
from nanobot.security.workspace_access import current_tool_workspace
@@ -236,6 +237,9 @@ class MessageTool(Tool):
media=media or [],
buttons=button_rows or [],
metadata=metadata,
delivery=(DeliveryRequest.from_context(
default_metadata, request_ctx.session_key, request_ctx.session_generation,
) if request_ctx is not None else None),
)
if self._suppress_delivery_var.get():
@@ -253,6 +257,7 @@ class MessageTool(Tool):
if button_rows
else ""
)
return f"Message sent to {channel}:{chat_id}{media_info}{button_info}"
action = "queued" if msg.delivery is not None else "sent"
return f"Message {action} to {channel}:{chat_id}{media_info}{button_info}"
except Exception as e:
return ToolResult.error(f"Error sending message: {str(e)}")
+7
View File
@@ -9,6 +9,7 @@ from copy import deepcopy
from dataclasses import dataclass, field
from typing import TYPE_CHECKING, Any, cast
from nanobot.bus.delivery import DeliveryRequest
from nanobot.bus.events import InboundMessage, OutboundMessage
from nanobot.bus.notification_delivery import notification_is_deliverable
from nanobot.bus.outbound_events import (
@@ -341,6 +342,12 @@ class TurnDelivery:
"response_sources": [dataclasses.asdict(self._response_source)],
})
if response.channel != "websocket" or stop_reason != "error":
delivery = DeliveryRequest.from_context(
self.input_message.metadata, self.session_key,
self.delivery_message.session_generation,
)
if delivery is not None:
response = dataclasses.replace(response, delivery=delivery)
await self.bus.publish_outbound(response)
elif self.lifecycle_message.channel == "cli":
await self.bus.publish_outbound(
+36
View File
@@ -0,0 +1,36 @@
"""Delivery correlation and pre-send failure contracts, independent of transports."""
from __future__ import annotations
from collections.abc import Mapping
from dataclasses import dataclass
DELIVERY_RUN_META = "_delivery_run_id"
class ChannelNotReadyError(RuntimeError):
"""No part of the message was sent; retry after the channel reconnects."""
class DeliveryRejectedError(RuntimeError):
"""No part of the message was sent; configuration or destination needs repair."""
@dataclass(frozen=True)
class DeliveryRequest:
"""A scheduled result belongs to one run and one admitted source session."""
run_id: str
session_key: str
session_generation: str | None
@classmethod
def from_context(
cls, metadata: Mapping[str, object], session_key: str | None, generation: str | None,
) -> DeliveryRequest | None:
run_id = metadata.get(DELIVERY_RUN_META)
if not isinstance(run_id, str) or not run_id:
return None
if not session_key:
raise ValueError("Scheduled delivery requires a source session")
return cls(run_id, session_key, generation)
+4
View File
@@ -4,6 +4,8 @@ from dataclasses import dataclass, field
from datetime import datetime
from typing import TYPE_CHECKING, Any, Literal
from nanobot.bus.delivery import DeliveryRequest
if TYPE_CHECKING:
from nanobot.events import AgentEvent
@@ -68,3 +70,5 @@ class OutboundMessage:
metadata: dict[str, Any] = field(default_factory=dict)
buttons: list[list[str]] = field(default_factory=list)
event: "AgentEvent | None" = None
delivery: DeliveryRequest | None = None
delivery_id: str | None = None
+3
View File
@@ -33,6 +33,7 @@ class MessageBus:
self.outbound: asyncio.Queue[OutboundMessage] = asyncio.Queue()
self._handlers: list[EventHandler] = []
self._pending: set[asyncio.Task[None]] = set()
self.outbound_recorder: Callable[[OutboundMessage], None] | None = None
async def publish_inbound(self, msg: InboundMessage) -> None:
"""Publish a message from a channel to the agent."""
@@ -44,6 +45,8 @@ class MessageBus:
async def publish_outbound(self, msg: OutboundMessage) -> None:
"""Queue a routed message or event for its channel."""
if self.outbound_recorder is not None:
self.outbound_recorder(msg)
await self.outbound.put(msg)
async def publish_event(
+4
View File
@@ -100,6 +100,10 @@ class BaseChannel(ABC):
Implementations should raise on delivery failure so the channel manager
can apply any retry policy in one place.
Raise ChannelNotReadyError only before submitting any part of a message.
Raise DeliveryRejectedError for a rejected destination or policy.
Other exceptions have an unknown delivery outcome for scheduled results.
A normal return confirms this adapter completed, not a recipient read receipt.
"""
pass
+2 -1
View File
@@ -17,6 +17,7 @@ from urllib.parse import unquote, urljoin, urlparse
import httpx
from pydantic import Field
from nanobot.bus.delivery import ChannelNotReadyError
from nanobot.bus.events import OutboundMessage
from nanobot.bus.queue import MessageBus
from nanobot.channels.base import BaseChannel
@@ -742,7 +743,7 @@ class DingTalkChannel(BaseChannel):
return
token = await self._get_access_token()
if not token:
raise RuntimeError("DingTalk access token unavailable")
raise ChannelNotReadyError("DingTalk access token unavailable")
content = msg.content.strip() if msg.content else ""
if content:
+2 -1
View File
@@ -13,6 +13,7 @@ from typing import TYPE_CHECKING, Any, Literal, cast
from pydantic import Field
from nanobot.bus.delivery import ChannelNotReadyError
from nanobot.bus.events import OutboundMessage
from nanobot.bus.outbound_events import ContextCompactionEvent, ProgressEvent
from nanobot.bus.queue import MessageBus
@@ -539,7 +540,7 @@ class DiscordChannel(BaseChannel):
"""Send a message through Discord using discord.py."""
client = self._client
if client is None or not client.is_ready():
raise RuntimeError("Discord client is not ready")
raise ChannelNotReadyError("Discord client is not ready")
is_progress = isinstance(msg.event, ProgressEvent)
+5 -8
View File
@@ -23,6 +23,7 @@ from typing import Any, Literal, cast
from loguru import logger
from pydantic import Field, field_validator
from nanobot.bus.delivery import DeliveryRejectedError
from nanobot.bus.events import OutboundMessage
from nanobot.bus.outbound_events import ProgressEvent
from nanobot.bus.queue import MessageBus
@@ -245,12 +246,10 @@ class EmailChannel(BaseChannel):
):
return
if not self.config.consent_granted:
self.logger.warning("Skip email send: consent_granted is false")
return
raise DeliveryRejectedError("Email consent_granted is false")
if not self.config.smtp_host:
self.logger.warning("SMTP host not configured")
return
raise DeliveryRejectedError("SMTP host not configured")
# Skip progress messages to prevent sending an empty email after each tool call
if isinstance(msg.event, ProgressEvent):
@@ -259,8 +258,7 @@ class EmailChannel(BaseChannel):
to_addr = msg.chat_id.strip()
if not to_addr:
self.logger.warning("Missing recipient address")
return
raise DeliveryRejectedError("Missing email recipient address")
# Determine if this is a reply (recipient has sent us an email before)
is_reply = to_addr in self._last_subject_by_chat
@@ -268,8 +266,7 @@ class EmailChannel(BaseChannel):
# autoReplyEnabled only controls automatic replies, not proactive sends
if is_reply and not self.config.auto_reply_enabled and not force_send:
self.logger.info("Skip automatic reply to {}: auto_reply_enabled is false", to_addr)
return
raise DeliveryRejectedError("Email auto_reply_enabled is false")
base_subject = self._last_subject_by_chat.get(to_addr, "nanobot reply")
subject = self._reply_subject(base_subject)
@@ -5,6 +5,7 @@ from pathlib import Path
import pytest
from nanobot.bus.delivery import DeliveryRejectedError
from nanobot.bus.events import OutboundMessage
from nanobot.bus.outbound_events import ProgressEvent
from nanobot.bus.queue import MessageBus
@@ -874,14 +875,15 @@ async def test_send_skips_reply_when_auto_reply_disabled(monkeypatch) -> None:
# Mark alice as someone who sent us an email (making this a "reply")
channel._last_subject_by_chat["alice@example.com"] = "Previous email"
# Reply should be skipped (auto_reply_enabled=False)
await channel.send(
OutboundMessage(
channel="email",
chat_id="alice@example.com",
content="Should not send.",
# A policy rejection must not look like successful delivery to the manager.
with pytest.raises(DeliveryRejectedError, match="auto_reply_enabled"):
await channel.send(
OutboundMessage(
channel="email",
chat_id="alice@example.com",
content="Should not send.",
)
)
)
assert fake_instances == []
# Reply with force_send=True should be sent
@@ -979,14 +981,15 @@ async def test_send_skips_when_consent_not_granted(monkeypatch) -> None:
cfg = _make_config()
cfg.consent_granted = False
channel = EmailChannel(cfg, MessageBus())
await channel.send(
OutboundMessage(
channel="email",
chat_id="alice@example.com",
content="Should not send.",
metadata={"force_send": True},
with pytest.raises(DeliveryRejectedError, match="consent_granted"):
await channel.send(
OutboundMessage(
channel="email",
chat_id="alice@example.com",
content="Should not send.",
metadata={"force_send": True},
)
)
)
assert called["smtp"] is False
+2 -4
View File
@@ -25,6 +25,7 @@ from rich.markup import escape
from rich.panel import Panel
from rich.text import Text
from nanobot.bus.delivery import ChannelNotReadyError
from nanobot.bus.events import OutboundMessage
from nanobot.bus.outbound_events import ProgressEvent
from nanobot.bus.queue import MessageBus
@@ -2446,10 +2447,7 @@ class FeishuChannel(BaseChannel):
):
return
if not self._client:
if msg.metadata.get(PAIRING_CODE_META_KEY):
raise RuntimeError("Feishu client is not ready to send the pairing reply")
self.logger.warning("client not initialized")
return
raise ChannelNotReadyError("Feishu client is not ready to send the reply")
try:
receive_id_type = "chat_id" if msg.chat_id.startswith("oc_") else "open_id"
+61 -3
View File
@@ -5,6 +5,7 @@ from __future__ import annotations
import asyncio
import hashlib
import inspect
import time
from collections import OrderedDict
from collections.abc import Awaitable, Callable, Iterable, Mapping
from contextlib import suppress
@@ -13,6 +14,7 @@ from typing import TYPE_CHECKING, Any, cast
from loguru import logger
from nanobot.bus.delivery import ChannelNotReadyError, DeliveryRejectedError
from nanobot.bus.events import OutboundMessage
from nanobot.bus.outbound_events import (
ProgressEvent,
@@ -32,6 +34,7 @@ from nanobot.channels.contracts import (
channel_runtime_name,
resolve_channel_action_target,
)
from nanobot.channels.outbox import RETRY_SECONDS, DeliveryOutbox
from nanobot.channels.registry import channel_default_enabled
from nanobot.config.schema import Config
from nanobot.utils.restart import (
@@ -154,6 +157,9 @@ class ChannelManager:
self._stopping_channels: set[str] = set()
self._started = False
self._origin_reply_fingerprints: OrderedDict[tuple[str, str, str], str] = OrderedDict()
self._outbox = DeliveryOutbox(self._config_path.parent / "delivery" / "outbox.sqlite3")
self._scheduled_deliveries: set[str] = set()
self.bus.outbound_recorder = self._outbox.record
self._init_channels()
@@ -750,18 +756,25 @@ class ChannelManager:
Retry waits occupy only their destination and one send slot. Saturation
pauses dispatch rather than creating unbounded tasks or dropping messages.
"""
if msg.delivery_id in self._scheduled_deliveries:
return
await self._outbound_slots.acquire()
if msg.channel in self._stopping_channels or self.channels.get(msg.channel) is not channel:
self._outbound_slots.release()
return
key = (msg.channel, msg.chat_id)
previous = self._outbound_tails.get(key)
if msg.delivery_id is not None:
self._scheduled_deliveries.add(msg.delivery_id)
async def send() -> None:
if previous is not None:
await asyncio.shield(asyncio.gather(previous, return_exceptions=True))
async with self._outbound_sends:
await self._send_with_retry(channel, msg)
if msg.delivery_id is not None:
await self._send_scheduled(channel, msg)
else:
await self._send_with_retry(channel, msg)
task = asyncio.create_task(send(), name=f"outbound-{msg.channel}-{msg.chat_id}")
self._outbound_tasks[task] = key
@@ -769,6 +782,8 @@ class ChannelManager:
def finished(done: asyncio.Task[None]) -> None:
self._outbound_tasks.pop(done, None)
if msg.delivery_id is not None:
self._scheduled_deliveries.discard(msg.delivery_id)
if self._outbound_tails.get(key) is done:
self._outbound_tails.pop(key, None)
self._outbound_slots.release()
@@ -777,6 +792,40 @@ class ChannelManager:
task.add_done_callback(finished)
async def _send_scheduled(self, channel: BaseChannel, msg: OutboundMessage) -> None:
request = msg.delivery
if request is not None and request.session_generation is not None and self._session_manager:
session = await self._session_manager.state.read(request.session_key)
if session is None or session.generation != request.session_generation:
self._outbox.finish(msg, "failed", "session_replaced")
return
if not self._outbox.claim(msg):
return
try:
await self._send_once(channel, msg)
except ChannelNotReadyError:
# The adapter guarantees that no part of the message was submitted.
self._outbox.finish(msg, "pending", "channel_not_ready")
except DeliveryRejectedError:
self._outbox.finish(msg, "failed", "delivery_rejected")
except asyncio.CancelledError:
self._outbox.finish(msg, "unknown", "interrupted_send")
raise
except Exception as error:
# A timeout can follow an accepted send, including a partial multi-part send.
# Retrying the whole result here could deliver it twice.
self._outbox.finish(msg, "unknown", type(error).__name__)
else:
self._outbox.finish(msg, "sent")
async def _recover_scheduled(self) -> None:
for msg in self._outbox.ready():
channel = self.channels.get(msg.channel)
if channel is None:
self._outbox.finish(msg, "failed", "channel_disabled")
else:
await self._queue_outbound(channel, msg)
async def _dispatch_outbound(self) -> None:
try:
await self._dispatch_outbound_loop()
@@ -790,9 +839,16 @@ class ChannelManager:
# Buffer for messages that couldn't be processed during delta coalescing
# (since asyncio.Queue doesn't support push_front)
pending: list[OutboundMessage] = []
next_recovery = 0.0
while True:
try:
if time.monotonic() >= next_recovery:
next_recovery = time.monotonic() + RETRY_SECONDS
try:
await self._recover_scheduled()
except Exception:
logger.exception("Scheduled delivery recovery failed; check the instance delivery store")
# First check pending buffer before waiting on queue
if pending:
msg = pending.pop(0)
@@ -856,12 +912,14 @@ class ChannelManager:
StreamDeltaEvent | StreamEndEvent | StreamedResponseEvent,
)
):
if self._should_suppress_outbound(msg):
if msg.delivery_id is None and self._should_suppress_outbound(msg):
logger.info("Suppressing duplicate outbound message to {}:{}", msg.channel, msg.chat_id)
continue
await self._queue_outbound(channel, msg)
else:
logger.warning("Unknown channel: {}", msg.channel)
if msg.delivery_id is not None:
self._outbox.finish(msg, "failed", "channel_disabled")
except asyncio.TimeoutError:
continue
@@ -1043,7 +1101,7 @@ class ChannelManager:
except asyncio.CancelledError:
raise # Propagate cancellation for graceful shutdown
except Exception as e:
if not channel.should_retry_send_error(e):
if isinstance(e, DeliveryRejectedError) or not channel.should_retry_send_error(e):
logger.error(
"Send to {} failed with a non-retryable {}: {}",
msg.channel,
+2 -1
View File
@@ -58,6 +58,7 @@ except ImportError as e:
"Matrix dependencies not installed. Run: nanobot plugins enable matrix"
) from e
from nanobot.bus.delivery import ChannelNotReadyError
from nanobot.bus.events import OutboundMessage
from nanobot.bus.outbound_events import ProgressEvent
from nanobot.bus.queue import MessageBus
@@ -621,7 +622,7 @@ class MatrixChannel(BaseChannel):
):
return
if not self.client:
raise RuntimeError("Matrix client not initialized")
raise ChannelNotReadyError("Matrix client not initialized")
text = msg.content or ""
candidates = self._collect_outbound_media_candidates(msg.media)
relates_to = self._build_outbound_relates_to(msg.metadata)
+2 -2
View File
@@ -11,6 +11,7 @@ from typing import Any, cast
import httpx
from pydantic import Field, model_validator
from nanobot.bus.delivery import ChannelNotReadyError
from nanobot.bus.events import OutboundMessage
from nanobot.bus.outbound_events import ProgressEvent
from nanobot.bus.queue import MessageBus
@@ -499,8 +500,7 @@ class MattermostChannel(BaseChannel):
):
return
if not self._http_client:
self.logger.warning("client not initialized")
return
raise ChannelNotReadyError("Mattermost client not initialized")
try:
chat_id = msg.chat_id
+3 -4
View File
@@ -15,6 +15,7 @@ from typing import Any, cast
import httpx
from pydantic import Field
from nanobot.bus.delivery import DeliveryRejectedError
from nanobot.bus.events import OutboundMessage
from nanobot.bus.queue import MessageBus
from nanobot.channels.base import BaseChannel
@@ -356,8 +357,7 @@ class MochatChannel(BaseChannel):
):
return
if not self.config.claw_token:
self.logger.warning("claw_token missing, skip send")
return
raise DeliveryRejectedError("MoChat claw_token missing")
parts = ([msg.content.strip()] if msg.content and msg.content.strip() else [])
if msg.media:
@@ -372,8 +372,7 @@ class MochatChannel(BaseChannel):
target = resolve_mochat_target(msg.chat_id)
if not target.id:
self.logger.warning("outbound target is empty")
return
raise DeliveryRejectedError("MoChat outbound target is empty")
is_panel = (target.is_panel or target.id in self._panel_set) and not target.id.startswith("session_")
try:
+2 -1
View File
@@ -35,6 +35,7 @@ except ImportError: # pragma: no cover
import httpx
from pydantic import Field
from nanobot.bus.delivery import ChannelNotReadyError
from nanobot.bus.events import OutboundMessage
from nanobot.bus.queue import MessageBus
from nanobot.channels.base import BaseChannel
@@ -256,7 +257,7 @@ class MSTeamsChannel(BaseChannel):
):
return
if not self._http:
raise RuntimeError("MSTeams HTTP client not initialized")
raise ChannelNotReadyError("MSTeams HTTP client not initialized")
ref = self._conversation_refs.get(str(msg.chat_id))
if not ref:
+2 -1
View File
@@ -19,6 +19,7 @@ from pydantic import Field
from websockets.asyncio.client import ClientConnection
from websockets.asyncio.client import connect as ws_connect
from nanobot.bus.delivery import ChannelNotReadyError
from nanobot.bus.events import OutboundMessage
from nanobot.bus.queue import MessageBus
from nanobot.channels.base import BaseChannel
@@ -443,7 +444,7 @@ class NapcatChannel(BaseChannel):
):
return
if self._ws is None:
raise RuntimeError("napcat: not connected")
raise ChannelNotReadyError("napcat: not connected")
kind, _, target = msg.chat_id.partition(":")
if kind not in ("private", "group") or not target:
+135
View File
@@ -0,0 +1,135 @@
"""Bounded storage for scheduled results; never reruns an agent turn."""
from __future__ import annotations
import json
import os
import sqlite3
import time
import uuid
from collections.abc import Generator
from contextlib import contextmanager
from dataclasses import asdict
from pathlib import Path
from typing import Literal
from loguru import logger
from nanobot.bus.delivery import DeliveryRequest
from nanobot.bus.events import OutboundMessage
DeliveryStatus = Literal["pending", "sending", "sent", "failed", "unknown"]
RETRY_SECONDS = 30
MAX_AGE_SECONDS = 3600
MAX_PENDING = 256
MAX_PAYLOAD_BYTES = 1024 * 1024
RETENTION_SECONDS = 7 * 86400
class DeliveryOutbox:
"""One gateway lease owns this instance store. Terminal rows contain no message text."""
def __init__(self, path: Path) -> None:
self.path = path
self._initialized = False
@contextmanager
def _connect(self) -> Generator[sqlite3.Connection, None, None]:
self.path.parent.mkdir(parents=True, exist_ok=True, mode=0o700)
fd = os.open(self.path, os.O_CREAT | os.O_RDWR, 0o600)
os.close(fd)
db = sqlite3.connect(self.path)
db.row_factory = sqlite3.Row
try:
with db:
if not self._initialized:
db.execute("""CREATE TABLE IF NOT EXISTS deliveries (
id TEXT PRIMARY KEY, run_id TEXT NOT NULL, channel TEXT NOT NULL,
payload TEXT, status TEXT NOT NULL, created REAL NOT NULL,
updated REAL NOT NULL, next_attempt REAL NOT NULL, error TEXT
)""")
# A crash during send cannot tell us whether the service accepted it.
db.execute("""UPDATE deliveries SET status='unknown', payload=NULL,
error='interrupted_send', updated=? WHERE status='sending'""", (time.time(),))
yield db
self._initialized = True
finally:
db.close()
def record(self, msg: OutboundMessage) -> None:
"""Commit before queue acceptance. Do not store runtime events or empty replies."""
if msg.delivery is None or msg.event is not None or not (msg.content.strip() or msg.media):
return
if msg.delivery_id is not None:
return
delivery_id = uuid.uuid4().hex
data = asdict(msg)
data["delivery_id"] = delivery_id
# Cron prompt audit data is already in the run record, not routing context.
data["metadata"] = {key: value for key, value in msg.metadata.items()
if not key.startswith("_cron_")}
payload = json.dumps(data, ensure_ascii=False)
if len(payload.encode("utf-8")) > MAX_PAYLOAD_BYTES:
raise ValueError("Scheduled delivery exceeds the 1 MiB queue limit")
now = time.time()
with self._connect() as db:
self._prune(db, now)
count = db.execute(
"SELECT count(*) FROM deliveries WHERE status IN ('pending','sending')",
).fetchone()[0]
if count >= MAX_PENDING:
raise RuntimeError("Scheduled delivery queue is full; check channel connectivity")
db.execute("INSERT INTO deliveries VALUES (?, ?, ?, ?, 'pending', ?, ?, ?, NULL)",
(delivery_id, msg.delivery.run_id, msg.channel, payload, now, now, now))
msg.delivery_id = delivery_id
self._log(msg, "pending")
@staticmethod
def _prune(db: sqlite3.Connection, now: float) -> None:
db.execute("""UPDATE deliveries SET status='failed', payload=NULL,
error='expired', updated=? WHERE status='pending' AND created<=?""",
(now, now - MAX_AGE_SECONDS))
db.execute("DELETE FROM deliveries WHERE status NOT IN ('pending','sending') AND updated<?",
(now - RETENTION_SECONDS,))
db.execute("""DELETE FROM deliveries WHERE id IN (
SELECT id FROM deliveries WHERE status NOT IN ('pending','sending')
ORDER BY updated DESC LIMIT -1 OFFSET 1000)""")
def ready(self) -> list[OutboundMessage]:
if not self.path.exists():
return []
now = time.time()
with self._connect() as db:
self._prune(db, now)
rows = db.execute("""SELECT payload FROM deliveries WHERE status='pending'
AND next_attempt<=? ORDER BY created LIMIT ?""", (now, MAX_PENDING)).fetchall()
messages: list[OutboundMessage] = []
for row in rows:
data = json.loads(row["payload"])
data["delivery"] = DeliveryRequest(**data["delivery"])
messages.append(OutboundMessage(**data))
return messages
def claim(self, msg: OutboundMessage) -> bool:
"""Only one queued copy may start an attempt; expired messages never start."""
now = time.time()
with self._connect() as db:
self._prune(db, now)
changed = db.execute("""UPDATE deliveries SET status='sending', updated=?
WHERE id=? AND status='pending' AND next_attempt<=?""",
(now, msg.delivery_id, now)).rowcount
return changed == 1
def finish(self, msg: OutboundMessage, status: DeliveryStatus, error: str | None = None) -> None:
now = time.time()
with self._connect() as db:
db.execute("""UPDATE deliveries SET status=?, error=?, updated=?, next_attempt=?,
payload=CASE WHEN ?='pending' THEN payload ELSE NULL END WHERE id=?""",
(status, error, now, now + RETRY_SECONDS, status, msg.delivery_id))
self._log(msg, status, error)
@staticmethod
def _log(msg: OutboundMessage, status: DeliveryStatus, error: str | None = None) -> None:
logger.info("Channel delivery: run={} delivery={} channel={} status={} error={}",
msg.delivery.run_id if msg.delivery else "-", msg.delivery_id,
msg.channel, status, error or "-")
+2 -1
View File
@@ -37,6 +37,7 @@ import aiohttp
from loguru import logger
from pydantic import Field
from nanobot.bus.delivery import ChannelNotReadyError
from nanobot.bus.events import OutboundMessage
from nanobot.bus.outbound_events import ContextCompactionEvent
from nanobot.bus.queue import MessageBus
@@ -437,7 +438,7 @@ class QQChannel(BaseChannel):
try:
if not self._client:
raise RuntimeError("QQ client not initialized")
raise ChannelNotReadyError("QQ client not initialized")
msg_id = msg.metadata.get("message_id")
chat_type = self._chat_type_cache.get(msg.chat_id, "c2c")
+2 -2
View File
@@ -14,6 +14,7 @@ from slack_sdk.socket_mode.response import SocketModeResponse
from slack_sdk.web.async_client import AsyncWebClient
from slackify_markdown import slackify_markdown # pyright: ignore[reportMissingTypeStubs]
from nanobot.bus.delivery import ChannelNotReadyError
from nanobot.bus.events import OutboundMessage
from nanobot.bus.outbound_events import ProgressEvent
from nanobot.bus.queue import MessageBus
@@ -208,8 +209,7 @@ class SlackChannel(BaseChannel):
):
return
if not self._web_client:
self.logger.warning("client not running")
return
raise ChannelNotReadyError("Slack client not running")
try:
web_api = self._require_web_api()
target_chat_id = await self._resolve_target_chat_id(msg.chat_id)
+3 -4
View File
@@ -29,6 +29,7 @@ from telegram.error import BadRequest, InvalidToken, NetworkError, RetryAfter, T
from telegram.ext import Application, CallbackQueryHandler, ContextTypes, MessageHandler, filters
from telegram.request import BaseRequest, HTTPXRequest
from nanobot.bus.delivery import ChannelNotReadyError, DeliveryRejectedError
from nanobot.bus.events import OutboundMessage
from nanobot.bus.outbound_events import ProgressEvent
from nanobot.bus.queue import MessageBus
@@ -1074,8 +1075,7 @@ class TelegramChannel(BaseChannel):
return
app = await self._wait_for_app()
if app is None:
self.logger.warning("bot not running")
return
raise ChannelNotReadyError("Telegram bot not running")
progress_event = msg.event if isinstance(msg.event, ProgressEvent) else None
@@ -1089,8 +1089,7 @@ class TelegramChannel(BaseChannel):
try:
chat_id = int(msg.chat_id)
except ValueError:
self.logger.exception("Invalid chat_id: {}", msg.chat_id)
return
raise DeliveryRejectedError("Invalid Telegram chat_id") from None
reply_to_message_id = msg.metadata.get("message_id")
message_thread_id = msg.metadata.get("message_thread_id")
if message_thread_id is None and reply_to_message_id is not None:
+2 -1
View File
@@ -12,6 +12,7 @@ from typing import Any, cast
from pydantic import Field
from nanobot.bus.delivery import ChannelNotReadyError
from nanobot.bus.events import OutboundMessage
from nanobot.bus.outbound_events import ProgressEvent
from nanobot.bus.queue import MessageBus
@@ -416,7 +417,7 @@ class WecomChannel(BaseChannel):
):
return
if not self._client:
raise RuntimeError("WeCom client not initialized")
raise ChannelNotReadyError("WeCom client not initialized")
try:
content = (msg.content or "").strip()
+2 -1
View File
@@ -31,6 +31,7 @@ from loguru import logger
from pydantic import Field, model_validator
from nanobot import __version__
from nanobot.bus.delivery import ChannelNotReadyError
from nanobot.bus.events import OutboundMessage
from nanobot.bus.outbound_events import ProgressEvent
from nanobot.bus.queue import MessageBus
@@ -1871,7 +1872,7 @@ class WeixinChannel(BaseChannel):
):
return
if not self._client or not self._token:
raise RuntimeError("WeChat client not initialized or not authenticated")
raise ChannelNotReadyError("WeChat client not initialized or not authenticated")
self._assert_session_active()
delivery_id = self._delivery_id(msg)
+2 -1
View File
@@ -18,6 +18,7 @@ from urllib.parse import urlparse
import httpx
from pydantic import Field
from nanobot.bus.delivery import ChannelNotReadyError
from nanobot.bus.events import OutboundMessage
from nanobot.bus.queue import MessageBus
from nanobot.channels.base import BaseChannel
@@ -466,7 +467,7 @@ class WhatsAppChannel(BaseChannel):
return
client = self._client
if client is None or not self._connected:
raise RuntimeError("WhatsApp channel is not connected")
raise ChannelNotReadyError("WhatsApp channel is not connected")
to = self._build_jid(msg.chat_id)
if msg.content:
+2
View File
@@ -8,6 +8,7 @@ import time
import uuid
from typing import Any, Protocol
from nanobot.bus.delivery import DELIVERY_RUN_META
from nanobot.bus.events import InboundMessage, OutboundMessage
from nanobot.cron.session_delivery import origin_delivery_context
from nanobot.cron.session_turns import CRON_DEFER_UNTIL_IDLE_META, CRON_TRIGGER_META
@@ -89,6 +90,7 @@ async def run_bound_cron_job(
),
}
metadata[CRON_DEFER_UNTIL_IDLE_META] = True
metadata[DELIVERY_RUN_META] = run_id
run_record_base: dict[str, Any] = {
"job_id": job.id,
"job_name": job.name,
+220
View File
@@ -0,0 +1,220 @@
"""Exercise scheduled delivery through the real gateway pipeline, without external sends."""
import asyncio
import json
import sqlite3
from functools import partial
from unittest.mock import AsyncMock, MagicMock
import pytest
from nanobot.agent.loop import AgentLoop
from nanobot.agent.tools.context import RequestContext, request_context
from nanobot.agent.tools.message import MessageTool
from nanobot.bus.delivery import DELIVERY_RUN_META, ChannelNotReadyError, DeliveryRequest
from nanobot.bus.events import OutboundMessage
from nanobot.bus.outbound_events import ProgressEvent
from nanobot.bus.queue import MessageBus
from nanobot.channels import outbox as outbox_module
from nanobot.channels.base import BaseChannel
from nanobot.channels.manager import ChannelManager
from nanobot.channels.outbox import DeliveryOutbox
from nanobot.channels.whatsapp.runtime import WhatsAppChannel
from nanobot.config.schema import Config
from nanobot.cron.bound_runner import run_bound_cron_job
from nanobot.cron.service import CronService
from nanobot.cron.types import CronSchedule
from nanobot.providers.base import GenerationSettings, LLMResponse, ToolCallRequest
from nanobot.session.manager import SessionManager
def rows(outbox):
with sqlite3.connect(outbox.path) as db:
db.row_factory = sqlite3.Row
return [dict(row) for row in db.execute("SELECT * FROM deliveries ORDER BY created")]
def make_manager(tmp_path, sessions=None):
config = Config.model_validate({"channels": {
"websocket": {"enabled": False}, "sendProgress": False, "sendToolHints": False,
}})
bus = MessageBus()
manager = ChannelManager(config, bus, config_path=tmp_path / "config.json", session_manager=sessions)
return manager
def message(channel="whatsapp", content="result", generation=None):
return OutboundMessage(channel, "synthetic", content,
delivery=DeliveryRequest("run-1", "whatsapp:synthetic", generation))
async def drain(manager):
async with asyncio.timeout(5):
while manager.bus.outbound_size or manager._outbound_tasks:
await asyncio.sleep(0.01)
@pytest.mark.parametrize("legacy_message", [False, True])
async def test_cron_offline_restart_and_reconnect_do_not_rerun_model(tmp_path, monkeypatch, legacy_message):
monkeypatch.setattr(outbox_module, "RETRY_SECONDS", 0)
workspace = tmp_path / "workspace"
workspace.mkdir()
sessions = SessionManager(workspace, sessions_root=tmp_path / "sessions")
manager = make_manager(tmp_path, sessions)
bus = manager.bus
cron = CronService(tmp_path / "cron" / "jobs.json")
provider = MagicMock(aclose=AsyncMock())
provider.get_default_model.return_value = "offline-test-model"
provider.generation = GenerationSettings(max_tokens=100)
provider.can_resume_conversation_state.return_value = False
provider.estimate_prompt_tokens.return_value = (100, "test")
calls = []
async def reply(**kwargs):
calls.append(kwargs)
if legacy_message and len(calls) == 1:
return LLMResponse(content=None, tool_calls=[ToolCallRequest(
id="send", name="message", arguments={"content": "Diagnostic result"},
)], finish_reason="tool_calls")
return LLMResponse(content="Diagnostic result")
provider.chat_stream_with_retry = reply
agent = AgentLoop(bus=bus, provider=provider, workspace=workspace,
model="offline-test-model", session_manager=sessions,
tools_config=manager.config.tools, cron_service=cron)
cron.on_job = partial(run_bound_cron_job, agent=agent, cron=cron)
channel = WhatsAppChannel({}, bus)
channel.send_progress = False
channel.send_tool_hints = False
channel._client = MagicMock(send_message=AsyncMock())
channel._connected = False
monkeypatch.setattr(channel, "_build_jid", lambda value: value)
monkeypatch.setattr(channel, "stop", AsyncMock())
manager.channels["whatsapp"] = channel
manager._dispatch_task = asyncio.create_task(manager._dispatch_outbound())
# Legacy channel/to fields still normalize through the existing binding migration.
job = cron.add_job("Reminder", CronSchedule(kind="every", every_ms=86400000),
"Use message to send Diagnostic result" if legacy_message else "Return Diagnostic result",
deliver=True, channel="whatsapp", to="synthetic")
try:
assert await asyncio.wait_for(cron.run_job(job.id), 15)
await drain(manager)
assert cron.list_jobs()[0].state.last_status == "ok"
assert len(rows(manager._outbox)) == 1
assert rows(manager._outbox)[0]["status"] == "pending"
channel._client.send_message.assert_not_called()
count = len(calls)
assert count == (2 if legacy_message else 1)
assert DELIVERY_RUN_META not in json.dumps(calls[0]["messages"])
assert "Diagnostic result" not in calls[0]["messages"][0]["content"]
await manager.stop_all()
# A second gateway uses the saved result; no timer, agent, or model is restarted.
manager = make_manager(tmp_path, sessions)
manager.channels["whatsapp"] = channel
channel._connected = True
await manager._recover_scheduled()
await drain(manager)
channel._client.send_message.assert_awaited_once_with("synthetic", "Diagnostic result")
assert rows(manager._outbox)[0]["status"] == "sent"
assert rows(manager._outbox)[0]["payload"] is None
again = make_manager(tmp_path, sessions)
again.channels["whatsapp"] = channel
await again._recover_scheduled()
assert channel._client.send_message.await_count == 1
assert len(calls) == count
# Existing jobs still load after delivery state is added beside them.
assert CronService(cron.store_path).list_jobs()[0].payload.message == job.payload.message
finally:
await manager.stop_all()
cron.stop()
await agent.aclose()
@pytest.mark.parametrize("failure", [TimeoutError("response lost"), asyncio.CancelledError()])
async def test_uncertain_attempt_is_not_replayed(tmp_path, failure):
manager = make_manager(tmp_path)
channel = MagicMock(spec=BaseChannel)
channel.send = AsyncMock(side_effect=failure)
msg = message()
await manager.bus.publish_outbound(msg)
if isinstance(failure, asyncio.CancelledError):
with pytest.raises(asyncio.CancelledError):
await manager._send_scheduled(channel, msg)
else:
await manager._send_scheduled(channel, msg)
assert rows(manager._outbox)[0]["status"] == "unknown"
assert DeliveryOutbox(manager._outbox.path).ready() == []
channel.send.assert_awaited_once()
async def test_legacy_broadcast_has_independent_targets_and_no_foreign_thread_metadata(tmp_path, monkeypatch):
monkeypatch.setattr(outbox_module, "RETRY_SECONDS", 0)
manager = make_manager(tmp_path)
tool = MessageTool(send_callback=manager.bus.publish_outbound, workspace=tmp_path)
with request_context(RequestContext(
"telegram", "source", session_key="telegram:source", metadata={
DELIVERY_RUN_META: "run-1", "message_thread_id": 42, "message_id": "parent",
},
)):
for channel in ("slack", "whatsapp"):
assert str(await tool.execute(content="result", channel=channel, chat_id="target")).startswith("Message queued")
messages = [manager.bus.outbound.get_nowait() for _ in range(2)]
assert all(msg.metadata == {} for msg in messages)
assert len({msg.delivery_id for msg in messages}) == 2
healthy = MagicMock(spec=BaseChannel, send=AsyncMock())
offline = MagicMock(spec=BaseChannel, send=AsyncMock(side_effect=ChannelNotReadyError()))
await manager._send_scheduled(healthy, messages[0])
await manager._send_scheduled(offline, messages[1])
assert [row["status"] for row in rows(manager._outbox)] == ["sent", "pending"]
assert [msg.channel for msg in manager._outbox.ready()] == ["whatsapp"]
async def test_queue_acceptance_survives_restart_but_inflight_is_unknown(tmp_path):
manager = make_manager(tmp_path)
pending, inflight = message(), message(content="second")
await manager.bus.publish_outbound(pending)
await manager.bus.publish_outbound(inflight)
assert manager._outbox.claim(inflight)
restarted = DeliveryOutbox(manager._outbox.path)
assert [msg.delivery_id for msg in restarted.ready()] == [pending.delivery_id]
assert [row["status"] for row in rows(restarted)] == ["pending", "unknown"]
async def test_queue_bounds_expiry_and_untracked_events(tmp_path, monkeypatch):
manager = make_manager(tmp_path)
monkeypatch.setattr(outbox_module, "MAX_PENDING", 1)
event = message()
event.event = ProgressEvent(tool_hint=True)
await manager.bus.publish_outbound(event)
await manager.bus.publish_outbound(OutboundMessage("slack", "synthetic", "ordinary reply"))
assert not manager._outbox.path.exists()
first = message()
await manager.bus.publish_outbound(first)
with pytest.raises(RuntimeError, match="queue is full"):
await manager.bus.publish_outbound(message(content="second"))
with pytest.raises(ValueError, match="1 MiB"):
await manager.bus.publish_outbound(message(content="a" * (1024 * 1024)))
monkeypatch.setattr(outbox_module, "MAX_AGE_SECONDS", 0)
assert manager._outbox.ready() == []
assert rows(manager._outbox)[0]["error"] == "expired"
assert not manager._outbox.claim(first)
assert manager._outbox.path.stat().st_mode & 0o777 == 0o600
@pytest.mark.parametrize("operation", ["delete", "reset"])
async def test_pending_result_cannot_send_after_source_session_is_replaced(tmp_path, operation):
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)
channel = MagicMock(spec=BaseChannel, send=AsyncMock())
msg = message(generation=session.generation)
try:
await manager.bus.publish_outbound(msg)
await getattr(sessions.state, operation)(session.key)
await manager._send_scheduled(channel, msg)
channel.send.assert_not_called()
assert rows(manager._outbox)[0]["error"] == "session_replaced"
finally:
await sessions.state.aclose()