Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/close-input-on-early-stop.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@cosyte/cli": patch
---

`cosyte parse` now closes its input file when the output pipe closes early (a `head` that has seen enough). Before, the file handle was left open, and on Node 26 the garbage collector could turn it into an uncaught error, so the run sometimes exited `1` with a platform error on stderr instead of `74` with `CLI_OUTPUT_WRITE_FAILED`.
23 changes: 16 additions & 7 deletions src/core/input.ts
Original file line number Diff line number Diff line change
Expand Up @@ -234,16 +234,25 @@ async function* readerAsChunks(read: () => Promise<Uint8Array>): AsyncGenerator<
yield* oneChunk(await read());
}

/** Re-attach the chunks detection consumed to the front of the unread remainder. */
/**
* Re-attach the chunks detection consumed to the front of the unread remainder. A consumer that stops
* early (a write to a closed pipe ends the record loop) finishes this generator, and the `finally`
* finishes the remainder with it, so the file it reads is closed. Left to the garbage collector, the
* open file handle is an uncaught error on Node 26, and the run exited 1 instead of 74.
*/
async function* rejoin(
head: readonly Uint8Array[],
rest: AsyncIterator<Uint8Array>,
rest: AsyncGenerator<Uint8Array>,
): AsyncGenerator<Uint8Array> {
for (const chunk of head) yield chunk;
for (;;) {
const step = await rest.next();
if (step.done === true) return;
yield step.value;
try {
for (const chunk of head) yield chunk;
for (;;) {
const step = await rest.next();
if (step.done === true) return;
yield step.value;
}
} finally {
await rest.return(undefined);
}
}

Expand Down
57 changes: 56 additions & 1 deletion test/input.test.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { describe, expect, it } from "vitest";

import { resolveInput } from "../src/core/input.js";
import { resolveInput, resolveInputStream } from "../src/core/input.js";
import { EXIT } from "../src/core/exit-codes.js";
import { CLI_CODES, CliError } from "../src/core/diagnostics.js";
import type { RunDeps } from "../src/core/io.js";
Expand Down Expand Up @@ -88,3 +88,58 @@ describe("resolveInput: the shared input + format front door", () => {
await expect(resolveInput("x.json", undefined, boom, "parse")).rejects.toThrow("unexpected");
});
});

describe("resolveInputStream releases the input when the consumer stops early", () => {
/**
* A chunk source that records whether it was finished. A real file source closes its file handle
* only when it is finished, and Node 26 turns a file handle left for the garbage collector into an
* uncaught error: a consumer that closed the pipe early then saw exit 1 instead of 74.
*/
function trackedSource(chunks: readonly string[]): {
readonly deps: RunDeps;
readonly finished: () => boolean;
} {
let finished = false;
async function* source(): AsyncGenerator<Uint8Array> {
try {
for (const c of chunks) yield await Promise.resolve(new TextEncoder().encode(c));
} finally {
finished = true;
}
}
const deps: RunDeps = {
readFile: () => Promise.reject(new Error("unused")),
readStdin: () => Promise.reject(new Error("unused")),
openFile: () => source(),
};
return { deps, finished: () => finished };
}

it("finishes the source when the consumer stops inside the detection window", async () => {
const t = trackedSource([
'{"resourceType":"Patient","id":"r0"}\n',
'{"resourceType":"Patient"}\n',
]);
const r = await resolveInputStream("records.ndjson", "fhir", t.deps, "parse");
expect(r.ok).toBe(true);
if (!r.ok) return;
const it = r.input.chunks[Symbol.asyncIterator]();
await it.next();
expect(t.finished()).toBe(false);
await it.return?.(undefined);
expect(t.finished()).toBe(true);
});

it("finishes the source when the consumer stops after the detection window", async () => {
const t = trackedSource(["a".repeat(600), "b", "c"]);
const r = await resolveInputStream("records.ndjson", "fhir", t.deps, "parse");
expect(r.ok).toBe(true);
if (!r.ok) return;
const it = r.input.chunks[Symbol.asyncIterator]();
await it.next();
await it.next();
expect(t.finished()).toBe(false);
await it.return?.(undefined);
expect(t.finished()).toBe(true);
});
});
Loading