Unblock native XYZAC TP oracle
This commit is contained in:
95
scripts/compare_xyzac_native_wasm_tick_trace.py
Normal file
95
scripts/compare_xyzac_native_wasm_tick_trace.py
Normal file
@@ -0,0 +1,95 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Compare the source LinuxCNC XYZAC oracle with the WASM worker trace."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import json
|
||||
import subprocess
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
NATIVE_REPORT = ROOT / "coverage/xyzac-native-tick-trace.report.json"
|
||||
WASM_REPORT = ROOT / "coverage/xyzac-wasm-tick-trace.report.json"
|
||||
REPORT = ROOT / "coverage/xyzac-native-wasm-tick-parity.report.json"
|
||||
|
||||
|
||||
def canonical(value: Any) -> str:
|
||||
return json.dumps(value, ensure_ascii=False, sort_keys=True, separators=(",", ":"))
|
||||
|
||||
|
||||
def digest(value: Any) -> str:
|
||||
return hashlib.sha256((value if isinstance(value, bytes) else canonical(value).encode())).hexdigest()
|
||||
|
||||
|
||||
def first_difference(left: Any, right: Any, path: str = "$") -> str | None:
|
||||
if type(left) is not type(right):
|
||||
return path
|
||||
if isinstance(left, dict):
|
||||
for key in sorted(set(left) | set(right)):
|
||||
if key not in left or key not in right:
|
||||
return f"{path}.{key}"
|
||||
difference = first_difference(left[key], right[key], f"{path}.{key}")
|
||||
if difference:
|
||||
return difference
|
||||
return None
|
||||
if isinstance(left, list):
|
||||
for index in range(max(len(left), len(right))):
|
||||
if index >= len(left) or index >= len(right):
|
||||
return f"{path}[{index}]"
|
||||
difference = first_difference(left[index], right[index], f"{path}[{index}]")
|
||||
if difference:
|
||||
return difference
|
||||
return None
|
||||
return None if left == right else path
|
||||
|
||||
|
||||
def canonical_row(row: dict[str, Any]) -> dict[str, Any]:
|
||||
result = dict(row)
|
||||
for key in ("joint_actual", "joint_commanded", "homed", "limits"):
|
||||
if isinstance(result.get(key), list):
|
||||
result[key] = result[key][:5]
|
||||
return result
|
||||
|
||||
|
||||
def compare_rows(native: list[dict[str, Any]], wasm: list[dict[str, Any]]) -> dict[str, Any]:
|
||||
fields = ("task_state", "task_mode", "interp_state", "exec_state", "current_line", "motion_line", "actual_pose", "commanded_pose", "joint_actual", "joint_commanded", "velocity", "queue_depth", "motion_id", "active_segment_id", "position", "homed", "limits", "kinematics_type", "motion_type", "paused")
|
||||
for index in range(max(len(native), len(wasm))):
|
||||
if index >= len(native) or index >= len(wasm):
|
||||
return {"status": "diverged", "first_divergent_tick": index, "difference_path": f"$.rows[{index}]", "native": native[index] if index < len(native) else None, "wasm": wasm[index] if index < len(wasm) else None}
|
||||
native_row = canonical_row(native[index])
|
||||
wasm_row = canonical_row(wasm[index])
|
||||
for field in fields:
|
||||
if native_row.get(field) != wasm_row.get(field):
|
||||
return {"status": "diverged", "first_divergent_tick": index, "difference_path": f"$.rows[{index}].{field}", "native": native_row.get(field), "wasm": wasm_row.get(field)}
|
||||
return {"status": "verified", "first_divergent_tick": None, "difference_path": None}
|
||||
|
||||
|
||||
def main() -> int:
|
||||
native = json.loads(NATIVE_REPORT.read_text(encoding="utf-8"))
|
||||
wasm_ticks = max(1, min(1000, int(native.get("row_count") or 1)))
|
||||
build = subprocess.run(["node", "scripts/run_xyzac_wasm_tick_trace.mjs", "--ticks", str(wasm_ticks), "--output", str(WASM_REPORT)], cwd=ROOT, text=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, check=False, timeout=120)
|
||||
wasm = json.loads(WASM_REPORT.read_text(encoding="utf-8")) if WASM_REPORT.is_file() else {"status": "blocked", "rows": []}
|
||||
comparison = compare_rows(native.get("rows", []), wasm.get("rows", [])) if native.get("status") == "verified" and wasm.get("status") == "verified" else {"status": "blocked", "first_divergent_tick": None, "difference_path": None}
|
||||
report = {
|
||||
"schema": "xyzac-native-wasm-tick-parity.v1",
|
||||
"status": comparison["status"],
|
||||
"candidate_eligible": comparison["status"] == "verified",
|
||||
"case": native.get("case"),
|
||||
"native": {"report": str(NATIVE_REPORT.relative_to(ROOT)), "report_sha256": native.get("report_sha256"), "trace_sha256": native.get("trace_sha256"), "row_count": native.get("row_count")},
|
||||
"wasm": {"report": str(WASM_REPORT.relative_to(ROOT)), "report_sha256": wasm.get("report_sha256"), "trace_sha256": wasm.get("trace_sha256"), "row_count": wasm.get("row_count"), "runner_returncode": build.returncode, "runner_output_sha256": digest(build.stdout)},
|
||||
"comparison": comparison,
|
||||
"first_divergent_tick": comparison.get("first_divergent_tick"),
|
||||
"difference_path": comparison.get("difference_path"),
|
||||
"known_boundaries": ["native public stat does not expose TP segment geometry", "WASM public snapshot does not expose acceleration/active blend geometry", "verified oracle availability is not a full TP numerical parity claim"],
|
||||
"release_status": "STOP_RELEASE",
|
||||
}
|
||||
report["report_sha256"] = digest({key: value for key, value in report.items() if key != "report_sha256"})
|
||||
REPORT.write_text(json.dumps(report, ensure_ascii=False, sort_keys=True, indent=2) + "\n", encoding="utf-8")
|
||||
print(json.dumps({"schema": report["schema"], "status": report["status"], "first_divergent_tick": report["first_divergent_tick"], "difference_path": report["difference_path"], "report_sha256": report["report_sha256"]}, ensure_ascii=False))
|
||||
return 0 if report["status"] == "verified" else 1
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
@@ -100,10 +100,20 @@ def cleanup_linuxcnc_services() -> dict[str, object]:
|
||||
pass
|
||||
lock = Path("/tmp/linuxcnc.lock")
|
||||
lock_removed = False
|
||||
lock_backup = None
|
||||
if lock.exists() and not any(service_pattern.search(command) for _, command in process_rows()):
|
||||
lock.unlink()
|
||||
# Preserve stale lock evidence for post-mortem inspection. A lock is
|
||||
# runtime state, not a repository artifact, so moving it is sufficient
|
||||
# and recoverable while allowing the next source launcher to start.
|
||||
lock_backup_path = Path(f"/tmp/linuxcnc.lock.stale-{time.strftime('%Y%m%d-%H%M%S')}")
|
||||
suffix = 1
|
||||
while lock_backup_path.exists():
|
||||
lock_backup_path = Path(f"/tmp/linuxcnc.lock.stale-{time.strftime('%Y%m%d-%H%M%S')}-{suffix}")
|
||||
suffix += 1
|
||||
lock.rename(lock_backup_path)
|
||||
lock_removed = True
|
||||
return {"commands": commands, "killed_pids": killed, "lock_path": lock.as_posix(), "lock_removed": lock_removed, "remaining_services": [command for _, command in process_rows() if service_pattern.search(command)]}
|
||||
lock_backup = lock_backup_path.as_posix()
|
||||
return {"commands": commands, "killed_pids": killed, "lock_path": lock.as_posix(), "lock_removed": lock_removed, "lock_backup": lock_backup, "remaining_services": [command for _, command in process_rows() if service_pattern.search(command)]}
|
||||
|
||||
|
||||
def run(screenshot_path: Path | None = None) -> dict[str, object]:
|
||||
|
||||
@@ -16,16 +16,22 @@ import os
|
||||
import re
|
||||
import signal
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
# The oracle must bind to the same source build that run-5axis-rtcp.sh starts.
|
||||
# In particular, importing the distro linuxcnc extension would silently bind to
|
||||
# a different NML ABI/version and produce plausible but unusable status values.
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
SOURCE_PYTHON_DIR = ROOT / "linuxcnc/lib/python"
|
||||
sys.path.insert(0, str(SOURCE_PYTHON_DIR))
|
||||
import linuxcnc
|
||||
|
||||
from run_axis3_tutorial_native import cleanup_linuxcnc_services
|
||||
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
CASE = "linuxcnc/configs/sim/axis/vismach/5axis/table-rotary-tilting/xyzac-trt.ini"
|
||||
PROGRAM = ROOT / "linuxcnc/configs/sim/axis/vismach/5axis/table-rotary-tilting/demos/xyzac_switchkins.ngc"
|
||||
SCHEMA = "xyzac-native-linuxcnc-tick-trace.v1"
|
||||
@@ -58,10 +64,13 @@ def scalar(value: Any) -> float | int | bool | str | None:
|
||||
|
||||
def stat_row(stat: Any, sample_index: int, previous_taskbeat: int | None) -> dict[str, Any]:
|
||||
stat.poll()
|
||||
taskbeat = scalar(getattr(stat, "taskbeat", None))
|
||||
taskbeat = scalar(getattr(stat, "task_heartbeat", None))
|
||||
commanded_pose = finite_list(getattr(stat, "position", None))
|
||||
distance_to_go = finite_list(getattr(stat, "dtg", None))
|
||||
return {
|
||||
"sample_index": sample_index,
|
||||
"taskbeat": taskbeat,
|
||||
"task_heartbeat": taskbeat,
|
||||
"taskbeat_changed": previous_taskbeat is None or taskbeat != previous_taskbeat,
|
||||
"task_state": scalar(getattr(stat, "task_state", None)),
|
||||
"task_mode": scalar(getattr(stat, "task_mode", None)),
|
||||
@@ -71,7 +80,7 @@ def stat_row(stat: Any, sample_index: int, previous_taskbeat: int | None) -> dic
|
||||
"motion_line": scalar(getattr(stat, "motion_line", None)),
|
||||
"read_line": scalar(getattr(stat, "read_line", None)),
|
||||
"actual_pose": finite_list(getattr(stat, "actual_position", None)),
|
||||
"commanded_pose": finite_list(getattr(stat, "command_position", None)),
|
||||
"commanded_pose": commanded_pose,
|
||||
"joint_actual": finite_list(getattr(stat, "joint_actual_position", None)),
|
||||
"joint_commanded": finite_list(getattr(stat, "joint_position", None)),
|
||||
"velocity": scalar(getattr(stat, "current_vel", None)),
|
||||
@@ -86,7 +95,7 @@ def stat_row(stat: Any, sample_index: int, previous_taskbeat: int | None) -> dic
|
||||
"active_segment_id": scalar(getattr(stat, "motion_id", None)),
|
||||
"active_segment_geometry": None,
|
||||
"active_segment_geometry_status": "unavailable_linuxcnc_stat_api",
|
||||
"distance_to_go": finite_list(getattr(stat, "distance_to_go", None)),
|
||||
"distance_to_go": distance_to_go,
|
||||
"position": finite_list(getattr(stat, "position", None)),
|
||||
"homed": list(getattr(stat, "homed", [])) if getattr(stat, "homed", None) is not None else None,
|
||||
"limits": list(getattr(stat, "limit", [])) if getattr(stat, "limit", None) is not None else None,
|
||||
@@ -150,6 +159,7 @@ def run(duration: float) -> dict[str, Any]:
|
||||
output_lines: list[str] = []
|
||||
rows: list[dict[str, Any]] = []
|
||||
errors: list[str] = []
|
||||
stage = "launch"
|
||||
stat: Any = None
|
||||
control: Any = None
|
||||
connected = False
|
||||
@@ -161,34 +171,56 @@ def run(duration: float) -> dict[str, Any]:
|
||||
if not window:
|
||||
time.sleep(0.1)
|
||||
continue
|
||||
try:
|
||||
stat = linuxcnc.stat()
|
||||
control = linuxcnc.command()
|
||||
stat.poll()
|
||||
if getattr(stat, "task_state", None) in (linuxcnc.STATE_ESTOP, linuxcnc.STATE_ESTOP_RESET, linuxcnc.STATE_OFF, linuxcnc.STATE_ON):
|
||||
# The AXIS toplevel is created only after linuxcncsvr/milltask have
|
||||
# opened the NML buffers. Creating linuxcnc.stat before that point
|
||||
# permanently binds an invalid channel, so wait for the real
|
||||
# window first and create fresh channels afterwards.
|
||||
time.sleep(0.1)
|
||||
if stat is None or control is None or not connected:
|
||||
if not window:
|
||||
raise RuntimeError("native_linuxcnc_window_unavailable")
|
||||
stat = None
|
||||
control = None
|
||||
attach_deadline = time.monotonic() + 10
|
||||
while time.monotonic() < attach_deadline and process.poll() is None:
|
||||
try:
|
||||
candidate_stat = linuxcnc.stat()
|
||||
candidate_stat.poll()
|
||||
stat = candidate_stat
|
||||
control = linuxcnc.command()
|
||||
connected = True
|
||||
break
|
||||
except Exception:
|
||||
time.sleep(0.1)
|
||||
if stat is None or control is None or not connected:
|
||||
raise RuntimeError("native_linuxcnc_stat_unavailable")
|
||||
except BaseException:
|
||||
stat = None
|
||||
control = None
|
||||
time.sleep(0.1)
|
||||
if stat is None or control is None or not connected:
|
||||
raise RuntimeError("native_linuxcnc_stat_unavailable")
|
||||
|
||||
stage = "state_estop_reset"
|
||||
control.state(linuxcnc.STATE_ESTOP_RESET)
|
||||
control.wait_complete(5)
|
||||
wait_stat(stat, lambda item: item.task_state != linuxcnc.STATE_ESTOP, 5)
|
||||
stage = "state_on"
|
||||
control.state(linuxcnc.STATE_ON)
|
||||
control.wait_complete(5)
|
||||
wait_stat(stat, lambda item: item.task_state == linuxcnc.STATE_ON, 5)
|
||||
stage = "mode_manual"
|
||||
control.mode(linuxcnc.MODE_MANUAL)
|
||||
control.wait_complete(5)
|
||||
for joint in range(5):
|
||||
stage = f"home_joint_{joint}"
|
||||
control.home(joint)
|
||||
control.wait_complete(5)
|
||||
stage = "wait_home_all"
|
||||
wait_stat(stat, lambda item: all(bool(value) for value in list(getattr(item, "homed", []))[:5]), 10)
|
||||
stage = "program_open"
|
||||
control.program_open(str(PROGRAM))
|
||||
control.wait_complete(5)
|
||||
stage = "mode_auto"
|
||||
control.mode(linuxcnc.MODE_AUTO)
|
||||
control.wait_complete(5)
|
||||
stage = "program_run"
|
||||
control.auto(linuxcnc.AUTO_RUN, 0)
|
||||
|
||||
start = time.monotonic()
|
||||
@@ -208,10 +240,11 @@ def run(duration: float) -> dict[str, Any]:
|
||||
sample_index += 1
|
||||
time.sleep(0.005)
|
||||
final = stat_row(stat, sample_index + 1, previous_taskbeat)
|
||||
final["native_elapsed_ms"] = round((time.monotonic() - start) * 1000.0, 3)
|
||||
rows.append(final)
|
||||
if final["taskbeat_changed"]:
|
||||
final["native_elapsed_ms"] = round((time.monotonic() - start) * 1000.0, 3)
|
||||
rows.append(final)
|
||||
except Exception as error:
|
||||
errors.append(f"{type(error).__name__}:{error}")
|
||||
errors.append(f"{stage}:{type(error).__name__}:{error}")
|
||||
finally:
|
||||
terminate_process(process)
|
||||
try:
|
||||
@@ -222,12 +255,19 @@ def run(duration: float) -> dict[str, Any]:
|
||||
cleanup_linuxcnc_services()
|
||||
|
||||
source_bytes = PROGRAM.read_bytes()
|
||||
ini_path = ROOT / CASE
|
||||
launcher_path = ROOT / "run-5axis-rtcp.sh"
|
||||
heartbeat_values = [row.get("task_heartbeat") for row in rows]
|
||||
valid_heartbeats = [value for value in heartbeat_values if isinstance(value, int)]
|
||||
heartbeat_monotonic = all(left < right for left, right in zip(valid_heartbeats, valid_heartbeats[1:]))
|
||||
trace_hash = sha256_bytes(canonical(rows).encode())
|
||||
python_module = getattr(linuxcnc, "__file__", None)
|
||||
source_python_module = str(ROOT / "linuxcnc/lib/python/linuxcnc.so")
|
||||
if python_module != source_python_module:
|
||||
errors.append("NATIVE_PYTHON_MODULE_MISMATCH")
|
||||
status = "verified" if rows and not errors else "blocked"
|
||||
status = "verified" if rows and not errors and heartbeat_monotonic and len(valid_heartbeats) == len(set(valid_heartbeats)) else "blocked"
|
||||
if rows and not heartbeat_monotonic:
|
||||
errors.append("NATIVE_TASK_HEARTBEAT_NON_MONOTONIC")
|
||||
return {
|
||||
"schema": SCHEMA,
|
||||
"status": status,
|
||||
@@ -235,8 +275,15 @@ def run(duration: float) -> dict[str, Any]:
|
||||
"launcher": command,
|
||||
"native_axis_window": window,
|
||||
"program": {"path": PROGRAM.relative_to(ROOT).as_posix(), "sha256": sha256_bytes(source_bytes)},
|
||||
"native_linuxcnc": {"python_module": python_module, "expected_source_python_module": source_python_module, "display": environment["DISPLAY"]},
|
||||
"tick_source": "linuxcnc.stat.taskbeat",
|
||||
"native_linuxcnc": {"python_module": python_module, "expected_source_python_module": source_python_module, "display": environment["DISPLAY"], "python_module_sha256": sha256_bytes(Path(python_module).read_bytes()) if python_module and Path(python_module).is_file() else None},
|
||||
"inputs": {
|
||||
"case_ini": {"path": CASE, "sha256": sha256_bytes(ini_path.read_bytes())},
|
||||
"launcher": {"path": "run-5axis-rtcp.sh", "sha256": sha256_bytes(launcher_path.read_bytes())},
|
||||
"program": {"path": PROGRAM.relative_to(ROOT).as_posix(), "sha256": sha256_bytes(source_bytes)},
|
||||
"source_python_module": {"path": source_python_module, "sha256": sha256_bytes(Path(source_python_module).read_bytes()) if Path(source_python_module).is_file() else None},
|
||||
},
|
||||
"tick_source": "linuxcnc.stat.task_heartbeat",
|
||||
"tick_integrity": {"first": valid_heartbeats[0] if valid_heartbeats else None, "last": valid_heartbeats[-1] if valid_heartbeats else None, "row_count": len(valid_heartbeats), "unique_count": len(set(valid_heartbeats)), "strictly_monotonic": heartbeat_monotonic},
|
||||
"rows": rows,
|
||||
"row_count": len(rows),
|
||||
"trace_sha256": trace_hash,
|
||||
|
||||
145
scripts/run_xyzac_wasm_tick_trace.mjs
Normal file
145
scripts/run_xyzac_wasm_tick_trace.mjs
Normal file
@@ -0,0 +1,145 @@
|
||||
#!/usr/bin/env node
|
||||
|
||||
import { readFile, writeFile } from "node:fs/promises";
|
||||
import { createHash } from "node:crypto";
|
||||
import { join, resolve } from "node:path";
|
||||
import createModule from "../build-wasm/linuxcnc-sim-core.js";
|
||||
import { loadSimulationCase, toWorkerConfiguration } from "../web/workspace/sim-case-loader.mjs";
|
||||
import { XyzacSession, CONTEXT_ID } from "../web/worker/xyzac-session.mjs";
|
||||
|
||||
const ROOT = resolve(process.cwd());
|
||||
const CASE = "linuxcnc/configs/sim/axis/vismach/5axis/table-rotary-tilting/xyzac-trt.ini";
|
||||
const PROGRAM = "linuxcnc/configs/sim/axis/vismach/5axis/table-rotary-tilting/demos/xyzac_switchkins.ngc";
|
||||
const SCHEMA = "xyzac-wasm-linuxcnc-tick-trace.v1";
|
||||
const AXES = ["x", "y", "z", "a", "b", "c", "u", "v", "w"];
|
||||
|
||||
const sha256 = (value) => createHash("sha256").update(value).digest("hex");
|
||||
const canonical = (value) => JSON.stringify(value, Object.keys(value).sort());
|
||||
const poseArray = (pose) => AXES.map((axis) => Number(pose?.[axis] ?? 0));
|
||||
const modeCode = (mode) => ({ MANUAL: 1, AUTO: 2, MDI: 3 }[mode] ?? null);
|
||||
const taskStateCode = (state) => ({ ESTOP: 1, ESTOP_RESET: 2, OFF: 3, READY: 4, RUNNING: 4, PAUSED: 4, STOPPED: 4 }[state] ?? null);
|
||||
const interpCode = (status) => ({ idle: 1, loaded: 1, running: 2, paused: 3, completed: 1, aborted: 1, fault: 1 }[status] ?? null);
|
||||
const execCode = (status, queueDepth) => (Number(queueDepth) > 0 ? 3 : ({ running: 2, paused: 2, loaded: 2, completed: 2, aborted: 2, idle: 2, fault: 4 }[status] ?? null));
|
||||
|
||||
function rowFrom(state, task, program, tick) {
|
||||
const position = state?.position ?? {};
|
||||
const motion = task?.motion ?? {};
|
||||
const visual = task?.visual ?? {};
|
||||
const limits = motion.limits ?? {};
|
||||
const joints = Array.isArray(visual.joints) ? visual.joints : Array.isArray(motion.joints) ? motion.joints : [];
|
||||
const homedAxes = Array.isArray(motion.homed_axes) ? motion.homed_axes : [];
|
||||
return {
|
||||
sample_index: tick,
|
||||
taskbeat: tick,
|
||||
task_heartbeat: tick,
|
||||
taskbeat_changed: true,
|
||||
task_state: taskStateCode(task?.state),
|
||||
task_mode: modeCode(task?.mode),
|
||||
interp_state: interpCode(program?.program_status),
|
||||
exec_state: execCode(program?.program_status, state?.queue_depth),
|
||||
current_line: Number(program?.current_line ?? 0),
|
||||
motion_line: Number(program?.current_line ?? 0),
|
||||
read_line: Number(program?.current_line ?? 0),
|
||||
actual_pose: poseArray(position),
|
||||
commanded_pose: poseArray(position),
|
||||
joint_actual: joints,
|
||||
joint_commanded: joints,
|
||||
velocity: Number(state?.velocity ?? 0),
|
||||
acceleration: null,
|
||||
feed_override: Number(motion.feed_override ?? 1),
|
||||
rapid_override: 1,
|
||||
feed_override_enabled: true,
|
||||
queue_depth: Number(state?.queue_depth ?? 0),
|
||||
active_queue: null,
|
||||
queue_full: null,
|
||||
motion_id: Number(state?.active_id ?? 0),
|
||||
active_segment_id: Number(state?.active_id ?? 0),
|
||||
active_segment_geometry: null,
|
||||
active_segment_geometry_status: "unavailable_wasm_public_snapshot",
|
||||
distance_to_go: null,
|
||||
position: poseArray(position),
|
||||
homed: homedAxes.map((value) => (value ? 1 : 0)),
|
||||
limits: ["x", "y", "z", "a", "b", "c", "u", "v", "w"].map((axis) => limits[axis] ? 1 : 0),
|
||||
kinematics_type: 4,
|
||||
motion_type: Number(state?.motion_type ?? 0),
|
||||
feed_hold_enabled: null,
|
||||
paused: program?.program_status === "paused",
|
||||
wasm_tick: tick,
|
||||
};
|
||||
}
|
||||
|
||||
const fetchImpl = async (url) => {
|
||||
try {
|
||||
const body = await readFile(join(ROOT, String(url).replace(/^\//, "")));
|
||||
return { ok: true, text: async () => body.toString("utf8") };
|
||||
} catch {
|
||||
return { ok: false, text: async () => "" };
|
||||
}
|
||||
};
|
||||
|
||||
async function run(maxTicks) {
|
||||
const bundle = await loadSimulationCase({ path: CASE, fetchImpl });
|
||||
if (bundle.status !== "ready") throw new Error(`case_load_${bundle.code ?? bundle.status}`);
|
||||
const source = bundle.files?.[PROGRAM];
|
||||
if (typeof source !== "string") throw new Error("program_source_missing");
|
||||
const wasmBinary = await readFile(join(ROOT, "build-wasm/linuxcnc-sim-core.wasm"));
|
||||
const core = await createModule({ wasmBinary });
|
||||
const session = new XyzacSession(core, { sessionId: "xyzac-native-wasm-oracle" });
|
||||
let seq = 0;
|
||||
const send = (kind, payload = {}) => session.accept({ schema_version: 1, context_id: CONTEXT_ID, session_id: session.sessionId, kind, seq: ++seq, operation_id: `oracle-${seq}`, payload });
|
||||
send("HELLO");
|
||||
send("SESSION_ATTACH");
|
||||
const loadedWorkspace = send("LOAD_WORKSPACE", { root_path: "/workspace", configuration: toWorkerConfiguration(bundle) });
|
||||
if (loadedWorkspace.payload?.status !== "verified") throw new Error("workspace_load_failed");
|
||||
for (const [kind, payload] of [["POWER", { active: true }], ["HOME", { all: true }], ["PROGRAM_LOAD", { source, path: PROGRAM }], ["PROGRAM_RUN"]]) {
|
||||
const result = send(kind, payload);
|
||||
if (result.payload?.status !== "verified") throw new Error(`${kind.toLowerCase()}_${result.payload?.code ?? "failed"}`);
|
||||
}
|
||||
const rows = [];
|
||||
let state = session.wasmMotion.read().state;
|
||||
let task = { ...session.task.export(), motion: session.motionProjection(), visual: { joints: state.joints } };
|
||||
let program = session.xyzacProgram.snapshot();
|
||||
rows.push(rowFrom(state, task, program, 0));
|
||||
for (let tick = 1; tick <= maxTicks; tick += 1) {
|
||||
const response = send("SIM_STEP", { cycles: 1 });
|
||||
if (response.payload?.status !== "verified") throw new Error(`sim_step_${response.payload?.code ?? "failed"}`);
|
||||
state = response.payload.wasm_motion?.state ?? session.wasmMotion.read().state;
|
||||
task = { ...response.payload.task, motion: response.payload.motion, visual: response.payload.panel_snapshot?.visual };
|
||||
program = response.payload.program ?? session.xyzacProgram.snapshot();
|
||||
rows.push(rowFrom(state, task, program, tick));
|
||||
if (program.program_status === "completed" && Number(state.queue_depth) === 0) break;
|
||||
}
|
||||
const traceHash = sha256(JSON.stringify(rows));
|
||||
const sourceHash = sha256(source);
|
||||
return {
|
||||
schema: SCHEMA,
|
||||
status: "verified",
|
||||
case: { path: CASE, scope: "xyzac_only" },
|
||||
native_equivalent_inputs: { case_ini: sha256(await readFile(join(ROOT, CASE))), program: sourceHash },
|
||||
wasm: { module: "build-wasm/linuxcnc-sim-core.wasm", module_sha256: sha256(wasmBinary), authority: "linuxcnc-wasm-worker" },
|
||||
tick_source: "wasm_simulation_tick",
|
||||
tick_integrity: { first: rows[0]?.wasm_tick ?? null, last: rows.at(-1)?.wasm_tick ?? null, row_count: rows.length, unique_count: new Set(rows.map((row) => row.wasm_tick)).size, strictly_monotonic: rows.every((row, index) => index === 0 || row.wasm_tick > rows[index - 1].wasm_tick) },
|
||||
rows,
|
||||
row_count: rows.length,
|
||||
trace_sha256: traceHash,
|
||||
errors: [],
|
||||
release_status: "STOP_RELEASE",
|
||||
};
|
||||
}
|
||||
|
||||
const args = process.argv.slice(2);
|
||||
const ticksIndex = args.indexOf("--ticks");
|
||||
const outputIndex = args.indexOf("--output");
|
||||
const maxTicks = Math.max(1, Math.min(100000, Number(ticksIndex >= 0 ? args[ticksIndex + 1] : 3000)));
|
||||
const output = outputIndex >= 0 ? resolve(args[outputIndex + 1]) : join(ROOT, "coverage/xyzac-wasm-tick-trace.report.json");
|
||||
try {
|
||||
const report = await run(maxTicks);
|
||||
const unsigned = { ...report, report_sha256: undefined };
|
||||
delete unsigned.report_sha256;
|
||||
report.report_sha256 = sha256(JSON.stringify(unsigned));
|
||||
await writeFile(output, `${JSON.stringify(report, null, 2)}\n`);
|
||||
console.log(JSON.stringify({ schema: report.schema, status: report.status, row_count: report.row_count, trace_sha256: report.trace_sha256, report_sha256: report.report_sha256 }));
|
||||
} catch (error) {
|
||||
console.error(JSON.stringify({ schema: SCHEMA, status: "blocked", error: String(error?.message ?? error) }));
|
||||
process.exitCode = 1;
|
||||
}
|
||||
Reference in New Issue
Block a user