Repository navigation
allocate the console scrollback as output arrives - #19750
Conversation
At console_max_lines = INT_MAX, ClientEventQueue's capacity() + 1 wrapped and trimLeadingLines() cut each batch of console output down to its last newline; trimLeadingLines() also doubled maxLines in int. Corrects the NEWS claim that a refused reservation kept the session from starting (setCapacity() logs the failure and keeps the old limit), and restores the scrollback capacity in the test fixture. Addresses #19738.
… output trimLeadingLines() skipped buffers of up to twice maxLines bytes, assuming at least two bytes per line, so output that was mostly blank lines kept more lines than the limit; it now skips only buffers of at most maxLines bytes, and counts lines in size_t. ConsoleActions::flush() erased the data it had pushed only after pushing all of it, so a push that threw (e.g. std::bad_alloc as the actions grow) left that data in the buffer for the next flush to push again. The erase now runs on every exit, and covers only the data actually pushed. Addresses #19738.
trimLeadingLines() now ignores a negative limit, so a limit that wrapped to INT_MIN would keep all output and the queue test couldn't see it; a static_assert on a constexpr helper rejects the overflow instead. Addresses #19738.
RStudio E2E - all platformsAll tests passed!
All platforms - commit |
gtritchie
left a comment
There was a problem hiding this comment.
One blocking issue, inline on RConsoleActions.cpp: if a growth allocation fails, the scrollback stays broken until it's reset. The other inline comments are minor. Two related issues are on lines this PR doesn't touch, so I've put them here.
SessionClientInit.cpp:344 (pre-existing, more reachable now). asJson() clears pActions before flush(), so if the flush throws it leaves {}. On a reload or resume with a non-empty getResumedMessage(), this line then calls actionsObject["data"].getArray().push_back(...) on a member that operator[] has just created as null. RAPIDJSON_ASSERT is the default assert(), so debug builds abort. Release builds most likely leave the value null and send "data": null, and RpcObjectList.length() then reads null.length in Shell's playback. This could already happen when a string allocation failed, but the growth failure below makes it persistent. Assigning empty type/data arrays in asJson() before flush() would avoid it.
RConsoleActions.cpp:380 (pre-existing, more reachable now). getConsoleLines() concatenates every action, strips ANSI codes and splits the whole scrollback into lines while holding mutex_, then keeps limit of them. Posit Assistant's runtime/getConsoleContent (SessionChat.cpp:3598) calls it with a default of 50 lines. With this PR, huge limits take effect on Windows and on Linux under heuristic overcommit, not just macOS, so each request can copy millions of lines. Fine as a follow-up; walking actions_ from the requested end and stopping at limit/maxChars would fix it.
| // iterate over buffer data in chunks, split via newlines | ||
| // remove the data pushed as actions, retaining any held-back suffix for | ||
| // the next add(); also when a push throws (e.g. std::bad_alloc as the | ||
| // actions grow), so that the next flush doesn't push that data again |
There was a problem hiding this comment.
When a growth allocation fails here, it fails again on every later flush. In Boost 1.91, push_back() calls check_low_capacity(), which works out the new capacity from size() and the internal capacity. A failed set_capacity() changes neither, so each later push asks for the same block.
From then on:
- each
add()that changes type throws inflush().END_LOCK_MUTEXlogs it, and the incoming prompt or input is dropped; - same-type output collects in
buffer_.dataand never drains; asJson()returns{}, so a browser reload (client init treats an initialized session as resumed) shows no history, andsaveToFile()saves an empty replay.
Before this change, the big allocation failed once in setCapacity() and the old limit stayed. Getting here takes a huge limit and tens of millions of actions (e.g. 1e9 on Windows: the 2^26 to 2^27 doubling needs a new ~5 GB block while the old ~2.7 GB one is live), so it's rare. But once it happens, it doesn't recover.
Suggestion: in pushAction(), catch std::bad_alloc from the push, pin the capacity with actions_.rset_capacity(actions_.size()) so the buffer acts as a full ring from then on, log it once, and push again.
There was a problem hiding this comment.
Agreed, and I confirmed it against check_low_capacity() in 1.91. Fixed in 7e536ac the way you suggested: pushConsoleAction() catches the std::bad_alloc, calls rset_capacity(size()) and pushes again. That call allocates nothing, because the storage is always full when a growth is attempted and set_capacity() returns early for an unchanged capacity. The failure is logged once per pin, and loadFromFile() adds its actions through the same helper.
One side effect: capacity() reports the lowered limit until the pref is next applied.
The helper is a template on the allocator, so there's now a test for it. ConsoleActionsGrowthTest.FailedGrowthKeepsTheNewestActions uses an allocator that refuses blocks of more than 100 actions and checks that the newest actions are kept in order, that later pushes don't allocate again, and that setting the capacity again lets the storage grow.
|
|
||
| // allocates as actions are added rather than its whole capacity up front: | ||
| // the capacity is the console_max_lines pref, which has no maximum | ||
| boost::circular_buffer_space_optimized<ConsoleAction> actions_; |
There was a problem hiding this comment.
Minor: each doubling allocates a new block and moves every ConsoleAction into it inside flush(), while mutex_ is held. ClientEventQueue::flushBufferedOutput() calls capacity() and add() while holding the queue's own mutex, so at tens of millions of actions one doubling can pause console output for a while. The plain buffer spread that page-fault cost across individual writes instead. I haven't measured it, and it may be fine to accept, but it's worth adding to the trade-offs in the description.
There was a problem hiding this comment.
I measured it and added it to the trade-offs in the description. In a standalone release build against Boost 1.91 on Windows (40-byte actions), one doubling took about 36 ms per million actions held:
| Actions held | Pause for one doubling |
|---|---|
| 1.0 million | 34 ms |
| 4.2 million | 161 ms |
| 16.8 million | 606 ms |
| 33.5 million | 1,447 ms |
Below 262,144 actions, which includes the default limit, no push took more than 5 ms. The plain buffer's slowest push over the same 33.5 million was 170 ms.
I've left the behavior as it is, since the pause only shows at limits far above the default.
| EXPECT_EQ("line 999\n", dataArray[999].getString()); | ||
| } | ||
|
|
||
| TEST_F(ConsoleActionsTest, HugeCapacityKeepsQueuedConsoleOutput) |
There was a problem hiding this comment.
Minor: this test no longer catches the queue overflow by itself. If flushBufferedOutput() went back to capacity() + 1, the limit wraps to INT_MIN in practice, and trimLeadingLines() now returns false for any negative limit, so the test still passes. The static_assert checks the helper but not that the call site uses it. The description's "Before the queue fix it failed" no longer holds, so I'd update that, or add a direct check of consoleOutputLineLimit.
There was a problem hiding this comment.
You're right. With capacity() + 1 the limit goes negative and trimLeadingLines() ignores it, so no test at INT_MAX can see that regression, and a direct test of consoleOutputLineLimit() wouldn't check the call site either.
I've corrected the description instead of adding a check: the test is now described as an end-to-end check of output at INT_MAX, and the static_assert as what rejects the overflow.
A failed growth left the actions buffer's size and storage unchanged, so every later push asked for the same allocation and failed with it: prompts and input were dropped, output collected in the pending buffer, and the replay came back empty. The push now lowers the capacity to the actions held, so the buffer drops its oldest action for each one added, until the capacity is next set. asJson() also provides its 'type' and 'data' arrays before it flushes, so client init doesn't index into a missing array when the flush throws. Addresses #19738.
|
Thanks for the review. The growth failure is fixed in 7e536ac, and the inline comments are answered in their threads. On the two points outside the diff:
The description is updated to match. On Windows (debug build) the rsession gtests pass (916; 3 skipped). Core passed 755 with 5 skipped; two |
gtritchie
left a comment
There was a problem hiding this comment.
Thanks, the growth failure and the client-init case are both fixed, and the description covers the rest. One non-blocking nit inline.
|
|
||
| // the storage is full, or it wouldn't have had to grow; a capacity equal | ||
| // to it is one that neither this nor the push below allocates for | ||
| actions.rset_capacity(actions.size()); |
There was a problem hiding this comment.
Nit, non-blocking: since capacity() returns the pinned size, the pin also sets the queue's per-batch trim (consoleOutputLineLimit) and, after a reload, the client's visible-line limit (console_actions_limit), for the rest of the session. At realistic sizes that's harmless, because the pin is at least half the size where growth failed.
The edge case is after reset(). clear() shrinks the storage to 0, so if the first allocation after a Console clear fails, size() is 0 and the pin is 0. From then on nothing is stored, consoleOutputLineLimit(0) is 1, and every output batch is cut to its last line until the pref changes. That takes a failed 80-byte allocation, so it's unlikely. Keeping the requested limit in its own member for capacity() to return, and not pinning when size() is 0, would avoid it.
There was a problem hiding this comment.
Fixed in 3186b38, as you suggested. capacity() now returns the limit last set, kept in its own member, so lowering the buffer's limit only affects how much scrollback is kept. On an empty buffer, pushConsoleAction() rethrows the std::bad_alloc instead of lowering the limit to 0, and flush() keeps that output pending for the next try. FailedGrowthAfterClearKeepsTheCapacity covers the clear() sequence.
When the actions buffer's storage couldn't grow, capacity() reported the lowered limit, so it also set the console output queue's per-batch trim and the client's line limit after a reload. After reset(), which frees the storage, a failed first allocation lowered the limit to 0: nothing was stored again, and every output batch was cut to its last line, until the pref next changed. capacity() now reports the limit last set, and pushConsoleAction() rethrows the std::bad_alloc when the buffer is empty, so a later push tries the allocation again. Addresses #19738.
Intent
#19738 asked whether the backend's other
boost::circular_buffers should followConsoleHistory(#19691) toboost::circular_buffer_space_optimized. This PR switches the Console scrollback (ConsoleActions), keeps the other three as they are, and removes two unused includes.Fixes #19738.
Approach
What the plain buffer costs.
circular_buffer::rset_capacity()allocates the whole capacity at once (allocate(new_capacity)inboost/circular_buffer/base.hpp).ConsoleActions' capacity is theconsole_max_linespref: default 10,000, no maximum, 32 bytes per slot with libc++ and 40 with libstdc++ or MSVC. What that up-front allocation costs depends on the platform. I measured it in a standalone program against Boost 1.91 at a capacity of 10,000,000:overcommit_memory=1):VmSizeup by 390 MB,VmRSSunchanged.Where the OS refuses the allocation,
rset_capacity()throwsstd::bad_alloc. That happens on Windows past the commit limit, and on Linux past RAM + swap under the default heuristic overcommit.setCapacity()'sEND_LOCK_MUTEXcatches and logs it, and the previous limit stays in effect. So a limit meant as "unlimited" silently left the replay at the constructor's 1,000 actions, or at the previous value.The switch. The space-optimized buffer's
set_capacity()andrset_capacity()only record the limit, trimming the oldest entries when it's lowered, as before.push_back()grows the storage by doubling up to the limit, andclear()(reset()) shrinks it. The trade-offs:ConsoleAction's move is noexcept, so these are moves, not copies.flush()withmutex_held, andClientEventQueue::flushBufferedOutput()callsadd()while holding the queue's own mutex, so Console output waits for the move. In a standalone release build against Boost 1.91 on Windows (40-byte actions), one doubling took about 36 ms per million actions held: 34 ms at 1.0 million, 161 ms at 4.2 million, 606 ms at 16.8 million and 1,447 ms at 33.5 million. Below 262,144 actions, which includes the default limit, no push took more than 5 ms. The plain buffer's slowest push over the same 33.5 million was 170 ms.A maximum on the pref would also work, but it's a schema change that has to deal with larger values users have already saved, and #12264 (virtualized console output) points toward larger scrollback, not smaller.
capacity()is unchanged: the space-optimized buffer's capacity object converts tosize_t.The other buffers stay as they are, as the issue's table suggested.
PlotManager::plots_holds 100 pointers andViewerHistory::entries_holds 20 entries.ConsoleProcessInfo::outputBuffer_holds 8,192 chars and is usually full in an active terminal.An overflow this makes reachable everywhere. With huge limits now accepted on every platform,
ClientEventQueue::flushBufferedOutput()'scapacity() + 1overflowed at exactlyINT_MAX(2,147,483,647).trimLeadingLines()then cut each batch of Console output back to its last newline, so the output disappeared from both the Console and the scrollback. This already happened on macOS, where the old buffer's reservation succeeded. The newconsoleOutputLineLimit()adds 1 only belowINT_MAX. Itsstatic_assertatINT_MAXmakes an overflowing version a compile error, because signed overflow isn't a constant expression.trimLeadingLines(), which also trims saved terminal buffers:size_t, so it no longer doubles the limit inint, which overflowed above about 1.07 billion.getSavedBuffer()would rewrite an unchanged terminal log every time it read one.ConsoleActions::flush()removed the output it had pushed from its pending buffer only after pushing all of it. Now that the actions buffer allocates as it grows, a push can throw (std::bad_alloc) partway through a flush. The lines already pushed then stayed pending, and the next flush pushed them again, duplicating them in the replay. The function now advances its position only after a push succeeds, and aBOOST_SCOPE_EXITremoves exactly what was pushed on every exit.When the storage can't grow. A failed growth leaves the buffer's size and storage as they were, and Boost works out the next capacity from those two, so every later push would ask for the same block and fail with it. Prompts and input would be dropped, output would collect in the pending buffer, and the replay would come back empty. The new
pushConsoleAction()catches thestd::bad_alloc, lowers the capacity to the actions held (which allocates nothing, because the storage is full) and pushes again. From then on the buffer drops its oldest action for each one added, as it does at its limit. The failure is logged once, and the lowered limit stays until the pref is next applied.capacity()still reports the pref's value, which the output queue trims each batch to and the client uses as its line limit. If the buffer is empty when growth fails, as just after a Console clear frees its storage,pushConsoleAction()rethrows instead, since a limit of 0 would store nothing again; the next push tries the allocation again.loadFromFile()adds its actions the same way.asJson()now provides emptytypeanddataarrays before it flushes. If the flush throws, client init's resume message then has arrays to append to, where before it indexed into an empty object. A flush can still throw on a string allocation, andadd()still drops the incoming output in that case, as it did before this PR.Cleanup. Removes the unused
<boost/circular_buffer.hpp>includes fromSessionLists.cppandSessionConsoleProcess.hpp.Automated Tests
New rsession gtests in
SessionConsoleActionsTests.cpp:HugeCapacityIsNotAllocatedUpFront: a capacity ofINT_MAXtakes effect, and 1,000 actions added afterwards, through several growth steps, are all kept in order. With the old buffer, the capacity assertion fails wherever the OS refuses the 64-80 GiB reservation (Windows, or Linux with less RAM + swap than that). macOS reserves it lazily, so there the test passes either way.HugeCapacityKeepsQueuedConsoleOutput: atINT_MAX, three lines of output sent through the realclientEventQueue()reach both the client event and the scrollback intact. This checks the path end to end, but it doesn't catch the queue overflow by itself:trimLeadingLines()now ignores the negative limit an overflow would produce. Thestatic_assertonconsoleOutputLineLimit()is what rejects the overflow.ConsoleActionsGrowthTest.FailedGrowthKeepsTheNewestActions: drivespushConsoleAction()on a buffer whose allocator refuses blocks of more than 100 actions. When the growth fails, the capacity becomes the actions held and the newest ones are kept in order; 250 further pushes succeed without another allocation; and setting the capacity again lets the storage grow.ConsoleActionsGrowthTest.FailedGrowthAfterClearKeepsTheCapacity: afterclear(), a push whose allocation is refused throws and leaves the capacity atINT_MAX, and a later push is stored.The fixture now restores the scrollback capacity in
TearDown(), so a failed assertion can't leave a later test atINT_MAX.New core gtests in
StringUtilsTests.cpp:TrimLeadingLinesKeepsTheLastLines: the basic case.TrimLeadingLinesTrimsBlankLines:"old\n"followed by 10 newlines, with a limit of 10, losesold; trimming the result again returns false. Both assertions failed before the fix.TrimLeadingLinesLeavesLinesWithinTheLimit: a buffer within the limit is left alone, as it is at a limit ofINT_MAXor -1.There's no test for a flush that throws partway through, or for
asJson()when its flush throws.ConsoleActions' own buffer has no injectable allocator, and after this change a flush only throws on a string allocation, so making one fail would need a test-only hook in production code. The existing chunking, held-back UTF-8 and multi-line tests cover the normal path through the new erase.Before the last commit (the growth-failure handling), the full rsession (953) and core (903; 12 skipped for Postgres and root privileges) gtest suites passed locally on macOS. With it, on Windows (debug build): rsession passed (916; 3 skipped), and core passed 755 with 5 skipped and 2 failed. The failures were two
ChildprocessTestpolling tests inChildProcessSubprocPollTests.cpp, which passed when re-run on their own.QA Notes
2147483647. Runprint(1:100): all of the output should appear, and should still be there after reloading the browser (Server) or the window (Desktop).1000000000and restart R. The rsession process's commit size (Task Manager > Details, "Commit size" column) should not grow by tens of GB. Run something with a lot of output, e.g.for (i in 1:5000) print(i), then reload: all of it should be restored, not just the last 1,000 lines.Documentation
None needed.
Checklist
NEWS.md