Skip to content

impl(011): runtime loading, the platform table and the ONNX encoder (3.6, 3.9.1) - #493

Merged
bartekus merged 1 commit into
mainfrom
impl/011-onnx-encoder
Nov 4, 2026
Merged

bartekus merged 1 commit into
mainfrom
impl/011-onnx-encoder

Conversation

@bartekus

@bartekus bartekus commented Nov 3, 2026

Copy link
Copy Markdown
Contributor

Spec 011: runtime loading, the qualified-platform table and the ONNX encoder (3.6, 3.8.3, 3.8.4, 3.9.1)

This is the "after the gate" code path of 011's Implementation record. The PR is based on main and is independent of #485 and #490.

Runtime and platforms (src/runtime.rs)

  • Platform table. The platform key of the compilation target (3.6.3) is checked against QUALIFIED_PLATFORMS, the committed feasibility record's pass verdicts. The record has none, so the table is empty. tests/feasibility_record.rs checks that the table and the record agree. An onnx bundle is refused unqualified_platform before its runtime path is read.
  • Loading (3.6.1).
    • A missing or relative path is refused runtime_missing.
    • The file is streamed through SHA-256 and compared with the manifest's entry for this platform (runtime_digest_mismatch).
    • A second digest in the process is refused runtime_conflict (3.6.2). An equal digest reuses the loaded runtime, but only for the version it reported.
    • Nothing consults ORT_DYLIB_PATH or any search path.
  • Version check. ort::util::probe reports the minor number of a 1.x library. It is the only safe reader, and the workspace forbids unsafe. The patch number is bound by the digest, whose full version the record observed. A library reporting no version or another version is refused runtime_version_mismatch. A manifest naming another ort than the pinned 2.0.0-rc.15 is manifest_invalid.

Encoder (src/onnx.rs)

  • One session from the verified graph bytes, which are released afterwards.
    • CPU only, with no environment execution providers.
    • The manifest's optimization level and thread counts. all maps to ORT_ENABLE_ALL.
  • At setup, the graph's inputs (names and int64 type) and its output (name, float type, hidden size) are checked against the manifest (graph_rejected, graph_signature_mismatch).
  • Each run feeds input_ids, attention_mask and, when declared, token_type_ids of zeros.
  • The workers share the session. Runs on it are serialized, because ort needs &mut Session.
  • A raised attempt signal requests termination through the run's RunOptions (3.12.2), using a waker registered on the signal.

Tests

  • Default, needing no library (tests/runtime/mod.rs): runtime_missing (none, relative, absent, a directory), runtime_digest_mismatch (wrong digest, no entry for the platform), runtime_version_mismatch (a synthetic non-library file with a matching digest; a non-1.x version), and manifest_invalid for another ort. Also the platform key and the empty table, and an onnx bundle refused before its runtime path is read. A unit test covers the conflict decision.
  • By hand (tests/runtime/hand.rs, ignored; set RUSTEV_EMBED_CHECKPOINT and RUSTEV_EMBED_RUNTIME). It assembles an onnx bundle from the pinned graph and tokenizer with one generated head. Run on 2026-11-03 on macos-aarch64 with the record's library (sha256 2a50a63e...), it passed:
    • All 21 reference token-id sequences reproduced through the backend's preparation: 19 inferred, plus one text_empty and one too_many_tokens.
    • Every pooled embedding is within the 3.3 bounds. The largest component difference is 2.83e-7, equal to the probe's. Embeddings are bitwise repeatable in process.
    • runtime_version_mismatch, runtime_conflict, graph_rejected and graph_signature_mismatch with the real library.
    • A raised signal ended a 256-token run after 2.9 ms; the same run uncancelled took 78.6 ms.
    • The backend still refuses the platform.
  • This run is evidence for a later record entry, not a stage 4 measurement, and no evidence file changed.

Boundaries

ort keeps default-features = false with std, load-dynamic, api-31, so no download feature is enabled. The crate graph and Cargo.toml are unchanged.

Not done here

  • A qualified platform: stage 4 of the complete backend, plus the Node local-embed build on the platform's native matrix target (3.2.3).
  • An onnx bundle's cache evidence (3.14.3).
  • 011 in make verify.

@github-actions

github-actions Bot commented Nov 3, 2026

Copy link
Copy Markdown

AI review (findings)

Reviewing the new ONNX runtime loading and encoder implementation.

runtime.rs — wrong error code for ort::init_from failure

In the load function, after ort::util::probe(path) succeeds and confirms the library is the expected 1.x version, ort::init_from(path) failure is mapped to RuntimeVersionMismatch:

let environment = ort::init_from(path)
    .map_err(|e| refusal(C::RuntimeVersionMismatch, "runtime_path", &e.to_string()))?

At this point the version has already been verified correct; init_from failure is an OS-level or initialization error (the library can't be loaded), not a version mismatch. The RuntimeMissing code is semantically correct here, since the problem is that the runtime could not be initialized from the path, not that it reported the wrong version. Using RuntimeVersionMismatch misleads operators diagnosing production failures and contradicts the error message that would accompany it (the ORT loader error string, not a version string). RuntimeMissing is what the .build() failure immediately below already uses for the analogous case.

feasibility_record.rs — order-sensitive comparison of unordered collection

The new test the_crates_platform_table_is_the_records_passing_verdicts does:

let passing: Vec<String> = record
    .verdict
    .iter()
    .filter(|(_, v)| v["verdict"] == "pass")
    .map(|(k, _)| k.clone())
    .collect();
let table: Vec<String> = rustev_backend_embed_linear::runtime::QUALIFIED_PLATFORMS
    .iter()
    .map(|p| serde_json::to_value(p).unwrap().as_str().unwrap().to_owned())
    .collect();
assert_eq!(table, passing, "3.6.3: the table is the record's");

assert_eq! on two Vec<String> is order-sensitive. passing is collected from record.verdict.iter(), whose order depends on the underlying map type used for the feasibility record's verdict field. If that map is a HashMap (the serde_json default for objects), iteration order is arbitrary. table follows the declaration order of QUALIFIED_PLATFORMS. When both are empty this passes trivially, but as soon as any platform is qualified the test will either spuriously fail or give false confidence depending on iteration order. Both vectors should be sorted before the comparison.

{"head": "26899638196d6565f681e87137bdee13960cd90d", "verdict": "findings", "findings": [{"path": "backends/rustev-backend-embed-linear/src/runtime.rs", "line": 237, "summary": "ort::init_from failure after a successful probe is mapped to RuntimeVersionMismatch; the failure here is an OS-level loading error, not a version mismatch, so RuntimeMissing is the correct code."}, {"path": "backends/rustev-backend-embed-linear/tests/feasibility_record.rs", "line": 155, "summary": "assert_eq!(table, passing) is order-sensitive but `passing` is collected from record.verdict whose iteration order is map-dependent; both vectors must be sorted before comparison or the test will fail spuriously when any platform is qualified."}]}

Subject: f1f08cd...2689963, diff digest a42f20f2bec07f4a79c7d6449d2d0027c2ce371dbfe4d178774f8acf4a13a702, 1 call(s). An AI comment is not an approval.

@bartekus
bartekus temporarily deployed to statecraft-review-exception November 3, 2026 21:50 — with GitHub Actions Inactive
@bartekus
bartekus force-pushed the impl/011-onnx-encoder branch from 2689963 to 9ca8e3a Compare November 3, 2026 21:56
@github-actions

github-actions Bot commented Nov 3, 2026

Copy link
Copy Markdown

AI review (findings)

Reviewing the new ONNX runtime loader and encoder implementation.

src/runtime.rs line 177 — wrong error code for ort::init_from failure

After ort::util::probe succeeds (line 169) confirming the minor version matches, ort::init_from is called to actually load the library. If that call fails (e.g., a missing DLL dependency, OS dlopen error, ABI incompatibility) the error is mapped to C::RuntimeVersionMismatch:

let environment = ort::init_from(path)
    .map_err(|e| refusal(C::RuntimeVersionMismatch, "runtime_path", &e.to_string()))?

The version was already confirmed by probe; an init_from failure is a loading failure, not a version mismatch. The module's own doc comment lists "Codes: runtime_missing, runtime_digest_mismatch, runtime_conflict, runtime_version_mismatch; manifest_invalid" and no code for post-probe init failure, which suggests this is an unintentional copy from the probe check immediately above it. The correct code is C::RuntimeMissing (consistent with the .build() failure two lines below, which does use C::RuntimeMissing).

No other concrete defects found. The TOCTOU between hash and load is explicitly acknowledged in the module doc and in the spec (3.6.5). The unwrap_or_else(|e| e.into_inner()) for the poisoned mutex is consistent across both LOADED in runtime.rs and session in onnx.rs. The onnx_run closure hardcoding the attention mask to all-ones is correct for unpadded sequences per 3.9.1. The GRAPH_SHA256 constant in hand.rs is 64 hex characters. The spec prose in the new increment note is consistent with the code.

{"head": "9ca8e3ab98bc05083c51c4d4cd6428e248c4fdc6", "verdict": "findings", "findings": [{"path": "backends/rustev-backend-embed-linear/src/runtime.rs", "line": 177, "summary": "ort::init_from failure after a successful probe is mapped to RuntimeVersionMismatch rather than RuntimeMissing; the loading failure is unrelated to version and the error code is misleading."}]}

Subject: f1f08cd...9ca8e3a, diff digest 313ab2d5cc0eca748d86fc35705b3f93f1f50ef9d8aa33c01542dbcf6cbf32ab, 1 call(s). An AI comment is not an approval.

@bartekus
bartekus temporarily deployed to statecraft-review-exception November 3, 2026 22:03 — with GitHub Actions Inactive
@bartekus
bartekus force-pushed the impl/011-onnx-encoder branch from 9ca8e3a to 960a3e3 Compare November 3, 2026 22:11
@github-actions

github-actions Bot commented Nov 3, 2026

Copy link
Copy Markdown

AI review (no-findings)

Reviewing the diff for bugs, security defects, and inconsistencies against the spec and governance rules.

src/runtime.rs

  • file_sha256 correctly calls file.metadata() on the already-open file descriptor (fstat, not stat), so the is_file() check is TOCTOU-safe against the path.
  • The TOCTOU between hash verification and probe/init_from is explicitly acknowledged as 3.6.5 and documented in the module comment; not a defect.
  • decide → Reuse branch's if let Some(l) is always true when reached (since decide only returns Reuse when loaded is Some), but this is unreachable-dead-code rather than a logic error.
  • The global LOADED mutex is held across probe and init_from, which blocks all other callers for the duration of library loading. This is intentional (single-load guarantee) and acceptable for a setup-time operation.
  • QUALIFIED_PLATFORMS is &[] (empty), so qualified_platform() always fails UnqualifiedPlatform on every target. tests/feasibility_record.rs::the_crates_platform_table_is_the_records_passing_verdicts enforces this matches the committed record.

src/onnx.rs

  • check_signature sorts both sides before comparing input sets; then validates each name is in {input_ids, attention_mask, token_type_ids} and that the required two are present. The output check validates rank-3 and shape[2] == hidden (dynamic dimensions for batch/sequence are correct for ONNX).
  • encode checks pre-lock and post-lock for cancellation; the Terminate waker wires the RunOptions::terminate() call correctly through poll_raised. If terminate() is called before run_with_options starts (signal raised while waiting on lock), ORT terminates immediately on start — the desired behavior.
  • bundle.graph = Vec::new() releases graph bytes after session creation, which is good practice.
  • Mutex poison recovery via unwrap_or_else(|e| e.into_inner()) is consistent with the same pattern in runtime.rs; in both cases safe Rust code in ort should not panic with the lock held.

src/backend.rs

  • onnx_run calls qualified_platform() before any path is read, which is the required security property (3.6.3): a bundle is refused on unqualified platform before the library path is touched. The test an_onnx_bundle_is_refused_before_its_runtime_path_is_read confirms this for None, relative, and absent paths.
  • The Environment local in onnx_run is dropped when the function returns, but the global LOADED holds a clone (Arc-counted internally), so the session's underlying environment data remains live.

tests/runtime/hand.rs (ignored)

  • GRAPH_SHA256 is 64 hex characters (8 groups of 8) — valid SHA-256.
  • The hand test correctly asserts UnqualifiedPlatform even with a real library, confirming 3.6.3 enforcement end-to-end.

specs/011-semantic-backend/spec.md

  • The revision note ("19 inferred, one text_empty, one too_many_tokens" = 21 total) is consistent with hand.rs's assert_eq!(inferred.len(), 19).
  • The note is marked as evidence for a later record entry and explicitly not declared verification, consistent with governance principle XI.

No concrete defects found.

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

Subject: f1f08cd...960a3e3, diff digest f2788afcf20d777475567552fc38f7dbdc4937e8e76fd1540b18bfd2f23e6ec7, 1 call(s). An AI comment is not an approval.

@bartekus
bartekus added this pull request to the merge queue Nov 3, 2026
@bartekus
bartekus removed this pull request from the merge queue due to a manual request Nov 3, 2026
@bartekus
bartekus force-pushed the impl/011-onnx-encoder branch from 960a3e3 to 1d72471 Compare November 4, 2026 02:00
@github-actions

github-actions Bot commented Nov 4, 2026

Copy link
Copy Markdown

AI review (no-findings)

Reviewing the diff carefully for bugs, security problems, and inconsistencies across src/runtime.rs, src/onnx.rs, src/backend.rs, updated tests, and the spec history entry.

src/runtime.rs

The load() function flow is correct: ORT version check → minor version parse → absolute-path validation → file hashing → manifest digest comparison → process-global LOADED check → probe() version comparison → init_from(). No partial write to LOADED can occur on failure because *loaded = Some(...) is the last statement. The documented TOCTOU concern (3.6.5) is intentional. The decide() logic is correct; the Reuse branch's inner if let Some(l) is always satisfied (Reuse only triggers when loaded is Some), which is redundant but not wrong.

src/onnx.rs

Cancellation pattern: the Terminate waker registers options.terminate() before the mutex is acquired, with a second is_raised() check after acquiring the lock. This correctly handles cancellation both before and during a run.

The check_signature output shape check (shape.len() == 3 && shape[2] == hidden as i64) is appropriate for models with a fixed hidden size (the all-MiniLM-L6-v2 graph declares 384 as a fixed dimension). The runtime-output check in encode (dims == [1, n, hidden]) is separately strict.

src/backend.rs

open_with_runner discards the ONNX Arc<Run> with _. For ONNX bundles this is currently guarded by the empty QUALIFIED_PLATFORMS table (which causes qualified_platform() to fail before any session is created), so no resources are leaked. For synthetic bundles prepare returns None, which is harmless.

The graph bytes are correctly zeroed (bundle.graph = Vec::new()) after session creation.

Tests

the_crates_platform_table_is_the_records_passing_verdicts correctly enforces that QUALIFIED_PLATFORMS == record pass verdicts (currently both empty). onnx_is_refused_before_runtime_loading_on_every_current_target correctly updates the assertion from an implementation-detail string to e.item == "platform". The hand test is properly #[ignore] and documents what it checks.

Spec history

The 2026-11-03 entry accurately describes the implementation: qualified-platform table empty, onnx bundle refused before runtime path is read, loading codes, session construction, graph-byte release, serialized runs, and cancellation via run options.

No concrete defect found.

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

Subject: 5d9923e...1d72471, diff digest 9271bfc5b986619bd283d9387648c508b1c4084813e9533efe143bcdc99ed98a, 1 call(s). An AI comment is not an approval.

@bartekus
bartekus added this pull request to the merge queue Nov 4, 2026
Merged via the queue into main with commit bf846f5 Nov 4, 2026
27 checks passed
@bartekus
bartekus deleted the impl/011-onnx-encoder branch November 4, 2026 03:08
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