Repository navigation
fix(relay): a relayed Discord interaction carries the text lane's chat and user labels #128797
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. Weβll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Changes from 5 commits
40322be
cd581c7
6aad417
0f3aa86
fa9259f
10b955a
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -148,6 +148,11 @@ def __init__( | |
| self._auto_thread_waiters: Dict[str, asyncio.Event] = {} | ||
| # Bounded FIFO seen-set for inbound replay dedupe (insertion-ordered dict). | ||
| self._seen_inbound: Dict[str, None] = {} | ||
| # Discord chat labels the text lane carries (connector-resolved) and a forwarded interaction | ||
| # does not: (scope, chat) -> (chat_name, chat_topic). The second map is what the session | ||
| # store is known to hold, so a label costs a write only when it is new or changed. | ||
| self._discord_chat_labels: Dict[tuple, tuple] = {} | ||
| self._discord_labels_recorded: Dict[tuple, tuple] = {} | ||
| # Live cards: draft_key -> draft_id of the OPEN native stream. Armed by | ||
| # send_draft; consumed by send() to convert the turn-final into | ||
| # draft(final=true) instead of a duplicate post. Keyed by _draft_key (chat + | ||
|
|
@@ -882,6 +887,7 @@ async def _on_inbound(self, event) -> None: | |
| self._seen_inbound[dedupe_key] = None | ||
| self._evict_oldest(self._seen_inbound, self._SEEN_INBOUND_MAX) | ||
| self._capture_scope(event) | ||
| await self._remember_discord_labels(event.source) | ||
| self._stamp_slack_session_thread(event) | ||
| # A structured prompt answer resolves its waiting primitive and is CONSUMED β | ||
| # never also dispatched as chat. | ||
|
|
@@ -891,6 +897,56 @@ async def _on_inbound(self, event) -> None: | |
| await self.handle_message(event) | ||
|
|
||
| _SEEN_INBOUND_MAX = 512 | ||
| _DISCORD_LABELS_MAX = 2048 | ||
|
Collaborator
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Nit: 2048 per map is generous but cheap (a tuple of two short strings). The only behavioral cost of a miss is one extra re-render on the first interaction after eviction/restart, which is the same as today. No change requested. |
||
|
|
||
| async def _remember_discord_labels(self, source) -> None: | ||
| """Keep the text lane's Discord chat labels for the interaction lane: the pinned | ||
| session-context prompt renders them, so a slash turn without them re-rendered the cached | ||
| prefix and the next message rendered it back.""" | ||
| if (getattr(source, "platform", None) != Platform.DISCORD or not source.chat_id | ||
| or not (source.chat_name or source.chat_topic)): | ||
| return | ||
| key, labels = (str(source.scope_id or ""), str(source.chat_id)), (source.chat_name, source.chat_topic) | ||
| self._discord_chat_labels[key] = labels | ||
| self._evict_oldest(self._discord_chat_labels, self._DISCORD_LABELS_MAX) | ||
| store = getattr(self, "_session_store", None) | ||
| if store is None or self._discord_labels_recorded.get(key) == labels: | ||
| return | ||
| # Recorded when observed, so the interaction lane has them after a restart whatever order | ||
| # the chat's sessions were created or reset in. Awaited before dispatch (the reader delivers | ||
| # events one at a time, so records land in observation order) but off the loop: it is a | ||
| # disk write. | ||
| try: | ||
| await asyncio.to_thread(store.record_chat_labels, source) | ||
| except Exception: | ||
| # Not recorded: leave the key out so the next message tries again. | ||
| logger.debug("relay: Discord chat labels not recorded", exc_info=True) | ||
| self._discord_labels_recorded.pop(key, None) | ||
| return | ||
| self._discord_labels_recorded[key] = labels | ||
| self._evict_oldest(self._discord_labels_recorded, self._DISCORD_LABELS_MAX) | ||
|
|
||
| def _discord_chat_labels_for(self, scope: str, chat_id: str) -> tuple: | ||
| """The text lane's last (chat_name, chat_topic) for a chat. After a restart (or eviction) the | ||
| map is empty until the text lane speaks again, so ask the session store for what that lane | ||
| last recorded; otherwise a first interaction re-renders the prompt the cache still holds.""" | ||
| key = (scope, chat_id) | ||
| if key in self._discord_chat_labels: | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. [P2] Invalidate positive and negative warm caches across peer adapters. Revalidating the existing peer-cache finding: with two adapters sharing a real SessionStore, warm the peer via _on_passthrough, then let the writer observe a new label. The peer keeps the old label, or None if it was warmed before any record existed. Both current-head and full-composition variants fail. Moving cold reads off the loop and making unavailable storage retryable does not invalidate an already populated local entry. Give label observations a shared generation/invalidation mechanism or revalidation policy; preserve both positive and negative controls. The body includes the runnable real-consumer check with inert transport delivery.
Contributor
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. The check still needs two RelayAdapters writing labels into one SessionStore, and the gateway doesn't run that topology. Under multiplex, I'm leaving this unchanged in this PR. If you can show a supported configuration where a second writer exists (for example a native Discord adapter and Relay both recording into the same store), I'll reproduce it and add the invalidation with both controls.
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. [P2] One RelayAdapter is enough to reproduce the generation splitThis new evidence supersedes my earlier withdrawal of the peer-cache finding in the 12:35 UTC current-head follow-up. I withdrew it there because the two-RelayAdapter fixture used a topology the gateway does not configure and, at that point, I had not established another supported writer/generation transition. The live-restore path below supplies exactly that missing reachability evidence. The topology reply is correct that normal multiplex startup does not intentionally create a second RelayAdapter. That is not the only supported way the backing record changes. This cache hit returns the local value without consulting the SessionStore or a store generation. Hermes explicitly supports live state.db restore: So the supported sequence is: observe A β snapshot β same adapter observes B β restore snapshot while the gateway stays live β durable That is the same cache-coherence failure the earlier positive/negative peer probe exposed; the supported live restore supplies the legal generation transition. Bind warm entries to a durable generation/restore epoch, invalidate/revalidate them, or explicitly define and test why live observations intentionally survive restore and how eviction preserves that policy. |
||
| return self._discord_chat_labels[key] | ||
| store = getattr(self, "_session_store", None) | ||
| try: | ||
| recorded = store.chat_labels(Platform.DISCORD, scope, chat_id) if store is not None else None | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. [P2] Keep the cold database read off the event loopMoving Reproduction: record a labelled text event through real Make the cold record lookup asynchronous/off-loop too, before constructing the interaction source. Regress with a real contended store and an independent coroutine that remains responsive. The reproduction uses the real transaction and getter; neither is stubbed. Verified on
Contributor
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Reproduced:
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. [P2] F13 β Cold label reads synchronously wait on the database writer lock on the event loopAttribution: introduced; same-head prior finding retained. The getter reaches SessionDB.get_meta, which deliberately uses the main writer lock, not a WAL read context. A write transaction holds that lock. Since conversion is called synchronously by the async passthrough callback, a cold chat stalls loop progress while waiting. Probe: real stored labels, cold adapter and real _execute_write transaction held on a threading Event. Schedule an independent coroutine heartbeat; release the transaction via a separate 300ms timer. The heartbeat runs only after release at head, while the same assertion passes at the merge base. The transaction/getter are real, not mocked; the hold/release is controlled. A source-bound receipt confirms the expected labels still return and the writer completes without error. Consequence/limit: this establishes where a contended read waits and that unrelated loop work is prevented during it. The hold duration is not a measured production latency or outage. It confirms the earlier cold-read finding. Repair/closure: move the cold read behind an awaited off-loop boundary or an equivalent nonblocking store API before constructing the source. Preserve failure/absence distinctions from F07. Regress a real contended writer plus an independent coroutine, alongside warm-hit and exception-retry controls. A point SELECT is not necessarily nonblocking when obtaining its lock is synchronous. Fresh receipt: state-head-final: cold-read-contention fails; state-base: same responsiveness assertion passes. Head Code under discussion β producer, state owner, and consumers:
Contributor
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Same as the 15:24 inline on line 938. Fixed in |
||
| except Exception: | ||
| # Labels only keep the prompt cache warm; a store fault must not drop the interaction. | ||
| # Not cached either: the next interaction asks the store again. | ||
| logger.debug("relay: recorded Discord chat labels unreadable", exc_info=True) | ||
| return (None, None) | ||
| if recorded is not None: | ||
| self._discord_labels_recorded[key] = recorded | ||
| self._evict_oldest(self._discord_labels_recorded, self._DISCORD_LABELS_MAX) | ||
| self._discord_chat_labels[key] = recorded or (None, None) | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. [P2] Invalidate peer adapters' positive and negative label cachesThis result, including a successful Reproduction: construct two relay adapters A and B over one real SessionStore. A converts an interaction before any observation, memoizing Use a shared observation generation/invalidation owner, or another mechanism that makes a changed authoritative record visible to all adapter readers. Cover both first observation after a successful miss and a rename after a positive hit. Avoid fixing only exception retry: these reads succeeded. Verified on
Contributor
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Not reachable in a supported topology, so not changed. One gateway process runs one
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. [P2] F07 β A recoverable DB-open failure becomes an indefinitely cached absent-label readAttribution: introduced. The guarantee in chat_labels' docstring is not upheld by its missing-handle branch. RecoverableHandleCache intentionally returns None on transient open failure, in-flight retry or backoff. The getter lookup then converts that unavailable state into the same None as an absent record. This assignment caches it. Probe: record labels using real SQLite; replace only the registry opener with a one-failure wrapper and drive the real RecoverableHandleCache with a controlled clock. First cold interaction returns (None,None). Advance beyond backoff; direct store read returns saved labels, and a fresh adapter returns them too. The original adapter still returns (None,None), with exactly two real open attempts overall. In the paired control, a raised getter exception correctly retries on the second interaction. Consequence: storage recovery does not repair this adapter's prompt inputs until another observation, eviction or restart. This is not the documented no-record fallback limitation and does not require multiple adapters. The record API is newly introduced; the base has no equivalent API, so no baseline read-recovery pass is invented. Repair/closure: propagate unavailable/indeterminate read state distinctly from an authoritative missing row and do not memoize it as permanent absence. Test failed open, backoff/in-flight miss, healthy reopen and a second interaction without intervening text, alongside the existing getter-exception case. Fresh receipt: state-head-final: unavailable-read fails; getter-exception control passes; base record API absent. Head Code under discussion β producer, state owner, and consumers:
Contributor
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Reproduced: no handle meant |
||
| self._evict_oldest(self._discord_chat_labels, self._DISCORD_LABELS_MAX) | ||
| return self._discord_chat_labels[key] | ||
|
|
||
| def _inbound_dedupe_key(self, event) -> Optional[str]: | ||
| """Stable replay identity: (platform, chat, platform message id). The platform | ||
|
|
@@ -1170,17 +1226,35 @@ def _discord_interaction_to_event(self, forward): | |
| if not isinstance(user, dict): | ||
| user = {} | ||
| guild_id = payload.get("guild_id") | ||
| # The text lane's user_display_name is the native author.display_name: guild nick, else | ||
| # global name, else username. The interaction carries all three as of now, so derive the | ||
| # same name from it; a remembered one would outlive a nickname change. | ||
| user_name = next( | ||
| (str(v) for v in ((member.get("nick") if isinstance(member, dict) else None), | ||
| user.get("global_name"), user.get("username")) if v), None) | ||
| chat_id = str(payload.get("channel_id") or "") | ||
| chat_name, chat_topic = self._discord_chat_labels_for(str(guild_id or ""), chat_id) | ||
| # The text lane keys a message inside a thread on chat_type "thread" + thread_id (both session-key | ||
| # fields), so an interaction sent there must carry the same or it lands in a per-user "group" | ||
| # session beside the thread's. The partial channel object marks a thread by type (10 announcement, | ||
| # 11 public, 12 private: what discord.py's Thread covers) and names the parent. | ||
| channel = payload.get("channel") if isinstance(payload.get("channel"), dict) else {} | ||
| is_thread = bool(guild_id) and channel.get("type") in (10, 11, 12) | ||
| source = SessionSource( | ||
| # The LOGICAL platform, not RELAY: session keys must match the connector's | ||
| # capability binding (platform="discord"), /sethome must file under the | ||
| # logical platform, and _capture_scope skips the generic "relay". | ||
| platform=Platform.DISCORD, | ||
| chat_id=str(payload.get("channel_id") or ""), | ||
| chat_id=chat_id, | ||
| # "group", not "channel": both the connector's capability binding and the | ||
| # native Discord adapter key guild channels as "group". | ||
| chat_type="group" if guild_id else "dm", | ||
| chat_type="thread" if is_thread else ("group" if guild_id else "dm"), | ||
| thread_id=chat_id if is_thread else None, | ||
| parent_chat_id=str(channel["parent_id"]) if is_thread and channel.get("parent_id") else None, | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. [P2] Preserve a known thread parent when the partial channel omits itThe new thread derivation fixes the session split, but unconditionally loses a known parent when Reproduction: admit and persist a text source with Recover an already-known parent from an authoritative thread source, or resolve it at the boundary, and preserve it consistently across prompt and routing consumers. Add a partial-channel regression with tools enabled; the tools-disabled renderer hides this difference. Parent omission predates this PR's thread repair; it remains part of the class being repaired here. Verified on
Contributor
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Not changed. Discord's channel docs say interactions "always receive full channel data" for channels the app can act on, and |
||
| user_id=str(user["id"]) if user.get("id") else None, | ||
| user_name=str(user["username"]) if user.get("username") else None, | ||
| user_name=user_name, | ||
| chat_name=chat_name, | ||
| chat_topic=chat_topic, | ||
| scope_id=str(guild_id) if guild_id else None, | ||
| message_id=str(payload.get("id")) if payload.get("id") else None, | ||
| # Same upstream-trust marker the relay text lane stamps. Set locally, never | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. [P2] Keep interaction identity separate from actual message identityThis source still uses Reproduction: forward a type-3 component with A second real-wire probe provides a text frame's root Normalize event/source message identity at the boundary and represent the interaction identifier separately. Use the attached actual message for components; slash invocations with no platform message must not invent one. Regress both component identity and root-only text frames with tools enabled. Both probes also fail on the merge base; they require repair but are not new regressions introduced by this PR. Verified on
Contributor
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Confirmed, and older than this PR (same on the merge base). Filed as #130306 with your probes, crediting you. It stays out of this PR on purpose. teknium1's review of #129032 measured what an identity split does to the slash prompt when |
||
|
|
||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -13,7 +13,7 @@ | |
| from utils import atomic_json_write | ||
|
|
||
| if TYPE_CHECKING: | ||
| from gateway.session import SessionEntry | ||
| from gateway.session import SessionEntry, SessionSource | ||
|
|
||
| # Log-record parity with the origin module. | ||
| logger = logging.getLogger("gateway.session") | ||
|
|
@@ -234,6 +234,30 @@ def _routing_db_method(self, name: str): | |
| method = getattr(self._routing_db or None, name, None) | ||
| return method if callable(method) else None | ||
|
|
||
| @staticmethod | ||
| def _chat_labels_meta_key(platform, scope_id, chat_id) -> str: | ||
| return f"gateway_chat_labels:{getattr(platform, 'value', platform)}:{scope_id or ''}:{chat_id}" | ||
|
|
||
| def record_chat_labels(self, source: SessionSource) -> None: | ||
| """Persist *source*'s ``chat_name`` / ``chat_topic`` as the chat's current labels, at the | ||
| moment they are observed. A session origin cannot answer "what is this chat called now": it | ||
| is written when its session is created, which can be after a newer observation (a delayed | ||
| first turn), and a reset inherits it under a fresh ``created_at``.""" | ||
| setter = self._routing_db_method("set_meta") | ||
| if setter is not None: | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. [P2] F08 β A no-op record call is cached as successful persistence and suppresses recovery writesAttribution: introduced. This missing-setter branch has no success indicator. After awaiting it, the adapter marks the labels recorded, and equality suppresses later writes. A temporarily unavailable handle is an intentional supported store state, not an exotic missing method. Probe: fail the registry open once through the real retry cache, admit an ordinary labeled text observation, then inspect the recorded map: it claims the tuple. Recover the handle and directly read the actual store: no row. Admit another unique text message with identical labels: still no row. A fresh adapter sees no labels. Changing the labels then persists successfully, proving healthy storage and isolating false write suppression. In the separate raised-setter control, the second same-label message does retry successfully. Consequence: a transient outage silently becomes persistent absence after recovery, and restart loses labels even though a healthy same-label observation arrived. This is distinct from failing to support permanent JSONL-only operation; the DB was available again. Repair/closure: make committed/no-store/failure results explicit, and populate the recorded cache only on evidence of the write. Preserve retry eligibility across missing handles and backoff. The regression must assert the durable row after an unchanged-label recovery observation, not just warm-cache equality or eventual success after a rename. Fresh receipt: state-head-final: unavailable-write fails; setter-exception control passes; base API absent. Head Code under discussion β producer, state owner, and consumers:
Contributor
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Reproduced, fixed in |
||
| setter(self._chat_labels_meta_key(source.platform, source.scope_id, source.chat_id), | ||
| json.dumps([source.chat_name, source.chat_topic])) | ||
|
|
||
| def chat_labels(self, platform, scope_id, chat_id) -> Optional[tuple]: | ||
| """The ``(chat_name, chat_topic)`` last recorded for a chat, or None when none was. Raises | ||
| when the store cannot be read: "unreadable now" is not "never labelled".""" | ||
| getter = self._routing_db_method("get_meta") | ||
| raw = getter(self._chat_labels_meta_key(platform, scope_id, chat_id)) if getter is not None else None | ||
| if not raw: | ||
| return None | ||
| chat_name, chat_topic = json.loads(raw) | ||
| return chat_name, chat_topic | ||
|
|
||
| def _load_routing_rows_locked(self) -> bool: | ||
| """Load state.db routing entries into ``_entries``; False when there is no loader or the | ||
| load failed (warned). Lock held.""" | ||
|
|
||
| Original file line number | Diff line number | Diff line change | |||||||||||||||||||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| @@ -0,0 +1,140 @@ | |||||||||||||||||||||||||||||
| """A relayed Discord interaction carries the same chat/user labels as a relayed message in that chat. | |||||||||||||||||||||||||||||
|
|
|||||||||||||||||||||||||||||
| The text lane gets ``chat_name``, ``chat_topic`` and ``user_display_name`` from the connector; a | |||||||||||||||||||||||||||||
| forwarded interaction (slash command, component) is the raw Discord body. Both land in one session, | |||||||||||||||||||||||||||||
| and the pinned session-context prompt renders those labels, so a slash turn built without them | |||||||||||||||||||||||||||||
| re-rendered the cached prefix and the next message rendered it back. | |||||||||||||||||||||||||||||
| """ | |||||||||||||||||||||||||||||
|
|
|||||||||||||||||||||||||||||
| import json | |||||||||||||||||||||||||||||
| import threading | |||||||||||||||||||||||||||||
| from unittest.mock import AsyncMock | |||||||||||||||||||||||||||||
|
|
|||||||||||||||||||||||||||||
| import pytest | |||||||||||||||||||||||||||||
|
|
|||||||||||||||||||||||||||||
| import gateway.run as gateway_run | |||||||||||||||||||||||||||||
| from gateway.config import GatewayConfig, Platform, PlatformConfig | |||||||||||||||||||||||||||||
| from gateway.relay.ws_transport import _event_from_wire | |||||||||||||||||||||||||||||
| from gateway.session import SessionStore, build_session_context, build_session_key | |||||||||||||||||||||||||||||
| from tests.gateway.relay.test_relay_interactive import _adapter | |||||||||||||||||||||||||||||
|
|
|||||||||||||||||||||||||||||
|
|
|||||||||||||||||||||||||||||
| def _forward(**payload): | |||||||||||||||||||||||||||||
| body = {"type": 2, "id": "i1", "channel_id": "ch1", "guild_id": "g1", "data": {"name": "status"}} | |||||||||||||||||||||||||||||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. [P1] F04 β Read-only status consumes first-agent-turn initialization through timestamp-based newnessAttribution: inherited. This /status fixture is converted and rendered, not run through its lifecycle. The real status handler gets or creates the row. The next existing-row lookup updates activity, before created_at == updated_at is used as newness. Probe: real status handler and real SessionStore, with expensive model-route/status-display leaves substituted. After /status then first agent lookup, _hmwa_open_session returns (False, False) and emits zero session:start hooks. Direct-first control returns (False, True), emits once. Both head and base reproduce. Driving the real turn-preparation guard with manually supplied auto_skill calls the skill loader in the direct control but not after status; execution stops before the model. Important narrowing: relay text reconstruction and interaction construction do not populate auto_skill. Thus the hook failure is demonstrated; unconditional relayed configured-skill loss is not established by that manually seeded fixture. The earlier issue wording needs that qualification. Repair/closure: represent initialization for an agent/session incarnation separately from last activity. Regress real /status β first text and /status β first model-reaching command, with direct-first and later-turn controls. If relay skill parity is intended, exercise its actual producer separately rather than manufacturing auto_skill in every test. Fresh receipt: lifecycle-parent and lifecycle-base-parent: status_first_turn, manual_skill_guard, auto_skill_wire. Head Code under discussion β producer, state owner, and consumers:
Contributor
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Confirmed by trace: |
|||||||||||||||||||||||||||||
| body.update(payload) | |||||||||||||||||||||||||||||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. [P2] F09 β Context-menu commands are flattened to slash names without their selected targetAttribution: inherited. Outer interaction type 2 is not synonymous with a slash/chat-input command. Discord's application-command data schema distinguishes the inner type and context-menu target_id. The current converter emits only /name and option values; event construction preserves neither target nor resolved message. Probe: a type-2 message command with inner data.type=3, target_id=selected-message-99 and matching resolved content becomes '/summarize', metadata={}, raw_message=None. The target cannot be recovered from the event. The nested slash control becomes '/skill run deploy' with its expected arguments. The merge-base adapter gives the same projection. Consequence/limit: a context-menu request reaching this generic boundary loses what it was invoked on; additionally unknown slash dispatch is not a general substitute for processing that selected message. This does not establish that the external connector currently registers or forwards this command type. Repair/closure: branch by inner command subtype and preserve the resolved target in a defined consumer contract, or explicitly reject unsupported context-menu types. Tests need target-distinct cases, user/message command controls and existing slash/subcommand compatibility. Do not equate a parsed slash string with preserved command intent. Fresh receipt: consumers-isolated: context-menu target assertion fails; exact-base equivalence passes. Head Code under discussion β producer, state owner, and consumers:
Contributor
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Confirmed: a context-menu command arrives as a bare |
|||||||||||||||||||||||||||||
|
|
|||||||||||||||||||||||||||||
| class Forward: | |||||||||||||||||||||||||||||
| platform, method, path = "discord", "POST", "/interactions/bot1" | |||||||||||||||||||||||||||||
|
|
|||||||||||||||||||||||||||||
| Forward.body = json.dumps(body).encode() | |||||||||||||||||||||||||||||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. [P2] F10 β Interaction action IDs are advertised and used as provider message targetsAttribution: inherited. Discord defines payload.id as interaction ID and message.id as the attached message when present. The converter conflates the former with source.message_id, while only hp1 prompt responses retain attached message identity. The new fixture's interaction ID therefore needs consumer assertions, not merely a label assertion. Observed: component id=interaction-1 attached to message=attached-message-77 β real session context exposes HERMES_SESSION_MESSAGE_ID=interaction-1, event.message_id=None. Cached guidance says the triggering message is supplied per-turn, but the event-ID note supplies none. Actual processing lifecycle emits local stub react operations targeting the interaction ID; normal text targets its message ID. Slash without any attached message has the same misleading source target. These behaviors predate the PR. No external reaction API or message disclosure was tested. Repair/closure: represent interaction action identity separately from an actual message target and any reply anchor. Components may have a real attached target; slash interactions may have none. Preserve action identity for F01 without treating it as a reply/react ID. Multiple clicks on one attached message must remain distinct actions. Tests should cover tool context, rendered promise, per-turn note, reactions and persistence owner, not only constructor fields. Fresh receipt: consumers-isolated: component/slash identity assertions fail; lifecycle both pins: reaction_id_kind, delivery_accounting, turn_owner. Head Code under discussion β producer, state owner, and consumers:
Contributor
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Confirmed and older than this PR. Filed as #130306 with F11 and the earlier inline. See the reply on line 1260 for why it stays out of this PR. |
|||||||||||||||||||||||||||||
| return Forward() | |||||||||||||||||||||||||||||
|
|
|||||||||||||||||||||||||||||
|
|
|||||||||||||||||||||||||||||
| def _pinned_prompt(source): | |||||||||||||||||||||||||||||
| runner = object.__new__(gateway_run.GatewayRunner) | |||||||||||||||||||||||||||||
| config = GatewayConfig(platforms={Platform.DISCORD: PlatformConfig(enabled=True, token="x")}) | |||||||||||||||||||||||||||||
| return runner._pinned_session_context_prompt(build_session_context(source, config), False, "k") | |||||||||||||||||||||||||||||
|
|
|||||||||||||||||||||||||||||
|
|
|||||||||||||||||||||||||||||
| def _message(chat, user="u1", chat_name="Hermes Server / #ops", chat_topic="Incident triage"): | |||||||||||||||||||||||||||||
| return _event_from_wire({"text": "hi", "message_type": "text", "source": { | |||||||||||||||||||||||||||||
| "platform": "discord", **chat, "scope_id": "g1", | |||||||||||||||||||||||||||||
| "user_id": user, "user_name": "ben", "user_display_name": "Ben D", | |||||||||||||||||||||||||||||
| "chat_name": chat_name, "chat_topic": chat_topic, "message_id": f"{user}:{chat_name}"}}) | |||||||||||||||||||||||||||||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. [P2] F11 β Root-only text message IDs never reach source-based context consumersAttribution: inherited. Source construction reads only source.message_id, whereas event construction reads the frame's root message_id. This added fixture supplies the nested field every time, so it cannot observe that split. Probe: two accepted text frames with equal chat/user/labels and the same root message_id; only one additionally supplies source.message_id. Both events have text-message-1. The root-only source has None. The actual tools capability gate is enabled with temporary configuration and a synthetic nonfunctional marker, and the pinned renderer returns different guidance because source ID presence is part of the key. Disabling tools makes rendered bytes match, which explains why tools-disabled parity assertions conceal it. The wire decoder is blob-identical at base/head. Consequence/limit: source context and event consumers disagree about a known real message. This is local accepted-wire evidence, not a claim that every connector chooses the root-only representation. Repair/closure: define and enforce event/source message-ID normalization and a conflict policy at the wire boundary. A root-only frame should not lose its known message ID in tool context; equal root/nested forms should converge. Include missing-ID and disagreeing-ID cases without conflating interaction action IDs from F10. Fresh receipt: consumers-isolated: root-only source-ID assertion fails; unchanged base/head decoder blob. Head Code under discussion β producer, state owner, and consumers:
Contributor
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Confirmed in |
|||||||||||||||||||||||||||||
|
|
|||||||||||||||||||||||||||||
|
|
|||||||||||||||||||||||||||||
| @pytest.mark.asyncio | |||||||||||||||||||||||||||||
| @pytest.mark.parametrize("case", [ | |||||||||||||||||||||||||||||
| "warm", "restart", "thread", "rename", "peer-rename", "late-session", "read-retry"]) | |||||||||||||||||||||||||||||
| async def test_slash_between_messages_keeps_one_pinned_prompt(tmp_path, case): | |||||||||||||||||||||||||||||
| """Every case but ``warm`` and ``thread`` restarts the gateway after the last message, so the | |||||||||||||||||||||||||||||
| slash command is the first event the new process sees in that chat; its chat labels are the | |||||||||||||||||||||||||||||
| ones the session store recorded when the text lane carried them. | |||||||||||||||||||||||||||||
| ``thread``: both events happen inside a thread, which the text lane keys on chat_type "thread" + | |||||||||||||||||||||||||||||
| thread_id; the slash command must land in that session, not in a per-user "group" one. | |||||||||||||||||||||||||||||
| ``rename`` / ``peer-rename``: the channel was renamed before the restart. In ``peer-rename`` | |||||||||||||||||||||||||||||
| another user's message carried the new labels and this user's session was reset since: a reset | |||||||||||||||||||||||||||||
| inherits the origin (old labels) under a fresh ``created_at``. | |||||||||||||||||||||||||||||
| ``late-session``: another user's older message, still carrying the old labels, only gets its | |||||||||||||||||||||||||||||
| session after the rename was observed. What the chat is called follows the order the labels | |||||||||||||||||||||||||||||
| were observed in, not the order its sessions were created in. | |||||||||||||||||||||||||||||
| ``read-retry``: the first read after the restart fails. That interaction goes through without | |||||||||||||||||||||||||||||
| labels; the next one asks the store again instead of keeping "no labels".""" | |||||||||||||||||||||||||||||
| config = GatewayConfig(platforms={Platform.DISCORD: PlatformConfig(enabled=True, token="x")}) | |||||||||||||||||||||||||||||
| store = SessionStore(tmp_path, config) | |||||||||||||||||||||||||||||
| adapter, _stub = _adapter(platform="discord") | |||||||||||||||||||||||||||||
| adapter.set_session_store(store) | |||||||||||||||||||||||||||||
| adapter.handle_message = AsyncMock() | |||||||||||||||||||||||||||||
| chat = ({"chat_id": "th1", "chat_type": "thread", "thread_id": "th1", "parent_chat_id": "ch1"} | |||||||||||||||||||||||||||||
| if case == "thread" else {"chat_id": "ch1", "chat_type": "group"}) | |||||||||||||||||||||||||||||
| renamed = {"chat_name": "Hermes Server / #triage", "chat_topic": "Renamed"} | |||||||||||||||||||||||||||||
| db, writers = store._routing_db, [] | |||||||||||||||||||||||||||||
| set_meta = db.set_meta | |||||||||||||||||||||||||||||
|
|
|||||||||||||||||||||||||||||
| def recording(key, value, **kwargs): | |||||||||||||||||||||||||||||
| if key.startswith("gateway_chat_labels:"): | |||||||||||||||||||||||||||||
| writers.append(threading.get_ident()) | |||||||||||||||||||||||||||||
| set_meta(key, value, **kwargs) | |||||||||||||||||||||||||||||
|
|
|||||||||||||||||||||||||||||
| db.set_meta = recording | |||||||||||||||||||||||||||||
|
|
|||||||||||||||||||||||||||||
| async def relay(event): | |||||||||||||||||||||||||||||
| await adapter._on_inbound(event) | |||||||||||||||||||||||||||||
| return store.get_or_create_session(event.source) | |||||||||||||||||||||||||||||
|
|
|||||||||||||||||||||||||||||
| if case == "late-session": | |||||||||||||||||||||||||||||
| late = _message(chat, "u2") | |||||||||||||||||||||||||||||
| await adapter._on_inbound(late) | |||||||||||||||||||||||||||||
| message = _message(chat, **renamed) | |||||||||||||||||||||||||||||
| await relay(message) | |||||||||||||||||||||||||||||
| store.get_or_create_session(late.source) | |||||||||||||||||||||||||||||
| else: | |||||||||||||||||||||||||||||
| if case == "peer-rename": | |||||||||||||||||||||||||||||
| await relay(_message(chat, "u2")) | |||||||||||||||||||||||||||||
| message = _message(chat) | |||||||||||||||||||||||||||||
| entry = await relay(message) | |||||||||||||||||||||||||||||
| if case in ("rename", "peer-rename"): | |||||||||||||||||||||||||||||
| await relay(_message(chat, "u1" if case == "rename" else "u2", **renamed)) | |||||||||||||||||||||||||||||
| message = _message(chat, **renamed) | |||||||||||||||||||||||||||||
| if case == "peer-rename": | |||||||||||||||||||||||||||||
| store.reset_session(entry.session_key) | |||||||||||||||||||||||||||||
| if case not in ("warm", "thread"): | |||||||||||||||||||||||||||||
| store = SessionStore(tmp_path, config) | |||||||||||||||||||||||||||||
| adapter, _stub = _adapter(platform="discord") | |||||||||||||||||||||||||||||
| adapter.set_session_store(store) | |||||||||||||||||||||||||||||
| interaction = {"member": {"nick": "Ben D", "user": {"id": "u1", "username": "ben"}}} | |||||||||||||||||||||||||||||
| if case == "thread": | |||||||||||||||||||||||||||||
| interaction.update(channel_id="th1", channel={"id": "th1", "type": 11, "parent_id": "ch1"}) | |||||||||||||||||||||||||||||
| if case == "read-retry": | |||||||||||||||||||||||||||||
| get_meta, faults = store._routing_db.get_meta, [OSError("database is locked")] | |||||||||||||||||||||||||||||
|
|
|||||||||||||||||||||||||||||
| def flaky(key): | |||||||||||||||||||||||||||||
| if faults: | |||||||||||||||||||||||||||||
| raise faults.pop() | |||||||||||||||||||||||||||||
| return get_meta(key) | |||||||||||||||||||||||||||||
|
|
|||||||||||||||||||||||||||||
| store._routing_db.get_meta = flaky | |||||||||||||||||||||||||||||
| assert adapter._discord_interaction_to_event(_forward(**interaction)).source.chat_name is None | |||||||||||||||||||||||||||||
| slash = adapter._discord_interaction_to_event(_forward(**interaction)) | |||||||||||||||||||||||||||||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. [P1] F05 β Admitted modal submissions lose their user-entered values before the consumerAttribution: inherited. The interaction-kind branch identifies type 5 in its support comment but supplies text only for types 2 and 3. The resulting event carries neither modal data nor raw payload. Discord's modal-submit schema identifies submitted components as the user's values. Probe: registered passthrough callback β real converter with a thread-scoped modal carrying RΓ©sumΓ© and Next week using Label/Text Input components. Dispatch receives text='', raw_message=None and no submitted values, while the thread key is valid. A separate legacy-shaped input with Unicode/empty optional field gives the same loss. Normal command and button controls retain their input. Real inbound preparation returns empty modal input; history reconstruction excludes that empty user row. Both baseline and head share the normalization omission. Consequence/limit: user-authored values are discarded at the local accepted boundary. No model call or provider UI was exercised, so this is not a claim about a particular live bot's modal registration or the final displayed response. Repair/closure: normalize supported modal component trees into a defined, lossless structured/text representation, or explicitly reject/route unsupported modal submissions. Assert multiple values, Unicode, empty optional values and thread identity at the actual consumer, not only source labels. Fresh receipt: consumers-isolated: modal value correctness fails; empty input/replay consequence passes; lifecycle both pins confirm. Head Code under discussion β producer, state owner, and consumers:
Contributor
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Confirmed on the converter: a type-5 body becomes |
|||||||||||||||||||||||||||||
|
|
|||||||||||||||||||||||||||||
| assert build_session_key(slash.source) == build_session_key(message.source) | |||||||||||||||||||||||||||||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. [P1] F03 β Startup auto-resume skips restored relay-backed Discord sessionsUpdated 2026-10-01 after the author's call-site challenge. Attribution: inherited. This replaces the broader transport-kind claim and its required persistence redesign. Detailed caller evidence and reconciliation: follow-up in this thread. Exact caller: Mechanism: source serialization deliberately omits the live relay marker. After restoration, the direct selectors look for the logical New evidence: Linux / Python 3.14.7, original Evidence boundary: the original probe established selector behavior only. The new control executes startup scheduling after adapter registration; no connector handshake, model turn or provider delivery is claimed. The positive-control terminal dispatch is a recorder. Repair and regression: resolve the correct owner-scoped relay capability in the affected delivery path while preserving pinned transport/profile ownership and existing native-adapter behavior. Cover the real scheduler in the two modes above, plus disconnected-owner and native controls. The evidence does not establish that a new persisted transport-kind field is necessary. The lookup substitution is diagnostic, not a complete patch. The heartbeat and plugin-injection direct-selector consumers should be covered by the same repair; their consequences are source-traced here rather than independently reproduced.
Contributor
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Not reproduced with the real transport. The marker is wire-invisible on purpose (
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. F03 call-site answer: startup auto-resume uses a different selectorThe caller is Your counterexample is correct for source = self._restored_source(entry)
adapter = self._delivery_adapter_for(source)
if adapter is None:That branch logs the unavailable adapter and continues without scheduling the pending session. Why the results differ
%%{init: {"theme":"dark","themeVariables":{"darkMode":true,"background":"#090d14","primaryTextColor":"#f8fafc","lineColor":"#94a3b8","clusterBkg":"#0f172a","clusterBorder":"#475569","edgeLabelBackground":"#111827"}}}%%
flowchart TD
subgraph CANVAS[" "]
direction TB
subgraph FLOW["Startup resume and completion delivery"]
direction TB
S["Restored Discord session"]
S --> A["Startup auto-resume"]
S --> I["Watch / completion injection"]
A --> D["_delivery_adapter_for"]
D --> K["Literal Discord adapter lookup"]
K --> X["No native adapter: skip resume"]
I --> R["resolve_delivery_transport"]
R --> F["Relay fronts Discord"]
F --> L["RelayAdapter selected"]
end
subgraph LEGEND["Legend"]
direction TB
L_authority["Ownership / policy checks"]:::authority
L_transition["Transitions / pending work"]:::transition
L_durable["Durable state"]:::durable
L_success["Successful outcomes"]:::success
L_failure["Failures"]:::failure
end
classDef entry fill:#172554,stroke:#60a5fa,color:#eff6ff,stroke-width:2px
classDef authority fill:#3b0764,stroke:#c084fc,color:#faf5ff,stroke-width:2px
classDef transition fill:#451a03,stroke:#fbbf24,color:#fffbeb,stroke-width:2px
classDef durable fill:#134e4a,stroke:#2dd4bf,color:#f0fdfa,stroke-width:2px
classDef success fill:#052e16,stroke:#4ade80,color:#f0fdf4,stroke-width:2px
classDef failure fill:#450a0a,stroke:#f87171,color:#fef2f2,stroke-width:2px
classDef context fill:#1e293b,stroke:#94a3b8,color:#f8fafc,stroke-width:2px
class D,K,R,F authority
class A,I transition
class S durable
class L success
class X failure
linkStyle default stroke:#94a3b8,stroke-width:1.5px
FLOW ~~~ LEGEND
style FLOW fill:#0f172a,stroke:#475569,color:#f8fafc
style LEGEND fill:#0f172a,stroke:#475569,color:#f8fafc
click S href "https://github.com/NousResearch/hermes-agent/blob/10b955a34d584fa30daf92353f45460e489e00d0/gateway/run_startup.py#L575-L616" "Pinned call-site implementation"
click A href "https://github.com/NousResearch/hermes-agent/blob/10b955a34d584fa30daf92353f45460e489e00d0/gateway/run_startup.py#L575-L616" "Pinned call-site implementation"
click I href "https://github.com/NousResearch/hermes-agent/blob/10b955a34d584fa30daf92353f45460e489e00d0/gateway/run_notifications.py#L1245-L1265" "Pinned call-site implementation"
click D href "https://github.com/NousResearch/hermes-agent/blob/10b955a34d584fa30daf92353f45460e489e00d0/gateway/authz_mixin.py#L285-L313" "Pinned call-site implementation"
click K href "https://github.com/NousResearch/hermes-agent/blob/10b955a34d584fa30daf92353f45460e489e00d0/gateway/authz_mixin.py#L254-L283" "Pinned call-site implementation"
click X href "https://github.com/NousResearch/hermes-agent/blob/10b955a34d584fa30daf92353f45460e489e00d0/gateway/run_startup.py#L595-L616" "Pinned call-site implementation"
click R href "https://github.com/NousResearch/hermes-agent/blob/10b955a34d584fa30daf92353f45460e489e00d0/gateway/delivery.py#L57-L74" "Pinned call-site implementation"
click F href "https://github.com/NousResearch/hermes-agent/blob/10b955a34d584fa30daf92353f45460e489e00d0/gateway/relay/adapter.py#L1164-L1170" "Pinned call-site implementation"
click L href "https://github.com/NousResearch/hermes-agent/blob/10b955a34d584fa30daf92353f45460e489e00d0/gateway/delivery.py#L57-L74" "Pinned call-site implementation"
end
style CANVAS fill:#090d14,stroke:#090d14,color:#f8fafc
Source map: startup Β· direct selectors Β· watch/completion selector Β· relay-aware resolver. Original diagram rendered and visually checked with Mermaid CLI. Fresh caller-level evidenceI reran this on The stronger control uses the actual
All unmodified scheduling runs log Boundary: this exercises constructed runtime objects and the production scheduling method after adapter registration. It does not exercise a connector handshake, an agent turn, or Discord delivery. The terminal dispatch recorder is the endpoint of the positive control. The lookup substitution is a diagnostic control, not a complete production patch. Correction to my earlier findingMy earlier probe stopped at selector resolution. Linking startup as a consumer did not establish its scheduling result; this follow-up executes that branch. F03 should be narrowed to the direct-selector path demonstrated above. Your working alias-aware routes should remain explicit controls. The wire-invisible relay marker is deliberate. I withdraw the earlier requirement that closure must introduce a persisted transport-kind discriminator: these results do not establish that a new field is necessary. The repair obligation is to make restored delivery consult the correct owner-scoped relay capability while preserving the existing profile/transport ownership rules. For the issue you offered to file, the concrete title is βStartup auto-resume skips restored relay-backed Discord sessions through the direct adapter selector.β This is an inherited P1 resume failure, present at both checked revisions. The regression must cover the actual scheduler in both modes above. Restored heartbeat polling and plugin-message injection are additional direct-selector consumers to cover in the same repair; those sibling consequences are source-traced here, not separately reproduced.
Contributor
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Thanks for naming the caller. Confirmed: In #131090, The regression drives the real scheduler over startup and reconnect, standalone and multiplexed-primary: red on main ( |
|||||||||||||||||||||||||||||
| prompts = {_pinned_prompt(event.source) for event in (message, slash, message)} | |||||||||||||||||||||||||||||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. [P2] F06 β Select component identity survives while the actual selected values disappearAttribution: inherited. Type-3 conversion projects only custom_id. Discord's component-data schema makes values present for select components. The hp1 prompt-token path is a separate recognized control and is not evidence that generic selects preserve their values. Probe: the registered callback receives a type-3 select with custom_id=choose, component_type=3 and values=[item-b]. The dispatched event is text='choose', metadata={}, prompt_response=None; the selected value appears nowhere. An ordinary button produces its intended custom_id. The exact merge-base adapter produces the same output tuple. No real select was registered or invoked in Discord. Consequence: if such a select reaches this generic forwarder, the consumer cannot distinguish selections. That conditional boundary is demonstrated; deployment frequency and supported connector menus are not. This is separate from modal flattening because it uses an otherwise implemented branch and needs value-aware component handling. Repair/closure: distinguish component type and carry selected values/resolved entities without confusing them with developer-defined custom_id. Alternatively reject unsupported select types explicitly. A regression should compare two different choices with the same custom_id and require different preserved user input, plus a button and recognized hp1 control. Fresh receipt: consumers-isolated: test_select_component_preserves_user_choices fails; exact-base adapter equivalence passes. Head Code under discussion β producer, state owner, and consumers:
Contributor
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Confirmed: |
|||||||||||||||||||||||||||||
| assert len(prompts) == 1 | |||||||||||||||||||||||||||||
| # Recording the labels is a disk write and _on_inbound runs on the gateway loop. | |||||||||||||||||||||||||||||
| assert writers and threading.get_ident() not in writers | |||||||||||||||||||||||||||||
|
|
|||||||||||||||||||||||||||||
|
|
|||||||||||||||||||||||||||||
| @pytest.mark.asyncio | |||||||||||||||||||||||||||||
| @pytest.mark.parametrize("member, expected", [ | |||||||||||||||||||||||||||||
| ({"nick": "Benny", "user": {"id": "u1", "username": "ben", "global_name": "Ben D"}}, "Benny"), | |||||||||||||||||||||||||||||
| ({"user": {"id": "u1", "username": "ben", "global_name": "Ben D"}}, "Ben D"), | |||||||||||||||||||||||||||||
| ({"user": {"id": "u1", "username": "ben"}}, "ben"), | |||||||||||||||||||||||||||||
| ]) | |||||||||||||||||||||||||||||
| async def test_interaction_names_the_user_as_the_text_lane_would_now(member, expected): | |||||||||||||||||||||||||||||
| """The text lane's user_display_name is the native author.display_name (guild nick, else global | |||||||||||||||||||||||||||||
| name, else username), and an interaction carries all three as of now. The name an earlier | |||||||||||||||||||||||||||||
| message carried ("Ben D" here) must not win: it predates a nickname change.""" | |||||||||||||||||||||||||||||
| adapter, _stub = _adapter(platform="discord") | |||||||||||||||||||||||||||||
| adapter.handle_message = AsyncMock() | |||||||||||||||||||||||||||||
| await adapter._on_inbound(_message({"chat_id": "ch1", "chat_type": "group"})) | |||||||||||||||||||||||||||||
| assert adapter._discord_interaction_to_event(_forward(member=member)).source.user_name == expected | |||||||||||||||||||||||||||||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -162,7 +162,17 @@ forward needs no response back (the provider was already satisfied), so it rides | |
| the same outbound WS as `inbound` via a `passthrough_forward` frame rather than | ||
| an HTTP POST. The gateway processes the decoded request through its normal agent | ||
| path (a Discord interaction is decoded to a `MessageEvent` and handled like a | ||
| message; the reply egresses over the outbound / `follow_up` path). `bufferId` is | ||
| message; the reply egresses over the outbound / `follow_up` path). An | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. [P1] F12 β Normal interaction replies select ordinary send rather than the documented follow-up capabilityAttribution: inherited. This changed paragraph retains the promise that a deferred interaction reply egresses through follow_up. The actual inline response path and final reply path route to ordinary send. send_follow_up exists separately; the source census finds its adapter entry called by tests, not the normal reply path. Probe: convert a real interaction; capture its scope; drive actual inline reply and send_final_ledgered with a harmless response and the in-memory connector. Both emit op='send', reply_to=None, zero follow-ups. Explicit send_follow_up on the same key emits op='follow_up'. Both base and head reproduce. Consequence/limit: the gateway's operation selection does not implement its written capability-response contract. A separate channel post is not proof that the provider's deferred interaction was completed. The external connector may have behavior not present here; this review did not inspect a live provider response or claim an observed stuck Discord UI. Repair/closure: select the interaction response capability through both inline/busy and normal final paths while retaining ordinary send for ordinary text. Test emitted op, session/action correlation and content with the connector contract, then verify deferred response completion externally. The documented thread capability-key obligation remains necessary once that actual caller exists; a method-only green test is not integration evidence. Fresh receipt: lifecycle-parent and lifecycle-base-parent: interaction_reply_route; production caller census. Head Code under discussion β producer, state owner, and consumers:
Contributor
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Verified that nothing in the tree calls
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. [P1] This changed contract still describes a call path the head does not executeThe paragraph says a normal decoded interaction reply egresses through The external provider consequence is still bounded: this does not by itself prove a stuck Discord UI. But the changed contract is presently false as a description of this repository. Either route the intended interaction response through the documented capability and assert emitted op/session correlation, or rewrite this paragraph to name the actual owner of deferred-response completion. |
||
| interaction sent inside a thread (partial `channel.type` 10, 11 or 12) is keyed | ||
| like the text lane's thread message: `chat_type: thread`, `thread_id` = the | ||
| thread channel id, `parent_chat_id` = `channel.parent_id`. The connector's | ||
| capability binding for that interaction must derive the same fields, or a later | ||
| `follow_up` names a session the vault never bound. The raw interaction has no | ||
| chat labels, so the gateway gives it the `chat_name` / `chat_topic` the text lane | ||
| last carried for that chat (recorded as observed, so they survive a restart), and | ||
| names the user from the interaction itself: guild nick, else global name, else | ||
| username. The connector's `user_display_name` on a text message must resolve the | ||
| same way, or the two lanes name one user differently. `bufferId` is | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. [P0] F01 β Buffered passthrough has no ACK/settlement path, and duplicate admission is not fencedAttribution: inherited. The modified contract says a buffered forward is acknowledged after durable handoff. The passthrough dispatcher forwards bufferId, but the receiving callback does not consume or acknowledge it and bypasses the text lane's replay set. Observed: local real WS frame dispatch β real adapter conversion, with final admission replaced by an inert recorder: identical buffer/provider interaction delivered twice β two admissions, zero ACK frames. A new interaction dispatches normally. Ordinary inbound control β one admission, two ACKs. The same results occur at merge base. Separately, the actual owner constructor generates two owners for repeated preparation of that keyless event; ordinary message-ID control is stable. The outbound ledger deliberately excludes slash replies; it cannot be cited as an inbound effect fence. Consequence and limit: the gateway violates its documented buffer-settlement contract and admits duplicates. This run did not execute a model/tool twice, inspect a live connector cursor, or inject a process crash. The prior issue's stronger duplicate-effect claim is not fresh evidence from this run. Repair/closure: define a distinct interaction action identity and durable admission/settlement record; ACK only after the specified durable handoff. Assert repeated delivery before claim, after claim, after effect/before ACK, and after ACK against harmless effects. An in-memory seen set or ACK immediately after task scheduling does not close the crash boundary. Fresh receipt: lifecycle-parent / lifecycle-base-parent: frame_ack_replay, turn_owner, delivery_accounting. Head Code under discussion β producer, state owner, and consumers:
Contributor
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Confirmed: |
||
| present when the forward was buffered (Phase 5 Β§5.3 buffered-only flip) and the | ||
| gateway acks it after durable handoff. | ||
|
|
||
|
|
||
Uh oh!
There was an error while loading. Please reload this page.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
[P1] F02 β The awaited label write opens a cancellation window before admission but after the seen bit
Attribution: new pre-admission exposure on an inherited early-dedupe design.
The message is marked seen before this new await, while message admission remains later. The transport ACKs ordinary inbound after the callback returns. Its teardown can cancel the reader, which directly awaits frame dispatch.
Probe: hold the real record method behind a threading Event, start the real transport inbound handler, cancel the intake task after the worker enters but before admission, release the worker, then replay the identical buffered text frame on the same adapter. Final dispatch is an inert AsyncMock. Observed first admissions=0, total admissions=0, replay ACKs=1, seen entries=1. The worker can finish writing metadata despite cancellation. In the no-cancellation control: admissions=1, ACKs=2. On the exact base, this new label wait does not exist and both arms admit once.
Attribution: early seen insertion predates this PR; the awaited storage leg newly exposes this specific pre-admission interruption. This is a same-adapter cancellation/replay experiment, not a claimed full gateway reconnect or production incident. A fresh adapter may clear the process map; that does not make an ACK without admission valid.
Repair/closure: retain or release admission ownership explicitly across cancellation. A message not admitted must remain retryable; an admitted message must not execute twice. Cover worker completion after cancellation, same-adapter replay, duplicate overlap, and uncancelled control. Moving the write off-loop must remain; reverting to a synchronous write would trade this defect for loop blocking.
Fresh receipt: cancellation-head: 1 failed / 1 passed; cancellation-base: 2 passed. Head
fa9259fdc1346c8d2ba5c1bd052358b559777789; native Windows; inert external I/O. Full reconciliation and test boundaries are in the review body.Code under discussion β producer, state owner, and consumers:
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Reproduced, fixed in
10b955a3. The window was older than this PR:_consume_prompt_responseand_localize_inbound_mediaalready awaited between the seen bit andhandle_message, and the label write widened it. A cancellation before admission now releases the seen bit, so the replay is admitted once. It is limited toCancelledError(teardown); a frame that raises keeps today's behaviour, so a poison frame does not replay forever. Rowcancelled: the intake task is cancelled while the write is held, then the frame is replayed and admitted once. Keeping the seen bit fails it.