Skip to content

impl(063): increment 3, the acquisition source seam in the Node binding - #519

Merged
bartekus merged 5 commits into
mainfrom
impl/063-acquisition
Nov 6, 2026
Merged

bartekus merged 5 commits into
mainfrom
impl/063-acquisition

Conversation

@bartekus

@bartekus bartekus commented Nov 6, 2026 •

Copy link
Copy Markdown
Contributor

Spec 063 increment 3 (3.4, 3.5): the acquisition source seam in the Node binding. Stacked on #518 (3a, sources on compile and load); review only the commits after it.

  • Callback machinery (3.4), src/callback.rs. Each host call is enqueued through a non-blocking threadsafe function and awaited on a one-shot channel; no Rust thread waits on JavaScript and no lock is held across the call. The queue slot belongs to the waiting side, so it is released the moment the runtime stops waiting (window close, cancellation, shutdown). An unsettled Promise is counted in abandonedPending until it settles, then its settlement is discarded and counted in lateResolutionsDiscarded. Increment 4's store reuses this module.
  • The seam (3.5), src/source.rs. EngineOptions.acquisitionSources installs each source through RuntimeBuilder::acquisition_source. A descriptor that does not parse, or a repeated name, is ConfigRefused invalid_source; maxConcurrency or queueCapacity outside 1 to 65,536 is out_of_range; all before any thread. cost_bound comes from the operation's declared cost (bounded gives its bound, otherwise unknown). A page crosses unchanged, copied up to 4 MiB (one byte more of a larger page, so the core's bounded parser refuses it as invalid_page). A thrown SeamFailure keeps its class (including the new denied) and charge, and its cancel only after an abort. Anything else (a malformed answer, a plain throw, a rejection) is permanent with charge unknown, and cancellation unconfirmed if the signal was raised. A full queue is overloaded, charge observed zero. The signal is aborted when the runtime raises the attempt's cancellation.
  • Gauges, shutdown, capture. gauges().seams gains acquisition:<name> with abandonedPending; shutdown resolves with abandonedPending. The plan handle keeps its source descriptors, and capture assembly receives them (they were passed empty until now).
  • Declarations by hand in index.d.ts: AcquisitionSource, AcquireCall, AcquireAnswer, acquisitionSources, denied on SeamFailure, the two new fields. No generated declaration changes.
  • Edits to shared files: lib.rs, index.js, index.d.ts, run.mjs and tools/rustev-conformance/src/** change by additions, except where a line can only change: the new trailing Engine.create argument, the shutdown return object, the two SeamFailure unions, load_checked becoming load_checked_with_sources in the Rust case runner, and capture.rs's assemble taking the sources. In seams.rs, five helpers become pub(crate) and SeamStats gains callbacks and abandoned_pending, with abandonedPending shown only for callback seams.
  • Conformance (3.13.2). Both runners gain scripted sources (src/acquire.rs, scriptedSource in run.mjs): per decision, the answer of each call in order. Four cases run on rust-api and native with identical bytes: runtime.acquire-page, runtime.acquire-retry-denied, runtime.acquire-window and runtime.acquire-widen. Each expected record is checked in tests/runtime.rs against what its mirrored test asserts. Fixtures are under fixtures/acquire/. Two differences from the mirrored tests, recorded in the spec:
    • The adapter-panic row is left out: a host cannot panic the runtime.
    • In runtime.acquire-window the source never answers, so both runners record not_observed. A host's cancellation answer crosses threads and cannot be ready when the runtime polls once, which is why runtime.cancel-stop excludes native.
  • Host-seam tests (3.13.3), test/source.test.mjs. Cover:
    • What a call carries: the request bytes, requestId, attemptId, remainingMs (20, the window), the principal handle and the signal.
    • denied: one call, missing_evidence, no exception.
    • A named class retried.
    • A synchronous throw: permanent, charge unknown.
    • A non-Promise page.
    • An unknown field, or a page over 4 MiB: invalid_page and invalid_backend_output.
    • A full queue: overloaded, charge zero, refusedFull.
    • A never-settling Promise: deadline at the window, the signal aborted, abandonedPending 1, no slot held. Its late settlement is then discarded and counted.
    • Shutdown with a pending callback: abandonedPending 1.
    • Refusals: duplicate names, an invalid descriptor, bounds out of range, an uninstalled or differently versioned source (source_binding).
  • Spec 063: the implementation record gains increment 3.

Not in this PR: runtime.capture-replay with acquisition pages (capture::outputs in the conformance crate still passes no sources). It follows as a separate commit or PR.

Checks run locally: make gate; cargo build --workspace --locked; cargo test -p rustev-node -p rustev-conformance --locked; clippy on both with -D warnings; cargo fmt --all --check; the release addon, copy-addon.mjs and tsc --noEmit --strict on index.d.ts; node --test integrations/rustev-node/test/*.test.mjs; run.mjs native.

Review note (d5593f6): c6df666bc71e both references are right: spec 063 3.4.5 defines abandonedPending, and 3.11 is where the gauge and shutdown declare it ("abandonedPending (3.4.5)" in 3.11).

@github-actions

github-actions Bot commented Nov 6, 2026

Copy link
Copy Markdown

AI review (findings)

Reviewing the diff for the acquisition source seam (spec 063 increment 3).

Finding 1 — source.rs report(): cancel acknowledgment incorrect when signal raised and host answers without a cancel field

In report():

let cancel = match (raised, a.cancel.as_deref()) {
    (false, _) | (true, None) => CancelAck::NotRequested,

When raised=true and the host returns a page (or failure) without a cancel field, the result is CancelAck::NotRequested, which asserts that no cancellation was requested — contradicting raised=true. The same condition in the unknown() closure for rejections/exceptions correctly uses CancelAck::Unconfirmed. This is reachable: the runtime raises the abort signal and sends the advisory notification; the host's Promise resolves with a page concurrently, with no cancel field. The resulting record would misreport the attempt's cancellation state.

Finding 2 — index.js sourceSeam: inconsistent null-guard on charge

page:   answer?.page   == null      ? undefined : bytes(answer.page),
charge: answer?.charge === undefined ? undefined : JSON.stringify(answer.charge),

page uses == null (matches both null and undefined); charge uses === undefined (misses null). A host returning charge: null on a success response produces JSON.stringify(null) → the string "null", which Rust's serde_json::from_str::<Charge> cannot parse, causing report() to call unknown() and emit a permanent failure. While TypeScript typings mark charge as required (not ?), a JavaScript host can still pass null, making the inconsistency a concrete defect for untyped callers.

{"head": "0043718e320e69f7f60142cd6ca63cb3baa58f07", "verdict": "findings", "findings": [{"path": "integrations/rustev-node/src/source.rs", "line": 162, "severity": "medium", "category": "correctness", "summary": "In report(), the match arm (true, None) => CancelAck::NotRequested incorrectly claims cancellation was not requested when raised=true and the host answers without a cancel field; CancelAck::Unconfirmed is the correct acknowledgment for this reachable race."}, {"path": "integrations/rustev-node/index.js", "line": 275, "severity": "low", "category": "correctness", "summary": "In sourceSeam, the charge null-guard uses === undefined while page uses == null; a host passing charge: null on a success response is incorrectly treated as a permanent failure rather than a missing charge."}]}

Subject: 95c4a59...0043718, diff digest 7461ada31b7dbcedb8df702acfa8612249985c93230c2a3d6cb1f13550d4eb46, 1 call(s). An AI comment is not an approval.

@bartekus
bartekus temporarily deployed to statecraft-review-exception November 6, 2026 01:30 — with GitHub Actions Inactive
bartekus added a commit that referenced this pull request Nov 6, 2026
A page or SeamFailure with charge null crossed as the string "null";
it now crosses as absent, as page does (AI review on #519).
@bartekus

bartekus commented Nov 6, 2026

Copy link
Copy Markdown
Contributor Author

Review note: finding 2 (charge: null) is fixed in the latest commit: null now crosses as absent, as page does, and source.test.mjs covers it (permanent, charge unknown).

Finding 1 is a false positive. CancelAck::NotRequested for a settled answer with no cancel, after the signal was raised, is deliberate. The adapter does not assert "no cancellation was requested". The runtime reads it as "the host did not act on the cancellation":

  • In crates/rustev-runtime/src/acquisition.rs (the Raced::Done(Ok(report)) arm), when signal.is_raised():
    • A report whose cancel != NotRequested is taken as the host's cancellation answer. The attempt ends Cancelled and the page is discarded.
    • A report with NotRequested keeps the page and records Cancellation::Requested { answer: CancelAnswer::Unconfirmed }.
  • So the record already shows the cancellation as requested and unconfirmed. Returning Unconfirmed from the adapter would instead turn a page the host delivered into a cancelled attempt and drop it.
  • Spec 063 3.5.5 keeps a SeamFailure's cancel "only when the signal was raised". It says nothing that would make a page without one a cancellation answer.
  • The existing backend adapter (integrations/rustev-node/src/seams.rs, report) maps an absent cancel to NotRequested the same way.
  • The unknown() path differs on purpose: for a throw or rejection, 3.5.5 (after 027 3.6.5) requires cancellation unconfirmed if the signal was raised, and that report carries no page.

@github-actions

github-actions Bot commented Nov 6, 2026

Copy link
Copy Markdown

AI review (findings)

Review

integrations/rustev-node/src/callback.rs — counter accounting

The abandoned_pending accounting in Pending::drop and the spawned task is correct across all races (task settles before rx.close, between fetch_add and rx.close, or after rx.close). In every path exactly one decrement of abandoned_pending and one increment of late_resolutions_discarded occur when the promise settles after the slot is released. The self.rx = None in poll correctly prevents the drop path from firing for a normally-completed future.

integrations/rustev-node/src/source.rs — report() and cancel logic

Cancel computation before the failure/success branch means an unknown cancel class on what would have been a successful page yields permanent — consistent with the spec's requirement that malformed host answers are permanent. The (false, _) | (true, None) => CancelAck::NotRequested arm correctly ignores unsolicited cancel fields.

integrations/rustev-node/src/source.rs — misplaced use

use std::future::Future;   // line 256, end of file

This use statement appears at the bottom of the file, separated from all other imports. std::future::Future is needed in scope to call .poll(cx) on Pin<&mut Pending<R>> inside the poll_fn closure. Because make code runs clippy with -D warnings, if Rust determines this import is redundant (e.g., the trait already enters scope through another re-export), compilation would fail. If it is genuinely required, the placement is harmless but violates the project's import style and makes the dependency non-obvious to readers.

tools/rustev-conformance/src/acquire.rs:138 — request_id extraction

let request_id = serde_json::to_value(call.request_id)
    .ok()
    .and_then(|v| v.as_str().map(str::to_string))
    .unwrap_or_default();

integrations/rustev-node/src/source.rs:220 uses call.request_id.to_string() for the same field. If AcquisitionRequestId's Serialize and Display implementations agree (both emit the bare hash string), the two approaches produce identical results. If they diverge — e.g., if serde wraps the ID in a tagged enum variant — as_str() returns None and request_id silently becomes "". The page bytes the conformance tool and the Node binding would then produce for the same call would differ, breaking the byte-exact cross-runner comparison that is the purpose of these cases. The correct form for consistency is call.request_id.to_string().

index.js / index.d.ts / lib.rs — no issues found

The JS sourceSeam wrapper correctly bridges to HostSource::new, the abort path is wired through aborts(), and scriptedSource in run.mjs is correctly wrapped by sourceSeam before being passed to the native engine. The abandonedPending field in shutdown is computed by reducing over gauges().seams at the moment shutdown resolves, consistent with spec 063 3.4.6.

Conformance fixtures and spec text

The spec increment entry (specs/063-node-binding-parity/spec.md) accurately describes the implementation. Fixture plan JSONs match the definitions constructed in acquire_cases(). The Ignore sentinel correctly models a source that never answers, sharing the same not_observed outcome between both runners (the host's cancel answer arrives after the runtime has already polled once).


{"head": "5e6a223fb136a586d1c775036250361473af2724", "verdict": "findings", "findings": [{"path": "integrations/rustev-node/src/source.rs", "line": 256, "severity": "low", "category": "other", "summary": "use std::future::Future is placed at the end of the file rather than with the other imports; if clippy considers it redundant the build fails under -D warnings, and if required it is a non-obvious dependency."}, {"path": "tools/rustev-conformance/src/acquire.rs", "line": 138, "severity": "low", "category": "correctness", "summary": "request_id is extracted via serde_json roundtrip (serde_json::to_value then as_str) rather than to_string() as in source.rs; if AcquisitionRequestId's Serialize and Display representations differ, the scripted page bytes silently use an empty request field, breaking byte-exact cross-runner comparison."}]}

Subject: 95c4a59...5e6a223, diff digest 437f249d68b1e41fa0d3fbb3aab41e1e6065db9512a4e44908e7884521fba377, 1 call(s). An AI comment is not an approval.

@bartekus
bartekus temporarily deployed to statecraft-review-exception November 6, 2026 01:38 — with GitHub Actions Inactive
Base automatically changed from impl/063-sources to main November 6, 2026 01:52
bartekus added a commit that referenced this pull request Nov 6, 2026
A page or SeamFailure with charge null crossed as the string "null";
it now crosses as absent, as page does (AI review on #519).
@bartekus
bartekus force-pushed the impl/063-acquisition branch from 5e6a223 to 7ee17b8 Compare November 6, 2026 01:56
@github-actions

github-actions Bot commented Nov 6, 2026

Copy link
Copy Markdown

AI review (no-findings)

Reviewing the PR, which adds the acquisition source seam (spec 063 increment 3) to the Node.js binding.

callback.rs — abandoned-pending accounting

The Drop impl on Pending<R> increments abandoned_pending before calling rx.close(), then checks try_recv() to detect same-side receipt. The spawned task decrements when tx.send fails. All orderings (send-before-close, send-after-close, send-between-add-and-close) correctly resolve to abandoned_pending = 0, lateResolutionsDiscarded = 1. Logic is sound.

source.rs — report cancel handling

For explicit SeamFailure with no cancel field when the abort signal is raised, the code returns CancelAck::NotRequested (via (false, _) | (true, None) => CancelAck::NotRequested). The unknown closure uses Unconfirmed for the same raised-but-no-response case. The distinction is intentional: a typed SeamFailure is an explicit answer (host chose not to acknowledge); an unexpected error is treated as unconfirmed. This matches the doc comment's scope ("malformed answer, throw or rejection") and is consistent with the spec.

source.rs — MAX_PAGE + 1 copy

page[..page.len().min(MAX_PAGE + 1)].to_vec() copies one extra byte for oversized pages so the core's bounded parser can reject them as invalid_page without further data crossing. Correct.

acquire.rs — Ignore case

std::future::pending().await never resolves; the runtime drops the future at the deadline, producing not_observed from the runtime's own timeout path, not from report. Both runners emit identical bytes. Matches the expected fixture and the spec note.

callback.rs — waker registration in poll_fn

After aborted = true, signal.poll_raised(cx) is skipped, but Pin::new(&mut pending).poll(cx) still registers a waker for the oneshot channel. The future is correctly re-woken when the channel settles. No missed wakeup.

scriptedSource in run.mjs — abort not in returned object

scriptedSource returns { descriptor, maxConcurrency, queueCapacity, acquire } with no abort. The abort function is added by sourceSeam via calls = aborts(). Correct — abort is an internal binding detail not exposed in AcquisitionSource.

cancel match for success path with raised signal

When the host returns a page after the abort signal is raised, a.cancel is None (never set for pages in the JS layer), yielding CancelAck::NotRequested. The acquisition succeeded and the page is used; NotRequested is appropriate because the cancellation didn't stop the host.

Conformance fixtures and sorted JSON parity

page_bytes in acquire.rs and sorted in run.mjs produce the same key-sorted, whitespace-free JSON. Both use the same schema, field names, and value representations. ✓

No concrete bugs, security problems, or authority/ratification changes found.

{"head": "7ee17b81b21632b8c4ef2f5cd4b7a82de519440c", "verdict": "no-findings", "findings": []}

Subject: 773d72f...7ee17b8, diff digest 437f249d68b1e41fa0d3fbb3aab41e1e6065db9512a4e44908e7884521fba377, 1 call(s). An AI comment is not an approval.

@bartekus
bartekus added this pull request to the merge queue Nov 6, 2026
@github-merge-queue
github-merge-queue Bot removed this pull request from the merge queue due to a conflict with the base branch Nov 6, 2026
@bartekus

bartekus commented Nov 6, 2026

Copy link
Copy Markdown
Contributor Author

M1: #519 was removed from the merge queue at 02:38 (merge_conflict) and is not armed. It is clean against main now, but it conflicts with #520 (063 increment 2, first in the queue) on the 063 shards (.statecraft/derived/*/by-spec/063-node-binding-parity.json), and likely on the Implementation record too. Once #520 merges, please rebase onto main: keep both record paragraphs in increment order, take main's shards, run make refresh, then make gate && git commit, and push. I re-arm when the new head is clean and green. Also: PR runs check only part of the acceptance suite, so please run .bin/spec-spine verify 063 and 027 locally before pushing (#522 failed in the queue on acceptance its PR run never ran).

@bartekus

bartekus commented Nov 6, 2026

Copy link
Copy Markdown
Contributor Author

M1: heads-up. The 031 3.8 npm declaration check (release-checks / semver, run in the merge queue) classes any new required member on an exported class or interface (e.g. a new Engine method) as breaking. That passes only at the breaking position, so it needs the family at 0.5.0. #520 failed the queue on this. I am landing the 0.5.0 version bump ahead of the freeze; Node PRs that add required members land after it. Optional members are compatible.

@bartekus

bartekus commented Nov 6, 2026

Copy link
Copy Markdown
Contributor Author

M5: I ran the 031 3.8 npm declaration diff (npm-api-diff.mjs against the published 0.4.1) locally. Two findings in the M5 stack are classed breaking, so both land after the 0.5.0 bump:

Everything else is compatible: the new interfaces, EngineOptions.acquisitionSources and store, compile sources, and shutdown's abandonedPending (an added output field). #525 and #526 change no declaration.

Once #520 and the bump are on main, I will rebase #519 and restack #524 to #526. For each: keep the record paragraphs in increment order, take main's shards, run make refresh, re-bless the conformance fixtures for the new PlanIds, run spec-spine verify 063 and 027 locally, then make gate && git commit and push. verify 027 passes on #519's current head; verify 063 declares no commands yet.

@bartekus

bartekus commented Nov 6, 2026

Copy link
Copy Markdown
Contributor Author

M1: #519 also adds required npm surface: Engine.shutdown(...) and a wider failureClass union, an output widened. The 031 3.8 npm check classes both as breaking, so #519 lands after the 0.5.0 version bump (owner-approved, in progress). After the bump merges, rebase onto main (re-bless any PlanId-bearing fixture at 0.5.0 through the bless paths, take main's 063 shards, make refresh), run .bin/spec-spine verify 063 and 027 locally, then push. I re-arm when it is clean and green.

@bartekus

bartekus commented Nov 6, 2026

Copy link
Copy Markdown
Contributor Author

M1: the 0.5.0 version bump has merged (4503383, #528), so every PlanId changed. #519 can land now. Please rebase onto main and re-bless any PlanId-bearing fixture through the bless paths (no hand-merged hashes). Take main's 063 shards, then make refresh. Run .bin/spec-spine verify 063 and 027 locally, then make gate && git commit, and push. I re-arm as soon as the new head is clean and green. Then restack #524, #525 and #526 the same way.

bartekus added a commit that referenced this pull request Nov 6, 2026
A page or SeamFailure with charge null crossed as the string "null";
it now crosses as absent, as page does (AI review on #519).
@bartekus
bartekus force-pushed the impl/063-acquisition branch from 7ee17b8 to 3659cfb Compare November 6, 2026 08:00
@github-actions

github-actions Bot commented Nov 6, 2026

Copy link
Copy Markdown

AI review (findings)

Reviewing the diff for correctness, security, and consistency. The changes implement spec 063 increment 3 — the full acquisition source seam for the Node binding, including asynchronous host callbacks, gauges, and conformance cases.

Areas examined

callback.rs — Pending/Drop atomic accounting: The fetch_add→rx.close()→try_recv sequence in Drop is sequentially consistent with the spawned task's tx.send→fetch_sub path. The two paths are mutually exclusive (if tx.send fails there is nothing to try_recv, and vice versa), so the counter stays correct. No race.

source.rs — report function: Found one concrete defect.

let cancel = match (raised, a.cancel.as_deref()) {
    (false, _) | (true, None) => CancelAck::NotRequested,   // ← (true, None) arm
    (true, Some("stopped")) => CancelAck::Stopped,
    (true, Some("unconfirmed")) => CancelAck::Unconfirmed,
    ...
};

When raised = true and the host threw a SeamFailure with no cancel field, this arm emits NotRequested — meaning "cancellation was never requested" — which is factually wrong when the abort signal has fired. The unknown closure just above handles the analogous non-SeamFailure case correctly:

let unknown = |detail: String| AcquireReport {
    cancel: if raised { CancelAck::Unconfirmed } else { CancelAck::NotRequested },
    ...
};

A concrete input that triggers this: the abort signal fires (window expiry or decision cancellation), and the host's acquire subsequently throws SeamFailure({ failureClass: 'denied', … }) with no cancel field. The resulting AcquireReport records not_requested instead of unconfirmed, misrepresenting whether the host acknowledged the cancellation. The test suite does not exercise this combination.

callback.rs — Pending::poll panic guard: The expect("a host call is not polled after it settles") is safe because poll_fn exits as soon as the closure returns Ready, so Pending is never polled twice.

source.rs — use std::future::Future at file bottom: This import is needed for the .poll(cx) call in acquire (calling the Future trait method on a pinned Pending). Module-level use items have file-wide scope in Rust, so placement is correct even if unusual.

acquire.rs / run.mjs — page serialisation alignment: page_bytes (Rust) and sorted (JS) both produce recursively key-sorted, whitespace-free JSON with identical primitive rendering. The two runners will produce byte-identical pages. ✓

Security: All host-supplied bytes cross through bounded parsers (SourceDescriptor::parse, canonical(), the core's page validator). No injection path found.

{"head": "3659cfb3396513b03b0599bfebad53731cdcd3b3", "verdict": "findings", "findings": [{"path": "integrations/rustev-node/src/source.rs", "line": null, "severity": "medium", "category": "correctness", "summary": "In `report`, the arm `(true, None) => CancelAck::NotRequested` fires when the abort signal was raised but the host threw a SeamFailure with no `cancel` field; it should produce `CancelAck::Unconfirmed` (consistent with the `unknown` closure and with 027 3.6.5), because `NotRequested` asserts the signal was never raised, which is false."}]}

Subject: 4503383...3659cfb, diff digest ca2fc5b29b18a1b67fc06c76c96c1f1f1a824d6903f3ea3bff409072b3a2367f, 1 call(s). An AI comment is not an approval.

@bartekus
bartekus had a problem deploying to statecraft-review-exception November 6, 2026 08:07 — with GitHub Actions Error
@bartekus

bartekus commented Nov 6, 2026

Copy link
Copy Markdown
Contributor Author

M5: rebased onto main at 4503383 (0.5.0). The rebase was clean; one new commit re-blesses the acquisition fixtures through the bless paths. Locally: make code, make gate, node tests 74 pass, run.mjs native 199 cases 0 failures, spec-spine verify 027 passed, verify 063 declares no commands. #524, #525 and #526 are restacked on it, each re-blessed at 0.5.0. #520 is still open; if it merges first I will rebase again.

@bartekus

bartekus commented Nov 6, 2026

Copy link
Copy Markdown
Contributor Author

Review note: finding 51931ad47fdb on 3659cfb is the same false positive answered at 01:32 (the rebase only moved the base and re-blessed fixtures; report in source.rs is unchanged). CancelAck::NotRequested after a raised signal means "the host did not act on the cancellation", which is how crates/rustev-runtime/src/acquisition.rs reads it in the Raced::Done(Ok(report)) arm; Unconfirmed is reserved for a rejected or malformed answer, where Rustev cannot know what the host did. The finding is medium and correctness, so it needs the owner exception rather than a body note.

bartekus added a commit that referenced this pull request Nov 6, 2026
A page or SeamFailure with charge null crossed as the string "null";
it now crosses as absent, as page does (AI review on #519).
@bartekus
bartekus force-pushed the impl/063-acquisition branch from 3659cfb to fc0df79 Compare November 6, 2026 09:02
@github-actions

github-actions Bot commented Nov 6, 2026

Copy link
Copy Markdown

AI review (findings)

Reviewing the acquisition source seam (spec 063 increment 3) added in this PR across the Node binding, the conformance tool, and their tests.

callback.rs — Pending<R> drop/abandoned-pending accounting

The drop handler increments abandoned_pending, closes rx, then checks try_recv. The three-way interleaving with the spawned task is covered: (a) task already sent before close() → try_recv succeeds and immediately corrects the count; (b) task sends after close() → tx.send fails and the task corrects the count; (c) task not yet spawned / runtime cancelled → abandoned_pending stays at 1 until shutdown clears it. No double-counting defect.

source.rs — cancel ack for a successful page when the signal is raised

report() resolves (raised=true, cancel=None) to CancelAck::NotRequested. AcquireAnswer carries no cancel field, so a page response always lands here. The ScriptedSource in the conformance tool resolves the same situation to Unconfirmed. Both choices are consistent within their own code-paths, and the conformance cases that touch window expiry all use ignore (never-settling), so no test exercises this branch. This is a design choice rather than a contradiction visible in the supplied evidence.

source.rs — trailing unused import

The file ends with:

use std::future::Future;

placed after all impl blocks. std::future::poll_fn is used fully-qualified; Box::pin(async move { … }) coerces to BoxFuture without the trait in scope; and nothing in the napi macro expansions on this file's types requires it. This import is unused. AGENTS.md specifies make code runs clippy -D warnings; an unused import is a dead_code/unused_imports lint that -D warnings promotes to a hard error, so this will break CI.

Security — page content, charges, requests

Pages are truncated to MAX_PAGE + 1 before the core's bounded parser sees them (intentional detection without full copy). Charges cross as opaque JSON parsed with .ok() so malformed values become Charge::Unknown. Requests are canonicalized before dispatch; a non-canonical request is a permanent local failure. No injection surface identified.

Conformance fixtures — deterministic bytes

Both the Rust write_sorted and the JS sorted function produce the same key-sorted, whitespace-free JSON for page bytes. The ignore conformance answer correctly produces not_observed on both runners (the host promise cannot settle synchronously when polled once). No byte-identity defect visible in the supplied evidence.

{"head": "fc0df799fb679da2f2df2897b75a1e81f696b12a", "verdict": "findings", "findings": [{"path": "integrations/rustev-node/src/source.rs", "line": null, "severity": "medium", "category": "correctness", "summary": "Trailing `use std::future::Future;` at the end of the file is unused and will fail `clippy -D warnings` enforced by `make code` and CI."}]}

Subject: b3bcc5f...fc0df79, diff digest 6add061d425696c94aa917832dce9c886c094b2121e0581fab630b71a750066a, 1 call(s). An AI comment is not an approval.

@bartekus
bartekus had a problem deploying to statecraft-review-exception November 6, 2026 09:09 — with GitHub Actions Error
@bartekus

bartekus commented Nov 6, 2026

Copy link
Copy Markdown
Contributor Author

M5: rebased onto main at b3bcc5f (#520 merged). The 063 shards conflicted; I took main's and ran make refresh. The record reads increments 1, 2, 3a, 3 in order. #520's profiled compile builds a PlanHandle without the sources field this PR adds, so fc0df79 returns the parsed sources from profile::compile and keeps them on the handle (two additive lines each in profile.rs and lib.rs); without it the crate does not build. Re-bless found nothing new. Locally: make code, make gate, node tests 81 pass, run.mjs native 222 cases 0 failures, verify 027 passed. #524 to #526 are restacked.

@bartekus

bartekus commented Nov 6, 2026

Copy link
Copy Markdown
Contributor Author

Review note: finding ada4adbbcf33 on fc0df79 is fixed in 9eafcaf: the trailing use std::future::Future; in source.rs is gone. It was redundant (edition 2024 has Future in the prelude) rather than a clippy failure; make code passed with it. #524 to #526 are restacked on 9eafcaf.

@github-actions

github-actions Bot commented Nov 6, 2026

Copy link
Copy Markdown

AI review (no-findings)

Reviewing the diff carefully for the acquisition source seam (spec 063, increment 3).

Callback infrastructure (callback.rs)

The abandoned/late-resolution counting in Pending::drop is correct. The three scenarios — settled before rx.close(), settled between fetch_add and rx.close(), and settled after rx.close() — are mutually exclusive in whether try_recv succeeds and whether the spawned task sees tx.send fail, so no double-decrement is possible. The comment "always finds the count to take back" is slightly imprecise but the logic holds.

Seam implementation (source.rs)

  • report's cancel matching: (false, _) | (true, None) => NotRequested correctly collapses both "signal not raised" and "host returned a page without a cancel field" into NotRequested. For failures via SeamFailure, the JS catch block does include e.cancel ?? undefined, so None on a failure correctly means the host didn't see it.
  • MAX_PAGE = SNAPSHOT_V1.max_bytes is cited to spec 3.5.4 as the page's parse class limit; the page[..page.len().min(MAX_PAGE + 1)].to_vec() trick correctly passes one extra byte so the core's bounded parser rejects oversized pages as invalid_page without copying the rest.
  • Queue-full returns Overloaded with Charge::Observed { units: 0 } immediately — consistent with the test expectation and spec 3.5.6.
  • The poll_fn loop inside acquire checks signal.poll_raised and sends the advisory abort via ThreadsafeFunctionCallMode::NonBlocking; the outer future is dropped later (triggering Pending::drop), which correctly records the abandoned state.

JavaScript layer (index.js, index.d.ts)

  • sourceSeam correctly wraps the user's AcquisitionSource and adds abort internally via aborts(); the TypeScript interface does not expose abort to the user, which is correct.
  • JSON.stringify(answer.charge) is applied to the host-supplied object, not a pre-serialised string; bytes(answer.page) receives a DocumentInput, which bytes() converts to Uint8Array.
  • shutdown reads abandonedPending from gauges after shutdownTelemetry; since spawned tasks may still be running, the count has an inherent race, but reading it at this point (after drain) is the best available approximation and is consistent with the spec.

Conformance runner (acquire.rs, run.mjs, tests/runtime.rs)

  • scriptedSource in run.mjs correctly produces sorted-key page bytes via sorted(), matching the Rust page_bytes() function's key-sorted output.
  • The Ignore case (std::future::pending().await) hangs until the outer future is dropped by the runtime, consistent with the spec note that a host's cancellation answer crosses threads and cannot be ready when the runtime polls once — explaining why runtime.acquire-window records not_observed on both runners.
  • acquire_mirrors assertions align with the expected JSON files for all four cases.

Spec edit (specs/063-node-binding-parity/spec.md)

The added increment note is implementation documentation only; it makes no lifecycle claim. The spec's status and implementation field are not changed.

No defects found.

{"head": "9eafcaf157c669ff7ff555eb17d50a1cddc70be7", "verdict": "no-findings", "findings": []}

Subject: b3bcc5f...9eafcaf, diff digest e8286e91a29786fadda88f604a778767a40ab460ae4d8e3266ba8ff483b67940, 1 call(s). An AI comment is not an approval.

acquisitionSources install host sources on the runtime (063 3.5); each
attempt is an asynchronous host callback (3.4, src/callback.rs) whose
queue slot is released when the runtime stops waiting, with unsettled
Promises counted in abandonedPending and late settlements discarded.
denied, cost bounds from the descriptor, the 4 MiB page copy, gauges and
shutdown's abandonedPending. Capture assembly receives the plan handle's
sources. Scripted sources in both conformance runners and the four
runtime.acquire-* cases; host-seam tests in test/source.test.mjs.
A page or SeamFailure with charge null crossed as the string "null";
it now crosses as absent, as page does (AI review on #519).
@bartekus
bartekus force-pushed the impl/063-acquisition branch from 9eafcaf to d5593f6 Compare November 6, 2026 09:31
@bartekus

bartekus commented Nov 6, 2026

Copy link
Copy Markdown
Contributor Author

M5: governance refused 8774974, df9ca4d and 16b235e: each carried main's 063 shards at its own tree after the rebase onto #520. I rebuilt the branch with make refresh and make gate run at every commit, so each commit's tree passes the gate; the final tree is byte-identical to 9eafcaf. #524 to #526 are rebuilt the same way.

@github-actions

github-actions Bot commented Nov 6, 2026

Copy link
Copy Markdown

AI review (findings)

Reviewing the diff for bugs, security problems, and inconsistencies against the governance context.

Code review

callback.rs — counter accounting in Pending::drop

The abandoned_pending counter is incremented before rx.close() and the spawned task decrements it on tx.send(r).is_err(). Both paths (item already in channel at try_recv, or task sees the closed receiver) decrement exactly once. The logic is sound and matches the comment.

source.rs — report function: cancel for SeamFailure with raised signal

let cancel = match (raised, a.cancel.as_deref()) {
    (false, _) | (true, None) => CancelAck::NotRequested,  // both arms merged
    ...
};

The unknown closure (for unexpected exceptions) correctly sets Unconfirmed when raised. For a named SeamFailure class (transient, overloaded, permanent, denied) thrown when the abort advisory was already sent but no cancel field is present, the code returns NotRequested. This is inconsistent with the unknown path, but is arguably intentional: a SeamFailure without cancel signals the host failed for independent reasons, not in response to cancellation. The existing tests don't exercise raised=true with a named SeamFailure, so this edge case is not validated by any conformance case.

callback.rs — call_async_catch availability

call_async_catch is called on the napi ThreadsafeFunction. This method is not in napi's public API documentation visible from the diff; if it is an internal or unstable method, it could break on napi version updates. The diff gives no evidence the method does not exist, however.

index.d.ts vs seams.rs — section reference mismatch

index.d.ts line 400 cites spec 063 §3.11 for abandonedPending in seams gauges; seams.rs cites §3.4.5 for the same field. One of these is wrong.

acquire.rs conformance — SourceAnswer::Ignore and CancelAck

The Ignore arm does std::future::pending().await, so the runtime drops the future and the AcquireReport block below the match is unreachable. The cancel logic there is dead code for that arm. This is harmless but could confuse a reader.

index.js sourceSeam — bytes on non-DocumentInput in ignore late settlement

The late resolution for ignore resolves with { page: 'late', ... }. The bytes('late') call converts the string 'late' to its UTF-8 bytes. Because this is a late resolution (the receiver was already dropped), the tx.send fails and the content is never validated—this is correct and harmless.

General assessment

The core concurrency invariants (slot release on drop, abandoned/late counter handoff between Pending::drop and the spawned task, abort advisory wiring) are correct. The page-size truncation (MAX_PAGE + 1) correctly passes one byte over the limit to the core parser. The scripted-source canonical JSON (sorted keys, no whitespace) is consistent between Rust (write_sorted) and JavaScript (sorted). The ignore conformance case documents and correctly implements the "both runners record not_observed" invariant.

{"head": "d5593f66e4a56196ba55d059f254bb8b032e8d47", "verdict": "findings", "findings": [{"path": "integrations/rustev-node/index.d.ts", "line": 400, "severity": "low", "category": "other", "summary": "abandonedPending is cited as spec 063 §3.11 here but as §3.4.5 in seams.rs; one reference is wrong."}]}

Subject: b3bcc5f...d5593f6, diff digest e8286e91a29786fadda88f604a778767a40ab460ae4d8e3266ba8ff483b67940, 1 call(s). An AI comment is not an approval.

@bartekus
bartekus had a problem deploying to statecraft-review-exception November 6, 2026 09:41 — with GitHub Actions Error
@bartekus

bartekus commented Nov 6, 2026

Copy link
Copy Markdown
Contributor Author

M5: #519 is clean and green at d5593f6 (ci-gate pass; the one AI finding is low and other, answered by a body review note, so review-exception skipped). Ready for you to re-arm. #524 to #526 stay stacked on it; #524's remaining AI finding (traceparent, medium) needs the owner exception.

@bartekus
bartekus added this pull request to the merge queue Nov 6, 2026
Merged via the queue into main with commit df67bc5 Nov 6, 2026
48 of 50 checks passed
@bartekus
bartekus deleted the impl/063-acquisition branch November 6, 2026 10:59

This branch was successfully deployed

No deployments
statecraft-review-exception — d5593f66 Deployed Nov 6, 2026 by bartekus via review-exception #3550
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

m5 Opened by the M5 worker; M1 arms

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant