fix(plugins): deliver scheduled reminders with an explicit installation binding (#2912)

ai-source-v2 finding F1 for langbot-team/ScheNotify 0.2.7: the detached
scheduler wrapped its whole lifetime in bind_invocation, so a reminder fired
after the scheduling call ended still ran under a freshly created, active
invocation - authority re-established outside the SDK's invocation lifetime.

Each delivery now passes the immutable installation binding as the explicit
action_context of the Host action. call_action resolves and validates that
context against the connection binding (Workspace, installation, revision and
artifact), so the Host - not the plugin - decides whether this installation may
still act, a superseded revision or detached installation is refused, and the
loop needs neither an invocation nor a configuration snapshot. The manifest and
permissions are unchanged: delivery is still the bot.message.send capability.

Co-authored-by: multica-agent <[email protected]>
This commit is contained in:
RockChinQ
2026-11-06 16:53:59 +08:00
committed by GitHub
co-authored by multica-agent
parent a814616204
commit f66adde797
2 changed files with 109 additions and 67 deletions
+64 -47
View File
@@ -12,12 +12,9 @@ from typing import Any
from zoneinfo import ZoneInfo, ZoneInfoNotFoundError
from langbot_plugin.api.definition.plugin import BasePlugin
from langbot_plugin.entities.io.actions.enums import PluginToRuntimeAction
from langbot_plugin.api.entities.builtin.platform import message as platform_message
from langbot_plugin.api.proxies.invocation import (
bind_invocation,
current_binding,
current_config,
)
from langbot_plugin.api.proxies.invocation import current_binding
logger = logging.getLogger(__name__)
@@ -216,16 +213,14 @@ class ScheNotify(BasePlugin):
def _ensure_loop(self, scope: str) -> None:
"""Start (or refresh) the scheduler of the invoking installation.
The invocation's handler, config and binding are captured here: the
detached loop re-enters them at fire time so every Host send stays
attributable to the installation that scheduled the reminder. A worker
upgrade keeps the scope token (the revision is excluded from it) but
presents a new binding, so the loop is restarted under the new authority
instead of sending with the superseded revision.
The loop captures no invocation: a reminder is delivered through the
installation-authorized ``bot.message.send`` Workspace operation, which
the Host authorizes from the installation grant and revokes with it. A
worker upgrade keeps the scope token (the revision is excluded from it)
but presents a new binding, so the loop is restarted for the new
revision instead of outliving it.
"""
handler = getattr(self, "plugin_runtime_handler", None)
config = current_config(handler)
binding = current_binding(handler)
binding = current_binding(getattr(self, "plugin_runtime_handler", None))
task = self._loops.get(scope)
if task is not None and not task.done():
@@ -233,13 +228,12 @@ class ScheNotify(BasePlugin):
return
task.cancel()
self._loop_bindings[scope] = binding
# Start from an empty context: ``create_task`` would otherwise copy the
# scheduling invocation's task-local state, including the SDK's audit
# correlation, which is closed once that invocation returns and makes
# every later send fail with "Plugin audit invocation has ended". The
# loop re-enters the captured invocation itself.
# Start from an empty Context: the scheduling invocation's task-local
# state is closed once that call returns, and the loop must not inherit
# it. What the loop keeps is the immutable installation binding, which
# the Host validates against the live connection on every delivery.
self._loops[scope] = asyncio.create_task(
self._check_loop_wrapper(scope, handler, config, binding),
self._check_loop_wrapper(scope, binding),
context=contextvars.Context(),
)
@@ -260,27 +254,26 @@ class ScheNotify(BasePlugin):
# ------------------------------------------------------------------ #
# Scheduler
# ------------------------------------------------------------------ #
async def _check_loop_wrapper(self, scope: str, handler: Any, config: Any, binding: Any):
"""Check one installation's due events until that binding is revoked.
async def _check_loop_wrapper(self, scope: str, binding: Any = None):
"""Check one installation's due events until that installation is revoked.
A detached task keeps no usable invocation of its own — the invocation
that started it has ended and is marked inactive. It therefore re-enters
the handler, config and binding captured when it started, so every send
this loop makes carries the scheduling installation's authority instead
of falling back to the worker's connection default. ``on_installation_revoked``
cancels the task, which exits this scope and drops the authority with it.
The loop holds no invocation and no configuration: each delivery passes
the installation binding as the explicit action context, so the Host
validates it (Workspace, installation, revision and artifact) against
the live connection and rejects a superseded or detached installation.
``on_installation_revoked`` cancels the task, so a revoked installation
stops delivering immediately.
"""
with bind_invocation(handler, config=config, binding=binding):
while True:
try:
await self._check_scheduled_events(scope)
except asyncio.CancelledError:
raise
except Exception as e:
logger.error(f"Error in check loop: {e}", exc_info=True)
await asyncio.sleep(CHECK_INTERVAL_SECONDS) # Check every minute
while True:
try:
await self._check_scheduled_events(scope, binding)
except asyncio.CancelledError:
raise
except Exception as e:
logger.error(f"Error in check loop: {type(e).__name__}: {e}")
await asyncio.sleep(CHECK_INTERVAL_SECONDS) # Check every minute
async def _check_scheduled_events(self, scope: str):
async def _check_scheduled_events(self, scope: str, binding: Any = None):
"""Send notifications for this installation's due events."""
# Event times are aware (naive ones are host-local), so the comparison
# needs no config and is independent of the configured timezone.
@@ -299,7 +292,7 @@ class ScheNotify(BasePlugin):
if now >= to_timezone(event["time"], datetime.timezone.utc):
# Send notification
try:
await self._send_notification(event)
await self._send_notification(event, binding)
except asyncio.CancelledError:
raise
except Exception as e:
@@ -318,24 +311,48 @@ class ScheNotify(BasePlugin):
delivered = set(delivered_ids)
events[:] = [event for event in events if event["id"] not in delivered]
async def _send_notification(self, event: dict[str, Any]):
async def _send_notification(self, event: dict[str, Any], binding: Any = None):
"""
Send notification message to the session.
The delivery is an ordinary Host action carrying the installation
binding as its explicit action context: the Host validates that context
against the live connection (Workspace, installation, revision and
artifact) and applies the installation's granted capabilities, so no
invocation is invented for the background task and a detached or
upgraded installation cannot be used to deliver.
Args:
event: Event dict containing session info and message
binding: Installation binding captured when the reminder was created
"""
message_chain = platform_message.MessageChain([
platform_message.Plain(text=f"{NOTIFY_PREFIX}{event['message']}")
])
payload = {
"bot_uuid": event["bot_uuid"],
"target_type": event["target_type"],
"target_id": event["target_id"],
"message_chain": message_chain.model_dump(),
}
# Send message using saved session info. Failures propagate so the
# scheduler can keep the event queued and record the failed attempt.
await self.send_message(
bot_uuid=event["bot_uuid"],
target_type=event["target_type"],
target_id=event["target_id"],
message_chain=message_chain
if binding is None:
# A dedicated worker's invocation carries no binding; the connection
# itself is the installation, so the task-local context is correct.
await self.send_message(
bot_uuid=payload["bot_uuid"],
target_type=payload["target_type"],
target_id=payload["target_id"],
message_chain=message_chain,
)
return
# Failures propagate so the scheduler keeps the event queued.
await self.plugin_runtime_handler.call_action(
PluginToRuntimeAction.SEND_MESSAGE,
payload,
timeout=180.0,
action_context=binding,
)
async def add_scheduled_event(
@@ -15,10 +15,11 @@ released nothing because nothing was keyed by an installation.
Second-round findings, also asserted below:
* the detached scheduler ran in a fresh empty context and never re-established
the scheduling installation's invocation, so the Host saw ``None`` as the
binding of a relay that carried tenant data
(``test_detached_send_runs_under_the_captured_installation_binding``);
* the detached scheduler first ran with no authority at all, then re-created one
with ``bind_invocation`` for the whole loop; certification review rejected
re-establishing an ended call's authority, so each delivery now passes the
installation binding as the explicit action context
(``test_detached_delivery_carries_the_installation_binding``);
* lookups deleted/listed by ``target_id`` alone, so another bot of the same
installation, or the other namespace with the same id, was treated as the same
session (``test_schedule_commands_do_not_reach_another_session`` and
@@ -43,6 +44,8 @@ import sys
from pathlib import Path
from types import SimpleNamespace
import pytest
from langbot_plugin.api.entities.builtin.command.context import ExecuteContext
from langbot_plugin.api.entities.builtin.provider.session import LauncherTypes, Session
from langbot_plugin.api.proxies.invocation import bind_invocation, current_binding
@@ -69,18 +72,31 @@ sche_main = _load_main()
class FlatHost:
"""Stub Host that records notification relays (no live platform call)."""
"""Stub Host that records deliveries (no live platform call).
Deliveries arrive as ``bot.message.send`` Workspace operations. The Host
authorizes those from the installation grant, so no invocation context is
involved; ``binding_seen`` records what the Context held at delivery time so
a test can prove the scheduler fabricated none.
"""
def __init__(self, *, fail_sends: int = 0, on_send=None):
self.sent: list[dict] = []
# Binding the relay was made under, as the real Host would resolve it.
self.authorities: list = []
# Explicit action context each delivery carried.
self.action_contexts: list = []
# Context binding at delivery time: must stay None (no fake invocation).
self.binding_seen: list = []
self.fail_sends = fail_sends
self.on_send = on_send
async def call_action(self, action, data, *args, **kwargs):
if action == Action.SEND_MESSAGE:
self.authorities.append(current_binding(self))
# ``action_context`` is the explicit installation authority the Host
# validates against the live connection; ``current_binding`` is the
# task-local invocation, which must stay absent for a background
# delivery.
self.action_contexts.append(kwargs.get("action_context"))
self.binding_seen.append(current_binding(self))
if self.fail_sends > 0:
self.fail_sends -= 1
raise RuntimeError("host refused the send")
@@ -121,12 +137,14 @@ def build_plugin(**host_kwargs):
def _texts(payloads: list[dict]) -> list[str]:
"""Plain text of each delivered ``message_chain_data`` argument list."""
texts = []
for payload in payloads:
chain = payload.get("message_chain_data") or payload.get("message_chain") or []
texts.append(
"".join(
part.get("text", "")
for part in payload["message_chain"]
for part in chain
if part.get("type") == "Plain"
)
)
@@ -177,7 +195,7 @@ def test_scheduler_is_registered_per_binding_and_stopped_on_revocation():
first, second = binding("installation-a"), binding("installation-b")
started: list[str] = []
async def fake_loop(scope, *_authority):
async def fake_loop(scope, *_extra):
started.append(scope)
await asyncio.sleep(3600)
@@ -258,7 +276,7 @@ def test_dedicated_binding_less_invocation_still_schedules():
plugin, host = build_plugin()
loop_scopes: list[str] = []
async def fake_loop(scope, *_authority):
async def fake_loop(scope, *_extra):
loop_scopes.append(scope)
await asyncio.sleep(3600)
@@ -300,13 +318,15 @@ async def _render(component, context) -> list[str]:
return [ret.text async for ret in component._execute(context)]
def test_detached_send_runs_under_the_captured_installation_binding():
"""The background relay carries the scheduling installation's authority.
def test_detached_delivery_carries_the_installation_binding():
"""A background delivery fabricates no invocation and names its authority.
Pre-fix the scheduler started its task in a fresh ``contextvars.Context()``
and never re-entered an invocation, so the Host resolved the relay's binding
to ``None`` (``host.authorities`` was ``[None]``) although the payload
carried the tenant's reminder text and target.
The scheduling call has ended by the time the reminder fires, so the loop
must not re-establish that call's authority (the previous
``bind_invocation`` in the loop did exactly that). It passes the immutable
installation binding as the explicit action context instead: the Host
validates it against the live connection on every delivery, so a detached
or upgraded installation cannot be used to send.
"""
async def scenario():
@@ -325,10 +345,12 @@ def test_detached_send_runs_under_the_captured_installation_binding():
await asyncio.sleep(0.01)
assert _texts(host.sent) == ["[Notify] A reminder"]
assert host.authorities == [first]
# The delivery names the installation it belongs to...
assert host.action_contexts == [first]
# ...and holds no invocation of its own.
assert host.binding_seen == [None]
assert plugin._events[plugin._scope(first)] == []
# The authority belongs to the loop, so revocation withdraws it with it.
await plugin.on_installation_revoked(first)
assert plugin._loops == {}
@@ -487,6 +509,7 @@ def test_failed_delivery_keeps_the_reminder_queued():
pending = plugin._events[scope]
assert [e["message"] for e in pending] == ["A reminder"]
assert pending[0]["failed_attempts"] == 1
# The queued failure records the Host error, never tenant data.
assert pending[0]["last_error"] == "host refused the send"
# The next pass retries the still-pending reminder and delivers it.
@@ -625,7 +648,9 @@ def test_worker_upgrade_restarts_the_loop_under_the_new_binding():
break
await asyncio.sleep(0.01)
assert _texts(host.sent) == ["[Notify] new revision"]
assert host.authorities == [revised]
# Deliveries carry no fabricated invocation, only the new binding.
assert host.binding_seen == [None]
assert host.action_contexts[-1] == revised
await plugin.on_installation_revoked(revised)