Skip to content
4 changes: 3 additions & 1 deletion docs/guides/native-candidate.md
Original file line number Diff line number Diff line change
Expand Up @@ -5423,7 +5423,9 @@ are allowed.
With the same explicit native binary/home selection used for `up`, run
`hack exec --path /absolute/project SERVICE -- /bin/echo hello`. The command targets
the current owned project/branch mapping, preserves binary stdout/stderr and the
command exit code, and never falls back to Compose. With piped input/output or
command exit code, and never falls back to Compose. Output redirected to a file
(`> out.txt`, `>> log`, `2>&1`) is written like any other command's output, and a
stream with no output leaves its file untouched. With piped input/output or
`HACK_NO_INTERACTIVE=1`, it uses finite exec with a 30-second observation budget;
a timeout may leave the command running and is not
retried. A ready foreground owner holds the provider lease briefly and often, and
Expand Down
23 changes: 21 additions & 2 deletions src/lib/native-authored-command.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1276,6 +1276,25 @@ export function nativeAuthoredCommandFailure(input: {
message: contract.unconfirmed,
});
}
/**
* Write one captured stream of an authored exec or one-off run to this
* process's stdout or stderr (HACK-2744). `Bun.write` with an empty payload
* truncates a regular-file destination to zero bytes, even one opened for
* append: with `>> log 2>&1`, a command with no stderr erased the whole file,
* its earlier content and the command's stdout included, and with `>> log`
* a command with no stdout erased the log. An empty stream therefore writes
* nothing; a non-empty one is written at the stream's current position, so
* append and truncate redirects behave as they do for any other command.
*/
export async function writeNativeCommandStream(
destination: typeof Bun.stdout,
bytes: Uint8Array
): Promise<void> {
if (bytes.byteLength === 0) {
return;
}
await Bun.write(destination, bytes);
}
type CommandCompletion = {
readonly exitCode: number;
readonly stdout: Uint8Array;
Expand Down Expand Up @@ -1331,11 +1350,11 @@ async function runAuthoredCommand(input: {
if (controller.signal.aborted) {
return 130;
}
await Bun.write(Bun.stdout, result.stdout);
await writeNativeCommandStream(Bun.stdout, result.stdout);
if (controller.signal.aborted) {
return 130;
}
await Bun.write(Bun.stderr, result.stderr);
await writeNativeCommandStream(Bun.stderr, result.stderr);
if (controller.signal.aborted) {
return 130;
}
Expand Down
51 changes: 51 additions & 0 deletions tests/fixtures/native-authored-exec-output-worker.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
/**
* HACK-2744 worker: writes one authored exec's captured streams to this
* process's real stdout and stderr, which the test points at files. `command`
* mode runs the public authored exec dispatch with an exec seam; `helper` mode
* calls only the stream writer (no platform requirement).
*
* Inputs (environment): HACK_TEST_MODE, HACK_TEST_STDOUT_BASE64,
* HACK_TEST_STDERR_BASE64, HACK_TEST_PROJECT_ROOT, HACK_TEST_NATIVE_HOME.
*/
import {
tryNativeAuthoredCommand,
writeNativeCommandStream,
} from "../../src/lib/native-authored-command.ts";

const stdout = Buffer.from(process.env.HACK_TEST_STDOUT_BASE64 ?? "", "base64");
const stderr = Buffer.from(process.env.HACK_TEST_STDERR_BASE64 ?? "", "base64");

if (process.env.HACK_TEST_MODE === "helper") {
await writeNativeCommandStream(Bun.stdout, stdout);
await writeNativeCommandStream(Bun.stderr, stderr);
process.exitCode = 0;
} else {
const projectRoot = process.env.HACK_TEST_PROJECT_ROOT ?? "";
const nativeHome = process.env.HACK_TEST_NATIVE_HOME ?? "";
const code = await tryNativeAuthoredCommand({
selected: { kind: "native", projectRoot },
options: {
cwd: projectRoot,
operation: "exec",
service: "web",
command: ["echo", "hello"],
},
env: {
HACK_RUNTIME_BACKEND: "native",
HACK_NATIVE_BINARY: `${projectRoot}/explicit-native`,
HACK_NATIVE_HOME: nativeHome,
},
exec: async () => ({
backend: "native",
run: "a".repeat(32),
service: "web",
container: "2".repeat(64),
exitCode: 0,
stdout,
stderr,
truncated: false,
}),
staleEnv: async () => null,
});
process.exitCode = code ?? 99;
}
168 changes: 168 additions & 0 deletions tests/native-authored-exec-output-file.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,168 @@
import { afterEach, expect, test } from "bun:test";
import { closeSync, openSync } from "node:fs";
import {
mkdir,
mkdtemp,
readFile,
realpath,
rm,
writeFile,
} from "node:fs/promises";
import { tmpdir } from "node:os";
import { join, resolve } from "node:path";

/**
* HACK-2744: an authored `hack exec` whose stdout (or stderr) is redirected to
* a regular file. `Bun.write` with an empty payload truncates a file
* destination, even one opened for append, so a command with no stderr erased
* a `>> log 2>&1` file: its earlier content and the command's stdout. These
* cases point the worker's real stdout and stderr at files the way a shell
* redirect does, then read the files back.
*/
const WORKER = resolve(
import.meta.dir,
"fixtures/native-authored-exec-output-worker.ts"
);
const roots: string[] = [];
afterEach(async () => {
await Promise.all(
roots.splice(0).map((root) => rm(root, { recursive: true, force: true }))
);
});

async function scratch() {
const root = await realpath(
await mkdtemp(join(tmpdir(), "native-authored-exec-output-"))
);
roots.push(root);
await mkdir(join(root, ".hack"), { mode: 0o700 });
await mkdir(join(root, "candidate"), { mode: 0o700 });
return root;
}

type Redirect = { readonly path: string; readonly flags: "a" | "w" };

async function run(opts: {
readonly root: string;
readonly mode: "command" | "helper";
readonly stdout: string;
readonly stderr: string;
readonly out: Redirect;
/** Omitted: stderr shares stdout's open file, as `2>&1` does. */
readonly err?: Redirect;
}): Promise<number> {
const outFd = openSync(opts.out.path, opts.out.flags);
const errFd = opts.err ? openSync(opts.err.path, opts.err.flags) : outFd;
try {
const child = Bun.spawn([process.execPath, WORKER], {
cwd: opts.root,
stdin: "ignore",
stdout: outFd,
stderr: errFd,
env: {
PATH: process.env.PATH ?? "",
HOME: opts.root,
TMPDIR: process.env.TMPDIR ?? tmpdir(),
HACK_NO_INTERACTIVE: "1",
HACK_TEST_MODE: opts.mode,
HACK_TEST_STDOUT_BASE64: Buffer.from(opts.stdout).toString("base64"),
HACK_TEST_STDERR_BASE64: Buffer.from(opts.stderr).toString("base64"),
HACK_TEST_PROJECT_ROOT: opts.root,
HACK_TEST_NATIVE_HOME: join(opts.root, "candidate"),
},
});
return await child.exited;
} finally {
closeSync(outFd);
if (errFd !== outFd) {
closeSync(errFd);
}
}
}

const cases = [
{
name: ">> log 2>&1 keeps the earlier line and adds stdout (no stderr)",
stdout: "hello\n",
stderr: "",
before: "earlier\n",
out: "a" as const,
shared: true,
expected: { out: "earlier\nhello\n" },
},
{
name: "> out 2>&1 holds stdout (no stderr)",
stdout: "hello\n",
stderr: "",
before: "stale\n",
out: "w" as const,
shared: true,
expected: { out: "hello\n" },
},
{
name: ">> log 2>&1 keeps both streams in order",
stdout: "hello\n",
stderr: "warn\n",
before: "earlier\n",
out: "a" as const,
shared: true,
expected: { out: "earlier\nhello\nwarn\n" },
},
{
name: ">> out with no stdout keeps the file, and 2>> err with no stderr keeps it",
stdout: "",
stderr: "",
before: "earlier\n",
out: "a" as const,
shared: false,
expected: { out: "earlier\n", err: "earlier-err\n" },
},
{
name: ">> out with stdout and 2>> err with no stderr keep both files",
stdout: "hello\n",
stderr: "",
before: "earlier\n",
out: "a" as const,
shared: false,
expected: { out: "earlier\nhello\n", err: "earlier-err\n" },
},
{
name: "> out and 2> err each get their own stream",
stdout: "hello\n",
stderr: "warn\n",
before: "stale\n",
out: "w" as const,
shared: false,
expected: { out: "hello\n", err: "warn\n" },
},
];

async function check(mode: "command" | "helper", c: (typeof cases)[number]) {
const root = await scratch();
const out = join(root, "out.txt");
const err = join(root, "err.txt");
await writeFile(out, c.before);
await writeFile(err, c.before.replace("\n", "-err\n"));
const code = await run({
root,
mode,
stdout: c.stdout,
stderr: c.stderr,
out: { path: out, flags: c.out },
err: c.shared ? undefined : { path: err, flags: c.out },
});
expect(code).toBe(0);
expect(await readFile(out, "utf8")).toBe(c.expected.out);
const expectedErr: string | undefined =
"err" in c.expected ? c.expected.err : undefined;
if (expectedErr !== undefined) {
expect(await readFile(err, "utf8")).toBe(expectedErr);
}
}

test.each(cases)("HACK-2744 stream writer: $name", (c) => check("helper", c));

const macTest = process.platform === "darwin" ? test : test.skip;
macTest.each(cases)("HACK-2744 authored hack exec: $name", (c) =>
check("command", c)
);
4 changes: 3 additions & 1 deletion tests/native-exec-stale-env.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -886,7 +886,9 @@ describe("authored native command wiring", () => {
}
expect(code).toBe(4);
expect(received.signal?.aborted).toBe(true);
expect(written).toEqual(["command-out\n", ""]);
// The empty stderr is deliberately not written: an empty `Bun.write`
// truncates a redirected file (HACK-2744).
expect(written).toEqual(["command-out\n"]);
expect(stderr).toEqual([]);
},
2000
Expand Down
Loading