Skip to content

impl(027): increment 6, the native crate - #131

Merged
bartekus merged 1 commit into
mainfrom
impl/027-node
Oct 21, 2026
Merged

bartekus merged 1 commit into
mainfrom
impl/027-node

Conversation

@bartekus

@bartekus bartekus commented Oct 20, 2026 •

Copy link
Copy Markdown
Contributor

Spec 027, increment 6 (first change): the native Node-API package. Stacked on #130.

  • integrations/rustev-node (napi 3.14.2, Node-API 8; publish = false, excluded from the crates.io release set): an Engine owning one sized Tokio runtime, rules-program and host backends, a host sink and optional context source; compile (or load a compiled plan) and the pure commands on the blocking pool, with sync variants; decide on the engine's runtime with AbortSignal, deadline, principal handle and traceparent; manual clock; gauges; shutdown.
  • Host seams (3.6) via weak threadsafe functions: bounded per-seam queues refused at once, remaining time, attempt identity, abort, reserved bound and trace context on every call, late settlements discarded and counted, non-SeamFailure rejections mapped to permanent / unknown charge / possibly continuing. Context source once before admission; ContextUnavailable on failure, nothing defaulted.
  • JavaScript layer (index.js, index.d.ts, generated document declarations byte-identical to the wasm package's): the 3.3 API, typed RustevError subclasses and codes (3.4), onGauges drop-oldest subscription, drain-then-cancel shutdown, platform-package loader naming a missing package.
  • unsafe: napi-rs's generated glue needs it, so this crate sets unsafe_code = "deny" (reason in the manifest); tests/no_unsafe.rs fails on hand-written unsafe.
  • test/negative.test.mjs: each section 5 row of the native package (20 tests, deterministic on a manual clock). A decision through the binding produces the CLI's golden run-record bytes.
  • ManualClock::pending_delays (additive, spec 003's crate) for deterministic clock driving; the conformance adapter that uses it follows in the second change.
  • Two owner findings, recorded in the spec: a host backend's cancellation answer is always not_observed (the runtime polls a cancelled attempt once; a host seam answers across threads), and section 5's "output failing the bounded parse" row disagrees with 3.6.5; the binding follows 3.6.5.

Review round 1 (5 findings): (1) Under node -e, process.argv[1] is the first argument after the code (there is no script path), so the copy reads the target directory; it ran that way in local verification, and the Makefile now says so. (2) fixed: a decision is counted in flight by a guard dropped when its task ends, panic included, so shutdown never waits on a panicked task. (3) fixed: compile takes exactly one of a definition and a plan, otherwise InvalidDocument; declared and tested. (4, 5) The generated types state what each bounded parser accepts (3.2.2: the schema describes the parser), while a field's description can state a compiler rule beyond it (AddressOverride.to is never caller, RemediationDecl.for never none: the compiler refuses both). The generated header now says so; both packages' copies regenerated and identical. Restacked on #130.

Review round 2 (5 findings): (1) fixed: the no-unsafe check reads source files only and fails on anything else in src/ rather than panicking. (2) fixed: compiles and commands on the blocking pool are counted, and shutdown waits for them as for decisions. (3) fixed: after raising cancellation, shutdown waits at most 30 seconds and reports what still runs (stillRunning). (4) fixed: a local build that does not load is a typed InternalError (local_build_unloadable) naming it; tested. (5) Repeated: the generated types state what each bounded parser accepts and the generated header says a field's description can state a compile rule beyond that; compile refuses caller for AddressOverride.to in every plan.

Review round 3 (6 findings): (1) Repeated, and wrong: under node -e the first argument after the code is process.argv[1] (node -e 'console.log(process.argv.slice(1))' x prints ["x"]). To leave no doubt, the copy is now a script, tools/rustev-conformance/js/copy-addon.mjs <target> <package>, run by make bindings and locally. (2) fixed: shutdown's local count is active, no longer shadowing the module's inFlight. (3) fixed: a seam failure with an empty reason records the status instead (the host seam failed without a reason (...)). (4) Repeated: the generated declarations' header states that the types describe what each parser accepts and that a description can state a compile rule beyond it (the compiler refuses caller for AddressOverride.to); each emitted schema now says the same in a root $comment (#126), which the type generator does not copy. (5, 6) These are the two owner findings already recorded in this spec's implementation record (the host backend's cancellation recorded not_observed, and section 5 against 3.6.5 for an unparseable answer); they need the owner's reading or an amendment, not a code change here. Restacked on #130.

Review round 4 (5 findings): (1) fixed, and it exposed a real defect: compileSync takes exactly one of a definition and a plan, refusing otherwise with InvalidDocument; the layer's error wrapper also re-typed errors it had thrown itself as InternalError, and now passes a RustevError through unchanged. Tested. (2) fixed: the no-unsafe check strips a // comment only outside string literals; tested. (3) The diagnostic report is the C-library test napi-rs uses; it runs once, on Linux only, and now without the network section where Node allows leaving it out. (4) fixed: copy-addon.mjs refuses a platform it has no package for. (5) fixed at the source (#130): the generator gave plan fields the referenced type's description; now every field keeps its own (AddressOverride.to: never caller), and this package's declarations are regenerated, byte-identical to the WebAssembly package's.

Review round 5 (2 findings, fixed): (1) an installed platform package that does not load is InternalError (platform_package_unloadable, naming it), and only an absent one is PlatformPackageMissing. (2) the no-unsafe check blanks /* */ block comments across lines as well as // comments, string literals staying code; tested.

Review round 6 (3 findings, fixed): (1) a command is counted before the shutdown check (both sequentially consistent), so either shutdown waits for it or it refuses; it never runs unseen. (2) the no-unsafe check reads raw strings (r#"…"#, br"…"), escaped strings and char literals ('"') as code, with lifetimes left alone; tested. (3) a package is missing only when Node cannot find the package itself (Cannot find module '<package>'); a missing dependency of an installed package makes it unloadable.

Review round 7 (3 findings, fixed): (1) a decision is counted in flight before the shutdown check, as a command is, so shutdown either waits for it or it refuses. (2) shutdown's count saturates at u32::MAX instead of truncating. (3) the no-unsafe check reads an escaped char literal ('\'') whole; tested.

Review round 8 (4 findings, fixed): (1) the no-unsafe check blanks string contents (plain, byte and raw) as it blanks comments, so text inside a string is not code; a real unsafe block is still found; tested. (2) the missing-package test first asserts that no platform package resolves from its directory (Node also searches ancestors), so it fails rather than passes if one does. (3) advanceClock takes any integral, non-negative number up to 2^53 - 1 and refuses the rest instead of truncating to 32 bits; tested. (4) the build-time copy script leaves out the report's network section too.

Review round 9 (2 findings, fixed): (1) clockDelays reports each pending delay as a JavaScript number, exact to 2^53 - 1 ms, the range advanceClock accepts, instead of capping at 32 bits. (2) the no-unsafe check matches the keyword unsafe, not a longer identifier such as unsafe_code; tested.

Split (the AI review was cancelled at its 15-minute limit twice): this PR is now increment 6's first change, the native crate (Rust: engine, seams, commands, errors, the no-unsafe check, the manual clock's pending delays); the JavaScript layer (index.js, declarations, generated types, package, tests, copy script) moves to a PR stacked on this one, and #132 is restacked on that.

Review round 10 (2 findings, fixed): (1) every usage refusal states the requirement (must be a string, must be a list, must list strings). (2) a compile on the blocking pool is counted and then checked against shutdown before it reaches the pool, as a command is, so both paths behave alike: shutdown waits for it, or it refuses.

Review round 11 (2 findings, fixed): (1) "failure": null in a host's answer is no failure; only an object is one. (2) the context source's fetch runs on its own task, as a backend's attempt does, so a settlement that arrives after its decision was dropped is discarded and counted (3.6.4). The 23 native tests (#135) and the 34 native conformance cases (#132) pass against this build.

Review round 12 (2 findings, fixed): (1) a host answer's cancel, when present, must be stopped or unconfirmed; any other value is refused like an unknown charge or remote end, and only an absent one means not requested. (2) compile and load on the blocking pool run under guard, so a panic crosses as InternalError with its message, as a command's does. Rebased on main after #134 merged.

Review round 13 (1 finding, fixed): advancing an engine on the system clock is refused with its own code, not_a_manual_clock, instead of out_of_range, which stays for numbers outside the accepted range; #135 tests both.

Review round 14 (1 finding, fixed): the synchronous command, compile and load are counted and then checked against shutdown, as their blocking-pool forms are, so a synchronous call (from a worker thread too) is one shutdown waits for. The native tests (#135, 27) and native conformance (#132, 34) pass against this build.

Review round 15 (1 finding, fixed): a compile given neither a definition nor a plan says so (neither was given), and one given both says not both.

Review round 16 (2 findings, fixed): (1) compile and load count themselves and then call uncounted forms (compile_uncounted, load_uncounted), which prepare_async, already counted, calls directly, so nothing is counted twice. (2) clockSleepers saturates at u32::MAX instead of truncating. The native tests (#135, 27) and native conformance (#132, 34) pass against this build.

Review round 17 (2 findings): (1) Nothing is dropped: the workspace's only lint is unsafe_code ([workspace.lints.rust]), which this crate overrides to deny; Cargo cannot inherit the workspace table and override one lint, so the manifest now says the table restates the workspace's and must mirror any lint it gains. (2) fixed: a host answer missing its charge or its remote end is refused naming the one that is missing.

@github-actions

Copy link
Copy Markdown

AI review (findings)

Group 1 of 2

Review Findings

1. Makefile — wrong process.argv index (Makefile, line ~113)

node -e '... fs.copyFileSync(process.argv[1]+"/release/"+p+"rustev_node."+m, ...)' $(CARGO_TARGET)

When Node.js is invoked with -e, process.argv[1] is "" (empty string); the first positional argument is at process.argv[2]. As written, the copyFileSync source path evaluates to "/release/librustev_node.so" — an absolute path rooted at /, not relative to $(CARGO_TARGET). The copy will fail on every platform, breaking the make bindings target.

Fix: replace process.argv[1] with process.argv[2].


2. in_flight counter never decremented on task-panic (src/lib.rs, ~554)

engine.in_flight.fetch_add(1, Ordering::SeqCst);
let task = self.engine.rt.spawn(async move {
    let r = runtime.decide(&plan, req, &signal).await;
    engine.in_flight.fetch_sub(1, Ordering::SeqCst);   // inside the task
    drop(trace);
    decided(r)
});
task.await.map_err(|e| fail("InternalError", "internal", e.to_string()))?

fetch_add happens unconditionally before spawning, but fetch_sub is inside the closure. If the spawned task panics (e.g., inside decided(r)), Tokio catches the panic, task.await returns a JoinError, and fetch_sub is never reached. The counter stays permanently elevated. The JavaScript shutdown loop (while (this.native.shutdown() > 0) { ... }) has no timeout on this second phase, so it will spin forever. fetch_sub should be called with a defer/drop guard (e.g., an RAII wrapper or placing it before decided(r)) so it runs even on panic.


3. prepare_async silently discards definition when both inputs are supplied (src/lib.rs, ~390)

match (definition, plan) {
    (_, Some(p)) => engine.load(Uint8Array::new(p), ds, cs),
    (Some(d), None) => engine.compile(Uint8Array::new(d), ds, cs),
    (None, None) => Err(fail("InvalidDocument", ...)),
}

The wildcard _ in the first arm silently ignores definition whenever plan is also present. The TypeScript declarations in index.d.ts make both optional without documenting that plan wins. A caller supplying both (e.g., believing definition provides extra type info) will silently get the plan path with no indication the definition was discarded.


{"head": "30f0d54cadfe6f50df67c88f0858bf8e3e36c871", "verdict": "findings", "findings": [{"path": "Makefile", "line": 113, "summary": "process.argv[1] is an empty string under `node -e`; the CARGO_TARGET argument is at process.argv[2], so copyFileSync receives a wrong absolute source path and will always fail."}, {"path": "integrations/rustev-node/src/lib.rs", "line": 554, "summary": "in_flight counter is fetch_add'd before spawn but fetch_sub'd only inside the task body; a task panic skips the decrement, leaving the counter permanently elevated and causing the JavaScript shutdown loop to spin forever."}, {"path": "integrations/rustev-node/src/lib.rs", "line": 390, "summary": "prepare_async silently discards the definition argument when plan is also provided, with no error or documentation in the TypeScript types."}]}

Group 2 of 2

Reviewing the three files in this group.

integrations/rustev-node/types/rustev-documents.d.ts

Two recurring inconsistencies in the generated declarations:

  1. AddressOverride.to — The JSDoc in RustevDefinition1.AddressOverride and RustevDefinition2.AddressOverride reads "host", "upstream" or "none"; never "caller", yet the type union is "none" | "caller" | "host" | "upstream". The caller variant is explicitly disallowed by spec (Address is an override "toward a party less able to act") but the TypeScript type permits it, so callers cannot rely on exhaustive checks to enforce the spec constraint.

  2. AddressOverride.to in RustevPlan2 and RustevPlan3 — the JSDoc is entirely wrong: it was copied from the Party type description ("Who can act on an outcome (3.5.2), ordered from most to least able to act on it themselves…") rather than stating the AddressOverride constraint. A consumer reading only the plan-namespace types gets no guidance.

  3. RemediationDecl.for — the JSDoc says `caller`, `host` or `upstream` but the type union is "none" | "caller" | "host" | "upstream", including "none". Appears across all four definition/plan namespaces.

These are in a generated file ("Do not edit"), so the root fix is in the source schemas or the generator. Because the spec states the file must be "byte-identical to the WebAssembly package's" declarations, the same errors presumably pre-exist there. The node package makes them newly part of the public API surface, so they are worth flagging for the schema owners.

specs/027-node-and-wasm-bindings/spec.md and tools/rustev-release/release-set.json — both look correct. Removing planned: true is appropriate now that the code ships. The exclusion of rustev-node from the crates.io release set is consistent with the spec and the Cargo.toml setting publish = false.

{"head": "30f0d54cadfe6f50df67c88f0858bf8e3e36c871", "verdict": "findings", "findings": [{"path": "integrations/rustev-node/types/rustev-documents.d.ts", "line": null, "summary": "AddressOverride.to type union includes \"caller\" in RustevDefinition1/2 despite JSDoc saying \"never caller\", and in RustevPlan2/3 the JSDoc is entirely wrong (copied from Party description), so TypeScript consumers get no correct constraint on this field."},{"path": "integrations/rustev-node/types/rustev-documents.d.ts", "line": null, "summary": "RemediationDecl.for JSDoc says 'caller, host or upstream' but the type union includes \"none\" across all four definition/plan namespaces, a mismatch between documentation and the generated type."}]}

Subject: c77d571...30f0d54, diff digest 13cb08df1ba7a4c669f9e8ff0eb048ea121175207f380e974d02de65aa089393, 2 call(s). An AI comment is not an approval.

@bartekus
bartekus had a problem deploying to statecraft-review-exception October 20, 2026 17:00 — with GitHub Actions Error
@bartekus
bartekus force-pushed the impl/027-wasm branch 3 times, most recently from 6054b28 to ca37009 Compare October 20, 2026 18:59
@github-actions

Copy link
Copy Markdown

AI review (findings)

Group 1 of 2

Reviewing the new rustev-node native addon for bugs, security issues, and inconsistencies.

index.js — compileSync silent divergence from compile

compileSync (around line 312) handles the "neither/both" case differently from the async compile:

  • If neither definition nor plan is supplied, it falls through to this.native.compile(bytes(undefined), ...). bytes(undefined) calls Buffer.from(JSON.stringify(undefined), 'utf8'), but JSON.stringify(undefined) returns the JS value undefined, so Buffer.from throws a TypeError. That TypeError exits through typed() as InternalError rather than the documented InvalidDocument.
  • If both are supplied, compileSync silently uses plan (the plan !== undefined branch wins), while the async path in Rust's prepare_async catches (Some(d), Some(p)) and returns a clear InvalidDocument("compile takes exactly one of a definition and a plan"). The two entry points give different behaviour for the same invalid input.

tests/no_unsafe.rs — read_dir iterates without filtering by file type

Lines 6-8 call std::fs::read_dir and unconditionally call std::fs::read_to_string on every entry. If a subdirectory is ever added under src/, read_to_string on that path returns an IsADirectory IO error, the .unwrap() panics, and the test dies with a confusing message rather than a meaningful assertion failure. The test also never checks the entry's extension, so it would attempt to read any non-.rs file that appears there.

{"head": "2c0874d2ff8f639bd00811fd2e11ceead4fa62b5", "verdict": "findings", "findings": [{"path": "integrations/rustev-node/index.js", "line": 312, "summary": "compileSync calls bytes(undefined) when neither definition nor plan is supplied, producing InternalError instead of InvalidDocument, and silently picks plan when both are supplied rather than raising InvalidDocument as the async compile path does."}, {"path": "integrations/rustev-node/tests/no_unsafe.rs", "line": 8, "summary": "read_to_string is called on every read_dir entry without checking file_type first; a subdirectory under src/ would cause an unwrap panic rather than a meaningful test failure."}]}

Group 2 of 2

Reviewing the five files in group 2.

tools/rustev-conformance/js/gen-types.mjs — The removed guard correctly goes away now that the node package lands in this increment. When in check mode and the file is missing, got becomes '' and the comparison fails with an error, which is the right behavior. Clean.

tools/rustev-release/release-set.json — rustev-node exclusion is consistent with the existing rustev-wasm entry and the spec's rationale. Clean.

specs/027-node-and-wasm-bindings/spec.md — planned: true removal, runtime extension entry, and the increment 6 prose all look internally consistent. The two open findings (host-backend not_observed answer, and the 3.6.5 / section-5 disagreement) are properly surfaced for the owner.

integrations/rustev-wasm/types/rustev-documents.d.ts — Only the five-line banner is added. No type changes. Clean.

integrations/rustev-node/types/rustev-documents.d.ts — This is a generated file, and nearly all of it is correct. One class of error propagated from the plan schemas is worth flagging:

  • In both RustevPlan2.AddressOverride and RustevPlan3.AddressOverride, the JSDoc on field to reads "Who can act on an outcome (3.5.2), ordered from most to least able to act on it themselves: the combination of parties is the greatest" — this is the Party type's description, not the address-override description. The definition schemas carry the correct text: "host, upstream or none; never caller".

  • The same wrong description appears on RustevPlan2.RemediationDecl.for and RustevPlan3.RemediationDecl.for: the Party description was copied instead of the correct "caller, host or upstream".

These are schema-level documentation bugs that generated into this new public API file. The type union itself ("none" | "caller" | "host" | "upstream") is structurally correct, but the incorrect JSDoc misleads consumers about the field's purpose and, in the AddressOverride case, contradicts the "never caller" constraint the compiler enforces.

{"head": "2c0874d2ff8f639bd00811fd2e11ceead4fa62b5", "verdict": "findings", "findings": [{"path": "integrations/rustev-node/types/rustev-documents.d.ts", "line": null, "summary": "In RustevPlan2.AddressOverride and RustevPlan3.AddressOverride the JSDoc on `to` reads the Party type description ('Who can act on an outcome…') instead of the correct address-override description; compare RustevDefinition1.AddressOverride.to which correctly says '`host`, `upstream` or `none`; never `caller`'."},{"path": "integrations/rustev-node/types/rustev-documents.d.ts", "line": null, "summary": "In RustevPlan2.RemediationDecl and RustevPlan3.RemediationDecl the JSDoc on `for` likewise carries the Party type description instead of the correct '`caller`, `host` or `upstream`' description seen in the definition schemas."}]}

Subject: ca37009...2c0874d, diff digest eb4f1f9c1eee04594a57c8bba412b8c87cb419134521842ea6b8d35e7e96a5d2, 2 call(s). An AI comment is not an approval.

@github-actions

Copy link
Copy Markdown

AI review (findings)

Group 1 of 2

Reviewing the new rustev-node NAPI binding against the diff.


integrations/rustev-node/tests/no_unsafe.rs line 10–11: std::fs::read_dir is not recursive, but more critically there is no file-vs-directory check before calling read_to_string(&p).unwrap(). If any subdirectory is ever placed inside src/, the unwrap() panics the test process with an IO error rather than failing the assertion. The test design is fragile.

integrations/rustev-node/src/lib.rs line ~380 (Engine::command_async): The shutdown guard checks self.inner.shut before spawning, but the spawn_blocking task is not counted in in_flight (only PlanHandle::decide uses InFlight::enter). The JavaScript shutdown loop while (this.native.shutdown() > 0) returns as soon as decisions drain, even if blocking command tasks submitted via command_async are still executing on the Tokio blocking pool. This means shutdown() can report completion while worker threads are still active.

integrations/rustev-node/index.js line ~383 (second while loop in shutdown): After raising cancel signals there is no timeout escape:

while (this.native.shutdown() > 0) {
  await new Promise((r) => setTimeout(r, 5));
}

If a cancelled decision does not complete (e.g., a host seam ignores the abort signal indefinitely), this loop never exits. The spec expects honest termination after cancellation, but there is no liveness guarantee here enforced by the binding itself.

integrations/rustev-node/index.js line ~119 (load): require(local) for a locally built addon is not wrapped in try/catch. A corrupt or ABI-mismatched .node file produces an untyped native loader error, bypassing the typed PlatformPackageMissing error class. The error message will be confusing to callers.

integrations/rustev-node/src/lib.rs traceparent_valid vs index.js TRACEPARENT regex: The JS regex (?!0{32}) and (?!0{16}) enforce non-zero trace-id and parent-id through negative lookahead. The Rust function checks p[1].bytes().any(|b| b != b'0') and p[2].bytes().any(|b| b != b'0'). These are semantically equivalent, so no inconsistency.

The clock_delays() Rust method (line ~379 lib.rs) clamps u64 delays to u32::MAX before returning Vec<u32>. The JS layer receives number[], but the declared TypeScript return type is number[], and JavaScript numbers can represent values up to 2^53. This truncation at ~49 days could silently lose precision for very large pending timers — minor and unlikely to matter in practice, but worth noting.

{"head": "da7b57e8f312d03b8b19d3db4587516980bab968", "verdict": "findings", "findings": [{"path": "integrations/rustev-node/tests/no_unsafe.rs", "line": 10, "summary": "read_dir is not filtered to files; a subdirectory in src/ would cause read_to_string().unwrap() to panic instead of failing the assertion."}, {"path": "integrations/rustev-node/src/lib.rs", "line": 380, "summary": "command_async tasks spawned via spawn_blocking are not counted in in_flight, so shutdown() can report zero in-flight while blocking command tasks are still running."}, {"path": "integrations/rustev-node/index.js", "line": 383, "summary": "The post-cancellation shutdown loop has no timeout, leaving shutdown() permanently stuck if any cancelled decision never completes."}, {"path": "integrations/rustev-node/index.js", "line": 119, "summary": "require(local) for a local .node file is not wrapped in try/catch, so a corrupt or ABI-mismatched build produces an untyped error instead of the typed PlatformPackageMissing class."}]}

Group 2 of 2

Reviewing the five files in this group: the new Node types declaration, the updated WASM types banner, the spec increment, the generator script, and the release set.

integrations/rustev-node/types/rustev-documents.d.ts — generated file, new. The banner matches what gen-types.mjs now emits. Content is structurally sound. One documentation inconsistency worth flagging: in the RustevPlan2 and RustevPlan3 namespaces, AddressOverride.to carries the Party type description ("Who can act on an outcome (3.5.2), ordered from most to least able to act on it themselves…") instead of the constraint that appears in RustevDefinition1 and RustevDefinition2 ("host, upstream or none; never caller"). The same mismatch appears on RemediationDecl.for in both plan namespaces. A caller reading the plan-namespace types would see the Party description and conclude "caller" is a valid choice for AddressOverride.to, which the definition-namespace comment correctly forbids. This is party-addressing logic, so the misleading description is security-relevant.

integrations/rustev-wasm/types/rustev-documents.d.ts — banner-only change; five lines added to match the new generator output. No issues.

specs/027-node-and-wasm-bindings/spec.md — removes planned: true from the node directory, adds the rustev-runtime extension with a rationale comment, and documents Increment 6. The spec itself explicitly surfaces two known inconsistencies for the owner's resolution (cancel behaviour and invalid-output classification), which is good practice rather than a problem.

tools/rustev-conformance/js/gen-types.mjs — removes the early-continue that skipped the node target when it didn't exist. Now that the file is present, the check correctly enforces byte-identity. The change is clean.

tools/rustev-release/release-set.json — adds rustev-node to the exclusion list with a correct rationale aligned to the spec.

{"head": "da7b57e8f312d03b8b19d3db4587516980bab968", "verdict": "findings", "findings": [{"path": "integrations/rustev-node/types/rustev-documents.d.ts", "line": null, "summary": "In the RustevPlan2 and RustevPlan3 namespaces, AddressOverride.to and RemediationDecl.for carry the Party type's docstring ('Who can act on an outcome…') instead of the constraint present in RustevDefinition1/2 ('never `caller`' / 'caller, host or upstream'), potentially misleading Node.js callers into treating `\"caller\"` as valid for AddressOverride.to."}]}

Subject: f3b0975...da7b57e, diff digest b3da39e4d536f402c50fa5a2a60d326dced933b7e297efa06189696cbf4c9906, 2 call(s). An AI comment is not an approval.

@github-actions

Copy link
Copy Markdown

AI review (findings)

Group 1 of 2

Review

integrations/rustev-node/index.js — compileSync inconsistency with compile

Both definition and plan provided (line 323–325):
compileSync checks only plan !== undefined and silently loads the plan, ignoring definition. The async compile correctly passes both to prepareAsync, which the Rust side rejects with InvalidDocument ("compile takes exactly one of a definition and a plan"). The sync path breaks the contract documented in both the type declaration and the comment.

Neither provided (line 325):
When plan is undefined and definition is also undefined, bytes(undefined) is called. JSON.stringify(undefined) returns the JS value undefined (not the string "undefined"), so Buffer.from(undefined, 'utf8') throws a TypeError. wrap catches it, typed tries JSON.parse on the TypeError message, fails, and returns new InternalError(...). The caller receives InternalError instead of InvalidDocument. The async path correctly passes undefined to prepareAsync, which returns InvalidDocument from Rust.

integrations/rustev-node/src/seams.rs — HostSink slot released before late-discard check

In deliver, drop(slot) is called inside the spawned task before tx.send(r).is_err() is evaluated (line ordering: drop(slot) then if tx.send(r).is_err()). The slot depth is decremented regardless of whether the receiver is still listening, so the capacity gauge is correct. No bug here — just noting it is intentional.

Minor: commands.rs error messages

s(a, "definition") produces "definition is a string" on a missing field (line ~35), which reads ambiguously; "definition is required" or "definition must be a string" would be clearer. Not a correctness issue.


The two compileSync issues are real bugs: one produces a semantically wrong error class, the other silently violates the "exactly one" contract.

{"head": "9878333a64e39ba5ecc71a817b857c93efbcb3d7", "verdict": "findings", "findings": [{"path": "integrations/rustev-node/index.js", "line": 323, "summary": "compileSync with both definition and plan silently loads plan only, while the async compile correctly returns InvalidDocument for this case, breaking the documented 'exactly one' contract."}, {"path": "integrations/rustev-node/index.js", "line": 325, "summary": "compileSync with neither definition nor plan calls bytes(undefined), which throws a TypeError that becomes InternalError instead of InvalidDocument, inconsistent with compile's behavior."}]}

Group 2 of 2

integrations/rustev-node/types/rustev-documents.d.ts: Reviewing the generated type file. The AddressOverride.to field in the RustevPlan2 and RustevPlan3 namespaces carries the wrong JSDoc: it reads "Who can act on an outcome (3.5.2), ordered from most to least able to act on it themselves: the combination of parties is the greatest" -- which is the Party type description, not the intended "host, upstream or none; never caller" restriction. The same wrong description appears on RemediationDecl.for in those same namespaces. By contrast, the RustevDefinition1 and RustevDefinition2 namespaces have the correct "host, upstream or none; never caller" comment on those fields. This is a codegen inconsistency rather than a runtime bug (the type union itself is unchanged), but it will mislead callers inspecting IDE tooltips.

tools/rustev-conformance/js/gen-types.mjs: The removal of the early-exit guard for rustev-node is correct now that the file exists. The existsSync(p) ? readFileSync(p, 'utf8') : '' path will correctly fail the check if the file is deleted rather than silently skipping it.

integrations/rustev-wasm/types/rustev-documents.d.ts: Banner-only change, no issues.

specs/027-node-and-wasm-bindings/spec.md: Removing planned: true from integrations/rustev-node/ is correct. The two findings disclosed to the owner (host-backend cancellation always recording not_observed; the parse-failure semantic conflict between 3.6.5 and the invalid_backend_output row) are properly called out as open questions for ratification, not implementation defects.

tools/rustev-release/release-set.json: Correct addition matching the rationale in the spec.

{"head": "9878333a64e39ba5ecc71a817b857c93efbcb3d7", "verdict": "findings", "findings": [{"path": "integrations/rustev-node/types/rustev-documents.d.ts", "line": null, "summary": "In RustevPlan2 and RustevPlan3 namespaces, AddressOverride.to and RemediationDecl.for carry the Party-type JSDoc description instead of the correct 'host, upstream or none; never caller' restriction, misleading IDE users about valid values."}]}

Subject: 7f5eedc...9878333, diff digest d76fd9c255c96e1de8ceec07c6f98191e8fa1beb3e451e3a61d28839cd62d3c0, 2 call(s). An AI comment is not an approval.

@github-actions

Copy link
Copy Markdown

AI review (findings)

Group 1 of 2

Review

integrations/rustev-node/src/lib.rs

command_async TOCTOU / no shutdown guard in closure (line ~430)

command_async checks shut before spawning but the blocking closure calls commands::run() directly — no self.live() call inside. Meanwhile prepare_async (line ~369) skips the upfront check but correctly gets EngineShutDown from compile()/load() via live(). The two paths are inverted: after shutdown(), command_async can execute a command silently (the TOCTOU window between the load and Blocking::enter means a concurrent shutdown() can be missed entirely), while prepare_async correctly rejects. Commands are pure but callers still expect consistent EngineShutDown semantics.

integrations/rustev-node/tests/no_unsafe.rs

code_of mishandles raw string literals (line ~37)

The parser tracks regular string literals with " but has no awareness of r"..." or r#"..."#. A raw string that contains an embedded " before its actual close delimiter will cause in_str to flip off prematurely, leaving remaining content classified as code. Any unsafe keyword inside such a raw string would appear in the code_of output and trigger a spurious test failure (false positive). Conversely, the same misparse could suppress detection in adjacent content. Currently none of the source files appear to use raw strings with embedded ", but the invariant is fragile.

integrations/rustev-node/index.js

MODULE_NOT_FOUND misclassification (line ~197)

if (e?.code === 'MODULE_NOT_FOUND' && String(e.message).includes(pkg)) {
    throw new classes.PlatformPackageMissing(...)
}

Node appends a Require stack section to MODULE_NOT_FOUND messages. If the platform package (@statecrafting/rustev-linux-x64-gnu) is installed but one of its JS dependencies is missing, the error message will contain pkg in the stack trace, causing a misleading PlatformPackageMissing error instead of InternalError / platform_package_unloadable. A tighter check (e.g. testing whether the first line of the message names exactly pkg) would be more accurate.


{"head": "801d0d3f90113a35902b34230e45bee306f5a1f3", "verdict": "findings", "findings": [{"path": "integrations/rustev-node/src/lib.rs", "line": 430, "summary": "command_async checks the shut flag before Blocking::enter but the spawned closure calls commands::run() without a live() guard, so a TOCTOU window allows command execution after shutdown() while prepare_async (which does the reverse) correctly rejects via live()."},{"path": "integrations/rustev-node/tests/no_unsafe.rs", "line": 37, "summary": "code_of does not handle raw string literals: a raw string containing a bare '\"' before its real close delimiter will cause in_str to flip incorrectly, treating raw-string content as code and potentially producing false positives or masking nearby content in the unsafe check."},{"path": "integrations/rustev-node/index.js", "line": 197, "summary": "String(e.message).includes(pkg) matches platform-package paths in Node's Require stack trace, so a MODULE_NOT_FOUND for a transitive dependency of an installed platform package is misclassified as PlatformPackageMissing rather than InternalError / platform_package_unloadable."}]}

Group 2 of 2

Reviewing the six files in group 2.

integrations/rustev-node/types/rustev-documents.d.ts — New generated file. Header matches the updated gen-types.mjs banner exactly, and content appears byte-identical to the updated WASM types file, which is the intended invariant that the generator enforces.

integrations/rustev-wasm/types/rustev-documents.d.ts — Adds five comment lines to the header only; no functional change to any type.

tools/rustev-conformance/js/gen-types.mjs — Removes the early-continue that skipped the node types file when it was absent. Now that the file is present, the check correctly validates it. The extended banner is consistent with both target files.

tools/rustev-conformance/js/copy-addon.mjs — Build utility for local development. Platform/arch detection is correct for napi-rs naming conventions: lib prefix dropped on Windows, correct extensions (dylib/so/dll), no libc suffix on macOS, -gnu/-musl on Linux. The process.report.getReport().header.glibcVersionRuntime call for musl detection is somewhat expensive but stable since Node 14, which is the minimum required for native addons. The !ext guard correctly catches unsupported platforms before copyFileSync is reached. No security concerns: paths come from the build system and the operation is a plain file copy.

specs/027-node-and-wasm-bindings/spec.md — Removes planned: true for the node directory (now present), adds the runtime crate to extends, and documents Increment 6 including two acknowledged behavioral findings for the owner. These are explicitly flagged as needing the owner's reading; they are design decisions, not bugs in the reviewed files.

tools/rustev-release/release-set.json — Adds rustev-node to the exclusion list with the same rationale used for rustev-wasm. Consistent.

No bugs, security issues, or inconsistencies found across the six reviewed files.

{"head": "801d0d3f90113a35902b34230e45bee306f5a1f3", "verdict": "no-findings", "findings": []}

Subject: 847339d...801d0d3, diff digest ffa9099dba4d8d5f514594bf0984209181e9af4461eb027359aba5a80bc80602, 2 call(s). An AI comment is not an approval.

@github-actions

Copy link
Copy Markdown

AI review (findings)

Group 1 of 2

Reviewing the diff, which introduces a new napi-rs Node.js binding (rustev-node) and a clock utility.

Findings

1. TOCTOU race between shutdown check and InFlight accounting — integrations/rustev-node/src/lib.rs

PlanHandle::decide checks shut.load(SeqCst) at the top of the function, but increments InFlight much later — after an await point (the async snapshot fetch via the context source). A concurrent shutdown() call during that async gap sees in_flight == 0, stores shut = true, finishes its drain loop, cancels the JS-tracked handles, and returns {stillRunning: 0} — while the task is then spawned unseen. The decision eventually completes (the cancel handle was already raised) but shutdown() has already returned with a misleading report.

command_async gets this right and the comment even calls it out:

// Counted before the shutdown check (both sequentially consistent):
let counted = Blocking::enter(self.inner.clone());
self.live()?;

decide does the opposite, creating the race.

2. Silent u64 → u32 truncation in shutdown() — integrations/rustev-node/src/lib.rs

(self.inner.in_flight.load(Ordering::SeqCst) + self.inner.blocking.load(Ordering::SeqCst))
    as u32

The two AtomicU64 values are summed as u64 and then cast to u32 without a saturating clamp or checked conversion. In practice the configured limits make overflow unreachable, but the cast should be … .min(u32::MAX as u64) as u32.

3. Char-literal parser edge case in code_of — integrations/rustev-node/tests/no_unsafe.rs

} else if c == b'\'' && (b.get(i + 2) == Some(&b'\'') || next == Some(b'\\')) {
    let mut end = i + 1;
    while end < b.len() && b[end] != b'\'' { ... }
    let end = (end + 1).min(b.len());

For the escaped char literal '\'' the loop starts at i+1, immediately finds \ ≠ ', advances to i+2 which is ', stops, then sets end = i+3. The closing ' at i+3 is left unprocessed. That stray ' then enters the top of the loop as a new potential literal or lifetime marker, potentially misclassifying subsequent code. The test vectors in the same file don't cover '\''. This doesn't produce false negatives for unsafe in the current codebase (strings/chars are kept as code, not blanked) but the parser is provably wrong for this input.

{"head": "3b02e05afc3cff24499ce275b6f97e9a886aea08", "verdict": "findings", "findings": [{"path": "integrations/rustev-node/src/lib.rs", "line": null, "summary": "TOCTOU race in PlanHandle::decide: the shutdown flag is checked before InFlight::enter with an async await point in between, so shutdown() can return {stillRunning: 0} while a task is about to be spawned — the opposite ordering from the correctly structured command_async."}, {"path": "integrations/rustev-node/src/lib.rs", "line": null, "summary": "shutdown() casts the sum of two AtomicU64 counters directly to u32 without a saturating clamp, silently truncating if the sum exceeds u32::MAX."}, {"path": "integrations/rustev-node/tests/no_unsafe.rs", "line": null, "summary": "code_of mis-parses the escaped char literal '\\'' (consumes 3 of 4 bytes), leaving a stray quote that can misclassify subsequent code, though this does not cause false negatives for unsafe detection in the current source files."}]}

Group 2 of 2

Reviewing the six files in this group.

integrations/rustev-node/types/rustev-documents.d.ts (new): Large generated declaration file, content mirrors the existing wasm package declarations with the same header comment and identical namespace exports. No issues.

integrations/rustev-wasm/types/rustev-documents.d.ts: Adds a clarifying comment block to the banner only. No issues.

specs/027-node-and-wasm-bindings/spec.md: Removes planned: true from the node directory entry (correct, since the implementation now lands), adds the runtime extends entry (correct per the comment), and documents increment 6 with two explicit owner findings. Consistent with the rest of the change.

tools/rustev-conformance/js/copy-addon.mjs: The native-extension mapping (darwin: 'dylib', linux: 'so', win32: 'dll') correctly reflects cargo cdylib output names. The lib prefix logic (present on mac/linux, absent on win32) is correct. Using process.report.getReport().header.glibcVersionRuntime to discriminate glibc vs musl is a known-good approach on Node 12+. Arguments validated before use; error handling via thrown exception from copyFileSync is appropriate for a build utility. No issues.

tools/rustev-conformance/js/gen-types.mjs: The removed special-case (!existsSync(p) && t.includes('rustev-node')) was a temporary bypass while the native package was planned-only; removing it now that the file is present in the same PR is correct. The check logic still handles a missing file gracefully (reads '' and diffs). No issues.

tools/rustev-release/release-set.json: Adds rustev-node to the exclusion list with a correct reason. Consistent with the wasm entry already present.

{"head": "3b02e05afc3cff24499ce275b6f97e9a886aea08", "verdict": "no-findings", "findings": []}

Subject: 04eed4d...3b02e05, diff digest 3263f2129504b3d230145729f4d1abdcea669f0ebc92586e48abc85f25610f77, 2 call(s). An AI comment is not an approval.

@github-actions

Copy link
Copy Markdown

AI review (findings)

Group 1 of 2

Reviewing the PR, which adds a Node-API binding (integrations/rustev-node) built on napi-rs. Main areas examined: error propagation, seam lifecycle, keep-alive logic, shutdown sequencing, and the no_unsafe.rs test parser.

integrations/rustev-node/tests/no_unsafe.rs — code_of mishandles b"..." byte-string literals

The parser handles br"..." (raw byte strings) correctly via the c == b'b' && next == Some(b'r') branch. But plain byte strings (b"...") are not handled as a unit: the b prefix is pushed verbatim, then the "..." portion is captured by the regular string branch. Because the string's contents are kept (by design — strings are "code"), any source file that writes a byte string literal containing the substring "unsafe" (e.g. b"handle unsafe input") would trigger the assert. The current source files contain no such byte strings, but the parser has a latent false-positive hole.

integrations/rustev-node/test/negative.test.mjs — "missing platform package" test is not isolated from parent node_modules

copyFileSync(join(pkg, 'index.js'), join(dir, 'index.js'));
// only index.js is copied; node_modules is NOT created
require(join(dir, 'index.js')); // expects MODULE_NOT_FOUND → PlatformPackageMissing

Node's require resolution ascends parent directories. If @statecrafting/rustev-<platform> is present in any ancestor node_modules (e.g. the repo root after npm install of optional deps), the package loads silently and no error is thrown. The assertion would then fail or—if the assert.throws predicate is silent—pass with the wrong behaviour.

integrations/rustev-node/src/lib.rs — advance_clock parameter declared u32 but typed as number in TypeScript

#[napi]
pub fn advance_clock(&self, ms: u32) -> Result<()> { … }

index.d.ts declares advanceClock(ms: number): void. napi-rs converts JavaScript numbers to u32 by truncation/wrapping, so passing a value above u32::MAX (≈ 4.29 billion ms, ~49 days) silently produces a much smaller advance. For a test-clock utility this is unlikely to matter in practice, but it is a type contract violation.

{"head": "5772002e4efef577f4b60387b95f1bd2961b64b2", "verdict": "findings", "findings": [{"path": "integrations/rustev-node/tests/no_unsafe.rs", "line": 50, "summary": "code_of does not handle b\"...\" byte-string literals as a unit; the b prefix is emitted as code and the string content is kept verbatim, so any byte string containing the substring \"unsafe\" would cause a false-positive assertion failure."}, {"path": "integrations/rustev-node/test/negative.test.mjs", "line": 234, "summary": "The 'missing platform package' test copies only index.js into a temp dir, but Node's require resolution ascends parent directories, so if the platform package is installed in any ancestor node_modules the test silently loads it instead of throwing PlatformPackageMissing."}, {"path": "integrations/rustev-node/src/lib.rs", "line": 296, "summary": "advance_clock accepts ms as u32 on the Rust side but is typed as number in index.d.ts; napi-rs truncates JavaScript values above u32::MAX (~4.29 billion ms) without error, violating the declared type contract."}]}

Group 2 of 2

Reviewing the six files in this group.

integrations/rustev-node/types/rustev-documents.d.ts — New generated file, byte-identical to the wasm counterpart (same banner, same type bodies). The generator update confirms both paths are now checked together. No issues.

integrations/rustev-wasm/types/rustev-documents.d.ts — Three lines added to the file-level comment. Cosmetic only.

tools/rustev-conformance/js/gen-types.mjs — Removes the existsSync(p) && t.includes('rustev-node') skip that kept the check from failing while the native package was still planned. Now that the types file exists, the guard was the right thing to remove. No issues.

tools/rustev-release/release-set.json — Adds rustev-node to the exclusions with an accurate reason. Consistent with the wasm entry and the spec.

specs/027-node-and-wasm-bindings/spec.md — The planned: true flag is dropped (correct, the directory now lands), the runtime directory is added as an extends target (with a comment explaining why: the read-only manual clock accessor), and a long Increment 6 prose section is added. Two findings are explicitly flagged for the owner, which is the right pattern.

tools/rustev-conformance/js/copy-addon.mjs — One specific concern:

process.report.getReport() generates a full Node.js diagnostic report (memory maps, open file handles, CPU info, libuv handles, etc.) just to read header.glibcVersionRuntime. It is correct — glibc systems will have that field, musl systems will not — but the call is expensive for what it returns. A cheaper alternative would be checking /lib/libc.musl-* existence or using child_process.execSync('ldd --version 2>&1'), though neither is blocking for a one-shot build script.

The platform → extension mapping (darwin→dylib, linux→so, win32→dll) and the conditional lib prefix (librustev_node on Unix, rustev_node on Windows) are both correct for Cargo's output. The resulting rustev.<platform>-<arch><libc>.node name matches napi-rs platform-package naming conventions. The exit on unknown platform is intentional.

No bugs or security issues found. The one item worth flagging is the heavyweight libc probe.

{"head": "5772002e4efef577f4b60387b95f1bd2961b64b2", "verdict": "findings", "findings": [{"path": "tools/rustev-conformance/js/copy-addon.mjs", "line": 26, "summary": "process.report.getReport() generates a full diagnostic report (memory maps, handles, CPU) just to probe glibcVersionRuntime; a stat check on /lib/libc.musl-*.so.1 or an equivalent lightweight test would be less wasteful for a build-time script."}]}

Subject: 2a8eeeb...5772002, diff digest f53ffda19f86037693098c0c453f1618d1defa8ba38fad32c38299c84bf74e82, 2 call(s). An AI comment is not an approval.

@github-actions

Copy link
Copy Markdown

AI review (findings)

Group 1 of 2

Review

crates/rustev-runtime/src/clock.rs

The new pending_delays() method looks correct: it computes at.saturating_sub(s.now) for each sleeper and returns a sorted vec.

integrations/rustev-node/src/lib.rs

clock_delays return type truncates silently. advance_clock accepts values up to 2^53 − 1 ms (guarded at both the JS and Rust layers), but clock_delays returns Vec<u32>, capping every delay at 4,294,967,295 ms (≈ 49.7 days). A conformance host that reads clockDelays() to decide how far to advance the clock for a timer set more than ~49.7 days ahead will silently receive the wrong value. The truncation is explicit (.min(u64::from(u32::MAX)) as u32) but the inconsistency with advanceClock's accepted range is a real defect for automated clock-driving. The TypeScript declaration clockDelays(): number[] does not imply u32 bounds.

integrations/rustev-node/tests/no_unsafe.rs

Substring match is fragile. The assertion !line.contains("unsafe") will fire on any source line where the string "unsafe" appears as a sub-identifier—most notably #[allow(unsafe_code)], which is a common annotation that napi-rs documentation recommends adding to suppress warnings. unsafe_code is a valid Rust identifier and is not a keyword; code_of does not strip attribute contents, so the line remains in the output and the assertion fails spuriously. No current source file triggers this, but the test is one annotation away from a false failure that masks real findings. A word-boundary regex (\bunsafe\b) would be reliable.

integrations/rustev-node/src/seams.rs

The bounded-queue admission loop in SeamStats::admit is a correct compare-exchange spin; the RAII Slot correctly tracks depth. The report() helper's treatment of a missing charge or remote end as unknown / PossiblyContinuing permanent failure matches spec 3.6.5.

integrations/rustev-node/index.js

The typed() error mapper, SeamFailure constructor, backendSeam cancel plumbing, and shutdown drain-then-cancel loop all look correct. The require-based platform-package loader correctly distinguishes "not found" from "installed but unloadable" by matching the error message prefix. The process.report.excludeNetwork side-effect is intentional and documented.

integrations/rustev-node/src/commands.rs

Store::resolve does only a BTreeMap key lookup—no filesystem access—so the {dir}/{reference} path is not a path-traversal risk. The ms() helper correctly accepts integral floats ≤ 2^53.

{"head": "61f70d21914ffbef44c1bebf0ce48d4cd61fddca", "verdict": "findings", "findings": [{"path": "integrations/rustev-node/src/lib.rs", "line": null, "summary": "clock_delays() returns Vec<u32> and silently caps every pending delay at u32::MAX (~4.3 billion ms), inconsistent with advanceClock's accepted range of up to 2^53-1 ms; a clock-driving test harness would receive wrong delay values for any timer set more than ~49.7 days ahead."}, {"path": "integrations/rustev-node/tests/no_unsafe.rs", "line": 26, "summary": "line.contains(\"unsafe\") is a substring check, not a keyword check; any source line with an identifier containing 'unsafe' (e.g. the lint name unsafe_code in #[allow(unsafe_code)]) would trigger a false positive, potentially masking real violations."}]}

Group 2 of 2

Reviewing the six files in group 2.

integrations/rustev-node/types/rustev-documents.d.ts (new)
Large generated TypeScript declarations. The header matches the updated banner in gen-types.mjs, and the content mirrors the wasm package declarations (now byte-identical as required). No issues.

integrations/rustev-wasm/types/rustev-documents.d.ts
Adds five lines to the banner comment only. Consistent with the gen-types.mjs change. No issues.

specs/027-node-and-wasm-bindings/spec.md
Removes planned: true from integrations/rustev-node/ (consistent with the code now being delivered), adds the runtime crate as an additive extension (for the manual clock accessor), and documents Increment 6. Internally consistent with the other changes.

tools/rustev-conformance/js/copy-addon.mjs (new)
Build-time utility script. The logic is sound:

  • Platform→extension mapping (dylib/so/dll) matches cargo build --release output for a cdylib.
  • process.report.excludeNetwork is guarded with an in check before setting.
  • glibcVersionRuntime truthiness correctly distinguishes glibc from musl.
  • process.arch values (x64, arm64, etc.) match napi-rs platform-package naming.
  • copyFileSync will throw with a native error on missing source; no clean error message, but not a security issue.
    No significant bugs or security concerns.

tools/rustev-conformance/js/gen-types.mjs
Removes the three-line skip block that exempted rustev-node when it was still planned. Correct now that the file is being added in this PR.

tools/rustev-release/release-set.json
Adds rustev-node to the exclusions list with the same rationale used for rustev-wasm. Consistent with the spec.

No bugs, security problems, or inconsistencies found.

{"head": "61f70d21914ffbef44c1bebf0ce48d4cd61fddca", "verdict": "no-findings", "findings": []}

Subject: a9bd081...61f70d2, diff digest fbfe9b6d0fa0bc3f09eef9d6d15a6541417e3a309f28ab8d4f919f4aa12b5fd0, 2 call(s). An AI comment is not an approval.

@github-actions

Copy link
Copy Markdown

AI review (findings)

Reviewing the PR — a new rustev-node napi-rs crate, a pending_delays() accessor on ManualClock, a spec entry, and a release-set exclusion.


integrations/rustev-node/src/commands.rs — confusing error wording

The s() helper at line ~32:

.ok_or_else(|| usage(format!("{k} is a string")))

Every other usage message uses the imperative form ("{k} must be a non-negative integer", "{k} is a list" in list()). "{k} is a string" reads as a description, not a refusal. It should read "{k} must be a string".


integrations/rustev-node/src/lib.rs — inconsistent shutdown-fence placement between command_async and prepare_async

command_async checks live() immediately after Blocking::enter (before scheduling the blocking task), so a task that clears the live check always runs to completion — a queued command is never killed by a mid-flight shutdown:

let counted = Blocking::enter(self.inner.clone());
self.live()?;         // one check; no recheck inside spawn_blocking
self.inner.rt.spawn_blocking(move || { ... commands::run(...) ... })

prepare_async performs no live() check outside the task; it dispatches the blocking task unconditionally and relies on the live() inside compile/load to reject:

let counted = Blocking::enter(self.inner.clone());
// no live() check here
self.inner.rt.spawn_blocking(move || {
    // live() fires inside engine.compile() / engine.load()
})

The consequence: a compile/load that races with shutdown can fail even after Blocking::enter counted it as admitted, while a command in the same race always completes. Both increment blocking and are supposed to behave uniformly under the shutdown fence. Either prepare_async should mirror command_async (check live() outside, no recheck inside), or command_async should recheck inside — but the two paths should agree.


No security issues found. The panic-catching (guard/catch_unwind), threadsafe-function queue overflow handling, atomic ordering for the in-flight/blocking counters, and traceparent_valid are all correct.

{"head": "e28fb80a602ab1abf82580eb3987085404e6aab8", "verdict": "findings", "findings": [{"path": "integrations/rustev-node/src/commands.rs", "line": 32, "summary": "Error message `\"{k} is a string\"` is grammatically a description, not a refusal; all other usage messages use the `must be` form."}, {"path": "integrations/rustev-node/src/lib.rs", "line": null, "summary": "`prepare_async` places no `live()` check outside `spawn_blocking` while `command_async` does, so a mid-flight shutdown kills a queued compile/load but lets a queued command complete — the two blocking-pool paths behave inconsistently under shutdown."}]}

Subject: 89a6ffd...e28fb80, diff digest 26c383fa75ba67e6de760451120688820443f0a28c0f3da7890d76ab7797a4d6, 1 call(s). An AI comment is not an approval.

@github-actions

Copy link
Copy Markdown

AI review (findings)

Review

crates/rustev-runtime/src/clock.rs

The new pending_delays method looks correct. saturating_sub handles sleepers already past due, and sort_unstable gives ascending order for the conformance runner to advance the clock deterministically.

integrations/rustev-node/Cargo.toml

Pinned exact versions (=3.14.2, =3.6.12, =2.6.0) and the cdylib crate type are correct for a napi-rs addon. The unsafe_code = "deny" lints comment matches the approach documented in the spec.

integrations/rustev-node/src/lib.rs

  • traceparent_valid: length 55, four parts, version "00", lowercase hex fields, non-zero trace and parent IDs — correct per the stated restriction to lowercase (the code comment says "lowercase hex").
  • InFlight/Blocking RAII guards: increment before the shutdown check, drop on early return — the "either shutdown waits or the call refuses" invariant holds.
  • prepare_async: the wildcard arm covers both (None, None) and (Some, Some) with the same error detail; functionally correct, slightly imprecise message.

integrations/rustev-node/src/seams.rs

Finding 1 — report() treats "failure": null as a failure.
v.get("failure") returns Some(&Value::Null) when the host response contains the key "failure" mapped to JSON null. The code enters the failure branch, f["class"].as_str() returns None on Null, and falls through to unknown(...), turning a successful host response that includes "failure": null into a permanent failure with unknown charge. The fix is if let Some(f) = v.get("failure").filter(|f| !f.is_null()).

Finding 2 — HostContext::snapshot doesn't track late resolutions.
The sink and backend seams spawn a separate Tokio task and use a oneshot channel so that, when the consumer drops the receiver (e.g., the decide future is abandoned), the spawned task can increment late_resolutions_discarded. HostContext::snapshot awaits the JavaScript Promise inline: if the decide future is dropped while p.await is pending, the slot is released correctly but late_resolutions_discarded is never incremented. The module doc comment claims 3.6.4 guarantees ("a late settlement is discarded and counted") for all seams; the context source silently violates that.

integrations/rustev-node/src/commands.rs

Store::resolve builds the map key as format!("{dir}/{reference}") with no normalisation; a reference containing .. segments would look up an unintended key in the in-memory inputs map (e.g., accessing a different store's data). Since all inputs are caller-supplied this is a limited-impact design-level concern rather than a security vulnerability, but it is an unexpected key-lookup behaviour.

integrations/rustev-node/tests/no_unsafe.rs

The code_of parser correctly handles //, /* */, plain strings, byte strings, raw strings (r#"…"#, br#"…"#), and char literals. has_unsafe_keyword correctly checks both surrounding characters are non-identifier. The directory-entry assertion is documented as intentional.

tools/rustev-release/release-set.json

Exclusion of rustev-node for the same reason as rustev-wasm is consistent.

{"head": "69ec26694994db739daebc7be45e354b97a86bd0", "verdict": "findings", "findings": [{"path": "integrations/rustev-node/src/seams.rs", "line": null, "summary": "In `report()`, `v.get(\"failure\")` is truthy for a JSON `null` value, so a host response with `\"failure\": null` is misinterpreted as an unknown permanent failure instead of falling through to the success path."}, {"path": "integrations/rustev-node/src/seams.rs", "line": null, "summary": "`HostContext::snapshot` awaits the JavaScript Promise inline without a spawned task and oneshot channel, so if the outer `decide` future is dropped during the fetch, `late_resolutions_discarded` is never incremented, violating the 3.6.4 guarantee stated in the module doc comment."}]}

Subject: 89a6ffd...69ec266, diff digest ea2c9bf82e3c9bf8a8e7bf039ed32434382963ada1c51daaaca793364c3a6988, 1 call(s). An AI comment is not an approval.

@github-actions

Copy link
Copy Markdown

AI review (findings)

Reviewing the PR which adds the integrations/rustev-node crate (napi-rs Node-API binding) plus a clock helper and spec update.


Finding 1 — seams.rs: report() silently drops invalid cancel values

seams.rs (~line 342):

let cancel = match v["cancel"].as_str() {
    Some("stopped") => CancelAck::Stopped,
    Some("unconfirmed") => CancelAck::Unconfirmed,
    _ => CancelAck::NotRequested,
};

An unrecognized cancel value (e.g., a host typo like "stopped_confirmed") silently becomes NotRequested. This is inconsistent with charge and remote, where an unrecognized value triggers the unknown() path and surfaces a diagnostic. A host that returns a malformed cancel field will have it silently swallowed rather than produce a detectable error.


Finding 2 — lib.rs: prepare_async missing guard() in spawn_blocking

lib.rs (~line 310):

self.inner
    .rt
    .spawn_blocking(move || {
        let _counted = counted;
        ...
        match (definition, plan) {
            (None, Some(p)) => engine.load(Uint8Array::new(p), ds, cs),
            (Some(d), None) => engine.compile(Uint8Array::new(d), ds, cs),
            _ => Err(fail(...)),
        }
    })
    .await
    .map_err(|e| fail("InternalError", "internal", e.to_string()))?

Unlike command_async (which wraps its blocking closure in guard(|| ...) to catch panics and forward the panic message as InternalError), prepare_async relies solely on JoinError to catch panics. The JoinError display just says "task panicked" with no message, so panic details are silently lost here. This is an inconsistency in diagnostic quality.


{"head": "d25e0318c47f69c361343a1ab89b751d82abe72a", "verdict": "findings", "findings": [{"path": "integrations/rustev-node/src/seams.rs", "line": 342, "summary": "Unrecognized `cancel` ack values silently default to NotRequested instead of returning `unknown`, inconsistent with how unrecognized `charge` and `remote` values are handled and able to mask host bugs."}, {"path": "integrations/rustev-node/src/lib.rs", "line": 310, "summary": "`prepare_async`'s spawn_blocking closure lacks `guard()`, so panics in `compile`/`load` produce a generic JoinError with no message, unlike `command_async` which correctly uses `guard()` to capture and forward panic details."}]}

Subject: 89a6ffd...d25e031, diff digest 4e902aa4805601b38f2e2dd1e4782b4a63f49e49c0688b13f2a96c10d726622d, 1 call(s). An AI comment is not an approval.

@github-actions

Copy link
Copy Markdown

AI review (findings)

Reviewing the PR, which introduces the rustev-node napi-rs binding, a pending_delays() accessor on ManualClock, and updates to the spec.

crates/rustev-runtime/src/clock.rs
The pending_delays() function looks correct: locks the clock state, computes each sleeper's remaining delay with saturating_sub, and returns a sorted vec. No issues.

integrations/rustev-node/src/commands.rs
The ms() helper correctly handles the missing-key-as-null behaviour of serde_json::Value, and the Store::resolve one-extra-byte pattern (max_bytes.saturating_add(1)) is intentional for truncation detection by the caller.

integrations/rustev-node/src/errors.rs
guard() uses AssertUnwindSafe; this is the accepted pattern at a napi boundary.

integrations/rustev-node/src/lib.rs
Shutdown/in-flight ordering: InFlight::enter and Blocking::enter always precede the shut.load check, both using SeqCst; that's correct. The Blocking drop on early return from prepare_async/command_async is also correct (the guard is a local, dropped on the ?-propagated error).

Issue — advance_clock error code for system clock (lib.rs):
The None branch (system clock) returns "ConfigRefused"/"out_of_range" with { "field": "clock", "detail": "not a manual clock" }. Every other use of "out_of_range" in this file is for a numeric out-of-range condition and carries min/max fields (see range(), and the ms branch at the top of the same function). A JavaScript caller that handles "out_of_range" generically and expects min/max fields will get an inconsistently shaped payload here. The correct code should be something like "unsupported_operation" or a dedicated code, not "out_of_range".

integrations/rustev-node/src/seams.rs
Queue-slot lifecycle: on the early-return path when record.record_canonical() fails in HostSink::deliver, slot is a let-bound local that drops correctly when the function returns (it is not captured by the returned async closure). Late-result discard counting and the cancel-forwarding logic in HostBackend::infer look correct.

integrations/rustev-node/tests/no_unsafe.rs
code_of correctly blanks string/raw-string contents and preserves newlines (so line numbers hold). has_unsafe_keyword correctly rejects unsafe_code identifiers. The test only walks src/ flat—subdirectories would cause an assert!(p.is_file()) failure, which is intentional by the comment.

traceparent_valid
Correctly enforces W3C Trace Context version-00: exactly 55 chars, four dash-separated fields, lowercase hex only, non-zero trace-id and parent-id. The length check is redundant but not harmful.

{"head": "915b13bd8f54ecb984b399dc4bf240657fdd569c", "verdict": "findings", "findings": [{"path": "integrations/rustev-node/src/lib.rs", "line": null, "summary": "advance_clock's None branch (system clock) returns \"ConfigRefused\"/\"out_of_range\" — the same code used for numeric range violations with min/max fields — instead of a distinct code for an unsupported-operation condition, producing an inconsistently shaped error payload."}]}

Subject: 4159d3c...915b13b, diff digest 81a2c07288e21ae42b5b6bdcb07211215c601ca657fba41beb344ffa93f286db, 1 call(s). An AI comment is not an approval.

@github-actions

Copy link
Copy Markdown

AI review (findings)

Reviewing the new integrations/rustev-node crate and the supporting changes to clock.rs, spec.md, and release-set.json.

integrations/rustev-node/src/lib.rs — sync methods not counted in blocking

command_async and prepare_async correctly call Blocking::enter before self.live()?, so shutdown() accounts for them:

// command_async
let counted = Blocking::enter(self.inner.clone());
self.live()?;

But the synchronous command, compile, and load methods do not:

pub fn command(&self, ...) -> Result<CommandResult> {
    guard(|| {
        self.live()?;        // no Blocking::enter
        ...
    })
}

shutdown() returns in_flight + blocking, which the JavaScript layer uses as its drain count. In single-main-thread usage this doesn't matter (you can't call both concurrently), but with Node.js Worker threads sharing an engine via a SharedReference, a Worker can be mid-command when another thread calls shutdown(). The drain count would undercount, and the JS layer could declare drain complete while the synchronous call is still running. compile and load have the same gap.

The fix is straightforward: each sync method should hold a Blocking guard for its lifetime (counting happens before live() is checked, as command_async does).

Everything else looks correct:

  • The SeamStats::admit CAS loop is race-free.
  • traceparent_valid correctly enforces the W3C version-00 format (2+1+32+1+16+1+2 = 55 chars, lowercase hex only, non-zero trace-id and parent-id).
  • ms() and integer() correctly cap at 2^53 − 1 before as u64 / as f64 conversions.
  • The code_of / has_unsafe_keyword parser in no_unsafe.rs handles doc comments, block comments, string literals, byte strings, raw strings, char literals, and lifetimes correctly.
  • pending_delays() in clock.rs correctly uses saturating_sub and the cap in clock_delays at 9 007 199 254 740 991 is representable exactly as f64.
  • Store::resolve does a plain HashMap lookup (no filesystem), so .. in reference is harmless.
  • The spec.md addition and release-set.json exclusion are consistent with each other and with the existing rustev-wasm precedent.
{"head": "36dfdcb3fcec6760f13cad942da226f3f46edfb3", "verdict": "findings", "findings": [{"path": "integrations/rustev-node/src/lib.rs", "line": null, "summary": "Sync `command`, `compile`, and `load` do not call `Blocking::enter`, so `shutdown()`'s drain count excludes them; concurrent calls from Worker threads are invisible to the shutdown-and-drain protocol."}]}

Subject: 55df832...36dfdcb, diff digest 44853579f01a59fe4663d0e3d0bf03c023118ac14022b71090d8a782ff76a20d, 1 call(s). An AI comment is not an approval.

@github-actions

Copy link
Copy Markdown

AI review (findings)

Reviewing the PR, which introduces integrations/rustev-node (a napi-rs native binding), adds pending_delays() to ManualClock, and excludes the new crate from the release set.

crates/rustev-runtime/src/clock.rs
pending_delays() locks the mutex with the standard poison-recovery pattern and returns sorted u64 delays. The saturating_sub prevents wrapping on a sleeper already past now. Looks correct.

integrations/rustev-node/Cargo.toml / build.rs
Exact-version pins (=3.14.2, =3.6.12, =2.6.0) and unsafe_code = "deny" are appropriate for the stated reasons. cdylib crate-type is correct for a native addon.

integrations/rustev-node/src/errors.rs
guard wraps with AssertUnwindSafe at the FFI boundary — the standard idiom. Error-class mapping follows the spec.

integrations/rustev-node/src/commands.rs
The ms() helper correctly tries as_u64() first and falls back to a float with range/fract checks. The Store resolver key-builds "{dir}/{reference}" and does an exact BTreeMap lookup, so there is no filesystem path traversal — only the caller's own inputs map is searched.

integrations/rustev-node/src/lib.rs

  • The InFlight/Blocking counter-before-check pattern combined with SeqCst ordering provides the stated invariant for shutdown correctly.
  • traceparent_valid correctly checks W3C version-00 format (55 chars, 4 parts, non-zero trace and parent IDs, lowercase hex).
  • Minor inconsistency: In prepare_async, the _ wildcard arm covers both (None, None) and (Some, Some). The error message "compile takes exactly one of a definition and a plan" is accurate for (Some, Some) but misleading for (None, None) where neither was supplied.

integrations/rustev-node/src/seams.rs

  • SeamStats::admit is a correct lock-free bounded-counter CAS loop.
  • The report() function correctly gives failure priority over output when both are present, and maps an unparseable RawOutput to unknown (permanent + unknown charge) per spec 3.6.5.
  • The infer future's poll_fn correctly registers the waker via rx.poll(cx) on every iteration so it wakes when the host responds after an abort is forwarded. The spawned task drops slot before sending on tx, so the queue depth is decremented whether or not the runtime is still waiting.
  • No blocking occurs across await points holding std::sync::Mutex<Traces>.

integrations/rustev-node/tests/no_unsafe.rs
code_of correctly handles '\x41', '\u{…}' (the next == Some(b'\\') branch catches all escape-starting char literals), raw strings of all delimiter depths, block comments, and byte strings. has_unsafe_keyword is Unicode-aware. No false-negative risk for unsafe detection in the crate's own source.

specs/027-node-and-wasm-bindings/spec.md / tools/rustev-release/release-set.json
planned: true → present (removal is correct, crate now exists). Release-set exclusion rationale matches the WASM crate pattern.

{"head": "3208b9e319357dea6a2a939bd119843df0d64584", "verdict": "findings", "findings": [{"path": "integrations/rustev-node/src/lib.rs", "line": 329, "summary": "The wildcard arm of `match (definition, plan)` in `prepare_async` emits 'compile takes exactly one of a definition and a plan' for both the (Some, Some) and (None, None) cases, producing a misleading error message when neither argument is provided."}]}

Subject: 55df832...3208b9e, diff digest 08e2e7090ae4c5cae743f416f91b66548b5364c6b066c5d61da69f284a4f22f6, 1 call(s). An AI comment is not an approval.

@github-actions

Copy link
Copy Markdown

AI review (findings)

Reviewing the new integrations/rustev-node crate and supporting changes.

Finding 1 — prepare_async double-counts the blocking counter

integrations/rustev-node/src/lib.rs lines ~295-330: prepare_async calls Blocking::enter before spawning (correct, to prevent the shutdown race), moves that guard into the closure, and then calls engine.compile or engine.load from inside the closure. Both compile (line ~249) and load (line ~275) immediately call Blocking::enter themselves. While the closure runs, blocking is 2 for a single logical compile. shutdown() reads in_flight + blocking to produce its reported count, so it over-reports by 1 for every concurrent prepare_async. If the JS layer uses that count to track outstanding work, it will await one more completion than exists.

A safe fix: count only in prepare_async and have the closure bypass the inner Blocking::enter in compile/load, or alternatively remove the outer count in prepare_async and push the shutdown-race guard entirely into the closure (where the inner count already handles it).

Finding 2 — clock_sleepers silently truncates

integrations/rustev-node/src/lib.rs line ~385:

map_or(0, |c| c.sleepers() as u32)

sleepers() returns usize; on a 64-bit host, any value above u32::MAX is silently truncated to zero or a wrong number. clock_delays() (line ~375) bounds the delay values defensively, so the same pattern should be applied here.

{"head": "c07be8cddffd67aa4c94208847d02bc289daf04d", "verdict": "findings", "findings": [{"path": "integrations/rustev-node/src/lib.rs", "line": 321, "summary": "prepare_async increments the blocking counter before spawning, then compile/load each increment it again inside the closure, causing shutdown() to over-report the in-flight count by one for every concurrent prepare_async call."}, {"path": "integrations/rustev-node/src/lib.rs", "line": 385, "summary": "clock_sleepers casts usize to u32 without a bounds check, silently truncating the sleeper count if it exceeds u32::MAX."}]}

Subject: 55df832...c07be8c, diff digest ff87cad841a8d826ffd26c1d756476d73e94ce6177b1675c3d32bc279634f40f, 1 call(s). An AI comment is not an approval.

@github-actions

Copy link
Copy Markdown

AI review (findings)

Review

The PR adds the rustev-node napi-rs binding (spec 027 increment 6) with an Engine struct, host seams, pure commands, and a no_unsafe.rs integrity test. The overall implementation is well-structured. Two items stand out.


Finding 1 — Cargo.toml: workspace lints not inherited

integrations/rustev-node/Cargo.toml contains only:

[lints.rust]
unsafe_code = "deny"

Without a [lints] table with workspace = true, Cargo does not inherit any workspace-level lint configuration — only this one lint is active in the crate. The spec comment says "relaxes the workspace's forbid to deny", which implies the intent was to override a single lint while keeping the rest, but the current form discards all other workspace lints (e.g. dead_code, unused_imports, or any additional safety lints the workspace may set). The correct form to override one lint while inheriting the rest would be:

[lints]
workspace = true

[lints.rust]
unsafe_code = "deny"

Finding 2 — seams.rs: misleading error message in report()

In report() (the host-answer parser), when only one of charge or remote fails to parse, the error says:

"the host's answer names no charge or remote end"

The or implies both are absent, but the path is hit whenever either is None. When debugging a host seam that returns a valid charge but an unrecognised remote string (e.g. a typo like "finished " with a trailing space), this message points in the wrong direction. Separate messages ("no charge" / "no remote end") or a conjunction ("charge and/or remote end") would be more accurate.


Minor notes (not findings)

  • shutdown() reads in_flight and blocking as two separate SeqCst loads. Because no new tasks can start after shut.store(true, SeqCst), the counts can only decrease between the two loads, so the sum can be overstated (safe/conservative) but never understated — no race hazard.
  • The no_unsafe.rs test's flat read_dir asserts each entry is a file; the comment explicitly documents that adding a subdirectory makes it fail until the test is extended. This is intentional.
  • Charge::Observed { units: 0 } for an overloaded seam queue (nothing called) is noted in the spec text as a documented-acceptable approximation.
{"head": "0140a6cf13eadca99c8a4c1a5362b00f25b9d592", "verdict": "findings", "findings": [{"path": "integrations/rustev-node/Cargo.toml", "line": 37, "summary": "The [lints.rust] section has no parent [lints] workspace = true, so the crate does not inherit any workspace lint configuration beyond unsafe_code = \"deny\", silently dropping all other workspace lints."},{"path": "integrations/rustev-node/src/seams.rs", "line": null, "summary": "In report(), the error string \"the host's answer names no charge or remote end\" is misleading when only one of the two fields is absent, making host-seam debug harder."}]}

Subject: 55df832...0140a6c, diff digest f9aca7c8cbeb60710435d7d1f297bed2bef21c0c119d0090c8ada76b3c810f24, 1 call(s). An AI comment is not an approval.

@github-actions

Copy link
Copy Markdown

AI review (no-findings)

Reviewing the PR, which introduces a napi-rs Node.js binding (integrations/rustev-node) plus a read-only accessor on ManualClock.

crates/rustev-runtime/src/clock.rs — pending_delays() uses saturating_sub to avoid underflow and returns a sorted copy of remaining delays. Correct.

integrations/rustev-node/src/lib.rs — Shutdown protocol is sound: every path increments its counter (InFlight/Blocking) before checking the shut flag, and all are SeqCst. The f64→u64 integer guard (fract == 0.0 && contains) is applied consistently in advance_clock, integer(), and the ms() helper. Panic catching via guard(AssertUnwindSafe(...)) is standard for this use case. The traceparent_valid length + split + hex + non-zero check correctly implements W3C version-00.

integrations/rustev-node/src/seams.rs — The queue slot (Slot) RAII guard is correctly moved into each spawned task and dropped before tx.send, so capacity is released regardless of whether the receiver is still live. Late-settlement counting via tx.send(...).is_err() is correct. The report() function treating a missing charge/remote as unknown with PossiblyContinuing is consistent with the seam contract. The abort forwarding is non-blocking as documented.

integrations/rustev-node/tests/no_unsafe.rs — The custom lexer strips //, /* */, plain strings, byte strings, raw strings (r#"…"#, br#"…"#), and char literals before scanning for the unsafe keyword. The word-boundary check (!ident_before && !ident_after) correctly rejects unsafe_code and similar identifiers. Test cases cover all these branches.

integrations/rustev-node/src/commands.rs — Store::resolve does a key lookup in a closed BTreeMap; no filesystem access, so the {dir}/{reference} concatenation carries no path-traversal risk. r.unwrap_or_else(|d| d) correctly flattens a Result<Done, Done> from the surface layer.

tools/rustev-release/release-set.json / specs/027-node-and-wasm-bindings/spec.md — Exclusion of rustev-node from the crates.io release set matches publish = false in Cargo.toml. Removing planned: true from the spec's establishes entry is correct now that the directory exists.

No bugs, security problems, or inconsistencies found.

{"head": "49c1e26ad9a88b6dea85a29fcea96203576434d9", "verdict": "no-findings", "findings": []}

Subject: 55df832...49c1e26, diff digest 70e9068708a0ce6ae8202b8f3881e3f4519a86d3a116f726721defbe069934b8, 1 call(s). An AI comment is not an approval.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant