Skip to content

fix readr Import Dataset preview on Windows (escape generated R path) + console-wait reliability - #18048

Merged
kevinushey merged 6 commits into
mainfrom
bugfix/17985-readr-preview-windows
Jun 24, 2026
Merged

kevinushey merged 6 commits into
mainfrom
bugfix/17985-readr-preview-windows

Conversation

@kevinushey

@kevinushey kevinushey commented Jun 24, 2026 •

Copy link
Copy Markdown
Collaborator

Addresses #17985.

Root cause (corrected)

The readr Import Dataset preview e2e test failed on Windows CI. The real cause is not a subprocess-start failure (as the issue title implies) or a console wait race (an earlier hypothesis in this PR) -- it's an unescaped path in generated R code:

The test wrote the CSV via writeLines(..., "${csvPath}"), where csvPath embeds sandbox.dir. On Windows that path comes back from R's tempfile() with backslashes (D:\a\rstudio\rstudio\pw-sandbox\pw_sandbox_*\workdir_*). Embedded raw into R source, the backslashes are escape sequences -- \r/\a become control chars and \p (pw-sandbox) / \w (workdir) are a hard parse error:

'\p' is an unrecognized escape in character string

So writeLines never runs, the CSV is never written, and vroom's check_path reports the file "does not exist." macOS uses forward-slash sandbox paths, so it never reproduced (nor did local desktop-dev validation).

Fix

Use the existing rPathLiteral helper (utils/r.ts -- normalizes \ -> /, which R accepts on Windows, then quotes), the same idiom other tests already use (project_id, project_editor_theme, ...). Dropped the test.fixme guard and the diagnostic scaffolding built around the earlier wait-race hypothesis.

Also in this PR: console-wait reliability (independent improvement)

While investigating, I found a genuine latent race: executeInConsole({wait:true}) uses waitForConsoleIdle, which only samples the rstudio-console-busy class and can return in the submit->busy gap before R runs the command. This is not what broke #17985, but it's a real footgun for ~456 callers. Fixed by exposing window.rstudio.console.promptCount on the automation bridge (a monotonic counter bumped on ConsolePromptEvent); executeInConsole now waits for the count to advance, with a busy-class fallback for older binaries. Plus a small typing cleanup (CommandEntry.isVisible()).

If reviewers would prefer, the console-wait change can be split into its own PR -- happy to do that.

Verification

  • import_dataset 2/2 on the macOS dev build; rs_value_contents 4/4 (console-heavy, exercises the new wait path); tsc --noEmit and ant javac/ant draft clean.
  • The Windows-specific fix is verified by this PR's Windows CI run (the failure was Windows-only).

Addresses #17985. The readr Import Dataset preview e2e test soft-skips on
Windows CI; the captured error is the preview subprocess reporting the CSV
"does not exist", not a subprocess-start failure as the issue title implies.

- ensureCsvWritten(): poll file.exists() after the writeLines and retry the
  write once, throwing a setup-level error rather than letting the preview
  time out after 45s when the CSV never landed.
- awaitPreviewOrSkip(): probe getwd()/file.exists()/list.files() via a new
  ConsolePaneActions.evalRString() helper and fold the result into the
  fixme/throw reason, so a Windows CI run distinguishes a missing file from
  one present-but-invisible to the separate preview process.

The test.fixme guard stays until a Windows CI run confirms the write-verify
stabilizes it.
@kevinushey kevinushey added this to the 2026.07 (Pacific Dogwood) milestone Jun 24, 2026
The writeLines used executeInConsole({wait:true}), whose waitForConsoleIdle
only polls for the absence of the busy class and can return in the
submit->busy gap before R has run the command -- so the write's completion
was never actually awaited. The preview subprocess could then open the CSV
before writeLines wrote it, yielding vroom's "<csv> does not exist" (the
suspected #17985 root cause).

Replace ensureCsvWritten with writeCsvConfirmed: run writeLines + file.exists
in one block via evalRLogical, which reads R's printed [1] TRUE/FALSE -- a
real post-execution completion signal. Retries once before throwing.
@github-actions

github-actions Bot commented Jun 24, 2026 •

Copy link
Copy Markdown

🍎 macOS Desktop E2E · ARM64

❌ 6 test(s) failed

███████████████████░ 98% pass rate

✅ Passed ❌ Failed ⚠️ Skipped 🔁 Flaky
386 6 28 0
📥 Download Playwright report

⬇️ playwright-report.zip — extract and open index.html

Includes screenshots, traces, and step-by-step details for every test. Expires in 15 days.


2 shards · macos-26 ARM64 · commit bb95c0196a6a9b46cea6244afd1caea250645f22 · Run #167

waitForConsoleIdle only samples the rstudio-console-busy class, so it can
observe a spuriously-idle console in the submit->busy gap and return before R
runs the command -- the root-cause race behind #17985's intermittent
"<csv> does not exist" preview failure (the writeLines hadn't run when the
preview subprocess opened the file).

Expose a race-free completion signal on the automation bridge:
ApplicationAutomation now keeps window.rstudio.console.promptCount, a monotonic
counter bumped on each ConsolePromptEvent (R returning to its top-level
prompt). executeInConsole captures it before submitting and waits for it to
advance, falling back to the busy-class wait only when the counter is absent
(older binaries). This fixes every wait:true caller with no per-site change.

- ApplicationAutomation.java: registerConsole() + promptCount JSNI surface
- console_pane.page.ts: getConsolePromptCount / waitForConsoleCommandComplete;
  both executeInConsole paths capture-then-wait on the counter
- commands.ts: type the new console bridge; add CommandEntry.isVisible() (the
  bridge already exposes it) and drop the now-needless command-lookup casts
- import_dataset.test.ts: drop the writeCsvConfirmed workaround -- a plain
  executeInConsole({wait:true}) is now a sufficient gate; keep the failure
  diagnostics and fixme guard pending Windows CI confirmation
@kevinushey kevinushey changed the title harden readr import preview test write + add windows diagnostics make executeInConsole(wait:true) reliable via console prompt-count signal Jun 24, 2026
@github-actions

github-actions Bot commented Jun 24, 2026 •

Copy link
Copy Markdown

🪟 Windows Desktop E2E · Server 2025 x64

❌ 6 test(s) failed

███████████████████░ 98% pass rate

✅ Passed ❌ Failed ⚠️ Skipped 🔁 Flaky
393 6 23 0
📥 Download Playwright report

⬇️ playwright-report.zip — extract and open index.html

Includes screenshots, traces, and step-by-step details for every test. Expires in 15 days.


2 shards · Windows Server 2025 x64 · commit bb95c0196a6a9b46cea6244afd1caea250645f22 · Run #167

The real Windows cause of the readr import-preview failure was not a wait
race: sandbox.dir comes back from R's tempfile() with backslashes, and the
test embedded it into R source as a raw "${csvPath}". R parses backslashes as
escape sequences, so \p (in "pw-sandbox") is a hard parse error and the
writeLines never runs -- the CSV is never written and the preview reports
"does not exist". Reproduced locally: '\p' is an unrecognized escape in
character string. macOS uses forward-slash sandbox paths, so it never hit it
(and neither did local validation).

- import_dataset.test.ts: build the writeLines path with rPathLiteral (the
  existing helper other tests already use: normalizes to forward slashes,
  which R accepts on Windows, and quotes safely). Normalize the file-chooser
  fill path too. Drop the test.fixme guard and the fs-probe diagnostic that
  were built around the earlier (incorrect) wait-race hypothesis.
- console_pane.actions.ts: remove the now-unused evalRString helper.

The prompt-count bridge work in the prior commit remains a separate, genuine
console-wait reliability improvement -- not the #17985 fix.

Verified: import_dataset 2/2 on the macOS dev build; tsc clean.
@kevinushey kevinushey changed the title make executeInConsole(wait:true) reliable via console prompt-count signal fix readr Import Dataset preview on Windows (escape generated R path) + console-wait reliability Jun 24, 2026
createSandbox passes tmpdir = PW_SANDBOX (a Node path) to R's tempfile(), so on
Windows the returned workdir is a backslash path. Embedding that into generated
R code breaks parsing (\p, \w are unrecognized escapes) -- the root cause of
the import-preview failure. The import_dataset test now routes its path through
rPathLiteral, but normalize at the source too so every test that interpolates
sandbox.dir into R is protected: normalizePath(winslash = "/") returns forward
slashes (which R accepts on all platforms) and matches R's own getwd() form.

Note: setting TEMP/TMPDIR would not help here -- the sandbox path comes from
PW_SANDBOX via an explicit tmpdir=, not R's default tempdir().

Verified: import_dataset 2/2 on the macOS dev build (workdir resolves to a
forward-slash path); tsc clean.
@kevinushey
kevinushey requested a review from gtritchie June 24, 2026 17:47
@gtritchie

Copy link
Copy Markdown
Member

Code review findings

Actionable items from an automated multi-agent review (code, tests, comments, error handling). The path-escaping fix and the prompt-count counter are correct on the main path; the items below are the actionable residue. Several concerns raised during review were disproved and are omitted (the os import is still used at line 108; the dropped dialog-cancel is safe because resetForNextTest hard-fails on leaked modals; normalizePath(mustWork=FALSE) is correct for separator canonicalization).

Important

  1. e2e/rstudio/pages/console_pane.page.ts:180-183 — the ExecuteInConsoleOptions.wait JSDoc still describes the old mechanism ("via waitForConsoleIdle" ... "the console-busy class is faster and more reliable than a blind sleep"). executeInConsole now calls waitForConsoleCommandComplete, and this PR's whole premise is that the busy-class wait is not reliable. This contradicts the function-level doc ~15 lines below. Fix: update to reference the new-prompt signal / waitForConsoleCommandComplete and drop the "more reliable" busy-class justification (keep the "added to recall history only when R executes it" note).

  2. e2e/rstudio/pages/console_pane.page.ts:115-134 — waitForConsoleCommandComplete silently falls back to the known-flaky waitForConsoleIdle when promptCountBefore === null, with no log. A run against a binary that predates the counter (or where registerConsole failed to install the object) reverts every executeInConsole to the flaky path with zero signal — reintroducing the exact flakiness this PR removes. This breaks from the codebase's "warn once on a degraded path" pattern (e2e/rstudio/utils/sandbox.ts:78-82). Fix: emit a one-time console.warn on the null path, guarded by a module-level flag to avoid spam.

  3. e2e/rstudio/pages/console_pane.page.ts:115-134 — ConsolePromptEvent fires for every prompt R emits, including continuation (+) and nested prompts (browser(), readline(), menu()), so count > before can resolve on the first intermediate prompt, returning before the command truly completes. Harmless for current callers (all submit self-contained one-shot expressions), but the docstring's "race-free completion signal" / "can't return spuriously-idle" overstates it — it can return spuriously-complete. Fix: document that the helper assumes the submitted command returns to top-level exactly once and must not be relied on for code that hits a nested/continuation prompt.

Suggestions

  1. The prompt-counter rationale is duplicated near-verbatim across 5 locations: ApplicationAutomation.java:231-244, ApplicationAutomation.java:105-109, e2e/rstudio/utils/commands.ts:188-195, the getConsolePromptCount/waitForConsoleCommandComplete JSDoc in console_pane.page.ts, and the promptCount bullet in e2e/rstudio/CLAUDE.md. The TS copies will drift from the Java implementation over time. Fix: keep the authoritative text in registerConsole (it owns the implementation) and reduce the others to a one-line summary plus a pointer.

  2. e2e/rstudio/pages/console_pane.page.ts (executeInConsole retry-loop comment, ~line 232) — comment says "waitForConsoleIdle alone can't catch that case," but the function no longer calls waitForConsoleIdle directly. The point about the empty-editor verification loop is still valid; just generalize the name to match the code (waitForConsoleCommandComplete).

  3. e2e/rstudio/tests/panes/environment/import_dataset.test.ts:108 — now that sandbox.ts normalizes to forward slashes at the source, the csvPath.replace(/\\/g, '/') round-trip here is a no-op on non-Windows and redundant belt-and-suspenders. Either drop the redundant first replace or add a one-line note so a future reader doesn't assume line 108 is load-bearing on non-Windows.

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

LGTM! Some nit-picky low pri feedback on comments, etc.

@kevinushey

Copy link
Copy Markdown
Collaborator Author

Thanks for the thorough review -- all six items addressed in bb95c01.

1. Stale wait? JSDoc -- rewrote to reference waitForConsoleCommandComplete / the new-prompt signal and dropped the "busy-class is faster and more reliable" justification; kept the recall-history-on-execute note.

2. Silent null-counter fallback -- added a one-time console.warn (module-flag guarded) before reverting to waitForConsoleIdle, mirroring the warn-once pattern in sandbox.ts.

3. Counter bumped on continuation/nested prompts -- went a step beyond the doc-only suggestion. The ConsolePromptEvent payload already carries the server's busy flag (exposed via ConsolePrompt.getBusy()), so I gated the bump on !event.getPrompt().getBusy(). Mid-execution prompts (browser(), readline(), menu(), continuation +) carry busy == true, so only a genuine top-level return advances the counter -- the "race-free completion signal" claim is now actually true for those cases rather than something to walk back. The one residual case the gate can't cover (a command deliberately left sitting at a continuation/interactive prompt) is now documented: the wait times out rather than resolving early, and no current caller hits it.

4. Duplicated rationale -- trimmed the commands.ts ConsoleBridge type doc to a one-line summary plus a pointer to registerConsole (authoritative) and waitForConsoleCommandComplete (consumer). Kept the helper docstrings and the CLAUDE.md surface entry self-contained since they serve test authors directly.

5. Stale waitForConsoleIdle in the retry-loop comment -- generalized to describe the completion-wait behavior (and clarified that an unsubmitted command now times the wait out rather than returning immediately).

6. Redundant csvPath.replace(/\\/g, '/') -- kept as belt-and-suspenders but updated the comment to be explicit that it's a no-op now that createSandbox normalizes its workdir to forward slashes, so a future reader doesn't assume it's load-bearing on non-Windows.

Verified tsc --noEmit clean and ant javac succeeds.

@kevinushey
kevinushey merged commit 4193515 into main Jun 24, 2026
10 of 11 checks passed
@kevinushey
kevinushey deleted the bugfix/17985-readr-preview-windows branch June 24, 2026 23:03
kevinushey added a commit that referenced this pull request Jun 25, 2026
…8061)

executeInConsole({wait:true}) waits for window.rstudio.console.promptCount
to increase. The bump was gated on !prompt.getBusy(), so it only fired at
the top-level prompt. A command that parks at an interactive sub-prompt
(browser()/Browse[N]>, readline(), menu()) never returns to top level on
its own, so the wait hung until timeout -- this broke the debugger e2e
tests, whose commands hit a breakpoint and enter Browse mode.

Bump on every ConsolePromptEvent instead. This is safe: a single
submission's intermediate continuation (+) and inter-statement prompts are
serviced from the server's buffered, line-split console input
(SessionConsoleInput.cpp rConsoleRead -> popConsoleInput) without firing a
client kConsolePrompt event, so a new prompt event is always a genuine "R
is waiting for input again" point, never a mid-expression state. One-shot
expressions still fire exactly one event at completion (the #18048 race
stays fixed); interactive/debugger commands now resolve at their settle
point instead of hanging.
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.

2 participants