Skip to content

impl(027): increment 4, the runtime conformance cases - #134

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

bartekus merged 1 commit into
mainfrom
impl/027-runtime-cases

Conversation

@bartekus

@bartekus bartekus commented Oct 20, 2026 •

Copy link
Copy Markdown
Contributor

Spec 027, increment 4 (second change): the runtime conformance cases. Stacked on #129, split from it because its AI review was cancelled at the 15-minute limit twice.

  • Runtime cases as data (3.12.4) under tools/rustev-conformance/cases/runtime/, each naming the test under crates/rustev-runtime/tests it mirrors: a full admission queue, retries drawing from a hard budget, transient retries with exponential delays, attempts in flight at the deadline, and cancellation.
  • A case declares its plan, descriptors and calibrations (fixtures from spec 002's shared builders, fixtures/runtime/), the runtime bounds, a scripted backend per registration, the requests, and the driver's steps on a manual clock.
  • The Rust runner (rustev_conformance::runtime) interprets a case with Rust seams; each request's result and run-record bytes are committed under expected/runtime/ and compared without normalization. tests/runtime.rs checks every expected record against what its mirrored test asserts, so a blessed record is never merely what the runner printed.
  • The manifest aggregates cases/cli and cases/runtime (34 cases).

Review round 1 (3 findings): (1) By design, and the code says so: a backend that ignores cancellation never answers; the runtime polls a cancelled attempt once (spec 003, 3.7.3), records not_observed and drops the attempt, so the decision ends without the pending future. (2) fixed: the deadline case waits for the runtime's timer (wait_sleeper) before advancing the clock, whenever the runtime arms it; its expected record is unchanged. (3) fixed: a release_all that frees no gate fails the case naming the backend, instead of surfacing later as a mismatch. Rebased on main after #129 merged.

Review round 2 (2 findings, fixed): (1) the budget case finds the topic request by its step, as the retry case does, never by position in the record. (2) a projection that names no task stops the run with a message naming the attempt and the projection, instead of falling through to an unexplained permanent failure; the redundant max(1) is gone.

Review round 3 (1 finding, fixed): an answer delivered by a released gate after cancellation was raised still stands, and its report now says the backend did not act on the cancellation (unconfirmed) instead of not_requested. No committed case releases and cancels the same gate, so every expected record is unchanged.

Review round 4 (3 findings): (1) Not so: json! serializes each element through a reference (to_value(&expr)), so json!([blip, blip]) compiles and does not move blip; the crate builds and its tests pass. (2) fixed: release_all counts only answers a waiting attempt receives, so a release that reaches no one fails the case. (3) By design, and now documented at release_all: a cancelled attempt leaves the gates whatever its backend does next, so a release after the cancellation finds nothing and the script is told so; no committed case releases after cancelling.

@github-actions

Copy link
Copy Markdown

AI review (no-findings)

Reading through the diff, I examined the new runtime conformance infrastructure, the scripted backend logic, the driver loop, and the case/expected data for consistency.

Key observations:

  1. src/runtime.rs answer method (line ~230): n.clamp(1, l.len()) - 1 correctly maps attempt-1 → index 0, attempt-n-beyond-end → last index. The caller always passes n.max(1), making the lower-clamp branch dead but harmless.

  2. OnCancel::Ignore path and pending(): The comment explains the runtime polls the future once after signalling cancellation, gets Poll::Pending, records not_observed, and drops the future. This matches the possibly_continuing/not_observed values in the deadline expected record, which correctly diverge from the backend's "remote": "finished" setting.

  3. Gate removal before pending(): In the cancel-signal path, s.gates.lock().unwrap().remove(&id) fires before std::future::pending().await, so a subsequent release_all doesn't try to send to a disconnected channel. Correct.

  4. until spin-loop: 100,000 yield_now iterations with a 30-second tokio::time::timeout safety valve on each spawned task — acceptable for a deterministic single-threaded test harness.

  5. Fixture/manifest sha256 consistency: Every file referenced in multiple cases carries the same hash (e.g., support.snapshot.json = 8009ccb4... everywhere). Cross-case consistency holds.

  6. Retry timing in expected record: dispatched_ms values [0, 10, 30] match the exponential delay (initial=10, second=20) declared in retry.plan.json. ✓

  7. Budget exhaustion arithmetic: 2 failed topic attempts × 4 units = 8 observed; remaining 2 < next reservation of 4; frustration and explicit_deadline never dispatched. Matches "observed":8 and 0-attempt entries in the record. ✓

  8. Admission queue logic: max_in_flight=1, max_queued=1 → d1 in-flight, d2 queued, d3 overloaded with no record. Drive sequence correctly serialises the three starts around the gate/queue waits. ✓

  9. serde_json::json! macro and the double-blip usage in tests (~line 310 of tests/runtime.rs): json! takes references via to_value(&expr), so using the same local Value variable twice does not cause a move error.

No bugs or security issues found.

{"head": "8ad51a0368023dbbe0f6b438a7873d9df88cfdf2", "verdict": "no-findings", "findings": []}

Subject: f6e9940...8ad51a0, diff digest 1ac60c0361c6ecc13f2adcf86d5aed6750b2cce0cdacaf8b0cea6f83094b6554, 1 call(s). An AI comment is not an approval.

@bartekus
bartekus force-pushed the impl/027-conformance branch from f6e9940 to bb605b5 Compare October 20, 2026 23:27
@bartekus
bartekus force-pushed the impl/027-runtime-cases branch from 8ad51a0 to 752fd43 Compare October 20, 2026 23:28
@github-actions

Copy link
Copy Markdown

AI review (no-findings)

{"head": "752fd433d4846577a9e63a94a045184613fd0fb4", "verdict": "no-findings", "findings": []}

Subject: bb605b5...752fd43, diff digest 2b3de448f2b6c04dad97977c704095f1def2c379f488fb8eb6dce53b6eb07979, 1 call(s). An AI comment is not an approval.

@bartekus
bartekus force-pushed the impl/027-conformance branch from bb605b5 to 7eed80e Compare October 20, 2026 23:40
@bartekus
bartekus force-pushed the impl/027-runtime-cases branch from 752fd43 to fdb1060 Compare October 20, 2026 23:40
@github-actions

Copy link
Copy Markdown

AI review (no-findings)

Reviewing this PR, which adds runtime conformance cases (admission, budget, retry, deadline, cancel) as data-driven tests with a scripted backend seam and a manual clock.

tools/rustev-conformance/src/runtime.rs

  • answer method (lines ~232-245): n.clamp(1, l.len()) - 1 correctly converts 1-indexed attempt numbers to 0-indexed array positions. The guard !l.is_empty() prevents the clamp(1, 0) panic. The "repeating last answer" semantics are correct.
  • Gate handling: The poll_fn inside the gate arm correctly races the oneshot receiver against the cancel signal. The OnCancel::Ignore => std::future::pending().await correctly represents a non-acknowledging backend; the runtime drops the future when it abandons the attempt at the deadline, so no permanent task leak occurs since tokio.block_on eventually drops the runtime.
  • release_all: Uses std::mem::take on the lock guard, then sends outside the lock — correct, avoids holding the lock while potentially blocking on the oneshot send.
  • Non-gate immediate answers always report CancelAck::NotRequested without checking the signal. This is correct: if the attempt completed before the signal was raised, NotRequested is the accurate report.

tools/rustev-conformance/tests/runtime.rs

  • until loop (100,000 yields): appropriate for a single-threaded Tokio runtime where yield_now cooperatively schedules other tasks.
  • blip used twice in json!([blip, blip, ...]): serde_json's json! macro serializes non-literal expressions via to_value(&expr), borrowing rather than moving, so this compiles and correctly deep-copies the value.
  • Index signals[i] where i = running.len(): valid since signals are allocated one-per-request in the same order as requests, and starts happen in request order.

Consistency checks

  • cases/runtime/*.json ↔ entries in cases/manifest.json: both contain identical runtime blocks. The aggregate() function in lib.rs now includes "runtime" in the directory list, so the manifest will include these. ✓
  • Expected outputs (d3.result.json = rejected/overloaded, no d3.record.json): consistent with max_in_flight=1, max_queued=1 — d3 is rejected immediately when both slots are occupied. ✓
  • Deadline case: backend "remote": "finished" describes completed attempts; deadline-abandoned gated attempts are recorded by the runtime with "remote": "possibly_continuing", matching the expected output. ✓
  • Retry delays (0, 10, 30 ms): matches Delay::Exponential { initial_ms: 10, max_ms: 40 } with two transient failures. ✓

No bugs or security issues found.

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

Subject: 7eed80e...fdb1060, diff digest 2b3de448f2b6c04dad97977c704095f1def2c379f488fb8eb6dce53b6eb07979, 1 call(s). An AI comment is not an approval.

@bartekus
bartekus force-pushed the impl/027-conformance branch from 7eed80e to 7c9d25b Compare October 20, 2026 23:50
@bartekus
bartekus force-pushed the impl/027-runtime-cases branch from fdb1060 to f054fda Compare October 20, 2026 23:50
@github-actions

Copy link
Copy Markdown

AI review (findings)

Reviewing the runtime conformance infrastructure added in this PR: new case files, expected outputs, fixtures, src/runtime.rs, and tests/runtime.rs.

OnCancel::Ignore hangs indefinitely

src/runtime.rs:222:

OnCancel::Ignore => std::future::pending().await,

When a gated attempt receives the cancel signal and on_cancel is Ignore, this arm produces a future that never resolves. The comment says the runtime polls it once and moves on (spec 003 §3.7.3), but the future isn't aborted — it leaks unless the runtime explicitly drops the spawned task's resources when the decision finishes. For Rust this is fine if decide drives the future and then drops it on completion, but a binding's runner that tokio::spawns the infer future without cancelling the handle would hang permanently. This is a correctness dependency on a non-obvious invariant that isn't enforced by the type system and will silently break naive binding implementations.

deadline drive lacks wait_sleeper before advance_ms

cases/runtime/runtime.deadline.json (and the mirrored entry in manifest.json):

"drive": ["start", {"wait_gated": {"backend": 0, "count": 3}}, {"advance_ms": {"ms": 2000}}]

The retry case correctly uses wait_sleeper before each advance_ms to ensure the delay timer is registered before the clock moves. The deadline case omits this for the 2000 ms wall-clock deadline. If the runtime registers the deadline timer after beginning backend dispatch rather than at decision start, this is a race. The committed expected outputs suggest it works today, but there is no wait_sleeper guard to enforce the ordering.

release_all return value is declared but silently discarded

src/runtime.rs:204 — release_all returns usize (the count of released gates), but every call site at line ~455 discards it with no assertion. If the expected gate count isn't checked, a script error (wrong backend index, premature release) would go undetected until the downstream wait_gated times out with a confusing message.

No other significant issues. SHA256s in the manifest are internally consistent with the fixture files added, the until-loop busy-wait is bounded by 100 000 yields plus a 30-second hard timeout, the mutex is never held across an await point, Arc cloning and variable shadowing in the Start match arm are correct.

{"head": "f054fda1983d276298977c99d161dbafd241d9aa", "verdict": "findings", "findings": [{"path": "tools/rustev-conformance/src/runtime.rs", "line": 222, "summary": "OnCancel::Ignore branches on std::future::pending() which never resolves; the future leaks unless the runtime explicitly drops it on decision completion, silently breaking any binding runner that spawns it without cancelling the handle."}, {"path": "tools/rustev-conformance/cases/runtime/runtime.deadline.json", "line": null, "summary": "The deadline drive script advances the clock by 2000 ms without a preceding wait_sleeper step, unlike the retry case; if the runtime registers its deadline timer after backend dispatch begins rather than at decision start this is a race condition."}, {"path": "tools/rustev-conformance/src/runtime.rs", "line": 204, "summary": "release_all returns the count of gates released but every call site discards the value, so a misconfigured script (wrong backend index or premature release) fails silently rather than being caught early."}]}

Subject: 7c9d25b...f054fda, diff digest 2b3de448f2b6c04dad97977c704095f1def2c379f488fb8eb6dce53b6eb07979, 1 call(s). An AI comment is not an approval.

@bartekus
bartekus had a problem deploying to statecraft-review-exception October 20, 2026 23:56 — with GitHub Actions Error
Base automatically changed from impl/027-conformance to main October 21, 2026 00:07
@bartekus
bartekus force-pushed the impl/027-runtime-cases branch from f054fda to 707f974 Compare October 21, 2026 00:18
@bartekus
bartekus enabled auto-merge (squash) October 21, 2026 00:18
@bartekus
bartekus force-pushed the impl/027-runtime-cases branch from 707f974 to ccc5547 Compare October 21, 2026 00:36
@github-actions

Copy link
Copy Markdown

AI review (findings)

Reviewing the PR, which adds runtime conformance cases (admission, budget, retry, deadline, cancel) under tools/rustev-conformance, with a new src/runtime.rs Rust runner and matching test harness.

1. Order-dependent index in mirrors for budget case

tools/rustev-conformance/tests/runtime.rs — mirrors function, budget branch:

let topic = &r.requests[0];
assert_eq!(topic.attempts.len(), 2, "...");

This hard-codes request index 0 as "topic" without a name guard. The retry case correctly uses .iter().find(|q| q.step == "topic"). If the runtime ever changes the order of entries in RunRecord::requests, this assertion silently checks the wrong step, giving a false pass. The inconsistency is latent but real.

2. Silent task-name fallback in infer

tools/rustev-conformance/src/runtime.rs, infer method:

let task = serde_json::from_slice::<Json>(call.projection).unwrap_or(Json::Null)["task"]
    .as_str()
    .unwrap_or_default()
    .to_string();

If call.projection is not parseable as JSON, or does not contain a "task" string field, task silently becomes "". self.answer("", n) then finds no scripted entry and returns a permanent failure with no indication of the root cause. A misconfigured projection key would appear only as an unexpected permanent failure downstream, making the test hard to debug.

3. Minor: redundant n.max(1) in infer

tools/rustev-conformance/src/runtime.rs:

let n = id.rsplit('/').next().and_then(|x| x.parse().ok()).unwrap_or(1usize);
let first = s.answer(&task, n.max(1));

unwrap_or(1) already guarantees n >= 1, so .max(1) is redundant. answer also re-applies clamp(1, l.len()). Neither causes incorrect behavior.

No security issues found. The SHA256 fixture pinning, #![forbid(unsafe_code)], and deny_unknown_fields guards are all in place. The until busy-wait is bounded at 100,000 yields which is sufficient for a single-threaded executor with a manual clock.

{"head": "ccc5547e4696e5270a8fd0e1e93d46ac8c9355eb", "verdict": "findings", "findings": [{"path": "tools/rustev-conformance/tests/runtime.rs", "line": null, "summary": "In the budget branch of `mirrors`, `r.requests[0]` assumes topic is always first in RunRecord::requests without a name check; the retry branch correctly uses `.iter().find(|q| q.step == \"topic\")`, so a future change in request ordering would silently assert on the wrong step."}, {"path": "tools/rustev-conformance/src/runtime.rs", "line": null, "summary": "In `infer`, the task name is silently coerced to an empty string when `call.projection` is not JSON or lacks a `\"task\"` key, causing a confusing permanent failure rather than a clear misconfiguration error."}]}

Subject: fb5d0c4...ccc5547, diff digest 99b4ce7f646b47fbbde249682bfa58ae067399a4bac6c2728db52ea14ffe32f8, 1 call(s). An AI comment is not an approval.

@bartekus
bartekus had a problem deploying to statecraft-review-exception October 21, 2026 00:45 — with GitHub Actions Error
@bartekus
bartekus force-pushed the impl/027-runtime-cases branch from ccc5547 to 3142064 Compare October 21, 2026 00:47
@github-actions

Copy link
Copy Markdown

AI review (findings)

Reviewing the PR, which adds data-driven runtime conformance cases (admission, budget, retry, deadline, cancel) with a Rust runner in tools/rustev-conformance/src/runtime.rs and a corresponding test suite.

Structural review:

  • Cargo.toml adds tokio as a regular dependency (not dev-dependency) since runtime.rs is a public pub mod. This is intentional but means the library always links tokio.
  • The until() busy-wait (100k yield_now iterations) is the correct approach for a single-threaded Tokio runtime with a manual clock; there is no real time involved.
  • The answer() clamping (n.clamp(1, l.len()) - 1) correctly handles first-attempt (n=1→index 0) and last-repeat (n>len→last index). The !l.is_empty() guard prevents clamp(1, 0) panic.

One concrete inconsistency found:

In tools/rustev-conformance/src/runtime.rs, the gate-released path always emits cancel: CancelAck::NotRequested:

// after a gate releases via on_release answer:
AttemptReport {
    result,
    charge,
    cancel: CancelAck::NotRequested,   // ← hard-coded
    remote: s.remote(),
}

If the cancellation signal is raised before release_all delivers the oneshot (i.e., both the rx and the signal fire in the same poll cycle), the poll_fn checks rx first and returns the release answer — but the cancel signal was observed yet the report claims it was never requested. This means the run record would show "cancellation":"not_requested" even though the signal was raised. The current five test cases avoid this (the cancel test uses only the None path; the admission/retry/deadline/budget tests never cancel), so no golden file is wrong. But future cases that interleave release_all and cancel could produce silently incorrect records.

Other observations (no-finding level):

  • tests/runtime.rs builds inputs from case.descriptors, case.calibrations, and case.requests[].snapshot, but not from case.backends[].descriptor. runtime::run calls doc(inputs, &b.descriptor), which would panic with "no input" if a backend's descriptor isn't also in case.descriptors. Currently they always coincide, but there is no explicit validation.
  • OnCancel::Ignore => std::future::pending().await is correct per spec 003 §3.7.3; the runtime drops the future rather than awaiting it.
  • The blip value used twice in json!([blip, blip, ...]) is fine because serde_json's json! macro takes &$value for non-literal expressions.
{"head": "314206452a40899f7f61fab2a475ff5a67eba465", "verdict": "findings", "findings": [{"path": "tools/rustev-conformance/src/runtime.rs", "line": 290, "summary": "After a gate is released via on_release, the AttemptReport hard-codes CancelAck::NotRequested regardless of whether the cancel signal was raised before the oneshot delivered, which would produce a wrong cancellation field in the run record for any future test case that concurrently cancels and releases the same gate."}]}

Subject: fb5d0c4...3142064, diff digest 3a59df1da61fd31ba2a4b33fa205eb51dbe1515c48362265155d45e7202630c9, 1 call(s). An AI comment is not an approval.

@bartekus
bartekus had a problem deploying to statecraft-review-exception October 21, 2026 00:55 — with GitHub Actions Error
@bartekus
bartekus force-pushed the impl/027-runtime-cases branch from 3142064 to 963d6a2 Compare October 21, 2026 00:56
@github-actions

Copy link
Copy Markdown

AI review (findings)

Reviewing the diff, focusing on tools/rustev-conformance/src/runtime.rs and tools/rustev-conformance/tests/runtime.rs.

Finding 1 — compile error: double-move of blip

tests/runtime.rs:259:

let blip = json!({ "fail": { ... } });
a["support.topic"] = json!([blip, blip, output("support.topic", 1)]);

serde_json::json! expands non-literal array elements via Value::from($expr), which moves. blip is moved in the first position and used again in the second — a use-after-move compile error. The serde_json docs explicitly note you must write blip.clone() to reuse a value in the macro. This test will not compile.

Finding 2 — release_all reports success even when all sends fail

runtime.rs:241–248:

fn release_all(&self) -> usize {
    let gates = std::mem::take(&mut *self.gates.lock().unwrap());
    let n = gates.len();   // count taken, not count delivered
    for (_, (task, tx)) in gates {
        ...
        let _ = tx.send(a);   // silently discards send error
    }
    n
}

The caller checks if released == 0 to guard against a no-op release step. But if receivers were already dropped (e.g., a gate was cancelled and removed from the map after std::mem::take grabbed it — a race window between take and iteration), the count is non-zero but nothing was delivered. The error check is bypassed and the test proceeds silently without actually unblocking any attempts.

Finding 3 — OnCancel::Ignore arm is inconsistent with gate removal

runtime.rs:222–225:

None => {
    s.gates.lock().unwrap().remove(&id);   // gate removed here …
    return match s.script.on_cancel {
        OnCancel::Ignore => std::future::pending().await,  // … then blocks forever

The gate is removed from the map before pending() suspends, so a subsequent release_all will not find it. If the driver script attempts a release_all after cancelling a backend that uses on_cancel: ignore, release_all would find no gates, return 0, and the runner would error with "released nothing". The current test cases avoid this ordering, but it's a latent script-authoring trap.

{"head": "963d6a21fc095d5caefccc347a0fc1b6979fbff9", "verdict": "findings", "findings": [{"path": "tools/rustev-conformance/tests/runtime.rs", "line": 259, "summary": "blip (a serde_json::Value) is used twice in json!([blip, blip, ...]) which moves the value in the first position, making the second use a compile error; serde_json docs say to write blip.clone() to reuse a Value in the macro."}, {"path": "tools/rustev-conformance/src/runtime.rs", "line": 245, "summary": "release_all returns the count of gates taken (n) before any sends, not the count of successful sends, so silently dropped oneshot receivers still yield a non-zero count and bypass the 'released nothing' script-error guard."}, {"path": "tools/rustev-conformance/src/runtime.rs", "line": 222, "summary": "For OnCancel::Ignore the gate is removed from the map before pending().await suspends, so a release_all called after cancelling an Ignore-policy backend will find no gates and erroneously report 'released nothing'."}]}

Subject: fb5d0c4...963d6a2, diff digest 2eb8f0e853640d448ad18cd95283031640b8037507e08db33096e27f38c2422d, 1 call(s). An AI comment is not an approval.

@bartekus
bartekus had a problem deploying to statecraft-review-exception October 21, 2026 01:03 — with GitHub Actions Error
@bartekus
bartekus force-pushed the impl/027-runtime-cases branch from 963d6a2 to 1a19ec0 Compare October 21, 2026 01:06
@github-actions

Copy link
Copy Markdown

AI review (no-findings)

Reviewing this PR, which adds runtime conformance cases to tools/rustev-conformance — new data-driven test cases mirroring tests in crates/rustev-runtime/tests, run with Rust seams under a manual clock.

tools/rustev-conformance/src/runtime.rs

  • answer() (line ~195): n.clamp(1, l.len()) - 1 correctly maps 1-indexed attempt numbers to 0-indexed list positions, with the last element repeating for over-length n. ✓
  • release_all(): atomically drains gates under lock, counts only successful sends; the released == 0 guard in the driver is appropriate.
  • OnCancel::Ignore branch returns std::future::pending().await. The comment explains the runtime polls once, records not_observed, and moves on — the future is dropped when the runtime abandons the attempt. This is consistent with the deadline test's expected record ("answer":"not_observed", "end":"deadline"). ✓
  • The mutex is never held across an await point. ✓
  • serde(deny_unknown_fields) on Answer and OnCancel enums: external tagging makes unit variants (Gate, Ignore) bare strings and struct variants (Output, Fail, Stop) inner objects — deny_unknown_fields correctly constrains the inner objects. ✓

tools/rustev-conformance/tests/runtime.rs

  • blip used twice in json!([blip, blip, ...]): json_internal! takes &$other, so blip is borrowed not moved on each use. ✓
  • mirrors() assertions are internally consistent with the expected golden files (e.g., budget: 2 attempts × 4 units = 8 observed; retry dispatch timestamps 0/10/30; cancel total 3 × 2 = 6 observed; deadline all charges Unknown). ✓
  • compare(c, 0, b"", &dir) in the_manifest_runtime_cases_pass_through_the_runner: passes step=0 and empty stdin. Runtime cases have a single command (no multi-step CLI argv), so step 0 covers all outputs. ✓

Case data / manifest consistency

SHA256 values in cases/manifest.json match the corresponding case files (same bytes in the individual JSON files under cases/runtime/). The aggregate() change to include both "cli" and "runtime" directories is correct; a missing directory is an error, and the PR adds all five files. ✓

Admission sequencing: drive order (start → wait_gated{3} → start → wait_queued{1} → start → release_all → wait_gated{3} → release_all) is consistent with max_in_flight:1, max_queued:1, max_parallel_requests:3 and the three requests (d1 judged, d2 judged, d3 overloaded). ✓

No bugs, security issues, or material inconsistencies found.

{"head": "1a19ec0ce7058c61019cc743a9cd91b203bdec09", "verdict": "no-findings", "findings": []}

Subject: fb5d0c4...1a19ec0, diff digest a501a9d3d1e4049b9b720414f80bf9d1a33596f0f0f5a7d72ad5f35b63b51dbd, 1 call(s). An AI comment is not an approval.

@bartekus
bartekus merged commit 5764d8b into main Oct 21, 2026
7 checks passed
@bartekus
bartekus deleted the impl/027-runtime-cases branch October 21, 2026 01:26
bartekus added a commit that referenced this pull request Oct 21, 2026
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.
bartekus added a commit that referenced this pull request Oct 21, 2026
Spec 027, increment 6 (second change): the native conformance adapter.
Stacked on #131.

- `tools/rustev-conformance/js/run.mjs` gains the `native` adapter:
every CLI case runs natively (pure commands compared whole with exit
codes; `run` compared on the judgment and the run record, the envelope's
paths, receipt and exit code being CLI presentation), and every runtime
case runs with TypeScript scripted seams driven on a manual clock. All
34 native cases produce their expected bytes, repeatedly; the 23
WebAssembly cases still pass.
- The manifest names each case's surfaces explicitly (pure commands
`cli`/`native`/`wasm`, `run` `cli`/`native`, runtime cases
`rust-api`/`native`).
- The runtime-case driver is now deterministic for asynchronous host
seams: `advance_timer { delay_ms }` advances only when that retry delay
is pending and no attempt is in flight (via
`ManualClock::pending_delays`, #131). Both runners use it.
- The cancellation case shared by both runners mirrors
`cancel.rs::no_answer_means_local_waiting_stopped_and_nothing_more`; the
confirmed-stop case stays Rust-only (`runtime.cancel-stop`), because the
runtime polls a cancelled attempt once and a host seam can never answer
within that poll (recorded in the spec as an owner finding).
- `make bindings` runs the native conformance after the native tests.

Review round 1 (3 findings, fixed): (1) `rawMember` walks the document's
structure and matches only a top-level key, never a nested key or text
inside a string. (2) The sink's records are now checked: a `run` case
requires the sink to have received exactly the bytes the result carries.
(3) An attempt whose scripted backend ignores cancellation is settled
when its case ends, as the late resolution the engine discards, so no
promise is left pending. Restacked on #131; native 34/34 (three runs)
and wasm 23/23.

Review round 2 (2 findings, fixed): (1) `rawMember` tolerates whitespace
around the colon and before the value (canonical goldens are compact,
but nothing depends on it); checked on nested keys, spaced JSON and a
key inside a string. (2) An attempt whose scripted backend ignored
cancellation is settled after its case by resolving, never rejecting, so
a discarded late settlement cannot surface as an unhandled rejection.
Restacked after #133 merged; native 34/34 (twice), wasm 23/23.

Review round 3 (3 findings, fixed): (1) an unknown `on_cancel` value
rejects at once as a script error instead of leaving the attempt
waiting. (2) the sink check runs for every `run` case, whatever outputs
it pins: the sink must have received exactly the result's record bytes.
(3) `rawMember`'s string scans are bounded by the text's length, so
malformed JSON ends the scan. Native 34/34 (twice), wasm 23/23.

Review round 4 (1 finding): by design: the native package links the
rules backend (3.3.2) and reads a rules program itself, as the CLI does,
so the native adapter passes the program's own bytes and every check and
compile case with a rules program produces the CLI's bytes natively
(34/34); only the WebAssembly adapter, which cannot read a rules program
(3.10.1), substitutes the derived descriptor. The code now says so.

Restacked after #130 stopped recording derived descriptors on `run`
cases: this PR now records them for `run` cases itself (the harvest
gives them to pure and `run` cases; the native runner prepares a
compiled plan against them), restored byte-identical to the descriptors
the pure cases carry. Native 34/34, wasm 23/23.

Review round 5 (3 findings): (1) `ManualClock::pending_delays` is in
`crates/rustev-runtime/src/clock.rs` from #131, this PR's base, so it is
in the tree this PR builds on; the workspace compiles and the Rust
runner uses it. (2) fixed: `valueAt` has one exit per kind of value: a
container ends at its matching bracket, a scalar before the delimiter
after it; checked on nested, spaced, string and number members. (3)
fixed: each runtime case keeps its own list of ignored attempts and
settles it when the case ends, however it ends, so none reaches a later
case. Native 34/34 (twice), wasm 23/23.

Review round 6 (1 finding, fixed): a record output is compared byte for
byte, and every normalization its case declares must already hold:
`timing` requires the record's timings to be the normalized zeros (they
are, under the manual clock), and any other normalization fails the
case, so none passes unchecked. Native 34/34 (twice), wasm 23/23.

Review round 7 (2 findings, both verified against #131):
`DecideResult.completion` is the declared field (`index.d.ts`), and the
native gauges object's key is `backendInFlight` (`src/lib.rs` builds it
in camelCase for JavaScript); every runtime case drives `advance_timer`
through it, and native passes 34/34.

Review round 8 (1 finding, fixed): the WebAssembly adapter's store
resolver returns an item that exists but is empty; only an absent item
is null. Restacked after #129 was split (#134 holds the runtime cases).

Review round 9 (1 finding): the late settlement's value is never read:
the native seam (`integrations/rustev-node/src/seams.rs`, #131) takes a
host's settlement as plain JSON, and when the attempt has already
finished it discards and counts it before anything parses it, so no
shape can cause a rejection; the runner's comment now says so.
Restacked; native 34/34 (twice), wasm 23/23.

Restacked on #134's fixes: the native runner gains the `wait_sleeper`
step (the deadline case now waits for the runtime's timer) and fails a
`release_all` that frees nothing, as the Rust runner does. Native 34/34
(twice), wasm 23/23.

CI `code` failed on the previous head: this PR had removed the Rust
runner's `wait_sleeper` step (its retry case moved to `advance_timer`)
while #134 now uses it in the deadline case. Restored, with both runners
supporting it; verified from a clean build of `rustev-runtime` and
`rustev-conformance` (an earlier local run had used a stale shared
build). Native 34/34 (twice).

Restacked on #130's last round: the runner's pure-command comparison
(`comparePure`) checks written outputs against the published artifact
(never skipping one), and the WebAssembly path requires its commands'
flags by name. Native 34/34 (twice), wasm 23/23.

Review round 10 (2 findings): (1) The record goldens hold the normalized
form (timings zero, written by the CLI tests through the shared
normalization), and a decision under the manual clock produces exactly
those bytes, so the byte comparison is the right one; native passes
34/34. The comment says so. (2) fixed: the pure-command engine decides
nothing, so its sink now throws if ever delivered to, failing the case,
instead of answering a placeholder receipt.

Restacked on #135 after #131 was split: this PR is now increment 6's
third change, on the JavaScript layer. Native 34/34 (twice), wasm 23/23.

Rebased after #130 merged: the harvest keeps main's staleness checks
(inputs, derived descriptors, surfaces) with this PR's surfaces
(`native` on every CLI case) and derived descriptors on `run` cases; the
runner keeps its scope object with main's required fields. A re-harvest
reproduces every case file (the wall-clock replay bundle aside). Native
34/34 (twice), wasm 23/23.

Review round 11 (3 findings): (1) fixed: the attempt loop no longer
shadows the flags object. (2) Not so: the native `command` takes its
arguments as a JSON value and deserializes `scope` from an object
(`integrations/rustev-node/src/commands.rs`, `replay_config`), and the
native replay cases pass; the comment says why it differs from the
WebAssembly call, which takes a string. (3) Repeated:
`ManualClock::pending_delays` is in #131, this PR's base.

Review round 12 (1 finding, raised before): the record goldens are
written in their normalized form by the CLI tests (timings zero), so
normalizing them would change nothing; the runner now checks that on the
golden too, failing with a message naming it if a golden were ever
stored unnormalized, as it checks the record. Native 34/34 (twice).

Split (the AI review was cancelled at its 15-minute limit twice): this
PR is now increment 6's third change, the native conformance cases
(surfaces, derived descriptors on `run` cases, the runtime driver's
corrections and the Rust-only cancel-stop case); the JavaScript runner's
native adapter (`run.mjs` and its `make bindings` step) moves to a PR
stacked on this one.

Review round 13 (1 finding, raised before):
`ManualClock::pending_delays` is on main
(`crates/rustev-runtime/src/clock.rs`, from #131, increment 6's first
change), so this PR does not change that file and the crate builds; the
spec record now names where the accessor comes from rather than reading
as if this change adds it.
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