This is an automated email from the ASF dual-hosted git repository.

jason810496 pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/airflow.git


The following commit(s) were added to refs/heads/main by this push:
     new 5118ea8943f TS SDK: Keep the bundle's error when airflow-ts-pack fails 
on a long minified line (#77306)
5118ea8943f is described below

commit 5118ea8943f1378d065565060a40d5b16bf7cd45
Author: Adam Postek <[email protected]>
AuthorDate: Thu Nov 26 03:01:32 2026 +0000

    TS SDK: Keep the bundle's error when airflow-ts-pack fails on a long 
minified line (#77306)
    
    * TS SDK: Keep the bundle's error when airflow-ts-pack fails on a long 
minified line
    
    Signed-off-by: Adam <[email protected]>
    
    * TS SDK: Keep pack errors on a piped stderr and bound how much of it is 
read
    
    Signed-off-by: Adam <[email protected]>
    
    * TS SDK: Clean up the stderr temp dir if opening it fails, and only report 
a failed bundle run
    
    Signed-off-by: Adam <[email protected]>
    
    ---------
    
    Signed-off-by: Adam <[email protected]>
---
 ts-sdk/src/cli/main.ts        |   3 +-
 ts-sdk/src/cli/pack.ts        |  87 ++++++++++++++++++++++++------
 ts-sdk/tests/cli/pack.test.ts | 121 +++++++++++++++++++++++++++++++++++++++++-
 3 files changed, 192 insertions(+), 19 deletions(-)

diff --git a/ts-sdk/src/cli/main.ts b/ts-sdk/src/cli/main.ts
index 1db958183fe..c0bb69a4dce 100644
--- a/ts-sdk/src/cli/main.ts
+++ b/ts-sdk/src/cli/main.ts
@@ -24,5 +24,6 @@ try {
   await runPack(process.argv.slice(2));
 } catch (error) {
   console.error(error instanceof Error ? error.message : error);
-  process.exit(1);
+  // process.exit() would drop stderr that is still being written to a pipe on 
macOS.
+  process.exitCode = 1;
 }
diff --git a/ts-sdk/src/cli/pack.ts b/ts-sdk/src/cli/pack.ts
index 7eb0d108938..6eba06554ab 100644
--- a/ts-sdk/src/cli/pack.ts
+++ b/ts-sdk/src/cli/pack.ts
@@ -25,8 +25,19 @@
 // bundle's own Dag registry and schema version, never from a hand-written 
sidecar.
 
 import { execFileSync } from "node:child_process";
-import { readFileSync, realpathSync, rmSync, writeFileSync } from "node:fs";
+import {
+  closeSync,
+  mkdtempSync,
+  openSync,
+  readFileSync,
+  readSync,
+  realpathSync,
+  rmSync,
+  statSync,
+  writeFileSync,
+} from "node:fs";
 import { readFile as readFileAsync } from "node:fs/promises";
+import { tmpdir } from "node:os";
 import path from "node:path";
 
 import {
@@ -45,6 +56,9 @@ const BUNDLE_FILENAME = "bundle.min.mjs";
 const STAGING_FILENAME = "bundle.pack-staging.mjs";
 const MANIFEST_TIMEOUT_MS = 60_000;
 const MANIFEST_MAX_BUFFER_BYTES = 64 * 1024 * 1024;
+const STDERR_TAIL_CHARS = 2000; // stderr opens with the whole minified line
+// The stderr file has no size cap, so read no more than its end.
+const STDERR_READ_LIMIT_BYTES = 1024 * 1024;
 const ESM_REQUIRE_BANNER =
   'import{createRequire as __airflowCreateRequire}from"node:module";' +
   "const require=__airflowCreateRequire(import.meta.url);";
@@ -115,24 +129,50 @@ function readSdkVersion(): string {
 }
 
 function readBundleManifest(bundlePath: string): BundleManifest {
-  let stdout: string;
+  // On macOS Node writes a piped stderr asynchronously, so output past the 64 
KiB pipe buffer is
+  // lost when the bundle exits, and Node prints the whole minified line 
before the error.
+  // Writes to a file are synchronous.
+  const stderrDir = mkdtempSync(path.join(tmpdir(), "airflow-ts-pack-"));
+  const stderrPath = path.join(stderrDir, "stderr");
+  let stderrFd: number;
   try {
-    stdout = execFileSync(process.execPath, [bundlePath, 
AIRFLOW_METADATA_FLAG], {
-      encoding: "utf-8",
-      timeout: MANIFEST_TIMEOUT_MS,
-      maxBuffer: MANIFEST_MAX_BUFFER_BYTES,
-    });
+    stderrFd = openSync(stderrPath, "w");
   } catch (error) {
-    const stderr = (error as { stderr?: string }).stderr ?? "";
-    const reported = stderr
-      .split("\n")
-      .reverse()
-      .find((line) => /^\w*Error: /.test(line.trim()))
-      ?.trim();
-    throw new Error(
-      reported ?? `Running the bundle with ${AIRFLOW_METADATA_FLAG} failed: 
${String(error)}`,
-      { cause: error },
-    );
+    rmSync(stderrDir, { recursive: true, force: true });
+    throw error;
+  }
+  let stdout: string;
+  try {
+    try {
+      stdout = execFileSync(process.execPath, [bundlePath, 
AIRFLOW_METADATA_FLAG], {
+        encoding: "utf-8",
+        stdio: ["pipe", "pipe", stderrFd],
+        timeout: MANIFEST_TIMEOUT_MS,
+        maxBuffer: MANIFEST_MAX_BUFFER_BYTES,
+      });
+    } catch (error) {
+      const stderr = readEnd(stderrPath, STDERR_READ_LIMIT_BYTES).text;
+      const reported = stderr
+        .split("\n")
+        .reverse()
+        .find((line) => /^\w*Error: /.test(line.trim()))
+        ?.trim();
+      throw new Error(
+        reported ??
+          `Running the bundle with ${AIRFLOW_METADATA_FLAG} failed: 
${String(error)}\n` +
+            stderr.trimEnd().slice(-STDERR_TAIL_CHARS),
+        { cause: error },
+      );
+    }
+    // Still pass on what a working bundle logs, such as warnings from user 
code.
+    const { text, skippedBytes } = readEnd(stderrPath, 
STDERR_READ_LIMIT_BYTES);
+    if (skippedBytes > 0) {
+      process.stderr.write(`[first ${skippedBytes} bytes of the bundle's 
stderr omitted]\n`);
+    }
+    if (text) process.stderr.write(text);
+  } finally {
+    closeSync(stderrFd);
+    rmSync(stderrDir, { recursive: true, force: true });
   }
 
   // Import-time logging from user code lands on stdout too; pick the sentinel 
line.
@@ -168,6 +208,19 @@ function readBundleManifest(bundlePath: string): 
BundleManifest {
   return manifest;
 }
 
+function readEnd(filePath: string, limit: number): { text: string; 
skippedBytes: number } {
+  const size = statSync(filePath).size;
+  const skippedBytes = Math.max(0, size - limit);
+  const fd = openSync(filePath, "r");
+  try {
+    const buffer = Buffer.alloc(size - skippedBytes);
+    const read = readSync(fd, buffer, 0, buffer.length, skippedBytes);
+    return { text: buffer.subarray(0, read).toString("utf-8"), skippedBytes };
+  } finally {
+    closeSync(fd);
+  }
+}
+
 // The document is checked before anything is read off it: JSON.parse also 
yields
 // null and primitives, and `null.supervisor_schema_version` would surface as a
 // raw TypeError rather than a report about the bundle.
diff --git a/ts-sdk/tests/cli/pack.test.ts b/ts-sdk/tests/cli/pack.test.ts
index 21f63b74596..b938db1fcce 100644
--- a/ts-sdk/tests/cli/pack.test.ts
+++ b/ts-sdk/tests/cli/pack.test.ts
@@ -17,12 +17,13 @@
  * under the License.
  */
 
-import { execFileSync } from "node:child_process";
+import { execFileSync, spawnSync } from "node:child_process";
 import { createHash } from "node:crypto";
 import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, 
writeFileSync } from "node:fs";
 import { tmpdir } from "node:os";
 import path from "node:path";
 import { fileURLToPath } from "node:url";
+import { build } from "esbuild";
 import { afterEach, describe, expect, it, vi } from "vitest";
 
 import {
@@ -41,6 +42,8 @@ const GOLDEN_BUNDLE = fileURLToPath(new 
URL("fixtures/bundle-v1.min.mjs", import
 const NOISY_ENTRY = fileURLToPath(new URL("fixtures/noisy-entry.ts", 
import.meta.url));
 const EMPTY_ENTRY = fileURLToPath(new URL("fixtures/empty-entry.ts", 
import.meta.url));
 const SDK_INDEX = fileURLToPath(new URL("../../src/index.ts", 
import.meta.url));
+const TS_SDK_DIR = fileURLToPath(new URL("../..", import.meta.url));
+const CLI_MAIN = path.join(TS_SDK_DIR, "src/cli/main.ts");
 
 // Shaped like what airflow-ts-pack ships: a code region nobody could read, 
and a source region
 // that needs escaping. Real esbuild output is not used here because the 
assertion is byte-exact
@@ -619,6 +622,85 @@ describe("runPack", () => {
     expect(existsSync(path.join(outdir, 
"bundle.pack-staging.mjs"))).toBe(false);
   });
 
+  it("reports the error from a bundle that fails on a minified line over 64 
KiB", async () => {
+    outdir = mkdtempSync(path.join(tmpdir(), "ts-pack-"));
+    const entry = path.join(outdir, "long-line-entry.ts");
+    writeFileSync(
+      entry,
+      [
+        `(globalThis as Record<string, unknown>).padding = 
${JSON.stringify("x".repeat(70_000))};`,
+        'throw new Error("final failure");',
+      ].join("\n"),
+    );
+    const stderr = captureStderr();
+
+    await expect(runPack([entry, "--outdir", outdir])).rejects.toHaveProperty(
+      "message",
+      "Error: final failure",
+    );
+    expect(stderr()).toBe("");
+  });
+
+  it("passes on what a working bundle writes to stderr", async () => {
+    outdir = mkdtempSync(path.join(tmpdir(), "ts-pack-"));
+    const entry = path.join(outdir, "warning-entry.ts");
+    writeFileSync(
+      entry,
+      [
+        `import { Bundle, Dag } from ${JSON.stringify(SDK_INDEX)};`,
+        'console.warn("heads up");',
+        'const warningDag = new Dag("warning_dag");',
+        'warningDag.task("solo", async () => undefined)();',
+        "await new Bundle(warningDag).serve();",
+      ].join("\n"),
+    );
+    const stderr = captureStderr();
+
+    await runPack([entry, "--outdir", outdir]);
+
+    expect(stderr()).toBe("heads up\n");
+    expect(existsSync(path.join(outdir, "bundle.min.mjs"))).toBe(true);
+  });
+
+  it("passes on only the last MiB of a working bundle's stderr", async () => {
+    outdir = mkdtempSync(path.join(tmpdir(), "ts-pack-"));
+    const entry = path.join(outdir, "noisy-entry.ts");
+    writeFileSync(
+      entry,
+      [
+        `import { Bundle, Dag } from ${JSON.stringify(SDK_INDEX)};`,
+        'process.stderr.write("x".repeat(1_100_000) + "\\nlast warning\\n");',
+        'const noisyDag = new Dag("noisy_dag");',
+        'noisyDag.task("solo", async () => undefined)();',
+        "await new Bundle(noisyDag).serve();",
+      ].join("\n"),
+    );
+    const stderr = captureStderr();
+
+    await runPack([entry, "--outdir", outdir]);
+
+    const omitted = 1_100_000 + "\nlast warning\n".length - 1024 * 1024;
+    expect(stderr()).toMatch(
+      new RegExp(
+        `^\\[first ${omitted} bytes of the bundle's stderr 
omitted\\]\\nx+\\nlast warning\\n$`,
+      ),
+    );
+    expect(stderr().length).toBeLessThan(1024 * 1024 + 100);
+  });
+
+  it("reports the end of stderr from a bundle that fails without an error 
line", async () => {
+    outdir = mkdtempSync(path.join(tmpdir(), "ts-pack-"));
+    const entry = path.join(outdir, "exit-entry.ts");
+    writeFileSync(
+      entry,
+      'process.stderr.write("x".repeat(5000) + "\\nlast 
words\\n");\nprocess.exit(1);',
+    );
+
+    await expect(runPack([entry, "--outdir", outdir])).rejects.toThrow(
+      /^Running the bundle with --airflow-metadata failed: 
[^]*\nx{1,1999}\nlast words$/,
+    );
+  });
+
   // A bundle can print the sentinel itself, so nothing on that line is 
trusted.
   it.each([
     [
@@ -921,3 +1003,40 @@ describe("runPack", () => {
     }
   });
 });
+
+describe("airflow-ts-pack", () => {
+  let cliDir: string;
+
+  afterEach(() => {
+    if (cliDir) rmSync(cliDir, { recursive: true, force: true });
+  });
+
+  // On macOS a piped stderr is written asynchronously, so exiting straight 
away dropped the
+  // error printed after a bundle's long warnings. Under tsx the drop does not 
happen, so run
+  // the CLI bundled, with plain node.
+  it("keeps the error after a bundle's long warnings when stderr is a pipe", 
async () => {
+    cliDir = mkdtempSync(path.join(TS_SDK_DIR, ".cli-test-"));
+    const cli = path.join(cliDir, "main.mjs");
+    await build({
+      entryPoints: [CLI_MAIN],
+      outfile: cli,
+      bundle: true,
+      platform: "node",
+      format: "esm",
+      packages: "external",
+      logLevel: "silent",
+    });
+    const entry = path.join(cliDir, "warns-without-serving.ts");
+    writeFileSync(entry, 'console.warn("w".repeat(500_000));');
+
+    const result = spawnSync(process.execPath, [cli, entry, "--outdir", 
cliDir], {
+      cwd: TS_SDK_DIR,
+      encoding: "utf-8",
+      stdio: ["ignore", "pipe", "pipe"],
+    });
+
+    expect(result.status).toBe(1);
+    expect(result.stderr).toContain("w".repeat(500_000));
+    expect(result.stderr.trimEnd()).toMatch(/^Bundle produced no 
--airflow-metadata output$/m);
+  });
+});

Reply via email to