Skip to content

limit only the saved history to R_HISTSIZE, as R does - #19691

Merged
kevinushey merged 10 commits into
mainfrom
bugfix/19690-r-histsize
Nov 19, 2026
Merged

kevinushey merged 10 commits into
mainfrom
bugfix/19690-r-histsize

Conversation

@kevinushey

@kevinushey kevinushey commented Nov 18, 2026 •

Copy link
Copy Markdown
Collaborator

Intent

With R_HISTSIZE=0, a setting people use to keep R from saving command history, the R session crashed at startup whenever there was a .Rhistory to load. A negative R_HISTSIZE stopped the session from starting at all (Unexpected exception: circular_buffer). Even without a .Rhistory, R_HISTSIZE=0 left the session with no command history: the History pane showed none of its commands, and the Console's command recall was empty after a browser reload.

Fixes #19690.

Approach

RStudio used R_HISTSIZE as the capacity of the session's in-memory console history. That history feeds the History pane's current-session list, the Console's recall after a reload, and what's written to .Rhistory. So a value of 0 made a zero-capacity circular_buffer. Loading .Rhistory into it at startup (ConsoleHistory::loadFromFile() -> readCollectionFromStream() -> circular_buffer::insert()) wrote through an invalid slot and segfaulted. A negative value became a huge capacity and threw.

R reads R_HISTSIZE differently. ?savehistory: it "controls the number of lines that are saved", and "there is no limit on the number of lines of history retained during a session". R reads it at the time of saving (R_setupHistory() before stifle_history() on quit, and history_truncate_file() in savehistory()), accepts 0, and ignores negative or invalid values with a warning, keeping its default of 512.

This follows R:

  • The session's history capacity is now max(512, R_HISTSIZE at startup), with no upper limit. A small value, or 0, no longer shrinks the history kept during the session, and a larger value still raises it as before. The capacity is fixed at startup, so raising R_HISTSIZE mid-session saves at most what the session kept.
  • The history is now a boost::circular_buffer_space_optimized, which allocates as commands are added. A plain circular_buffer allocates its whole capacity up front, so a value meant as "unlimited" (e.g. R_HISTSIZE=999999999) tried to allocate gigabytes at startup, on main too. setCapacity() also keeps a capacity of at least 1, so no caller can make the zero-capacity buffer that crashed.
  • New ConsoleHistory::saveToHistoryFile() writes only the most recent R_HISTSIZE commands, reading R_HISTSIZE at the time of the save. It's used for .Rhistory on quit and for savehistory(), both through the POSIX callback and through rs_saveHistory on Windows. Saving the session's state on suspend still writes the whole history, so a resumed session gets all of it back.
  • A negative or invalid R_HISTSIZE means 512, as in R, though without R's warning (main ignored invalid values silently too). Values R accepts with a size suffix (e.g. 1k) are still treated as invalid, as before; R's parser for them isn't part of its API.

The ConsoleHistory constructor is now public so the test can use its own instance, as in #19688.

Overlaps:

Automated Tests

New SessionConsoleHistoryTest.RHistsizeLimitsOnlyTheSavedHistory (rsession gtests, new file SessionConsoleHistoryTests.cpp), on its own ConsoleHistory instances:

  • R_HISTSIZE=0: the capacity is 512, a three-command history file loads (this is where the crash was), and saving clears an existing file.
  • R_HISTSIZE=2 at startup: the capacity is 512 and all three commands are kept, but saving writes only the last two. The value is read at save time, so the first history now saves two as well. The suspend snapshot (saveToFile(path, true)) still writes all three.
  • R_HISTSIZE=1000: the capacity is 1000, and 600 loaded commands are all saved.
  • R_HISTSIZE=999999999: the capacity is 999999999, and 600 loaded commands are all saved.
  • Unset, -1 and abc: a new history's capacity is 512, loading the 600-command file keeps its newest 512, and saving the 600-command history writes exactly the newest 512, in order.
  • setCapacity(0) and setCapacity(-1): the capacity is 1, and loading the three-command file keeps the last command.

Every save starts from a file holding a stale command, so a save that writes nothing can't pass. With main's setCapacityFromRHistsize() the test fails with capacity 0 and then segfaults in loadFromFile().

New test-history.R test: after loadhistory() of three commands, R_HISTSIZE=2 and savehistory() write the last two. That goes through Rsavehistory() on POSIX and rs_saveHistory on Windows; the save on quit (RCleanUp()) isn't covered.

The full rsession gtest suite (920 tests) and the R history tests pass locally (macOS, R 4.6.1).

End to end, in a macOS rsession with a two-line .Rhistory and an isolated HOME:

  • 0: starts; savehistory() writes nothing, and after Sys.setenv(R_HISTSIZE = "100") it writes the loaded and new commands.
  • -1 and abc: start normally and save the whole history.
  • On main: 0 crashed (exit 139) and -1 didn't start (exit 1).

QA Notes

  1. Put R_HISTSIZE=0 in ~/.Renviron, with a .Rhistory in the working directory, and start RStudio. The session should start, and the History pane should list the session's commands as they're run.
  2. Quit with history saving on (Tools > Global Options > General > Always save history). .Rhistory should be empty.
  3. With R_HISTSIZE=-1, RStudio should start normally.
  4. With R_HISTSIZE=3, savehistory() should write only the last three commands, while the History pane keeps the full session history.
  5. With R_HISTSIZE=999999999, RStudio should start normally, without a jump in the R session's memory use.

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

@kevinushey kevinushey added this to the 2026.12 (Parrot Balsam) milestone Nov 18, 2026
@kevinushey
kevinushey requested a review from gtritchie November 18, 2026 07:47
@github-actions

github-actions Bot commented Nov 18, 2026 •

Copy link
Copy Markdown

RStudio E2E - all platforms

All tests passed!

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

Passed Failed Skipped Flaky
4299 0 193 2
Platform ✅ Passed ❌ Failed ⚠️ Skipped 🔁 Flaky
✅ auth-teardown 4 0 10 0
✅ desktop-linux 1440 0 49 1
✅ desktop-windows 1436 0 60 0
✅ server-linux 1383 0 54 1
✅ setup 36 0 20 0

View report online


All platforms - commit 2e61c1ec31bed9ee97f20ab622d02e768d078929 - Run #2398

@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, this fixes the crash, and having R_HISTSIZE apply only at save time matches R. Comments are inline, roughly most serious first. The main one is that the session's capacity still grows with R_HISTSIZE with no upper limit (on RConsoleHistory.cpp:78). The rest are parity gaps with R, a guard on setCapacity(), test coverage, and two small cleanups.

// in R, R_HISTSIZE limits only the commands saved to a history file, not
// those kept during the session (see saveToHistoryFile()), so a smaller
// value doesn't shrink the session's history
setCapacity(std::max(kDefaultHistorySize, rHistorySize()));

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.

The session's capacity still follows R_HISTSIZE with no upper limit, and boost::circular_buffer::set_capacity() allocates the whole capacity up front (allocate(new_capacity)). With R_HISTSIZE=999999999 in ~/.Renviron (a common "unlimited" habit), startup tries to allocate 24-32 GB of std::string slots. That can fail with bad_alloc, which is the same kind of startup failure this PR fixes for negative values. A value like 10,000,000 still costs a few hundred MB.

Now that R_HISTSIZE is read at save time, the in-session capacity doesn't need to follow it closely. Could it be capped (or fixed), so a large value raises it only up to a sensible limit?

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.

Switched the history to boost::circular_buffer_space_optimized in c963f7b, so the capacity is only a maximum and memory grows with the history actually kept: R_HISTSIZE=999999999 no longer allocates anything up front. A large value still works as the user asked, without a limit.

const int kDefaultHistorySize = 512;

// R_HISTSIZE as R reads it: R ignores a negative or invalid value
int rHistorySize()

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.

The comment says "as R reads it", but R parses R_HISTSIZE with R_Decode2Long(), which accepts k/K/M/G suffixes. stringTo<int> rejects them, so R_HISTSIZE=10k saves 10000 lines in R and 512 here. The PR description notes this. Since R's parser is just strtol plus one suffix character, could we match it, or at least reword the comment so it doesn't claim parity?

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.

Reworded in 42691ac. The comment now says R also accepts a k/K/M/G suffix and that such a value is invalid here. I didn't port the parser: it's a rare spelling, R_Decode2Long() isn't API, and main treated these values as invalid too.

{
std::string histSize = core::system::getenv("R_HISTSIZE");
int size = safe_convert::stringTo<int>(histSize, kDefaultHistorySize);
return size < 0 ? kDefaultHistorySize : 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.

When the value is negative or can't be parsed, R prints WARNING: invalid R_HISTSIZE ignored; (R_setupHistory()). Here it falls back to 512 silently, so someone who sets -1 or 1e5 expecting more history gets 512 lines on every quit, with nothing telling them why. A one-time console warning at startup would match R.

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'd rather leave this out. main also ignored an invalid value without saying anything (it kept 512; only a negative value crashed), so this PR doesn't make it worse.



// saves a user's history file (.Rhistory on quit, savehistory()) as R does:
// only the most recent R_HISTSIZE commands, read at the time of saving

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.

"Only the most recent R_HISTSIZE commands, read at the time of saving" can't hold once R_HISTSIZE grows past the startup capacity. Start with R_HISTSIZE unset, run 800 commands, then Sys.setenv(R_HISTSIZE = "2000"); savehistory(). R writes 800 lines, but this writes 512, because the oldest 288 were already evicted from the buffer. The PR description mentions this. Could the comment and the NEWS entry ("read when the file is saved") say so too?

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.

Done in 42691ac. The header comment now says a save can't hold more than the session kept, so raising R_HISTSIZE past capacity() mid-session saves at most capacity(). NEWS now says the history file can't hold more than the session kept.

Comment thread src/cpp/r/session/RConsoleHistory.cpp Outdated

void ConsoleHistory::setCapacity(int capacity)
{
historyBuffer_.set_capacity(capacity);

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.

The crash came from a zero-capacity buffer reaching loadFromFile(). The PR changes the one caller that could pass 0, but setCapacity(int) is still public (and the constructor now is too). setCapacity(0) followed by loadFromFile() would segfault again, and setCapacity(-1) converts to a huge size_t and throws. Clamping or rejecting non-positive values here would rule out that failure for any future caller.

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.

Done in 42691ac and 0e36f19: setCapacity() now keeps a capacity of at least 1, so 0 and -1 both give 1. The test covers both, including loading a file afterward.

namespace session {
namespace tests {

TEST(SessionConsoleHistoryTest, RHistsizeLimitsOnlyTheSavedHistory) {

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.

Two gaps in coverage:

  • The test calls saveToHistoryFile() directly, so nothing checks that Rsavehistory, rs_saveHistory and RCleanUp use it. If any of them still called saveToFile(path, false), these tests would pass.
  • The last512 checks save largeHistory, whose capacity is 1000. So loading a history file longer than the default 512 capacity, where circular_buffer::insert overwrites at end-when-full, is never covered.

Also a nit: the .clang-format config uses Allman braces (per .claude/CLAUDE.md), so this opening brace would move to its own line.

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.

Both added. a483d66 adds a test-history.R test that loads three commands, sets R_HISTSIZE=2 and calls savehistory(). That goes through Rsavehistory() on POSIX and rs_saveHistory on Windows, so it fails if either calls saveToFile(). RCleanUp() is still untested, since it only runs at quit. 42691ac loads the 600-command file into each default-capacity history and checks that it keeps the newest 512, and moves the brace.

Comment thread src/cpp/r/session/RConsoleHistory.cpp Outdated

Error ConsoleHistory::saveToHistoryFile(const FilePath& filePath) const
{
std::size_t count = std::min(static_cast<std::size_t>(rHistorySize()),

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: ConsoleHistory::subset() already copies an index range into a vector, so this could be subset(size() - std::min(size(), rHistorySize()), size(), &commands) without the size_t/ptrdiff_t casts.

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.

Done in 42691ac.

circular_buffer allocates its whole capacity up front, so a large
R_HISTSIZE meant as "unlimited" (e.g. 999999999) tried to allocate
gigabytes at startup. setCapacity() now clamps to [1, 100000], which
also keeps any caller from making the zero-capacity buffer that crashed
loadFromFile().

Also say that a k/K/M/G suffix R accepts is invalid here, that a save
can't hold more than the session kept, use subset() in
saveToHistoryFile(), and test loading a history file longer than the
default capacity.

Addresses #19690.
This goes through Rsavehistory() on POSIX and rs_saveHistory on
Windows, which the gtest, calling saveToHistoryFile() directly, didn't
cover.

Addresses #19690.
A larger R_HISTSIZE raises the capacity as it did before; only the
lower bound of 1 stays, which keeps the zero-capacity buffer that
crashed loadFromFile() out of reach.

Addresses #19690.
circular_buffer allocates its whole capacity up front, so a large
R_HISTSIZE meant as "unlimited" (e.g. 999999999) tried to allocate
gigabytes at startup. The space-optimized buffer allocates as commands
are added, so the capacity can follow R_HISTSIZE without a limit.

Addresses #19690.
Takes #19688's loadFromFile(), with its staging buffer declared as a
HistoryBuffer so it can swap with the history.

@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 follow-ups address the review. The one left out, warning on an invalid R_HISTSIZE, is fine to leave, since main ignored those values silently too.

@kevinushey
kevinushey merged commit 032bcf8 into main Nov 19, 2026
36 of 37 checks passed
@kevinushey
kevinushey deleted the bugfix/19690-r-histsize branch November 19, 2026 20:26
kevinushey added a commit that referenced this pull request Nov 23, 2026
* allocate the console scrollback as output arrives

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.

* keep console output intact at the largest scrollback limit

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.

* assert the queue test runs at the largest scrollback limit

Addresses #19738.

* clear startup output from the queue test with clear()

Addresses #19738.

* trim blank lines in trimLeadingLines(); don't re-push flushed console 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.

* don't report a trim when trimLeadingLines() removes nothing

Addresses #19738.

* check the console output line limit for overflow at compile time

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.

* keep the console scrollback working when its storage can't grow

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.

* report the scrollback limit as set; don't lower it to 0

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.

* stop the growth-failure test before reading an empty buffer

Addresses #19738.
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.

the R session crashes at startup when R_HISTSIZE is 0 and fails to start when it is negative

2 participants