diff --git a/Cargo.lock b/Cargo.lock index 8f5f0aa4..7fef67a4 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1395,14 +1395,18 @@ name = "omni-vela-native" version = "0.1.0" dependencies = [ "anyhow", + "axum", + "http-body-util", "libm", "omni-qwen3-5-native", + "omni-runtime", "onig", "safetensors 0.8.0", "serde", "serde_json", "sha2 0.11.0", "tokenizers 0.22.2", + "tokio", ] [[package]] diff --git a/README.md b/README.md index d2566630..6d3e9c8f 100644 --- a/README.md +++ b/README.md @@ -198,7 +198,7 @@ checkpoint. Public231 concurrency-1 latency for heads `1ba07d1`, `f968e576`, | Kev-4B | [Pinned CPU export and Rust pointer head](recipe/kev/README.md); no worker or full-model parity yet ([#27](https://github.com/InferMatrixLab/system1-omni/issues/27)) | | D3 (Decision 3.0) | [Python reference worker](recipe/d3/reference.md) on the checkpoint's pinned runtime; `choice`/`noul`/`score` over text, image and video state; author-run on A100 for text and media serving (see the integration and media PRs) | | Vela 2.0 0.3B | [Python reference worker](recipe/vela/reference.md) on the checkpoint's pinned runtime; all five kinds (`choice`/`noul`/`score`/`span`/`set`) for text state; CPU FP32 validated (author-run, evidence in the integration PR) | -| Vela 2.0 0.8B hybrid | [Python reference worker](recipe/vela/reference.md) on the checkpoint's pinned runtime; same surface plus `span_heads`; [native library](recipe/vela/native.md) (bundle export, wire contract, processing, F32 heads); CPU FP32 parity recorded in the integration PR | +| Vela 2.0 0.8B hybrid | [Python reference worker](recipe/vela/reference.md) on the checkpoint's pinned runtime; same surface plus `span_heads`; [native Rust/CUDA text worker](recipe/vela/native.md#serve-the-08b-native-worker) (uniform-BF16 backbone, FP32 heads); CPU FP32 reference parity recorded in the integration PR | | Vela 2.0 4B / 9B | Same worker and member registry as the 0.8B (one shared runtime); **historical 4B/9B validation** on an RTX 4090 48 GB is recorded in [the native recipe](recipe/vela/native.md), including frozen fixtures and CUDA executor parity. Full 4B/9B replay under the current strict span assertions remains unverified. | | Clef-flash (9B) and Clef (27B) | [Rust `omni-clef` server](recipe/clef/reference.md) and pinned Python joint-schema executor on one persistent thread; text `choice`/`noul`/`score`. [Historical flash GPU run](recipe/clef/reference.md#controlled-migration-acceptance), with raw evidence lost after a host restart: three Public231 C1 rounds per HTTP path, 231/231 each, exact parity with frozen FLA configurations; concurrency/cancellation/child-exit checks. Fresh acceptance with durable artifacts is pending. 27B, media and a native joint head remain unverified or unimplemented | | pplx-decider-v1.1-27b | [Python reference worker](recipe/pplx_decider/README.md) on the pinned checkpoint; `choice`/`noul`/`score` text plus up to four images. Lab L20X-labeled GPUs are the H200 target. Kept Public231 primary is `fcf5e2b`: 231/231, p50 87.782 ms, p95 291.183 ms, grouped-value FlashInfer with q and k packed before the L2 view (p50 −1.30%, p95 −1.56% versus `4b99b73` 88.942 / 295.797). `4b99b73` was p50 −4.20%, p95 −0.22% versus `ffae182` 92.844 / 296.458. Uncached all-sequence FlashInfer `3c72f02` is not the primary (p50 88.808 ms, p95 300.751 ms). Short-sequence FlashInfer `a50b9aa` missed its gate (p50 95.446 ms, p95 300.871 ms). cuDNN-first SDPA `0dcaa0ac` missed its gate (p50 138.501 ms, p95 332.859 ms). Fused gate-up `8b4ee326` missed its gate (p50 102.437 ms, p95 304.970 ms). Always-on dynamic compile `e36b32ed` missed the both-percentiles gate (p50 97.751 ms, p95 263.124 ms; p95 improved). The 512-token split `7e3b1be` missed its gate (p50 100.037 ms, p95 257.084 ms). Isolated-median compile `34ba5de` missed its gate (p50 97.084 ms, p95 256.679 ms; the 136-token probe was eager). The FlashInfer state-workspace ring `17a7b120` missed its gate (p50 89.165 ms, p95 295.723 ms). Always-on FLA residual RMSNorm `3afb472` missed its gate (p50 93.935 ms, p95 274.902 ms). Length-gated FLA residual RMSNorm `705ae089` missed its gate (p50 94.604 ms, p95 274.835 ms). `use_cp=auto` `a6f4d9a` missed its gate (p50 112.294 ms, p95 299.419 ms). Grouped-value `3ecdf5a` crashed in warmup (0/231, no p50 or p95). FLA fused gated RMSNorm `801ef7b` missed its gate (p50 89.172 ms, p95 274.790 ms). FLA `swiglu_fwd` `2bbbe4e` missed its gate (owner closeout p50 97.613 ms, p95 292.795 ms) and is not installed | diff --git a/docs/architecture.md b/docs/architecture.md index a08ec776..d7db22f4 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -161,6 +161,7 @@ and candidate identity, usage, and response metadata outside the executor. | Laya | One padded request: token IDs, true lengths, question types and ordered option markers; at most 16 questions, 512 tokens per row and 2048 markers. | Per-question FP32 option logits and two action logits copied back after GPU heads. | Calibrate and decode ordered `choice`, `score` and `noul` answers, usage and metadata. | | JEMM | Ordered token IDs, three-axis positions, candidate counts and optional shared image patches for one complete request. | Per-question selected BF16 label logits copied back as FP32. | Apply checksum-covered text/image calibration and reconstruct ordered `choice`, `score` and `noul` answers and usage. | | StartLux Instant 4B | One unpadded token-ID prompt per question, or per knockout group and then a final prompt, in request order. | FP32 letter logits from a CPU dot of the tied embedding rows at the last position. | Per-type temperature, none-check split, wide-choice residual, and ordered `choice`, `noul`, and `score` answers with token usage. | +| Vela 2.0 0.8B | One rendered request, with ordinary and span-window rows, question readout positions and span word offsets. | FP32 candidate logits and router/broad word-by-label logits from CUDA backbone readouts. | Aggregate span windows by question and word offset, calibrate and assemble the five typed question kinds, extensions and rendered-row usage. | | Clef | The raw `systemone` body. Preparation stays in the pinned Python encoder. | One joint-schema forward on the executor process main thread. The Rust closure only exchanges a frame. | The checkpoint's `systemone_answer` object, forwarded with its HTTP status unchanged. | Cua-S1 input collections are serial work. For both Open-Jev checkpoints, @@ -172,7 +173,7 @@ retain original batch row counts; output/down GEMMs retain candidate lengths. Request-local prefixes run as exclusive items. It restores question/candidate grouping before normalization. Laya batches questions within one request. Shared runtime admission precedes blocking dispatch: Cua-S1 admits one question forward at a -time; serial Open-Jev modes, Decider, Laya, StartLux Instant, and Clef admit one complete request. Clef's admitted work is the frame exchange with its executor process. StartLux runs each prompt inside that admission one at a time. Cua-S1's CPU letter projection +time; serial Open-Jev modes, Decider, Laya, StartLux Instant, Vela 0.8B, and Clef admit one complete request. Clef's admitted work is the frame exchange with its executor process. StartLux runs each prompt inside that admission one at a time. Cua-S1's CPU letter projection stays outside admission; Open-Jev's scalar heads and Laya's GPU heads and synchronized readback remain inside their request unit. Decider includes every backbone row and CUDA head projection, synchronizes both streams and retires diff --git a/docs/supported-models.md b/docs/supported-models.md index ba797fba..5a51c314 100644 --- a/docs/supported-models.md +++ b/docs/supported-models.md @@ -30,7 +30,7 @@ Models that are being added are also tracked in issues labeled [new model](https | OmniJev-4B v1.1 | [Native Rust/CUDA worker](../recipe/omnijev/native.md) on the shared Qwen3.5 vision and language path, eager | Contract, preparation, pixels, heads and finishing checked against the reference; no CPU inference | Compared with the reference on compute capability 8.9 for [140 answers](../recipe/omnijev/native.md#comparison-with-the-reference) | Not supported | Compute capability 8.0 or newer, CUDA toolkit to build, the export from `export.py` | | D3 (Decision 3.0) | [Python reference worker](../recipe/d3/reference.md) on the checkpoint's pinned runtime — text, image and video state over `choice`/`noul`/`score`, with the deliberate transport differences documented in the recipe; the native worker is in progress ([#136](https://github.com/ThinkFlowLab/system1-omni/issues/136)) | Unverified | Author-run on NVIDIA A100 (sm_80): serving smoke and reference parity for text and media (exact decisions, max delta 0.0); evidence in the integration and media PRs. Owner: @MrDongsls. | Unverified | Python 3.12, the [pinned runtime requirements](../recipe/d3/requirements.txt), the [pinned package](https://huggingface.co/vllm-sr/d3) (~52 GB); [media budgets and the 64 MiB total request cap](../recipe/d3/reference.md) | | Vela 2.0 0.3B | [Python reference worker](../recipe/vela/reference.md) running the checkpoint's pinned runtime | **CPU FP32 validated** (author-run, x86 WSL2, 24 cores): startup with all-kind warmup, the four example requests plus five synthetic rejections, and exact-match reference parity against the pinned upstream server on all nine (four 200s byte-equal incl. key order, agreed 422/413); byte-identical frontend forwarding; evidence in the integration PR. Owner: @MrDongsls. | Unverified (bf16-autocast is an untested deployment option) | Not supported | Python 3.12, the [pinned requirements](../recipe/vela/requirements.txt), the [pinned package](https://huggingface.co/vllm-sr/Vela-2.0-0.3B) (1.24 GB FP32 weights; ~4.4 GB with ONNX/assets) | -| Vela 2.0 0.8B hybrid | [Python reference worker](../recipe/vela/reference.md) running the checkpoint's pinned runtime (same wire layer as 0.3B); [native library](../recipe/vela/native.md) — bundle export, wire contract, processing, F32 heads and CUDA executor (no HTTP worker) | Same surface as 0.3B plus the `span_heads` field (router/broad dispatch); **CPU FP32 parity** (author-run; evidence in the integration PR) | Serving unverified; native executor parity author-run on sm_120 and on one RTX 4090 48 GB / sm_89 / CUDA 13.2 profile (4/4, worst drift 0.3297); the earlier 24 GB / CUDA 13.0 profile remains unrerun after the fixed-GEMM change | Not supported | Python 3.12, the [pinned requirements](../recipe/vela/requirements.txt), the [pinned package](https://huggingface.co/vllm-sr/Vela-2.0-0.8B) (2.02 GB shard + 4.5 MB broad head; ~3 GB FP32 parameters) | +| Vela 2.0 0.8B hybrid | [Python reference worker](../recipe/vela/reference.md) running the checkpoint's pinned runtime (same wire layer as 0.3B); [native Rust/CUDA text worker](../recipe/vela/native.md#serve-the-08b-native-worker) — bundle gate, processing, FP32 heads and typed responses | Same surface as 0.3B plus the `span_heads` field (router/broad dispatch); **CPU FP32 parity** (author-run; evidence in the integration PR) | Native serving uses uniform BF16 plus FP32 heads; executor logit parity author-run on sm_120 and on one RTX 4090 48 GB / sm_89 / CUDA 13.2 profile (4/4, worst drift 0.3297); the earlier 24 GB / CUDA 13.0 profile remains unrerun after the fixed-GEMM change | Not supported | Python 3.12, the [pinned requirements](../recipe/vela/requirements.txt), the [pinned package](https://huggingface.co/vllm-sr/Vela-2.0-0.8B) (2.02 GB shard + 4.5 MB broad head; ~3 GB FP32 parameters) | | Vela 2.0 4B / 9B | [Python reference worker](../recipe/vela/reference.md) on the checkpoint's pinned runtime, same wire layer and member registry as the 0.8B (one runtime, shared byte-identical across the decoder members); the [native library](../recipe/vela/native.md) exports and gates them with the same member-parameterized stack (widths derived from tensor shapes) | Historical 4B/9B validation is recorded in the native recipe; full head/response replay under the current strict span assertions remains unverified | Historical CUDA executor parity was recorded on sm_89; the current 0.8B SM89 fixed-GEMM replay is documented separately in the native recipe | Not supported | Python 3.12, the [pinned requirements](../recipe/vela/requirements.txt), the pinned 4B (`d6923941`, ~9.7 GB, 3 shards) or 9B (`068425bb`, ~17.9 GB, 5 shards) package | | Clef-flash (9B) | [Rust `omni-clef` server](../recipe/clef/reference.md) with a pinned Python executor on one persistent thread; text `choice`/`noul`/`score`, non-thinking prompt, 16384-token limit | 18 Rust lifecycle/serving and 36 Python contract tests; pinned tokenizer fixture; no CPU inference | [Historical author-run results](../recipe/clef/reference.md#controlled-migration-acceptance) on NVIDIA L20X (PyTorch capability 9.0, nvidia-smi 8.9): three C1 rounds per HTTP path, 231/231 each, exact 693-pair response parity under frozen FLA configurations; concurrency, cancellation recovery and child exit checked. Raw evidence and frozen caches were lost after a host restart; new acceptance with durable artifacts is pending. Recorded latency and the failed cache-control experiment remain in the recipe | Not supported | Python 3.12, [tested dependencies](../recipe/clef/requirements.txt), Rust `omni-clef`, pinned flash snapshot (~19.1 GB) | | Clef (27B) | Same `omni-clef` server and text contract as Clef-flash, selected with `--variant clef` | Contract tests only; no inference | Not run | Not supported | Same stack; pinned `Cloudflare/clef` snapshot (~55.0 GB). Weights and joint-head config differ from flash | diff --git a/mkdocs.yml b/mkdocs.yml index 74d23dca..74694355 100644 --- a/mkdocs.yml +++ b/mkdocs.yml @@ -88,8 +88,8 @@ nav: - LFM2.5-350M choice worker: recipe/lfm2/README.md - D3 reference worker: recipe/d3/reference.md - Vela 2.0 reference workers: recipe/vela/reference.md - - Vela 2.0 decoder native library: recipe/vela/native.md + - Vela 2.0 native decoder and 0.8B CUDA worker: recipe/vela/native.md - Clef reference worker: recipe/clef/reference.md - pplx-decider reference worker: recipe/pplx_decider/README.md - - Vela 2.0 0.8B native library: recipe/vela/native.md + - Vela 2.0 0.8B native CUDA worker: recipe/vela/native.md - Contributing: CONTRIBUTING.md diff --git a/recipe/README.md b/recipe/README.md index f745eba0..675f534a 100644 --- a/recipe/README.md +++ b/recipe/README.md @@ -63,7 +63,7 @@ For a first real decision, follow the [complete CPU walkthrough](../docs/getting five SystemOne question kinds (`choice`/`noul`/`score` plus the `span`/`set` extensions) through the Python worker and the Rust frontend on CPU FP32; or a decoder member (0.8B `326b01d8`, 4B `d6923941`, 9B `068425bb`) behind its own 10-file gate. -- [Vela 2.0 decoder native library](vela/native.md): export the pinned-bundle +- [Vela 2.0 native decoder and 0.8B CUDA worker](vela/native.md): export the pinned-bundle manifest gate, wire contract and token-level processing for the decoder members (0.8B, 4B and 9B), checked against frozen fixtures; serving stays with the reference Python worker. diff --git a/recipe/vela/native.md b/recipe/vela/native.md index a1711eb3..b91e4ad3 100644 --- a/recipe/vela/native.md +++ b/recipe/vela/native.md @@ -1,4 +1,4 @@ -# Vela 2.0 decoder native library +# Vela 2.0 native decoder and 0.8B CUDA worker This recipe belongs to `omni-vela-native` at [`src/models/vela/native/`](../../src/models/vela/native/). The 0.3B @@ -13,8 +13,10 @@ program, member-parameterized): the exported-bundle gate, the wire contract, the token-level processing, the F32 heads (widths derived from the tensors' shapes) and scoring, and backbone execution on CUDA through the shared qwen3_5 crate — all mirrored from the pinned -runtime and checked against frozen fixtures. This is a library; the -HTTP worker is the [reference recipe](reference.md)'s Python worker. +runtime and checked against frozen fixtures. The Rust HTTP worker serves +the **0.8B text model** through the same processor and CUDA executor. +Use the [Python reference recipe](reference.md) for reference serving and +for the other decoder members. The recorded fixtures and parity evidence below are the 0.8B's (CPU FP32 recordings). Historical 4B/9B runs on an RTX 4090 48 GB (sm_89, CUDA 13.2 toolkit) recorded exact-match plans and native executor @@ -271,6 +273,71 @@ small-case logit results; they do not replace complete GPU typed-answer or native HTTP acceptance. Test wall time includes repeated bundle hashing and is not serving latency. +## Serve the 0.8B native worker + +From the repository root, export the 0.8B bundle with `--bf16-out`, save +the manifest digest printed by the exporter, and build the SM89 Qwen CUDA +library as above. The worker loads the expanded export, including its +`bf16/` directory, and keeps one CUDA model on the first visible device. +Build and launch the Rust worker and optional pass-through frontend: + +```sh +bash src/backends/cuda/qwen3_5/build.sh /absolute/path/to/worker-library 89 +cargo build --locked --release -p omni-vela-native -p omni-jev +export VELA_NATIVE_BUNDLE=/absolute/path/to/vela08-native +export VELA_NATIVE_MANIFEST_SHA256='paste-digest-printed-by-the-exporter' +export VELA_CUDA_LIB=/absolute/path/to/worker-library/libqwen3_5_cuda.so +VELA_NATIVE_BIND=127.0.0.1:8000 target/release/omni-vela-native +``` + +In another shell: + +```sh +curl --fail http://127.0.0.1:8000/ready +jq '.request' tests/vela/fixtures/native-plan-Vela-2.0-0.8B-example-request.json | + curl --fail-with-body http://127.0.0.1:8000/v1/systemone \ + -H 'Content-Type: application/json' --data-binary @- + +OMNI_JEV_BIND=127.0.0.1:8080 OMNI_JEV_BACKEND_URL=http://127.0.0.1:8000 \ + target/release/omni-jev +# Send the same POST to http://127.0.0.1:8080/v1/systemone. +``` + +The worker binds after bundle verification and a real warmup. `/health` +and `/ready` are direct worker endpoints. The Rust frontend forwards +`/health` and `/v1/systemone`; its backend request timeout is 60 seconds. +Keep the unauthenticated worker on a trusted interface. The native worker +accepts JSON bodies up to 8 MiB and returns the Vela error detail envelope. +It handles text and structured JSON state for Choice, Noul, Score, Span +and Set. Media and requests for other model IDs are outside its envelope. + +All ordinary and window rows are planned before CUDA dispatch. The +worker admits one complete request at a time. It runs the pinned BF16 +backbone per readout and computes the candidate, router and broad heads +in FP32. Only span blocks run in the window rows. Those rows carry +their ordinary row's question and head attribution. Span logits are +aggregated by original word offsets before calibration and response +finishing. Usage sums rendered ordinary and window row lengths, with +zero generated tokens. A disconnected client cannot release an executing +request's admission before its CUDA work returns. + +Run the original CPU tests and opt-in checks above separately. The +complete GPU capture uses the same executor and finisher as HTTP: + +```sh +# JSON array of [case-name, absolute-path-to-request-json] pairs +export VELA_PIPELINE_CASES=/absolute/path/to/cases.json +export VELA_PIPELINE_OUTPUT=/absolute/path/to/new-output-directory +cargo test --release --locked -p omni-vela-native --test vela_native_pipeline \ + -- --ignored --nocapture +``` + +Capture output includes the actual token plan, raw per-row head logits +and complete typed response. Compare against separately frozen paired +reference outputs. The recorded 0.35 replay gate covers raw logits. +The existing CPU response gate covers finishing on frozen reference +readouts. Complete GPU typed numeric acceptance needs its own criterion. + ## Scope and limits - Each completed ordinary row and span-window row must contain at most @@ -299,6 +366,6 @@ is not serving latency. token-level processing, F32 heads, scoring and span decoding, the SystemOne response finishing, and backbone execution through the shared crate (full-sequence per readout position, fixed-GEMM replay). -- Not implemented: the HTTP worker around the library, long-span GPU - parity on the windowed case, and measured serving latency. No - performance claims are made. +- The native HTTP binary supports the 0.8B text profile. No serving + latency, throughput, or other decoder member's native HTTP evidence + is claimed here. diff --git a/src/models/vela/README.md b/src/models/vela/README.md index 5c9af37b..a64eab55 100644 --- a/src/models/vela/README.md +++ b/src/models/vela/README.md @@ -363,9 +363,14 @@ the 0.3B's 8,192 window nor the backbone's 262,144 position metadata widens native support. Multi-part span targets remain an explicit native 422, and non-finite JSON retains the generic native 400 wording. -The crate is a library; the HTTP worker around `Processor` + -`Executor` is not part of it. Long-span GPU parity and measured -latency are not recorded. Checks: `cargo test -p omni-vela-native` +The native `omni-vela-native` worker serves the pinned 0.8B text +bundle. `Processor` associates each span with its rendered ordinary +row and window range. The worker owns one CUDA executor and uses the +shared serial scheduler for one complete request. Candidate readouts +are scored in rendered block order. Span windows contribute to their +own question by word offset, then the finisher assembles the ordered +typed response, calibrated extensions and usage. The HTTP socket binds +after a successful warmup. Checks: `cargo test -p omni-vela-native` (ordinary tests need no weights or GPU; render, head and response parity are opt-in with `VELA_NATIVE_BUNDLE`, executor parity additionally with `VELA_CUDA_LIB`; see [recipe/vela/native.md](../../../recipe/vela/native.md)). diff --git a/src/models/vela/native/Cargo.toml b/src/models/vela/native/Cargo.toml index 83cecc53..f6383432 100644 --- a/src/models/vela/native/Cargo.toml +++ b/src/models/vela/native/Cargo.toml @@ -6,6 +6,10 @@ publish = false description = "Native library for the Vela 2.0 decoder members (0.8B/4B/9B): bundle gate, wire contract, processing, F32 heads, scoring and CUDA execution" [dependencies] +axum = "0.8.8" +http-body-util = "0.1.3" +omni-runtime = { path = "../../../runtime" } +tokio = { version = "1.49.0", features = ["macros", "net", "rt-multi-thread", "time"] } anyhow = "1.0.100" libm = "0.2" safetensors = "0.8.0" @@ -46,3 +50,11 @@ path = "../../../../tests/vela/native_executor.rs" [[test]] name = "vela_native_response" path = "../../../../tests/vela/native_response.rs" + +[[bin]] +name = "omni-vela-native" +path = "src/main.rs" + +[[test]] +name = "vela_native_pipeline" +path = "../../../../tests/vela/native_pipeline.rs" diff --git a/src/models/vela/native/src/lib.rs b/src/models/vela/native/src/lib.rs index 9bf3c2cd..533b7baa 100644 --- a/src/models/vela/native/src/lib.rs +++ b/src/models/vela/native/src/lib.rs @@ -7,15 +7,17 @@ //! `head-input-*` fixtures and the oracle responses; every width is //! derived from the tensors' shapes, so one implementation serves all //! members), and backbone execution on CUDA through the shared -//! qwen3_5 crate. The HTTP worker is not part of this crate. +//! qwen3_5 crate. The HTTP worker serves the pinned 0.8B member. pub mod bundle; pub mod contract; pub mod executor; pub mod heads; +pub mod pipeline; pub mod processing; pub mod questions; pub mod render; pub mod scoring; pub mod state; pub mod words; +pub mod worker; diff --git a/src/models/vela/native/src/main.rs b/src/models/vela/native/src/main.rs new file mode 100644 index 00000000..653000c7 --- /dev/null +++ b/src/models/vela/native/src/main.rs @@ -0,0 +1,26 @@ +use std::{net::SocketAddr, sync::Arc}; + +use anyhow::{Context, Result}; +use omni_vela_native::worker::{Engine, router}; + +#[tokio::main] +async fn main() -> Result<()> { + let bundle = std::env::var_os("VELA_NATIVE_BUNDLE").context("set VELA_NATIVE_BUNDLE")?; + let library = std::env::var_os("VELA_CUDA_LIB").context("set VELA_CUDA_LIB")?; + let anchor = + std::env::var("VELA_NATIVE_MANIFEST_SHA256").context("set VELA_NATIVE_MANIFEST_SHA256")?; + let bind: SocketAddr = std::env::var("VELA_NATIVE_BIND") + .unwrap_or_else(|_| "127.0.0.1:8000".into()) + .parse() + .context("invalid VELA_NATIVE_BIND socket address")?; + let engine = Engine::load(bundle.into(), library.into(), anchor).await?; + let listener = tokio::net::TcpListener::bind(bind) + .await + .context("bind Vela worker")?; + eprintln!( + "Vela 2.0 0.8B warmup complete, ready on {}", + listener.local_addr()? + ); + axum::serve(listener, router(Arc::new(engine))).await?; + Ok(()) +} diff --git a/src/models/vela/native/src/pipeline.rs b/src/models/vela/native/src/pipeline.rs new file mode 100644 index 00000000..7aafee37 --- /dev/null +++ b/src/models/vela/native/src/pipeline.rs @@ -0,0 +1,321 @@ +//! Executes the processor's complete plan through CUDA readouts and the native heads. + +use std::collections::HashMap; + +use anyhow::{Context, Result, ensure}; +use serde_json::Value; + +use crate::executor::Executor; +use crate::processing::{Planned, SpanPlan}; +use crate::render::{Block, RenderedRow}; +use crate::scoring::{ + Calibration, QBlock, SpanOut, aggregate_windows, row_answers, sigmoid, system_one_response, +}; + +/// Raw head outputs in rendered-row order. Question logits precede set bias. +#[derive(serde::Serialize)] +pub struct RowLogits { + pub questions: Vec>, + pub span: Option>>, +} + +impl Executor { + /// Execute one request. The observer receives its actual raw head outputs, + /// indexed as ordinary rows followed by window rows. + pub fn execute( + &mut self, + model_name: &str, + planned: &Planned, + calibration: &Calibration, + mut observe: impl FnMut(usize, &RowLogits), + ) -> Result { + let predict = &planned.predict_request; + let thresholds = predict["questions"] + .as_array() + .context("predict questions")? + .iter() + .filter_map(|q| Some((q["id"].as_str()?.to_owned(), q["threshold"].as_f64()?))) + .collect(); + let part_texts: HashMap<_, _> = predict["parts"] + .as_array() + .context("predict parts")? + .iter() + .map(|p| { + Ok(( + p["type"].as_str().context("part type")?.to_owned(), + p["text"].as_str().context("part text")?.to_owned(), + )) + }) + .collect::>()?; + let plan = planned.plan.as_array().context("response plan")?; + ensure!( + planned.rows.len() == planned.spans.len(), + "span plan row count" + ); + let mut next_window = 0; + let mut answers = Vec::new(); + let mut span_probs = HashMap::new(); + for (index, (row, span_plan)) in planned.rows.iter().zip(&planned.spans).enumerate() { + let mut raw = self.score_row( + row, + span_plan + .as_ref() + .is_some_and(|span| !span.windows.is_empty()), + )?; + observe(index, &raw); + let blocks = row.blocks.iter().filter_map(|block| { + let Block::Question { + qid, + qtype, + names, + has_abs, + .. + } = block + else { + return None; + }; + Some((qid, qtype, names, has_abs)) + }); + let mut questions = Vec::new(); + for ((qid, qtype, names, has_abs), mut logits) in blocks.zip(raw.questions) { + if qtype == "set" { + for logit in &mut logits { + *logit += self.heads.set_bias; + } + ensure!(logits.iter().all(|v| v.is_finite()), "non-finite set logit"); + } + questions.push(QBlock { + qid: qid.clone(), + qtype: qtype.clone(), + names: names.clone(), + has_abs: *has_abs, + logits, + }); + } + let span = if let Some(span) = span_plan { + ensure!(span.windows.start == next_window, "window row attribution"); + let output = self.finish_span(row, span, raw.span.take(), planned, &mut observe)?; + next_window = span.windows.end; + let entry = plan + .iter() + .find(|entry| entry["qid"] == span.qid) + .context("span response plan")?; + span_probs.insert( + span.qid.clone(), + span_probabilities(&output, entry, calibration), + ); + Some(output) + } else { + ensure!(raw.span.is_none(), "span logits have no owner"); + None + }; + let text = span + .as_ref() + .and_then(|span| part_texts.get(&span.over)) + .map(String::as_str); + answers.extend(row_answers( + calibration, + &questions, + span.as_ref(), + &thresholds, + text, + )); + } + ensure!( + next_window == planned.window_rows.len(), + "unconsumed window row" + ); + let input_tokens = planned + .rows + .iter() + .chain(&planned.window_rows) + .map(|row| row.n_tokens) + .sum(); + system_one_response( + model_name, + plan, + &answers, + &span_probs, + &part_texts, + input_tokens, + ) + } + + fn score_row(&mut self, row: &RenderedRow, skip_span: bool) -> Result { + // A windowed ordinary row still carries its span block for usage and + // admission, while only the window rows run that span head. + let without_span; + let row = if skip_span { + without_span = { + let mut row = row.clone(); + row.blocks + .retain(|block| matches!(block, Block::Question { .. })); + row + }; + &without_span + } else { + row + }; + let readouts = self.row_readouts(row)?; + let hidden = self.heads.hidden(); + let valid_hidden = + |values: &Vec| values.len() == hidden && values.iter().all(|v| v.is_finite()); + let mut questions = Vec::new(); + let mut readout_questions = readouts.questions.iter(); + for (index, block) in row.blocks.iter().enumerate() { + let Block::Question { + qid, + names, + ends, + has_abs, + .. + } = block + else { + continue; + }; + let readout = readout_questions + .next() + .context("missing question readout")?; + let count = names.len() + usize::from(*has_abs); + ensure!( + readout.block_index == index + && &readout.qid == qid + && ends.len() == count + && readout.candidates.len() == count + && readout.candidates.iter().all(valid_hidden), + "question {qid} readout shape, finiteness or attribution" + ); + let query = readout + .query + .as_ref() + .filter(|q| valid_hidden(q)) + .context("invalid question query")?; + let logits = self.heads.forward_candidate(&readout.candidates, query); + ensure!( + logits.len() == count && logits.iter().all(|v| v.is_finite()), + "invalid question {qid} logits" + ); + questions.push(logits); + } + ensure!( + readout_questions.next().is_none(), + "unconsumed question readout" + ); + let span = match readouts.span { + Some(readout) => { + let labels = row.names.as_ref().context("span label names")?.len(); + let words = row.w_offs.as_ref().context("span word offsets")?.len(); + ensure!( + labels > 0 + && readout.labels.len() == labels + && readout.words.len() == words + && readout + .labels + .iter() + .chain(&readout.words) + .all(valid_hidden) + && readout.query.as_ref().is_some_and(valid_hidden), + "invalid span readout" + ); + let head = match row.head.as_str() { + "broad" => &self.heads.broad, + "router" => &self.heads.router, + other => anyhow::bail!("unknown span head {other}"), + }; + let logits = head.forward(&readout.words, &readout.labels); + ensure!( + logits.len() == words + && logits + .iter() + .all(|r| r.len() == labels && r.iter().all(|v| v.is_finite())), + "invalid span logits" + ); + Some(logits) + } + None => { + ensure!( + !row.blocks + .iter() + .any(|block| matches!(block, Block::Span { .. })), + "missing span readout" + ); + None + } + }; + Ok(RowLogits { questions, span }) + } + + fn finish_span( + &mut self, + row: &RenderedRow, + plan: &SpanPlan, + ordinary: Option>>, + planned: &Planned, + observe: &mut impl FnMut(usize, &RowLogits), + ) -> Result { + let names = row.names.as_ref().context("ordinary span labels")?; + let logits = if plan.windows.is_empty() { + ordinary.context("ordinary span logits")? + } else { + ensure!( + ordinary.is_none(), + "windowed span also ran on its ordinary row" + ); + let mut logits = Vec::new(); + let mut offsets = Vec::new(); + for index in plan.windows.clone() { + let window = planned + .window_rows + .get(index) + .context("missing window row")?; + ensure!( + window.window + && window.head == row.head + && window.names == row.names + && window.span_over == row.span_over, + "window span attribution" + ); + let raw = self.score_row(window, false)?; + ensure!( + raw.questions.is_empty(), + "window contains non-span question scores" + ); + observe(planned.rows.len() + index, &raw); + logits.push(raw.span.context("window span logits")?); + offsets.push(window.w_offs.clone().context("window offsets")?); + } + aggregate_windows(names, &plan.offsets, &logits, &offsets) + }; + Ok(SpanOut { + qid: plan.qid.clone(), + over: row.span_over.clone().context("span target")?, + names: names.clone(), + offs: plan.offsets.clone(), + logits, + head: row.head.clone(), + head_reason: row.head_reason.clone(), + label_alias: plan.label_alias.clone(), + n_tokens: plan.target_tokens, + }) + } +} + +fn span_probabilities(span: &SpanOut, entry: &Value, calibration: &Calibration) -> Vec { + let bounds = entry["range"] + .as_array() + .and_then(|bounds| Some((bounds.first()?.as_u64()?, bounds.get(1)?.as_u64()?))); + let temperature = calibration.span_temperature(&span.head); + span.logits + .iter() + .zip(&span.offs) + .filter(|(_, (start, end))| { + bounds.is_none_or(|(lo, hi)| *start as u64 >= lo && *end as u64 <= hi) + }) + .map(|(logits, _)| { + logits + .iter() + .map(|v| sigmoid(f64::from(*v) / temperature) as f32) + .fold(0.0, f32::max) + }) + .collect() +} diff --git a/src/models/vela/native/src/processing.rs b/src/models/vela/native/src/processing.rs index d705568f..41f2ab7d 100644 --- a/src/models/vela/native/src/processing.rs +++ b/src/models/vela/native/src/processing.rs @@ -26,11 +26,20 @@ pub struct Processor { halu_desc: String, } +pub(crate) struct SpanPlan { + pub qid: String, + pub target_tokens: usize, + pub offsets: Vec<(usize, usize)>, + pub windows: std::ops::Range, + pub label_alias: Option, +} + pub struct Planned { pub predict_request: Value, pub plan: Value, pub rows: Vec, pub window_rows: Vec, + pub(crate) spans: Vec>, } impl Processor { @@ -92,6 +101,10 @@ impl Processor { }) } + pub(crate) fn clear_request_cache(&self) { + self.encoder.clear(); + } + /// The full planning path for one admitted request body. pub fn plan(&self, body: &Map) -> Result { let state = system_one_state(&body["state"])?; @@ -137,6 +150,7 @@ impl Processor { spans.iter().flat_map(|q| q.over.iter().cloned()).collect(); let mut rendered = Vec::new(); let mut window_rows = Vec::new(); + let mut span_plans = Vec::new(); let mut parts_by_role = std::collections::HashMap::new(); for part in self.prepared_parts(&state_parts, &span_roles)? { parts_by_role.insert(part.role.clone(), part); @@ -159,26 +173,45 @@ impl Processor { // `_window_rows`: a span target beyond RMAX becomes one row // per window (the full-render span block stays on the row). let span = row.iter().find(|q| q.kind == "span"); + let mut span_plan = None; if let Some(span) = span { - let index = parts.iter().position(|p| p.role == span.over[0]); - if let Some(index) = index { - let part = &parts[index]; - let has_words = part.words.is_some(); - if part.ids.len() > RMAX && has_words { - let (_, first_tokens) = part.words.as_ref().expect("words"); - for (a, b) in crate::render::span_windows(first_tokens, part.ids.len()) { - let mut windowed_parts = parts.clone(); - windowed_parts[index] = window_part(part, a, b); - let (w_adjusted, w_dispatch) = context.prepare_questions(&row)?; - let mut record = - context.render(&windowed_parts, &w_adjusted, &w_dispatch)?; - // The runtime's window rows carry the head only. - record.window = true; - window_rows.push(record); - } + let index = parts + .iter() + .position(|p| p.role == span.over[0]) + .ok_or_else(RequestError::internal)?; + let part = &parts[index]; + let (offsets, first_tokens) = + part.words.as_ref().ok_or_else(RequestError::internal)?; + let start = window_rows.len(); + // The pinned runtime renders only the span question in each window. + if part.ids.len() > RMAX { + let adjusted_span = &adjusted[adjusted.len() - 1..]; + for (a, b) in crate::render::span_windows(first_tokens, part.ids.len()) { + let mut windowed_parts = parts.clone(); + windowed_parts[index] = window_part(part, a, b); + let mut window = + context.render(&windowed_parts, adjusted_span, &dispatch)?; + window.window = true; + window_rows.push(window); } } + let windows = start..window_rows.len(); + let label_alias = crate::render::halu_alias(&span.names) + .filter(|alias| dispatch.head == "router" && *alias != HALU_LABEL) + .map(|alias| serde_json::json!({(HALU_LABEL): alias})); + span_plan = Some(SpanPlan { + qid: span.id.clone(), + target_tokens: part.ids.len(), + offsets: if windows.is_empty() { + record.w_offs.clone().unwrap_or_default() + } else { + offsets.clone() + }, + windows, + label_alias, + }); } + span_plans.push(span_plan); rendered.push(record); } Ok(Planned { @@ -186,6 +219,7 @@ impl Processor { plan, rows: rendered, window_rows, + spans: span_plans, }) } diff --git a/src/models/vela/native/src/render.rs b/src/models/vela/native/src/render.rs index 7efe37b1..e416956d 100644 --- a/src/models/vela/native/src/render.rs +++ b/src/models/vela/native/src/render.rs @@ -144,6 +144,10 @@ impl Encoder { Ok(entry) } + pub(crate) fn clear(&self) { + self.cache.borrow_mut().clear(); + } + /// Memoized token ids of a whole string (the reference's `_ids`). pub fn ids(&self, text: &str) -> Result, RequestError> { Ok(self.encode(text)?.0) diff --git a/src/models/vela/native/src/scoring.rs b/src/models/vela/native/src/scoring.rs index 82b2c771..2d85dbd0 100644 --- a/src/models/vela/native/src/scoring.rs +++ b/src/models/vela/native/src/scoring.rs @@ -835,7 +835,17 @@ pub fn system_one_response( } } _ => { - out = answer["spans"].as_array().cloned().unwrap_or_default(); + if let Some(predicted) = answer["spans"].as_array() { + out.extend(predicted.iter().map(|span| { + serde_json::json!({ + "label": span["label"], + "start": span["start"], + "end": span["end"], + "text": span["text"], + "probability": span["probability"], + }) + })); + } } } spans.insert(qid.to_string(), Value::Array(out)); diff --git a/src/models/vela/native/src/worker.rs b/src/models/vela/native/src/worker.rs new file mode 100644 index 00000000..e3fef96d --- /dev/null +++ b/src/models/vela/native/src/worker.rs @@ -0,0 +1,183 @@ +//! HTTP transport for the pinned Vela 2.0 0.8B CUDA bundle. + +use std::{ + path::{Path, PathBuf}, + sync::{Arc, Mutex}, + time::Duration, +}; + +use anyhow::{Context, Result, ensure}; +use axum::{ + Json, Router, + body::to_bytes, + extract::{Request, State}, + http::{StatusCode, header}, + response::{IntoResponse, Response}, + routing::{get, post}, +}; +use omni_runtime::SerialScheduler; +use serde_json::{Value, json}; + +use crate::{ + bundle::{Bundle, MEMBERS}, + contract::{self, RequestError}, + executor::Executor, + processing::Processor, + scoring::Calibration, +}; + +pub struct Engine { + model_name: String, + processor: Arc>, + executor: Arc>, + calibration: Arc, + scheduler: SerialScheduler, +} + +impl Engine { + /// Asset verification and actual inference complete before the router is served. + pub async fn load(bundle: PathBuf, library: PathBuf, anchor: String) -> Result { + tokio::task::spawn_blocking(move || Self::load_and_warm(&bundle, &library, &anchor)).await? + } + + fn load_and_warm(bundle: &Path, library: &Path, anchor: &str) -> Result { + let manifest = Bundle::load(bundle, anchor)?; + ensure!( + manifest.member.model_id == MEMBERS[0].model_id, + "HTTP worker requires the Vela 2.0 0.8B bundle" + ); + let model_name = manifest.model_name().to_owned(); + let processor = Processor::load(bundle, anchor)?; + let calibration = Calibration::load(bundle, anchor)?; + let mut executor = Executor::load(bundle, library, anchor)?; + let body = json!({ + "model": model_name, + "state": {"request": "Contact alice@example.com about the delivery."}, + "questions": { + "delivery": {"type": "noul", "instructions": "Does this mention a delivery?"}, + "pii": {"type": "span", "instructions": "Find email addresses.", + "criteria": {"EMAIL_ADDRESS": "email address"}, "over": "request"}, + "event": {"type": "span", "instructions": "Find delivery events.", + "criteria": {"delivery": "delivery event"}, "over": "request"} + } + }); + let planned = processor + .plan(body.as_object().context("warmup request")?) + .map_err(|error| anyhow::anyhow!("warmup planning failed: {}", error.body))?; + executor.execute(&model_name, &planned, &calibration, |_, _| {})?; + Ok(Self { + model_name, + processor: Arc::new(Mutex::new(processor)), + executor: Arc::new(Mutex::new(executor)), + calibration: Arc::new(calibration), + scheduler: SerialScheduler::default(), + }) + } + + pub async fn decide(&self, raw: &[u8]) -> std::result::Result { + let body = contract::compile(raw, &self.model_name)?; + let processor = Arc::clone(&self.processor); + let planned = tokio::task::spawn_blocking(move || { + let processor = processor.lock().map_err(report_failure)?; + let planned = processor.plan(&body); + processor.clear_request_cache(); + planned + }) + .await + .map_err(report_failure)??; + let executor = Arc::clone(&self.executor); + let calibration = Arc::clone(&self.calibration); + let name = self.model_name.clone(); + self.scheduler + .run(move || { + // Keep the sole mutable CUDA owner and scheduler permit through + // every row; forward_fixed reselects device 0 and synchronizes. + let mut executor = executor + .lock() + .map_err(|_| anyhow::anyhow!("executor lock poisoned"))?; + executor.execute(&name, &planned, &calibration, |_, _| {}) + }) + .await + .map_err(report_failure) + } +} + +fn report_failure(error: impl std::fmt::Display) -> RequestError { + eprintln!("Vela inference failed: {error:#}"); + RequestError::internal() +} + +pub fn router(engine: Arc) -> Router { + Router::new() + .route("/health", get(|| async { Json(json!({"status": "ok"})) })) + .route("/ready", get(|| async { Json(json!({"ready": true})) })) + .route("/v1/systemone", post(system_one)) + .fallback(|| async { rejection(RequestError::detail(404, "unknown route")) }) + .with_state(engine) +} + +async fn system_one(State(engine): State>, request: Request) -> Response { + let Some(content_type) = request + .headers() + .get(header::CONTENT_TYPE) + .and_then(|v| v.to_str().ok()) + else { + return rejection(RequestError::detail( + 415, + "Content-Type must be application/json", + )); + }; + if !content_type + .split(';') + .next() + .is_some_and(|v| v.trim().eq_ignore_ascii_case("application/json")) + { + return rejection(RequestError::detail( + 415, + "Content-Type must be application/json", + )); + } + if request + .headers() + .get(header::CONTENT_LENGTH) + .and_then(|v| v.to_str().ok()) + .and_then(|v| v.parse::().ok()) + .is_some_and(|n| n > contract::MAX_BODY as u64) + { + return rejection(RequestError::detail( + 413, + "request exceeds the 8 MiB body limit", + )); + } + let raw = match tokio::time::timeout( + Duration::from_secs(15), + to_bytes(request.into_body(), contract::MAX_BODY), + ) + .await + { + Ok(Ok(raw)) => raw, + Ok(Err(error)) + if std::error::Error::source(&error) + .is_some_and(|source| source.is::()) => + { + return rejection(RequestError::detail( + 413, + "request exceeds the 8 MiB body limit", + )); + } + Ok(Err(_)) => return rejection(RequestError::detail(400, "incomplete body")), + Err(_) => return rejection(RequestError::detail(408, "request body timed out")), + }; + match engine.decide(&raw).await { + Ok(value) => Json(value).into_response(), + Err(error) => rejection(error), + } +} + +fn rejection(error: RequestError) -> Response { + ( + StatusCode::from_u16(error.status).expect("valid Vela status"), + Json(error.body), + ) + .into_response() +} diff --git a/tests/vela/native_pipeline.rs b/tests/vela/native_pipeline.rs new file mode 100644 index 00000000..7d9af6c5 --- /dev/null +++ b/tests/vela/native_pipeline.rs @@ -0,0 +1,75 @@ +//! Opt-in capture of actual CUDA readouts through the production typed pipeline. + +use std::{fs, path::PathBuf, time::Instant}; + +use omni_vela_native::{ + bundle::Bundle, contract, executor::Executor, processing::Processor, scoring::Calibration, +}; +use serde_json::{Value, json}; + +#[test] +#[ignore = "requires pinned Vela 0.8B bundle, CUDA and a manifest of request files"] +fn complete_cuda_pipeline_captures_typed_responses_and_raw_logits() { + let bundle = PathBuf::from(std::env::var_os("VELA_NATIVE_BUNDLE").unwrap()); + let anchor = std::env::var("VELA_NATIVE_MANIFEST_SHA256").unwrap(); + let lib = PathBuf::from(std::env::var_os("VELA_CUDA_LIB").unwrap()); + let cases: Vec<(String, PathBuf)> = serde_json::from_slice( + &fs::read(std::env::var_os("VELA_PIPELINE_CASES").unwrap()).unwrap(), + ) + .unwrap(); + let out = PathBuf::from(std::env::var_os("VELA_PIPELINE_OUTPUT").unwrap()); + fs::create_dir(&out).unwrap(); + let name = Bundle::load(&bundle, &anchor) + .unwrap() + .model_name() + .to_owned(); + let processor = Processor::load(&bundle, &anchor).unwrap(); + let calibration = Calibration::load(&bundle, &anchor).unwrap(); + let mut executor = Executor::load(&bundle, &lib, &anchor).unwrap(); + + let mut failed = Vec::new(); + for (case, path) in cases { + let started = Instant::now(); + println!("{case}: start"); + let request = fs::read(path).unwrap(); + let body = contract::compile(&request, &name).expect("capture case admits"); + let planned = processor.plan(&body).expect("capture case plans"); + let mut rows: Vec> = + vec![None; planned.rows.len() + planned.window_rows.len()]; + let result = executor.execute(&name, &planned, &calibration, |row, logits| { + assert!( + rows[row] + .replace(serde_json::to_value(logits).unwrap()) + .is_none(), + "duplicate row" + ); + }); + let response = match result { + Ok(response) => { + assert!(rows.iter().all(Option::is_some), "missing row"); + json!({"status": 200, "response": response}) + } + Err(error) => { + failed.push(case.clone()); + json!({"status": 500, "error": format!("{error:#}")}) + } + }; + let output = json!({ + "request": body, "response": response, + "plan": planned.plan, "predict_request": planned.predict_request, + "rows": planned.rows, "window_rows": planned.window_rows, + "logits": rows, "wall_seconds": started.elapsed().as_secs_f64() + }); + fs::write( + out.join(format!("{case}.json")), + serde_json::to_vec(&output).unwrap(), + ) + .unwrap(); + println!( + "{case}: status {} in {:?}", + response["status"], + started.elapsed() + ); + } + assert!(failed.is_empty(), "failed cases: {failed:?}"); +} diff --git a/tests/vela/native_response.rs b/tests/vela/native_response.rs index bf62882c..cb81bc4c 100644 --- a/tests/vela/native_response.rs +++ b/tests/vela/native_response.rs @@ -575,3 +575,27 @@ fn response_parity_rejects_missing_spans() { ); } } + +#[test] +fn response_finishing_keeps_wire_field_order_for_part_spans() { + let plan = json!({"qid": "pii", "type": "span", "range": null, "part": "user"}); + let prediction = json!({ + "id": "pii", "type": "span", "head": "router", "threshold": 0.15, + "spans": [{"start": 1, "end": 3, "label": "PERSON", "probability": 0.7, "text": "😀李"}] + }); + let got = system_one_response( + "m", + &[plan], + &[prediction], + &HashMap::new(), + &HashMap::new(), + 42, + ) + .unwrap(); + let span = got["spans"]["pii"][0].as_object().unwrap(); + assert_eq!( + span.keys().map(String::as_str).collect::>(), + ["label", "start", "end", "text", "probability"] + ); + assert_eq!(span["text"], "😀李"); +} diff --git a/tests/vela/native_row_limits.rs b/tests/vela/native_row_limits.rs index 776e13f6..6bdd9fc4 100644 --- a/tests/vela/native_row_limits.rs +++ b/tests/vela/native_row_limits.rs @@ -235,3 +235,36 @@ fn an_oversized_window_rejects_even_when_the_primary_row_fits() { ); rejected(processor.plan(&body)); } + +#[test] +fn mixed_window_rows_only_render_their_span_question() { + let processor = processor(); + let plan = planned( + &processor, + &body( + 2_300, + json!({ + "topic": question("noul", 1), + "first": question("span", 1), + "second": question("span", 2), + }), + ), + ); + assert_eq!(plan.rows.len(), 2); + assert_eq!(plan.spans.len(), 2); + let first = plan.spans[0].as_ref().unwrap(); + let second = plan.spans[1].as_ref().unwrap(); + assert_eq!(first.qid, "first"); + assert_eq!(second.qid, "second"); + assert!(!first.windows.is_empty() && !second.windows.is_empty()); + assert_eq!(first.windows.start, 0); + assert_eq!(first.windows.end, second.windows.start); + assert_eq!(second.windows.end, plan.window_rows.len()); + assert!(matches!( + plan.rows[0].blocks.as_slice(), + [Block::Question { .. }, Block::Span { .. }] + )); + for window in plan.window_rows { + assert!(matches!(window.blocks.as_slice(), [Block::Span { .. }])); + } +}