Skip to content

Commit 27e746a

Browse files
authored
Keep multi-byte characters whole across execProcess output chunks (#15346)
execProcess decoded each read chunk of subprocess output on its own, so a UTF-8 character split across two chunks came back as two U+FFFD replacement characters in both the returned text and the console output. Output is now decoded with a streaming decoder per stream, which holds an incomplete character until the next chunk completes it. - filteredAsyncIterator is an async generator with one streaming decoder per stream; a chunk holding only part of a character yields nothing. - Merged stdout and stderr pass through the decoder before they are combined, so a pending character on one stream cannot be joined with bytes from the other. - processOutput decodes each chunk once and reuses the text for printing and accumulation. Fixes #15341
1 parent 11a9c60 commit 27e746a

5 files changed

Lines changed: 155 additions & 18 deletions

File tree

‎dev-docs/runtime-migration/README.md‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -152,6 +152,9 @@ The rows below are the ones that still need a named person or an external answer
152152
| PR 00c, Phase 1 plans, PRs 33–37 and tooling PR 38, release correction | Decided 2026-11-03: boundary work and the script notice target 1.12 on Deno; Node and script/extension changes target 1.13; bundled-Deno removal targets 1.14. In 00c, change "Starting with Quarto 1.12" to 1.13 in text and tests and publish the migration page before the 1.12 notice. Unlanded Phase 0/1 user-visible changes use `changelog-1.12.md`; PRs 33–36 use `changelog-1.13.md`, PR 37 uses `changelog-1.14.md`, and later tooling changes use their actual landing release. Shift the supported-surface matrix, compatibility warnings, retirement dates and soak from 1.12/1.13 to 1.13/1.14; rollback targets the last stable Deno release, expected 1.12. Do not change shipped 1.11 entries or historical evidence. | coordinator (plan refresh), release manager (cut dates) | step 0 of each affected plan; PR 09 review |
153153
| Any plan that type-checks `src/quarto.ts` (from PR 09 Task 3, 2026-10-28) | the command `deno check --unstable-kv --unstable-ffi --import-map=import_map.json quarto.ts` fails on Deno 2.7.14 and on 2.9.8 (re-checked 2026-11-03) with `Requires import access to "cdn.skypack.dev:443"` (a remote import in `src/core/yaml.ts:31`); add `--allow-import` | coordinator | step 0 of each |
154154
| PR 27 (from PR 09 Task 3, 2026-10-28) | The Deno types (2.7.14, and 2.9.8 re-checked 2026-11-03) make `Deno.SymlinkOptions.type` required and `Deno.truncateSync` string-only, so the layer's `symlink[Sync]` forwards an options object only when a `type` is given and `truncateSync` converts a URL with `toPathString`; the node:fs reimplementation keeps both behaviours | coordinator | PR 27 step 0 |
155+
| PR 08 Task 1 and Task 2 step 2 (from #15341, the `execProcess` UTF-8 fix on `main`) | The plan's premise that `src/deno_ral/process.ts` is 10 lines (context section, `08-ral-process.md:25`) is stale: `execPath(): string` already exists there with the planned signature. Task 2 step 2 imports `pooledMap` (`:933`) and its `processOutput` snippet (`:1047-1066`) restores the per-chunk body that decodes each chunk twice, which would revert the fix; applied as written over the current body, which already prints through its own helper, it would also print inherited output twice. Re-derive the snippet from the current `processOutput` (decode once with `{ stream: true }`, flush at the end, skip empty text) and make `writeStdoutSync`/`writeStderrSync` the only change; drop `pooledMap` from the import as `filteredAsyncIterator` no longer uses it. Add `unit/exec-process-utf8-chunks.test.ts` to Task 2's verification | PR 08 executor | PR 08 step 0 |
156+
| PR 28 Task 4 step 3 (from #15341) | the merged-mode `addStream` snippet (`28-ral-process-on-node-apis.md:894-900`) wraps only filtered streams (`filter ? filteredAsyncIterator(iterator, filter) : iterator`), which drops the per-stream decoding that keeps a character split across chunks whole when both streams are merged. Keep `filteredAsyncIterator(iterator, filter)` on both streams, and add `unit/exec-process-utf8-chunks.test.ts` to the PR's gate | PR 28 executor | PR 28 step 0 |
157+
| PRs 23 and 31 (from #15341) | `tests/unit/exec-process-utf8-chunks.test.ts` starts its child as `execPath() eval '<script>'`, a Deno-only invocation (the `eval` subcommand; the script body itself uses only `node:fs`). Add it to PR 23's runtime re-invocation inventory (`23-codemod-tests.md:42-43`) so PR 31's `runtimeScriptCommand` converts it | PR 23 executor | PR 23 step 0 |
155158

156159
## Shared rules and tables
157160

‎news/changelog-1.12.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -65,3 +65,4 @@ All changes included in 1.12:
6565
- ([#15271](https://github.com/quarto-dev/quarto-cli/issues/15271)): Translate the `tools-share` and `tools-download` language keys in Catalan, Chinese, Czech, Danish, Dutch, Finnish, French, German, Hebrew, Indonesian, Italian, Japanese, Korean, Lithuanian, Norwegian Bokmål, Norwegian Nynorsk, Polish, Portuguese, Russian, Slovak, Swedish, Turkish and Ukrainian, and `tools-share` in Serbian (Latin), using reviewed machine translation.
6666
- ([#15289](https://github.com/quarto-dev/quarto-cli/issues/15289)): Translate the `announcement-dismiss-label` language key, the accessible name of the close button of a website announcement, in Azerbaijani, Basque, Bulgarian, Catalan, Chinese (Simplified and Traditional), Czech, Dutch, Finnish, French, German, Hebrew, Icelandic, Indonesian, Italian, Japanese, Korean, Lithuanian, Norwegian Nynorsk, Polish, Portuguese, Russian, Serbian (Latin), Slovak, Slovenian, Spanish, Swedish, Turkish and Ukrainian, using reviewed machine translation.
6767
- ([#15325](https://github.com/quarto-dev/quarto-cli/issues/15325)): Validate and offer completion for `column`, `fig-column` and `tbl-column` in document front matter. They already took effect there, but an invalid value was silently accepted.
68+
- ([#15341](https://github.com/quarto-dev/quarto-cli/issues/15341)): Fix non-ASCII characters in large output from external tools such as Pandoc, knitr or LaTeX occasionally turning into `�`.

‎src/core/process.ts‎

Lines changed: 32 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@
44
* Copyright (C) 2020-2022 Posit Software, PBC
55
*/
66

7-
import { MuxAsyncIterator, pooledMap } from "async";
7+
import { MuxAsyncIterator } from "async";
88
import { debug, info } from "../deno_ral/log.ts";
99
import { onCleanup } from "./cleanup.ts";
1010
import { ProcessResult } from "./process-types.ts";
@@ -129,10 +129,7 @@ export async function execProcess(
129129
iterator: AsyncIterableIterator<Uint8Array<ArrayBuffer>>,
130130
filter?: (output: string) => string,
131131
) => {
132-
const streamIter = filter
133-
? filteredAsyncIterator(iterator, filter)
134-
: iterator;
135-
multiplexIterator.add(streamIter);
132+
multiplexIterator.add(filteredAsyncIterator(iterator, filter));
136133
};
137134

138135
addStream(process.stdout.values());
@@ -227,17 +224,27 @@ export function processSuccessResult(): ProcessResult {
227224
};
228225
}
229226

230-
function filteredAsyncIterator(
231-
iterator: AsyncIterableIterator<Uint8Array>,
232-
filter: (output: string) => string,
233-
): AsyncIterableIterator<Uint8Array> {
227+
// Re-encodes a byte stream so each yielded chunk holds whole characters: a
228+
// multi-byte character split across two reads is held back until complete.
229+
// Chunks that decode to no text yet are skipped, so the filter never sees "".
230+
async function* filteredAsyncIterator(
231+
iterator: AsyncIterable<Uint8Array>,
232+
filter?: (output: string) => string,
233+
): AsyncGenerator<Uint8Array> {
234234
const encoder = new TextEncoder();
235235
const decoder = new TextDecoder();
236-
return pooledMap(1, iterator, (data: Uint8Array) => {
237-
return Promise.resolve(
238-
encoder.encode(filter(decoder.decode(data))),
239-
);
240-
});
236+
const encode = (text: string) =>
237+
encoder.encode(filter ? filter(text) : text);
238+
for await (const chunk of iterator) {
239+
const text = decoder.decode(chunk, { stream: true });
240+
if (text !== "") {
241+
yield encode(text);
242+
}
243+
}
244+
const tail = decoder.decode();
245+
if (tail !== "") {
246+
yield encode(tail);
247+
}
241248
}
242249

243250
// Processes ouptut from an interator (stderr, stdout, etc...)
@@ -248,18 +255,25 @@ async function processOutput(
248255
): Promise<string> {
249256
const decoder = new TextDecoder();
250257
let outputText = "";
258+
const accept = (text: string) => {
259+
if (text === "") {
260+
return;
261+
}
262+
if ((output === "inherit" || output === undefined) && !which) {
263+
info(text, { newline: false });
264+
}
265+
outputText += text;
266+
};
251267
for await (const chunk of iterator) {
252268
if (output === "inherit" || output === undefined) {
253269
if (which === "stdout") {
254270
Deno.stdout.writeSync(chunk);
255271
} else if (which === "stderr") {
256272
Deno.stderr.writeSync(chunk);
257-
} else {
258-
info(decoder.decode(chunk), { newline: false });
259273
}
260274
}
261-
const text = decoder.decode(chunk);
262-
outputText += text;
275+
accept(decoder.decode(chunk, { stream: true }));
263276
}
277+
accept(decoder.decode());
264278
return outputText;
265279
}

‎src/deno_ral/process.ts‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,3 +8,7 @@ export const call = async (path: string, opts: Deno.CommandOptions = {}) => {
88
const cmd = new Deno.Command(path, opts);
99
return cmd.output();
1010
};
11+
12+
export function execPath(): string {
13+
return Deno.execPath();
14+
}
Lines changed: 115 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,115 @@
1+
/*
2+
* exec-process-utf8-chunks.test.ts
3+
*
4+
* Regression test for #15341: execProcess must keep a multi-byte UTF-8
5+
* character whole when the subprocess output splits it across two read
6+
* chunks. The child writes a long run of 3-byte characters, so read
7+
* boundaries (64 KiB is not a multiple of 3) fall inside a character.
8+
*
9+
* Copyright (C) 2026 Posit Software, PBC
10+
*/
11+
12+
import { unitTest } from "../test.ts";
13+
import { assertEquals } from "../asserts.ts";
14+
import { execProcess } from "../../src/core/process.ts";
15+
import { execPath } from "../../src/deno_ral/process.ts";
16+
17+
const kChar = "“";
18+
const kCount = 100_000;
19+
const expected = kChar.repeat(kCount);
20+
21+
// Child-side helpers: write all bytes to an fd, and sleep between writes.
22+
const prelude = `import { writeSync } from "node:fs";
23+
const w = (fd, b) => { let o = 0; while (o < b.length) o += writeSync(fd, b, o); };
24+
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
25+
`;
26+
27+
const childCmd = (script: string) => ({
28+
cmd: execPath(),
29+
args: ["eval", prelude + script],
30+
stdout: "piped" as const,
31+
stderr: "piped" as const,
32+
});
33+
34+
const largeCmd = (fd: 1 | 2) =>
35+
childCmd(`w(${fd}, new TextEncoder().encode("${kChar}".repeat(${kCount})));`);
36+
37+
// 3 rounds: stdout [E2]; stderr "”"; stdout [80 9C]. Each stdout character
38+
// is split across two writes with the other stream's output in between.
39+
const interleavedCmd = childCmd(`for (let i = 0; i < 3; i++) {
40+
w(1, Uint8Array.of(0xE2));
41+
await sleep(100);
42+
w(2, new TextEncoder().encode("”"));
43+
await sleep(100);
44+
w(1, Uint8Array.of(0x80, 0x9C));
45+
await sleep(100);
46+
}`);
47+
48+
const partialStderrCmd = childCmd(`w(2, Uint8Array.of(0xE2, 0x80));`);
49+
50+
const truncatedCmd = childCmd(`w(1, Uint8Array.of(0x61, 0xE2, 0x80));`);
51+
52+
unitTest("execProcess - stdout keeps characters split across chunks", async () => {
53+
const result = await execProcess(largeCmd(1));
54+
assertEquals(result.stdout, expected);
55+
});
56+
57+
unitTest("execProcess - stderr keeps characters split across chunks", async () => {
58+
const result = await execProcess(largeCmd(2));
59+
assertEquals(result.stderr, expected);
60+
});
61+
62+
unitTest(
63+
"execProcess - filtered stderr keeps characters split across chunks",
64+
async () => {
65+
const result = await execProcess(
66+
largeCmd(2),
67+
undefined,
68+
undefined,
69+
(output) => output,
70+
);
71+
assertEquals(result.stderr, expected);
72+
},
73+
);
74+
75+
unitTest(
76+
"execProcess - merged output keeps characters split across chunks",
77+
async () => {
78+
const result = await execProcess(
79+
largeCmd(2),
80+
undefined,
81+
"stderr>stdout",
82+
(output) => output,
83+
);
84+
assertEquals(result.stdout, expected);
85+
},
86+
);
87+
88+
unitTest(
89+
"execProcess - merged output interleaving streams keeps characters whole",
90+
async () => {
91+
const result = await execProcess(interleavedCmd, undefined, "stderr>stdout");
92+
// Mux order across sources is not a contract, so compare sorted characters.
93+
assertEquals([...result.stdout!].sort().join(""), "“““”””");
94+
},
95+
);
96+
97+
unitTest("execProcess - filter never sees empty text", async () => {
98+
const seen: string[] = [];
99+
const result = await execProcess(
100+
partialStderrCmd,
101+
undefined,
102+
undefined,
103+
(s) => {
104+
seen.push(s);
105+
return s;
106+
},
107+
);
108+
assertEquals(seen, ["�"]);
109+
assertEquals(result.stderr, "�");
110+
});
111+
112+
unitTest("execProcess - truncated tail decodes to one U+FFFD", async () => {
113+
const result = await execProcess(truncatedCmd);
114+
assertEquals(result.stdout, "a�");
115+
});

0 commit comments

Comments
 (0)