space-data-module-sdk 0.9.6 → 0.9.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -136,6 +136,10 @@
136
136
  <li>thread counts are swept via the fixture's <code>threadEnvVar</code> (default <code>SDM_PARITY_THREADS</code>) — runs at 1/2/4/8 (fixture-configurable) must be byte-identical within a lane AND across lanes. Browser sequential <em>throughput</em> divergence is sanctioned until <code>browser-worker-topology</code> lands; results must still match byte-for-byte;</li>
137
137
  <li>signed/published artifacts are stripped to the canonical module payload once (<code>toLoadableWasmBytes</code>) so every lane executes identical wasm bytes.</li>
138
138
  </ul>
139
+ <h2 id="command-surface-errors"><a class="anchor" href="#command-surface-errors" aria-hidden="true">#</a>Command-surface errors</h2>
140
+ <p>A non-zero command exit with a well-formed <code>$PIV</code> response on stdout throws <code>PluginInvokeError</code> in both the browser and WasmEdge harnesses. It preserves <code>statusCode</code>, <code>errorCode</code>, <code>errorMessage</code>, <code>exitCode</code>, and the decoded <code>response</code>. All three parity lanes record the same error summary in <code>commandError</code>.</p>
141
+ <p>A non-zero guest exit without a response frame throws <code>WasiExitError</code>, with <code>code</code> and guest <code>stderr</code>. Runtime traps remain runtime failures. Exit <code>0</code> is unchanged: the response is returned, including a handler-level non-zero <code>statusCode</code>.</p>
142
+ <p>Every lane run and report summary carries <code>exitCode</code> (a number, or <code>null</code> when no exit code is available) and <code>commandError</code> (<code>PluginInvokeError.toJSON()</code>, or <code>null</code>). Successful runs have <code>exitCode: 0</code> and <code>commandError: null</code>.</p>
139
143
  <h2 id="fixtures"><a class="anchor" href="#fixtures" aria-hidden="true">#</a>Fixtures</h2>
140
144
  <div class="codeblock"><div class="codeblock-head">json</div><pre><code>{
141
145
  &quot;name&quot;: &quot;sgp4-command-parity&quot;,
@@ -177,6 +181,7 @@
177
181
  <nav class="rail" aria-label="On this page"><h2>On this page</h2><ul><li><a class="depth-2" href="#running">Running</a></li>
178
182
  <li><a class="depth-2" href="#the-wasmedge-pin-one-place">The WasmEdge pin: ONE place</a></li>
179
183
  <li><a class="depth-2" href="#determinism-contract">Determinism contract</a></li>
184
+ <li><a class="depth-2" href="#command-surface-errors">Command-surface errors</a></li>
180
185
  <li><a class="depth-2" href="#fixtures">Fixtures</a></li>
181
186
  <li><a class="depth-2" href="#scope-and-current-limits-v1">Scope and current limits (v1)</a></li></ul></nav>
182
187
  </div>
@@ -82,6 +82,22 @@ Every lane receives EXACTLY the same guest-observable inputs:
82
82
  - signed/published artifacts are stripped to the canonical module payload once
83
83
  (`toLoadableWasmBytes`) so every lane executes identical wasm bytes.
84
84
 
85
+ ## Command-surface errors
86
+
87
+ A non-zero command exit with a well-formed `$PIV` response on stdout throws
88
+ `PluginInvokeError` in both the browser and WasmEdge harnesses. It preserves
89
+ `statusCode`, `errorCode`, `errorMessage`, `exitCode`, and the decoded `response`.
90
+ All three parity lanes record the same error summary in `commandError`.
91
+
92
+ A non-zero guest exit without a response frame throws `WasiExitError`, with
93
+ `code` and guest `stderr`. Runtime traps remain runtime failures. Exit `0` is
94
+ unchanged: the response is returned, including a handler-level non-zero
95
+ `statusCode`.
96
+
97
+ Every lane run and report summary carries `exitCode` (a number, or `null` when
98
+ no exit code is available) and `commandError` (`PluginInvokeError.toJSON()`, or
99
+ `null`). Successful runs have `exitCode: 0` and `commandError: null`.
100
+
85
101
  ## Fixtures
86
102
 
87
103
  ```json
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "space-data-module-sdk",
3
- "version": "0.9.6",
3
+ "version": "0.9.8",
4
4
  "license": "Apache-2.0",
5
5
  "description": "Module SDK for building, validating, signing, and deploying WebAssembly modules on the Space Data Network.",
6
6
  "type": "module",
@@ -43,6 +43,7 @@ import {
43
43
  decodePluginInvokeResponse,
44
44
  writePluginInvokeRequestToArena,
45
45
  } from "../invoke/codec.js";
46
+ import { invokeErrorFromCommandRun } from "../invoke/commandOutcome.js";
46
47
  import { toUint8Array } from "../runtime/bufferLike.js";
47
48
  import {
48
49
  ModuleSignatureError,
@@ -857,6 +858,7 @@ export async function createBrowserModuleHarness(options = {}) {
857
858
  wasiThreadPoolSize: options.wasiThreadPoolSize,
858
859
  });
859
860
  lastCommandContext = commandContext;
861
+ let exitError = null;
860
862
  try {
861
863
  const commandExport = commandContext.instance.exports[DefaultInvokeExports.commandSymbol];
862
864
  if (typeof commandExport !== "function") {
@@ -866,13 +868,17 @@ export async function createBrowserModuleHarness(options = {}) {
866
868
  }
867
869
  commandExport();
868
870
  } catch (error) {
869
- if (!(error instanceof WasiExitError) || error.code !== 0) {
870
- throw error;
871
- }
871
+ if (!(error instanceof WasiExitError)) throw error;
872
+ if (error.code !== 0) exitError = error;
872
873
  } finally {
873
874
  await commandContext.threadHost?.terminateAll();
874
875
  }
875
- return commandContext.wasi.stdout;
876
+ const stdout = commandContext.wasi.stdout;
877
+ if (exitError) {
878
+ exitError.stderr = new TextDecoder().decode(commandContext.wasi.stderr);
879
+ throw invokeErrorFromCommandRun(exitError.code, stdout) ?? exitError;
880
+ }
881
+ return stdout;
876
882
  }
877
883
 
878
884
  // --- Public API ---
@@ -29,6 +29,13 @@ import {
29
29
  } from "../bundle/signing.js";
30
30
  import { attachHostDispatch, inspectModule } from "./isomorphicLoaderCore.js";
31
31
  import { assertArtifactRuntimeTarget } from "./runtimeTargetGate.js";
32
+ import { DEFAULT_HOSTCALL_IMPORT_MODULE } from "./abi.js";
33
+ import { WasiExitError } from "./wasiShim.js";
34
+ import { invokeErrorFromCommandRun } from "../invoke/commandOutcome.js";
35
+ import { normalizeWasmEdgeOutcome } from "../testing/wasmedgeOutput.js";
36
+
37
+ /** The typed failure the WasmEdge command harness's runner answers for any operation but plugin.getConfig. */
38
+ export const WASMEDGE_UNSUPPORTED_MESSAGE = "the WasmEdge command harness serves only plugin.getConfig";
32
39
 
33
40
  export { inspectModule, attachHostDispatch };
34
41
 
@@ -67,38 +74,73 @@ async function createWasmEdgeCommandHarness(options = {}) {
67
74
 
68
75
  const threaded = inspection.imports.some((entry) =>
69
76
  entry.module === "wasi" && entry.name === "thread-spawn");
77
+ // The plain WasmEdge CLI provides WASI and nothing else: an artifact that
78
+ // imports the typed hostcall bridge (space_data_module_host) fails to
79
+ // instantiate there ("unknown import"). The SDK's runner serves the bridge,
80
+ // threaded or not, so a bridged artifact always runs on it; plain wasmedge
81
+ // stays for WASI-only artifacts.
82
+ const bridged = inspection.imports.some((entry) =>
83
+ entry.module === DEFAULT_HOSTCALL_IMPORT_MODULE);
84
+ const useRunner = threaded || bridged;
70
85
  const hasCommand = inspection.exports.includes(DefaultInvokeExports.commandSymbol);
71
86
  const hasDirect = inspection.exports.includes(DefaultInvokeExports.invokeSymbol);
72
87
  // The one-shot wasi-threads runner serves the direct surface of a reactor,
73
88
  // and of a command artifact when the caller asks for it (--sdm-direct): the
74
89
  // module's constructors then run through its initializer export, never main.
75
- const surface = hasCommand && !(options.surface === "direct" && threaded && hasDirect)
90
+ const surface = hasCommand && !(options.surface === "direct" && useRunner && hasDirect)
76
91
  ? "command"
77
92
  : "direct";
78
- if (surface === "direct" && (!threaded || !hasDirect)) {
93
+ if (surface === "direct" && (!useRunner || !hasDirect)) {
79
94
  throw new Error(
80
95
  "Standalone WasmEdge loading requires a command-surface artifact with the _start export.",
81
96
  );
82
97
  }
83
98
 
84
- const command = threaded
99
+ const command = useRunner
85
100
  ? await (await import("../testing/buildWasmEdgeRunner.js")).resolveWasmEdgeWasiThreadsRunner(options)
86
101
  : options.wasmEdgeRunnerBinary ?? options.wasmEdgeBinary ?? "wasmedge";
87
102
  let launchWasmPath = wasmPath;
88
103
  let tempArtifactDir = null;
104
+ const ensureTempDir = async () => {
105
+ if (!tempArtifactDir) {
106
+ const [{ mkdtemp }, osModule] = await Promise.all([
107
+ import("node:fs/promises"),
108
+ import("node:os"),
109
+ ]);
110
+ const os = osModule.default ?? osModule;
111
+ tempArtifactDir = await mkdtemp(path.join(os.tmpdir(), "sdm-module-"));
112
+ }
113
+ return tempArtifactDir;
114
+ };
89
115
  if (loadableBytes.byteLength !== wasmBytes.byteLength) {
90
- const [{ mkdtemp, writeFile }, osModule] = await Promise.all([
116
+ const { writeFile } = await import("node:fs/promises");
117
+ launchWasmPath = path.join(await ensureTempDir(), "module.wasm");
118
+ await writeFile(launchWasmPath, loadableBytes);
119
+ }
120
+ // The runner replays staged $PIV answers for the bridge, as on the parity
121
+ // lanes: plugin.getConfig answers the module's config (options.config, else
122
+ // the host's plugin.getConfig(), else {}), and every other operation answers
123
+ // a typed "unsupported" failure.
124
+ const hostcallArgs = [];
125
+ if (bridged) {
126
+ const [{ writeFile }, { encodeParityHostcallAnswers, PARITY_HOSTCALL_FILES }] = await Promise.all([
91
127
  import("node:fs/promises"),
92
- import("node:os"),
128
+ import("../testing/parityHostcalls.js"),
93
129
  ]);
94
- const os = osModule.default ?? osModule;
95
- tempArtifactDir = await mkdtemp(path.join(os.tmpdir(), "sdm-module-"));
96
- launchWasmPath = path.join(tempArtifactDir, "module.wasm");
97
- await writeFile(launchWasmPath, loadableBytes);
130
+ const config = options.config ??
131
+ (typeof options.host?.plugin?.getConfig === "function" ? await options.host.plugin.getConfig() : {});
132
+ const answers = encodeParityHostcallAnswers(config, WASMEDGE_UNSUPPORTED_MESSAGE);
133
+ const dir = await ensureTempDir();
134
+ const configPath = path.join(dir, PARITY_HOSTCALL_FILES.config);
135
+ const unsupportedPath = path.join(dir, PARITY_HOSTCALL_FILES.unsupported);
136
+ await writeFile(configPath, answers.config);
137
+ await writeFile(unsupportedPath, answers.unsupported);
138
+ hostcallArgs.push("--sdm-hostcall-config", configPath, "--sdm-hostcall-unsupported", unsupportedPath);
98
139
  }
99
140
 
100
141
  const args = [
101
142
  ...(surface === "direct" && hasCommand ? ["--sdm-direct"] : []),
143
+ ...hostcallArgs,
102
144
  ...(options.enableThreads === false ? [] : ["--enable-threads"]),
103
145
  ...Object.entries(options.env ?? {}).flatMap(([key, value]) => ["--env", `${key}=${value}`]),
104
146
  launchWasmPath,
@@ -150,17 +192,33 @@ async function createWasmEdgeCommandHarness(options = {}) {
150
192
  );
151
193
  });
152
194
  child.on("close", (code, signal) => {
153
- if (code !== 0 || signal !== null) {
195
+ if (signal !== null) {
154
196
  reject(
155
197
  formatFailure(
156
- `WasmEdge command harness exited with ${
157
- signal ? `signal ${signal}` : `code ${code}`
158
- }.`,
198
+ `WasmEdge command harness exited with signal ${signal}.`,
159
199
  ),
160
200
  );
161
201
  return;
162
202
  }
163
- resolve(new Uint8Array(Buffer.concat(stdoutChunks)));
203
+ const stdout = new Uint8Array(Buffer.concat(stdoutChunks));
204
+ if (code === 0) {
205
+ resolve(stdout);
206
+ return;
207
+ }
208
+ const stderr = Buffer.concat(stderrChunks);
209
+ const normalized = normalizeWasmEdgeOutcome({ stdout, stderr });
210
+ const invokeError = invokeErrorFromCommandRun(code, normalized.stdout);
211
+ if (invokeError) {
212
+ reject(invokeError);
213
+ } else if (normalized.diagnostics) {
214
+ reject(new Error(
215
+ `WasmEdge command harness exited with code ${code}.\n${normalized.diagnosticText.trim()}`,
216
+ ));
217
+ } else {
218
+ const error = new WasiExitError(code);
219
+ error.stderr = stderr.toString("utf8");
220
+ reject(error);
221
+ }
164
222
  });
165
223
  child.stdin.end(Buffer.from(normalizedRequest));
166
224
  });
@@ -202,6 +260,8 @@ async function createWasmEdgeCommandHarness(options = {}) {
202
260
  * @param {string[]} [options.args] - WASI args.
203
261
  * @param {Object} [options.env] - WASI environment variables.
204
262
  * @param {string} [options.surface] - "direct" or "command".
263
+ * @param {Object} [options.config] - The module config plugin.getConfig answers
264
+ * on the WasmEdge leg (default: options.host's plugin.getConfig(), else {}).
205
265
  * @param {Object} [options.runtimeHost] - Runtime host for row/region ops.
206
266
  * @returns {Promise<Object>} Harness with invoke(), readManifest(), destroy().
207
267
  */
@@ -278,10 +338,12 @@ export async function loadModule(options = {}) {
278
338
  if (needsCompiledModule) {
279
339
  const inspection = await inspectModule(wasmModule);
280
340
  const threaded = inspection.imports.some((entry) => entry.module === "wasi" && entry.name === "thread-spawn");
341
+ const bridged = inspection.imports.some((entry) => entry.module === DEFAULT_HOSTCALL_IMPORT_MODULE);
342
+ const useRunner = threaded || bridged;
281
343
  if (
282
344
  (inspection.profile === "standalone" || inspection.profile === "module-host-abi") &&
283
- (inspection.exports.includes("_start") || (threaded && inspection.exports.includes("plugin_invoke_stream"))) &&
284
- (!options.wasmEdgeRunnerBinary || options.surface === "command" || threaded)
345
+ (inspection.exports.includes("_start") || (useRunner && inspection.exports.includes("plugin_invoke_stream"))) &&
346
+ (!options.wasmEdgeRunnerBinary || options.surface === "command" || useRunner)
285
347
  ) {
286
348
  return attachHostDispatch(
287
349
  await createWasmEdgeCommandHarness(options),
package/src/index.d.ts CHANGED
@@ -1951,7 +1951,30 @@ export function createNodeHostSyncHostcallBridge(options: {
1951
1951
  }): HostcallBridge;
1952
1952
  export class WasiExitError extends Error {
1953
1953
  code: number;
1954
+ stderr?: string;
1954
1955
  }
1956
+ export interface CommandErrorSummary {
1957
+ name: "PluginInvokeError";
1958
+ message: string;
1959
+ exitCode: number;
1960
+ statusCode: number;
1961
+ errorCode: string | null;
1962
+ errorMessage: string | null;
1963
+ }
1964
+ export class PluginInvokeError extends Error {
1965
+ constructor(options: { exitCode: number; response: DecodedPluginInvokeResponseEnvelope });
1966
+ name: "PluginInvokeError";
1967
+ exitCode: number;
1968
+ statusCode: number;
1969
+ errorCode: string | null;
1970
+ errorMessage: string | null;
1971
+ response: DecodedPluginInvokeResponseEnvelope;
1972
+ toJSON(): CommandErrorSummary;
1973
+ }
1974
+ export function invokeErrorFromCommandRun(
1975
+ exitCode: number | null,
1976
+ stdout: Uint8Array | ArrayBufferView | ArrayBuffer,
1977
+ ): PluginInvokeError | null;
1955
1978
  export interface BrowserWasiShim {
1956
1979
  imports: Record<string, Record<string, (...args: number[]) => number>>;
1957
1980
  setMemory(mem: { buffer: ArrayBuffer | SharedArrayBuffer }): void;
@@ -0,0 +1,38 @@
1
+ /**
2
+ * What a non-zero command exit means. A command-surface guest writes its PIV
3
+ * response to stdout whether or not the request succeeded and exits non-zero
4
+ * when validation or dispatch failed (compiler/invokeGlue.js `main`), so a
5
+ * well-formed response on a non-zero exit is the guest's own explanation.
6
+ * The browser and WasmEdge harnesses and every parity lane read it here.
7
+ */
8
+ import { decodePluginInvokeResponse } from "./codec.js";
9
+ import { toUint8Array } from "../runtime/bufferLike.js";
10
+
11
+ export class PluginInvokeError extends Error {
12
+ constructor({ exitCode, response }) {
13
+ const detail = [response.errorCode, response.errorMessage].filter(Boolean).join(": ");
14
+ super(`${detail || "module returned an error response"} (status ${response.statusCode})`);
15
+ this.name = "PluginInvokeError";
16
+ this.exitCode = exitCode;
17
+ this.statusCode = response.statusCode;
18
+ this.errorCode = response.errorCode ?? null;
19
+ this.errorMessage = response.errorMessage ?? null;
20
+ this.response = response;
21
+ }
22
+
23
+ toJSON() {
24
+ const { name, message, exitCode, statusCode, errorCode, errorMessage } = this;
25
+ return { name, message, exitCode, statusCode, errorCode, errorMessage };
26
+ }
27
+ }
28
+
29
+ export function invokeErrorFromCommandRun(exitCode, stdout) {
30
+ if (!Number.isInteger(exitCode) || exitCode === 0) return null;
31
+ try {
32
+ const bytes = toUint8Array(stdout);
33
+ if (!bytes || bytes.byteLength < 8) return null;
34
+ return new PluginInvokeError({ exitCode, response: decodePluginInvokeResponse(bytes) });
35
+ } catch {
36
+ return null;
37
+ }
38
+ }
@@ -11,3 +11,4 @@ export {
11
11
  normalizeInvokeSurfaces,
12
12
  writePluginInvokeRequestToArena,
13
13
  } from "./codec.js";
14
+ export { PluginInvokeError, invokeErrorFromCommandRun } from "./commandOutcome.js";
@@ -1,4 +1,5 @@
1
1
  import type {
2
+ CommandErrorSummary,
2
3
  InvokeSurface,
3
4
  PayloadTypeRef,
4
5
  PayloadWireFormat,
@@ -535,6 +536,8 @@ export interface ParityRunResult {
535
536
  threadCount: number;
536
537
  exitClass: string;
537
538
  exitDetail?: string | null;
539
+ exitCode: number | null;
540
+ commandError: CommandErrorSummary | null;
538
541
  stdout: Uint8Array;
539
542
  stderr?: Uint8Array;
540
543
  stateFiles?: Record<string, string> | null;
@@ -563,6 +566,8 @@ export interface ParityReport {
563
566
  threadCount: number;
564
567
  exitClass: string;
565
568
  exitDetail: string | null;
569
+ exitCode: number | null;
570
+ commandError: CommandErrorSummary | null;
566
571
  stdoutSha256: string;
567
572
  stdoutLength: number;
568
573
  }>;
@@ -76,6 +76,8 @@ export async function createStandaloneHarness(runtimeKind, wasmPath, options = {
76
76
  args: options.args,
77
77
  env: options.env,
78
78
  cwd: options.cwd,
79
+ // plugin.getConfig answers the same config the browser lane's host serves (hostOptions.config).
80
+ config: options.config ?? options.hostOptions?.config ?? options.host?.plugin?.getConfig?.(),
79
81
  });
80
82
  }
81
83
 
@@ -13,6 +13,8 @@
13
13
  */
14
14
 
15
15
  import { createBrowserModuleHarness } from "../host/browserModuleHarness.js";
16
+ import { WasiExitError } from "../host/wasiShim.js";
17
+ import { PluginInvokeError } from "../invoke/commandOutcome.js";
16
18
  import { parityHostcallDispatch } from "./parityHostcalls.js";
17
19
 
18
20
  const OK = "ok";
@@ -39,10 +41,18 @@ function bytesToBase64(bytes) {
39
41
  }
40
42
 
41
43
  function classifyBrowserError(error) {
44
+ if (error instanceof PluginInvokeError) {
45
+ return {
46
+ exitClass: GUEST_ERROR,
47
+ exitDetail: `exit=${error.exitCode}`,
48
+ exitCode: error.exitCode,
49
+ commandError: error.toJSON(),
50
+ };
51
+ }
42
52
  // WasiExitError with code 0 is swallowed inside the harness; reaching here
43
53
  // with one means a real nonzero guest exit.
44
- if (error?.name === "WasiExitError") {
45
- return { exitClass: GUEST_ERROR, exitDetail: `exit=${error.code}` };
54
+ if (error instanceof WasiExitError) {
55
+ return { exitClass: GUEST_ERROR, exitDetail: `exit=${error.code}`, exitCode: error.code, commandError: null };
46
56
  }
47
57
  // The harness refused the artifact because the ARTIFACT declares it does not
48
58
  // run here. That is the contract working. Classing it TRAP would score a
@@ -52,11 +62,15 @@ function classifyBrowserError(error) {
52
62
  return {
53
63
  exitClass: OUT_OF_SCOPE,
54
64
  exitDetail: `declared runtimeTargets [${(error.declaredTargets ?? []).join(", ")}]`,
65
+ exitCode: null,
66
+ commandError: null,
55
67
  };
56
68
  }
57
69
  return {
58
70
  exitClass: TRAP,
59
71
  exitDetail: `${error?.name ?? "Error"}: ${error?.message ?? String(error)}`,
72
+ exitCode: null,
73
+ commandError: null,
60
74
  };
61
75
  }
62
76
 
@@ -89,6 +103,8 @@ export async function runParityPlanInBrowser({ baseUrl = "" } = {}) {
89
103
  setStatus(`case ${planCase.id} @ ${threadCount} thread(s)`);
90
104
  let exitClass = OK;
91
105
  let exitDetail = null;
106
+ let exitCode = 0;
107
+ let commandError = null;
92
108
  let stdout = new Uint8Array(0);
93
109
  let stderr = new Uint8Array(0);
94
110
  let harness = null;
@@ -119,7 +135,7 @@ export async function runParityPlanInBrowser({ baseUrl = "" } = {}) {
119
135
  stdout = await harness.invokeRaw(stdinBytes);
120
136
  stderr = harness.wasi?.stderr ?? new Uint8Array(0);
121
137
  } catch (error) {
122
- ({ exitClass, exitDetail } = classifyBrowserError(error));
138
+ ({ exitClass, exitDetail, exitCode, commandError } = classifyBrowserError(error));
123
139
  } finally {
124
140
  stderr = harness?.wasi?.stderr ?? stderr;
125
141
  if (exitClass !== OK) stdout = harness?.wasi?.stdout ?? stdout;
@@ -135,6 +151,8 @@ export async function runParityPlanInBrowser({ baseUrl = "" } = {}) {
135
151
  threadCount,
136
152
  exitClass,
137
153
  exitDetail,
154
+ exitCode,
155
+ commandError,
138
156
  spawnCount,
139
157
  stdoutBase64: bytesToBase64(stdout),
140
158
  stderrBase64: bytesToBase64(stderr),
@@ -612,6 +612,8 @@ export async function runParityHarness(options = {}) {
612
612
  threadCount,
613
613
  exitClass: ExitClass.HarnessFailure,
614
614
  exitDetail: error?.message ?? String(error),
615
+ exitCode: null,
616
+ commandError: null,
615
617
  stdout: new Uint8Array(0),
616
618
  })),
617
619
  );
@@ -644,6 +646,8 @@ export async function runParityHarness(options = {}) {
644
646
  threadCount: run.threadCount,
645
647
  exitClass: run.exitClass,
646
648
  exitDetail: run.exitDetail ?? null,
649
+ exitCode: run.exitCode,
650
+ commandError: run.commandError,
647
651
  spawnCount: run.spawnCount ?? null,
648
652
  stdoutSha256: sha256Hex(toUint8Array(run.stdout) ?? new Uint8Array(0)),
649
653
  stdoutLength: (toUint8Array(run.stdout) ?? new Uint8Array(0)).length,
@@ -27,8 +27,11 @@ export function parityHostcallDispatch(config) {
27
27
  };
28
28
  }
29
29
 
30
- /** The $PIV answers the WasmEdge runner replays for one case: {config, unsupported} bytes. */
31
- export function encodeParityHostcallAnswers(config) {
30
+ /**
31
+ * The $PIV answers the WasmEdge runner replays for one case: {config, unsupported} bytes. `message` is the unsupported
32
+ * failure's text (the parity harness's by default).
33
+ */
34
+ export function encodeParityHostcallAnswers(config, message = PARITY_UNSUPPORTED_MESSAGE) {
32
35
  const failure = (error) => encodeHostCallResult({ ok: false, error: { code: hostcallErrorCode(error), message: String(error?.message ?? error) } });
33
36
  let answer;
34
37
  try {
@@ -36,5 +39,5 @@ export function encodeParityHostcallAnswers(config) {
36
39
  } catch (error) {
37
40
  answer = failure(error);
38
41
  }
39
- return { config: answer, unsupported: failure(unsupported()) };
42
+ return { config: answer, unsupported: failure(Object.assign(new Error(message), { hostcallCode: "unsupported" })) };
40
43
  }
@@ -30,6 +30,7 @@ import { promisify } from "node:util";
30
30
 
31
31
  import { ExitClass, assertWasmEdgeVersionMatchesPin } from "./parityHarness.js";
32
32
  import { normalizeWasmEdgeOutcome } from "./wasmedgeOutput.js";
33
+ import { invokeErrorFromCommandRun } from "../invoke/commandOutcome.js";
33
34
  import { isWasiThreadsModule } from "../host/wasiThreadHost.js";
34
35
  import { resolveWasmEdgeWasiThreadsRunner } from "./buildWasmEdgeRunner.js";
35
36
  import { PARITY_HOSTCALL_FILES, encodeParityHostcallAnswers, importsHostcallBridge } from "./parityHostcalls.js";
@@ -70,6 +71,29 @@ function classifyProcessOutcome({ code, signal, stderrText }) {
70
71
  return { exitClass: ExitClass.GuestError, exitDetail: `exit=${code}` };
71
72
  }
72
73
 
74
+ function wasmEdgeRun(outcome, caseId, threadCount, threaded) {
75
+ // WasmEdge logs diagnostics to stdout; separate them before classification.
76
+ const normalized = normalizeWasmEdgeOutcome(outcome);
77
+ const { exitClass, exitDetail } = classifyProcessOutcome({
78
+ code: outcome.code,
79
+ signal: outcome.signal,
80
+ stderrText: normalized.diagnosticText,
81
+ });
82
+ const exitCode = !outcome.signal && Number.isInteger(outcome.code) ? outcome.code : null;
83
+ return {
84
+ caseId,
85
+ threadCount,
86
+ exitClass,
87
+ exitDetail,
88
+ exitCode,
89
+ commandError: invokeErrorFromCommandRun(exitCode, normalized.stdout)?.toJSON() ?? null,
90
+ stdout: normalized.stdout,
91
+ stderr: normalized.stderr,
92
+ spawnCount: threaded ? Number(/sdm-wasi-threads: spawned=(\d+)/.exec(normalized.diagnosticText)?.[1] ?? NaN) : null,
93
+ stateFiles: null,
94
+ };
95
+ }
96
+
73
97
  function spawnWithStdin(command, args, { cwd, env, stdinBytes, timeoutMs }) {
74
98
  return new Promise((resolve, reject) => {
75
99
  const child = spawn(command, args, {
@@ -237,24 +261,7 @@ export async function runNativeWasmEdgeLane(context) {
237
261
  timeoutMs: context.timeoutMs,
238
262
  },
239
263
  );
240
- // WasmEdge logs its own diagnostics to STDOUT; pull them out before
241
- // anything compares guest bytes or classifies an exit.
242
- const normalized = normalizeWasmEdgeOutcome(outcome);
243
- const { exitClass, exitDetail } = classifyProcessOutcome({
244
- code: outcome.code,
245
- signal: outcome.signal,
246
- stderrText: normalized.diagnosticText,
247
- });
248
- runs.push({
249
- caseId: planCase.id,
250
- threadCount,
251
- exitClass,
252
- exitDetail,
253
- stdout: normalized.stdout,
254
- stderr: normalized.stderr,
255
- spawnCount: threaded ? Number(/sdm-wasi-threads: spawned=(\d+)/.exec(normalized.diagnosticText)?.[1] ?? NaN) : null,
256
- stateFiles: null,
257
- });
264
+ runs.push(wasmEdgeRun(outcome, planCase.id, threadCount, threaded));
258
265
  }
259
266
  }
260
267
  } finally {
@@ -363,22 +370,7 @@ export async function runDockerWasmEdgeLane(context) {
363
370
  stdinBytes: planCase.stdinBytes,
364
371
  timeoutMs: context.timeoutMs,
365
372
  });
366
- const normalized = normalizeWasmEdgeOutcome(outcome);
367
- const { exitClass, exitDetail } = classifyProcessOutcome({
368
- code: outcome.code,
369
- signal: outcome.signal,
370
- stderrText: normalized.diagnosticText,
371
- });
372
- runs.push({
373
- caseId: planCase.id,
374
- threadCount,
375
- exitClass,
376
- exitDetail,
377
- stdout: normalized.stdout,
378
- stderr: normalized.stderr,
379
- spawnCount: threaded ? Number(/sdm-wasi-threads: spawned=(\d+)/.exec(normalized.diagnosticText)?.[1] ?? NaN) : null,
380
- stateFiles: null,
381
- });
373
+ runs.push(wasmEdgeRun(outcome, planCase.id, threadCount, threaded));
382
374
  }
383
375
  }
384
376
  } finally {
@@ -588,6 +580,8 @@ export async function runBrowserLane(context) {
588
580
  threadCount: Number(run.threadCount),
589
581
  exitClass: String(run.exitClass),
590
582
  exitDetail: run.exitDetail ?? null,
583
+ exitCode: run.exitCode,
584
+ commandError: run.commandError,
591
585
  spawnCount: run.spawnCount ?? null,
592
586
  stdout: new Uint8Array(Buffer.from(String(run.stdoutBase64 ?? ""), "base64")),
593
587
  stderr: new Uint8Array(Buffer.from(String(run.stderrBase64 ?? ""), "base64")),
@@ -72,6 +72,7 @@ export function normalizeWasmEdgeOutcome({ stdout, stderr }) {
72
72
  return {
73
73
  stdout: guestStdout,
74
74
  stderr: encoder.encode(combined),
75
+ diagnostics,
75
76
  diagnosticText: combined,
76
77
  };
77
78
  }