Skip to content

fix(messaging): stop a Slack or Telegram turn that makes no progress - #5382

Merged
kovtcharov-amd merged 8 commits into
amd:mainfrom
kovtcharov:claude/rel-j-bridge-watchdog
Oct 19, 2026
Merged

kovtcharov-amd merged 8 commits into
amd:mainfrom
kovtcharov:claude/rel-j-bridge-watchdog

Conversation

@kovtcharov

@kovtcharov kovtcharov commented Oct 19, 2026 •

Copy link
Copy Markdown
Contributor

The Slack and Telegram bridges answer one message at a time and waited for each answer with no deadline. If the agent went quiet while still running, every later message on the bridge waited behind it forever. Now a turn that makes no progress for 75 minutes is stopped. A running tool or an approval waiting on you doesn't count as no progress, and GAIA_STREAM_TIMEOUT changes the window, as in the Agent UI (#5200). If the agent acknowledges the stop, the user is told and can send "continue". If it doesn't, the agent is restarted: the user is told the conversation was reset, and anyone else it was talking to sees a note on their next answer. After three restarts in a day, each message says how to restart the bridge. On Telegram the partial reply is kept, and a stopped turn never sends its question later.

Reproduced by tests/unit/messaging/test_bridge_turn_idle.py, tests/unit/messaging/test_bridge_restart.py and the Telegram tests test_a_reply_that_stops_streaming_is_stopped_and_frees_the_bot and test_a_turn_stopped_before_its_thread_ran_never_sends_later; they fail on main and pass here.

🔍 Technical details
  • AgentChannel takes:

    • idle_limit: from GAIA_STREAM_TIMEOUT, else 4500 s, read through the new shared gaia.stream_timeout that the Agent UI now uses too;
    • cancel_grace: 30 s;
    • max_restarts and restart_window: 3 per 24 h;
    • restart_hint, clock and poll_seconds.

    Between tool_call and tool_result, and while a needs_confirmation is pending, the idle clock does not run. Both have deadlines of their own: the tool timeout, and Slack's 10-minute approval deny.

  • When a turn goes idle:

    • cancel is sent;
    • output the child sends while the stop is pending is dropped;
    • the child's own end of the turn is answered with the "continue" message;
    • the reader claims a terminal event under the lock before rendering it, so a stop that races a real answer cannot render over it.
  • If the child does not end the turn within the grace period, it is terminated, waited on, and killed if needed, then respawned. The stopped user gets the "reset" message, and RESTART_NOTICE is put in front of the next answer for every other sender the old child had served.

  • Children and turns are swapped under one lock. A reader drops lines once its child has been replaced, and matches every line to the turn current for that child. Closing during a respawn stops the new child, and close() stops whichever child is current.

  • Once the budget is used up, queued turns get an error naming the restart without becoming the active turn. Slack's hint, slack_restart_hint(background), is "Ctrl+C, then gaia slack start --allowed-users …", or "gaia slack stop, then … --background" when the bridge was started in the background. gaia slack start and gaia telegram start report a bad GAIA_STREAM_TIMEOUT as a clean error.

  • Telegram uses wait_for(queue.get(), idle_limit). The generation thread checks the stop before it creates the session and again before it sends. On a stop, only the session the turn actually used is dropped.

  • Each stuck Telegram generation keeps one default-executor thread until its model call ends. That pool is bounded; the LLM layer's own stall timeout is what frees them.

  • Docs: guides/slack.mdx and guides/telegram-adapter.mdx. There is no messaging CHANGELOG to update.

Test plan

  • python -m pytest tests/unit/messaging tests/unit/test_telegram_adapter.py tests/unit/test_telegram_allowlist.py tests/unit/test_stream_timeout_env.py tests/unit/chat/ui/test_turn_idle_limit.py: 295 passed, three runs in a row. The bridge tests run on a fake clock against fake children.

  • Each fix was reverted by mutation and its test failed:

    • removing the reader's identity check, the late-line test fails;
    • claiming the terminal event after rendering, the slow-render test fails;
    • removing the kill in _stop_child, the terminate-then-kill test fails;
    • showing late tokens of a stopped turn, the silent-turn test fails.

    Against the previous head, the close-during-respawn, reset-message, rolling-budget and default-budget tests fail.

  • python util/lint.py --black --isort --flake8 --pylint --test-lanes

Both bridges answer one message at a time and waited for each answer with
no deadline, so one agent that went quiet while still alive blocked every
later chat on the bridge.

Slack (AgentChannel): a turn with no progress for 75 minutes is ended for
the user and the agent is sent a cancel, mirroring the Agent UI's rule: a
running tool or a pending approval is not idle. If the agent does not end
the turn within 30 s it is shut down, and queued and later messages get an
error naming the restart instead of waiting. Late events from a stopped
turn are not rendered.

Telegram: a reply that streams nothing new for 75 minutes is stopped, the
partial text is kept with a note, and the stream is closed when it next
yields. A second message from the same user while the stopped stream is
still unwinding is told to wait instead of racing it on the same session.
… a Telegram user

- Slack: the reader claims a turn's answer before rendering it, so a stop
  racing the answer cannot render over it; a message refused after the
  child is shut down is never made the active turn; the stop message no
  longer promises partial text the Slack reply replaces.
- Telegram: a stopped reply drops the user's session so the next message
  starts fresh, instead of a busy guard that locked the user out for good
  when the stream never yielded again; a failing stream close is logged.
@github-actions github-actions Bot added documentation Documentation changes tests Test changes labels Oct 19, 2026
@github-actions

Copy link
Copy Markdown
Contributor

Verdict: Approve with suggestions

Before this PR, a Slack or Telegram reply that went quiet without ending held every later message on that bridge forever. Now a reply that makes no progress for 75 minutes is stopped and the user is told why. On Slack, an agent that ignores the stop is shut down, and later messages say to restart the bridge. I found no blocking issues. The races I looked for are covered: a stop landing at the same moment as a real answer, late output from a stopped reply, and output the shut-down agent flushes late. The Slack and Telegram guides match what the code does. Two small optional cleanups are below.

Real-world evidence

N/A: no evidence bundle was produced. Running this for real would mean holding a live Slack or Telegram reply silent for 75 minutes. The verdict rests on static review and the PR's fake-clock unit tests, which the author reports passing (243 passed). I could not re-run them here because pytest isn't installed in this review environment.

🔍 Technical details

Issues found

🟢 Child isn't reaped after the forced kill (src/gaia/messaging/bridge.py, _shut_down_wedged_child). If terminate() doesn't stop it within 5 s, proc.kill() runs, but nothing waits on the process afterwards. On POSIX that leaves a zombie until the adapter exits. One more short wait fixes it:

            except subprocess.TimeoutExpired:
                proc.kill()
                wait(timeout=5)

🟢 import pytest inside a test function (tests/unit/messaging/test_bridge_turn_idle.py, test_idle_limit_must_be_positive). Move it to the module imports. The Telegram test file already imports it at the top.

Checked, not an issue

  • The child dies after an idle stop but before its own terminal event. _dispatch_terminal_error returns without setting _turn_done, but _read_loop always calls _turn_done.set() on EOF, so the writer never hangs.
  • tool_running can't stay stuck after a tool fails. The canonical translator emits a tool_result on tool_end when the result was skipped, so tool_call always pairs with a tool_result.
  • _format_duration(4500) renders "75 minutes", which matches both guides.

Strengths

  • Terminal events are claimed under _active_lock before rendering. That turns "stop vs. real answer" into a single compare-and-set rather than a timing race, and the stopped turn still waits for the child's own terminal event before the next turn runs.
  • Turns queued behind a shut-down child get the error without ever becoming _active, so late output from the killed child can't land in them.
  • Fake clock and fake child make the bridge tests fast and deterministic. The Telegram test checks that the stream is closed when it next yields, and that the stuck user's session is dropped.

kovtcharov and others added 3 commits October 18, 2026 22:49
…gram turn late

Review follow-ups.

- Telegram: a turn stopped before its thread ran, or while its session was
  being made, sent the old question once it got going, inside the session
  the next message would use. The thread now checks the stop before making
  the session and again before sending, and only a session the stopped turn
  actually used is dropped.
- Slack: one wedged agent took the bridge down until a restart, and the
  restart hint named a command that needs --allowed-users and would open a
  second connection beside the running bridge. A child that ignores a stop
  is now replaced, up to three times per bridge, and logged; output its
  killed predecessor flushes late is dropped. After that, each message says
  to stop the bridge and how to start it again.
- GAIA_STREAM_TIMEOUT sets the no-progress window for both bridges, as it
  does for the Agent UI.
- A killed child is waited on, so none is left behind.
Two tests imported pytest inside the function body; the module now imports it with the rest.
…nd close the restart races

Round-2 review follow-ups.

- Closing the bridge while a wedged agent was being replaced left the new
  child running. The replacement checks for close after it starts and stops
  the child it made, and close() stops whichever child is current.
- A stopped turn was told to send "continue" even when the agent was then
  replaced and had lost the conversation. The message is now decided once
  the outcome is known: "continue" when the agent acknowledged the stop,
  "restarted, send your message again" when it was replaced. Anyone else
  the old agent had talked to gets a note on their next answer.
- The restart budget never reset. It is now three restarts per 24 hours.
- A late line from a replaced child could still be matched to the next turn
  between the identity check and reading the active turn; both now happen
  under one lock.
- The no-progress window is read through one shared gaia.stream_timeout,
  also used by the Agent UI. `gaia slack start` and `gaia telegram start`
  turn a bad GAIA_STREAM_TIMEOUT into a clean error, and the Slack restart
  hint keeps --background when the bridge was started that way.
- Tests cover each of these and the earlier fixes: late output from a
  replaced child whose reader is still alive, the terminal claim during a
  slow render, dropped late tokens, terminate-then-kill, the default
  budget, Telegram's GAIA_STREAM_TIMEOUT, and the Slack hint wiring.
@github-actions github-actions Bot added the cli CLI changes label Oct 19, 2026
@github-actions

Copy link
Copy Markdown
Contributor

🟡 When a stuck Slack agent is restarted, the user will probably get the wrong message. Before the replacement starts, the old agent's output closes. The bridge reads that as a crash, so the user is told "it most likely crashed, check the logs, resend" and never hears that the agent was restarted and lost the conversation. The restart message the last commit added would then be dropped, because the turn has already ended. The new test misses this: its fake process exits instantly and has no wait(), so the replacement always wins the race. With a real process, the old output's reader gets end-of-file during the up-to-5 s wait in _stop_child. Mark the old child as being retired before stopping it, and add a wait() to the fake so the test runs into the race.

🔍 Technical details

src/gaia/messaging/bridge.py, _replace_wedged_child → self._stop_child(self._proc). That blocks in proc.wait(timeout=5) while self._proc still points at the old child. The old reader (_read_loop(proc)) reaches EOF, finds proc is self._proc still true, and calls _dispatch_terminal_error(self._dead or "...most likely crashed..."). _dead is None on the restart path, and _render_terminal_error checks only saw_terminal, not stopped_at, so the crash text renders. The later _render_terminal_error(state, "...restarted...Send your message again.") returns False.

One fix: under _active_lock, set self._retiring = self._proc before calling _stop_child. In the reader's EOF path, return when proc is self._retiring, the same way it returns after the swap. close() and the budget-exhausted path still need a terminal message, and they already render one through _render_terminal_error.

Test: give FakeProc (or a subclass) a wait() that blocks until the reader has seen EOF. Then test_a_replaced_child_resets_the_conversation_and_says_so reproduces the race.

…rash

While the stuck agent was being shut down, its output closed before the
replacement took over, so the bridge read that as a crash and the user got
"it most likely crashed" instead of the restart message. The old child is now
marked as retiring before it is stopped, and nothing it sends after that,
including its end of stream, can end the turn.
@kovtcharov-amd
kovtcharov-amd added this pull request to the merge queue Oct 19, 2026
Merged via the queue into amd:main with commit 8eb0353 Oct 19, 2026
39 checks passed
@kovtcharov-amd
kovtcharov-amd deleted the claude/rel-j-bridge-watchdog branch October 19, 2026 16:37
github-merge-queue Bot pushed a commit that referenced this pull request Oct 21, 2026
…imit (#5456)

Three fixes on main could be reverted with every test still passing.
That covers a scheduled email marked failed while it is still sending
(#5380), the Slack/Telegram notice after an agent restart telling users
to "continue" a conversation the agent forgot (#5382), and nothing
proving a hung tool under the messaging bridge ever ends. Each new test
fails on the user-visible symptom when its fix is undone.

- **Scheduler lease, both stores.** Two claims with the same timestamp
are told apart only by `claim_id`. Without that half of the recovery
guard, a stale read fails a live send or re-queues a running job.
- **Restart notice.** The existing check only caught a quoted
`"continue"`. An unquoted "Send continue" that also dropped "no longer
remembers this conversation" passed everything.
- **Hung tool under the bridge.** A running tool keeps the bridge's idle
clock fresh, so only the agent's own tool limit
(`GAIA_AGENT_TOOL_TIMEOUT`, 180 s) ends it. This drives the real
`gaia-agent` turn loop behind a real `AgentChannel` and checks the user
still gets an answer. It needs the flagship wheel, so it runs in the
gaia-agent lane.

<details>
<summary>🔍 Technical details</summary>

Reverts run locally, each against the new test:

| Revert | Result |
|---|---|
| Drop `claim_id = :claim` from `recover_claim` (daemon + email store) |
4 fail: status `failed`/`pending` != `firing` |
| Restart notice → `restarted. Send continue to pick up where it left
off.` | new test fails; all existing messaging tests pass |
| Restart notice → `... Send "continue" to pick up where it left off.` |
new test fails (existing test also catches this one) |
| `_call_tool_bounded` timeout → `inf` | fails: "the hung tool was never
ended", user stuck at the `tool_call` |
| Bridge idle refresh ignores `tool_running` | fails: `error` != `final`
|

The email schedule tests skip from the repo root unless
`gaia_agent_email` is installed, because the root conftest only
redirects hub packages that are already installed. CI does run them:
`test_email_agent_unit.yml` installs the wheel and gates wholesale
skips. Main push run 39538913521 shows all 13 stale-firing tests and 16
`test_email_schedule.py` tests PASSED.
</details>

## Test plan

- [x] `python -m pytest tests/unit/test_daemon_scheduler_stale_firing.py
tests/unit/messaging/ -q`: passes locally and in Unit Tests run
39541345649. That run executed the new daemon and restart tests and
skipped `test_bridge_hung_tool.py` as allowlisted.
- [x] `python -m pytest
hub/agents/email/python/tests/test_email_schedule_stale_firing.py -q`
with `gaia_agent_email` installed: passes locally, and both new cases
(`scheduled_send`, `snooze`) passed in Email Agent Unit Tests run
39541345667.
- [x] `python util/check_test_lane_coverage.py` passes (run locally).
- [x] CI: Gaia Agent Tests run 39541345605 executed
`test_bridge_hung_tool.py` and it passed (not skipped).

---------

Co-authored-by: Kalin Ovtcharov <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

cli CLI changes documentation Documentation changes tests Test changes

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants