Skip to content

fix session shutdown wedge with an active posit assistant - #18417

Merged
gtritchie merged 10 commits into
mainfrom
bugfix/assistant-shutdown-wedge
Aug 4, 2026
Merged

gtritchie merged 10 commits into
mainfrom
bugfix/assistant-shutdown-wedge

Conversation

@kevinushey

Copy link
Copy Markdown
Collaborator

Addresses #18394.

CI shards have been dying with 300 seconds of output silence (run-with-heartbeat exit 124) at session-restart boundaries in the tests/projects region. The investigation (see the issue comment) traced it to session shutdowns that never complete when the Posit Assistant chat backend / NES agent are running: the desktop relaunch is driven purely by the rsession child's exit event, and the server session proxy only launches a replacement when connect() to the session's socket fails -- so an rsession that never finishes rCleanup() wedges the whole IDE, silently, in both modes.

Every wait in the shutdown sequence is bounded except one thing: the assistant/chat stop loops pumped the full module_context::onBackgroundProcessing() pass (every module's background handlers plus scheduled commands) and r::session::event_loop::processEvents() (arbitrary R callbacks) on every poll, mid-teardown. Any blocking item dispatched there wedges the exit permanently, with nothing logged (the whole path was DLOG-only).

Changes:

  • SessionAssistant.cpp / SessionChat.cpp: during session shutdown, the stop waits pump only processSupervisor().poll() -- which drains the child pipes, flushes the queued shutdown request, and fires the exit callbacks these waits are watching. (Agent I/O handlers already early-return during shutdown, so the full pump delivered nothing else on this path.) If the agent/backend survives SIGTERM plus the grace wait, escalate with SIGKILL to its detached process group -- terminateProcess() is a single-pid SIGTERM, terminateAllChildProcesses() is off by default in the session, and exitWithParent is compiled out on macOS, so a surviving agent was otherwise orphaned forever. The did-not-exit paths now log at WARN so any recurrence localizes itself in the session logs CI already attaches.
  • session-launcher.ts (desktop): launchNextSession() now clears workbenchInitialized on reload, as the desktop_launch_session IPC path already did. Without this, a replacement session dying during startup after a project switch was misread as a crash of a running workbench, the launch error page was suppressed, and the window hung silently on the old dead frame.
  • e2e: desktop workers now start with assistant/chat_provider at "none" (both default to "posit", so once a @chat suite installed the backend into a worker's data home, every unrelated suite in that worker ran -- and tore down -- the agents on every restart). A per-test fixture guard flips leaked provider prefs back to "none" for tests not tagged @ai/@chat. Desktop-only: server mode shares one config across workers, so a per-test flip there would race concurrently-running @chat suites.
  • e2e: new restart-under-agent.test.ts stress test (@chat lane, desktop-only) that enables the assistant and loops project open/close cycles with the agents live -- the exact workload that wedged CI -- so a recurrence fails visibly in this test instead of killing whatever shard happened to inherit the leaked provider state.

Verification: rsession + core C++ suites pass; desktop typecheck/lint/unit tests pass (one pre-existing environmental failure: findComponents needs a built rsession); e2e typecheck passes; the new stress test passes locally against this branch's build. The wedge mechanism is the only unbounded path found in the shutdown sequence, but no stack was ever captured from a wedged CI runner, so the WARN logging is there to confirm or refute recurrence from CI artifacts.

Follow-ups deliberately not in this PR (noted on the issue): the server session proxy has no request deadline; the local-stream acceptor lacks FD_CLOEXEC (and the Windows acceptor handle is inheritable), so a non-ChildProcess fork can starve session relaunch indefinitely.

…ents at shutdown

The assistant/chat shutdown waits pumped the full background-processing
pass (every module's background handlers plus scheduled commands) and the
R event loop on each poll. Dispatching arbitrary work mid-rCleanup means
any one blocking item wedges the session's exit permanently -- and with
it the desktop relaunch (driven by the child exit event) or the server
session proxy (whose connect() to the still-held listening socket
succeeds, so session-unavailable recovery never launches a replacement).
The supervisor poll alone drains the child pipes, flushes the queued
shutdown request, and fires the exit callbacks these waits watch; agent
I/O handlers already early-return during shutdown, so the full pump
delivered nothing else on this path.

Also escalate to SIGKILL on the agent's detached process group when it
survives the grace waits: terminateProcess() is a single-pid SIGTERM,
terminateAllChildProcesses() is off by default in the session, and
exitWithParent is compiled out on macOS, so a surviving agent was
otherwise orphaned forever. The did-not-exit paths now log at WARN so a
recurrence localizes itself in session logs (everything on this path was
previously DLOG-only).

Addresses #18394.
…s at startup

launchNextSession never cleared workbenchInitialized (only the
desktop_launch_session IPC path through MainWindow.launchSession did), so
a replacement session that died during startup after a project switch was
misread as a crash of a running workbench: the launch error page was
suppressed and the window hung silently on the old, dead frame.

Addresses #18394.
The assistant and chat_provider prefs default to "posit", so once a
@chat suite installs the Posit Assistant backend into a worker's data
home, every later session start in that worker launches the chat backend
and NES agent -- and every project open/close/restart in unrelated suites
then shuts them down seconds after startup. That churn is the window for
the session-shutdown wedge that has been killing whole CI shards via the
run-with-heartbeat watchdog.

Start desktop workers with both prefs at "none" via base-prefs.jsonc,
and flip leaked provider prefs back to "none" from the per-test fixture
for tests not tagged @ai/@chat. Desktop only: server mode shares one
config/data home across workers, so a per-test pref flip there would race
a @chat suite running concurrently in another worker.

Addresses #18394.
Loop project open/close cycles with the Posit Assistant chat backend and
NES agent running -- the exact workload that wedged CI shards. The @chat
suites only hit this incidentally when the tests/projects region shared
their worker; this makes the workload deliberate so a recurrence fails
here, visibly, instead of killing whatever unrelated shard inherited the
leaked provider state. Gated on the backend actually starting
(positai.log appears) so it cannot silently degrade into testing plain
restarts.

Addresses #18394.
@kevinushey kevinushey added this to the 2026.08 (Yellow Yarrow) milestone Jul 30, 2026
@posit-snyk-bot

posit-snyk-bot commented Jul 30, 2026 •

Copy link
Copy Markdown
Contributor

✅ Snyk checks have passed. No issues have been found so far.

Status Scan Engine Critical High Medium Low Total (0)
✅ Open Source Security 0 0 0 0 0 issues
✅ Licenses 0 0 0 0 0 issues

💻 Catch issues earlier using the plugins for VS Code, JetBrains IDEs, Visual Studio, and Eclipse.

@kevinushey
kevinushey requested a review from gtritchie July 31, 2026 00:08
Two rsession-scope tests for the #18394 shutdown-pump change:
processSupervisor().poll() alone must reap an exited child and fire its
exit callback, and it must NOT dispatch scheduled commands (while
onBackgroundProcessing(false) does). A supervisor or scheduling refactor
that breaks either assumption fails here instead of resurfacing as a
silent CI shard hang.

Addresses #18394.
@kevinushey

Copy link
Copy Markdown
Collaborator Author

Since the supervisor-only pump touches sensitive shutdown code, here is the verification that went beyond "existing tests still pass":

1. Unit tests pinning the load-bearing semantics (added in 97b07fd, rsession scope): processSupervisor().poll() alone reaps an exited child and fires its exit callback, and it does NOT dispatch scheduled commands (while onBackgroundProcessing(false) does). If a supervisor or scheduling refactor ever invalidates either assumption, these fail loudly instead of the wedge resurfacing as a silent CI shard hang.

2. Adversarial A/B experiment reproducing the wedge mechanism locally (throwaway spec, not committed). Setup: assistant enabled, then SIGSTOP the NES agent (a stopped process doesn't act on SIGTERM, forcing the shutdown stop-wait to burn its full 10s budget -- the wide pump window the CI wedges imply), plant eight later::later() marker callbacks due at 300ms..3s, and trigger a session restart. Each marker writes a file if it gets dispatched; markers due after quit_session lands can only be dispatched by the shutdown waits' pump.

pre-fix build (base of this branch) this branch
markers dispatched mid-shutdown all 8 (fired t0+0.4s .. t0+3.0s) zero
restart completes 14.9s 14.2s
frozen agent afterwards reaped by POSIX orphaned-group SIGHUP/CONT delivery reaped by the new escalation -- session log shows Agent process <pid> did not exit at session shutdown; sending SIGKILL. for the exact frozen pid

So the pre-fix shutdown wait demonstrably dispatches arbitrary pending R callbacks mid-teardown (a blocking one wedges rsession's exit exactly as diagnosed in #18394), and the patched wait dispatches none while the restart still completes and the stuck agent still gets cleaned up. Two earlier runs also confirmed the graceful path is unaffected: with healthy (unfrozen) agents both builds close in ~4.5s, because the agents exit on the first poll iterations and the pump window never opens.

One incidental finding from a false start: the first experiment runs showed no live agents at all mid-test -- the new per-test fixture guard had flipped the provider prefs to none for the (untagged) experiment spec and stopped the agents seconds after session start. Annoying for the experiment (it needed the @chat tag), but it is direct evidence the e2e guard does its job.

3. Why the risky branch is narrower than it looks: it is gated to s_isSessionShuttingDown (only onShutdown-time waits change), and on that path the full pump was doing nothing useful anyway -- onStdout/onContinue early-return during shutdown, and poll() still drains the child pipes, delivers the queued shutdown request, and fires the exit callbacks the waits watch.

… pane

uninstall-posit-ai and deprecate-pai-blocking opened the chat pane relying
on the chat_provider default of "posit"; with base-prefs now seeding
"none" the pane has no provider and waitForChatReady times out (seen on
the macOS shard for uninstall-posit-ai; deprecate-pai-blocking has the
same latent dependence on suite ordering). chat-guardrails-paths is
console-driven and unaffected.

Addresses #18394.
@github-actions

github-actions Bot commented Jul 31, 2026 •

Copy link
Copy Markdown

RStudio E2E - all platforms

All tests passed!

#################### 100% pass rate

Passed Failed Skipped Flaky
1903 0 369 1
Platform ✅ Passed ❌ Failed ⚠️ Skipped 🔁 Flaky
✅ desktop-linux 474 0 90 0
✅ desktop-macos 469 0 95 1
✅ desktop-windows 480 0 90 0
✅ server-linux 460 0 94 0
✅ setup 20 0 0 0
View / download the full report

View report online -- opens in the browser, no download needed. Available for 14 days.

Download playwright-report.zip -- extract and open index.html

Includes screenshots, traces, and step-by-step details for every test. Expires in 15 days.


All platforms - commit 2bd60819bfd4a3d3f4487cf668295f32165e2145 - Run #416

@gtritchie

Copy link
Copy Markdown
Member

Code review findings

Actionable items from an automated multi-agent review. Verified against source; the C++ was not built or run.

Critical

  1. src/cpp/session/modules/SessionChat.cpp:6304-6311 and :6335 — chat::onSuspend bypasses both halves of the fix, and it runs before onShutdown on the suspend leg (r/session/RSuspend.cpp:158-166 → RCleanUp → SessionMain.cpp:1505). Its wait loop still pumps onBackgroundProcessing(false) + processEvents() — the exact wedge pattern this PR identifies — and it then sets s_chatBackendPid = -1 unconditionally after a single-pid SIGTERM, so the guard at onShutdown:6371 is false and the entire new poll-only wait plus SIGKILL escalation (:6387-6448) is dead code on every suspend. That covers server idle-timeout suspends and desktop suspend-for-restart — and NEWS.md explicitly names "restarting R" as fixed. The new e2e test drives project open/close (the quit path), so it does not cover this either. Fix: factor the wait + escalation into one helper used by both onSuspend and onShutdown, and stop clearing s_chatBackendPid in onSuspend so the escalation can still run.

Important

  1. src/cpp/session/SessionModuleContextTests.cpp:388-417 — the test spawns its child with default ProcessOptions, i.e. callbacksRequireMainThread == false, unlike the production code it exists to pin (SessionAssistant.cpp:1467, SessionChat.cpp:5324). These tests run inside a live initialized session where SessionOfflineService.cpp:280 also calls processSupervisor().poll() on a background thread (handleOfflineEnabled defaults true). So (a) the offline thread can do the reaping and the test passes without main-thread poll() doing anything — it does not actually pin the documented invariant, and (b) *pExited / *pExitStatus are written off-thread while the main thread reads them. Fix: options.callbacksRequireMainThread = true; before runCommand.

  2. e2e/rstudio/tests/panes/posit-assistant-chat/restart-under-agent.test.ts:51-64 — the "guard against silently testing nothing" can pass while proving nothing. rstudioSession is worker-scoped (rstudio.fixture.ts:240) and logDir is <dataHome>/log (desktop.fixture.ts:710), shared by every spec in that worker; the PR's own premise is that an earlier @chat suite already ran the backend there, so fs.existsSync(positai.log) is satisfied on the first poll by a stale file. The fixture already snapshots log sizes per test (rstudio.fixture.ts:122) precisely because logs accumulate — baseline the size/mtime before setChatProvider and poll for growth. Separately, the NES agent enabled at :49 is never verified at all, and that is the module with the changed waitFor and the new SIGKILL; "the wedged CI sessions ran both" is asserted only in a comment.

  3. e2e/rstudio/tests/panes/posit-assistant-chat/restart-under-agent.test.ts:66-70 — afterAll leaks provider state on exactly the path it exists to protect. closeProjectIfOpen is wrapped in an empty .catch(() => {}) (also against project standards, and it swallows the wedge signal this suite exists to detect), while the two setPref calls are unguarded. setPref → waitForPrefEntry throws after 10s when the bridge is gone, so on a real wedge the first call throws and chat_provider stays "posit" for every later suite in that worker — the contagion the whole fixture change is meant to stop. Fix: log rather than swallow in the catch, and make the two writes independently non-fatal (Promise.allSettled or per-call .catch).

  4. src/cpp/session/modules/SessionChat.cpp:6429-6431 and src/cpp/session/modules/SessionAssistant.cpp:2271-2273 — "nothing else reaps or kills it once this process exits" is false on Linux: both children set options.exitWithParent = true (SessionAssistant.cpp:1466, SessionChat.cpp:5323), which becomes prctl(PR_SET_PDEATHSIG, SIGTERM) in the child on non-Apple POSIX (core/system/PosixChildProcess.cpp:815-822). The escalation is still justified — say why instead: the only parent-death guard sends SIGTERM, the signal this process has just demonstrated it ignores, and it is compiled out on macOS. As written, a maintainer who greps exitWithParent concludes the comment is stale and may delete the escalation.

  5. src/cpp/session/modules/SessionChat.cpp:6388 — "it flushes the shutdown request queued above" is wrong, and it is presented as the justification for the change. requestBackendShutdown sends via ops.writeToStdin(message, false) (:904), a synchronous ::write (PosixChildProcess.cpp:291-315) that has already completed before the loop starts; and the chat backend registers no onContinue callback (:5307-5318), so poll() has no stdin path for this child at all. The wait needs poll() only to reap the backend and fire onBackendExit. Drop the clause.

  6. src/cpp/session/modules/SessionAssistant.cpp:2277, src/cpp/session/modules/SessionChat.cpp:6446 — the ::kill return is discarded, and the justifying comment gets EPERM backwards: for a negative pid, EPERM means a process is there and was not killed — precisely the surviving-orphan case worth logging. Since the process is detached and rsession is exiting, this log is the only artifact that will ever exist. Fix: if (::kill(-pid, SIGKILL) == -1 && errno != ESRCH) WLOG(...) (needs <cerrno>/<cstring>). Note also that setsid() fails forward in the child (PosixChildProcess.cpp:632-639), so if it ever failed, -pid names no group, nothing is killed, and the WLOG one line above still claims "sending SIGKILL".

  7. src/cpp/session/modules/SessionAssistant.cpp:2268-2277, src/cpp/session/modules/SessionChat.cpp:6442-6446 — the pid-1 hazard the comment describes is real in principle but not currently reachable: callbacksRequireMainThread = true on both children plus the off-main-thread early return in AsyncChildProcess::poll() (PosixChildProcess.cpp:1063, enabled unconditionally at SessionMain.cpp:2232) means onExit only ever runs on the main thread, and no poll occurs between the check and the kill. But safety rests entirely on that unstated invariant while the global is read three times, and SessionChat repeats the same pattern with no comment at all. Fix: PidType pid = s_agentPid; if (pid > 1) ::kill(-pid, SIGKILL); at both sites — > 1 also covers -0 == 0, which would signal rsession's own process group.

Suggestions

  1. src/cpp/session/modules/SessionChat.cpp:6384-6408 — requestBackendShutdown silently declines to send when the peer reported capabilities without lifecycle/requestShutdown (:877-882; note it does send when no capabilities were received, since peerHasCapability returns true then). The wait loop and the newly-promoted WLOG("Chat backend did not exit within its shutdown grace period") run regardless, so an older backend gets a full second of pointless polling and a warning blaming it for ignoring a request never sent. Fix: return a bool and skip both the wait and the warning.

  2. src/cpp/session/modules/SessionChat.cpp:6423, src/cpp/session/modules/SessionAssistant.cpp:2268 — the group SIGKILL only fires when the leader ignored SIGTERM. On the normal path terminateProcess(pid) is a single-pid SIGTERM (PosixSystem.cpp:1236-1247) and nothing ever signals the rest of the detached group; rCleanup's terminateAllChildren can't help because the child was already reaped out of the supervisor's list. AsyncChildProcess::terminate() already signals -pid for detachSession children (PosixChildProcess.cpp:396-400) and chat retains ProcessOperations, so using ops.terminate() instead would close this for free. (Only matters if the backend/agent fork children — reportHasSubprocs = false on both suggests the authors expected some; unverified.)

  3. src/node/desktop/src/main/session-launcher.ts:515-523 — the change itself is correct and load-bearing (the reload path uses loadUrl, never MainWindow.launchSession), but "the same way MainWindow.launchSession does" asserts a parity that doesn't hold: main-window.ts:194-197 clears the flag unconditionally, this clears it only if (reload). Gating on reload is right — a non-reload restart keeps the same workbench frame — but say so, or the redundancy with main-window.ts:197 invites deletion. This is also the one change in the diff that is trivially unit-testable, and test/unit/main/session-launcher.test.ts plus sinon are already in place: stub mainWindow, stub launchSession to throw, assert the flag is cleared for reload === true and preserved for false.

  4. e2e/rstudio/fixtures/rstudio.fixture.ts:59-74 — getPref returns null for an absent entry and, unlike setPref, has no waitForPrefEntry gate (utils/commands.ts:571-580). leakedOn(null) is false, so a transiently-empty prefs map makes the guard silently conclude "clean" — silence is the wrong default for a protective guard. Fix: gate the reads, or console.warn on a null read.

  5. e2e/rstudio/fixtures/rstudio.fixture.ts:282-284 — the guard runs in the test-scoped perTestReset, which Playwright runs after beforeAll. A non-@ai suite whose beforeAll restarts the session or opens a project (common — chat-guardrails.test.ts:88-107 does) still does that work under the leaked chat_provider="posit". Worth stating in the doc comment at minimum.

  6. src/cpp/session/modules/SessionChat.cpp:6432-6435 — the Windows sentence ("terminateProcess() is already TerminateProcess(), and the session's kill-on-close job object reaps stragglers") sits inside the #ifndef _WIN32 block, describing a branch that doesn't exist there; the assistant version at :2279-2280 is correctly in the #else. Also "reaps" → "kills". (Context, pre-existing and out of scope: the job object is real and does cover these children, but Win32System.cpp:174 tests AssignProcessToJobObject inverted and initHook discards the error, so a setup failure is unobservable — and the Windows branch here sends no signal.)

  7. e2e/rstudio/fixtures/rstudio.fixture.ts:56-57 — "(Server-mode restarts … remain exposed to e2e: shards die with 300s output silence (heartbeat exit 124) in the projects test region #18394 until the product-side shutdown hardening lands.)" is stale on merge; the hardening lands in this PR. Delete, or restate the real residual gap.

  8. e2e/rstudio/tests/panes/posit-assistant-chat/chat-user-skills.test.ts:122 — "The default chat_provider is 'posit', so the backend auto-starts" is now false given the new base pref, and this suite is the one @chat suite that never selects the provider before that point. The Step 1 setPref('chat_provider','none') plus its deliberate waitForTimeout(5000) is now a no-op wait on every run.

  9. deprecate-pai-blocking.test.ts:76-78 and uninstall-posit-ai.test.ts:69-71 carry the identical three-line comment and setPref call, which the next @chat suite will paste again. Extract a selectPositChatProvider(page) helper into _chat-setup.ts and state the rationale once at its definition.

  10. restart-under-agent.test.ts:82 and :86-90 — both assertions are unreachable as failures. createAndOpenProject builds projectDir from the name argument (utils/project.ts:175), so toContain asserts string concatenation; and openProject (utils/commands.ts:732-790) cannot return until rstudio.ready, the project path matches, and the console is idle, throwing a purpose-built diagnostic otherwise — so a recurrence fails there with a good message, never at the isActive() poll. The comment "this is where the wedged shards died" is misleading, and the dead poll adds a second 60s budget to the timeout math.

  11. e2e/rstudio/fixtures/rstudio.fixture.ts:54-55 (repeated at restart-under-agent.test.ts:24-25) — "server mode shares one config/data home across all workers" overstates it: configHome lives under a per-launchServer mkdtempSync root (server.fixture.ts:89-99); only dataHome is shared. Since prefs are written to the config home, the stated cross-worker race exists only against an external server (PW_RSTUDIO_SERVER_URL).

  12. e2e/rstudio/fixtures/base-prefs.jsonc:32-33 — "every session start would launch the chat backend + NES agent" is true for the agent (SessionAssistant.cpp:2208-2219) but not the backend: startChatBackend is only reached via the chat_start_backend RPC issued when the chat pane initializes (:5407), or by onResume.

  13. src/cpp/session/modules/SessionAssistant.cpp:627-633, src/cpp/session/modules/SessionChat.cpp:6387-6394 — neither comment records the load-bearing assumption that processSupervisor().poll() is a no-op inside another poll (core/system/Process.cpp:333-337), which this codebase has already been bitten by (SessionAssistant.cpp:2929-2934). If onShutdown were ever entered from inside a poll, both new waits degrade to plain sleeps (10s assistant, 1.5s chat) and the WARN fires spuriously. I found no such path today; the new tests pin only the top-level case.

  14. The e2e: shards die with 300s output silence (heartbeat exit 124) in the projects test region #18394 rationale is written out in full six times (SessionAssistant.cpp:627-633, SessionChat.cpp:6387-6394, SessionModuleContextTests.cpp:374-382, base-prefs.jsonc:29-37, rstudio.fixture.ts:44-57, restart-under-agent.test.ts:11-25) and the copies have already diverged on substance — the C++ versions disagree with the test header on how isolated poll() is, and the test header's "dispatching no other module's work" is too strong (poll() fires every supervised child's I/O callbacks; Process.cpp:342-343 warns it "can end up executing R code"). Keep one canonical explanation and reduce the rest to a pointer.

  15. src/cpp/session/modules/SessionAssistant.cpp:621, :2268 — waitFor is a fixed 100 × 100ms loop, so stopAgentSync() in onShutdown can burn 10s before the new SIGKILL, versus chat's 1s + 0.5s. Pre-existing, but it undercuts the bounded-exit goal on a path this PR is tightening.

  16. src/cpp/session/modules/SessionAssistant.cpp:22-24, src/cpp/session/modules/SessionChat.cpp:29-31 — kill()/SIGKILL are POSIX, declared by <signal.h>; <csignal> only guarantees the C subset. Compiles on glibc/libc++, but <signal.h> is strictly correct. Both sites also bypass the existing core::system::killProcess(pid, signal) helper (PosixSystem.cpp:1240) without saying why.

@gtritchie gtritchie left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Feedback posted

The chat module's suspend handler still pumped the full background-processing
pass and cleared the backend pid unconditionally, which both preserved the
wedge on server idle-timeout suspends / suspend-for-restart and made the
onShutdown escalation dead code on that leg. Factor the request/wait/escalate
sequence into stopChatBackendForSessionExit() and use it from both handlers.

Also from review: skip the grace wait when the shutdown request was never
sent (older backends without lifecycle/requestShutdown), log SIGKILL failures
other than ESRCH, snapshot pids and guard with > 1 before signaling the
process group, pin callbacksRequireMainThread in the supervisor-pump test,
and correct the comments on exitWithParent and supervisor-poll semantics.
From review: the comment claimed parity with MainWindow.launchSession, which
clears the flag unconditionally -- state the reload gating rationale instead,
and pin both branches with unit tests.
From review: baseline positai.log before enabling the provider so a stale log
from an earlier @chat suite can't satisfy the started-backend guard; make the
afterAll steps independently non-fatal and logged instead of swallowed; drop
the unreachable assertions after createAndOpenProject; warn when the leak
guard cannot read the provider prefs; make chat-user-skills' backend stop
conditional on a leaked-on provider; extract selectPositChatProvider; and
correct the server-mode config-home and backend-start comments.
From review: terminate the chat backend through its retained process handle,
which signals the detached child's whole process group instead of the single
pid, and cut the assistant's shutdown reap wait from 10s to 2s -- the SIGKILL
escalation is the backstop, and session exit should stay fast even when the
agent ignores SIGTERM. Non-exit callers keep the patient 10s default.
@kevinushey

Copy link
Copy Markdown
Collaborator Author

Thanks -- this was a genuinely useful review. All items are addressed in bf6ab6c (session), 2e5e345 (desktop), 3c4c318 (e2e), and 2bd6081 (items 10/23), with the following notes:

1: Confirmed, including the ordering (suspend hook -> RCleanUp -> onShutdown). The request/wait/escalate sequence is now factored into stopChatBackendForSessionExit() and used by both onSuspend and onShutdown. The assistant side needed no change: it has no suspend handler, and its onShutdown runs from rCleanup on the suspend leg with s_isSessionShuttingDown set before the wait.

2: The premise doesn't hold: ProcessOptions() defaults callbacksRequireMainThread to true (Process.hpp:91/104), and with the gate enabled at SessionMain.cpp:2232, AsyncChildProcess::poll() early-returns off the main thread (PosixChildProcess.cpp:1063) -- the offline thread can't reap this child, and *pExited is never written off-thread. I set the flag explicitly anyway so the pin doesn't depend on the default.

7/24: Fixed via direct ::kill + errno != ESRCH -> LOG_ERROR (the PosixChildProcess.cpp:1903 idiom) rather than core::system::killProcess: that helper is only declared in the POSIX-only PosixSystem.hpp (not included by session modules) and its doc comment promises single-process semantics, which a negative pid would contradict. Includes switched to <signal.h> + <cerrno>.

10: Applied for chat (2bd6081): the force-terminate now goes through the retained ProcessOperations::terminate(), which signals the detached child's whole process group. The assistant retains no ProcessOperations (its writes go through onContinue), so its normal path keeps the single-pid terminateProcess, with the group SIGKILL as the backstop.

23: Applied (2bd6081): waitFor/stopAgentSync take an iteration bound and onShutdown uses 2s instead of 10s; non-exit callers keep the patient default.

16: Kept the stop but made it conditional -- it's not always a no-op: an earlier @chat suite can leak chat_provider="posit" into the worker (the per-test guard skips @chat-tagged tests), and then a backend is running when this suite starts.

3: Stale-log hole fixed with a size baseline. The NES agent half is documented rather than guarded: the agent has no bridge-observable startup artifact today (runtime status only lands in SessionInfo at client init). Exposing it on the automation bridge would make a good follow-up.

22: Fixed the diverged/overstrong wording (the test header now says poll still fires I/O/exit callbacks of other supervised children), and the chat helper collapses one C++ copy. I've left the remaining copies in place -- each addresses a different audience and they all point at #18394 as canonical.

14's parenthetical: confirmed, Win32System.cpp:174 tests AssignProcessToJobObject inverted; that deserves its own issue.

Everything else applied as suggested. Verification: full build, 407 rsession gtests, 449 desktop unit tests (2 new for launchNextSession), desktop lint/typecheck, e2e typecheck all pass.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants