Skip to content

allocate the console scrollback as output arrives - #19750

Merged
kevinushey merged 12 commits into
mainfrom
feature/19738-console-actions-space-optimized
Nov 23, 2026
Merged

kevinushey merged 12 commits into
mainfrom
feature/19738-console-actions-space-optimized

Conversation

@kevinushey

@kevinushey kevinushey commented Nov 20, 2026 •

Copy link
Copy Markdown
Collaborator

Intent

#19738 asked whether the backend's other boost::circular_buffers should follow ConsoleHistory (#19691) to boost::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) in boost/circular_buffer/base.hpp). ConsoleActions' capacity is the console_max_lines pref: 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:

  • macOS: 305 MB of address space, with no change in resident memory or footprint until slots are written.
  • Linux (Docker, overcommit_memory=1): VmSize up by 390 MB, VmRSS unchanged.
  • Windows (not measured; the heap commits large allocations): the whole capacity counts against the system's commit limit as soon as the pref is applied.

Where the OS refuses the allocation, rset_capacity() throws std::bad_alloc. That happens on Windows past the commit limit, and on Linux past RAM + swap under the default heuristic overcommit. setCapacity()'s END_LOCK_MUTEX catches 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() and rset_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, and clear() (reset()) shrinks it. The trade-offs:

  • Each doubling moves the stored actions. ConsoleAction's move is noexcept, so these are moves, not copies.
  • A doubling happens inside flush() with mutex_ held, and ClientEventQueue::flushBufferedOutput() calls add() 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.
  • On macOS the allocator kept the freed growth blocks for reuse, so footprint at a given fill was about 2-3x the plain buffer's: 0.9 vs 0.3 MB at 10,000 actions, 63 vs 31 MB at 1,000,000. At the default limit that's under a megabyte.

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 to size_t.

The other buffers stay as they are, as the issue's table suggested. PlotManager::plots_ holds 100 pointers and ViewerHistory::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()'s capacity() + 1 overflowed at exactly INT_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 new consoleOutputLineLimit() adds 1 only below INT_MAX. Its static_assert at INT_MAX makes an overflowing version a compile error, because signed overflow isn't a constant expression.

trimLeadingLines(), which also trims saved terminal buffers:

  • It skipped any buffer of at most twice the line limit in bytes, assuming at least two bytes per line. Output that was mostly blank lines therefore kept more lines than the limit. It now skips only buffers of at most the limit in bytes.
  • It counts lines in size_t, so it no longer doubles the limit in int, which overflowed above about 1.07 billion.
  • It ignores a negative limit.
  • It returns false when the cutoff is the start of the buffer and there's nothing to remove. Otherwise 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 a BOOST_SCOPE_EXIT removes 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 the std::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 empty type and data arrays 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, and add() still drops the incoming output in that case, as it did before this PR.

Cleanup. Removes the unused <boost/circular_buffer.hpp> includes from SessionLists.cpp and SessionConsoleProcess.hpp.

Automated Tests

New rsession gtests in SessionConsoleActionsTests.cpp:

  • HugeCapacityIsNotAllocatedUpFront: a capacity of INT_MAX takes 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: at INT_MAX, three lines of output sent through the real clientEventQueue() 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. The static_assert on consoleOutputLineLimit() is what rejects the overflow.
  • ConsoleActionsGrowthTest.FailedGrowthKeepsTheNewestActions: drives pushConsoleAction() 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: after clear(), a push whose allocation is refused throws and leaves the capacity at INT_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 at INT_MAX.

New core gtests in StringUtilsTests.cpp:

  • TrimLeadingLinesKeepsTheLastLines: the basic case.
  • TrimLeadingLinesTrimsBlankLines: "old\n" followed by 10 newlines, with a limit of 10, loses old; 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 of INT_MAX or -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 ChildprocessTest polling tests in ChildProcessSubprocPollTests.cpp, which passed when re-run on their own.

QA Notes

  1. In Tools > Global Options > Console, set "Maximum lines of output to keep in the console" to 2147483647. Run print(1:100): all of the output should appear, and should still be there after reloading the browser (Server) or the window (Desktop).
  2. On Windows, set the limit to 1000000000 and 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.
  3. With the default limit (10,000), the Console and its restore after a reload should behave as before.

Documentation

None needed.

Checklist

  • If this PR adds a new feature, or fixes a bug in a previously released version, it includes an entry in NEWS.md
  • If this PR adds or changes UI, the updated UI meets accessibility standards (n/a: no UI)
  • A reviewer is assigned to this PR (if unsure who to assign, check Area Owners list)
  • This PR passes all local unit tests

ConsoleActions now keeps its actions in a boost::circular_buffer_space_optimized, as ConsoleHistory does since #19691, so the console_max_lines capacity is no longer allocated up front. Also drops two unused <boost/circular_buffer.hpp> includes.

Addresses #19738.
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.
@kevinushey kevinushey added this to the 2026.12 (Parrot Balsam) milestone Nov 20, 2026
@kevinushey
kevinushey requested a review from gtritchie November 20, 2026 02:41
… 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.
@github-actions

github-actions Bot commented Nov 20, 2026 •

Copy link
Copy Markdown

RStudio E2E - all platforms

All tests passed!

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

Passed Failed Skipped Flaky
5795 0 276 5
Platform ✅ Passed ❌ Failed ⚠️ Skipped 🔁 Flaky
✅ auth-teardown 4 0 16 0
✅ desktop-linux 1455 0 49 1
✅ desktop-macos 1452 0 54 0
✅ desktop-windows 1437 0 71 3
✅ server-linux 1399 0 54 1
✅ setup 48 0 32 0

View report online


All platforms - commit 95aad47d5b0964c4310190004ffb660040fef0fa - Run #2482

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

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

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.

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 in flush(). END_LOCK_MUTEX logs it, and the incoming prompt or input is dropped;
  • same-type output collects in buffer_.data and never drains;
  • asJson() returns {}, so a browser reload (client init treats an initialized session as resumed) shows no history, and saveToFile() 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.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

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_;

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.

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.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

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)

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.

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.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

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.
@kevinushey

Copy link
Copy Markdown
Collaborator Author

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:

  • SessionClientInit.cpp:344: fixed in the same commit. asJson() now assigns empty type and data arrays before flush(), so the resume message has arrays to append to if the flush throws. There's no test for it, since nothing can make that flush throw without a hook in production code.
  • getConsoleLines(): agreed, and left out of this PR. I'm handling it as a separate change.

The description is updated to match. On Windows (debug build) the rsession gtests pass (916; 3 skipped). Core passed 755 with 5 skipped; two ChildprocessTest polling tests in ChildProcessSubprocPollTests.cpp failed in the full run and passed when re-run on their own.

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

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());

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.

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.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

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.

kevinushey and others added 4 commits November 20, 2026 15:08
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.
@kevinushey
kevinushey merged commit 6e99a6e into main Nov 23, 2026
1 of 7 checks passed
@kevinushey
kevinushey deleted the feature/19738-console-actions-space-optimized branch November 23, 2026 22:39
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.

Evaluate circular_buffer_space_optimized for the console scrollback and other circular buffers

2 participants