Repository navigation
keep serving requests while r runs code from the idle event loop - #19237
Conversation
while R is at the prompt, waitForMethod() runs R's input handlers between dequeues; a handler that runs for a long time -- shiny::runApp() scheduled with later::later() -- keeps it from dequeuing, and the polled event handler only served requests while console input was executing. every request then queued until the handler returned: console input, prefs, client_init, and the interrupt that could have ended it (which was also dropped, on the listener thread, for the same reason). the IDE looked idle and could only be recovered by killing rsession. track R code dispatched from the idle loop as its own busy state: the polled event handler serves requests while it runs (console input is buffered for the prompt rather than left at the head of the queue, where it would hold up everything behind it), interrupts are accepted, and after a second the client is told R is busy so it offers the interrupt; the prompt is reissued when the handler returns. Addresses #19236
…pt as issued review fixes: console input dequeued by waitForMethod is now queued before this iteration's input handlers run, so input a long handler lets through cannot overtake it; the prompt restored after a busy handler keeps its own history flag instead of the interactive one; and a client_init served while a handler runs (before the busy delay) is remembered so the busy state it sent is cleared when the handler returns. Addresses #19236
…n prompt review fixes: a console_input request dequeued by waitForMethod is held in the wait frame again while input handlers run (a read a handler opens must not take it as its answer), and rConsoleRead queues it ahead of input the handlers let into the queue, so submission order holds. the prompt restored when a handler returns is now the one of the read actually waiting (a readline() inside a handler is a read of its own), with its history flag, and it is restored whenever a handler issued a prompt of its own -- after a nested read is answered the REPL prompt comes back instead of nothing. Addresses #19236
…ed input review fixes: console_input counts queue clears, so waitForMethod can tell that an interrupt discarded pending input while it held a dequeued request, and discards that request too (acknowledged, like the input it was queued behind). processIdleEvents restores the waiting read's prompt after such a clear as well, since a client that submitted the discarded input marked itself busy and only a prompt clears that -- the delayed busy report may not have fired yet. Addresses #19236
review fix: the cancellation test now waits for the async completion of the console_input RPC (the listener's acknowledgement carries an asyncHandle; the main thread's handling arrives as an async_completion event with that handle) before pressing Escape, so the interrupt cannot beat the throttled polled handler, and it checks that the delayed busy report -- the only thing that enables the interrupt command -- has not fired yet. Addresses #19236
…lper's listener review fixes: the idle-event state snapshots the executing flag and the prompt count when handlers are dispatched. the busy report is gated on the snapshot, not the live flag a handler's readline() sets when it hands R the answer, and is armed again when a prompt was issued meanwhile (the read's prompt cleared the client's busy state); the executing flag such a read leaves behind is cleared once the handler returns. the e2e helper now listens for the async completion before submitting the input. Addresses #19236
…ed; count reads review fixes: waitForMethod serves any dequeued request other than the one it waits for before running the input handlers (held across a long handler, an ordinary RPC would hang), and holds only the waited-for one. the idle-event state keeps "busy was reported" apart from the armed report, so busy=false is sent even when a nested read re-armed the report and the handler returned before it fired again. console reads completed are counted, so a read satisfied straight from queued input (no prompt of its own) still restores the waiting read's prompt when the handler returns. Addresses #19236
…he wire review fixes: the buffered-read test waits for the callback to start, submits a number (a bare word can raise a completion popup, whose dismissing Escape is an interrupt in an empty console), and gates the callback's read on a flag file written once the input is confirmed queued; it skips where the runner cannot write the session's sandbox. the busy regression test records the busy client events from the events long-poll and checks the last one after the callback is false, since the console's busy class is cleared by any prompt while the workbench tracks the event. Addresses #19236
…an R option review fixes: waitForMethod checks for queued console input before the idle-suspend check, and input accepted while a handler ran resets the suspend timeout like any request, so a suspend cannot drop it. the busy report's delay is the R option rstudio.idleEventBusyDelay (seconds, one by default), read when the handlers are dispatched; the e2e tests use it to keep the report out of the pre-report cancellation case, and gate a callback's read on the observed busy event instead of on timing. Addresses #19236
review fix: rstudio.idleEventBusyDelay is honoured only when finite, non-negative, and at most a day, else the default applies, so converting it to a duration is always in range. Addresses #19236
review fix: a read a handler ran clears R's "at the top-level prompt" flag when it hands over the answer, as any read does; restore it once the handler returns, before the waiting read's prompt is reissued, so that prompt does not report R busy (the notebook chunk queue and the chat pane key off that). Addresses #19236
RStudio E2E - all platforms1 test(s) failed
View / download the full reportView report online -- opens in the browser, no download needed. Available for 14 days. Download playwright-report.zip -- extract and open
All platforms - commit |
gtritchie
left a comment
There was a problem hiding this comment.
Reproduced the hang and the fix locally; the state machine reads correctly and the e2e suite is thorough. Two correctness issues in when processIdleEvents() restores the prompt, one sizeable chunk that duplicates an existing path, and a few smaller cleanups, inline.
The two blocking ones:
- The prompt is reissued on every uncaught error in a
latercallback, even when nothing was queued and the client was never told R was busy (details inline). - The restore also runs inside the registered modal waits (
rstudioapidialogs, locator, edit, choose-file) during a command, where the saved prompt is empty andbusyis true.
The rest (duplicate bufferConsoleInput, copied return-to-prompt reset, three-site busy predicate, per-tick option read, test duplication/coverage) are take-or-leave.
| ClientEvent busyEvent(client_events::kBusy, false); | ||
| module_context::enqueClientEvent(busyEvent); | ||
| } | ||
| if (busyReported || |
There was a problem hiding this comment.
This restores the prompt whenever bufferClears changed, but rConsoleReset() bumps that counter on every uncaught error or interrupt in a handler when discard_pending_console_input_on_error is on (its default), regardless of whether anything was pending.
Verified locally with later 1.4.8 / Rcpp 1.1.2: later::later(function() stop("boom")); later::run_now() runs options(error=), i.e. R enters jump_to_top_ex, and in errors.c the R_ResetConsole() call there precedes try_jump_to_restart() unconditionally. So at an idle prompt, any callback that errors now triggers restoreConsolePrompt(): Shell.consolePrompt resets the history position, onDetectChanges(ChangeSourceREPL) refreshes Environment/Files, the onConsolePrompt hooks run, and window.rstudio.console.promptCount advances although no command completed (so waitForConsoleCommandComplete() can resolve on a prompt that was not the command's). Before this PR nothing was reissued here.
Suggest restoring only when input was actually pending or held: bump the counter only when the buffer was non-empty, and let waitForMethod (which knows it held a request) handle that case itself.
There was a problem hiding this comment.
Confirmed, and reproduced with an e2e test against the old binary (one prompt too many). R's jump_to_top_ex runs R_ResetConsole() before try_jump_to_restart(), so every uncaught error bumped the counter. Fixed in ce733ea: a separate counter only counts clears that found input queued, and that is what drives the restore. The any-clear counter stays for waitForMethod, which still needs it to discard a held request on an empty-queue interrupt; it now restores the prompt itself in that case. Tests for the error paths are in 571ce73.
| console_input::readsCompleted() != readsBefore || | ||
| console_input::bufferClears() != clearsBefore) | ||
| { | ||
| console_input::restoreConsolePrompt(); |
There was a problem hiding this comment.
processIdleEvents() runs for every waitForMethod, including the registered modal waits during a command (kUserPromptCompleted, kLocatorCompleted, the rstudioapi dialogs, kEditCompleted, kChooseFileCompleted). In those, s_currentPrompt is whatever rConsoleRead restored after its own wait: "" once the first top-level read has returned.
E.g. later::later(function() x <<- readline("q? "), 1); rstudioapi::showPrompt("t", "m"): while showPrompt waits, processEvents runs the callback, its readline completes (readsCompleted changes) and this sends console_prompt with prompt "" and busy = !isAtTopLevel() = true; the client clears its busy state and shows an empty prompt while R is still inside showPrompt. An uncaught error in any callback during such a wait (bufferClears, pref on) does the same.
Passing method into processIdleEvents() and restoring only when method == kConsoleInput would scope it to the case it was written for.
There was a problem hiding this comment.
Agreed. processIdleEvents now takes the wait's method and only restores the prompt for a console read (ce733ea). The busy=false event is still sent when owed. I did not add an e2e test for the dialog case; driving an rstudioapi dialog from a test seemed more than the fix warrants, but I can if you want it pinned.
| // looked idle to the client). Queue it for the prompt rather than leave it at | ||
| // the head of the connection queue, where it would hold up every request | ||
| // behind it -- the interrupt that could end the handler among them. | ||
| void bufferConsoleInput(boost::shared_ptr<HttpConnection> ptrConnection) |
There was a problem hiding this comment.
I think this function and the bufferInput special-casing in polledEventHandler can go. console_input is already registered as a plain RPC in SessionMain.cpp:646 (bufferConsoleInput -> console_input::extractConsoleInput), and it is never added to s_waitForMethodNames (only the registered waits are, SessionMain.cpp:593-598 and RStudioAPI.cpp:377-380), so isWaitForMethodUri() is already false for it. With || s_idleEvents.active on the dequeue condition, a console_input arriving during a handler falls to handleConnection(ptrConnection, BackgroundConnection) -> rpc::handleRpcRequest -> that registered method, for sync and async-RPC connections alike, and is buffered identically.
So the bufferInput flag never changes the isWaitForMethodUri(...) && !bufferInput outcome, and the comment about input being 'left at the head of the queue' describes a path that doesn't exist. The one real difference is the suspend::resetSuspendTimeout() call; that could live in the existing handler if you want to keep it.
There was a problem hiding this comment.
You're right, the registered handler is the same path and console_input is never a registered wait. Removed in ce733ea. The suspend-timeout reset was moot as well: every waitForMethod entry resets it, and queued input is handed back before the idle-suspend check.
There was a problem hiding this comment.
Correction to the above: the suspend-timeout reset was not moot for input that is discarded. Queued input dropped by an interrupt or an uncaught error is never handed back, so nothing re-entered waitForMethod and an idle suspend could follow a callback that outlasted the timeout. Every request served from polledEventHandler now resets it, as the foreground path does (53c5a7b).
| } | ||
|
|
||
| // a console read a handler ran (readline()) marks console input as | ||
| // executing, and R as no longer at its top-level prompt, when it hands R |
There was a problem hiding this comment.
Nit: this sequence (setExecuting(false), updateSessionExecuting(), busy=false, setAtTopLevelPrompt(true), reissue the prompt) is a second copy of SessionChat.cpp:1425-1436, down to the rationale comment about readline() leaving atTopLevelPrompt false. A single console_input helper used by both would keep them in step when the next flag a nested read leaves behind turns up.
There was a problem hiding this comment.
I looked at unifying them, and I think they are different operations: the chat one unconditionally resets to the top level and reissues the last top-level prompt, while this one restores only what a nested read changed and reissues the waiting read's own prompt (possibly a nested one). A shared helper would need flags for both. Happy to be talked into it, but I'd leave them separate.
| if (console_input::executing()) | ||
| // only accept interrupts while R is running code: processing | ||
| // input, or an input handler dispatched from the idle loop | ||
| if (console_input::executing() || s_idleEvents.active) |
There was a problem hiding this comment.
Nit: console_input::executing() || <idle handlers active> is now spelled at three sites (here, polledEventHandler at L502, and checkForInterrupt in SessionHttpConnectionUtils.cpp:324). One console_input::isRunningCode() (both inputs are atomics, so it can stay listener-thread safe) would also make it obvious which other gates on executing() alone, e.g. the rBusy filter in SessionMain.cpp:1261, were considered.
There was a problem hiding this comment.
Added console_input::isRunningCode() and used it at all three sites (ce733ea). On rBusy: that filter is deliberate. R only calls R_Busy(1) from the REPL, so during an idle handler R never signals busy itself; the delayed report in polledEventHandler is the only source and it has its own policy.
There was a problem hiding this comment.
Update: isRunningCode() is no longer the predicate at the listener. The dispatch of the handlers itself (no callback due, twenty times a second) counted as R running code, so an Escape at a continuation prompt or readline() landing in it was sent as an interrupt the dispatch swallowed. The listener now waits out a 50ms dispatch grace while the same dispatch stays active and then decides (http_methods::idleEventsPastDispatch, a4b027c and 1d1d1fc); the main-thread sites use the non-blocking grace-based processingIdleEvents() through isRunningCode().
| if (active) | ||
| state.busyDelay = idleEventBusyDelay(); | ||
| setIdleEvents(state); | ||
| } |
There was a problem hiding this comment.
Minor: this constructor runs on every waitForMethod iteration (every 50 ms while idle), so idleEventBusyDelay() does an Rf_install plus a linear scan of base's .Options pairlist about twenty times a second forever, for a value that is almost never set. Cheap (no R eval), but it could be read lazily in polledEventHandler when the report is first considered, or cached and refreshed when the report is (re)armed.
There was a problem hiding this comment.
Now read lazily in polledEventHandler the first time the report is considered, once per dispatch (ce733ea). An idle session never reads it.
|
|
||
| test('a read opened by a callback gets its own prompt, and the REPL prompt returns after it', async ({ rstudioPage: page }) => { | ||
| // The prompt sits in the cell before the input's, in the shell's input row. | ||
| const promptText = () => page.evaluate(() => |
There was a problem hiding this comment.
Nit: this promptText closure is defined identically in four tests (here, L229, L257, L295). Worth hoisting to module scope or console_pane.page.ts, since it encodes the console input row's DOM structure.
There was a problem hiding this comment.
Hoisted to getConsolePromptText in console_pane.page.ts (571ce73).
| const consoleInput = page.locator(CONSOLE_INPUT); | ||
| // The interrupt's console reset discards queued input under this pref | ||
| // (its default); the test relies on that, so say so. | ||
| await setPref(page, 'discard_pending_console_input_on_error', true); |
There was a problem hiding this comment.
Coverage: the interrupt is the only bufferClears trigger exercised, and only with discard_pending_console_input_on_error = true. Two paths are untested: an uncaught error in a callback with input queued (the other clear path, which is reachable, see the processIdleEvents comment), and an interrupt with the pref off, where queued input must survive and run. One test each, mirroring this one, would pin both.
There was a problem hiding this comment.
Added in 571ce73: an error with input queued under the pref (discarded, prompt back), an error with the pref off (input kept and run), and an error with nothing queued (no prompt reissued, which is the regression test for your first finding). I did not add the interrupt-with-pref-off case: the interrupt RPC handler clears the queue unconditionally regardless of the pref (that predates this PR), so queued input never survives an interrupt. The pref only governs R's own console reset, which the error tests cover.
There was a problem hiding this comment.
Thanks for the three error-path tests. One correction on the interrupt case, not blocking: the kInterrupt branch in handleConnection that clears the queue unconditionally is unreachable for client interrupts. The listener's checkForInterrupt (SessionHttpConnectionListenerImpl.hpp:423, and the named-pipe twin) consumes every interrupt request before it can reach the main queue, the offline queue, or the listener's direct dispatch. So the clear you see on interrupt comes from R's onintr -> jump_to_top_ex -> R_ResetConsole -> rConsoleReset, which the discard pref does govern. With the pref off, input queued behind a callback survives an interrupt and runs at the next prompt; that path is live and still untested. Fine to leave for a follow-up given the error tests cover the same mechanism.
An uncaught error in a callback with input queued (discarded under the pref, kept and run without it), and with nothing queued, where no prompt may be reissued. The prompt-text closure moves to console_pane.page.ts.
…iscarded The prompt was reissued whenever the input queue had been cleared while the handlers ran, but R's console reset runs on every uncaught error with the discard pref on, queue empty or not: a later callback that errored at an idle prompt reissued a prompt for no command. It was also reissued inside the registered waits a command runs (dialogs), where the current prompt is the enclosing read's or none. Count clears that found input separately, and restore the prompt only on behalf of a console read; a held request discarded by a reset gets its prompt from waitForMethod. Also: drop the local console_input buffering in polledEventHandler, whose registered handler already queues it on the same path (console_input is not a registered wait); share the running-code predicate as console_input::isRunningCode(); read the busy-delay option once a handler has run long enough for the report to matter, not on every dispatch.
…ivity A wait for the client inside an RPC's R code (an addin's dialog) has no console input executing, so a long idle handler during it reported R busy with no prompt to follow and the console stayed busy after the dialog closed. The report now applies only when the handlers run for a console read. Requests served while a handler runs reset the suspend timeout, as the foreground path does: input queued and then discarded by an interrupt is never handed back, so nothing else kept an idle suspend from following a handler that outlasted the timeout. The error-path tests assemble the error message so the echoed command cannot satisfy the wait for it.
client_init served while an input handler runs posted busy=true for the reloaded client, whatever the wait the handler ran for; inside a dialog wait nothing cleared it afterwards. It is now answered with that wait's own init: the waiting read's prompt, or the dialog's event again, as waitForMethod answers it. A reissued prompt re-arms the busy report, so a handler that runs on is reported busy again.
…dler A request served while an input handler runs sees R busy (isAtTopLevel() is false inside executeSafely): a notebook chunk execution defers to the next console prompt, which a callback that returns before the busy report never produced, so the chunks sat queued until another command ran. Before this PR such a request was served after the handler, at the prompt. Count requests served and reissue the waiting read's prompt for them. A prompt issued mid-handler -- a reload's client_init answered with the waiting read's prompt -- reported R busy the same way; reissue it too, so the console and the chat pane are not left waiting.
gtritchie
left a comment
There was a problem hiding this comment.
Both rounds of changes check out against the new head (ce733ea): the prompt is now restored only for a console read and only when input was actually discarded, the duplicate bufferConsoleInput path is gone, the busy predicate is in one place, the option is read lazily, and the new error-path tests cover the clear-on-error mechanism including the no-prompt regression. Leaving the chat-module helper separate is fine given the two operations differ.
One note, not blocking (details on the thread): the interrupt-with-pref-off path is live, since the handleConnection interrupt branch is never reached for client interrupts and R's console reset is what governs the discard, so queued input surviving an interrupt with the pref off remains untested.
…g code A prompt reissued when the handlers return while console input is pending for the read -- input queued during a callback, or a notebook chunk's code, which is console input too -- read as the end of a command that had not run: the notebook queue finishes the chunk on the prompt, dropping its output capture. Reissue nothing while input is pending; that input prompts when done. The listener counted any active dispatch of the handlers as R running code, including the microseconds spent finding no callback due, twenty times a second. An Escape at a continuation prompt or a readline() landing there became an interrupt the dispatch swallowed, with the read still waiting, instead of the cancel it should be. The handlers count as running code only after a 50ms grace.
…terrupt A console_input request the wait already holds (a notebook chunk's code arrives as one) is input about to run as much as queued input is, so no prompt is reissued ahead of it either; the restore after a discarded held request stays. The listener's grace left an Escape in the first 50ms of a real callback answered "not busy": the client then sent a cancel, which was queued while the callback ran on, and a second Escape was needed. The listener now waits the grace out while the same dispatch stays active and then decides: still active, it is a callback and the interrupt goes through; returned, it was the dispatch alone and the read is cancelled. The queued-input test releases the callback by flag once both submissions are confirmed queued, rather than racing a sleep.
…unks itself A prompt reissued because a request was served mid-handler could not be made safe: a notebook chunk's console_input may still be in flight, in the connection queue, or held, and the queue takes any prompt for the end of the chunk, dropping its output capture. It also fired whenever two RPCs were in flight at an idle prompt, resetting the console's history position. Drop that trigger. The notebook queue, deferring with no unit in flight because R was mid-handler, now retries once R idles instead of waiting for a console prompt that is not coming; it never processes with a unit in flight, whose code completes on the prompt that follows it. Requests are served from the polled event handler only once a dispatch has outlasted the grace, so the dispatch alone, twenty times a second, does not count as a callback. The listener looks at executing() again after waiting a dispatch out: the handlers may have returned to a read that took queued input and started a command meanwhile.
… well The wait dequeues the console_input it is for before the idle handlers run and hands it over after; in between it was pending input to the handlers' return only, by a flag passed along. A deferred notebook chunk's idle retry ran in that interval too, sent the chunk's code, and the held command then prompted before that code was read, which the queue took for the end of the chunk. Held input now counts as pending input for everyone (console_input::hasPendingInput), and the retry waits for the console to be free of it; the prompt after pending input resumes the queue as before. The no-prompt test submits its follow-up only after the callback has announced its return, so pending input cannot hold a prompt back and mask the assertion.
…odule The held-input flag made a read nested in an input handler take the enclosing wait's request as pending: it returned to rConsoleRead with nothing queued, which popped an empty queue. The hold is now a depth that nests with the reads, the hand-back looks at queued input only, and the hold is taken before background processing runs the notebook queue's retry, not after. A reissued prompt no longer runs the module prompt hook. To modules a prompt marks the REPL done evaluating input -- the notebook queue finishes a chunk on it -- and nothing was evaluated; a chunk whose code was still on its way to the console was taken for done. Deferred chunks resume by the queue's own retry. The busy delay is bounded below by the dispatch grace: the polled event handler runs in the dispatch itself, and a delay of zero reported every one of them busy, with a prompt each.
…again A language switch queued behind an idle-loop callback and discarded by an interrupt left the console's projected language standing, with no prompt to clear it: the next Python submission would have skipped the switch. The projection is dropped when the queue has been cleared since it was made. The notebook queue's retry, blocked by pending input, schedules itself again rather than counting on that input's prompt, which an answer held for a callback's read never produces. The e2e suite releases every flag-gated callback in teardown, so a test that fails before releasing its own does not leave the cleanup queued behind it.
…oss a read Dropping the projected language on a queue clear forgot a switch still on its way through the console input service: adapted back to R before it landed, the console omitted the quit and the late switch put it in Python. The projection is the prompt's to clear again; a switch queued and then discarded behind an idle-loop callback leaves it standing until the next prompt, which the next submission's error produces. A chunk deferred while a callback runs, where the callback then reads from the console: the chunk runs once the answer ends the callback, without another console command.
|
Pushed ten further commits (53c5a7b..f9c79f1) from a review-fix loop on top of the review-1 fixes. The substance:
The e2e spec is at 19 tests (two notebook tests need rmarkdown/knitr). |
The environment module refreshed whether the global environment can be serialized in its prompt hook only. A prompt reissued after R ran code from the idle loop runs no prompt hook, so an external pointer a callback created left the session counted suspendable until the next command. The refresh moves to the detect-changes event for the REPL source, which both a real prompt and a reissued one fire -- once per prompt, as before.
The inspection that follows a prompt runs user code (a length() or str() method), which may itself create an external pointer; the refresh ran ahead of it and cached the session as suspendable. It now runs after, monitoring or not.
Modules learn of a user interrupt from onUserInterrupt, which nothing emitted. An interrupt during a command is followed by that command's prompt, which the notebook queue acts on; one that ends an idle-loop callback is followed by no module prompt, so a chunk queued behind the callback stayed queued and ran on the next retry, and one whose code R's console reset discarded stayed in flight with its output capture and working directory in place. The listener (and the queued interrupt handler) note an interrupt accepted for the handlers, and their return emits onUserInterrupt; the notebook queue drops its work, as the client drops its own queue on an interrupt.
…back's read Input discarded by R's console reset without an interrupt (a callback's uncaught error, with the discard pref on) is reported to modules as a user interrupt as well: a notebook chunk whose code it was is gone, and its context would otherwise stay in place. An interrupt accepted while the handlers run is noted whether or not the console counts as executing, which it does once a read a callback opened was answered. A held request that fails validation at hand-over (a reload meanwhile changed the client) reissues the prompt it kept back. The notebook queue's clear() drops its context after disconnecting it, so the destructor's clear() does not disconnect it again.
…andlers run A held console_input request discarded by a reset that found the queue empty was reported to no module, so a notebook chunk whose code it was kept its context. It is reported like discarded queued input. An interrupt is noted as the handlers' whenever they are active, grace or no grace: after a read a callback opened was answered the console counts as executing and the dispatch is young again, and the interrupt went unnoted.
A read nested in a running command (a notebook chunk's option evaluation asking the console) may have the module's own code on the stack below it; reporting an interrupt from its wait had the notebook queue delete itself under that code. The command's own abort and prompt report an interrupt there; the handlers' return reports one only for the top-level read with nothing executing.
A user interrupt reported while the queue's code is on the stack (a chunk's option evaluation asked the console, and the idle loop ran an interrupted callback during that read) had the queue delete itself under that code. Calls into the queue are now scoped; an interrupt during one marks the drop, which the last scope to unwind carries out, and the unit on the stack sends nothing further. With that, the handlers' return reports an interrupt from any wait, nested or not -- a read nested in a command clears executing() on entry, so no gate on it told the two apart. Unit test: an external pointer in the global environment makes the session unsuspendable on the next return to the prompt, and suspendable again once removed.
The handlers' return reported an interrupt to modules so that the notebook queue would drop chunks queued behind an interrupted callback. The queue was never built to be dropped from under its own code, and making it so kept finding another path: a read nested in chunk-option evaluation, an R error unwinding past the scope guard, an asynchronous engine's completion. The client already drops its chunk queue on an interrupt and sends the deletions to the server, so the server-side report is withdrawn, with the guard machinery and the two tests that depended on it. What stays: deferred chunks resume by the queue's own idle retry; clear() drops its context once; a held request rejected at hand-over reissues the prompt it kept back.
The notebook queue's idle retry ran a chunk the client had dropped on an interrupt meanwhile, since the client's drop does not reach the server (#19257). Until it does, a chunk whose execution request was served while a callback ran waits for the next console command, as it did before this change.
A language switch queued behind an idle-loop callback and discarded by an interrupt or a callback's error left the projection standing, with no prompt to clear it: the next Python submission skipped the switch and ran in R. The projection is dropped when input has been discarded since it was made. A switch still on its way to the buffer is forgotten with it for the few milliseconds before it lands; tracking the switch itself is #19258.
A browser() a callback entered marked a browser active from its Browse[N]> read. The callback returned past it, and the top-level read that would clear the mark is the one already waiting, so quitting was refused until the next command. The mark is cleared with the other flags a handler's own read leaves behind. The environment module's debug state still follows at the next REPL prompt (#19259).
|
Pushed a further set of commits (2ceca05..56684c8) after merging origin/main and a second review-fix loop. The substance:
The e2e spec is at 17 tests. |
Fixes #19236.
Problem
R code run from the idle event loop -- a
later::later()callback, e.g.shiny::runApp()scheduled that way -- left the session deaf until the callback returned. The IDE looked idle (no busy indicator), but console input never executed, preference writes and every other RPC hung, a browser reload never got pastclient_init, and the interrupt did nothing. The only recovery was killingrsession. This is the general form of #17178 (fixed for one entry point by #17908), and it took out a CI shard in #19226 when the Posit Assistant chose this launch style "to keep the console free".Cause
While R is at the prompt,
waitForMethod()runs R's input handlers (which is howlatercallbacks run) between dequeues, so a long-running handler keeps it from dequeuing. The other drain,polledEventHandler(), only served requests whileconsole_input::executing()was true, and that flag stays false because the console is at its prompt. The listener thread'scheckForInterrupt()and the main thread's interrupt handler were gated on the same flag, so interrupts were dropped too.Fix
Track "R is running an input handler dispatched from the idle loop" as its own busy state (
SessionHttpMethods.cpp), scoped around the idle loop'sprocessEvents()call and suspended while a nested wait for the client runs its own loop:polledEventHandler()serves queued requests while the handlers have run for longer than the dispatch itself takes (a 50ms grace: the dispatch runs twenty times a second and nearly always returns at once). Console input that arrives then is queued for the prompt by its registered handler, as input typed ahead of a running command is, andwaitForMethod()hands it torConsoleRead()once the handler returns. Requests served this way reset the suspend timeout, as foreground requests do.readline()or a continuation prompt has to become a cancel of that read.rstudio.idleEventBusyDelay, seconds, bounded below by the grace and above by a day), the client is told R is busy, which shows the interrupt button -- only when the handlers run for a top-level console read with no console input executing; a dialog wait inside a command or an RPC's R code has no prompt to clear it with. busy=false and the waiting read's prompt follow when the handler returns.waitForMethod()itself would answer it.An interrupted callback ends with
later's own "later: exception occurred while executing callback." message, as it does in a terminal R session.Design notes (from the review rounds)
readline()) replaced the waiting read's prompt or took input the client had submitted; input the client queued was discarded (an interrupt, or an uncaught error with the discard pref on); or a reload'sclient_initwas answered with a prompt that reported R busy. Not on an error that found nothing queued, not inside a dialog wait, and never ahead of pending input, queued or held -- that input prompts when it runs. The reissued prompt is a client event only: the module prompt hook marks the REPL done evaluating input (the notebook queue finishes a chunk on it), and nothing was evaluated.console_inputthe wait dequeued just before a long handler is held across it (areadline()a handler opens must not take it; an interrupt discards it like queued input) and handed over ahead of input the handlers queued. Held input counts as pending input, nesting with reads.onDetectChangesfor the REPL source), so an external pointer a callback created is seen.Known limitations, with follow-ups
browser()inside a callback returns, the Environment pane's debug frame follows at the next REPL prompt, not the reissued one: Environment pane keeps a callback's debug frame after browser() returns inside an idle-loop callback #19259.Testing
tests/panes/console/idle_event_loop_callback.test.ts(17 tests), passing in server mode locally and in CI: requests are served and the interrupt works while a callback runs; a reload mid-callback gets its prompt back and is reported busy again, also when the callback returns before the report; a request served during a short callback leaves the prompt alone; input sent during a callback runs, in order, with no prompt ahead of it; Escape at a continuation prompt cancels it while idle; an interrupt before the busy report discards queued input and returns the prompt; an uncaught error discards queued input (pref on), keeps it (pref off), and reissues no prompt with nothing queued; a zero busy delay reports nothing; a callback'sreadline()gets its own prompt and the REPL prompt (not busy) returns after it, also when the callback runs on afterwards, when busy was reported before the read, and when the read takes input that was already queued.EnvironmentSuspendabilityTest: an external pointer in the global environment makes the session unsuspendable on the next return to the prompt.later::later(function() shiny::runApp(...), 1)now shows R busy within a second, a fresh browser load is served while the app runs, typed input is queued rather than lost, and the interrupt button stops the app. Before the fix the same session had to be killed.