Skip to content

Move process and stdio calls to deno_ral/process.ts - #15435

Draft
cderv wants to merge 33 commits into
mainfrom
rt/08-ral-process
Draft

cderv wants to merge 33 commits into
mainfrom
rt/08-ral-process

Conversation

@cderv

@cderv cderv commented Nov 27, 2026 •

Copy link
Copy Markdown
Member

Move process and stdio calls to deno_ral/process.ts


Part of the runtime migration (#15133). Follows #15429, which moved environment variables to deno_ral. This does the same for processes and the standard streams: src/deno_ral/process.ts becomes Quarto's own process interface (spawn, exec, execSync, exit, cwd, args, execPath, onSignal, killProcess, writeStdoutSync, writeStderrSync, isTerminal, readStdin, ...), and execProcess in src/core/process.ts now runs on it. Every direct Deno.Command, Deno.run, Deno.exit, Deno.cwd, Deno.args, signal listener and stdio call in src and in the build tooling under package/src goes through the layer. The layer still calls Deno underneath. A later PR reimplements it on Node behind the same interface, and tests/unit/ral/process.test.ts is the contract both must pass.

What changes for users

  • quarto run script.ts | head -n 1: Quarto stopped with Error executing '...deno.exe': ... (os error 232) and a stack trace once head closed the pipe. Now Quarto stops the script and ends without the error (exit code 1 in both cases, the stopped script's failure). It also no longer waits for a process the script started that keeps the pipe open, which can happen on Linux and macOS where a child inherits the pipe. The same path serves pre- and post-render scripts.
  • A write to Quarto's own stdout or stderr after the reader went away no longer throws: the rest of the output is dropped and Quarto exits with its normal code.
  • External preview servers (Shiny for Python, a project's serve: command) now run in their own process group on Linux and macOS, and Quarto's cleanup stops the whole group. On Windows the whole process tree is stopped with taskkill /T. The terminal's Ctrl-C no longer reaches the server directly, so Quarto registers the stop before the server starts.
  • Engine extensions: quarto.system.execProcess ignores the Deno-only options uid, gid and windowsRawArguments, which were never part of the API declared in @quarto/types (changelog entry under Extensions).

Runtime boundary

The baseline for src drops from 219 to 85 Deno.* calls (-134, comment lines counted), and for package/src from 241 to 207 (-34: 32 code sites and two comment lines in package/src/util/tar.ts). The tests scope goes up by one, from 774 to 775: tests/unit/launcher-arguments.test.ts runs cmd with windowsRawArguments to check a command line as typed at a terminal, and the layer has no raw Windows command line, so the test keeps the direct call. The check now reports a new process or stdio call in src or package/src, Deno.stdout.writeSync() included, as covered by the layer, like the fs and env calls.

Left on Deno on purpose:

  • src/webui/quarto-preview/build.ts and src/resources/tools/ast-diagram/main.ts run with deno run without Quarto's import map, so they cannot import deno_ral. Later PRs port them with the build tooling and the quarto run work.
  • The julia-engine subtree, maintained upstream in PumasAI/quarto-julia-engine. How the engine moves to a runtime-neutral process API there is still open. A Node port of the engine exists in gordonwoodhull/quarto-julia-engine (branch q2/node-port), which is the reference for that conversation.
  • src/command/render/latexmk/quarto-latexmk.ts, the standalone tinitex entry, which is scheduled for deletion.

The branch also carries the plan's execution log and follow-up notes for the Node port under dev-docs/runtime-migration/.

Pending checks

  • quarto preview then Ctrl-C on Linux, macOS and Windows: exits promptly, no pandoc or deno process left
  • Shiny for Python preview then Ctrl-C: no uvicorn left on Linux and macOS, no python left on Windows

The new case in tests/unit/exec-process-reader-gone.test.ts (a process started by the script keeps the pipe open) only exercises the fix on Linux and macOS: Windows does not hand the pipe to that process, so the case passes there with or without the fix. The Linux and macOS CI runs are the evidence for it.

Test plan

On Windows:

  • Process layer contract test and execProcess tests (stdin, split UTF-8 chunks, reader going away): 30 passed
  • Unit tests for project, render, tools, Chrome launch and the runtime layer: 259 passed, 4 ignored
  • Smoke tests for render, Jupyter, create, inspect, check, typst-gather, run, project, site, OJS and build-ts-extension: 58 passed, 1 ignored
  • deno check quarto.ts passes
  • Runtime boundary check at the new baseline; codemod dry run over src: 0 calls would be rewritten
  • quarto run endless.ts | head -n 1 ends without the error (the main build prints os error 232 and a stack trace)
  • quarto inspect doc.qmd | head -c 1 prints one character, exit 0, nothing on stderr
  • quarto check finds Chrome, and a {mermaid} document renders to docx

Checklist

I have (if applicable):

  • referenced the GitHub issue this PR closes
  • updated the appropriate changelog in the PR
  • ensured the present test suite passes
  • added new tests
  • created a separate documentation PR in Quarto's website repo and linked it to this PR
AI-assisted PR
  • AI tool used: Kimi K3 / K3.1 Pro (in Pi and Posit Assistant) for the implementation, Codex for branch review, Claude Code (Opus, Sonnet) for the rest
  • Codebase grounding: local clone
  • Human review: I have reviewed, tested, and verified the AI-generated content before submitting.

Note: autonomous AI agents submitting PRs without human oversight are not permitted — see the Code of Conduct.

cderv added 26 commits November 27, 2026 16:06
Step 0 re-grepped the plan's 200 citations against main at d0f4d3e:
none are gone, and the 14 that changed come from the execProcess UTF-8
fix (#15346) and the fs codemods. Fix the code blocks the executor
transcribes. Without these fixes, the processOutput snippet would undo
Deno.readFileSync that the ratchet rejects, and the create --json input
fails. Apply the Windows review findings for this plan: spawn ping
directly, check every taskkill exit code, correct the SIGTERM wording
and the Windows pass count. Drop the "Deno" in globalThis branch of the
contract test helper, an indirect Deno access the ratchet does not
count. Record the procedural amendments (explicit staging,
--allow-import gates, the Windows manual checks, the codemod dry run as
a final check, recounts) as open-decision rows, plus one row for PR 28.

The README code-block audit gains a check for mechanical rewrite steps
that a tool landed since the plan already covers: tools/codemod-deno-ral.ts
has had a process rule since #15223, and the plan's sed steps never
mention it.
PR 08 Task 2 hit TS2345 where execProcess fed deno_ral's wide
ReadableStream<Uint8Array> process streams into an addStream helper typed
for Deno's narrow Uint8Array<ArrayBuffer>; widening that one annotation was
enough. fs.ts follows the opposite convention for its outputs (narrow,
because callers hand the bytes to Blob or crypto.subtle.digest), so the
process layer now differs from it. No caller needs narrow process chunks
today, so the choice is left to PR 28, which implements the streams on Node.
…anup

- check-runtime-boundary: a call such as Deno.stdout.writeSync() is keyed
  `stdout.writeSync`, so the bare `stdout`/`stderr`/`stdin` entries never
  matched it and a reintroduced call was only an uncovered finding a
  baseline update could clear. Register the member keys of the migrated
  stream operations.
- launcher-arguments test: execProcess no longer takes Deno-only options,
  so passing windowsRawArguments failed type-checking on Windows. The raw
  typed command line has no layer equivalent; the fixture calls the runtime
  command API directly (one deliberate tests-scope call).
- External previews: the server now leads its own process group on POSIX,
  so a terminal Ctrl-C no longer reaches it. Register the stop handler
  before start(), which waits for the ready pattern, in both project and
  Jupyter (Shiny) preview.
- Drop a TODO left behind by the deleted typstWatch, and a redundant copy
  of processArgs() in quarto.ts.
- deno-essentials rule (loaded for src/**): name the process layer, since
  the deno-ral rule that already says so only loads for src/deno_ral/.
- Changelog: clearEnv, signal and detached are not in the declared
  ExecProcessOptions type, so do not advertise them to typed extensions.
- Execution log: the merged-output drain is not timed (as before).
- HANDOFF points at the PR 00b overlap row in OPEN-DECISIONS.md.
- OPEN-DECISIONS: label the Windows tasklist check as PowerShell; record
  layerScriptCommand and known-failures for the child-script tests on Node.
- README audit regex also finds inline and backticked sed/awk/perl.
- README audit regex: a dash after sed/awk/perl dropped optionless
  commands (the dprint rewrite in plan 38); match a command at line start,
  after a backtick or after a colon instead.
- Changelog: numeric stdio is still honoured in part (stdin forwarded, no
  echo for a numeric stdout), so name only the options execProcess drops.
- deno-essentials path example uses cwd() from the process layer.
- PR 08 checklist and HANDOFF state section match the corrected log and
  the OPEN-DECISIONS overlap row.
The layer's standard-stream writes treat a broken pipe as "stop writing"
and return a short count. With respectStreams (`quarto run`), execProcess
ignored that count and kept collecting the child's output: for
`quarto run script | head -n 1` with a script that keeps writing, a fast
writer's output grew until Quarto failed with "Invalid string length",
and a slow one grew indefinitely. Before the layer, the first write threw
BrokenPipe and Quarto crashed with a stack trace.

processOutput now stops the child on the first short write, so the
pipeline ends quietly with the child's status.
- README audit regex: the embedded backtick ended the code span, and
  `xargs sed` was missed. A word boundary before the command and
  whitespace after it finds every form; prose hits are skipped by hand.
- OPEN-DECISIONS: the Node stream writes must report a broken pipe as a
  short count, which execProcess now relies on to stop a passthrough child.
tests/unit/launcher-arguments.test.ts runs cmd with windowsRawArguments
to check a command line typed as at a terminal; the runtime layer has no
raw Windows command line, so the fixture keeps the direct call.
On Node an EPIPE ends Quarto with exitCode ?? 0 (PR 28 Task 5), which
also ends a passthrough child; requiring the Node writes to return a
short count instead contradicted that rule.
- check-runtime-boundary: Deno.stdin.close() is keyed `stdin.close` and
  had no replacement, so reintroducing the call create --json dropped
  would be only an uncovered finding. readStdinLines now owns closing
  stdin; register the key.
- exec-process-reader-gone test: the runner exits with a marker code when
  execProcess reports the stopped child as failed, so the test also checks
  that the child's status reaches the caller (the child's own code is
  platform-specific).
- deno-ral rule: the direct-call prohibition exempts the wrappers in
  deno_ral/process.ts, the one place those calls belong.
The reader-gone test now asserts the runner's marker code 9, which holds
on Deno only: on Node the broken-pipe rule ends the runner with code 0
before execProcess returns. Record what the Node gate should expect.
Both pipe tests launch Deno-specific child command lines, the planned Node
broken-pipe exit skips registered child cleanup, and the expected exit
codes when the reader closes early differ by runtime. Recorded for PR 28
step 0 rather than resolved in PR 08, which only runs on Deno.
…PR 28

PR 28's process.ts is one node:-API implementation used on Deno too, and
its writeAllSync exits with exitCode ?? 0 on EPIPE before a script reaches
its own exit(). The 3 and the marker 9 that PR 08's pipe tests assert are
therefore Deno expectations of PR 08 only, and change to 0 in PR 28, as
its Task 5 Step 4 already does for inspect-pipe.test.ts.
With respectStreams, a short write stops the child, but execProcess then
waited for both pipes to reach EOF. A worker the `quarto run` script
started inherits those pipes on POSIX and can hold them open long after
the script is stopped, so `quarto run script | head` hung until the worker
ended. Before the process layer, the throwing write ended the command at
once. Once the reader is gone, wait for the child's exit instead.

Windows does not reproduce the hang: a worker started there does not keep
the parent's pipe open (a writer that starts a 30-second worker and exits
gives `wc -c` EOF within a second), so the new test case passes on Windows
with or without the change and guards the POSIX path in CI.
Since execProcess stopped waiting for the pipes after a short write, it
returns while the two reads are still running. Pre- and post-render
scripts go through the same run handlers (respectStreams), so a render
continues after `quarto render | head` closes, and a worker the script
left running could fill memory through the abandoned reads. A flag shared
by both streams now makes them drain the rest without keeping it.

No new test: what the abandoned reads keep is not observable once
execProcess has returned.
The coordinator's wrap-up ran the plan's review checklist and the
whole-branch checks of README "How to execute a plan" at 7fe1594.
Item 13 is accepted with a note: comments beside rewritten code changed,
but the only removed comment lines holding a Deno call are the planned
ones, so PR 25 keeps the rest. The test evidence is reused from the same
HEAD; the preview Ctrl-C checks and the changelog PR number wait for the
open PR.
@posit-snyk-bot

posit-snyk-bot commented Nov 27, 2026 •

Copy link
Copy Markdown
Collaborator

✅ Snyk checks have passed. No issues have been found so far.

Status Scan Engine Critical High Medium Low Total (0)
✅ Open Source Security 0 0 0 0 0 issues
✅ Licenses 0 0 0 0 0 issues

💻 Catch issues earlier using the plugins for VS Code, JetBrains IDEs, Visual Studio, and Eclipse.

Items 13 and 14 were ticked with their exceptions recorded only in the
wrap-up log entry; the boxes now name them, so the checklist does not
read as a clean pass.
…is gone

After a short passthrough write, execProcess sends SIGTERM and then
waited on the child's status with no deadline (`quarto run` passes no
timeout). On POSIX a script that traps or ignores SIGTERM keeps writing
into pipes that execProcess keeps draining, so `quarto run script |
head -n 1` hung indefinitely. Before the process layer, the broken
write threw and Quarto exited.

Wait at most 2 seconds, then return a failed result without killing the
child. Signal escalation stays out by design: the child remains
registered for exit cleanup, and once Quarto exits its next write meets
a pipe with no reader, which is where the old behavior left it.

The new test case is POSIX-only in substance: Windows terminates the
child on kill(), so it passes there with or without this change.
After a short passthrough write, execProcess stopped the child with
SIGTERM but kept reading both pipes, so Quarto itself stood in for the
reader that went away. That premise produced each failure in turn: a
worker holding the pipes kept EOF from coming, a child ignoring SIGTERM
never saw a write error, and once the grace period expired the
abandoned reads kept draining in the background, which in a long-lived
preview leaves the pre/post-render script running.

On main the stop came from the broken pipe Quarto's exit caused. Cause
it without exiting: read each stream through its own reader and, on the
short write, SIGTERM the child and cancel both readers. Cancelling ends
our pending reads at once and closes our end of the pipes, so the child
(or a worker that inherited them) meets a broken pipe on its next
write. `stream.values()` cannot do this: on Deno 2.9.8, return() on its
iterator with a read pending on a silent stream does not resolve, while
reader.cancel() resolves the pending read with done (checked on Linux
and Windows). This removes the reader-gone signal and the race that
waited on it.

The 2 s grace stays for a child that ignores SIGTERM and no longer
writes; such a child now leaves the exit-cleanup list when it ends, so
the list does not grow across preview re-renders.

The SIGTERM-ignoring test now has its writer exit with 7 after the
broken pipe and asserts that code reaches the caller: on Linux it got 1
(grace expiry) before this change and 7 after. Windows terminates the
child on kill(), so it expects 1 there.
Reading through explicit readers dropped what `stream.values()` did on
an early exit: cancel the stream. When a stderrFilter throws, execProcess
rejects but the stderr reader stays open and unread, so a child still
writing blocks on the full pipe instead of meeting a broken pipe. No
in-tree caller reaches this (the one filter, in rmd.ts, merges output
and takes the values() branch), but quarto.system.execProcess exposes
stderrFilter to engines.

readerChunks now cancels its reader when the consumer stops before EOF.
The new test fails on Windows and Linux without the change (the child
is still blocked after 10 s) and passes with it.
On Windows, Ctrl-C reaches an external preview server (shiny, a project
`serve:` command) as well as Quarto. By the time Quarto's synchronous
cleanup calls stop(), taskkill finds no process, and the fallback
process.kill() fails with "Access is denied": Deno has not yet seen the
exit, and Windows refuses to terminate a process that has already ended.
Every Ctrl-C of such a preview then printed "Error occurred during
cleanup: PermissionDenied". Calling process.kill() at once, as stop() did
before taskkill, won the race and printed nothing.

A server that no longer exists needs no fallback. isNoSuchProcess covers
both forms of that error: the Windows taskkill path's ESRCH code and
Deno.errors.NotFound from POSIX kill.

The new test fails on Windows without the change with the same error,
and passes on Windows and Linux with it.
isNoSuchProcess accepted any Deno NotFound to cover POSIX kill, whose
"no such process" error carries no code. On Windows that also matched a
failure to launch taskkill (a PATH without System32 gives NotFound), so
the preview server's stop() took it for an ended server and skipped its
direct-kill fallback, leaving the server running.

killProcess now tags the POSIX error with code ESRCH, as its Windows path
already does, and isNoSuchProcess matches that code only. The new
contract test fails on Linux without the tag and passes on Windows and
Linux with it.
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