Skip to content
Closed
Show file tree
Hide file tree
Changes from 5 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
80 changes: 77 additions & 3 deletions gateway/relay/adapter.py
Original file line number Diff line number Diff line change
Expand Up @@ -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 +
Expand Down Expand Up @@ -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)

@andrexibiza andrexibiza Sep 30, 2026 •

Copy link
Copy Markdown
Contributor

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:

Copy link
Copy Markdown
Contributor Author

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_response and _localize_inbound_media already awaited between the seen bit and handle_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 to CancelledError (teardown); a frame that raises keeps today's behaviour, so a poison frame does not replay forever. Row cancelled: the intake task is cancelled while the write is held, then the frame is replayed and admitted once. Keeping the seen bit fails it.

self._stamp_slack_session_thread(event)
# A structured prompt answer resolves its waiting primitive and is CONSUMED β€”
# never also dispatched as chat.
Expand All @@ -891,6 +897,56 @@ async def _on_inbound(self, event) -> None:
await self.handle_message(event)

_SEEN_INBOUND_MAX = 512
_DISCORD_LABELS_MAX = 2048

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The 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:

@andrexibiza andrexibiza Oct 1, 2026 •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The 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.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The 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, run_adapters.py refuses Relay on a secondary profile, because it is shared process-level ingress. So one process has one RelayAdapter, and two gateway processes can't share a home because of the per-home host lock. Within that single adapter, a new observation updates its own entry, so the positive and negative entries this cache holds can't go stale from another writer.

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.

@andrexibiza andrexibiza Oct 2, 2026 •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[P2] One RelayAdapter is enough to reproduce the generation split

This 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: restore_quick_snapshot writes snapshot pages through SQLite backup() so a gateway/dashboard/CLI connection may remain open, and test_restore_state_db_live_connection pins that behavior.

So the supported sequence is: observe A β†’ snapshot β†’ same adapter observes B β†’ restore snapshot while the gateway stays live β†’ durable gateway_chat_labels:... is A again β†’ this line still returns B until eviction/restart, after which the same restored state reads A. No second gateway and no second RelayAdapter are involved.

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

@andrexibiza andrexibiza Sep 30, 2026 •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[P2] Keep the cold database read off the event loop

Moving record_chat_labels to asyncio.to_thread fixes the write side, but this synchronous call reaches SessionDB.get_meta, which takes the main connection's writer lock. A cold interaction can therefore freeze the loop behind an unrelated database write, including the WS reader, heartbeats and other chats.

Reproduction: record a labelled text event through real _on_inbound; create a cold relay adapter over that same store. Start a background SessionDB._execute_write transaction whose callback waits on a threading Event. Once entered, schedule an asyncio.sleep(0.01) heartbeat, convert a forwarded interaction, and release the transaction after 300ms with a separate threading Timer. The heartbeat completes after 310ms, failing the <150ms responsiveness assertion. The same cold-conversion control passes on the merge base. This is a controlled contention proof, not a production latency estimate.

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 fa9259fdc1346c8d2ba5c1bd052358b559777789 and its clean composition onto upstream 8d30c4eaabd85edb77a02fef6c5388d9344ef80c, using scripts/run_tests.sh, a temporary HERMES_HOME, real SQLite/SessionStore, and real boundary conversion. Only final message dispatch was mocked.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Reproduced: _discord_chat_labels_for called store.chat_labels on the loop, and get_meta takes the writer lock. Fixed in 10b955a3. _on_passthrough now awaits the cold read in a worker before admission, and the converter no longer touches the store. Every restart case asserts that both the read and the write ran off the loop thread. Putting the read back on the loop fails 9 cases.

@andrexibiza andrexibiza Sep 30, 2026 •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The 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 loop

Attribution: 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 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:

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Same as the 15:24 inline on line 938. Fixed in 10b955a3 (cold read in a worker, before admission). The failure and absence cases (F07) are kept apart.

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)

@andrexibiza andrexibiza Sep 30, 2026 •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[P2] Invalidate peer adapters' positive and negative label caches

This result, including a successful None, is cached indefinitely. A later record_chat_labels from another adapter updates the shared record without invalidating this adapter's map. The runner installs the same self.session_store on primary and secondary adapters in _wire_adapter_handlers; the record key is per platform/scope/chat.

Reproduction: construct two relay adapters A and B over one real SessionStore. A converts an interaction before any observation, memoizing (None, None). B receives a labelled message for that guild/channel through _on_inbound. A direct real store.chat_labels read now returns the new name/topic, but A's next interaction still returns missing labels. A second parameterized case first lets A observe old labels, then lets B observe the rename: the persisted record is new but A's interaction remains old. Both cases fail on the head and current-main composition. Restart/eviction makes A read the newer record, so the same interaction's result depends on cache lifetime.

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 fa9259fdc1346c8d2ba5c1bd052358b559777789 and its clean composition onto upstream 8d30c4eaabd85edb77a02fef6c5388d9344ef80c, using scripts/run_tests.sh, a temporary HERMES_HOME, real SQLite/SessionStore, and real boundary conversion. Only final message dispatch was mocked.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The 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 RelayAdapter: under multiplex, run_adapters.py refuses a secondary's Relay (shared process-level ingress), and the adapter map is keyed by Platform.RELAY. The only writer of a chat's record is the adapter that reads it, and it updates its own map first. Your audit narrows this the same way (Q2).

@andrexibiza andrexibiza Sep 30, 2026 •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The 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 read

Attribution: 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 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:

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Reproduced: no handle meant chat_labels returned None, which was then cached as absence. Fixed in 10b955a3: with no get_meta it raises, so the interaction goes through unlabelled, nothing is cached, and the next one reads again. Row read-unavailable. Making it return None again fails it.

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
Expand Down Expand Up @@ -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,

@andrexibiza andrexibiza Sep 30, 2026 •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[P2] Preserve a known thread parent when the partial channel omits it

The new thread derivation fixes the session split, but unconditionally loses a known parent when channel.parent_id is absent. Discord describes the interaction's channel as partial; the Channel schema marks parent_id optional. This finding concerns that valid omission, not a claim that every live interaction omits it.

Reproduction: admit and persist a text source with chat_id=thread_id=th1, chat_type=thread, parent_chat_id=ch1. Convert a same-user interaction carrying channel={id:th1,type:11} without the parent field. The session keys now match, but the interaction's parent is None. Enable the real Discord tool capability through temporary config/secret scope and render the real pinned session context: text shows Parent channel + Thread, while the interaction shows Channel. The actual ProfileRoute(chat_id=ch1).matches returns True for text, False for the interaction, so this is also a parent-based routing gap rather than just presentation.

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 fa9259fdc1346c8d2ba5c1bd052358b559777789 and its clean composition onto upstream 8d30c4eaabd85edb77a02fef6c5388d9344ef80c, using scripts/run_tests.sh, a temporary HERMES_HOME, real SQLite/SessionStore, and real boundary conversion. Only final message dispatch was mocked.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The 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 parent_id is never obfuscated, so a thread interaction carries its parent. Recovering a parent from the text lane would cover a payload shape Discord does not send. Your audit marks it conditional too (Q1).

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

@andrexibiza andrexibiza Sep 30, 2026 •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[P2] Keep interaction identity separate from actual message identity

This source still uses payload.id as message_id. Discord's interaction schema distinguishes the interaction ID from the component's attached message.id. The resulting MessageEvent also leaves its own message_id empty. These existing boundary defects are relevant to the full prompt/input-parity class even though this assignment predates the diff.

Reproduction: forward a type-3 component with id=i1, message.id=actual-message-77, and a foreign custom_id that follows the normal text/agent path. The real converter returns source.message_id=i1, event.message_id=None. Passing its real SessionContext through GatewayRunner._set_session_env exposes HERMES_SESSION_MESSAGE_ID=i1, not the actual attached message. Thus source-based consumers receive an interaction identifier as a message target, while event-based reply/message-note consumers receive no message identifier.

A second real-wire probe provides a text frame's root message_id=platform-message-1 but omits the optional nested source.message_id. The text decoder leaves the source ID empty; the interaction source always has one. With actual Discord tool capability enabled and equal labels/user/session keys, the pinned renderer still changes its Triggering message guidance. Label parity alone therefore does not close the prefix class.

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 fa9259fdc1346c8d2ba5c1bd052358b559777789 and its clean composition onto upstream 8d30c4eaabd85edb77a02fef6c5388d9344ef80c, using scripts/run_tests.sh, a temporary HERMES_HOME, real SQLite/SessionStore, and real boundary conversion. Only final message dispatch was mocked.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The 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 source.message_id presence changes. This PR keeps today's identity, and the test now renders the prompt with Discord tools loaded, so a split that drops source.message_id fails 11 cases.

Expand Down
26 changes: 25 additions & 1 deletion gateway/session_persistence.py
Original file line number Diff line number Diff line change
Expand Up @@ -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")
Expand Down Expand Up @@ -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:

@andrexibiza andrexibiza Sep 30, 2026 •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The 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 writes

Attribution: 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 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:

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Reproduced, fixed in 10b955a3. record_chat_labels returns whether it wrote, and only a write fills _discord_labels_recorded. Row write-unavailable: the first write finds no handle, the next message with the same labels writes them, and they survive the restart. Counting the no-op as written fails it.

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."""
Expand Down
140 changes: 140 additions & 0 deletions tests/gateway/relay/test_relay_discord_interaction_labels.py
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"}}

@andrexibiza andrexibiza Sep 30, 2026 •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The 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 newness

Attribution: 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 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:

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Confirmed by trace: _hmwa_open_session decides newness by created_at == updated_at, /status creates the entry, and the first real message's lookup moves updated_at. Older than this PR, gateway-wide, different class. Filed as #130304, crediting you.

body.update(payload)

@andrexibiza andrexibiza Sep 30, 2026 •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The 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 target

Attribution: 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 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:

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Confirmed: a context-menu command arrives as a bare /summarize, with no target_id and no resolved object. Filed in #130305.


class Forward:
platform, method, path = "discord", "POST", "/interactions/bot1"

Forward.body = json.dumps(body).encode()

@andrexibiza andrexibiza Sep 30, 2026 •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[P2] F10 β€” Interaction action IDs are advertised and used as provider message targets

Attribution: 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 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:

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The 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}"}})

@andrexibiza andrexibiza Sep 30, 2026 •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[P2] F11 β€” Root-only text message IDs never reach source-based context consumers

Attribution: 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 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:

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Confirmed in _event_from_wire: root and nested ids are filled independently. The fixture now carries both. Filed in #130306.



@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))

@andrexibiza andrexibiza Sep 30, 2026 •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[P1] F05 β€” Admitted modal submissions lose their user-entered values before the consumer

Attribution: 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 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:

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Confirmed on the converter: a type-5 body becomes text == "". Older than this PR, different class (content normalization). Filed with F06 and F09 as #130305, crediting you.


assert build_session_key(slash.source) == build_session_key(message.source)

@andrexibiza andrexibiza Sep 30, 2026 •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[P1] F03 β€” Startup auto-resume skips restored relay-backed Discord sessions

Updated 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: GatewayStartupMixin._schedule_resume_pending_sessions, lines 597–604, invoked by the startup sequence. It restores the session source, calls _delivery_adapter_for(source), and skips the pending session when the result is None.

Mechanism: source serialization deliberately omits the live relay marker. After restoration, the direct selectors look for the logical Platform.DISCORD key; the registered adapter is keyed by Platform.RELAY. This path never asks fronts_platform. By comparison, resolve_delivery_transport and _resolve_injection_adapter select the same real relay correctly. The author's counterexample is valid for those paths.

New evidence: Linux / Python 3.14.7, original fa9259fdc1346c8d2ba5c1bd052358b559777789 and current 10b955a34d584fa30daf92353f45460e489e00d0; standalone and multiplexed default/primary; text-derived and interaction-derived session origins. The test uses actual GatewayRunner(config), WebSocketRelayTransport, RelayAdapter, production adapter publication, real session persistence/reload and the actual startup scheduler. Discord is present in the transport's real _identities. With one eligible persisted session and a passing real owner-authorization control, startup schedules zero and leaves resume_pending set. Routing the lookup through the existing relay-aware resolver yields one captured resume dispatch with the other gates unchanged.

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.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The 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 (SessionSource comment: a peer cannot forge it). A restored relay-origin Discord row in a relay-only config does resolve its transport: resolve_delivery_transport returns the RelayAdapter, because fronts_platform reads the transport's configured _identities, which a real WebSocketRelayTransport(url, "discord", ...) carries. Probe: from_dict(to_dict()) drops the marker, and resolution still returns RelayAdapter. "Native wins when both are configured" is that resolver's documented rule. I could not get the relay-only miss from any caller I traced (_resolve_injection_adapter, the restart-notice path). If your probe resolves through a different call site, please name it and I will file it.

@andrexibiza andrexibiza Oct 1, 2026 •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

F03 call-site answer: startup auto-resume uses a different selector

The caller is GatewayStartupMixin._schedule_resume_pending_sessions(), specifically gateway/run_startup.py:597–604. The real startup sequence invokes it from _start_finish_wiring.

Your counterexample is correct for resolve_delivery_transport and the injection/restart-notice paths you traced. I independently confirmed the generic resolver and _resolve_injection_adapter select the real relay after restoration. Startup auto-resume takes this other branch:

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

_delivery_adapter_for first calls _intake_adapter_for. A live source's relay marker selects the relay. A restored source deliberately lacks that marker; the remaining lookups use the logical Platform.DISCORD key in the applicable adapter map. The production primary registration stores the relay under Platform.RELAY. Those direct lookups do not consult fronts_platform.

resolve_delivery_transport does consult fronts_platform, whose advertised identity set comes from the real WebSocketRelayTransport constructor. _resolve_injection_adapter reaches that resolver. Your observation that the configured identity survives without the source marker is therefore part of the explanation.

%%{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
Loading

Source map: startup Β· direct selectors Β· watch/completion selector Β· relay-aware resolver. Original diagram rendered and visually checked with Mermaid CLI.

Fresh caller-level evidence

I reran this on fa9259fdc1346c8d2ba5c1bd052358b559777789 and 10b955a34d584fa30daf92353f45460e489e00d0, in fresh processes using Linux / Python 3.14.7. Each revision was checked with multiplexing off and with the default/primary profile under multiplexing, using both a decoded text source and an interaction-converter source.

The stronger control uses the actual GatewayRunner(config) constructor, WebSocketRelayTransport, RelayAdapter, and _publish_primary_adapter(Platform.RELAY, relay). Only Relay is enabled and registered. It creates a real session, calls SessionStore.mark_resume_pending(..., "restart_timeout"), constructs another runner/store over the same temporary home, restores the persisted origin, and executes the real startup scheduler. The shutdown path uses that same pending-marker producer.

Observation Standalone Multiplexed primary/default
Real transport advertises Discord; fronts_platform(DISCORD) Yes; True Yes; True
Restored relay marker / persisted transport profile False / None False / "default"
resolve_delivery_transport and _resolve_injection_adapter Same real RelayAdapter Same real RelayAdapter
_delivery_adapter_for(restored) None None
Real owner authorization under the explicit temporary allowlist Passes Passes
Eligible persisted sessions / scheduled resumes 1 / 0 1 / 0
Pending marker after the skipped attempt Remains set Remains set
Lookup-only positive control: scheduled resumes 1 1

All unmodified scheduling runs log Skipping auto-resume … adapter not ready for discord. For sensitivity, I changed only the instance's delivery lookup to the existing resolve_delivery_transport and recorded the terminal resume dispatch. The same scheduler then dispatched once to the same relay. Candidate selection, freshness checks, persisted state and authorization were unchanged.

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 finding

My 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.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for naming the caller. Confirmed: _schedule_resume_pending_sessions goes through _delivery_adapter_for, and a restored source has no relay marker, so the Platform.DISCORD lookups miss a Relay registered under Platform.RELAY. It is filed as #131089 under your title and fixed in #131090, outside this PR.

In #131090, _delivery_adapter_for falls back to the Relay in the owning profile's own adapter map, using resolve_delivery_transport's rule: a live native adapter still wins, and a secondary profile whose bot is offline still gets None. Two more gaps on the same path are fixed there too. After a restart the Relay's egress caches are empty, so the revived turn's reply would have been declined; startup resume, the restored heartbeat poll and plugin injection now warm them before dispatch. And on Relay reconnect, resume now covers the platforms it fronts.

The regression drives the real scheduler over startup and reconnect, standalone and multiplexed-primary: red on main (0 == 1 scheduled), green with the fix. The negative controls (native wins; secondary fails closed) are pinned by sabotage checks. Credit to you in both.

prompts = {_pinned_prompt(event.source) for event in (message, slash, message)}

@andrexibiza andrexibiza Sep 30, 2026 •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[P2] F06 β€” Select component identity survives while the actual selected values disappear

Attribution: 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 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:

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Confirmed: values are dropped and only custom_id survives. Filed in #130305.

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
12 changes: 11 additions & 1 deletion website/docs/developer-guide/relay-connector-contract.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

@andrexibiza andrexibiza Sep 30, 2026 •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The 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 capability

Attribution: 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 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:

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Verified that nothing in the tree calls send_follow_up; replies leave as op: send. Not shown to be a defect. Β§3.1 says the reply goes out "over the outbound / follow_up path". Whether a send into an interaction's channel leaves the deferred response open is decided by the connector, which is not in this repo. If it does, the fix needs the reply anchor from #130306, so it is noted there rather than filed alone.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The 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 execute

The paragraph says a normal decoded interaction reply egresses through follow_up. On this exact head, inline and final replies both enter the ordinary send lifecycle and RelayAdapter emits op: "send"; send_follow_up remains a separate session-bound method. The author already confirmed in the existing F12 thread that the normal reply path has no send_follow_up caller.

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

@andrexibiza andrexibiza Sep 30, 2026 •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The 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 fenced

Attribution: 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 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:

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Confirmed: _on_passthrough ignores buffer_id, so no inbound_ack is sent, and passthrough has no seen-set either. Older than this PR and a different class (transport settlement). It is already filed as #52581, with an open fix in #52583 (Adolanium) that acks after the handler returns. The missing replay fence belongs with that fix. Not duplicated here.

present when the forward was buffered (Phase 5 Β§5.3 buffered-only flip) and the
gateway acks it after durable handoff.

Expand Down