Skip to content

Commit 839948c

Browse files
authored
Fix quarto preview crash on knitr document in a project subdirectory (#14699)
Previewing a knitr document in a project subdirectory — running `quarto preview` from that subdirectory with a bare filename, the shape RStudio's Render button uses — failed with `rmarkdown:::abs_path(input): The file 'doc.qmd' does not exist.` This is a regression from #13804, live in stable 1.9.38 and main. #13804 shared one ProjectContext (and its fileInformationCache) between preview's format-resolution and render steps, with cache keys normalized to absolute paths, but the cached ExecutionTarget.input/source kept whatever form the caller passed. Format-resolution seeds the cache with a cwd-relative bare filename; renderProject later looks the same file up by its absolute path, collides on the same cache key, and inherits the stale relative input. The knitr subprocess runs with cwd set to the project directory, where the subdirectory-relative filename doesn't resolve. Normalize the path to absolute once, at the single convergence point (fileExecutionEngineAndTarget in src/execute/engine.ts), so target.source/target.input are always absolute regardless of how the caller spelled the path — consistent with project renders, which were already absolute. This also fixes #12401: QUARTO_DOCUMENT_PATH was relative for single-file renders but absolute for project renders, since both derive from target.source. Adds a regression test exercising the real knitr subprocess and a manual preview-matrix entry (T33) with an on-disk fixture, since `quarto preview` itself can't run under the automated test harness. Fixes #14683, fixes #12401, fixes #14151
1 parent 6cb6e3f commit 839948c

12 files changed

Lines changed: 521 additions & 1 deletion

File tree

‎.claude/rules/testing/test-anti-patterns.md‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,3 +17,9 @@ paths:
1717
Never create `Project.toml`, `.venv/`, or `renv.lock` in test fixture directories.
1818

1919
**Details:** `llm-docs/testing-patterns.md` → "Shared Test Environments"
20+
21+
## Don't: `Deno.chdir()` inside the test body
22+
23+
`Deno.chdir()` mutates process-global cwd, so a test that changes it can leak into other tests in the same process. The harness already changes and restores the working directory: return the directory from `TestContext.cwd`, create fixtures in `setup`, clean up in `teardown` (examples: `tests/unit/dotenv-config.test.ts`, `tests/smoke/use/template.test.ts`). For a temp directory you don't need to run *from*, use `withTempDir` (`tests/utils.ts`). A test that only needs a *relative* input can pass a path relative to the current cwd without changing it.
24+
25+
**Details:** `llm-docs/testing-patterns.md` → "Working-Directory-Sensitive Tests"
Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
---
2+
paths:
3+
- "tests/unit/preview-subdir-knitr-cwd.test.ts"
4+
---
5+
6+
# R unit test that changes working directory
7+
8+
This test runs a knitr subprocess with cwd set to a scratch directory
9+
(required to reproduce the bug). R's `.Rprofile` lookup is cwd-exact, so it
10+
won't pick up `tests/renv` activation there — on CI the R subprocess fails
11+
with `there is no package called 'rmarkdown'`. `setup()` writes a
12+
`.Rprofile` into the fixture dir to re-activate renv against the real
13+
`tests/` project.
14+
15+
**Details:** `llm-docs/testing-patterns.md` → "R Tests That Change Working Directory"

‎llm-docs/testing-patterns.md‎

Lines changed: 64 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -169,6 +169,40 @@ testQuartoCmd(
169169
- Clean up entire temp directory including source files
170170
- File verification uses relative paths when checking files in `cwd()`
171171

172+
### Working-Directory-Sensitive Tests
173+
174+
Some tests need to run from a specific directory (e.g. reproducing a bug that
175+
depends on the process cwd). **Do not `Deno.chdir()` inside the test body** —
176+
it mutates process-global cwd and can leak into other tests in the same
177+
process. Use the `TestContext` options instead; the harness changes the cwd
178+
before the test and restores it afterward:
179+
180+
```typescript
181+
const workingDir = Deno.makeTempDirSync();
182+
183+
unitTest("runs from workingDir", async () => {
184+
// cwd is workingDir here (set by the harness)
185+
}, {
186+
setup: () => { Deno.writeTextFileSync(".env.example", "..."); return Promise.resolve(); },
187+
cwd: () => workingDir,
188+
teardown: () => { try { Deno.removeSync(workingDir, { recursive: true }); } catch { /* best-effort */ } return Promise.resolve(); },
189+
});
190+
```
191+
192+
**Key points:**
193+
194+
- The harness calls `cwd()` **before** `setup()`, so the directory must already
195+
exist when `cwd()` runs — create it at module scope, not in `setup`.
196+
- `teardown` runs **before** the harness restores the cwd, so on Windows the
197+
temp dir may still be the cwd and resist removal. Wrap the removal in
198+
try/catch (best-effort) — see `tests/smoke/use/template.test.ts` and
199+
`tests/unit/dotenv-config.test.ts`.
200+
- For a temp directory you don't need to run *from*, prefer `withTempDir`
201+
(`tests/utils.ts`), which creates and recursively removes it in a `finally`.
202+
- A test that only needs a **relative** input (not a specific cwd) can pass a
203+
path relative to the current cwd (`relative(Deno.cwd(), absFile)`) without
204+
changing directories at all.
205+
172206
## Verification Helpers
173207

174208
### Core Verifiers
@@ -363,6 +397,36 @@ Rscript -e "renv::install(); renv::snapshot()"
363397

364398
**Note:** While Quarto supports local Project.toml files in document directories for production use, the quarto-cli test infrastructure specifically does NOT support this pattern. All test dependencies must be in the main `tests/` environment.
365399

400+
### R Tests That Change Working Directory
401+
402+
R resolves `.Rprofile` from the **exact** process cwd (no parent-directory
403+
search). On CI, rmarkdown/knitr live only in `tests/renv`'s project library,
404+
activated when cwd is `tests/` (via `tests/.Rprofile` sourcing
405+
`renv/activate.R`). Most knitr tests never leave `tests/` — they pass paths
406+
relative to the current cwd instead of changing directories — so activation
407+
happens automatically.
408+
409+
A test that must run with cwd set elsewhere (a scratch temp dir, via
410+
`TestContext.cwd()` — see "Working-Directory-Sensitive Tests" above) loses
411+
that activation: the R subprocess starts outside `tests/`, renv never
412+
activates, and package loads fail with `there is no package called
413+
'rmarkdown'`. This is CI-only — a developer machine with rmarkdown on the
414+
default `.libPaths()` masks it entirely. The render pipeline also tends to
415+
swallow the underlying subprocess error, so the failure can be silent beyond
416+
the bare package-load message.
417+
418+
**Fix:** in the fixture's cwd, write a `.Rprofile` that re-points renv at the
419+
real project, regardless of where the test's cwd actually is:
420+
421+
```r
422+
Sys.setenv(RENV_PROJECT = "<absolute path to tests/>")
423+
source("<absolute path to tests/>/renv/activate.R")
424+
```
425+
426+
`renv/activate.R` reads `RENV_PROJECT` to determine the project root if set,
427+
falling back to `getwd()` otherwise — setting it explicitly decouples renv
428+
activation from the test's cwd.
429+
366430
## Best Practices
367431

368432
1. **Always clean up**: Use teardown to remove generated files

‎news/changelog-1.10.md‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@ All changes included in 1.10:
66
- ([#14281](https://github.com/quarto-dev/quarto-cli/issues/14281)): Fix transient `.quarto_ipynb` files accumulating during `quarto preview` with Jupyter engine.
77
- ([#14298](https://github.com/quarto-dev/quarto-cli/issues/14298)): Fix `quarto preview` browse URL including output filename (e.g., `hello.html`) for single-file documents, breaking Posit Workbench proxied server access.
88
- ([#14489](https://github.com/quarto-dev/quarto-cli/issues/14489)): Restore `--output-dir` support for `quarto preview` of single files when no `_quarto.yml` is present (e.g. R-package workspaces). Regression introduced in v1.9.18.
9+
- ([#14683](https://github.com/quarto-dev/quarto-cli/issues/14683)): Fix `quarto preview` of a knitr document in a project subdirectory failing when run from that subdirectory with a bare filename (the shape RStudio's Render button uses). Regression introduced in v1.9.18.
910
- ([rstudio/rstudio#17333](https://github.com/rstudio/rstudio/issues/17333)): Fix `quarto inspect` on standalone files emitting project metadata that breaks RStudio's publishing wizard.
1011

1112
## Dependencies
@@ -115,6 +116,7 @@ All changes included in 1.10:
115116
- ([#6092](https://github.com/quarto-dev/quarto-cli/issues/6092)): Fix the `default-image-extension` being appended to an extensionless URL ending in a slash (e.g. `![](https://example.com/)`), which broke the embed/iframe image syntax.
116117
- ([#6651](https://github.com/quarto-dev/quarto-cli/issues/6651)): Fix dart-sass compilation failing in enterprise environments where `.bat` files are blocked by group policy.
117118
- ([#11703](https://github.com/quarto-dev/quarto-cli/issues/11703)): Fix SCSS color-variable export (`--quarto-scss-export-*`) being silently skipped when a theme rule contains consecutive semicolons (e.g. `max-height: 100% !important;;`).
119+
- ([#12401](https://github.com/quarto-dev/quarto-cli/issues/12401)): Fix `QUARTO_DOCUMENT_PATH` being a relative path for single-file renders, inconsistent with project renders where it was absolute. Execution target paths are now normalized to absolute at a single point, so single-file and project renders behave the same.
118120
- ([#14255](https://github.com/quarto-dev/quarto-cli/issues/14255)): Fix shortcodes inside inline and display math expressions not being resolved.
119121
- ([#14342](https://github.com/quarto-dev/quarto-cli/issues/14342)): Work around TOCTOU race in Deno's `expandGlobSync` that can cause unexpected exceptions to be raised while traversing directories during project initialization.
120122
- ([#14445](https://github.com/quarto-dev/quarto-cli/issues/14445)): Fix intermittent `Uncaught (in promise) TypeError: Writable stream is closed or errored.` aborting renders on Linux. `execProcess` now awaits and swallows the rejection from `process.stdin.close()` when the child closes its stdin first. The captured stderr is now also surfaced when `typst-gather analyze` falls back to staging all packages, so failures are diagnosable without bypassing `quarto`.

‎src/execute/engine.ts‎

Lines changed: 14 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,7 @@ import {
1212
partitionYamlFrontMatter,
1313
readYamlFromMarkdown,
1414
} from "../core/yaml.ts";
15-
import { dirAndStem } from "../core/path.ts";
15+
import { dirAndStem, normalizePath } from "../core/path.ts";
1616

1717
import { metadataAsFormat } from "../config/metadata.ts";
1818
import { kBaseFormat, kEngine } from "../config/constants.ts";
@@ -355,6 +355,19 @@ export async function fileExecutionEngineAndTarget(
355355
flags: RenderFlags | undefined,
356356
project: ProjectContext,
357357
): Promise<{ engine: ExecutionEngineInstance; target: ExecutionTarget }> {
358+
// Establish an "always absolute" contract for the file path at this single
359+
// convergence point for all callers (preview format-resolution, render, and
360+
// project render). fileInformationCache keys are normalized to absolute
361+
// (FileInformationCacheMap), so a caller passing a cwd-relative path — e.g.
362+
// preview seeding the cache with the bare filename RStudio's Render button
363+
// uses from a subdirectory — would otherwise store a target whose
364+
// source/input stay relative under an absolute key, a stale value that a
365+
// later absolute-path lookup reuses. Normalizing here keeps target.source and
366+
// target.input consistent with the key and with project renders (which
367+
// already pass absolute paths). See #14151 (the contract), #12401
368+
// (QUARTO_DOCUMENT_PATH / cwd inconsistency), #14150 (doubled subdirectory),
369+
// and #14683 (knitr abs_path failure previewing from a subdirectory).
370+
file = normalizePath(file);
358371
const cached = ensureFileInformationCache(project, file);
359372
if (cached && cached.engine && cached.target) {
360373
return { engine: cached.engine, target: cached.target };

‎tests/docs/manual/preview/README.md‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -161,6 +161,13 @@ After every change to preview URL or handler logic, verify that single-file prev
161161
- **Expected:** HTTP 200. Browse URL may include path for non-index files in project context.
162162
- **Catches:** `isSingleFile` guard accidentally excluding real project files from path computation
163163

164+
#### T33: knitr doc in a subdirectory — preview from that subdirectory (#14683)
165+
166+
- **Setup:** Fixture `knitr-subdir-14683/` — a website project with a knitr doc at `labs/doc.qmd` (an `{r}` chunk plus a `QUARTO_DOCUMENT_PATH` echo). Requires R + `rmarkdown`/`knitr`.
167+
- **Steps:** From `knitr-subdir-14683/labs/` (the doc's own directory), run `quarto preview doc.qmd --to html --no-watch-inputs --no-browser --port XXXX` — the shape RStudio's Render button uses (bare filename, cwd = the doc's subdirectory).
168+
- **Expected:** Renders without `Error in rmarkdown:::abs_path(input)`; `_site/labs/doc.html` is produced showing `[1] 2` (the R chunk executed). The echoed `QUARTO_DOCUMENT_PATH` is the doc's absolute subdirectory (ends in `labs`), not `.` / the project root (#12401).
169+
- **Catches:** `fileExecutionEngineAndTarget` not normalizing the input to absolute — a cwd-relative `target.input`/`source` in the shared preview cache makes the knitr R subprocess (cwd = project dir) fail `abs_path` on the subdirectory-relative filename.
170+
164171
## Test Matrix: Format Change Detection (#14533)
165172

166173
After every change to `previewRenderRequestIsCompatible` or the
Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
/.quarto/
2+
/_site/
3+
**/*_files/
4+
**/*.quarto_ipynb
Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
project:
2+
type: website
3+
4+
website:
5+
title: "Knitr Subdir Preview (#14683)"
Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
---
2+
title: Home
3+
---
4+
5+
Home page. The regression fixture is `labs/doc.qmd` — preview it from the
6+
`labs/` directory with a bare filename (see T33).
Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
---
2+
title: Claude Test
3+
engine: knitr
4+
---
5+
6+
A knitr document in a project subdirectory. Previewing it from this `labs/`
7+
directory with a bare filename (`quarto preview doc.qmd`) is the shape
8+
RStudio's Render button uses, and is what regressed in #14683.
9+
10+
```{r}
11+
1 + 1
12+
```
13+
14+
The rendered output must show `[1] 2` above (the R engine executed), and
15+
`QUARTO_DOCUMENT_PATH` below must be this file's absolute directory (ending in
16+
`labs`), not `.` or the project root (#12401).
17+
18+
```{r}
19+
cat("QUARTO_DOCUMENT_PATH:", Sys.getenv("QUARTO_DOCUMENT_PATH"))
20+
```

0 commit comments

Comments
 (0)