Skip to content

armgit / Ix

Public Imported from GitHub
0

Understand any codebase instantly. System intelligence for codebases, built for humans and AI.

fix(ingest): widen the vm guard again, and decouple the teardown steps (#621)

Joseph Mikhail1ade249ac6a0
diff --git a/ix-cli/src/cli/__tests__/ingest-files.test.ts b/ix-cli/src/cli/__tests__/ingest-files.test.ts
index b439631e..128f46d0 100644
--- a/ix-cli/src/cli/__tests__/ingest-files.test.ts
+++ b/ix-cli/src/cli/__tests__/ingest-files.test.ts
@@ -308,13 +308,22 @@ describe("ingestFiles against a fake backend", () => {
// `saved` is shared across the describe, so the next `beforeEach`
// snapshotted those polluted values and the file's final restore wrote
// the fixture `HOME` back into the process.
- await backend.stop();
+ // And the steps do not share fate. Env first, because it is the one that
+ // leaks OUT of this file: a `stop()` that rejects or outruns the hook
+ // timeout would otherwise skip it and leave the whole process pointed at
+ // a deleted fixture home. `backend` is optional-chained because a
+ // `beforeEach` that throws in `mkdtempSync` leaves it unassigned, and a
+ // TypeError here would bury that failure.
for (const [k, v] of Object.entries(saved)) {
if (v === undefined) delete process.env[k];
else process.env[k] = v;
}
- rmSync(home, { recursive: true, force: true });
- rmSync(repo, { recursive: true, force: true });
+ try {
+ await backend?.stop();
+ } finally {
+ rmSync(home, { recursive: true, force: true });
+ rmSync(repo, { recursive: true, force: true });
+ }
}
});
diff --git a/ix-cli/src/cli/__tests__/ingestion-loader.test.ts b/ix-cli/src/cli/__tests__/ingestion-loader.test.ts
new file mode 100644
index 00000000..844ad2b9
--- /dev/null
+++ b/ix-cli/src/cli/__tests__/ingestion-loader.test.ts
@@ -0,0 +1,86 @@
+import { describe, expect, it } from "vitest";
+
+import { isVmDynamicImportUnavailable } from "../commands/ingestion-loader.js";
+
+/**
+ * The loader reaches `ingestFiles` through `new Function("return import(...)")`
+ * so the specifier stays invisible to bundlers. That indirection cannot run in
+ * a `vm` context without an `importModuleDynamically` hook -- vitest's
+ * vite-node being the one that matters -- so there is a fallback, and this
+ * predicate is the gate on it. Get the gate wrong in either direction and the
+ * damage is quiet: too narrow and `ingestFiles` is unloadable under vite-node
+ * (which is how the whole commit path went untested through two rewrites); too
+ * wide and a genuine module-not-found is swallowed and retried.
+ *
+ * Every error below is DERIVED from a real failure rather than written out by
+ * hand. A hand-built `Error` with a plausible message and code proves only that
+ * the predicate matches the shape its author already had in mind, which is the
+ * shape it was written against -- so such a test passes whether or not the
+ * predicate is right about the runtime.
+ */
+describe("isVmDynamicImportUnavailable", () => {
+ /** The genuine article: run the loader's own indirection under vitest. */
+ async function realVmFailure(): Promise<unknown> {
+ try {
+ await new Function("specifier", "return import(specifier);")("node:path");
+ return null;
+ } catch (err) {
+ return err;
+ }
+ }
+
+ it("matches the error vitest's vm context actually raises", async () => {
+ const err = await realVmFailure();
+ // If this is null the host gained a dynamic-import hook and the fallback is
+ // no longer needed -- which is a real change worth failing on rather than
+ // skipping past, because the whole fallback would then be dead code.
+ expect(err, "expected the vm indirection to fail under vite-node").not.toBeNull();
+ expect(isVmDynamicImportUnavailable(err)).toBe(true);
+ });
+
+ it("still matches once a module runner has rethrown it with its own code", async () => {
+ // The regression this file exists for. An earlier revision matched `code`
+ // OR the message as a ternary -- message only when `code` was absent --
+ // which is narrower than the plain message test it replaced. Vite's module
+ // runner rethrows the vm failure with `code: 'ERR_LOAD_URL'` and the
+ // message preserved, so the wrapped error HAS a code, fails the prefix
+ // test, never reaches the message test, and the fallback never fires on the
+ // one host it is for.
+ const original = (await realVmFailure()) as Error;
+ const wrapped = new Error(original.message, { cause: original });
+ (wrapped as NodeJS.ErrnoException).code = "ERR_LOAD_URL";
+
+ expect(isVmDynamicImportUnavailable(wrapped)).toBe(true);
+ });
+
+ it("does not throw when the error carries a NUMERIC code", async () => {
+ // `NodeJS.ErrnoException['code']` is typed as a string, but libuv-, zlib-
+ // and OpenSSL-derived errors carry numbers. `code.startsWith` on one throws
+ // a TypeError from inside the loader's catch block, replacing the real load
+ // failure with an unrelated type error and discarding the original.
+ const numeric = new Error("some unrelated failure");
+ (numeric as unknown as { code: number }).code = -4058;
+
+ expect(() => isVmDynamicImportUnavailable(numeric)).not.toThrow();
+ expect(isVmDynamicImportUnavailable(numeric)).toBe(false);
+ });
+
+ it("does not match a genuine module-not-found", async () => {
+ // The other direction, and the reason this cannot simply return true: a
+ // real resolution failure must propagate, not be retried and reported
+ // twice. Derived, again -- an actual failed import of a module that is not
+ // there.
+ let err: unknown = null;
+ try {
+ // Through a variable, so TypeScript does not try to resolve it at compile
+ // time -- the point is a RUNTIME resolution failure.
+ const missing = "./this-module-does-not-exist.js";
+ await import(missing);
+ } catch (caught) {
+ err = caught;
+ }
+
+ expect(err, "expected the import to fail").not.toBeNull();
+ expect(isVmDynamicImportUnavailable(err)).toBe(false);
+ });
+});
diff --git a/ix-cli/src/cli/commands/ingestion-loader.ts b/ix-cli/src/cli/commands/ingestion-loader.ts
index 1c25a074..ef01ae0e 100644
--- a/ix-cli/src/cli/commands/ingestion-loader.ts
+++ b/ix-cli/src/cli/commands/ingestion-loader.ts
@@ -44,22 +44,43 @@ const importViaFunction = new Function(
* genuine module-not-found still propagates, rather than being retried and
* reported twice.
*/
+/**
+ * Is this "this host cannot do dynamic import", as opposed to any other error?
+ *
+ * Exported for its test. The shapes it has to accept are not guessable, which
+ * is why that test derives them from a real failure rather than writing plausible
+ * ones by hand.
+ */
+export function isVmDynamicImportUnavailable(err: unknown): boolean {
+ const code = (err as NodeJS.ErrnoException | null)?.code;
+ return (
+ (typeof code === "string" && code.startsWith("ERR_VM_DYNAMIC_IMPORT_CALLBACK_MISSING")) ||
+ /dynamic import callback/i.test(String(err))
+ );
+}
+
const importModule = async (specifier: string): Promise<any> => {
try {
return await importViaFunction(specifier);
} catch (err) {
- // Matched on `code`, not on the message. Node raises
- // ERR_VM_DYNAMIC_IMPORT_CALLBACK_MISSING and ..._FLAG here, and the
- // previous test was a substring of the English text -- reword that upstream
- // and this guard silently stops matching: the harness goes red with the
- // original vm error and a real vm-hosted consumer regresses to unloadable,
- // with nothing pointing at the guard. The message check is kept only as a
- // fallback for an error that arrives without a code.
- const code = (err as NodeJS.ErrnoException | null)?.code;
- const isVmCallbackMissing = code
- ? code.startsWith("ERR_VM_DYNAMIC_IMPORT_CALLBACK_MISSING")
- : /dynamic import callback/i.test(String(err));
- if (!isVmCallbackMissing) throw err;
+ // EITHER signal, never one excluding the other. Node raises
+ // ERR_VM_DYNAMIC_IMPORT_CALLBACK_MISSING (and a ..._FLAG variant) with a
+ // matching message, and the code is the stabler of the two -- but an
+ // earlier revision wrote this as a ternary, so the message test became
+ // reachable only when `code` was absent. That is NARROWER than the plain
+ // message match it replaced, and it breaks on the host this fallback exists
+ // for: Vite's module runner rethrows the vm failure with its own
+ // `code: 'ERR_LOAD_URL'` while preserving the message, so the wrapped error
+ // has a code, fails the prefix test, never reaches the message test, and
+ // `ingestFiles` becomes unloadable under vite-node.
+ //
+ // `typeof code === "string"` because `code` is only typed as a string.
+ // Numeric codes are common in the wild (libuv, zlib, OpenSSL), and
+ // `.startsWith` on one throws a TypeError from inside this catch --
+ // replacing the real load failure with an unrelated type error and
+ // discarding the original, which is the exact failure the rest of this
+ // block exists to prevent.
+ if (!isVmDynamicImportUnavailable(err)) throw err;
try {
// The ignore pragmas are load-bearing, not decoration. A bare
// `import(variable)` is exactly the static-analysis surface the