Skip to content

collapse the utf-8 r::sexp / RFunction variants into the defaults - #19683

Merged
kevinushey merged 8 commits into
mainfrom
developer/19663-collapse-utf8-variants
Nov 18, 2026
Merged

kevinushey merged 8 commits into
mainfrom
developer/19663-collapse-utf8-variants

Conversation

@kevinushey

@kevinushey kevinushey commented Nov 18, 2026 •

Copy link
Copy Markdown
Collaborator

Intent

Follow-up to #19640. That PR made r::sexp::create() mark strings as UTF-8, and made asString() / extract() read strings as UTF-8 by default. Since then, the explicit UTF-8 variants have done exactly what the defaults do, and keeping both spellings suggests they differ. This collapses them into the defaults and removes the variants.

Fixes #19663.

Approach

Removed APIs, with what each call site now uses:

Removed Replacement
r::sexp::asUtf8String() r::sexp::asString()
r::sexp::createUtf8() (string, vector, FilePath) r::sexp::create()
RFunction::addUtf8Param() RFunction::addParam()
RFunction::callUtf8() RFunction::call()
the asUtf8 parameter on the string extract() overloads (dropped; no caller passed false)

Notes:

  • createUtf8(const FilePath&) had no create() counterpart, so this adds create(const core::FilePath&). That also lets addParam(filePath) work, which the former addUtf8Param(filePath) call sites rely on. FilePath's constructors are all explicit, so the new overload can't make an existing create() call ambiguous.
  • create(const std::string&) already delegated to createUtf8(const std::string&), so its body moved over unchanged.
  • create(const std::vector<std::string>&) keeps its existing body. The removed createUtf8(vector) used Rf_mkCharLenCE, which differs from create() only for strings with embedded NULs. The only callers that move over pass lists of file paths (SessionFiles.cpp, SessionChat.cpp), and paths can't contain NULs.
  • With the asUtf8 parameter gone, nothing reads strings in R's native encoding any more. The Rf_translateChar() branch of translate() was dead, so it's removed, and asStringImpl() is folded into asString().
  • callRHandler() in RJsonRpc.cpp no longer special-cases string parameters. mark R strings in RPC methods as UTF-8 #8448 added those branches only to route strings to addUtf8Param(), and create(const json::Value&) already sends strings to create(const std::string&).
  • Three comments in SessionChat.cpp that explained why a call used a UTF-8 variant are removed. Plain call() / addParam() now behave the same way.

Embedded NULs in R-implemented RPCs

A review of this branch turned up an older bug on the same path, fixed here too. JSON text can carry a NUL character (\u0000), and the parsed json::Value keeps it. R raises embedded nul in string when create() builds such a string. In callRHandler(), that happens while the handler's arguments are being built, before the call runs under protection, so the R error longjmps past the handler and the RPC never gets a response. This predates #19640.

callRHandler() now rejects any request whose params or kwparams contain a NUL, at any depth, before building R arguments, and returns a ParamInvalid JSON-RPC error. It rejects member names containing a NUL too, since R would silently cut them off at the NUL.

None of these APIs has a pro-only caller in rstudio-pro, and no open PR in either repository adds a new call to one, so downstream merges keep building.

No NEWS entry. The refactor has no user-visible change, and the NUL fix only affects RPC requests that the IDE's own client doesn't send in normal use.

Automated Tests

  • SessionRTest.StringsReachRMarkedUtf8 gains a FilePath case: a FilePath passed to an RFunction reaches R marked UTF-8. This goes through the new create(const FilePath&) overload, and doesn't compile on main.
  • SessionRTest.RFunctionRefusesNonMainThread drops its addUtf8Param("y") line. That line existed to cover addUtf8Param's own main-thread guard; addParam("x") still covers the remaining guard.
  • New SessionRTest.JsonRpcRefusesStringsWithEmbeddedNul registers an R RPC handler and calls it through getRpcMethods(), the way the session dispatches. It parses six requests from JSON text containing a NUL: a positional string, a kwparam value, an array element, an object value, an object member name, and a kwparam name. Each must come back as a ParamInvalid error, and a request without a NUL must still reach the handler. The requests are parsed from text because a json::Value assigned from a std::string stops at the first NUL. Each call runs inside r::exec::executeSafely, so an R error that escapes the handler fails this test instead of ending the run. With the check disabled, the four value cases report the escaped embedded nul in string: 'a\0b' error, and the two name cases return success because R silently cut the names off at the NUL.
  • SessionRTest.StringsFromRAreReadAsUtf8 and NamesReadFromRFindTheirBindings, added in mark file paths passed to R as utf-8 #19640, still pin the UTF-8 read path.
  • The full rsession gtest suite and the R testthat suite pass locally (macOS, R 4.6.1).

QA Notes

No QA needed: this is an internal refactor with no behavior change. As a smoke test, a non-ASCII file path still round-trips through the Files pane (create a folder named test-é, then upload and extract a zip into it).

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 (n/a: internal refactor)
  • 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 03:32
@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
5745 0 245 1
Platform ✅ Passed ❌ Failed ⚠️ Skipped 🔁 Flaky
✅ auth-teardown 4 0 16 0
✅ desktop-linux 1438 0 46 0
✅ desktop-macos 1444 0 40 1
✅ desktop-windows 1433 0 57 0
✅ server-linux 1378 0 54 0
✅ setup 48 0 32 0

View report online


All platforms - commit 62c9e9249c6ee71c1d16757d083e141242ed3882 - Run #2355

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

Notes inline. The refactor itself looks right: no references to the removed APIs remain, and every changed call site resolves to the intended create() overload. The main point is the first comment, about where the embedded-NUL check lives. The rest are minor.

SEXP sexpDetails;
error = r::exec::RFunction(".rs.getRmdPublishDetails")
.addUtf8Param(target)
.addParam(target)

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 embedded-NUL check only covers RPCs implemented in R (callRHandler). C++ RPC handlers that pass a client string to addParam still reach create(const std::string&) -> Rf_mkCharLenCE without protection.

Here, target comes from request.params (line 572), and json::Value::getString() keeps the NUL (std::string(ptr, len)). So "\u0000" in the request raises embedded nul in string while the arguments are being built, longjmps past these frames, and leaves the RPC unanswered. That's the same failure the new check fixes for R handlers.

This predates the PR, but moving the check down into RFunction::addParam (recording the problem and returning it from call()) would cover every handler instead of one dispatch path.

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, same failure, and RFunction is the better place for the check. I'd rather not do it in this PR, though. The generic version (each create() under executeSafely()) would run R_ToplevelExec and swap R's error handler on every addParam(). The cheaper version, scanning string params and names and returning the first problem from call(), changes how every RFunction reports errors, and it pairs naturally with unifying the mkChar helpers from your RSexp.cpp comment. Filed as #19697; the callRHandler() check moves there when that lands.

ASSERT_FALSE(error);

json::JsonRpcResponse response;
error = handler(request, &response);

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 six NUL cases run under executeSafely so that an escaping R error fails the test instead of ending the run, but this control call invokes handler() directly. If a later change makes the clean path raise an R error while building arguments, it would take down the whole rsession gtest run. Suggest wrapping it the same way.

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

Comment thread src/cpp/r/RSexp.cpp

// protection not required as long as we immediately assign into protected STRSXP
int size = static_cast<int>(value.size());
SEXP charSEXP = Rf_mkCharLenCE(value.c_str(), size, CE_UTF8);

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, not reachable today: this overload errors on an embedded NUL (Rf_mkCharLenCE), but create(std::vector<std::string>), create(std::set<std::string>) and JSON object member names go through mkCharUtf8 -> Rf_mkCharCE, which silently truncates at the NUL. Now that createUtf8(vector) is gone, the overloads that mark strings UTF-8 disagree on that edge case.

The callers that moved over (finalizePaths, rs_chatNormalizePath) build their vectors from R strings, so they can't hit it. Building all of them on one mkChar helper would keep the next caller from being surprised.

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.

That split predates this PR. On main, create(const std::string&) already went through createUtf8() / Rf_mkCharLenCE, and create(std::vector<std::string>) already used mkCharUtf8(). Unifying them means picking an error or truncation, and neither is a good default while create() can't report a failure: erroring turns today's silent truncation into a longjmp for direct callers, and truncating means R sees a different string than any check upstream did. I've folded it into #19697 with the RFunction check.

Comment thread src/cpp/r/RJsonRpc.cpp
bool containsNul(const core::json::Value& value)
{
if (value.isString())
return value.getString().find('\0') != std::string::npos;

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.

Small one: getString() returns a newly built std::string, so this copies every string parameter at every depth just to scan it, and then create() copies it again. That's cheap next to the conversion into R, but scanning the underlying buffer (or doing the check where create() already copies) would avoid it for large text payloads.

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.

True, though it's the same order of work as the conversion it guards: Rf_mkCharLenCE already reads every byte of each string, and create() copies it again. Avoiding the copy here would need a new accessor on json::Value, since the rapidjson buffer is private. I'd leave it for now; once the check moves per #19697, it can scan the copy create() already makes.

Comment thread src/cpp/r/session/RSearchPath.cpp Outdated
.addUtf8Param(searchPathsFile.getAbsolutePath())
.addUtf8Param(packagePathsFile.getAbsolutePath())
.addUtf8Param(environmentDataPath.getAbsolutePath())
.addParam(searchPathsFile.getAbsolutePath())

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: with the new create(const FilePath&), these could be .addParam(searchPathsFile) and so on. The same applies to the other rewritten lines that still unwrap paths: fun.addParam(filePath.getAbsolutePath()) in SessionHelp, dataPath in NotebookAlternateEngines, and the three create(...getAbsolutePath()) returns in SessionSpelling.

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 62c9e92, for all eight lines.

@gtritchie gtritchie left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Feedback posted above. Nothing here is blocking; the request-changes state is procedural until the comments are addressed.

@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 remaining items are tracked in #19697.

@kevinushey
kevinushey merged commit 94ade53 into main Nov 18, 2026
56 checks passed
@kevinushey
kevinushey deleted the developer/19663-collapse-utf8-variants branch November 18, 2026 21:04
kevinushey added a commit that referenced this pull request Nov 23, 2026
…19712)

* collapse the utf-8 r::sexp / RFunction variants into the defaults

Addresses #19663.

* drop the json-rpc string special case and a stale comment; check the filepath round trip

* drop the stale destfile encoding note

* refuse json-rpc strings with embedded nuls before calling r handlers

* run the embedded-nul rpc test calls protected

* put the nul after valid entries in two rpc test cases

* run the embedded-nul rpc test's control call protected too

* pass file paths to create() / addParam() directly

* refuse embedded nuls in every rfunction param, not just r rpc handlers

RFunction::addParam() checks names and string-bearing values with sexp::containsNul() and records the first problem for call() to return, so a NUL from a C++ RPC handler's client string no longer raises R's error outside the protected call. This replaces the callRHandler() check. Every string create() builds now goes through one mkChar helper, which raises R's error on a NUL instead of cutting the string off.

Addresses #19697.

* keep create()'s nul handling as it was; mirror create()'s overloads in containsNul()

Raising R's error on a NUL in every create() overload added longjmps where r::sexp promises none (findVar() on a user command name, a _quarto.yml editor key, rs_readLines), so create() keeps erroring for std::string and truncating elsewhere; unifying it is a follow-up. containsNul() now has one overload per create() overload instead of a catch-all template, which won for a YAML sequence iterator's element and skipped the check. The test covers the remaining overloads and keeps fixtures and protection out of the protected callbacks.

Addresses #19697.

* refuse rfunction param names longer than r's symbol limit

call() passes each name to Rf_install(), which raises 'variable names are limited to 10000 bytes' outside the protected call, so a long JSON-RPC kwparams name longjmped past the handler just as a NUL did. acceptParam() now refuses names over 10000 bytes too.

Addresses #19697.

* skip the nul scan after a refused param; test more positions

Addresses #19697.

* record a refused param as a string, not an error

A default-constructed core::Error allocates its implementation, which every RFunction would have paid for; call() now builds the error from the recorded reason.

Addresses #19697.

* set the result on a refused rfunction call

Callers such as the connection handlers pass the result on before checking the error, so a refused call now leaves it as R_NilValue instead of untouched.

Addresses #19697.

* count the rpc test handler's calls

The refused requests must not run the handler at all; the control request runs it once.

Addresses #19697.

* drop the news entry, as in #19683

The IDE's own client doesn't send these requests in normal use.

Addresses #19697.

* keep r errors from longjmping past r::sexp lookups and rpc handlers

- r::sexp lookups by name treat a name R can't make a symbol from (empty, over 10000 bytes, or containing a nul) as unbound, instead of raising R's error or looking up the name cut off at the nul; the Object Explorer checks a View() title the same way before Rf_install().
- findVar() / findVarInFrame() read an active binding, or a promise R_getVarEx() forces, with errors and interrupts caught (R_tryCatch, silently); forcePromise() and findFunction()'s promise forcing likewise.
- create(json::Array / json::Object) protects each element only until it's stored, so a long array can't overflow R's protection stack.
- parseString() refuses code with a nul; the _quarto.yml editor options, document hooks, and notebook chunks skip or report strings with a nul instead of handing them to create().
- RPC dispatch runs each handler under R_ToplevelExec() as a backstop, answering a request an R error interrupted.

Addresses #19697.

* keep the rpc backstop on the main thread, and deliver a response once

- invokeRpcHandler() runs offline requests' handlers directly, off the main thread, rather than entering R_ToplevelExec() while the main thread runs R.
- A shared RpcDelivery records when a response is claimed and when it's sent: the backstop answers only if nothing was sent (also when the continuation failed before sending), and a continuation an async handler kept is dropped once the backstop answered.
- installUtf8() checks the symbol length R checks, of the native name.
- findFunction() reads each binding once and stops when one's R code fails, rather than reading a failing getter twice and returning a function further out.
- A cyclic YAML alias becomes NULL in create() and is skipped by containsNul(), instead of recursing until the stack overflows.
- A notebook chunk with a nul runs its error in R even when the document's default engine isn't R.
- Tests: per-version promise forcing, getter call counts, shadowed functions, cyclic aliases, the Quarto editor guard, and the delivery protocol.

Addresses #19697.

* answer an rpc an r error interrupted with R_UnwindProtect, not R_ToplevelExec

- R_ToplevelExec() ran each handler in a top-level context of its own, discarding calling handlers R code registered meanwhile (a notebook's first chunk installs its condition handlers so) and catching interrupts meant for running R code. R_UnwindProtect() answers the request from its cleanup and lets the unwinding continue as before.
- An RpcDelivery claim records whether the main thread made it; the backstop releases only a main-thread claim, leaving a response another thread is delivering to it. claimRpcDelivery() / markRpcDeliverySent() are shared by the end functions and the test.
- Before R 3.6.2, R_tryCatch() transferred control for every condition, so caught lookups use R_ToplevelExec() there.
- findVar() reads a found binding from its frame instead of repeating the inherited lookup; findFunction() classifies each binding once.
- containsNul() reads YAML map keys as scalars, as create() does, instead of traversing composite keys.
- The Object Explorer skips a cached View() title that isn't a string; the notebook NUL error calls base::stop().
- NEWS entry for the user-visible cases.

Addresses #19697.

* run an rpc's after-response work outside the backstop; re-arm caught interrupts

- R restores its handler stack when any context ends, R_UnwindProtect()'s included, so after-response work (a notebook's first chunk registers its condition handlers there) is held while the handler runs and done once invokeRpcHandler()'s context has ended.
- A caught lookup re-arms an interrupt, so R code running meanwhile still sees it.
- The R_tryCatch() version check uses base::getRversion(), and is cached only once it succeeds.
- findFunction() stops at a missing argument; containsNul() stops at a composite YAML key; the Object Explorer reads the title's length with Rf_xlength(); a notebook chunk whose metadata holds a NUL takes the same error path as one whose code does.
- Tests: after-response ordering, a paused worker's claim, warning and interrupting bindings, a missing binding shadowing a function, and the promise check by behavior rather than R version.

Addresses #19697.

* define NotebookQueueUnit::docType(); skip malformed notebook units; hold only after-response work

- docType() was declared but never defined; macOS's dynamic lookup hid it, other platforms wouldn't link.
- A notebook unit whose document ID or type holds a NUL is skipped before its paths are touched (read up to the NUL, they could name another document's cached output); the code scan runs only when options failed.
- After-response deferral keeps only the callback and its change-detection flag (JsonRpcResponse::afterResponse()), not a copy of the response.
- The YAML check reads keys as create() does: a null key as "null", and a composite key ends the whole check.
- The R_tryCatch() version probe calls base's >= as well as getRversion(); the pre-3.6.2 fallback uses executeSafely(), so a caught error can't start options(error).
- runtime::lookupsForcePromises() tells the promise test which lookup R uses; the Quarto test puts the bad editor options first.

Addresses #19697.

* refuse a nul in a notebook queue's or unit's doc_id when it's read

* say an interrupted rpc was interrupted; skip trycatch where r's lookup runs no code; use up a prompt-time interrupt

* replace the containsNul() overloads with a NulCheckScope at create()'s two string makers

* clear r's error buffer while an rpc handler runs; re-arm a caught interrupt in later callbacks; end stray nul-check scopes at the prompt; cache the r version check

* refuse a notebook queue with a refused unit; refuse a nul in a chunk id or recovered doc type; stop findFunction at a promise that's missing; evaluate versionTest in base

* test versionTest against a global Ops.numeric_version; refuse a nul doc id with a nonempty queue

* tell an interrupted rpc from an error by r's own error signal, not the error buffer

A handler's own caught R error leaves its message in R's error buffer, so an interrupt that then unwound through the backstop was answered as that error. From R 4.0 the backstop has R call it as an uncaught error is signaled; before that it still reads the buffer.
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.

Collapse the r::sexp / RFunction UTF-8 variants that now match the defaults

2 participants