STRA-338: integrate the kar-off-ab branch (GGUF-PLE profile, replay smoke) into the hexagonal base so backend.rs can be split on top of it

This commit is contained in:
Pavlo Ratushnyi
2026-11-05 18:24:17 +01:00
1346 changed files with 191093 additions and 179408 deletions
+2
View File
@@ -5,6 +5,8 @@ name: Product
# tests of leleka-deploy, leleka-memory, leleka-runtime-client, leleka-runtime or leleka-cuda-driver, or compiled the six release
# binaries. This job runs `scripts/check-local.sh --product`, the same command a developer runs locally:
# - scripts/check-ci-coverage.py: fails when a workspace member (or default-member) has no entry in scripts/ci-coverage.json
# - scripts/check-architecture.py: dependency direction between layers, adapter edges, no new .rs over 400 lines, source ratchets
# (architecture.json is the policy, architecture-baseline.json the debt that may only fall; self-tests in check_architecture_test.py)
# - cargo build --locked (every default-member) and the release build of leleka, strata-next, leleka-inference, leleka-daemon,
# leleka-cli, leleka-seal-exec (docs/deploy.md section 8)
# - cargo check of the CUDA-feature crates (leleka-cuda-driver --features cuda-driver, leleka-runtime)
+1
View File
@@ -16,6 +16,7 @@ Read `PROJECT_CHARTER.md` before changing architecture, performance policy, or s
- For non-lossy changes, compare greedy output or tensor values against the defined baseline and record numerical tolerances.
- Do not label a change as a performance improvement without paired A/B measurements on the same workload and a quality result. Record hardware, software, model digest, configuration, cache state, token counts, and distributions as required by the charter.
- Do not conflate a synthetic kernel gain with an end-to-end agent workload gain. Report both when relevant.
- Dependency direction, file sizes and source patterns are gated by `scripts/check-architecture.py` (policy `architecture.json`, debt `architecture-baseline.json`, run by `scripts/check-local.sh --product`). A number in the baseline may only fall; lower it with `--update-baseline`, never raise it without `--allow-increase` and a reason in review.
- Keep the Strata upstream commit and local changes traceable. Do not overwrite or silently replace the upstream provenance record.
## Repository state
Generated
+30 -5
View File
@@ -1281,6 +1281,7 @@ dependencies = [
"leleka-gguf",
"leleka-gptoss",
"leleka-tokenizer",
"leleka-worker-protocol",
]
[[package]]
@@ -1319,6 +1320,20 @@ dependencies = [
"serde_json",
]
[[package]]
name = "leleka-gateway-text"
version = "0.1.0"
dependencies = [
"hex",
"minijinja",
"minijinja-contrib",
"regex",
"regex-syntax",
"serde",
"serde_json",
"sha2",
]
[[package]]
name = "leleka-gguf"
version = "0.1.0"
@@ -1438,12 +1453,19 @@ dependencies = [
name = "leleka-native-cpu-expert"
version = "0.1.0"
dependencies = [
"leleka-cuda-driver",
"leleka-libc-shim",
"sha2",
"windows-sys 0.61.2",
]
[[package]]
name = "leleka-native-parity-bench"
version = "0.1.0"
dependencies = [
"leleka-cuda-driver",
"leleka-native-cpu-expert",
]
[[package]]
name = "leleka-npu-service"
version = "0.1.0"
@@ -1562,6 +1584,10 @@ dependencies = [
"serde_json",
]
[[package]]
name = "leleka-worker-protocol"
version = "0.1.0"
[[package]]
name = "libc"
version = "0.2.190"
@@ -2767,6 +2793,7 @@ dependencies = [
"http-body-util",
"jsonschema",
"leleka-backend-api",
"leleka-gateway-text",
"leleka-gguf",
"leleka-harmony",
"leleka-kar-codec",
@@ -2779,6 +2806,7 @@ dependencies = [
"leleka-sampler-ref",
"leleka-serving-policy",
"leleka-tokenizer",
"leleka-worker-protocol",
"libc",
"minijinja",
"minijinja-contrib",
@@ -2805,17 +2833,14 @@ dependencies = [
"hex",
"jsonschema",
"leleka-backend-api",
"leleka-gateway-text",
"leleka-obs",
"leleka-runtime",
"leleka-runtime-client",
"leleka-sampler-ref",
"leleka-serving-policy",
"minijinja",
"minijinja-contrib",
"prost",
"protoc-bin-vendored",
"regex",
"regex-syntax",
"reqwest",
"rustix",
"serde",
+2 -2
View File
@@ -1,7 +1,7 @@
[workspace]
resolver = "3"
members = ["crates/backend-api", "crates/cpu-kernels", "crates/cpu-sys", "crates/cpu-worker", "crates/gguf", "crates/gptoss", "crates/gptoss-igpu", "crates/harmony", "crates/igpu", "crates/kar-codec", "crates/igpu-worker", "crates/shm", "crates/openvino", "crates/npu-service", "crates/gptoss-npu", "crates/npu-worker", "crates/gpu-npu-worker", "crates/tokenizer", "control-plane", "desktop-core", "crates/libc-shim", "crates/runtime-client", "crates/model-format", "crates/offline-tools", "crates/quant-core", "crates/context", "crates/cuda-driver", "crates/leleka-runtime", "crates/leleka-memory", "crates/deploy", "crates/obs", "crates/native-cpu-expert", "crates/sampler-ref", "crates/experimental-ref", "crates/serving-policy"]
default-members = ["crates/backend-api", "crates/cpu-kernels", "crates/cpu-sys", "crates/cpu-worker", "crates/gguf", "crates/gptoss", "crates/gptoss-igpu", "crates/harmony", "crates/igpu", "crates/kar-codec", "crates/igpu-worker", "crates/shm", "crates/openvino", "crates/npu-service", "crates/gptoss-npu", "crates/npu-worker", "crates/gpu-npu-worker", "crates/tokenizer", "control-plane", "desktop-core", "crates/runtime-client", "crates/model-format", "crates/offline-tools", "crates/quant-core", "crates/context", "crates/leleka-memory", "crates/sampler-ref", "crates/experimental-ref", "crates/serving-policy", "crates/deploy", "crates/obs"]
members = ["crates/backend-api", "crates/worker-protocol", "crates/cpu-kernels", "crates/cpu-sys", "crates/cpu-worker", "crates/gguf", "crates/gptoss", "crates/gptoss-igpu", "crates/harmony", "crates/igpu", "crates/kar-codec", "crates/igpu-worker", "crates/shm", "crates/openvino", "crates/npu-service", "crates/gptoss-npu", "crates/npu-worker", "crates/gpu-npu-worker", "crates/tokenizer", "crates/gateway-text", "control-plane", "desktop-core", "crates/libc-shim", "crates/runtime-client", "crates/model-format", "crates/offline-tools", "crates/quant-core", "crates/context", "crates/cuda-driver", "crates/leleka-runtime", "crates/leleka-memory", "crates/deploy", "crates/obs", "crates/native-cpu-expert", "crates/native-parity-bench", "crates/sampler-ref", "crates/experimental-ref", "crates/serving-policy"]
default-members = ["crates/backend-api", "crates/worker-protocol", "crates/cpu-kernels", "crates/cpu-sys", "crates/cpu-worker", "crates/gguf", "crates/gptoss", "crates/gptoss-igpu", "crates/harmony", "crates/igpu", "crates/kar-codec", "crates/igpu-worker", "crates/shm", "crates/openvino", "crates/npu-service", "crates/gptoss-npu", "crates/npu-worker", "crates/gpu-npu-worker", "crates/tokenizer", "crates/gateway-text", "control-plane", "desktop-core", "crates/runtime-client", "crates/model-format", "crates/offline-tools", "crates/quant-core", "crates/context", "crates/leleka-memory", "crates/sampler-ref", "crates/experimental-ref", "crates/serving-policy", "crates/deploy", "crates/obs"]
[workspace.package]
edition = "2024"
+206
View File
@@ -0,0 +1,206 @@
{
"_comment": "Debt that exists today. Every number may only fall (scripts/check-architecture.py --update-baseline refuses to raise one). Do not edit by hand; regenerate. Policy: architecture.json.",
"violations": [
"forbidden-dep leleka-memory libc",
"forbidden-dep leleka-memory windows-sys"
],
"oversize": {
"control-plane/examples/cp_replay.rs": 946,
"control-plane/src/config/impl_config/impl_config_2_2.rs": 434,
"control-plane/src/ggml_bridge/tests.rs": 1286,
"control-plane/src/gguf_f32_stream/tests.rs": 909,
"control-plane/src/main.rs": 1156,
"control-plane/src/prepare_preview/tests.rs": 808,
"control-plane/src/prometheus.rs": 441,
"control-plane/src/responses/tests.rs": 2961,
"control-plane/src/service_install.rs": 436,
"control-plane/src/vision.rs": 402,
"control-plane/src/worker.rs": 1271,
"control-plane/tests/backend_worker_http.rs": 1832,
"control-plane/tests/mcp_hub.rs": 444,
"control-plane/tests/memory_gate_http.rs": 464,
"control-plane/tests/tool_corpus.rs": 464,
"control-plane/tests/vision_http.rs": 602,
"crates/backend-api/src/lib.rs": 756,
"crates/context/tests/rope_plan_golden.rs": 412,
"crates/cpu-kernels/src/lib.rs": 464,
"crates/cpu-sys/src/lib.rs": 1007,
"crates/cpu-sys/src/simd.rs": 1503,
"crates/cpu-worker/tests/serve_loop.rs": 477,
"crates/cuda-driver/src/api.rs": 423,
"crates/cuda-driver/src/closed_kernels/tests.rs": 405,
"crates/cuda-driver/src/experimental.rs": 407,
"crates/cuda-driver/src/ffi.rs": 1897,
"crates/cuda-driver/src/gdn_native_batch.rs": 557,
"crates/cuda-driver/src/gdn_prompt_device/impl_originalgdnpromptdevice/impl_originalgdnpromptdevice_2_2.rs": 618,
"crates/cuda-driver/src/lib.rs": 3508,
"crates/cuda-driver/src/mmq_resident_gpu.rs": 517,
"crates/cuda-driver/src/moe_prefill_batch.rs": 476,
"crates/cuda-driver/src/mtp_original_full_forward/impl_originalmtpfullforward_2/impl_originalmtpfullforward.rs": 621,
"crates/cuda-driver/src/mtp_original_full_symbols.rs": 445,
"crates/cuda-driver/src/mtp_original_int8_ffi.rs": 543,
"crates/cuda-driver/src/mtp_original_prefill/impl_originalmtpprefill/impl_originalmtpprefill_4.rs": 676,
"crates/cuda-driver/src/mtp_original_scalar_prefill/impl_originalmtpscalarprefill/impl_originalmtpscalarprefill_4.rs": 622,
"crates/cuda-driver/src/native_head.rs": 533,
"crates/cuda-driver/src/original_gpu_schedule_ffi.rs": 454,
"crates/cuda-driver/src/original_mtp_rt/tests.rs": 435,
"crates/cuda-driver/src/original_verify_window_gr/tests.rs": 506,
"crates/cuda-driver/src/original_verify_window_moe/tests.rs": 720,
"crates/cuda-driver/src/original_verify_window_planner/tests.rs": 411,
"crates/cuda-driver/src/original_verify_window_qsa/tests.rs": 652,
"crates/cuda-driver/src/ple_batch_ffi.rs": 625,
"crates/cuda-driver/src/prefill_stage_gdn_gpu.rs": 420,
"crates/cuda-driver/src/qwen_dispatch.rs": 2003,
"crates/cuda-driver/src/qwen_ffi.rs": 1696,
"crates/cuda-driver/src/sm86_table.rs": 933,
"crates/cuda-driver/tests/mock_driver.rs": 1560,
"crates/cuda-driver/tests/original_serve_preflight_probe.rs": 784,
"crates/cuda-driver/tests/projection_family_mock.rs": 721,
"crates/cuda-driver/tests/q6_mock.rs": 463,
"crates/deploy/src/app.rs": 1481,
"crates/deploy/src/bin/fake_runtime.rs": 426,
"crates/deploy/src/cli/tests.rs": 407,
"crates/deploy/src/config.rs": 735,
"crates/deploy/src/expert_profile/tests.rs": 484,
"crates/deploy/src/facts.rs": 430,
"crates/deploy/src/plan.rs": 1470,
"crates/deploy/src/preflight/evaluate_fn.rs": 670,
"crates/deploy/src/preflight/tests.rs": 475,
"crates/deploy/src/profile.rs": 982,
"crates/deploy/src/reconfigure/tests.rs": 599,
"crates/deploy/src/resources.rs": 944,
"crates/deploy/src/sealed.rs": 592,
"crates/deploy/src/supervisor.rs": 1849,
"crates/deploy/tests/e2e.rs": 2118,
"crates/experimental-ref/tests/emulated_kernels.rs": 467,
"crates/gateway-text/src/prompt/tests.rs": 492,
"crates/gateway-text/src/tool_output/tests.rs": 654,
"crates/gguf/src/lib.rs": 560,
"crates/gguf/tests/synthetic.rs": 460,
"crates/gptoss-igpu/src/lib.rs": 524,
"crates/gptoss-npu/src/lib.rs": 809,
"crates/gptoss/src/lib.rs": 1788,
"crates/gptoss/tests/synthetic_model.rs": 922,
"crates/igpu/src/lib.rs": 1386,
"crates/igpu/src/shaders.rs": 440,
"crates/leleka-memory/src/lock.rs": 432,
"crates/leleka-runtime/src/backend.rs": 3770,
"crates/leleka-runtime/src/backend_original_serve.rs": 1115,
"crates/leleka-runtime/src/conversation/cache/tests.rs": 407,
"crates/leleka-runtime/src/conversation/manager_tests.rs": 1129,
"crates/leleka-runtime/src/conversation/snapshot_tests.rs": 1596,
"crates/leleka-runtime/src/gpu_proofs/backend_original_serve_memory_smoke.rs": 851,
"crates/leleka-runtime/src/gpu_proofs/backend_original_serve_prefix_smoke.rs": 447,
"crates/leleka-runtime/src/gpu_proofs/backend_original_serve_smoke.rs": 979,
"crates/leleka-runtime/src/gpu_proofs/native_down_candidate_only.rs": 1648,
"crates/leleka-runtime/src/gpu_proofs/native_down_public_pair.rs": 540,
"crates/leleka-runtime/src/model_binding/qwen4exp_kar_ple.rs": 1026,
"crates/leleka-runtime/src/model_binding/qwen4exp_mtp.rs": 1124,
"crates/leleka-runtime/src/prefix_cache/store/tests.rs": 582,
"crates/leleka-runtime/src/qwen_forward/executor_prefill_chunk/impl_qwenforward/impl_qwenforward_3.rs": 980,
"crates/leleka-runtime/src/qwen_forward/executor_prefill_chunk/prepare_micro_ffn_rows_fn.rs": 466,
"crates/leleka-runtime/src/qwen_forward/gr.rs": 1036,
"crates/leleka-runtime/src/qwen_forward/kar_ple_cache.rs": 730,
"crates/leleka-runtime/src/qwen_forward/mtp_decoder_batch_gpu/check_loaded_fn.rs": 454,
"crates/leleka-runtime/src/qwen_forward/original_serve_engine/tests.rs": 668,
"crates/leleka-runtime/src/qwen_forward/original_serve_prefix/tests.rs": 674,
"crates/leleka-runtime/src/qwen_forward/original_spec_controller/tests.rs": 813,
"crates/leleka-runtime/src/qwen_forward/session/tests.rs": 538,
"crates/model-format/src/gguf.rs": 1099,
"crates/model-format/src/ple_reader/tests.rs": 750,
"crates/model-format/src/qwen4exp.rs": 625,
"crates/model-format/tests/kar_extents.rs": 532,
"crates/model-format/tests/kar_kernel_model/mod.rs": 942,
"crates/model-format/tests/kar_levels/mod.rs": 545,
"crates/model-format/tests/kar_ple/mod.rs": 765,
"crates/model-format/tests/qwen_artifact_binding/fixtures.rs": 475,
"crates/model-format/tests/qwen_artifact_binding/mod.rs": 1098,
"crates/model-format/tests/qwen_rows_sdet/mod.rs": 443,
"crates/native-cpu-expert/examples/kernel_ab.rs": 3347,
"crates/obs/src/lib.rs": 603,
"crates/openvino/src/lib.rs": 676,
"crates/quant-core/src/iq2s_grid.rs": 1032,
"crates/runtime-client/tests/grpc_backend.rs": 689,
"crates/shm/src/lib.rs": 432,
"crates/tokenizer/src/lib.rs": 840,
"desktop-core/src/bin/leleka-inference.rs": 1487,
"desktop-core/src/runtime_rpc/impl_proto_runtime_server_runtime.rs": 463,
"desktop-core/src/runtime_rpc/tests.rs": 628,
"desktop-core/tests/api_over_runtime.rs": 638,
"desktop-core/tests/gateway.rs": 403,
"desktop-core/tests/managed_worker.rs": 500,
"desktop-core/tests/native_tools_retry_sdet.rs": 552,
"desktop-core/tests/native_tools_sdet.rs": 543,
"desktop-core/tests/runtime_gateway_sdet.rs": 563
},
"source": {
"dyn-trait:leleka-backend-api": 1,
"dyn-trait:leleka-cpu-worker": 4,
"dyn-trait:leleka-cuda-driver": 51,
"dyn-trait:leleka-deploy": 17,
"dyn-trait:leleka-experimental-ref": 3,
"dyn-trait:leleka-gptoss": 10,
"dyn-trait:leleka-gptoss-igpu": 4,
"dyn-trait:leleka-gptoss-npu": 4,
"dyn-trait:leleka-gpu-npu-worker": 6,
"dyn-trait:leleka-memory": 17,
"dyn-trait:leleka-model-format": 8,
"dyn-trait:leleka-runtime": 70,
"dyn-trait:leleka-tokenizer": 2,
"dyn-trait:strata-control": 35,
"dyn-trait:strata-desktop-core": 2,
"env-read:leleka-cpu-kernels": 1,
"env-read:leleka-cpu-worker": 2,
"env-read:leleka-cuda-driver": 130,
"env-read:leleka-deploy": 41,
"env-read:leleka-gateway-text": 2,
"env-read:leleka-gptoss": 6,
"env-read:leleka-gptoss-npu": 1,
"env-read:leleka-gpu-npu-worker": 2,
"env-read:leleka-igpu": 1,
"env-read:leleka-libc-shim": 4,
"env-read:leleka-memory": 3,
"env-read:leleka-model-format": 5,
"env-read:leleka-native-cpu-expert": 19,
"env-read:leleka-native-parity-bench": 1,
"env-read:leleka-npu-service": 1,
"env-read:leleka-npu-worker": 1,
"env-read:leleka-obs": 2,
"env-read:leleka-runtime": 256,
"env-read:leleka-tokenizer": 2,
"env-read:strata-control": 19,
"env-read:strata-desktop-core": 15,
"instant-now:leleka-backend-api": 2,
"instant-now:leleka-cpu-worker": 9,
"instant-now:leleka-cuda-driver": 45,
"instant-now:leleka-deploy": 28,
"instant-now:leleka-gptoss": 4,
"instant-now:leleka-gptoss-igpu": 5,
"instant-now:leleka-gptoss-npu": 13,
"instant-now:leleka-gpu-npu-worker": 4,
"instant-now:leleka-igpu": 1,
"instant-now:leleka-memory": 12,
"instant-now:leleka-model-format": 10,
"instant-now:leleka-native-cpu-expert": 30,
"instant-now:leleka-npu-service": 5,
"instant-now:leleka-runtime": 79,
"instant-now:strata-control": 37,
"instant-now:strata-desktop-core": 15,
"path-include:leleka-cuda-driver": 115,
"path-include:leleka-model-format": 12,
"path-include:leleka-native-cpu-expert": 2,
"path-include:leleka-runtime": 107,
"path-include:strata-desktop-core": 2,
"process-global:leleka-cuda-driver": 110,
"process-global:leleka-gateway-text": 5,
"process-global:leleka-gptoss-npu": 3,
"process-global:leleka-libc-shim": 13,
"process-global:leleka-memory": 10,
"process-global:leleka-model-format": 8,
"process-global:leleka-native-cpu-expert": 32,
"process-global:leleka-obs": 7,
"process-global:leleka-runtime": 114,
"process-global:leleka-tokenizer": 4,
"process-global:strata-control": 14
}
}
+48
View File
@@ -0,0 +1,48 @@
{
"_comment": "Policy read by scripts/check-architecture.py (STRA-338 ADR). Layers are ordered low to high; a normal dependency must point to the same or a lower layer. L2 (core) is reserved: it is empty until the engine/gateway domain crates are extracted (steps S19, S21). Every workspace package appears in exactly one layer.",
"max_lines": 400,
"adapter_layer": "L3",
"pure_layers": ["L0", "L1"],
"forbidden_in_pure": ["tokio", "axum", "tonic", "tonic-prost", "reqwest", "hyper", "libc", "rustix", "windows-sys", "sysinfo", "wgpu"],
"layers": {
"L0": ["leleka-backend-api", "leleka-worker-protocol"],
"L1": [
"leleka-obs", "leleka-context", "leleka-sampler-ref", "leleka-quant-core", "leleka-serving-policy", "leleka-harmony",
"leleka-tokenizer", "leleka-gguf", "leleka-kar-codec", "leleka-experimental-ref", "leleka-cpu-sys", "leleka-cpu-kernels",
"leleka-shm", "leleka-openvino", "leleka-memory", "leleka-gateway-text"
],
"L2": [],
"L3": [
"leleka-libc-shim", "leleka-model-format", "leleka-cuda-driver", "leleka-native-cpu-expert", "leleka-gptoss", "leleka-igpu",
"leleka-gptoss-igpu", "leleka-gptoss-npu", "leleka-npu-service", "leleka-cpu-worker", "leleka-igpu-worker", "leleka-npu-worker",
"leleka-gpu-npu-worker", "leleka-offline-tools", "leleka-runtime-client"
],
"L4": ["leleka-runtime", "strata-desktop-core", "strata-control", "leleka-deploy", "leleka-native-parity-bench"]
},
"adapter_edges": [
["leleka-cuda-driver", "leleka-libc-shim"],
["leleka-cuda-driver", "leleka-model-format"],
["leleka-model-format", "leleka-libc-shim"],
["leleka-native-cpu-expert", "leleka-libc-shim"],
["leleka-cpu-worker", "leleka-gptoss"],
["leleka-gptoss-igpu", "leleka-gptoss"],
["leleka-gptoss-igpu", "leleka-igpu"],
["leleka-gptoss-npu", "leleka-gptoss"],
["leleka-igpu-worker", "leleka-cpu-worker"],
["leleka-igpu-worker", "leleka-gptoss-igpu"],
["leleka-npu-worker", "leleka-cpu-worker"],
["leleka-npu-worker", "leleka-gptoss-npu"],
["leleka-gpu-npu-worker", "leleka-cpu-worker"],
["leleka-gpu-npu-worker", "leleka-gptoss"],
["leleka-gpu-npu-worker", "leleka-gptoss-igpu"],
["leleka-gpu-npu-worker", "leleka-gptoss-npu"],
["leleka-offline-tools", "leleka-model-format"]
],
"source_patterns": [
{"id": "env-read", "regex": "\\benv::var(_os)?\\(", "why": "configuration must be parsed once into a Settings struct (S13), not read all over the code"},
{"id": "instant-now", "regex": "\\bInstant::now\\(\\)", "why": "time must come from an injected Clock in core logic (S14)"},
{"id": "path-include", "regex": "#\\[path\\s*=\\s*\"(?![^\"]*tests\\.rs\")(?![A-Za-z0-9_]+/[A-Za-z0-9_]+\\.rs\")", "why": "a file compiled into two crates must be one crate (S8); a tests.rs or a child module file of the form dir/name.rs is not an include"},
{"id": "process-global", "regex": "\\b(OnceLock|LazyLock|OnceCell)\\b|\\bstatic\\s+mut\\b|Governor::global\\(|serving_cells\\(\\)", "why": "process globals make core logic untestable without a GPU (S14)"},
{"id": "dyn-trait", "regex": "\\bdyn\\s+[A-Z]", "why": "no dynamic dispatch per round or token; dyn is for startup composition only"}
]
}
+2
View File
@@ -15,6 +15,8 @@ axum = "0.8"
futures-core = "0.3"
hex = "0.4"
leleka-gguf = { path = "../crates/gguf" }
leleka-gateway-text = { path = "../crates/gateway-text" }
leleka-worker-protocol = { path = "../crates/worker-protocol" }
leleka-obs = { path = "../crates/obs" }
leleka-kar-codec = { path = "../crates/kar-codec" }
leleka-harmony = { path = "../crates/harmony" }
+7 -560
View File
@@ -53,34 +53,6 @@ pub struct AppState {
pub monitor: Arc<crate::request_monitor::RequestMonitor>,
}
impl Default for AppState {
fn default() -> Self {
Self {
queue_timeout: None,
lifecycle: Default::default(),
api_key: None,
model: None,
worker: Arc::new(RwLock::new(WorkerStatus::default())),
pool: Vec::new(),
tokenizer: None,
generation: None,
response_history: Arc::new(RwLock::new(responses::ResponseHistory::default())),
settings: Arc::new(crate::settings::Settings::default()),
aliases: Arc::new(Vec::new()),
cors: Arc::new(Default::default()),
trusted_origins: Arc::new(Vec::new()),
control: None,
started_at: std::time::SystemTime::now(),
chat_template: None,
mcp: None,
vision: None,
prefix_cache: Arc::new(Default::default()),
memory: Arc::new(Default::default()),
monitor: Arc::new(Default::default()),
}
}
}
#[derive(Serialize)]
struct HealthResponse {
status: &'static str,
@@ -97,540 +69,15 @@ struct StatusResponse {
max_context: Option<usize>,
}
pub fn router(state: AppState) -> Router {
let observe = crate::request_log::Observe {
model: state.model.clone(),
memory: state.memory.clone(),
};
Router::new()
.route("/health", get(health))
.route("/ready", get(ready))
.route("/status", get(status))
.route("/metrics", get(metrics))
.route("/api/health", get(crate::server_api::api_health))
.route("/props", get(crate::server_api::props))
.route("/slots", get(crate::server_api::slots))
.route("/v1/status", get(crate::server_api::v1_status))
.route("/v1/prefix_match", post(crate::server_api::v1_prefix_match))
.route("/v1/reconfigure", post(crate::server_api::v1_reconfigure))
.route("/mcp", get(crate::server_api::mcp_status))
.route(
"/settings",
get(crate::server_api::settings_get).post(crate::server_api::settings_post),
)
.route("/load", post(crate::server_api::load_post))
.route("/unload", post(crate::server_api::unload_post))
.route("/v1/load", post(crate::server_api::v1_load))
.route("/v1/unload", post(crate::server_api::v1_unload))
.route("/models", get(crate::models_api::list))
.route("/v1/models", get(crate::models_api::list))
.route("/v1/models/{id}", get(crate::models_api::retrieve))
.route(
"/v1/responses",
post(responses::create_route)
.layer(middleware::from_fn_with_state(
state.lifecycle.clone(),
crate::lifecycle::admit,
))
.layer(middleware::from_fn_with_state(
state.monitor.clone(),
crate::request_monitor::capture,
))
.layer(middleware::from_fn_with_state(
observe.clone(),
crate::request_log::observe,
)),
)
.route(
"/v1/responses/input_tokens",
post(responses::count_input_tokens).layer(middleware::from_fn_with_state(
state.lifecycle.clone(),
crate::lifecycle::admit,
)),
)
.route(
"/v1/chat/completions",
post(crate::chat::create)
.layer(middleware::from_fn_with_state(
state.lifecycle.clone(),
crate::lifecycle::admit,
))
.layer(middleware::from_fn_with_state(
state.monitor.clone(),
crate::request_monitor::capture,
))
.layer(middleware::from_fn_with_state(
observe.clone(),
crate::request_log::observe,
)),
)
.route(
"/v1/messages/count_tokens",
post(crate::messages::count_tokens)
.layer(middleware::from_fn_with_state(
state.lifecycle.clone(),
crate::lifecycle::admit,
))
.layer(middleware::from_fn(crate::messages::protocol)),
)
.route(
"/v1/messages",
post(crate::messages::create)
.layer(middleware::from_fn_with_state(
state.lifecycle.clone(),
crate::lifecycle::admit,
))
.layer(middleware::from_fn(crate::messages::protocol))
.layer(middleware::from_fn_with_state(
state.monitor.clone(),
crate::request_monitor::capture,
))
.layer(middleware::from_fn_with_state(
observe.clone(),
crate::request_log::observe,
)),
)
.route("/api/requests", get(crate::server_api::api_requests))
.route("/admin/lifecycle", get(lifecycle_status))
.route(
"/v1/responses/{id}",
get(responses::retrieve).delete(responses::delete),
)
.route(
"/v1/responses/{id}/input_items",
get(responses::input_items),
)
.route("/admin/drain", post(drain))
.route("/admin/resume", post(resume))
.fallback(crate::server_api::not_found)
.layer(DefaultBodyLimit::max(16 * 1024 * 1024))
.layer(middleware::from_fn_with_state(
state.api_key.clone(),
crate::auth::authorize,
))
// Outermost: a browser's credential-less preflight is answered before authentication.
.layer(middleware::from_fn_with_state(
state.cors.clone(),
crate::server_api::cors_layer,
))
.with_state(state)
}
async fn health() -> Json<HealthResponse> {
Json(HealthResponse { status: "ok" })
}
async fn lifecycle_status(State(state): State<AppState>) -> Json<serde_json::Value> {
let worker = *state.worker.read().await;
let lifecycle = state.lifecycle.snapshot();
let drained = lifecycle.draining
&& lifecycle.requests_in_flight == 0
&& lifecycle.generation_jobs == 0
&& worker.metrics.active_since.is_none()
&& matches!(
worker.state,
WorkerState::Ready | WorkerState::Unconfigured | WorkerState::Unloaded
);
Json(
serde_json::json!({"service":"strata-control", "server_pid":std::process::id(), "model":state.model,
"draining":lifecycle.draining,
"shutting_down":lifecycle.shutting_down,
"max_in_flight_requests":lifecycle.max_in_flight_requests,
"available_request_slots":lifecycle.max_in_flight_requests.saturating_sub(lifecycle.requests_in_flight),
"requests_in_flight":lifecycle.requests_in_flight, "generation_jobs":lifecycle.generation_jobs,
"drained":drained, "worker":worker.state}),
)
}
fn lifecycle_precondition(headers: &HeaderMap) -> Option<Response> {
let mut values = headers.get_all("x-strata-expected-pid").iter();
let value = values.next()?;
let pid = value
.to_str()
.ok()
.filter(|s| !s.is_empty() && s.bytes().all(|b| b.is_ascii_digit()))
.and_then(|s| s.parse::<u32>().ok())
.filter(|n| *n > 0);
if values.next().is_some() || pid.is_none() {
return Some((StatusCode::BAD_REQUEST, Json(serde_json::json!({"error":{"code":"invalid_expected_pid","message":"expected PID must be one positive integer"}}))).into_response());
}
if pid != Some(std::process::id()) {
return Some((StatusCode::CONFLICT, Json(serde_json::json!({"error":{"code":"process_identity_changed","message":"native process no longer matches expected PID; admission unchanged"}}))).into_response());
}
None
}
async fn drain(State(state): State<AppState>, headers: HeaderMap) -> Response {
if let Some(response) = lifecycle_precondition(&headers) {
return response;
}
state.lifecycle.set_draining(true);
lifecycle_status(State(state)).await.into_response()
}
async fn resume(State(state): State<AppState>, headers: HeaderMap) -> Response {
if let Some(response) = lifecycle_precondition(&headers) {
return response;
}
state.lifecycle.set_draining(false);
lifecycle_status(State(state)).await.into_response()
}
/// `GET /metrics`: the native JSON document, or its Prometheus text exposition (`?format=prometheus`, or an `Accept` that asks
/// for `text/plain` / OpenMetrics, as a Prometheus scraper sends). `?requests=all` lists every kept generation, not the last 12.
async fn metrics(
State(state): State<AppState>,
RawQuery(query): RawQuery,
headers: HeaderMap,
) -> Response {
let accept = headers
.get(axum::http::header::ACCEPT)
.and_then(|v| v.to_str().ok());
let all = query
.as_deref()
.is_some_and(|q| q.split('&').any(|pair| pair == "requests=all"));
let document = metrics_document(&state, all).await;
if crate::prometheus::wanted(query.as_deref(), accept) {
let mut response = crate::prometheus::render(&document).into_response();
response.headers_mut().insert(
axum::http::header::CONTENT_TYPE,
axum::http::HeaderValue::from_static(crate::prometheus::CONTENT_TYPE),
);
return response;
}
Json(document).into_response()
}
/// The generations shown by default in `requests` (the Python Monitor shows twelve).
const RECENT_REQUESTS: usize = 12;
/// The `/metrics` document. `schema_version` stays 1: the members below `generation` are the Python Monitor's
/// (`engine`, `live`, `requests`, `requests_kept`, `totals`, `hardware`, `hardware_static`, `history`, `time`) and were added
/// beside the native ones, which are unchanged.
pub async fn metrics_document(state: &AppState, all_requests: bool) -> serde_json::Value {
let worker = *state.worker.read().await;
let generation = worker.metrics;
let lifecycle = state.lifecycle.snapshot();
let queue_capacity = state.generation.as_ref().map(mpsc::Sender::max_capacity);
let queue_used = state
.generation
.as_ref()
.map(|sender| sender.max_capacity() - sender.capacity());
let memory = state.memory.status();
let (hardware, hardware_static, telemetry, history) = state.memory.hardware();
let busy = generation.active_since.is_some();
let phase = telemetry["phase"].as_str();
let engine_state = if worker.state != WorkerState::Ready {
serde_json::to_value(worker.state).unwrap_or(serde_json::Value::Null)
} else if busy {
serde_json::json!(if phase == Some("prefill") {
"reading"
} else {
"generating"
})
} else {
serde_json::json!("idle")
};
let elapsed_ms = generation
.active_since
.map(|start| start.elapsed().as_millis().min(u64::MAX as u128) as u64);
let live = serde_json::json!({
"state": engine_state,
"active": busy,
"queued": lifecycle.generation_jobs.saturating_sub(usize::from(busy)),
"phase": if busy { phase.map_or(serde_json::Value::Null, |p| serde_json::json!(p)) } else { serde_json::Value::Null },
"prompt_tokens": if busy { telemetry["request"]["prompt_tokens"].clone() } else { serde_json::Value::Null },
"generated": if busy { telemetry["request"]["generated_tokens"].clone() } else { serde_json::Value::Null },
"elapsed_s": elapsed_ms.map(|ms| (ms as f64 / 100.0).round() / 10.0),
"tok_s": if busy { hardware["tok_s"].clone() } else { serde_json::Value::Null },
"tok_s_mean": if busy { hardware["tok_s_mean"].clone() } else { serde_json::Value::Null },
"prefill_tok_s_mean": if busy { hardware["prefill_tok_s_mean"].clone() } else { serde_json::Value::Null },
"prompt_read": null, "prompt_total": null, "max_tokens": null, "tok_s_window_s": null,
});
let engine = serde_json::json!({
"model": state.model, "max_context": worker.max_context.or(worker.known_max_context),
"images": state.vision.is_some(), "version": env!("CARGO_PKG_VERSION"),
"api_monitor": state.monitor.enabled(),
"settings": telemetry["settings"].clone(),
});
let (requests, requests_kept, totals) = match generation.history {
Some(history) => (
history.requests((!all_requests).then_some(RECENT_REQUESTS)),
history.kept(),
history.totals(),
),
None => (Vec::new(), 0, serde_json::Value::Null),
};
serde_json::json!({
"schema_version": 1,
"scope": "control_plane_process",
"model": state.model,
"worker": worker.state,
"up": worker.state == WorkerState::Ready,
"active": busy,
"active_elapsed_ms": elapsed_ms,
"queue_capacity": queue_capacity,
"queue_used": queue_used,
"memory": {
"level": memory["gate"]["level"].clone(),
"gate_rejections": state.memory.gate_rejections(),
"available_bytes": memory["gate"]["available_bytes"].clone(),
},
"generation": generation,
"done_decode_tokens_per_second": crate::metrics::token_rate(generation.done_generated_tokens, generation.done_decode_ms),
"engine": engine,
"live": live,
"requests": requests,
"requests_kept": requests_kept,
"totals": totals,
"api_uptime_s": state.started_at.elapsed().map_or(0, |d| d.as_secs()),
"supervisor": supervisor_block(),
"hardware": hardware,
"hardware_static": hardware_static,
"history": history,
"telemetry": telemetry,
"time": std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map_or(0.0, |d| d.as_secs_f64()),
})
}
/// The supervisor's own account (`LELEKA_STATUS_FILE`, set by `leleka run`): restarts and uptime of the service. `null` when this
/// process was not started by a supervisor, or the file cannot be read.
fn supervisor_block() -> serde_json::Value {
let Some(path) = std::env::var_os("LELEKA_STATUS_FILE") else {
return serde_json::Value::Null;
};
let Ok(text) = std::fs::read_to_string(path) else {
return serde_json::Value::Null;
};
let Ok(status) = serde_json::from_str::<serde_json::Value>(&text) else {
return serde_json::Value::Null;
};
let now = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map_or(0, |d| d.as_secs());
serde_json::json!({
"phase": status["phase"],
"restarts_total": status["restarts_total"],
"uptime_s": status["started_unix"].as_u64().map(|started| now.saturating_sub(started)),
"last_restart_reason": status["last_restart_reason"],
})
}
async fn ready(State(state): State<AppState>) -> (StatusCode, Json<StatusResponse>) {
let worker = *state.worker.read().await;
let inference_ready = worker.state == WorkerState::Ready
&& pool_ready(&state).await
&& state.tokenizer.is_some()
&& state.generation.is_some()
&& !state.lifecycle.snapshot().draining;
let code = if inference_ready {
StatusCode::OK
} else {
StatusCode::SERVICE_UNAVAILABLE
};
(
code,
Json(status_body(worker, inference_ready, state.model)),
)
}
async fn status(State(state): State<AppState>) -> Json<StatusResponse> {
let worker = *state.worker.read().await;
let inference_ready = worker.state == WorkerState::Ready
&& pool_ready(&state).await
&& state.tokenizer.is_some()
&& state.generation.is_some()
&& !state.lifecycle.snapshot().draining;
Json(status_body(worker, inference_ready, state.model))
}
/// Every member of a worker pool is ready (true without a pool).
async fn pool_ready(state: &AppState) -> bool {
for member in &state.pool {
if member.read().await.state != WorkerState::Ready {
return false;
}
}
true
}
fn status_body(
worker: WorkerStatus,
inference_ready: bool,
model: Option<String>,
) -> StatusResponse {
StatusResponse {
service: "strata-control",
server_pid: std::process::id(),
model,
version: env!("CARGO_PKG_VERSION"),
worker: worker.state,
ready: inference_ready,
max_context: worker.max_context,
}
}
#[cfg(test)]
mod tests {
use super::*;
mod tests;
#[tokio::test]
async fn conditional_admission_rejects_stale_or_ambiguous_pid_before_mutation() {
let state = AppState::default();
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
let url = format!("http://{}", listener.local_addr().unwrap());
let router = router(state.clone());
let server = tokio::spawn(async move { axum::serve(listener, router).await });
let client = reqwest::Client::new();
for (path, initial) in [("drain", false), ("resume", true)] {
state.lifecycle.set_draining(initial);
for (value, status) in [
("0".to_string(), 400),
("bad".into(), 400),
((std::process::id() + 1).to_string(), 409),
] {
let response = client
.post(format!("{url}/admin/{path}"))
.header("x-strata-expected-pid", value)
.send()
.await
.unwrap();
assert_eq!(response.status().as_u16(), status);
assert_eq!(state.lifecycle.snapshot().draining, initial);
}
let duplicate = client
.post(format!("{url}/admin/{path}"))
.header("x-strata-expected-pid", std::process::id())
.header("x-strata-expected-pid", std::process::id())
.send()
.await
.unwrap();
assert_eq!(duplicate.status(), StatusCode::BAD_REQUEST);
assert_eq!(state.lifecycle.snapshot().draining, initial);
let response = client
.post(format!("{url}/admin/{path}"))
.header("x-strata-expected-pid", std::process::id())
.send()
.await
.unwrap();
assert_eq!(response.status(), StatusCode::OK);
let value: serde_json::Value =
serde_json::from_str(&response.text().await.unwrap()).unwrap();
assert_eq!(value["server_pid"], std::process::id());
assert_eq!(value["service"], "strata-control");
assert_eq!(value["draining"], !initial);
}
server.abort();
let _ = server.await;
}
#[tokio::test]
async fn drain_rejects_new_requests_before_json_parsing_and_resume_is_idempotent() {
let state = AppState::default();
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
let url = format!("http://{}", listener.local_addr().unwrap());
let router = router(state.clone());
let server = tokio::spawn(async move { axum::serve(listener, router).await });
let client = reqwest::Client::new();
for _ in 0..2 {
let response = client
.post(format!("{url}/admin/drain"))
.send()
.await
.unwrap();
let data: serde_json::Value =
serde_json::from_str(&response.text().await.unwrap()).unwrap();
assert_eq!(data["draining"], true);
assert_eq!(data["drained"], true);
}
let response = client
.post(format!("{url}/v1/responses"))
.header("content-type", "application/json")
.body("invalid json")
.send()
.await
.unwrap();
assert_eq!(response.status(), StatusCode::SERVICE_UNAVAILABLE);
assert!(response.text().await.unwrap().contains("runtime_draining"));
assert_eq!(state.lifecycle.snapshot().requests_in_flight, 0);
let job = state.lifecycle.generation();
assert_eq!(
lifecycle_status(State(state.clone())).await.0["drained"],
false
);
drop(job);
state.worker.write().await.state = WorkerState::Restarting;
assert_eq!(
lifecycle_status(State(state.clone())).await.0["drained"],
false
);
for _ in 0..2 {
let response = client
.post(format!("{url}/admin/resume"))
.send()
.await
.unwrap();
assert_eq!(response.status(), StatusCode::OK);
}
let response = client
.post(format!("{url}/v1/responses"))
.header("content-type", "application/json")
.body("invalid json")
.send()
.await
.unwrap();
assert_eq!(response.status(), StatusCode::BAD_REQUEST);
let _ = response.text().await.unwrap();
server.abort();
}
#[tokio::test]
async fn metrics_expose_activity_without_changing_discovery() {
let (sender, mut receiver) = mpsc::channel(2);
let state = AppState {
generation: Some(sender.clone()),
..Default::default()
};
let initial_status = serde_json::to_value(status(State(state.clone())).await.0).unwrap();
let initial_metrics = metrics_document(&state, false).await;
assert_eq!(initial_metrics["active"], false);
assert!(initial_metrics["done_decode_tokens_per_second"].is_null());
let (result, _rx) = tokio::sync::oneshot::channel();
sender
.send(GenerationCommand {
queue: None,
activity: None,
request: crate::wire::Generate {
token_ids: vec![10],
max_new: 1,
..Default::default()
},
result: crate::worker::GenerationResult::Buffered(result),
})
.await
.unwrap();
state.worker.write().await.metrics.start();
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
let url = format!("http://{}/metrics", listener.local_addr().unwrap());
let router = router(state.clone());
let server = tokio::spawn(async move { axum::serve(listener, router).await });
let response = reqwest::get(url).await.unwrap();
assert_eq!(response.status(), StatusCode::OK);
assert_eq!(response.headers()["content-type"], "application/json");
let body: serde_json::Value =
serde_json::from_str(&response.text().await.unwrap()).unwrap();
assert_eq!(body["active"], true);
assert!(body["active_elapsed_ms"].is_u64());
assert_eq!(body["generation"]["started"], 1);
assert_eq!(body["queue_capacity"], 2);
assert_eq!(body["queue_used"], 1);
assert!(body["generation"].get("active_since").is_none());
assert_eq!(
serde_json::to_value(status(State(state.clone())).await.0).unwrap(),
initial_status
);
receiver.recv().await.unwrap();
assert_eq!(metrics_document(&state, false).await["queue_used"], 0);
server.abort();
}
}
mod impl_default_for_appstate;
#[allow(unused_imports)]
pub use impl_default_for_appstate::*;
mod metrics_document;
#[allow(unused_imports)]
pub use metrics_document::*;
@@ -0,0 +1,236 @@
//! Moved out of the parent module by STRA-338: impl Default_for_AppState, fn router, fn health, fn lifecycle_status, fn lifecycle_precondition, fn drain ....
#[allow(unused_imports)]
use super::*;
impl Default for AppState {
fn default() -> Self {
Self {
queue_timeout: None,
lifecycle: Default::default(),
api_key: None,
model: None,
worker: Arc::new(RwLock::new(WorkerStatus::default())),
pool: Vec::new(),
tokenizer: None,
generation: None,
response_history: Arc::new(RwLock::new(responses::ResponseHistory::default())),
settings: Arc::new(crate::settings::Settings::default()),
aliases: Arc::new(Vec::new()),
cors: Arc::new(Default::default()),
trusted_origins: Arc::new(Vec::new()),
control: None,
started_at: std::time::SystemTime::now(),
chat_template: None,
mcp: None,
vision: None,
prefix_cache: Arc::new(Default::default()),
memory: Arc::new(Default::default()),
monitor: Arc::new(Default::default()),
}
}
}
pub fn router(state: AppState) -> Router {
let observe = crate::request_log::Observe {
model: state.model.clone(),
memory: state.memory.clone(),
};
Router::new()
.route("/health", get(health))
.route("/ready", get(ready))
.route("/status", get(status))
.route("/metrics", get(metrics))
.route("/api/health", get(crate::server_api::api_health))
.route("/props", get(crate::server_api::props))
.route("/slots", get(crate::server_api::slots))
.route("/v1/status", get(crate::server_api::v1_status))
.route("/v1/prefix_match", post(crate::server_api::v1_prefix_match))
.route("/v1/reconfigure", post(crate::server_api::v1_reconfigure))
.route("/mcp", get(crate::server_api::mcp_status))
.route(
"/settings",
get(crate::server_api::settings_get).post(crate::server_api::settings_post),
)
.route("/load", post(crate::server_api::load_post))
.route("/unload", post(crate::server_api::unload_post))
.route("/v1/load", post(crate::server_api::v1_load))
.route("/v1/unload", post(crate::server_api::v1_unload))
.route("/models", get(crate::models_api::list))
.route("/v1/models", get(crate::models_api::list))
.route("/v1/models/{id}", get(crate::models_api::retrieve))
.route(
"/v1/responses",
post(responses::create_route)
.layer(middleware::from_fn_with_state(
state.lifecycle.clone(),
crate::lifecycle::admit,
))
.layer(middleware::from_fn_with_state(
state.monitor.clone(),
crate::request_monitor::capture,
))
.layer(middleware::from_fn_with_state(
observe.clone(),
crate::request_log::observe,
)),
)
.route(
"/v1/responses/input_tokens",
post(responses::count_input_tokens).layer(middleware::from_fn_with_state(
state.lifecycle.clone(),
crate::lifecycle::admit,
)),
)
.route(
"/v1/chat/completions",
post(crate::chat::create)
.layer(middleware::from_fn_with_state(
state.lifecycle.clone(),
crate::lifecycle::admit,
))
.layer(middleware::from_fn_with_state(
state.monitor.clone(),
crate::request_monitor::capture,
))
.layer(middleware::from_fn_with_state(
observe.clone(),
crate::request_log::observe,
)),
)
.route(
"/v1/messages/count_tokens",
post(crate::messages::count_tokens)
.layer(middleware::from_fn_with_state(
state.lifecycle.clone(),
crate::lifecycle::admit,
))
.layer(middleware::from_fn(crate::messages::protocol)),
)
.route(
"/v1/messages",
post(crate::messages::create)
.layer(middleware::from_fn_with_state(
state.lifecycle.clone(),
crate::lifecycle::admit,
))
.layer(middleware::from_fn(crate::messages::protocol))
.layer(middleware::from_fn_with_state(
state.monitor.clone(),
crate::request_monitor::capture,
))
.layer(middleware::from_fn_with_state(
observe.clone(),
crate::request_log::observe,
)),
)
.route("/api/requests", get(crate::server_api::api_requests))
.route("/admin/lifecycle", get(lifecycle_status))
.route(
"/v1/responses/{id}",
get(responses::retrieve).delete(responses::delete),
)
.route(
"/v1/responses/{id}/input_items",
get(responses::input_items),
)
.route("/admin/drain", post(drain))
.route("/admin/resume", post(resume))
.fallback(crate::server_api::not_found)
.layer(DefaultBodyLimit::max(16 * 1024 * 1024))
.layer(middleware::from_fn_with_state(
state.api_key.clone(),
crate::auth::authorize,
))
// Outermost: a browser's credential-less preflight is answered before authentication.
.layer(middleware::from_fn_with_state(
state.cors.clone(),
crate::server_api::cors_layer,
))
.with_state(state)
}
pub(super) async fn health() -> Json<HealthResponse> {
Json(HealthResponse { status: "ok" })
}
pub(super) async fn lifecycle_status(State(state): State<AppState>) -> Json<serde_json::Value> {
let worker = *state.worker.read().await;
let lifecycle = state.lifecycle.snapshot();
let drained = lifecycle.draining
&& lifecycle.requests_in_flight == 0
&& lifecycle.generation_jobs == 0
&& worker.metrics.active_since.is_none()
&& matches!(
worker.state,
WorkerState::Ready | WorkerState::Unconfigured | WorkerState::Unloaded
);
Json(
serde_json::json!({"service":"strata-control", "server_pid":std::process::id(), "model":state.model,
"draining":lifecycle.draining,
"shutting_down":lifecycle.shutting_down,
"max_in_flight_requests":lifecycle.max_in_flight_requests,
"available_request_slots":lifecycle.max_in_flight_requests.saturating_sub(lifecycle.requests_in_flight),
"requests_in_flight":lifecycle.requests_in_flight, "generation_jobs":lifecycle.generation_jobs,
"drained":drained, "worker":worker.state}),
)
}
pub(super) fn lifecycle_precondition(headers: &HeaderMap) -> Option<Response> {
let mut values = headers.get_all("x-strata-expected-pid").iter();
let value = values.next()?;
let pid = value
.to_str()
.ok()
.filter(|s| !s.is_empty() && s.bytes().all(|b| b.is_ascii_digit()))
.and_then(|s| s.parse::<u32>().ok())
.filter(|n| *n > 0);
if values.next().is_some() || pid.is_none() {
return Some((StatusCode::BAD_REQUEST, Json(serde_json::json!({"error":{"code":"invalid_expected_pid","message":"expected PID must be one positive integer"}}))).into_response());
}
if pid != Some(std::process::id()) {
return Some((StatusCode::CONFLICT, Json(serde_json::json!({"error":{"code":"process_identity_changed","message":"native process no longer matches expected PID; admission unchanged"}}))).into_response());
}
None
}
pub(super) async fn drain(State(state): State<AppState>, headers: HeaderMap) -> Response {
if let Some(response) = lifecycle_precondition(&headers) {
return response;
}
state.lifecycle.set_draining(true);
lifecycle_status(State(state)).await.into_response()
}
pub(super) async fn resume(State(state): State<AppState>, headers: HeaderMap) -> Response {
if let Some(response) = lifecycle_precondition(&headers) {
return response;
}
state.lifecycle.set_draining(false);
lifecycle_status(State(state)).await.into_response()
}
/// `GET /metrics`: the native JSON document, or its Prometheus text exposition (`?format=prometheus`, or an `Accept` that asks
/// for `text/plain` / OpenMetrics, as a Prometheus scraper sends). `?requests=all` lists every kept generation, not the last 12.
pub(super) async fn metrics(
State(state): State<AppState>,
RawQuery(query): RawQuery,
headers: HeaderMap,
) -> Response {
let accept = headers
.get(axum::http::header::ACCEPT)
.and_then(|v| v.to_str().ok());
let all = query
.as_deref()
.is_some_and(|q| q.split('&').any(|pair| pair == "requests=all"));
let document = metrics_document(&state, all).await;
if crate::prometheus::wanted(query.as_deref(), accept) {
let mut response = crate::prometheus::render(&document).into_response();
response.headers_mut().insert(
axum::http::header::CONTENT_TYPE,
axum::http::HeaderValue::from_static(crate::prometheus::CONTENT_TYPE),
);
return response;
}
Json(document).into_response()
}
+170
View File
@@ -0,0 +1,170 @@
//! Moved out of the parent module by STRA-338: fn metrics_document, fn supervisor_block, fn ready, fn status, fn pool_ready, fn status_body.
#[allow(unused_imports)]
use super::*;
/// The `/metrics` document. `schema_version` stays 1: the members below `generation` are the Python Monitor's
/// (`engine`, `live`, `requests`, `requests_kept`, `totals`, `hardware`, `hardware_static`, `history`, `time`) and were added
/// beside the native ones, which are unchanged.
pub async fn metrics_document(state: &AppState, all_requests: bool) -> serde_json::Value {
let worker = *state.worker.read().await;
let generation = worker.metrics;
let lifecycle = state.lifecycle.snapshot();
let queue_capacity = state.generation.as_ref().map(mpsc::Sender::max_capacity);
let queue_used = state
.generation
.as_ref()
.map(|sender| sender.max_capacity() - sender.capacity());
let memory = state.memory.status();
let (hardware, hardware_static, telemetry, history) = state.memory.hardware();
let busy = generation.active_since.is_some();
let phase = telemetry["phase"].as_str();
let engine_state = if worker.state != WorkerState::Ready {
serde_json::to_value(worker.state).unwrap_or(serde_json::Value::Null)
} else if busy {
serde_json::json!(if phase == Some("prefill") {
"reading"
} else {
"generating"
})
} else {
serde_json::json!("idle")
};
let elapsed_ms = generation
.active_since
.map(|start| start.elapsed().as_millis().min(u64::MAX as u128) as u64);
let live = serde_json::json!({
"state": engine_state,
"active": busy,
"queued": lifecycle.generation_jobs.saturating_sub(usize::from(busy)),
"phase": if busy { phase.map_or(serde_json::Value::Null, |p| serde_json::json!(p)) } else { serde_json::Value::Null },
"prompt_tokens": if busy { telemetry["request"]["prompt_tokens"].clone() } else { serde_json::Value::Null },
"generated": if busy { telemetry["request"]["generated_tokens"].clone() } else { serde_json::Value::Null },
"elapsed_s": elapsed_ms.map(|ms| (ms as f64 / 100.0).round() / 10.0),
"tok_s": if busy { hardware["tok_s"].clone() } else { serde_json::Value::Null },
"tok_s_mean": if busy { hardware["tok_s_mean"].clone() } else { serde_json::Value::Null },
"prefill_tok_s_mean": if busy { hardware["prefill_tok_s_mean"].clone() } else { serde_json::Value::Null },
"prompt_read": null, "prompt_total": null, "max_tokens": null, "tok_s_window_s": null,
});
let engine = serde_json::json!({
"model": state.model, "max_context": worker.max_context.or(worker.known_max_context),
"images": state.vision.is_some(), "version": env!("CARGO_PKG_VERSION"),
"api_monitor": state.monitor.enabled(),
"settings": telemetry["settings"].clone(),
});
let (requests, requests_kept, totals) = match generation.history {
Some(history) => (
history.requests((!all_requests).then_some(RECENT_REQUESTS)),
history.kept(),
history.totals(),
),
None => (Vec::new(), 0, serde_json::Value::Null),
};
serde_json::json!({
"schema_version": 1,
"scope": "control_plane_process",
"model": state.model,
"worker": worker.state,
"up": worker.state == WorkerState::Ready,
"active": busy,
"active_elapsed_ms": elapsed_ms,
"queue_capacity": queue_capacity,
"queue_used": queue_used,
"memory": {
"level": memory["gate"]["level"].clone(),
"gate_rejections": state.memory.gate_rejections(),
"available_bytes": memory["gate"]["available_bytes"].clone(),
},
"generation": generation,
"done_decode_tokens_per_second": crate::metrics::token_rate(generation.done_generated_tokens, generation.done_decode_ms),
"engine": engine,
"live": live,
"requests": requests,
"requests_kept": requests_kept,
"totals": totals,
"api_uptime_s": state.started_at.elapsed().map_or(0, |d| d.as_secs()),
"supervisor": supervisor_block(),
"hardware": hardware,
"hardware_static": hardware_static,
"history": history,
"telemetry": telemetry,
"time": std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map_or(0.0, |d| d.as_secs_f64()),
})
}
/// The supervisor's own account (`LELEKA_STATUS_FILE`, set by `leleka run`): restarts and uptime of the service. `null` when this
/// process was not started by a supervisor, or the file cannot be read.
pub(super) fn supervisor_block() -> serde_json::Value {
let Some(path) = std::env::var_os("LELEKA_STATUS_FILE") else {
return serde_json::Value::Null;
};
let Ok(text) = std::fs::read_to_string(path) else {
return serde_json::Value::Null;
};
let Ok(status) = serde_json::from_str::<serde_json::Value>(&text) else {
return serde_json::Value::Null;
};
let now = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map_or(0, |d| d.as_secs());
serde_json::json!({
"phase": status["phase"],
"restarts_total": status["restarts_total"],
"uptime_s": status["started_unix"].as_u64().map(|started| now.saturating_sub(started)),
"last_restart_reason": status["last_restart_reason"],
})
}
pub(super) async fn ready(State(state): State<AppState>) -> (StatusCode, Json<StatusResponse>) {
let worker = *state.worker.read().await;
let inference_ready = worker.state == WorkerState::Ready
&& pool_ready(&state).await
&& state.tokenizer.is_some()
&& state.generation.is_some()
&& !state.lifecycle.snapshot().draining;
let code = if inference_ready {
StatusCode::OK
} else {
StatusCode::SERVICE_UNAVAILABLE
};
(
code,
Json(status_body(worker, inference_ready, state.model)),
)
}
pub(super) async fn status(State(state): State<AppState>) -> Json<StatusResponse> {
let worker = *state.worker.read().await;
let inference_ready = worker.state == WorkerState::Ready
&& pool_ready(&state).await
&& state.tokenizer.is_some()
&& state.generation.is_some()
&& !state.lifecycle.snapshot().draining;
Json(status_body(worker, inference_ready, state.model))
}
/// Every member of a worker pool is ready (true without a pool).
pub(super) async fn pool_ready(state: &AppState) -> bool {
for member in &state.pool {
if member.read().await.state != WorkerState::Ready {
return false;
}
}
true
}
pub(super) fn status_body(
worker: WorkerStatus,
inference_ready: bool,
model: Option<String>,
) -> StatusResponse {
StatusResponse {
service: "strata-control",
server_pid: std::process::id(),
model,
version: env!("CARGO_PKG_VERSION"),
worker: worker.state,
ready: inference_ready,
max_context: worker.max_context,
}
}
+162
View File
@@ -0,0 +1,162 @@
//! Unit tests of this module (moved out of the file by STRA-338; the test ids are unchanged).
use super::*;
#[tokio::test]
async fn conditional_admission_rejects_stale_or_ambiguous_pid_before_mutation() {
let state = AppState::default();
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
let url = format!("http://{}", listener.local_addr().unwrap());
let router = router(state.clone());
let server = tokio::spawn(async move { axum::serve(listener, router).await });
let client = reqwest::Client::new();
for (path, initial) in [("drain", false), ("resume", true)] {
state.lifecycle.set_draining(initial);
for (value, status) in [
("0".to_string(), 400),
("bad".into(), 400),
((std::process::id() + 1).to_string(), 409),
] {
let response = client
.post(format!("{url}/admin/{path}"))
.header("x-strata-expected-pid", value)
.send()
.await
.unwrap();
assert_eq!(response.status().as_u16(), status);
assert_eq!(state.lifecycle.snapshot().draining, initial);
}
let duplicate = client
.post(format!("{url}/admin/{path}"))
.header("x-strata-expected-pid", std::process::id())
.header("x-strata-expected-pid", std::process::id())
.send()
.await
.unwrap();
assert_eq!(duplicate.status(), StatusCode::BAD_REQUEST);
assert_eq!(state.lifecycle.snapshot().draining, initial);
let response = client
.post(format!("{url}/admin/{path}"))
.header("x-strata-expected-pid", std::process::id())
.send()
.await
.unwrap();
assert_eq!(response.status(), StatusCode::OK);
let value: serde_json::Value =
serde_json::from_str(&response.text().await.unwrap()).unwrap();
assert_eq!(value["server_pid"], std::process::id());
assert_eq!(value["service"], "strata-control");
assert_eq!(value["draining"], !initial);
}
server.abort();
let _ = server.await;
}
#[tokio::test]
async fn drain_rejects_new_requests_before_json_parsing_and_resume_is_idempotent() {
let state = AppState::default();
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
let url = format!("http://{}", listener.local_addr().unwrap());
let router = router(state.clone());
let server = tokio::spawn(async move { axum::serve(listener, router).await });
let client = reqwest::Client::new();
for _ in 0..2 {
let response = client
.post(format!("{url}/admin/drain"))
.send()
.await
.unwrap();
let data: serde_json::Value =
serde_json::from_str(&response.text().await.unwrap()).unwrap();
assert_eq!(data["draining"], true);
assert_eq!(data["drained"], true);
}
let response = client
.post(format!("{url}/v1/responses"))
.header("content-type", "application/json")
.body("invalid json")
.send()
.await
.unwrap();
assert_eq!(response.status(), StatusCode::SERVICE_UNAVAILABLE);
assert!(response.text().await.unwrap().contains("runtime_draining"));
assert_eq!(state.lifecycle.snapshot().requests_in_flight, 0);
let job = state.lifecycle.generation();
assert_eq!(
lifecycle_status(State(state.clone())).await.0["drained"],
false
);
drop(job);
state.worker.write().await.state = WorkerState::Restarting;
assert_eq!(
lifecycle_status(State(state.clone())).await.0["drained"],
false
);
for _ in 0..2 {
let response = client
.post(format!("{url}/admin/resume"))
.send()
.await
.unwrap();
assert_eq!(response.status(), StatusCode::OK);
}
let response = client
.post(format!("{url}/v1/responses"))
.header("content-type", "application/json")
.body("invalid json")
.send()
.await
.unwrap();
assert_eq!(response.status(), StatusCode::BAD_REQUEST);
let _ = response.text().await.unwrap();
server.abort();
}
#[tokio::test]
async fn metrics_expose_activity_without_changing_discovery() {
let (sender, mut receiver) = mpsc::channel(2);
let state = AppState {
generation: Some(sender.clone()),
..Default::default()
};
let initial_status = serde_json::to_value(status(State(state.clone())).await.0).unwrap();
let initial_metrics = metrics_document(&state, false).await;
assert_eq!(initial_metrics["active"], false);
assert!(initial_metrics["done_decode_tokens_per_second"].is_null());
let (result, _rx) = tokio::sync::oneshot::channel();
sender
.send(GenerationCommand {
queue: None,
activity: None,
request: crate::wire::Generate {
token_ids: vec![10],
max_new: 1,
..Default::default()
},
result: crate::worker::GenerationResult::Buffered(result),
})
.await
.unwrap();
state.worker.write().await.metrics.start();
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
let url = format!("http://{}/metrics", listener.local_addr().unwrap());
let router = router(state.clone());
let server = tokio::spawn(async move { axum::serve(listener, router).await });
let response = reqwest::get(url).await.unwrap();
assert_eq!(response.status(), StatusCode::OK);
assert_eq!(response.headers()["content-type"], "application/json");
let body: serde_json::Value = serde_json::from_str(&response.text().await.unwrap()).unwrap();
assert_eq!(body["active"], true);
assert!(body["active_elapsed_ms"].is_u64());
assert_eq!(body["generation"]["started"], 1);
assert_eq!(body["queue_capacity"], 2);
assert_eq!(body["queue_used"], 1);
assert!(body["generation"].get("active_since").is_none());
assert_eq!(
serde_json::to_value(status(State(state.clone())).await.0).unwrap(),
initial_status
);
receiver.recv().await.unwrap();
assert_eq!(metrics_document(&state, false).await["queue_used"], 0);
server.abort();
}
+12 -732
View File
@@ -96,607 +96,6 @@ enum Cancel {
Failure(String),
}
/// The runtime gRPC contract names a request by UUID and refuses a repeated one.
fn request_id() -> String {
uuid::Uuid::new_v4().to_string()
}
/// Run a blocking backend call off the async threads. The backend is `Send` but not `Sync`, so
/// calls are serialised by the mutex; `start_generation` and `cancel` return quickly by contract.
async fn on_engine<T: Send + 'static>(
engine: &Engine,
call: impl FnOnce(&mut dyn api::Backend) -> T + Send + 'static,
) -> Result<T, String> {
let engine = Arc::clone(engine);
tokio::task::spawn_blocking(move || {
let mut guard = engine
.lock()
.map_err(|_| "engine state is poisoned".to_owned())?;
Ok(call(&mut **guard))
})
.await
.map_err(|error| format!("engine call failed: {error}"))?
}
/// The prompt as text, or why the engine would not see exactly these tokens.
fn prompt_text(tokenizer: &Tokenizer, ids: &[u32]) -> Result<String, String> {
let bytes = tokenizer.decode_bytes(ids).map_err(|e| e.to_string())?;
let text = String::from_utf8(bytes)
.map_err(|_| "the prompt tokens do not decode to valid UTF-8 text".to_owned())?;
let again = tokenizer.encode(&text, true).map_err(|e| e.to_string())?;
if again != ids {
return Err(
"the prompt tokens are not the canonical encoding of their text, so a text-level engine \
would tokenize the prompt differently; refusing to serve different tokens than were counted"
.to_owned(),
);
}
Ok(text)
}
/// Token ids whose bytes are exactly `text`.
fn text_tokens(tokenizer: &Tokenizer, text: &str) -> Result<Vec<u32>, String> {
let ids = tokenizer.encode(text, false).map_err(|e| e.to_string())?;
let bytes = tokenizer.decode_bytes(&ids).map_err(|e| e.to_string())?;
if bytes != text.as_bytes() {
return Err("an engine text delta does not survive re-tokenization unchanged".to_owned());
}
Ok(ids)
}
/// Map an HTTP-layer request onto the engine contract, or say what cannot be carried.
async fn prepare(
config: &BackendWorkerConfig,
request: &Generate,
) -> Result<api::GenerationRequest, String> {
if request.embeddings.is_some() {
return Err("image input is not supported over the text-level engine contract".to_owned());
}
if request.reasoning.is_some() {
return Err("reasoning_budget_tokens needs token-level continuation, which the text-level engine contract does not provide".to_owned());
}
if request.tune.is_some() {
return Err(
"strata_tune is an engine-process setting and is not part of the engine contract"
.to_owned(),
);
}
if request.cvec.is_some() {
return Err(
"experimental_speed_projection (control vectors) is not part of the engine contract"
.to_owned(),
);
}
let fits = usize::try_from(request.max_new)
.ok()
.and_then(|new| request.token_ids.len().checked_add(new))
.and_then(|total| total.checked_add(8))
.is_some_and(|total| total <= config.max_context);
if !fits {
return Err("prompt, output budget, and 8-token margin exceed context".to_owned());
}
if request.token_ids.is_empty() || request.max_new == 0 {
return Err("a generation needs prompt tokens and a positive max_new".to_owned());
}
if request.max_new > config.max_output_tokens {
return Err(format!(
"max_output_tokens {} exceeds the runtime's limit of {}",
request.max_new, config.max_output_tokens
));
}
let fixed = leleka_serving_policy::fixed::to_fixed_point(&request.sampling)
.map_err(|error| format!("sampling: {error}"))?;
let prompt_span = crate::stage_trace::span("worker_prompt_text");
let prompt = match &request.prompt_text {
// The HTTP layer produced the ids from this very text; the engine is given the text if the ids still decode to it
// (a table walk over the ids, well under a millisecond for a whole conversation).
Some(text)
if config
.tokenizer
.decodes_to(&request.token_ids, text.as_bytes()) =>
{
text.to_string()
}
// Control-token text inside a message travels marked (`LiteralMarks`), and the engine reads the marks
// (`encode_marked`): the text is handed over if that encoding is exactly the ids that were counted.
// Anything else is decoded and must be the canonical encoding of its own text, or it is refused.
other => {
let tokenizer = Arc::clone(&config.tokenizer);
let ids = request.token_ids.clone();
let marked = other.clone();
tokio::task::spawn_blocking(move || match marked {
Some(text)
if tokenizer.marks().has_marks(&text)
&& tokenizer
.encode_marked(&text)
.is_ok_and(|encoded| encoded == ids) =>
{
Ok(text.to_string())
}
_ => prompt_text(&tokenizer, &ids),
})
.await
.map_err(|error| error.to_string())??
}
};
drop(prompt_span);
Ok(api::GenerationRequest {
request_id: request.obs.id().unwrap_or_else(request_id),
prompt,
max_output_tokens: request.max_new,
temperature_milli: fixed.temperature_milli,
sampling: api::SamplingOptions {
top_p_micro: fixed.top_p_micro,
top_k: fixed.top_k,
min_p_micro: fixed.min_p_micro,
repetition_penalty_micro: fixed.repetition_penalty_micro,
frequency_penalty_micro: fixed.frequency_penalty_micro,
presence_penalty_micro: fixed.presence_penalty_micro,
penalty_last_n: fixed.penalty_last_n,
seed: fixed.seed,
},
})
}
pub async fn run_backend_worker(
backend: Box<dyn api::Backend>,
config: BackendWorkerConfig,
status: Arc<RwLock<WorkerStatus>>,
mut shutdown: watch::Receiver<bool>,
mut requests: mpsc::Receiver<GenerationCommand>,
mut control: mpsc::Receiver<Control>,
) {
let engine: Engine = Arc::new(Mutex::new(backend));
let mut waiting: Vec<LoadReply> = Vec::new();
let mut attached_before = false;
let mut requests_closed = false;
let mut control_closed = false;
'attach: loop {
update(
&status,
if attached_before {
WorkerState::Restarting
} else {
WorkerState::Starting
},
None,
)
.await;
// Fail what queued up while the engine was away; nothing is replayed.
while let Ok(command) = requests.try_recv() {
command
.request
.obs
.error("worker is restarting; request was not replayed");
command.request.obs.finalize();
send_failure(
command.result,
"worker is restarting; request was not replayed".to_owned(),
)
.await;
}
let loaded = loop {
let model = config.model.clone();
let runtime = config.runtime.clone();
match on_engine(&engine, move |backend| backend.load(model, runtime)).await {
Ok(Ok(loaded))
if loaded
.validate_for_load(&config.model, &config.runtime)
.is_ok() =>
{
break loaded;
}
Ok(Ok(_)) => crate::elog!(
"the engine returned a load result that does not match the request"
),
Ok(Err(error)) => leleka_obs::info(
"api",
"engine_wait",
&[("reason", error.to_string().as_str().into())],
),
Err(error) => leleka_obs::info(
"api",
"engine_wait",
&[("reason", error.to_string().as_str().into())],
),
}
let retry = tokio::time::sleep(config.attach_retry);
tokio::pin!(retry);
loop {
tokio::select! {
biased;
_ = shutdown.changed() => {
update(&status, WorkerState::Stopping, None).await;
return;
}
_ = &mut retry => break,
message = control.recv(), if !control_closed => match message {
Some(Control::Load { reply }) => waiting.push(reply),
Some(Control::Reconfigure { reply, .. }) => crate::worker::reconfigure_unavailable(reply, "the worker is not attached to the engine"),
Some(Control::Unload { reply, .. }) => {
let _ = reply.send(leleka_serving_policy::idle::Outcome::NotLoaded);
}
None => control_closed = true,
},
command = requests.recv(), if !requests_closed => match command {
Some(command) => {
command.request.obs.error("worker is not attached to the engine; request was not replayed");
command.request.obs.finalize();
send_failure(
command.result,
"worker is not attached to the engine; request was not replayed".to_owned(),
)
.await
}
None => requests_closed = true,
},
}
}
};
attached_before = true;
crate::request_log::note_engine_attached();
update(&status, WorkerState::Ready, Some(config.max_context)).await;
status.write().await.output_cap = Some(config.max_output_tokens);
status.write().await.text_level_engine = true;
status.write().await.last_activity = Some(Instant::now());
for reply in waiting.drain(..) {
let _ = reply.send(Ok(()));
}
let mut health = tokio::time::interval(config.health_interval);
health.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Delay);
health.reset();
loop {
tokio::select! {
biased;
_ = shutdown.changed() => {
update(&status, WorkerState::Stopping, None).await;
return;
}
_ = health.tick() => {
let wanted = config.model.clone();
let present = on_engine(&engine, move |backend| backend.capabilities().supports(&wanted)).await;
if present != Ok(true) {
crate::request_log::note_engine_lost("the runtime no longer reports the model as loaded");
update(&status, WorkerState::Failed, None).await;
continue 'attach;
}
refresh_prefix_view(&engine, &config).await;
}
message = control.recv(), if !control_closed => match message {
Some(Control::Load { reply }) => {
let _ = reply.send(Ok(()));
}
Some(Control::Reconfigure { settings, reply }) => {
// Requests that arrive meanwhile wait in the queue: the engine reopens its serve stack in tens of seconds.
let answer = match on_engine(&engine, move |backend| backend.reconfigure(&settings)).await {
Ok(Ok(effective)) => Ok(effective),
Ok(Err(error)) => Err((
match error.code {
api::ErrorCode::InvalidRequest => 400,
api::ErrorCode::UnsupportedModel => 501,
api::ErrorCode::ResourceExhausted => 409,
api::ErrorCode::BackendUnavailable => 503,
api::ErrorCode::Internal => 500,
},
error.message,
)),
Err(message) => Err((500, message)),
};
let _ = reply.send(answer);
refresh_prefix_view(&engine, &config).await;
}
Some(Control::Unload { reply, .. }) => {
// The runtime's lifecycle belongs to its operator (leleka-cli), not to HTTP.
let _ = reply.send(leleka_serving_policy::idle::Outcome::Unsupported);
}
None => control_closed = true,
},
command = requests.recv(), if !requests_closed => {
let Some(mut command) = command else {
requests_closed = true;
continue;
};
if command.result.is_closed()
|| command.queue.take().is_some_and(|ticket| !ticket.claim())
{
continue;
}
status.write().await.last_activity = Some(Instant::now());
let _activity = command.activity.take();
match serve_one(&engine, &config, &status, &mut shutdown, &mut command, &loaded)
.await
{
Served::Done => {
status.write().await.last_activity = Some(Instant::now());
refresh_prefix_view(&engine, &config).await;
}
Served::Shutdown => {
update(&status, WorkerState::Stopping, None).await;
return;
}
Served::Lost(reason) => {
crate::request_log::note_engine_lost(&reason);
update(&status, WorkerState::Failed, None).await;
continue 'attach;
}
}
}
}
}
}
}
/// Copy the engine's prefix-cache summary into the view the status endpoint reads.
async fn refresh_prefix_view(engine: &Engine, config: &BackendWorkerConfig) {
if let Some(view) = &config.prefix_view {
let summary = on_engine(engine, |backend| backend.prefix_cache_summary())
.await
.ok()
.flatten();
view.set(summary);
}
if let Some(view) = &config.memory_view {
let report = on_engine(engine, |backend| backend.memory_report())
.await
.ok()
.flatten();
view.set(report);
let telemetry = on_engine(engine, |backend| backend.telemetry_report())
.await
.ok()
.flatten();
view.set_telemetry(telemetry);
}
}
async fn trigger_cancel(engine: &Engine, request_id: &str) {
let id = request_id.to_owned();
// The engine may already have finished; "not active" is not an error here.
let _ = on_engine(engine, move |backend| backend.cancel(&id)).await;
}
/// Fail a queued request: the client gets `message`, the request record gets its class.
async fn fail_command(command: &mut GenerationCommand, message: String) {
command.request.obs.error(&message);
send_failure(command.result.take(), message).await;
}
/// One generation, from the contract request to the terminal event the HTTP layer sees, plus its record.
async fn serve_one(
engine: &Engine,
config: &BackendWorkerConfig,
status: &RwLock<WorkerStatus>,
shutdown: &mut watch::Receiver<bool>,
command: &mut GenerationCommand,
loaded: &api::LoadedModel,
) -> Served {
let served = serve_one_inner(engine, config, status, shutdown, command, loaded).await;
let obs = &command.request.obs;
match &served {
Served::Lost(reason) => {
obs.error(reason);
obs.engine_restarted();
}
Served::Shutdown => obs.error("the service is shutting down"),
Served::Done => {}
}
obs.finalize();
served
}
async fn serve_one_inner(
engine: &Engine,
config: &BackendWorkerConfig,
status: &RwLock<WorkerStatus>,
shutdown: &mut watch::Receiver<bool>,
command: &mut GenerationCommand,
loaded: &api::LoadedModel,
) -> Served {
let request = match prepare(config, &command.request).await {
Ok(request) => request,
Err(message) => {
fail_command(command, message).await;
return Served::Done;
}
};
let id = request.request_id.clone();
let counted_input = u64::try_from(command.request.token_ids.len()).unwrap_or(u64::MAX);
status.write().await.metrics.start();
command.request.obs.engine_start();
// The line is written once the engine has the request (its time is taken now), so a slow log sink cannot delay the start.
let start_ms = crate::worker::unix_ms();
let max_new = request.max_output_tokens;
let started = Instant::now();
let start = {
let _span = crate::stage_trace::span("engine_start");
let model = loaded.clone();
on_engine(engine, move |backend| {
backend.start_generation(&model, request)
})
.await
};
if leleka_obs::settings().legacy {
// parsed by the lab scripts (scripts/cp/live_report.py, scripts/e2e/analyze_session.py)
leleka_obs::legacy_line(&format!(
"generation start: t_unix_ms={start_ms} prompt_tokens={counted_input} max_new={max_new}"
));
}
let stream = match start {
Ok(Ok(stream)) => stream,
Ok(Err(error)) => {
status.write().await.metrics.fail();
let message = format!("engine refused the generation: {error}");
fail_command(command, message.clone()).await;
return if error.code == api::ErrorCode::BackendUnavailable {
Served::Lost(message)
} else {
Served::Done
};
}
Err(message) => {
status.write().await.metrics.fail();
fail_command(command, message.clone()).await;
return Served::Lost(message);
}
};
// The contract stream blocks; a thread moves it onto an async channel. Dropping the receiver
// ends the thread, and dropping the stream tells the engine nobody is listening.
let (pump, mut events) = mpsc::channel::<Result<api::GenerationEvent, api::StreamError>>(16);
std::thread::spawn(move || {
let mut stream = stream;
loop {
match stream.recv() {
Ok(Some(event)) => {
let last = matches!(event, api::GenerationEvent::Terminal(_));
if pump.blocking_send(Ok(event)).is_err() || last {
return;
}
}
Ok(None) => return,
Err(error) => {
let _ = pump.blocking_send(Err(error));
return;
}
}
}
});
let mut stops = leleka_serving_policy::stop::LiteralStops::new(&STOP_LITERALS);
let mut buffered: Vec<Event> = Vec::new();
let mut usage: Option<api::Usage> = None;
let mut cancel: Option<Cancel> = None;
let mut first_delta: Option<Instant> = None;
let mut delivered: u64 = 0;
let mut last_progress = Instant::now();
let deadline = config.generation_timeout.map(|limit| started + limit);
let mut drain_deadline: Option<Instant> = None;
let mut ticker = tokio::time::interval(Duration::from_secs(1));
ticker.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Delay);
ticker.reset();
macro_rules! begin_cancel {
($cause:expr) => {{
cancel = Some($cause);
drain_deadline = Some(Instant::now() + config.cancel_drain_timeout);
trigger_cancel(engine, &id).await;
}};
}
loop {
let item = tokio::select! {
biased;
_ = shutdown.changed() => {
trigger_cancel(engine, &id).await;
return Served::Shutdown;
}
_ = tokio::time::sleep_until(drain_deadline.unwrap_or_else(Instant::now)), if drain_deadline.is_some() => {
status.write().await.metrics.fail();
let message = match cancel.take() {
Some(Cancel::Failure(message)) => message,
_ => "engine did not terminate the generation after it was cancelled".to_owned(),
};
fail_command(command, message.clone()).await;
return Served::Lost(message);
}
_ = tokio::time::sleep_until(deadline.unwrap_or_else(Instant::now)), if deadline.is_some() && cancel.is_none() => {
begin_cancel!(Cancel::Failure(
"generation exceeded configured execution deadline".to_owned()
));
continue;
}
_ = command.result.closed(), if cancel.is_none() => {
begin_cancel!(Cancel::Client);
continue;
}
_ = ticker.tick(), if config.stall_timeout.is_some() && cancel.is_none() => {
if let Some(limit) = config.stall_timeout
&& last_progress.elapsed() >= limit
{
begin_cancel!(Cancel::Failure(format!(
"engine made no progress for {} s during a request (stall watchdog)",
last_progress.elapsed().as_secs()
)));
}
continue;
}
item = events.recv() => item,
};
last_progress = Instant::now();
let event = match item {
Some(Ok(event)) => event,
Some(Err(api::StreamError::MissingTerminal)) | None => {
status.write().await.metrics.fail();
let message = match cancel.take() {
Some(Cancel::Failure(message)) => message,
_ => "engine stream ended without a terminal event".to_owned(),
};
fail_command(command, message.clone()).await;
return Served::Lost(message);
}
};
match event {
api::GenerationEvent::TextDelta { text } => {
if cancel.is_some() {
continue;
}
if first_delta.is_none() {
command.request.obs.first_token();
}
first_delta.get_or_insert_with(Instant::now);
let piece = stops.push(&text);
if !piece.emit.is_empty() {
let retokenize = crate::stage_trace::time("delta_retokenize", || {
text_tokens(&config.tokenizer, &piece.emit)
});
match retokenize {
Ok(ids) => {
for id in ids {
delivered += 1;
deliver(command, &mut buffered, Event::Token(id)).await;
}
}
Err(message) => {
begin_cancel!(Cancel::Failure(message));
continue;
}
}
}
if piece.stopped {
begin_cancel!(Cancel::Marker);
}
}
api::GenerationEvent::Usage(report) => usage = Some(report),
api::GenerationEvent::ToolCallDelta { .. } => {
if cancel.is_none() {
begin_cancel!(Cancel::Failure(
"the engine sent a tool-call delta although it advertises native tool calls as unsupported".to_owned()
));
}
}
api::GenerationEvent::Terminal(terminal) => {
return conclude(
command,
status,
buffered,
terminal,
Conclusion {
cancel,
stops: &mut stops,
usage,
delivered,
started,
first_delta,
counted_input,
tokenizer: &config.tokenizer,
},
)
.await;
}
}
}
}
struct Conclusion<'a> {
cancel: Option<Cancel>,
stops: &'a mut leleka_serving_policy::stop::LiteralStops,
@@ -708,134 +107,15 @@ struct Conclusion<'a> {
tokenizer: &'a Tokenizer,
}
/// The terminal event of the engine, turned into the single terminal event the HTTP layer needs.
async fn conclude(
command: &mut GenerationCommand,
status: &RwLock<WorkerStatus>,
mut buffered: Vec<Event>,
terminal: api::GenerationTerminal,
mut state: Conclusion<'_>,
) -> Served {
let ended = Instant::now();
let prompt_ms = state
.first_delta
.unwrap_or(ended)
.duration_since(state.started)
.as_secs_f64()
* 1000.0;
let decode_ms = state
.first_delta
.map_or(0.0, |at| ended.duration_since(at).as_secs_f64() * 1000.0);
let make_done = |reported: Option<&api::Usage>, finish: Finish, delivered: u64| {
let fallback = state.usage.as_ref();
let generated = reported
.or(fallback)
.map_or(delivered, |usage| usage.output_tokens);
Done {
generated,
prompt_tokens: reported
.or(fallback)
.map_or(state.counted_input, |usage| usage.input_tokens),
prompt_ms,
decode_ms,
finish,
drafts_accepted: None,
drafts_offered: None,
reused: reported
.or(fallback)
.map(|usage| usage.reused_input_tokens.min(usage.input_tokens)),
expert_hits: None,
expert_lookups: None,
}
};
let disconnected = matches!(state.cancel, Some(Cancel::Client)) || command.result.is_closed();
match terminal {
api::GenerationTerminal::Completed { reason, usage } => {
match state.cancel.take() {
Some(Cancel::Failure(message)) => {
status.write().await.metrics.fail();
fail_command(command, message).await;
return Served::Done;
}
Some(Cancel::Client) => {
let done = make_done(Some(&usage), Finish::Cancel, state.delivered);
let _ = finish(command, buffered, done, true, status).await;
return Served::Done;
}
Some(Cancel::Marker) => {
let done = make_done(Some(&usage), Finish::Stop, state.delivered);
let _ = finish(command, buffered, done, disconnected, status).await;
return Served::Done;
}
None => {}
}
// The text ended without a marker: whatever was held back was ordinary text.
let tail = state.stops.finish();
if !tail.is_empty() {
match text_tokens(state.tokenizer, &tail) {
Ok(ids) => {
for id in ids {
state.delivered += 1;
deliver(command, &mut buffered, Event::Token(id)).await;
}
}
Err(message) => {
status.write().await.metrics.fail();
fail_command(command, message).await;
return Served::Done;
}
}
}
if usage.input_tokens != state.counted_input {
crate::elog!(
"the engine counted {} input tokens, the control plane {}",
usage.input_tokens,
state.counted_input
);
}
let finish_reason = match reason {
api::FinishReason::Length => Finish::Length,
// Tool calls are parsed from the text by this server, never taken from the engine.
api::FinishReason::Stop | api::FinishReason::ToolCalls => Finish::Stop,
};
let done = make_done(Some(&usage), finish_reason, state.delivered);
let _ = finish(command, buffered, done, disconnected, status).await;
Served::Done
}
api::GenerationTerminal::Cancelled => {
match state.cancel.take() {
Some(Cancel::Marker) => {
let done = make_done(None, Finish::Stop, state.delivered);
let _ = finish(command, buffered, done, disconnected, status).await;
}
Some(Cancel::Client) => {
let done = make_done(None, Finish::Cancel, state.delivered);
let _ = finish(command, buffered, done, true, status).await;
}
Some(Cancel::Failure(message)) => {
status.write().await.metrics.fail();
fail_command(command, message).await;
}
None => {
status.write().await.metrics.fail();
fail_command(
command,
"the engine cancelled the generation without a request".to_owned(),
)
.await;
}
}
Served::Done
}
api::GenerationTerminal::Failed { message, code, .. } => {
status.write().await.metrics.fail();
let message = if message.is_empty() {
format!("engine generation failed ({code:?})")
} else {
message
};
fail_command(command, message).await;
Served::Done
}
}
}
mod request_id;
#[allow(unused_imports)]
pub use request_id::*;
mod run_backend_worker;
#[allow(unused_imports)]
pub use run_backend_worker::*;
mod serve_one;
#[allow(unused_imports)]
pub use serve_one::*;
mod conclude;
#[allow(unused_imports)]
pub use conclude::*;
@@ -0,0 +1,136 @@
//! Moved out of the parent module by STRA-338: fn conclude.
#[allow(unused_imports)]
use super::*;
/// The terminal event of the engine, turned into the single terminal event the HTTP layer needs.
pub(super) async fn conclude(
command: &mut GenerationCommand,
status: &RwLock<WorkerStatus>,
mut buffered: Vec<Event>,
terminal: api::GenerationTerminal,
mut state: Conclusion<'_>,
) -> Served {
let ended = Instant::now();
let prompt_ms = state
.first_delta
.unwrap_or(ended)
.duration_since(state.started)
.as_secs_f64()
* 1000.0;
let decode_ms = state
.first_delta
.map_or(0.0, |at| ended.duration_since(at).as_secs_f64() * 1000.0);
let make_done = |reported: Option<&api::Usage>, finish: Finish, delivered: u64| {
let fallback = state.usage.as_ref();
let generated = reported
.or(fallback)
.map_or(delivered, |usage| usage.output_tokens);
Done {
generated,
prompt_tokens: reported
.or(fallback)
.map_or(state.counted_input, |usage| usage.input_tokens),
prompt_ms,
decode_ms,
finish,
drafts_accepted: None,
drafts_offered: None,
reused: reported
.or(fallback)
.map(|usage| usage.reused_input_tokens.min(usage.input_tokens)),
expert_hits: None,
expert_lookups: None,
}
};
let disconnected = matches!(state.cancel, Some(Cancel::Client)) || command.result.is_closed();
match terminal {
api::GenerationTerminal::Completed { reason, usage } => {
match state.cancel.take() {
Some(Cancel::Failure(message)) => {
status.write().await.metrics.fail();
fail_command(command, message).await;
return Served::Done;
}
Some(Cancel::Client) => {
let done = make_done(Some(&usage), Finish::Cancel, state.delivered);
let _ = finish(command, buffered, done, true, status).await;
return Served::Done;
}
Some(Cancel::Marker) => {
let done = make_done(Some(&usage), Finish::Stop, state.delivered);
let _ = finish(command, buffered, done, disconnected, status).await;
return Served::Done;
}
None => {}
}
// The text ended without a marker: whatever was held back was ordinary text.
let tail = state.stops.finish();
if !tail.is_empty() {
match text_tokens(state.tokenizer, &tail) {
Ok(ids) => {
for id in ids {
state.delivered += 1;
deliver(command, &mut buffered, Event::Token(id)).await;
}
}
Err(message) => {
status.write().await.metrics.fail();
fail_command(command, message).await;
return Served::Done;
}
}
}
if usage.input_tokens != state.counted_input {
crate::elog!(
"the engine counted {} input tokens, the control plane {}",
usage.input_tokens,
state.counted_input
);
}
let finish_reason = match reason {
api::FinishReason::Length => Finish::Length,
// Tool calls are parsed from the text by this server, never taken from the engine.
api::FinishReason::Stop | api::FinishReason::ToolCalls => Finish::Stop,
};
let done = make_done(Some(&usage), finish_reason, state.delivered);
let _ = finish(command, buffered, done, disconnected, status).await;
Served::Done
}
api::GenerationTerminal::Cancelled => {
match state.cancel.take() {
Some(Cancel::Marker) => {
let done = make_done(None, Finish::Stop, state.delivered);
let _ = finish(command, buffered, done, disconnected, status).await;
}
Some(Cancel::Client) => {
let done = make_done(None, Finish::Cancel, state.delivered);
let _ = finish(command, buffered, done, true, status).await;
}
Some(Cancel::Failure(message)) => {
status.write().await.metrics.fail();
fail_command(command, message).await;
}
None => {
status.write().await.metrics.fail();
fail_command(
command,
"the engine cancelled the generation without a request".to_owned(),
)
.await;
}
}
Served::Done
}
api::GenerationTerminal::Failed { message, code, .. } => {
status.write().await.metrics.fail();
let message = if message.is_empty() {
format!("engine generation failed ({code:?})")
} else {
message
};
fail_command(command, message).await;
Served::Done
}
}
}
@@ -0,0 +1,146 @@
//! Moved out of the parent module by STRA-338: fn request_id, fn on_engine, fn prompt_text, fn text_tokens, fn prepare.
#[allow(unused_imports)]
use super::*;
/// The runtime gRPC contract names a request by UUID and refuses a repeated one.
pub(super) fn request_id() -> String {
uuid::Uuid::new_v4().to_string()
}
/// Run a blocking backend call off the async threads. The backend is `Send` but not `Sync`, so
/// calls are serialised by the mutex; `start_generation` and `cancel` return quickly by contract.
pub(super) async fn on_engine<T: Send + 'static>(
engine: &Engine,
call: impl FnOnce(&mut dyn api::Backend) -> T + Send + 'static,
) -> Result<T, String> {
let engine = Arc::clone(engine);
tokio::task::spawn_blocking(move || {
let mut guard = engine
.lock()
.map_err(|_| "engine state is poisoned".to_owned())?;
Ok(call(&mut **guard))
})
.await
.map_err(|error| format!("engine call failed: {error}"))?
}
/// The prompt as text, or why the engine would not see exactly these tokens.
pub(super) fn prompt_text(tokenizer: &Tokenizer, ids: &[u32]) -> Result<String, String> {
let bytes = tokenizer.decode_bytes(ids).map_err(|e| e.to_string())?;
let text = String::from_utf8(bytes)
.map_err(|_| "the prompt tokens do not decode to valid UTF-8 text".to_owned())?;
let again = tokenizer.encode(&text, true).map_err(|e| e.to_string())?;
if again != ids {
return Err(
"the prompt tokens are not the canonical encoding of their text, so a text-level engine \
would tokenize the prompt differently; refusing to serve different tokens than were counted"
.to_owned(),
);
}
Ok(text)
}
/// Token ids whose bytes are exactly `text`.
pub(super) fn text_tokens(tokenizer: &Tokenizer, text: &str) -> Result<Vec<u32>, String> {
let ids = tokenizer.encode(text, false).map_err(|e| e.to_string())?;
let bytes = tokenizer.decode_bytes(&ids).map_err(|e| e.to_string())?;
if bytes != text.as_bytes() {
return Err("an engine text delta does not survive re-tokenization unchanged".to_owned());
}
Ok(ids)
}
/// Map an HTTP-layer request onto the engine contract, or say what cannot be carried.
pub(super) async fn prepare(
config: &BackendWorkerConfig,
request: &Generate,
) -> Result<api::GenerationRequest, String> {
if request.embeddings.is_some() {
return Err("image input is not supported over the text-level engine contract".to_owned());
}
if request.reasoning.is_some() {
return Err("reasoning_budget_tokens needs token-level continuation, which the text-level engine contract does not provide".to_owned());
}
if request.tune.is_some() {
return Err(
"strata_tune is an engine-process setting and is not part of the engine contract"
.to_owned(),
);
}
if request.cvec.is_some() {
return Err(
"experimental_speed_projection (control vectors) is not part of the engine contract"
.to_owned(),
);
}
let fits = usize::try_from(request.max_new)
.ok()
.and_then(|new| request.token_ids.len().checked_add(new))
.and_then(|total| total.checked_add(8))
.is_some_and(|total| total <= config.max_context);
if !fits {
return Err("prompt, output budget, and 8-token margin exceed context".to_owned());
}
if request.token_ids.is_empty() || request.max_new == 0 {
return Err("a generation needs prompt tokens and a positive max_new".to_owned());
}
if request.max_new > config.max_output_tokens {
return Err(format!(
"max_output_tokens {} exceeds the runtime's limit of {}",
request.max_new, config.max_output_tokens
));
}
let fixed = leleka_serving_policy::fixed::to_fixed_point(&request.sampling)
.map_err(|error| format!("sampling: {error}"))?;
let prompt_span = crate::stage_trace::span("worker_prompt_text");
let prompt = match &request.prompt_text {
// The HTTP layer produced the ids from this very text; the engine is given the text if the ids still decode to it
// (a table walk over the ids, well under a millisecond for a whole conversation).
Some(text)
if config
.tokenizer
.decodes_to(&request.token_ids, text.as_bytes()) =>
{
text.to_string()
}
// Control-token text inside a message travels marked (`LiteralMarks`), and the engine reads the marks
// (`encode_marked`): the text is handed over if that encoding is exactly the ids that were counted.
// Anything else is decoded and must be the canonical encoding of its own text, or it is refused.
other => {
let tokenizer = Arc::clone(&config.tokenizer);
let ids = request.token_ids.clone();
let marked = other.clone();
tokio::task::spawn_blocking(move || match marked {
Some(text)
if tokenizer.marks().has_marks(&text)
&& tokenizer
.encode_marked(&text)
.is_ok_and(|encoded| encoded == ids) =>
{
Ok(text.to_string())
}
_ => prompt_text(&tokenizer, &ids),
})
.await
.map_err(|error| error.to_string())??
}
};
drop(prompt_span);
Ok(api::GenerationRequest {
request_id: request.obs.id().unwrap_or_else(request_id),
prompt,
max_output_tokens: request.max_new,
temperature_milli: fixed.temperature_milli,
sampling: api::SamplingOptions {
top_p_micro: fixed.top_p_micro,
top_k: fixed.top_k,
min_p_micro: fixed.min_p_micro,
repetition_penalty_micro: fixed.repetition_penalty_micro,
frequency_penalty_micro: fixed.frequency_penalty_micro,
presence_penalty_micro: fixed.presence_penalty_micro,
penalty_last_n: fixed.penalty_last_n,
seed: fixed.seed,
},
})
}
@@ -0,0 +1,227 @@
//! Moved out of the parent module by STRA-338: fn run_backend_worker, fn refresh_prefix_view, fn trigger_cancel, fn fail_command.
#[allow(unused_imports)]
use super::*;
pub async fn run_backend_worker(
backend: Box<dyn api::Backend>,
config: BackendWorkerConfig,
status: Arc<RwLock<WorkerStatus>>,
mut shutdown: watch::Receiver<bool>,
mut requests: mpsc::Receiver<GenerationCommand>,
mut control: mpsc::Receiver<Control>,
) {
let engine: Engine = Arc::new(Mutex::new(backend));
let mut waiting: Vec<LoadReply> = Vec::new();
let mut attached_before = false;
let mut requests_closed = false;
let mut control_closed = false;
'attach: loop {
update(
&status,
if attached_before {
WorkerState::Restarting
} else {
WorkerState::Starting
},
None,
)
.await;
// Fail what queued up while the engine was away; nothing is replayed.
while let Ok(command) = requests.try_recv() {
command
.request
.obs
.error("worker is restarting; request was not replayed");
command.request.obs.finalize();
send_failure(
command.result,
"worker is restarting; request was not replayed".to_owned(),
)
.await;
}
let loaded = loop {
let model = config.model.clone();
let runtime = config.runtime.clone();
match on_engine(&engine, move |backend| backend.load(model, runtime)).await {
Ok(Ok(loaded))
if loaded
.validate_for_load(&config.model, &config.runtime)
.is_ok() =>
{
break loaded;
}
Ok(Ok(_)) => crate::elog!(
"the engine returned a load result that does not match the request"
),
Ok(Err(error)) => leleka_obs::info(
"api",
"engine_wait",
&[("reason", error.to_string().as_str().into())],
),
Err(error) => leleka_obs::info(
"api",
"engine_wait",
&[("reason", error.to_string().as_str().into())],
),
}
let retry = tokio::time::sleep(config.attach_retry);
tokio::pin!(retry);
loop {
tokio::select! {
biased;
_ = shutdown.changed() => {
update(&status, WorkerState::Stopping, None).await;
return;
}
_ = &mut retry => break,
message = control.recv(), if !control_closed => match message {
Some(Control::Load { reply }) => waiting.push(reply),
Some(Control::Reconfigure { reply, .. }) => crate::worker::reconfigure_unavailable(reply, "the worker is not attached to the engine"),
Some(Control::Unload { reply, .. }) => {
let _ = reply.send(leleka_serving_policy::idle::Outcome::NotLoaded);
}
None => control_closed = true,
},
command = requests.recv(), if !requests_closed => match command {
Some(command) => {
command.request.obs.error("worker is not attached to the engine; request was not replayed");
command.request.obs.finalize();
send_failure(
command.result,
"worker is not attached to the engine; request was not replayed".to_owned(),
)
.await
}
None => requests_closed = true,
},
}
}
};
attached_before = true;
crate::request_log::note_engine_attached();
update(&status, WorkerState::Ready, Some(config.max_context)).await;
status.write().await.output_cap = Some(config.max_output_tokens);
status.write().await.text_level_engine = true;
status.write().await.last_activity = Some(Instant::now());
for reply in waiting.drain(..) {
let _ = reply.send(Ok(()));
}
let mut health = tokio::time::interval(config.health_interval);
health.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Delay);
health.reset();
loop {
tokio::select! {
biased;
_ = shutdown.changed() => {
update(&status, WorkerState::Stopping, None).await;
return;
}
_ = health.tick() => {
let wanted = config.model.clone();
let present = on_engine(&engine, move |backend| backend.capabilities().supports(&wanted)).await;
if present != Ok(true) {
crate::request_log::note_engine_lost("the runtime no longer reports the model as loaded");
update(&status, WorkerState::Failed, None).await;
continue 'attach;
}
refresh_prefix_view(&engine, &config).await;
}
message = control.recv(), if !control_closed => match message {
Some(Control::Load { reply }) => {
let _ = reply.send(Ok(()));
}
Some(Control::Reconfigure { settings, reply }) => {
// Requests that arrive meanwhile wait in the queue: the engine reopens its serve stack in tens of seconds.
let answer = match on_engine(&engine, move |backend| backend.reconfigure(&settings)).await {
Ok(Ok(effective)) => Ok(effective),
Ok(Err(error)) => Err((
match error.code {
api::ErrorCode::InvalidRequest => 400,
api::ErrorCode::UnsupportedModel => 501,
api::ErrorCode::ResourceExhausted => 409,
api::ErrorCode::BackendUnavailable => 503,
api::ErrorCode::Internal => 500,
},
error.message,
)),
Err(message) => Err((500, message)),
};
let _ = reply.send(answer);
refresh_prefix_view(&engine, &config).await;
}
Some(Control::Unload { reply, .. }) => {
// The runtime's lifecycle belongs to its operator (leleka-cli), not to HTTP.
let _ = reply.send(leleka_serving_policy::idle::Outcome::Unsupported);
}
None => control_closed = true,
},
command = requests.recv(), if !requests_closed => {
let Some(mut command) = command else {
requests_closed = true;
continue;
};
if command.result.is_closed()
|| command.queue.take().is_some_and(|ticket| !ticket.claim())
{
continue;
}
status.write().await.last_activity = Some(Instant::now());
let _activity = command.activity.take();
match serve_one(&engine, &config, &status, &mut shutdown, &mut command, &loaded)
.await
{
Served::Done => {
status.write().await.last_activity = Some(Instant::now());
refresh_prefix_view(&engine, &config).await;
}
Served::Shutdown => {
update(&status, WorkerState::Stopping, None).await;
return;
}
Served::Lost(reason) => {
crate::request_log::note_engine_lost(&reason);
update(&status, WorkerState::Failed, None).await;
continue 'attach;
}
}
}
}
}
}
}
/// Copy the engine's prefix-cache summary into the view the status endpoint reads.
pub(super) async fn refresh_prefix_view(engine: &Engine, config: &BackendWorkerConfig) {
if let Some(view) = &config.prefix_view {
let summary = on_engine(engine, |backend| backend.prefix_cache_summary())
.await
.ok()
.flatten();
view.set(summary);
}
if let Some(view) = &config.memory_view {
let report = on_engine(engine, |backend| backend.memory_report())
.await
.ok()
.flatten();
view.set(report);
let telemetry = on_engine(engine, |backend| backend.telemetry_report())
.await
.ok()
.flatten();
view.set_telemetry(telemetry);
}
}
pub(super) async fn trigger_cancel(engine: &Engine, request_id: &str) {
let id = request_id.to_owned();
// The engine may already have finished; "not active" is not an error here.
let _ = on_engine(engine, move |backend| backend.cancel(&id)).await;
}
/// Fail a queued request: the client gets `message`, the request record gets its class.
pub(super) async fn fail_command(command: &mut GenerationCommand, message: String) {
command.request.obs.error(&message);
send_failure(command.result.take(), message).await;
}
@@ -0,0 +1,240 @@
//! Moved out of the parent module by STRA-338: fn serve_one, fn serve_one_inner.
#[allow(unused_imports)]
use super::*;
/// One generation, from the contract request to the terminal event the HTTP layer sees, plus its record.
pub(super) async fn serve_one(
engine: &Engine,
config: &BackendWorkerConfig,
status: &RwLock<WorkerStatus>,
shutdown: &mut watch::Receiver<bool>,
command: &mut GenerationCommand,
loaded: &api::LoadedModel,
) -> Served {
let served = serve_one_inner(engine, config, status, shutdown, command, loaded).await;
let obs = &command.request.obs;
match &served {
Served::Lost(reason) => {
obs.error(reason);
obs.engine_restarted();
}
Served::Shutdown => obs.error("the service is shutting down"),
Served::Done => {}
}
obs.finalize();
served
}
pub(super) async fn serve_one_inner(
engine: &Engine,
config: &BackendWorkerConfig,
status: &RwLock<WorkerStatus>,
shutdown: &mut watch::Receiver<bool>,
command: &mut GenerationCommand,
loaded: &api::LoadedModel,
) -> Served {
let request = match prepare(config, &command.request).await {
Ok(request) => request,
Err(message) => {
fail_command(command, message).await;
return Served::Done;
}
};
let id = request.request_id.clone();
let counted_input = u64::try_from(command.request.token_ids.len()).unwrap_or(u64::MAX);
status.write().await.metrics.start();
command.request.obs.engine_start();
// The line is written once the engine has the request (its time is taken now), so a slow log sink cannot delay the start.
let start_ms = crate::worker::unix_ms();
let max_new = request.max_output_tokens;
let started = Instant::now();
let start = {
let _span = crate::stage_trace::span("engine_start");
let model = loaded.clone();
on_engine(engine, move |backend| {
backend.start_generation(&model, request)
})
.await
};
if leleka_obs::settings().legacy {
// parsed by the lab scripts (scripts/cp/live_report.py, scripts/e2e/analyze_session.py)
leleka_obs::legacy_line(&format!(
"generation start: t_unix_ms={start_ms} prompt_tokens={counted_input} max_new={max_new}"
));
}
let stream = match start {
Ok(Ok(stream)) => stream,
Ok(Err(error)) => {
status.write().await.metrics.fail();
let message = format!("engine refused the generation: {error}");
fail_command(command, message.clone()).await;
return if error.code == api::ErrorCode::BackendUnavailable {
Served::Lost(message)
} else {
Served::Done
};
}
Err(message) => {
status.write().await.metrics.fail();
fail_command(command, message.clone()).await;
return Served::Lost(message);
}
};
// The contract stream blocks; a thread moves it onto an async channel. Dropping the receiver
// ends the thread, and dropping the stream tells the engine nobody is listening.
let (pump, mut events) = mpsc::channel::<Result<api::GenerationEvent, api::StreamError>>(16);
std::thread::spawn(move || {
let mut stream = stream;
loop {
match stream.recv() {
Ok(Some(event)) => {
let last = matches!(event, api::GenerationEvent::Terminal(_));
if pump.blocking_send(Ok(event)).is_err() || last {
return;
}
}
Ok(None) => return,
Err(error) => {
let _ = pump.blocking_send(Err(error));
return;
}
}
}
});
let mut stops = leleka_serving_policy::stop::LiteralStops::new(&STOP_LITERALS);
let mut buffered: Vec<Event> = Vec::new();
let mut usage: Option<api::Usage> = None;
let mut cancel: Option<Cancel> = None;
let mut first_delta: Option<Instant> = None;
let mut delivered: u64 = 0;
let mut last_progress = Instant::now();
let deadline = config.generation_timeout.map(|limit| started + limit);
let mut drain_deadline: Option<Instant> = None;
let mut ticker = tokio::time::interval(Duration::from_secs(1));
ticker.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Delay);
ticker.reset();
macro_rules! begin_cancel {
($cause:expr) => {{
cancel = Some($cause);
drain_deadline = Some(Instant::now() + config.cancel_drain_timeout);
trigger_cancel(engine, &id).await;
}};
}
loop {
let item = tokio::select! {
biased;
_ = shutdown.changed() => {
trigger_cancel(engine, &id).await;
return Served::Shutdown;
}
_ = tokio::time::sleep_until(drain_deadline.unwrap_or_else(Instant::now)), if drain_deadline.is_some() => {
status.write().await.metrics.fail();
let message = match cancel.take() {
Some(Cancel::Failure(message)) => message,
_ => "engine did not terminate the generation after it was cancelled".to_owned(),
};
fail_command(command, message.clone()).await;
return Served::Lost(message);
}
_ = tokio::time::sleep_until(deadline.unwrap_or_else(Instant::now)), if deadline.is_some() && cancel.is_none() => {
begin_cancel!(Cancel::Failure(
"generation exceeded configured execution deadline".to_owned()
));
continue;
}
_ = command.result.closed(), if cancel.is_none() => {
begin_cancel!(Cancel::Client);
continue;
}
_ = ticker.tick(), if config.stall_timeout.is_some() && cancel.is_none() => {
if let Some(limit) = config.stall_timeout
&& last_progress.elapsed() >= limit
{
begin_cancel!(Cancel::Failure(format!(
"engine made no progress for {} s during a request (stall watchdog)",
last_progress.elapsed().as_secs()
)));
}
continue;
}
item = events.recv() => item,
};
last_progress = Instant::now();
let event = match item {
Some(Ok(event)) => event,
Some(Err(api::StreamError::MissingTerminal)) | None => {
status.write().await.metrics.fail();
let message = match cancel.take() {
Some(Cancel::Failure(message)) => message,
_ => "engine stream ended without a terminal event".to_owned(),
};
fail_command(command, message.clone()).await;
return Served::Lost(message);
}
};
match event {
api::GenerationEvent::TextDelta { text } => {
if cancel.is_some() {
continue;
}
if first_delta.is_none() {
command.request.obs.first_token();
}
first_delta.get_or_insert_with(Instant::now);
let piece = stops.push(&text);
if !piece.emit.is_empty() {
let retokenize = crate::stage_trace::time("delta_retokenize", || {
text_tokens(&config.tokenizer, &piece.emit)
});
match retokenize {
Ok(ids) => {
for id in ids {
delivered += 1;
deliver(command, &mut buffered, Event::Token(id)).await;
}
}
Err(message) => {
begin_cancel!(Cancel::Failure(message));
continue;
}
}
}
if piece.stopped {
begin_cancel!(Cancel::Marker);
}
}
api::GenerationEvent::Usage(report) => usage = Some(report),
api::GenerationEvent::ToolCallDelta { .. } => {
if cancel.is_none() {
begin_cancel!(Cancel::Failure(
"the engine sent a tool-call delta although it advertises native tool calls as unsupported".to_owned()
));
}
}
api::GenerationEvent::Terminal(terminal) => {
return conclude(
command,
status,
buffered,
terminal,
Conclusion {
cancel,
stops: &mut stops,
usage,
delivered,
started,
first_delta,
counted_input,
tokenizer: &config.tokenizer,
},
)
.await;
}
}
}
}
+13 -566
View File
@@ -88,9 +88,6 @@ struct Function {
}
type Invalid = (&'static str, &'static str);
fn invalid(param: &'static str, message: &'static str) -> Invalid {
(param, message)
}
/// A message's content: plain text, or (user messages only) the list of text and picture parts in the Responses
/// shape (`input_text` / `input_image`), whose order the template keeps.
enum Content {
@@ -98,567 +95,17 @@ enum Content {
Parts(Vec<Value>),
}
impl Content {
fn text(self) -> Option<String> {
match self {
Self::Text(text) => Some(text),
Self::Parts(_) => None,
}
}
fn into_value(self) -> Value {
match self {
Self::Text(text) => Value::String(text),
Self::Parts(parts) => Value::Array(parts),
}
}
}
/// An `image_url` part (`serve/frontend.py` `_image_source`): `"image_url": {"url": ..., "detail": ...}` or the bare
/// string. The source itself is checked when it is read, so an empty one fails there with the Python server's words.
fn image_part(part: &serde_json::Map<String, Value>) -> Result<Value, Invalid> {
let bad = || {
invalid(
"messages",
"image_url parts need an image_url of text or {url, detail}",
)
};
if part
.keys()
.any(|k| !matches!(k.as_str(), "type" | "image_url"))
{
return Err(bad());
}
let url = match part.get("image_url") {
None | Some(Value::Null) => String::new(),
Some(Value::String(url)) => url.clone(),
Some(Value::Object(object)) => {
if object
.keys()
.any(|k| !matches!(k.as_str(), "url" | "detail"))
{
return Err(bad());
}
match object.get("url") {
None | Some(Value::Null) => String::new(),
Some(Value::String(url)) => url.clone(),
_ => return Err(bad()),
}
}
_ => return Err(bad()),
};
Ok(json!({"type": "input_image", "image_url": url}))
}
fn content(value: Option<Value>, role: &str) -> Result<Option<Content>, Invalid> {
match value {
None | Some(Value::Null) => Ok(None),
Some(Value::String(s)) => Ok(Some(Content::Text(s))),
Some(Value::Array(parts)) => {
let mut text = String::new();
let mut listed = Vec::new();
let mut pictures = false;
for part in parts {
let object = part
.as_object()
.ok_or(invalid("messages", "content must contain text parts"))?;
if part["type"] == "image_url" {
if role != "user" {
return Err(invalid(
"messages",
"image content is only supported in user messages",
));
}
pictures = true;
listed.push(image_part(object)?);
continue;
}
if object.len() != 2 || part["type"] != "text" {
return Err(invalid(
"messages",
"only text and image_url content parts are supported",
));
}
let piece = part["text"]
.as_str()
.ok_or(invalid("messages", "text part needs a string"))?;
text.push_str(piece);
listed.push(json!({"type": "input_text", "text": piece}));
}
Ok(Some(if pictures {
Content::Parts(listed)
} else {
Content::Text(text)
}))
}
_ => Err(invalid("messages", "content must be text or text parts")),
}
}
impl Request {
fn into_responses(self) -> Result<(Value, bool, bool), Invalid> {
if self.n.is_some_and(|n| n != 1) {
return Err(invalid("n", "only n=1 is supported"));
}
if self.max_tokens.is_some() && self.max_completion_tokens.is_some() {
return Err(invalid(
"max_completion_tokens",
"specify only one output token limit",
));
}
if self
.reasoning_effort
.as_deref()
.is_some_and(|e| e != "none")
{
return Err(invalid(
"reasoning_effort",
"this Chat subset supports only reasoning_effort=none",
));
}
if self.store == Some(true) {
return Err(invalid(
"store",
"stored Chat completions are not supported",
));
}
if self.stop.is_some() {
return Err(invalid("stop", "custom stop sequences are not supported"));
}
if self.logprobs == Some(true) {
return Err(invalid("logprobs", "log probabilities are not supported"));
}
if !self.stream && self.stream_options.is_some() {
return Err(invalid(
"stream_options",
"stream_options requires stream=true",
));
}
if self
.stream_options
.as_ref()
.is_some_and(|s| s.include_obfuscation == Some(true))
{
return Err(invalid(
"stream_options",
"stream obfuscation is not supported",
));
}
let include_usage = self
.stream_options
.is_some_and(|s| s.include_usage == Some(true));
let mut input = Vec::new();
for message in self.messages {
if message.refusal.is_some() {
return Err(invalid("messages", "refusal content is not supported"));
}
let text = content(message.content, &message.role)?;
match message.role.as_str() {
"system" | "developer" | "user" | "assistant" => {
if message.tool_call_id.is_some()
|| (message.role != "assistant" && message.tool_calls.is_some())
{
return Err(invalid(
"messages",
"tool_calls belongs to assistant; tool_call_id belongs to tool",
));
}
let calls = message.tool_calls.unwrap_or_default();
if text.is_none() && calls.is_empty() {
return Err(invalid(
"messages",
"message needs text or assistant tool calls",
));
}
if let Some(text) = text {
input.push(json!({"role":message.role,"content":text.into_value()}));
}
for call in calls {
if call.kind != "function" {
return Err(invalid(
"messages",
"only function tool calls are supported",
));
}
input.push(json!({"type":"function_call","call_id":call.id,"name":call.function.name,"arguments":call.function.arguments}));
}
}
"tool" => {
if message.tool_calls.is_some() {
return Err(invalid("messages", "tool result cannot declare tool calls"));
}
input.push(json!({"type":"function_call_output", "call_id":message.tool_call_id.ok_or(invalid("messages", "tool result needs tool_call_id"))?, "output":text.and_then(Content::text).ok_or(invalid("messages", "tool result needs text"))?}));
}
_ => return Err(invalid("messages", "unsupported message role")),
}
}
let mut tools = Vec::new();
for tool in self.tools {
if tool.kind != "function" {
return Err(invalid("tools", "only function tools are supported"));
}
let f = tool.function;
let mut value = json!({"type":"function","name":f.name,"parameters":f.parameters.unwrap_or(json!({"type":"object","properties":{}}))});
if let Some(description) = f.description {
value["description"] = json!(description);
}
if let Some(strict) = f.strict {
value["strict"] = json!(strict);
}
tools.push(value);
}
let choice = match self.tool_choice {
Some(Value::Object(value)) => {
if value.len() != 2 || value.get("type") != Some(&json!("function")) {
return Err(invalid("tool_choice", "unsupported tool choice"));
}
let function = value
.get("function")
.and_then(Value::as_object)
.ok_or(invalid("tool_choice", "forced function needs a name"))?;
if function.len() != 1 {
return Err(invalid("tool_choice", "forced function accepts only name"));
}
Some(
json!({"type":"function","name":function.get("name").and_then(Value::as_str).ok_or(invalid("tool_choice", "forced function needs a name"))?}),
)
}
choice => choice,
};
let format = match self.response_format {
Some(Value::Object(mut format))
if format.get("type") == Some(&json!("json_schema")) =>
{
if format.len() != 2 {
return Err(invalid(
"response_format",
"json_schema format requires a json_schema object",
));
}
let mut schema = format
.remove("json_schema")
.and_then(|v| v.as_object().cloned())
.ok_or(invalid(
"response_format",
"json_schema format requires a json_schema object",
))?;
if schema
.keys()
.any(|k| !matches!(k.as_str(), "name" | "schema" | "strict"))
{
return Err(invalid(
"response_format",
"supported json_schema fields are name, schema and strict",
));
}
schema.insert("type".into(), json!("json_schema"));
Some(Value::Object(schema))
}
Some(value) => {
if !value.as_object().is_some_and(|o| o.len() == 1)
|| !matches!(value["type"].as_str(), Some("text" | "json_object"))
{
return Err(invalid("response_format", "unsupported response format"));
}
Some(value)
}
None => None,
};
let mut request = json!({"model":self.model,"input":input,"stream":self.stream,"store":false,
"reasoning":{"effort":"none"},"tools":tools});
for (key, value) in [
(
"max_output_tokens",
self.max_completion_tokens
.or(self.max_tokens)
.map(|v| json!(v)),
),
("temperature", self.temperature.map(|v| json!(v))),
("top_p", self.top_p.map(|v| json!(v))),
(
"parallel_tool_calls",
self.parallel_tool_calls.map(|v| json!(v)),
),
("tool_choice", choice),
] {
if let Some(value) = value {
request[key] = value;
}
}
if let Some(format) = format {
request["text"] = json!({"format":format});
}
Ok((request, self.stream, include_usage))
}
}
fn usage(response: &Value) -> Value {
let u = &response["usage"];
json!({"prompt_tokens":u["input_tokens"],"completion_tokens":u["output_tokens"],"total_tokens":u["total_tokens"],
"prompt_tokens_details":{"cached_tokens":u["input_tokens_details"]["cached_tokens"]},
"completion_tokens_details":{"reasoning_tokens":u["output_tokens_details"]["reasoning_tokens"]}})
}
fn call(item: &Value) -> Value {
json!({"id":item["call_id"],"type":"function","function":{"name":item["name"],"arguments":item["arguments"]}})
}
fn finish(response: &Value) -> &'static str {
if response["status"] == "incomplete" {
"length"
} else if response["output"]
.as_array()
.is_some_and(|items| items.iter().any(|i| i["type"] == "function_call"))
{
"tool_calls"
} else {
"stop"
}
}
fn identity(response: &Value, object: &str) -> Value {
json!({"id":format!("chatcmpl-{}",response["id"].as_str().unwrap_or("unknown")),"object":object,
"created":response["created_at"],"model":response["model"]})
}
fn completion(response: &Value) -> Value {
let mut text = String::new();
let mut calls = Vec::new();
if let Some(items) = response["output"].as_array() {
for item in items {
if item["type"] == "function_call" {
calls.push(call(item));
}
if item["type"] == "message"
&& let Some(parts) = item["content"].as_array()
{
for part in parts {
if part["type"] == "output_text" {
text.push_str(part["text"].as_str().unwrap_or(""));
}
}
}
}
}
let mut message = json!({"role":"assistant","content":if text.is_empty() && !calls.is_empty() {Value::Null} else {json!(text)},"refusal":null});
if !calls.is_empty() {
message["tool_calls"] = json!(calls);
}
let mut value = identity(response, "chat.completion");
value["choices"] =
json!([{"index":0,"message":message,"finish_reason":finish(response),"logprobs":null}]);
value["usage"] = usage(response);
value
}
fn error(status: StatusCode, code: &str, param: Option<&str>, message: &str) -> Response {
(status,Json(json!({"error":{"type":if status.is_server_error(){"server_error"}else{"invalid_request_error"},"code":code,"param":param,"message":message}}))).into_response()
}
pub async fn create(
State(state): State<AppState>,
body: Result<Json<Value>, JsonRejection>,
) -> Response {
let Json(body) = match body {
Ok(body) => body,
Err(e) => return error(e.status(), "invalid_json", None, &e.to_string()),
};
// Sampling extensions (top_k, min_p, penalties, seed, ...) are validated once, by the native request.
let (body, extensions) = crate::sampling::split_extensions(body);
let request: Request = match serde_json::from_value(body) {
Ok(r) => r,
Err(e) => {
return error(
StatusCode::BAD_REQUEST,
"invalid_request",
None,
&e.to_string(),
);
}
};
let (mut request, stream, include_usage) = match request.into_responses() {
Ok(r) => r,
Err((p, m)) => {
return error(
StatusCode::BAD_REQUEST,
"unsupported_chat_feature",
Some(p),
m,
);
}
};
for (key, value) in extensions {
request[key] = value;
}
let response = responses::create(State(state), Ok(Json(request))).await;
if stream && response.status().is_success() {
return stream_response(response.into_body(), include_usage);
}
let status = response.status();
// a refusal that tells the client when to come back (503 memory_pressure) keeps its Retry-After through the re-wrapping below
let retry_after = response
.headers()
.get(axum::http::header::RETRY_AFTER)
.cloned();
let bytes = match to_bytes(response.into_body(), MAX_EVENT).await {
Ok(b) => b,
Err(_) => {
return error(
StatusCode::BAD_GATEWAY,
"response_too_large",
None,
"native response could not be read within the adapter limit",
);
}
};
let mut value: Value = match serde_json::from_slice(&bytes) {
Ok(v) => v,
Err(_) => {
return error(
StatusCode::BAD_GATEWAY,
"invalid_native_response",
None,
"native response was not JSON",
);
}
};
if !status.is_success() {
if let Some(param) = value["error"]["param"].as_str() {
let mapped = match param {
"input" => "messages",
"max_output_tokens" => "max_completion_tokens",
"text" => "response_format",
p => p,
};
value["error"]["param"] = json!(mapped);
}
let mut refusal = (status, Json(value)).into_response();
if let Some(retry_after) = retry_after {
refusal
.headers_mut()
.insert(axum::http::header::RETRY_AFTER, retry_after);
}
return refusal;
}
Json(completion(&value)).into_response()
}
struct Events(mpsc::Receiver<Event>);
impl Stream for Events {
type Item = Result<Event, Infallible>;
fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
self.0.poll_recv(cx).map(|v| v.map(Ok))
}
}
async fn send(sender: &mpsc::Sender<Event>, value: Value) -> Result<(), &'static str> {
sender
.send(Event::default().data(value.to_string()))
.await
.map_err(|_| "client disconnected")
}
fn chunk(base: &Value, delta: Value, reason: Value, include_usage: bool) -> Value {
let mut v = base.clone();
v["choices"] = json!([{"index":0,"delta":delta,"finish_reason":reason,"logprobs":null}]);
if include_usage {
v["usage"] = Value::Null;
}
v
}
async fn adapt(
body: &mut Body,
sender: &mpsc::Sender<Event>,
include_usage: bool,
) -> Result<(), &'static str> {
let mut reader = NativeEvents::new(body);
let mut base = None;
let mut calls = 0;
loop {
let event =
tokio::select! { _=sender.closed()=>return Ok(()), event=reader.next()=>event? };
match event["type"].as_str() {
Some("response.created") => {
let value = identity(&event["response"], "chat.completion.chunk");
send(
sender,
chunk(
&value,
json!({"role":"assistant","content":""}),
Value::Null,
include_usage,
),
)
.await?;
base = Some(value);
}
Some("response.output_text.delta") => {
send(
sender,
chunk(
base.as_ref().ok_or("missing stream identity")?,
json!({"content":event["delta"]}),
Value::Null,
include_usage,
),
)
.await?;
}
Some("response.output_item.done") if event["item"]["type"] == "function_call" => {
let mut item = call(&event["item"]);
item["index"] = json!(calls);
calls += 1;
send(
sender,
chunk(
base.as_ref().ok_or("missing stream identity")?,
json!({"tool_calls":[item]}),
Value::Null,
include_usage,
),
)
.await?;
}
Some("response.completed" | "response.incomplete") => {
let base = base.as_ref().ok_or("missing stream identity")?;
send(
sender,
chunk(
base,
json!({}),
json!(finish(&event["response"])),
include_usage,
),
)
.await?;
if include_usage {
let mut v = base.clone();
v["choices"] = json!([]);
v["usage"] = usage(&event["response"]);
send(sender, v).await?;
}
sender
.send(Event::default().data("[DONE]"))
.await
.map_err(|_| "client disconnected")?;
return Ok(());
}
Some("response.failed") => {
send(sender, json!({"error":event["response"]["error"]})).await?;
sender
.send(Event::default().data("[DONE]"))
.await
.map_err(|_| "client disconnected")?;
return Ok(());
}
_ => {}
}
}
}
fn stream_response(mut body: Body, include_usage: bool) -> Response {
let (sender, received) = mpsc::channel(8);
tokio::spawn(async move {
let outcome = adapt(&mut body, &sender, include_usage).await;
drop(body); // Release the native receiver before reporting an adapter failure.
if let Err(message) = outcome {
let _=send(&sender,json!({"error":{"type":"server_error","code":"chat_stream_failed","message":message}})).await;
let _ = sender.send(Event::default().data("[DONE]")).await;
}
});
Sse::new(Events(received))
.keep_alive(crate::native_events::keep_alive())
.into_response()
}
mod invalid;
#[allow(unused_imports)]
pub use invalid::*;
mod impl_request;
#[allow(unused_imports)]
pub use impl_request::*;
mod completion;
#[allow(unused_imports)]
pub use completion::*;
mod stream_response;
#[allow(unused_imports)]
pub use stream_response::*;
+239
View File
@@ -0,0 +1,239 @@
//! Moved out of the parent module by STRA-338: fn completion, fn error, fn create, impl Stream_for_Events, fn send, fn chunk ....
#[allow(unused_imports)]
use super::*;
pub(super) fn completion(response: &Value) -> Value {
let mut text = String::new();
let mut calls = Vec::new();
if let Some(items) = response["output"].as_array() {
for item in items {
if item["type"] == "function_call" {
calls.push(call(item));
}
if item["type"] == "message"
&& let Some(parts) = item["content"].as_array()
{
for part in parts {
if part["type"] == "output_text" {
text.push_str(part["text"].as_str().unwrap_or(""));
}
}
}
}
}
let mut message = json!({"role":"assistant","content":if text.is_empty() && !calls.is_empty() {Value::Null} else {json!(text)},"refusal":null});
if !calls.is_empty() {
message["tool_calls"] = json!(calls);
}
let mut value = identity(response, "chat.completion");
value["choices"] =
json!([{"index":0,"message":message,"finish_reason":finish(response),"logprobs":null}]);
value["usage"] = usage(response);
value
}
pub(super) fn error(
status: StatusCode,
code: &str,
param: Option<&str>,
message: &str,
) -> Response {
(status,Json(json!({"error":{"type":if status.is_server_error(){"server_error"}else{"invalid_request_error"},"code":code,"param":param,"message":message}}))).into_response()
}
pub async fn create(
State(state): State<AppState>,
body: Result<Json<Value>, JsonRejection>,
) -> Response {
let Json(body) = match body {
Ok(body) => body,
Err(e) => return error(e.status(), "invalid_json", None, &e.to_string()),
};
// Sampling extensions (top_k, min_p, penalties, seed, ...) are validated once, by the native request.
let (body, extensions) = crate::sampling::split_extensions(body);
let request: Request = match serde_json::from_value(body) {
Ok(r) => r,
Err(e) => {
return error(
StatusCode::BAD_REQUEST,
"invalid_request",
None,
&e.to_string(),
);
}
};
let (mut request, stream, include_usage) = match request.into_responses() {
Ok(r) => r,
Err((p, m)) => {
return error(
StatusCode::BAD_REQUEST,
"unsupported_chat_feature",
Some(p),
m,
);
}
};
for (key, value) in extensions {
request[key] = value;
}
let response = responses::create(State(state), Ok(Json(request))).await;
if stream && response.status().is_success() {
return stream_response(response.into_body(), include_usage);
}
let status = response.status();
// a refusal that tells the client when to come back (503 memory_pressure) keeps its Retry-After through the re-wrapping below
let retry_after = response
.headers()
.get(axum::http::header::RETRY_AFTER)
.cloned();
let bytes = match to_bytes(response.into_body(), MAX_EVENT).await {
Ok(b) => b,
Err(_) => {
return error(
StatusCode::BAD_GATEWAY,
"response_too_large",
None,
"native response could not be read within the adapter limit",
);
}
};
let mut value: Value = match serde_json::from_slice(&bytes) {
Ok(v) => v,
Err(_) => {
return error(
StatusCode::BAD_GATEWAY,
"invalid_native_response",
None,
"native response was not JSON",
);
}
};
if !status.is_success() {
if let Some(param) = value["error"]["param"].as_str() {
let mapped = match param {
"input" => "messages",
"max_output_tokens" => "max_completion_tokens",
"text" => "response_format",
p => p,
};
value["error"]["param"] = json!(mapped);
}
let mut refusal = (status, Json(value)).into_response();
if let Some(retry_after) = retry_after {
refusal
.headers_mut()
.insert(axum::http::header::RETRY_AFTER, retry_after);
}
return refusal;
}
Json(completion(&value)).into_response()
}
impl Stream for Events {
type Item = Result<Event, Infallible>;
fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
self.0.poll_recv(cx).map(|v| v.map(Ok))
}
}
pub(super) async fn send(sender: &mpsc::Sender<Event>, value: Value) -> Result<(), &'static str> {
sender
.send(Event::default().data(value.to_string()))
.await
.map_err(|_| "client disconnected")
}
pub(super) fn chunk(base: &Value, delta: Value, reason: Value, include_usage: bool) -> Value {
let mut v = base.clone();
v["choices"] = json!([{"index":0,"delta":delta,"finish_reason":reason,"logprobs":null}]);
if include_usage {
v["usage"] = Value::Null;
}
v
}
pub(super) async fn adapt(
body: &mut Body,
sender: &mpsc::Sender<Event>,
include_usage: bool,
) -> Result<(), &'static str> {
let mut reader = NativeEvents::new(body);
let mut base = None;
let mut calls = 0;
loop {
let event =
tokio::select! { _=sender.closed()=>return Ok(()), event=reader.next()=>event? };
match event["type"].as_str() {
Some("response.created") => {
let value = identity(&event["response"], "chat.completion.chunk");
send(
sender,
chunk(
&value,
json!({"role":"assistant","content":""}),
Value::Null,
include_usage,
),
)
.await?;
base = Some(value);
}
Some("response.output_text.delta") => {
send(
sender,
chunk(
base.as_ref().ok_or("missing stream identity")?,
json!({"content":event["delta"]}),
Value::Null,
include_usage,
),
)
.await?;
}
Some("response.output_item.done") if event["item"]["type"] == "function_call" => {
let mut item = call(&event["item"]);
item["index"] = json!(calls);
calls += 1;
send(
sender,
chunk(
base.as_ref().ok_or("missing stream identity")?,
json!({"tool_calls":[item]}),
Value::Null,
include_usage,
),
)
.await?;
}
Some("response.completed" | "response.incomplete") => {
let base = base.as_ref().ok_or("missing stream identity")?;
send(
sender,
chunk(
base,
json!({}),
json!(finish(&event["response"])),
include_usage,
),
)
.await?;
if include_usage {
let mut v = base.clone();
v["choices"] = json!([]);
v["usage"] = usage(&event["response"]);
send(sender, v).await?;
}
sender
.send(Event::default().data("[DONE]"))
.await
.map_err(|_| "client disconnected")?;
return Ok(());
}
Some("response.failed") => {
send(sender, json!({"error":event["response"]["error"]})).await?;
sender
.send(Event::default().data("[DONE]"))
.await
.map_err(|_| "client disconnected")?;
return Ok(());
}
_ => {}
}
}
}
+227
View File
@@ -0,0 +1,227 @@
//! Moved out of the parent module by STRA-338: impl Request, fn usage, fn call, fn finish, fn identity.
#[allow(unused_imports)]
use super::*;
impl Request {
pub(super) fn into_responses(self) -> Result<(Value, bool, bool), Invalid> {
if self.n.is_some_and(|n| n != 1) {
return Err(invalid("n", "only n=1 is supported"));
}
if self.max_tokens.is_some() && self.max_completion_tokens.is_some() {
return Err(invalid(
"max_completion_tokens",
"specify only one output token limit",
));
}
if self
.reasoning_effort
.as_deref()
.is_some_and(|e| e != "none")
{
return Err(invalid(
"reasoning_effort",
"this Chat subset supports only reasoning_effort=none",
));
}
if self.store == Some(true) {
return Err(invalid(
"store",
"stored Chat completions are not supported",
));
}
if self.stop.is_some() {
return Err(invalid("stop", "custom stop sequences are not supported"));
}
if self.logprobs == Some(true) {
return Err(invalid("logprobs", "log probabilities are not supported"));
}
if !self.stream && self.stream_options.is_some() {
return Err(invalid(
"stream_options",
"stream_options requires stream=true",
));
}
if self
.stream_options
.as_ref()
.is_some_and(|s| s.include_obfuscation == Some(true))
{
return Err(invalid(
"stream_options",
"stream obfuscation is not supported",
));
}
let include_usage = self
.stream_options
.is_some_and(|s| s.include_usage == Some(true));
let mut input = Vec::new();
for message in self.messages {
if message.refusal.is_some() {
return Err(invalid("messages", "refusal content is not supported"));
}
let text = content(message.content, &message.role)?;
match message.role.as_str() {
"system" | "developer" | "user" | "assistant" => {
if message.tool_call_id.is_some()
|| (message.role != "assistant" && message.tool_calls.is_some())
{
return Err(invalid(
"messages",
"tool_calls belongs to assistant; tool_call_id belongs to tool",
));
}
let calls = message.tool_calls.unwrap_or_default();
if text.is_none() && calls.is_empty() {
return Err(invalid(
"messages",
"message needs text or assistant tool calls",
));
}
if let Some(text) = text {
input.push(json!({"role":message.role,"content":text.into_value()}));
}
for call in calls {
if call.kind != "function" {
return Err(invalid(
"messages",
"only function tool calls are supported",
));
}
input.push(json!({"type":"function_call","call_id":call.id,"name":call.function.name,"arguments":call.function.arguments}));
}
}
"tool" => {
if message.tool_calls.is_some() {
return Err(invalid("messages", "tool result cannot declare tool calls"));
}
input.push(json!({"type":"function_call_output", "call_id":message.tool_call_id.ok_or(invalid("messages", "tool result needs tool_call_id"))?, "output":text.and_then(Content::text).ok_or(invalid("messages", "tool result needs text"))?}));
}
_ => return Err(invalid("messages", "unsupported message role")),
}
}
let mut tools = Vec::new();
for tool in self.tools {
if tool.kind != "function" {
return Err(invalid("tools", "only function tools are supported"));
}
let f = tool.function;
let mut value = json!({"type":"function","name":f.name,"parameters":f.parameters.unwrap_or(json!({"type":"object","properties":{}}))});
if let Some(description) = f.description {
value["description"] = json!(description);
}
if let Some(strict) = f.strict {
value["strict"] = json!(strict);
}
tools.push(value);
}
let choice = match self.tool_choice {
Some(Value::Object(value)) => {
if value.len() != 2 || value.get("type") != Some(&json!("function")) {
return Err(invalid("tool_choice", "unsupported tool choice"));
}
let function = value
.get("function")
.and_then(Value::as_object)
.ok_or(invalid("tool_choice", "forced function needs a name"))?;
if function.len() != 1 {
return Err(invalid("tool_choice", "forced function accepts only name"));
}
Some(
json!({"type":"function","name":function.get("name").and_then(Value::as_str).ok_or(invalid("tool_choice", "forced function needs a name"))?}),
)
}
choice => choice,
};
let format = match self.response_format {
Some(Value::Object(mut format))
if format.get("type") == Some(&json!("json_schema")) =>
{
if format.len() != 2 {
return Err(invalid(
"response_format",
"json_schema format requires a json_schema object",
));
}
let mut schema = format
.remove("json_schema")
.and_then(|v| v.as_object().cloned())
.ok_or(invalid(
"response_format",
"json_schema format requires a json_schema object",
))?;
if schema
.keys()
.any(|k| !matches!(k.as_str(), "name" | "schema" | "strict"))
{
return Err(invalid(
"response_format",
"supported json_schema fields are name, schema and strict",
));
}
schema.insert("type".into(), json!("json_schema"));
Some(Value::Object(schema))
}
Some(value) => {
if !value.as_object().is_some_and(|o| o.len() == 1)
|| !matches!(value["type"].as_str(), Some("text" | "json_object"))
{
return Err(invalid("response_format", "unsupported response format"));
}
Some(value)
}
None => None,
};
let mut request = json!({"model":self.model,"input":input,"stream":self.stream,"store":false,
"reasoning":{"effort":"none"},"tools":tools});
for (key, value) in [
(
"max_output_tokens",
self.max_completion_tokens
.or(self.max_tokens)
.map(|v| json!(v)),
),
("temperature", self.temperature.map(|v| json!(v))),
("top_p", self.top_p.map(|v| json!(v))),
(
"parallel_tool_calls",
self.parallel_tool_calls.map(|v| json!(v)),
),
("tool_choice", choice),
] {
if let Some(value) = value {
request[key] = value;
}
}
if let Some(format) = format {
request["text"] = json!({"format":format});
}
Ok((request, self.stream, include_usage))
}
}
pub(super) fn usage(response: &Value) -> Value {
let u = &response["usage"];
json!({"prompt_tokens":u["input_tokens"],"completion_tokens":u["output_tokens"],"total_tokens":u["total_tokens"],
"prompt_tokens_details":{"cached_tokens":u["input_tokens_details"]["cached_tokens"]},
"completion_tokens_details":{"reasoning_tokens":u["output_tokens_details"]["reasoning_tokens"]}})
}
pub(super) fn call(item: &Value) -> Value {
json!({"id":item["call_id"],"type":"function","function":{"name":item["name"],"arguments":item["arguments"]}})
}
pub(super) fn finish(response: &Value) -> &'static str {
if response["status"] == "incomplete" {
"length"
} else if response["output"]
.as_array()
.is_some_and(|items| items.iter().any(|i| i["type"] == "function_call"))
{
"tool_calls"
} else {
"stop"
}
}
pub(super) fn identity(response: &Value, object: &str) -> Value {
json!({"id":format!("chatcmpl-{}",response["id"].as_str().unwrap_or("unknown")),"object":object,
"created":response["created_at"],"model":response["model"]})
}
+105
View File
@@ -0,0 +1,105 @@
//! Moved out of the parent module by STRA-338: fn invalid, impl Content, fn image_part, fn content.
#[allow(unused_imports)]
use super::*;
pub(super) fn invalid(param: &'static str, message: &'static str) -> Invalid {
(param, message)
}
impl Content {
pub(super) fn text(self) -> Option<String> {
match self {
Self::Text(text) => Some(text),
Self::Parts(_) => None,
}
}
pub(super) fn into_value(self) -> Value {
match self {
Self::Text(text) => Value::String(text),
Self::Parts(parts) => Value::Array(parts),
}
}
}
/// An `image_url` part (`serve/frontend.py` `_image_source`): `"image_url": {"url": ..., "detail": ...}` or the bare
/// string. The source itself is checked when it is read, so an empty one fails there with the Python server's words.
pub(super) fn image_part(part: &serde_json::Map<String, Value>) -> Result<Value, Invalid> {
let bad = || {
invalid(
"messages",
"image_url parts need an image_url of text or {url, detail}",
)
};
if part
.keys()
.any(|k| !matches!(k.as_str(), "type" | "image_url"))
{
return Err(bad());
}
let url = match part.get("image_url") {
None | Some(Value::Null) => String::new(),
Some(Value::String(url)) => url.clone(),
Some(Value::Object(object)) => {
if object
.keys()
.any(|k| !matches!(k.as_str(), "url" | "detail"))
{
return Err(bad());
}
match object.get("url") {
None | Some(Value::Null) => String::new(),
Some(Value::String(url)) => url.clone(),
_ => return Err(bad()),
}
}
_ => return Err(bad()),
};
Ok(json!({"type": "input_image", "image_url": url}))
}
pub(super) fn content(value: Option<Value>, role: &str) -> Result<Option<Content>, Invalid> {
match value {
None | Some(Value::Null) => Ok(None),
Some(Value::String(s)) => Ok(Some(Content::Text(s))),
Some(Value::Array(parts)) => {
let mut text = String::new();
let mut listed = Vec::new();
let mut pictures = false;
for part in parts {
let object = part
.as_object()
.ok_or(invalid("messages", "content must contain text parts"))?;
if part["type"] == "image_url" {
if role != "user" {
return Err(invalid(
"messages",
"image content is only supported in user messages",
));
}
pictures = true;
listed.push(image_part(object)?);
continue;
}
if object.len() != 2 || part["type"] != "text" {
return Err(invalid(
"messages",
"only text and image_url content parts are supported",
));
}
let piece = part["text"]
.as_str()
.ok_or(invalid("messages", "text part needs a string"))?;
text.push_str(piece);
listed.push(json!({"type": "input_text", "text": piece}));
}
Ok(Some(if pictures {
Content::Parts(listed)
} else {
Content::Text(text)
}))
}
_ => Err(invalid("messages", "content must be text or text parts")),
}
}
+19
View File
@@ -0,0 +1,19 @@
//! Moved out of the parent module by STRA-338: fn stream_response.
#[allow(unused_imports)]
use super::*;
pub(super) fn stream_response(mut body: Body, include_usage: bool) -> Response {
let (sender, received) = mpsc::channel(8);
tokio::spawn(async move {
let outcome = adapt(&mut body, &sender, include_usage).await;
drop(body); // Release the native receiver before reporting an adapter failure.
if let Err(message) = outcome {
let _=send(&sender,json!({"error":{"type":"server_error","code":"chat_stream_failed","message":message}})).await;
let _ = sender.send(Event::default().data("[DONE]")).await;
}
});
Sse::new(Events(received))
.keep_alive(crate::native_events::keep_alive())
.into_response()
}
+10 -949
View File
@@ -159,954 +159,15 @@ struct ControlVectorFile {
scale: f32,
}
impl ControlVector {
/// The engine arguments for this vector after checking the files (GGUF control vectors with
/// F32 `direction.<layer>` tensors of one width), so a typo stops the start, not the load.
fn engine_args(&self) -> Result<Vec<String>, String> {
if self.files.is_empty() || self.files.len() > 16 {
return Err("control_vector.files needs 1 to 16 files".into());
}
let mode = match self.mode.as_deref() {
None => leleka_serving_policy::cvec::Mode::Add,
Some(text) => leleka_serving_policy::cvec::parse_mode(text)?,
};
let single = match self.dir.as_deref() {
None => -1,
Some(text) => leleka_serving_policy::cvec::parse_dir(text)?,
};
if single >= 0 && mode != leleka_serving_policy::cvec::Mode::Project {
return Err("control_vector.dir single:L needs mode project".into());
}
let mut width: Option<u64> = None;
let mut list = Vec::new();
for file in &self.files {
if !file.path.is_absolute()
|| file.path.to_str().is_none_or(|p| p.contains([',', '\n']))
{
return Err("control_vector file paths must be absolute, without commas".into());
}
if !file.scale.is_finite() {
return Err("control_vector scale must be finite".into());
}
let metadata = fs::metadata(&file.path)
.map_err(|error| format!("control_vector {}: {error}", file.path.display()))?;
if !metadata.is_file() || metadata.len() > 256 * 1024 * 1024 {
return Err(format!(
"control_vector {} must be a regular file of at most 256 MiB",
file.path.display()
));
}
let parsed = leleka_serving_policy::cvec::parse_gguf(
&fs::read(&file.path)
.map_err(|error| format!("control_vector {}: {error}", file.path.display()))?,
)
.map_err(|error| format!("control_vector {}: {error}", file.path.display()))?;
if parsed.architecture.as_deref() != Some("controlvector") {
return Err(format!(
"control_vector {}: not a control vector GGUF (general.architecture is not 'controlvector')",
file.path.display()
));
}
let mut found = false;
for tensor in parsed
.tensors
.iter()
.filter(|t| t.name.starts_with("direction."))
{
if tensor.kind != 0 {
return Err(format!(
"control_vector {}: {} must be f32",
file.path.display(),
tensor.name
));
}
if *width.get_or_insert(tensor.elements) != tensor.elements {
return Err(format!(
"control_vector {}: direction tensors differ in width",
file.path.display()
));
}
found = true;
}
if !found {
return Err(format!(
"control_vector {}: no direction.<layer> tensors",
file.path.display()
));
}
list.push(format!("{}:{}", file.path.display(), file.scale));
}
let mut args = vec!["--control-vector-scaled".to_owned(), list.join(",")];
args.extend([
"--cvec-mode".to_owned(),
if mode == leleka_serving_policy::cvec::Mode::Project {
"project"
} else {
"add"
}
.to_owned(),
]);
if let Some(dir) = &self.dir {
args.extend(["--cvec-dir".to_owned(), dir.clone()]);
}
if let Some([first, last]) = self.layer_range {
args.extend([
"--control-vector-layer-range".to_owned(),
first.to_string(),
last.to_string(),
]);
}
Ok(args)
}
}
impl Config {
pub fn load() -> Result<Self, Box<dyn std::error::Error>> {
Self::load_with_path(None)
}
/// An explicit CLI config path takes precedence over STRATA_CONFIG.
pub fn load_with_path(path: Option<&Path>) -> Result<Self, Box<dyn std::error::Error>> {
let config_path = path
.map(|p| p.as_os_str().to_owned())
.or_else(|| env::var_os("STRATA_CONFIG"))
.map(PathBuf::from);
let file = match &config_path {
Some(path) => serde_json::from_str::<FileConfig>(&fs::read_to_string(path)?)?,
None => FileConfig::default(),
};
crate::asset_bundle::validate(&file.assets)?;
if let Some(native) = &file.native_model {
native.validate(&file.assets)?;
}
let bind: SocketAddr = optional_env("STRATA_BIND")?
.or(file.bind)
.unwrap_or_else(|| "127.0.0.1:8081".to_owned())
.parse()?;
let max_in_flight_requests = optional_env("STRATA_MAX_IN_FLIGHT_REQUESTS")?
.map(|value| value.parse::<usize>())
.transpose()?
.or(file.max_in_flight_requests)
.unwrap_or(crate::lifecycle::DEFAULT_MAX_IN_FLIGHT_REQUESTS);
crate::lifecycle::validate_capacity(max_in_flight_requests)?;
let prompt_date = optional_env("STRATA_PROMPT_DATE")?
.or(file.prompt_date)
.map(|text| crate::responses::PromptDate::parse(&text))
.transpose()?
.unwrap_or(crate::responses::PromptDate::Utc);
let queue_timeout_s = optional_env("STRATA_QUEUE_TIMEOUT_S")?
.map(|value| value.parse::<u64>())
.transpose()?
.or(file.queue_timeout_s);
if queue_timeout_s.is_some_and(|seconds| !(1..=86400).contains(&seconds)) {
return Err("queue_timeout_s must be between 1 and 86400 when configured".into());
}
let shutdown_grace_s = optional_env("STRATA_SHUTDOWN_GRACE_S")?
.map(|value| value.parse::<u64>())
.transpose()?
.or(file.shutdown_grace_s)
.unwrap_or(0);
if shutdown_grace_s > 20 {
return Err("shutdown_grace_s must be between 0 and 20".into());
}
let executable = env::var_os("STRATA_ENGINE_EXE").or_else(|| {
file.engine
.as_ref()
.map(|engine| OsString::from(&engine.executable))
});
let args_override = optional_env("STRATA_ENGINE_ARGS_JSON")?
.map(|value| serde_json::from_str::<Vec<String>>(&value))
.transpose()?;
let timeout_override = optional_env("STRATA_STARTUP_TIMEOUT_S")?
.map(|value| value.parse::<u64>())
.transpose()?;
let configured_args = file.engine.as_ref().map(|engine| engine.args.clone());
let args = args_override.or(configured_args).unwrap_or_default();
let startup_timeout_s = timeout_override
.or_else(|| {
file.engine
.as_ref()
.and_then(|engine| engine.startup_timeout_s)
})
.unwrap_or(600);
if !(1..=3600).contains(&startup_timeout_s) {
return Err("startup_timeout_s must be between 1 and 3600".into());
}
let max_restarts = optional_env("STRATA_MAX_WORKER_RESTARTS")?
.map(|value| value.parse::<u32>())
.transpose()?
.or_else(|| file.engine.as_ref().and_then(|engine| engine.max_restarts))
.unwrap_or(3);
if max_restarts > 3 {
return Err("max_restarts must be between 0 and 3".into());
}
let generation_timeout_s = optional_env("STRATA_GENERATION_TIMEOUT_S")?
.map(|value| value.parse::<u64>())
.transpose()?
.or_else(|| {
file.engine
.as_ref()
.and_then(|engine| engine.generation_timeout_s)
});
if generation_timeout_s.is_some_and(|seconds| !(1..=86400).contains(&seconds)) {
return Err("generation_timeout_s must be between 1 and 86400".into());
}
let engine_file = file.engine.as_ref();
let mut args = args;
if let Some(vector) = engine_file.and_then(|engine| engine.control_vector.as_ref()) {
if args
.iter()
.any(|arg| arg.starts_with("--control-vector") || arg.starts_with("--cvec-"))
{
return Err("control_vector owns the --control-vector*/--cvec-* arguments; remove them from engine args".into());
}
args.extend(vector.engine_args()?);
}
let stall_timeout_s = engine_file.and_then(|engine| engine.stall_timeout_s);
if stall_timeout_s.is_some_and(|seconds| !(1..=86400).contains(&seconds)) {
return Err("stall_timeout_s must be between 1 and 86400".into());
}
let idle_unload_s = engine_file.and_then(|engine| engine.idle_unload_s);
if idle_unload_s.is_some_and(|seconds| !seconds.is_finite() || seconds < 0.0) {
return Err("idle_unload_s must be a non-negative number".into());
}
let worker = match executable {
Some(executable) if !executable.is_empty() => Some(WorkerConfig {
executable,
cuda_memory: None,
args,
startup_timeout: Duration::from_secs(startup_timeout_s),
generation_timeout: generation_timeout_s.map(Duration::from_secs),
max_restarts,
lazy: engine_file.is_some_and(|engine| engine.lazy_load),
stall_timeout: stall_timeout_s.map(Duration::from_secs),
before_load: engine_file.and_then(|engine| engine.before_load.clone()),
min_free_vram_mib: engine_file
.and_then(|engine| engine.min_free_vram_mib)
.unwrap_or(0),
vision: None,
}),
Some(_) => return Err("engine executable cannot be empty".into()),
None if !args.is_empty() => return Err("engine args require an executable".into()),
None => None,
};
let extra = file
.engine
.as_ref()
.map(|engine| engine.extra_workers.as_slice())
.unwrap_or_default();
if !extra.is_empty() {
if file.runtime.is_some() {
return Err("extra_workers and runtime are mutually exclusive: the pool feeds stdio engine children, a runtime block serves in front of one leleka-inference".into());
}
if engine_file.is_some_and(|engine| {
engine.lazy_load || engine.idle_unload_s.is_some_and(|seconds| seconds > 0.0)
}) {
return Err("extra_workers cannot be combined with lazy_load or idle_unload_s: the pool dispatcher does not load or unload workers on demand".into());
}
if file.vision.is_some() {
return Err("extra_workers cannot be combined with vision: images are read by the single supervised worker".into());
}
}
if extra.len() > 7 {
return Err("at most 7 extra_workers".into());
}
let mut extra_workers = Vec::with_capacity(extra.len());
for entry in extra {
let Some(main) = worker.as_ref() else {
return Err("extra_workers require an engine executable".into());
};
if entry.executable.is_empty() {
return Err("an extra worker executable cannot be empty".into());
}
extra_workers.push(WorkerConfig {
executable: OsString::from(&entry.executable),
cuda_memory: None,
args: entry.args.clone(),
startup_timeout: main.startup_timeout,
generation_timeout: main.generation_timeout,
max_restarts: main.max_restarts,
lazy: false,
stall_timeout: main.stall_timeout,
before_load: None,
min_free_vram_mib: 0,
vision: None,
});
}
let mut tokenizer_dir = env::var_os("STRATA_TOKENIZER_DIR")
.map(PathBuf::from)
.or_else(|| {
file.engine
.as_ref()
.and_then(|engine| engine.tokenizer_dir.clone())
});
if let Some(native) = &file.native_model {
let worker = worker
.as_ref()
.ok_or("native_model requires an engine executable")?;
if tokenizer_dir.is_some()
|| worker.args.iter().any(|arg| {
["--pack", "--native", "--gguf"]
.iter()
.any(|key| arg == key || arg.starts_with(&format!("{key}=")))
})
{
return Err("native_model owns pack/source/tokenizer settings; remove conflicting overrides".into());
}
tokenizer_dir = Some(native.output.join("tokenizer"));
}
if file.runtime.is_some() {
if worker.is_some() {
return Err("runtime and engine are mutually exclusive: the API serves in front of either a stdio engine child or a running leleka-inference".into());
}
if file.native_model.is_some()
|| file.mtp_pack.is_some()
|| file.vision.is_some()
|| file.gpu_requirement.is_some()
|| file.cuda_memory.is_some()
|| file.engine_probe
{
return Err("runtime cannot be combined with native_model, mtp_pack, vision, gpu_requirement, cuda_memory or engine_probe: the runtime process owns the model and the GPU".into());
}
}
let runtime = file
.runtime
.map(crate::runtime_config::FileRuntime::resolve)
.transpose()?;
if let Some(runtime) = &runtime {
tokenizer_dir.get_or_insert_with(|| runtime.tokenizer_dir.clone());
}
if worker.is_none() && runtime.is_none() && tokenizer_dir.is_some() {
return Err("tokenizer_dir requires an engine executable".into());
}
let gptoss_gguf = env::var_os("STRATA_GPTOSS_GGUF")
.map(PathBuf::from)
.or_else(|| {
file.engine
.as_ref()
.and_then(|engine| engine.gptoss_gguf.clone())
});
if gptoss_gguf.is_some() && file.vision.is_some() {
return Err("vision is not available for the gpt-oss family (gptoss_gguf)".into());
}
if gptoss_gguf.is_some() && (worker.is_none() || tokenizer_dir.is_some()) {
return Err(
"gptoss_gguf requires an engine executable and excludes tokenizer_dir".into(),
);
}
if worker.is_none() && file.gpu_requirement.is_some() {
return Err("gpu_requirement requires an engine executable".into());
}
if let Some(policy) = file.cuda_memory {
policy.validate()?;
if file.gpu_requirement.is_none() {
return Err("cuda_memory requires an explicit gpu_requirement".into());
}
}
if worker.is_none() && file.engine_probe {
return Err("engine_probe requires an engine executable".into());
}
if let Some(mtp) = &file.mtp_pack {
let worker = worker
.as_ref()
.ok_or("mtp_pack requires an engine executable")?;
if !file.assets.iter().any(|asset| &asset.directory == mtp) {
return Err("mtp_pack must exactly match a pinned assets bundle directory".into());
}
if mtp.to_str().is_none()
|| worker
.args
.iter()
.any(|arg| arg == "--mtp" || arg.starts_with("--mtp="))
{
return Err(
"mtp_pack requires UTF-8 path and owns --mtp; remove conflicting engine args"
.into(),
);
}
}
let model = optional_env("STRATA_MODEL_ID")?.or(file.model);
if model.as_ref().is_some_and(|id| {
id.is_empty()
|| id.len() > 180
|| !id
.bytes()
.all(|b| b.is_ascii_alphanumeric() || matches!(b, b'_' | b'-' | b'.'))
}) {
return Err(
"model ID requires 1..180 ASCII letters, digits, dots, hyphens or underscores"
.into(),
);
}
let api_key = env::var_os("STRATA_API_KEY_FILE")
.map(PathBuf::from)
.or(file.api_key_file)
.map(|path| crate::auth::ApiKey::from_file(&path).map(std::sync::Arc::new))
.transpose()?;
let response_history_dir = env::var_os("STRATA_RESPONSE_HISTORY_DIR")
.map(PathBuf::from)
.or(file.response_history_dir);
if response_history_dir.as_ref().is_some_and(|p| {
!p.is_absolute()
|| p.file_name().is_none()
|| p.components()
.any(|c| matches!(c, std::path::Component::ParentDir))
}) {
return Err(
"response_history_dir must be an absolute non-root path without '..'".into(),
);
}
let aliases = match &file.aliases {
None => Vec::new(),
Some(value) => leleka_serving_policy::shared::normalize_aliases(
value,
model.as_deref().unwrap_or(""),
)
.map_err(|message| format!("config {message}"))?,
};
if aliases.iter().any(|alias| {
alias.len() > 180
|| !alias
.bytes()
.all(|b| b.is_ascii_alphanumeric() || matches!(b, b'_' | b'-' | b'.'))
}) {
return Err(
"aliases require 1..180 ASCII letters, digits, dots, hyphens or underscores".into(),
);
}
let cors_origins = leleka_serving_policy::cors::origins_of(
file.cors_origins
.as_ref()
.unwrap_or(&serde_json::Value::Null),
"cors_origins",
true,
)?;
let trusted_origins = leleka_serving_policy::cors::origins_of(
file.trusted_origins
.as_ref()
.unwrap_or(&serde_json::Value::Null),
"trusted_origins",
false,
)?;
let sampling = leleka_serving_policy::shared::sampling_defaults_from_config(
file.sampling.as_ref().unwrap_or(&serde_json::Value::Null),
)?;
for ignored in &sampling.ignored {
crate::elog!("config sampling.{ignored}: unknown key, ignored");
}
if let Some(value) = &file.reasoning_budget_tokens {
leleka_serving_policy::reasoning::parse_budget(None, Some(value))
.map_err(|message| format!("config {message}"))?;
}
let shared_settings_file = file.shared_settings_file.clone().or_else(|| {
config_path
.as_deref()
.map(crate::settings::default_shared_path)
});
let mut mcp_servers = std::collections::BTreeMap::new();
let null = serde_json::Value::Null;
mcp_servers.extend(crate::mcp::servers_from(
file.mcp_servers.as_ref().unwrap_or(&null),
"config mcp_servers",
)?);
mcp_servers.extend(crate::mcp::servers_from(
file.mcp_servers_desktop.as_ref().unwrap_or(&null),
"config mcpServers",
)?);
if let Some(path) = &file.mcp_config_file {
// Claude Desktop's format; a name in both takes this file's entry.
let location = format!("mcp_config_file {}", path.display());
let text = std::fs::read_to_string(path)
.map_err(|error| format!("[strata] {location}: {error}"))?;
let data: serde_json::Value = serde_json::from_str(text.trim_start_matches('\u{feff}'))
.map_err(|error| format!("[strata] {location}: {error}"))?;
let block = data
.get("mcpServers")
.or_else(|| data.get("mcp_servers"))
.ok_or_else(|| {
format!("[strata] {location}: expected {{\"mcpServers\": {{...}}}}")
})?;
mcp_servers.extend(crate::mcp::servers_from(block, &location)?);
}
let mcp_settings = crate::mcp::settings_from(file.mcp.as_ref().unwrap_or(&null))?;
if let Some(vision) = &file.vision {
vision.validate()?;
if worker.is_none() {
return Err("vision requires an engine executable".into());
}
if worker.as_ref().is_some_and(|worker| worker.lazy) {
return Err("lazy loading is text-only; disable vision in the config".into());
}
}
Ok(Self {
vision: file.vision,
mcp_servers,
mcp_settings,
aliases,
cors_origins,
trusted_origins,
api_monitor: file.api_monitor == Some(true),
tool_call_recovery: match optional_env("STRATA_TOOL_CALL_RECOVERY")?.as_deref() {
Some("1" | "true") => true,
Some("0" | "false") => false,
Some(other) => {
return Err(format!(
"STRATA_TOOL_CALL_RECOVERY must be 1, true, 0 or false, not {other:?}"
)
.into());
}
None => file.tool_call_recovery == Some(true),
},
sampling,
reasoning_budget_tokens: file.reasoning_budget_tokens,
shared_settings_file,
idle_unload: idle_unload_s
.filter(|seconds| *seconds > 0.0)
.map(Duration::from_secs_f64),
mtp_pack: file.mtp_pack,
response_history_dir,
assets: file.assets,
native_model: file.native_model,
gpu_requirement: file.gpu_requirement,
cuda_memory: file.cuda_memory,
host_checked: false,
engine_probe: file.engine_probe,
shutdown_grace: Duration::from_secs(shutdown_grace_s),
queue_timeout: queue_timeout_s.map(Duration::from_secs),
max_in_flight_requests,
api_key,
bind,
model,
worker,
runtime,
extra_workers,
prompt_date,
tokenizer_dir,
gptoss_gguf,
})
}
/// Complete acquisition/preparation before the listener or worker starts.
pub async fn provision(&mut self) -> Result<(), Box<dyn std::error::Error>> {
self.check_host().await?;
self.prepare_assets().await
}
/// Prepare a switch target while the previous runtime still owns GPU memory.
/// Serving must subsequently perform full host admission; never mark it checked here.
pub async fn prepare_for_switch(&mut self) -> Result<(), Box<dyn std::error::Error>> {
if let Some(requirement) = self.gpu_requirement {
crate::doctor::check(requirement).await?;
}
self.prepare_assets().await
}
async fn prepare_assets(&mut self) -> Result<(), Box<dyn std::error::Error>> {
if self.engine_probe {
let worker = self
.worker
.as_ref()
.ok_or("engine_probe requires an engine executable")?;
crate::engine_probe::check(&worker.executable).await?;
}
// Parse all manifests before any acquisition, including the source model.
if let Some(native) = &self.native_model {
crate::model::Manifest::load(&native.manifest).await?;
}
crate::asset_bundle::provision(&self.assets).await?;
if let Some(mtp) = self.mtp_pack.clone() {
let checked = mtp.clone();
tokio::task::spawn_blocking(move || crate::mtp_pack::check(&checked)).await??;
self.worker
.as_mut()
.ok_or("mtp_pack requires worker")?
.args
.extend([
"--mtp".to_owned(),
mtp.to_str().ok_or("MTP path must be UTF-8")?.to_owned(),
]);
}
if let Some(native) = &self.native_model {
let primary = native.ensure().await?;
let output = native.output.to_str().ok_or("pack path must be UTF-8")?;
let source = primary.to_str().ok_or("source path must be UTF-8")?;
self.worker
.as_mut()
.ok_or("native_model requires worker")?
.args
.extend([
"--pack".to_owned(),
output.to_owned(),
"--native".to_owned(),
source.to_owned(),
]);
}
Ok(())
}
/// Point-in-time driver policy check; never creates a CUDA context.
pub async fn check_host(&mut self) -> Result<(), Box<dyn std::error::Error>> {
if let Some(requirement) = self.gpu_requirement
&& !self.host_checked
{
crate::doctor::check(requirement).await?;
if let Some(policy) = self.cuda_memory {
let selected = policy.select().await?;
crate::elog!(
"cuda_memory: selected {} for declared {} + {} MiB; allocation is not reserved",
selected.uuid,
policy.required_mib,
policy.reserve_mib
);
self.worker
.as_mut()
.ok_or("cuda_memory requires worker")?
.cuda_memory = Some(selected);
}
self.host_checked = true;
}
Ok(())
}
}
fn optional_env(name: &str) -> Result<Option<String>, env::VarError> {
match env::var(name) {
Ok(value) => Ok(Some(value)),
Err(env::VarError::NotPresent) => Ok(None),
Err(error) => Err(error),
}
}
#[cfg(test)]
mod tests {
use super::*;
use serde_json::json;
mod tests;
fn temp(name: &str) -> PathBuf {
let dir = env::temp_dir().join(format!("strata-config-{}-{name}", std::process::id()));
let _ = fs::remove_dir_all(&dir);
fs::create_dir_all(&dir).unwrap();
dir
}
fn load(dir: &Path, value: serde_json::Value) -> Result<Config, String> {
let path = dir.join("config.json");
fs::write(&path, value.to_string()).unwrap();
Config::load_with_path(Some(&path)).map_err(|e| e.to_string())
}
fn control_vector_file(
dir: &Path,
name: &str,
architecture: &str,
kind: u32,
elements: u64,
) -> PathBuf {
let mut bytes = b"GGUF".to_vec();
bytes.extend_from_slice(&3u32.to_le_bytes());
bytes.extend_from_slice(&1u64.to_le_bytes());
bytes.extend_from_slice(&1u64.to_le_bytes());
let key = b"general.architecture";
bytes.extend_from_slice(&(key.len() as u64).to_le_bytes());
bytes.extend_from_slice(key);
bytes.extend_from_slice(&8u32.to_le_bytes());
bytes.extend_from_slice(&(architecture.len() as u64).to_le_bytes());
bytes.extend_from_slice(architecture.as_bytes());
let tensor = b"direction.1";
bytes.extend_from_slice(&(tensor.len() as u64).to_le_bytes());
bytes.extend_from_slice(tensor);
bytes.extend_from_slice(&1u32.to_le_bytes());
bytes.extend_from_slice(&elements.to_le_bytes());
bytes.extend_from_slice(&kind.to_le_bytes());
bytes.extend_from_slice(&0u64.to_le_bytes());
while !bytes.len().is_multiple_of(32) {
bytes.push(0);
}
bytes.extend(std::iter::repeat_n(0u8, elements as usize * 4));
let path = dir.join(name);
fs::write(&path, bytes).unwrap();
path
}
#[test]
fn serving_settings_are_read_and_checked_at_start() {
let dir = temp("serving");
let config = load(
&dir,
json!({
"model": "strata-test",
"aliases": ["gpt-local", " strata-test ", "gpt-local"],
"cors_origins": ["https://chat.example.com/", "*"],
"trusted_origins": "https://strata.example.com",
"sampling": {"temperature": 0.6, "top_k": 30, "nonsense": 1},
"reasoning_budget_tokens": 128,
"engine": {"executable": "/bin/engine", "lazy_load": true, "idle_unload_s": 90,
"min_free_vram_mib": 20000, "before_load": "echo hook",
"stall_timeout_s": 120}
}),
)
.unwrap();
assert_eq!(config.aliases, vec!["gpt-local"]);
assert_eq!(config.cors_origins, vec!["https://chat.example.com", "*"]);
assert_eq!(config.trusted_origins, vec!["https://strata.example.com"]);
assert!(!config.api_monitor, "the request monitor is opt-in");
assert_eq!(config.sampling.sampling.top_k, Some(30));
assert_eq!(config.sampling.ignored, vec!["nonsense"]);
assert_eq!(config.idle_unload, Some(Duration::from_secs(90)));
assert_eq!(
config.shared_settings_file,
Some(dir.join("config.shared-settings.json"))
);
let worker = config.worker.unwrap();
assert!(worker.lazy);
assert_eq!(worker.min_free_vram_mib, 20000);
assert_eq!(worker.stall_timeout, Some(Duration::from_secs(120)));
assert_eq!(
worker.before_load,
Some(crate::worker::BeforeLoad::Shell("echo hook".into()))
);
let _ = fs::remove_dir_all(dir);
}
#[test]
fn tool_call_recovery_is_off_unless_the_config_or_the_environment_turns_it_on() {
let dir = temp("tool-call-recovery");
assert!(
!load(&dir, json!({"model": "m"}))
.unwrap()
.tool_call_recovery,
"experimental: opt-in"
);
assert!(
load(&dir, json!({"model": "m", "tool_call_recovery": true}))
.unwrap()
.tool_call_recovery
);
assert!(
!load(&dir, json!({"model": "m", "tool_call_recovery": false}))
.unwrap()
.tool_call_recovery
);
assert!(load(&dir, json!({"model": "m", "tool_call_recovery": "yes"})).is_err());
let _ = fs::remove_dir_all(dir);
}
#[test]
fn the_request_monitor_is_enabled_only_by_a_true_boolean() {
let dir = temp("api-monitor");
assert!(
load(&dir, json!({"model": "m", "api_monitor": true}))
.unwrap()
.api_monitor
);
assert!(
!load(&dir, json!({"model": "m", "api_monitor": false}))
.unwrap()
.api_monitor
);
assert!(load(&dir, json!({"model": "m", "api_monitor": "yes"})).is_err());
let _ = fs::remove_dir_all(dir);
}
#[test]
fn bad_serving_settings_stop_the_start() {
let dir = temp("serving-bad");
for (name, value) in [
("sampling", json!({"sampling": {"top_k": 100}})),
("cors", json!({"cors_origins": ["https://a.example/path"]})),
("trusted", json!({"trusted_origins": ["*"]})),
("aliases", json!({"aliases": [1]})),
("alias charset", json!({"aliases": ["has space"]})),
("budget", json!({"reasoning_budget_tokens": "many"})),
(
"stall",
json!({"engine": {"executable": "/bin/e", "stall_timeout_s": 0}}),
),
(
"idle",
json!({"engine": {"executable": "/bin/e", "idle_unload_s": -1}}),
),
] {
assert!(load(&dir, value).is_err(), "{name}");
}
let _ = fs::remove_dir_all(dir);
}
#[test]
fn a_runtime_block_excludes_every_way_of_starting_an_engine_itself() {
let dir = temp("runtime-exclusive");
let runtime = json!({
"address": "127.0.0.1:18766", "token_env": "LELEKA_RUNTIME_TOKEN_UNSET_IN_TESTS",
"tokenizer_dir": "/models/tokenizer",
"model": {"family": "f", "architecture": "a", "weight_format": "w",
"artifact_digest": format!("sha256:{}", "a".repeat(64))},
"mode": {"type": "native"}, "max_context": 4096
});
for (name, extra) in [
("engine", json!({"engine": {"executable": "/bin/e"}})),
("native_model", json!({"native_model": {}})),
("mtp_pack", json!({"mtp_pack": "/m"})),
("engine_probe", json!({"engine_probe": true})),
] {
let mut value = json!({"runtime": runtime});
for (key, item) in extra.as_object().unwrap() {
value[key] = item.clone();
}
let error = load(&dir, value).err().unwrap_or_default();
assert!(!error.is_empty(), "{name} must be refused");
}
// Alone it is accepted up to the credential, which comes from the environment.
let error = load(&dir, json!({"runtime": runtime})).err().unwrap();
assert!(
error.contains("LELEKA_RUNTIME_TOKEN_UNSET_IN_TESTS"),
"{error}"
);
let engine_error = load(
&dir,
json!({"runtime": runtime, "engine": {"executable": "/bin/e"}}),
)
.err()
.unwrap();
assert!(
engine_error.contains("mutually exclusive"),
"{engine_error}"
);
let _ = fs::remove_dir_all(dir);
}
/// The documented example stays a valid block: it parses completely and stops only at the
/// credential, which comes from the environment.
#[test]
fn the_runtime_example_config_is_valid_up_to_the_credential() {
let dir = temp("runtime-example");
let example: serde_json::Value =
serde_json::from_str(include_str!("../config.runtime.example.json")).unwrap();
let mut value = example.clone();
value.as_object_mut().unwrap().remove("api_key_file");
let error = load(&dir, value).err().unwrap();
assert!(error.contains("LELEKA_RUNTIME_TOKEN is not set"), "{error}");
let _ = fs::remove_dir_all(dir);
}
#[test]
fn a_control_vector_becomes_engine_arguments_after_a_preflight() {
let dir = temp("cvec");
let good = control_vector_file(&dir, "good.gguf", "controlvector", 0, 8);
let config = load(
&dir,
json!({"engine": {"executable": "/bin/engine", "args": ["--max-context", "4096"],
"control_vector": {"files": [{"path": good, "scale": 0.5}], "mode": "project",
"dir": "single:3", "layer_range": [2, 40]}}}),
)
.unwrap();
let args = config.worker.unwrap().args;
assert_eq!(args[..2], ["--max-context", "4096"]);
assert_eq!(args[2], "--control-vector-scaled");
assert_eq!(args[3], format!("{}:0.5", good.display()));
assert_eq!(
args[4..],
[
"--cvec-mode",
"project",
"--cvec-dir",
"single:3",
"--control-vector-layer-range",
"2",
"40"
]
);
for (name, value) in [
(
"wrong arch",
control_vector_file(&dir, "arch.gguf", "llama", 0, 8),
),
(
"f16",
control_vector_file(&dir, "f16.gguf", "controlvector", 1, 8),
),
] {
let result = load(
&dir,
json!({"engine": {"executable": "/bin/e", "control_vector": {"files": [{"path": value, "scale": 1.0}]}}}),
);
assert!(result.is_err(), "{name}");
}
for bad in [
json!({"files": []}),
json!({"files": [{"path": "relative.gguf", "scale": 1.0}]}),
json!({"files": [{"path": dir.join("missing.gguf"), "scale": 1.0}]}),
json!({"files": [{"path": good, "scale": 1.0}], "dir": "single:2"}),
json!({"files": [{"path": good, "scale": 1.0}], "mode": "mix"}),
json!({"files": [{"path": good, "scale": 1.0}], "dir": "everywhere"}),
] {
assert!(
load(
&dir,
json!({"engine": {"executable": "/bin/e", "control_vector": bad}})
)
.is_err(),
"{bad}"
);
}
assert!(
load(
&dir,
json!({"engine": {"executable": "/bin/e", "args": ["--cvec-mode", "add"],
"control_vector": {"files": [{"path": good, "scale": 1.0}]}}})
)
.is_err(),
"owned arguments"
);
let _ = fs::remove_dir_all(dir);
}
#[test]
fn vision_section_needs_an_engine_and_is_text_only_when_lazy() {
let dir = temp("vision");
let vision = json!({"exe": "/v/strata-vision", "mmproj": "/v/mmproj.gguf", "model": "/v/model.gguf",
"gpu": true, "threads": 4, "max_tokens": 1024, "cuda_device": 1});
let config = load(
&dir,
json!({"engine": {"executable": "/bin/true"}, "vision": vision}),
)
.unwrap();
let loaded = config.vision.unwrap();
assert!(loaded.gpu);
assert_eq!(loaded.cuda_device, Some(1));
assert_eq!(loaded.max_tokens, Some(1024));
assert!(
config.worker.unwrap().vision.is_none(),
"serve hands the started encoder to the worker"
);
assert!(
load(&dir, json!({"vision": vision}))
.err()
.unwrap()
.contains("requires an engine")
);
assert!(
load(
&dir,
json!({"engine": {"executable": "/bin/true", "lazy_load": true}, "vision": vision})
)
.err()
.unwrap()
.contains("text-only")
);
assert!(
load(
&dir,
json!({"engine": {"executable": "/bin/true"}, "vision": {"exe": "x"}})
)
.is_err()
);
let _ = fs::remove_dir_all(dir);
}
}
mod impl_controlvector;
#[allow(unused_imports)]
pub use impl_controlvector::*;
mod impl_config;
#[allow(unused_imports)]
pub use impl_config::*;
mod optional_env;
#[allow(unused_imports)]
pub use optional_env::*;
+8
View File
@@ -0,0 +1,8 @@
//! Moved out of the parent module by STRA-338: impl Config.
#[allow(unused_imports)]
use super::*;
mod impl_config_2;
mod impl_config_2_2;
mod impl_config_3;
@@ -0,0 +1,10 @@
//! Moved out of the parent module by STRA-338: impl Config.
#[allow(unused_imports)]
use super::*;
impl Config {
pub fn load() -> Result<Self, Box<dyn std::error::Error>> {
Self::load_with_path(None)
}
}
@@ -0,0 +1,434 @@
//! Moved out of the parent module by STRA-338: impl Config (2).
#[allow(unused_imports)]
use super::*;
impl Config {
/// An explicit CLI config path takes precedence over STRATA_CONFIG.
pub fn load_with_path(path: Option<&Path>) -> Result<Self, Box<dyn std::error::Error>> {
let config_path = path
.map(|p| p.as_os_str().to_owned())
.or_else(|| env::var_os("STRATA_CONFIG"))
.map(PathBuf::from);
let file = match &config_path {
Some(path) => serde_json::from_str::<FileConfig>(&fs::read_to_string(path)?)?,
None => FileConfig::default(),
};
crate::asset_bundle::validate(&file.assets)?;
if let Some(native) = &file.native_model {
native.validate(&file.assets)?;
}
let bind: SocketAddr = optional_env("STRATA_BIND")?
.or(file.bind)
.unwrap_or_else(|| "127.0.0.1:8081".to_owned())
.parse()?;
let max_in_flight_requests = optional_env("STRATA_MAX_IN_FLIGHT_REQUESTS")?
.map(|value| value.parse::<usize>())
.transpose()?
.or(file.max_in_flight_requests)
.unwrap_or(crate::lifecycle::DEFAULT_MAX_IN_FLIGHT_REQUESTS);
crate::lifecycle::validate_capacity(max_in_flight_requests)?;
let prompt_date = optional_env("STRATA_PROMPT_DATE")?
.or(file.prompt_date)
.map(|text| crate::responses::PromptDate::parse(&text))
.transpose()?
.unwrap_or(crate::responses::PromptDate::Utc);
let queue_timeout_s = optional_env("STRATA_QUEUE_TIMEOUT_S")?
.map(|value| value.parse::<u64>())
.transpose()?
.or(file.queue_timeout_s);
if queue_timeout_s.is_some_and(|seconds| !(1..=86400).contains(&seconds)) {
return Err("queue_timeout_s must be between 1 and 86400 when configured".into());
}
let shutdown_grace_s = optional_env("STRATA_SHUTDOWN_GRACE_S")?
.map(|value| value.parse::<u64>())
.transpose()?
.or(file.shutdown_grace_s)
.unwrap_or(0);
if shutdown_grace_s > 20 {
return Err("shutdown_grace_s must be between 0 and 20".into());
}
let executable = env::var_os("STRATA_ENGINE_EXE").or_else(|| {
file.engine
.as_ref()
.map(|engine| OsString::from(&engine.executable))
});
let args_override = optional_env("STRATA_ENGINE_ARGS_JSON")?
.map(|value| serde_json::from_str::<Vec<String>>(&value))
.transpose()?;
let timeout_override = optional_env("STRATA_STARTUP_TIMEOUT_S")?
.map(|value| value.parse::<u64>())
.transpose()?;
let configured_args = file.engine.as_ref().map(|engine| engine.args.clone());
let args = args_override.or(configured_args).unwrap_or_default();
let startup_timeout_s = timeout_override
.or_else(|| {
file.engine
.as_ref()
.and_then(|engine| engine.startup_timeout_s)
})
.unwrap_or(600);
if !(1..=3600).contains(&startup_timeout_s) {
return Err("startup_timeout_s must be between 1 and 3600".into());
}
let max_restarts = optional_env("STRATA_MAX_WORKER_RESTARTS")?
.map(|value| value.parse::<u32>())
.transpose()?
.or_else(|| file.engine.as_ref().and_then(|engine| engine.max_restarts))
.unwrap_or(3);
if max_restarts > 3 {
return Err("max_restarts must be between 0 and 3".into());
}
let generation_timeout_s = optional_env("STRATA_GENERATION_TIMEOUT_S")?
.map(|value| value.parse::<u64>())
.transpose()?
.or_else(|| {
file.engine
.as_ref()
.and_then(|engine| engine.generation_timeout_s)
});
if generation_timeout_s.is_some_and(|seconds| !(1..=86400).contains(&seconds)) {
return Err("generation_timeout_s must be between 1 and 86400".into());
}
let engine_file = file.engine.as_ref();
let mut args = args;
if let Some(vector) = engine_file.and_then(|engine| engine.control_vector.as_ref()) {
if args
.iter()
.any(|arg| arg.starts_with("--control-vector") || arg.starts_with("--cvec-"))
{
return Err("control_vector owns the --control-vector*/--cvec-* arguments; remove them from engine args".into());
}
args.extend(vector.engine_args()?);
}
let stall_timeout_s = engine_file.and_then(|engine| engine.stall_timeout_s);
if stall_timeout_s.is_some_and(|seconds| !(1..=86400).contains(&seconds)) {
return Err("stall_timeout_s must be between 1 and 86400".into());
}
let idle_unload_s = engine_file.and_then(|engine| engine.idle_unload_s);
if idle_unload_s.is_some_and(|seconds| !seconds.is_finite() || seconds < 0.0) {
return Err("idle_unload_s must be a non-negative number".into());
}
let worker = match executable {
Some(executable) if !executable.is_empty() => Some(WorkerConfig {
executable,
cuda_memory: None,
args,
startup_timeout: Duration::from_secs(startup_timeout_s),
generation_timeout: generation_timeout_s.map(Duration::from_secs),
max_restarts,
lazy: engine_file.is_some_and(|engine| engine.lazy_load),
stall_timeout: stall_timeout_s.map(Duration::from_secs),
before_load: engine_file.and_then(|engine| engine.before_load.clone()),
min_free_vram_mib: engine_file
.and_then(|engine| engine.min_free_vram_mib)
.unwrap_or(0),
vision: None,
}),
Some(_) => return Err("engine executable cannot be empty".into()),
None if !args.is_empty() => return Err("engine args require an executable".into()),
None => None,
};
let extra = file
.engine
.as_ref()
.map(|engine| engine.extra_workers.as_slice())
.unwrap_or_default();
if !extra.is_empty() {
if file.runtime.is_some() {
return Err("extra_workers and runtime are mutually exclusive: the pool feeds stdio engine children, a runtime block serves in front of one leleka-inference".into());
}
if engine_file.is_some_and(|engine| {
engine.lazy_load || engine.idle_unload_s.is_some_and(|seconds| seconds > 0.0)
}) {
return Err("extra_workers cannot be combined with lazy_load or idle_unload_s: the pool dispatcher does not load or unload workers on demand".into());
}
if file.vision.is_some() {
return Err("extra_workers cannot be combined with vision: images are read by the single supervised worker".into());
}
}
if extra.len() > 7 {
return Err("at most 7 extra_workers".into());
}
let mut extra_workers = Vec::with_capacity(extra.len());
for entry in extra {
let Some(main) = worker.as_ref() else {
return Err("extra_workers require an engine executable".into());
};
if entry.executable.is_empty() {
return Err("an extra worker executable cannot be empty".into());
}
extra_workers.push(WorkerConfig {
executable: OsString::from(&entry.executable),
cuda_memory: None,
args: entry.args.clone(),
startup_timeout: main.startup_timeout,
generation_timeout: main.generation_timeout,
max_restarts: main.max_restarts,
lazy: false,
stall_timeout: main.stall_timeout,
before_load: None,
min_free_vram_mib: 0,
vision: None,
});
}
let mut tokenizer_dir = env::var_os("STRATA_TOKENIZER_DIR")
.map(PathBuf::from)
.or_else(|| {
file.engine
.as_ref()
.and_then(|engine| engine.tokenizer_dir.clone())
});
if let Some(native) = &file.native_model {
let worker = worker
.as_ref()
.ok_or("native_model requires an engine executable")?;
if tokenizer_dir.is_some()
|| worker.args.iter().any(|arg| {
["--pack", "--native", "--gguf"]
.iter()
.any(|key| arg == key || arg.starts_with(&format!("{key}=")))
})
{
return Err("native_model owns pack/source/tokenizer settings; remove conflicting overrides".into());
}
tokenizer_dir = Some(native.output.join("tokenizer"));
}
if file.runtime.is_some() {
if worker.is_some() {
return Err("runtime and engine are mutually exclusive: the API serves in front of either a stdio engine child or a running leleka-inference".into());
}
if file.native_model.is_some()
|| file.mtp_pack.is_some()
|| file.vision.is_some()
|| file.gpu_requirement.is_some()
|| file.cuda_memory.is_some()
|| file.engine_probe
{
return Err("runtime cannot be combined with native_model, mtp_pack, vision, gpu_requirement, cuda_memory or engine_probe: the runtime process owns the model and the GPU".into());
}
}
let runtime = file
.runtime
.map(crate::runtime_config::FileRuntime::resolve)
.transpose()?;
if let Some(runtime) = &runtime {
tokenizer_dir.get_or_insert_with(|| runtime.tokenizer_dir.clone());
}
if worker.is_none() && runtime.is_none() && tokenizer_dir.is_some() {
return Err("tokenizer_dir requires an engine executable".into());
}
let gptoss_gguf = env::var_os("STRATA_GPTOSS_GGUF")
.map(PathBuf::from)
.or_else(|| {
file.engine
.as_ref()
.and_then(|engine| engine.gptoss_gguf.clone())
});
if gptoss_gguf.is_some() && file.vision.is_some() {
return Err("vision is not available for the gpt-oss family (gptoss_gguf)".into());
}
if gptoss_gguf.is_some() && (worker.is_none() || tokenizer_dir.is_some()) {
return Err(
"gptoss_gguf requires an engine executable and excludes tokenizer_dir".into(),
);
}
if worker.is_none() && file.gpu_requirement.is_some() {
return Err("gpu_requirement requires an engine executable".into());
}
if let Some(policy) = file.cuda_memory {
policy.validate()?;
if file.gpu_requirement.is_none() {
return Err("cuda_memory requires an explicit gpu_requirement".into());
}
}
if worker.is_none() && file.engine_probe {
return Err("engine_probe requires an engine executable".into());
}
if let Some(mtp) = &file.mtp_pack {
let worker = worker
.as_ref()
.ok_or("mtp_pack requires an engine executable")?;
if !file.assets.iter().any(|asset| &asset.directory == mtp) {
return Err("mtp_pack must exactly match a pinned assets bundle directory".into());
}
if mtp.to_str().is_none()
|| worker
.args
.iter()
.any(|arg| arg == "--mtp" || arg.starts_with("--mtp="))
{
return Err(
"mtp_pack requires UTF-8 path and owns --mtp; remove conflicting engine args"
.into(),
);
}
}
let model = optional_env("STRATA_MODEL_ID")?.or(file.model);
if model.as_ref().is_some_and(|id| {
id.is_empty()
|| id.len() > 180
|| !id
.bytes()
.all(|b| b.is_ascii_alphanumeric() || matches!(b, b'_' | b'-' | b'.'))
}) {
return Err(
"model ID requires 1..180 ASCII letters, digits, dots, hyphens or underscores"
.into(),
);
}
let api_key = env::var_os("STRATA_API_KEY_FILE")
.map(PathBuf::from)
.or(file.api_key_file)
.map(|path| crate::auth::ApiKey::from_file(&path).map(std::sync::Arc::new))
.transpose()?;
let response_history_dir = env::var_os("STRATA_RESPONSE_HISTORY_DIR")
.map(PathBuf::from)
.or(file.response_history_dir);
if response_history_dir.as_ref().is_some_and(|p| {
!p.is_absolute()
|| p.file_name().is_none()
|| p.components()
.any(|c| matches!(c, std::path::Component::ParentDir))
}) {
return Err(
"response_history_dir must be an absolute non-root path without '..'".into(),
);
}
let aliases = match &file.aliases {
None => Vec::new(),
Some(value) => leleka_serving_policy::shared::normalize_aliases(
value,
model.as_deref().unwrap_or(""),
)
.map_err(|message| format!("config {message}"))?,
};
if aliases.iter().any(|alias| {
alias.len() > 180
|| !alias
.bytes()
.all(|b| b.is_ascii_alphanumeric() || matches!(b, b'_' | b'-' | b'.'))
}) {
return Err(
"aliases require 1..180 ASCII letters, digits, dots, hyphens or underscores".into(),
);
}
let cors_origins = leleka_serving_policy::cors::origins_of(
file.cors_origins
.as_ref()
.unwrap_or(&serde_json::Value::Null),
"cors_origins",
true,
)?;
let trusted_origins = leleka_serving_policy::cors::origins_of(
file.trusted_origins
.as_ref()
.unwrap_or(&serde_json::Value::Null),
"trusted_origins",
false,
)?;
let sampling = leleka_serving_policy::shared::sampling_defaults_from_config(
file.sampling.as_ref().unwrap_or(&serde_json::Value::Null),
)?;
for ignored in &sampling.ignored {
crate::elog!("config sampling.{ignored}: unknown key, ignored");
}
if let Some(value) = &file.reasoning_budget_tokens {
leleka_serving_policy::reasoning::parse_budget(None, Some(value))
.map_err(|message| format!("config {message}"))?;
}
let shared_settings_file = file.shared_settings_file.clone().or_else(|| {
config_path
.as_deref()
.map(crate::settings::default_shared_path)
});
let mut mcp_servers = std::collections::BTreeMap::new();
let null = serde_json::Value::Null;
mcp_servers.extend(crate::mcp::servers_from(
file.mcp_servers.as_ref().unwrap_or(&null),
"config mcp_servers",
)?);
mcp_servers.extend(crate::mcp::servers_from(
file.mcp_servers_desktop.as_ref().unwrap_or(&null),
"config mcpServers",
)?);
if let Some(path) = &file.mcp_config_file {
// Claude Desktop's format; a name in both takes this file's entry.
let location = format!("mcp_config_file {}", path.display());
let text = std::fs::read_to_string(path)
.map_err(|error| format!("[strata] {location}: {error}"))?;
let data: serde_json::Value = serde_json::from_str(text.trim_start_matches('\u{feff}'))
.map_err(|error| format!("[strata] {location}: {error}"))?;
let block = data
.get("mcpServers")
.or_else(|| data.get("mcp_servers"))
.ok_or_else(|| {
format!("[strata] {location}: expected {{\"mcpServers\": {{...}}}}")
})?;
mcp_servers.extend(crate::mcp::servers_from(block, &location)?);
}
let mcp_settings = crate::mcp::settings_from(file.mcp.as_ref().unwrap_or(&null))?;
if let Some(vision) = &file.vision {
vision.validate()?;
if worker.is_none() {
return Err("vision requires an engine executable".into());
}
if worker.as_ref().is_some_and(|worker| worker.lazy) {
return Err("lazy loading is text-only; disable vision in the config".into());
}
}
Ok(Self {
vision: file.vision,
mcp_servers,
mcp_settings,
aliases,
cors_origins,
trusted_origins,
api_monitor: file.api_monitor == Some(true),
tool_call_recovery: match optional_env("STRATA_TOOL_CALL_RECOVERY")?.as_deref() {
Some("1" | "true") => true,
Some("0" | "false") => false,
Some(other) => {
return Err(format!(
"STRATA_TOOL_CALL_RECOVERY must be 1, true, 0 or false, not {other:?}"
)
.into());
}
None => file.tool_call_recovery == Some(true),
},
sampling,
reasoning_budget_tokens: file.reasoning_budget_tokens,
shared_settings_file,
idle_unload: idle_unload_s
.filter(|seconds| *seconds > 0.0)
.map(Duration::from_secs_f64),
mtp_pack: file.mtp_pack,
response_history_dir,
assets: file.assets,
native_model: file.native_model,
gpu_requirement: file.gpu_requirement,
cuda_memory: file.cuda_memory,
host_checked: false,
engine_probe: file.engine_probe,
shutdown_grace: Duration::from_secs(shutdown_grace_s),
queue_timeout: queue_timeout_s.map(Duration::from_secs),
max_in_flight_requests,
api_key,
bind,
model,
worker,
runtime,
extra_workers,
prompt_date,
tokenizer_dir,
gptoss_gguf,
})
}
}
@@ -0,0 +1,90 @@
//! Moved out of the parent module by STRA-338: impl Config (3).
#[allow(unused_imports)]
use super::*;
impl Config {
/// Complete acquisition/preparation before the listener or worker starts.
pub async fn provision(&mut self) -> Result<(), Box<dyn std::error::Error>> {
self.check_host().await?;
self.prepare_assets().await
}
/// Prepare a switch target while the previous runtime still owns GPU memory.
/// Serving must subsequently perform full host admission; never mark it checked here.
pub async fn prepare_for_switch(&mut self) -> Result<(), Box<dyn std::error::Error>> {
if let Some(requirement) = self.gpu_requirement {
crate::doctor::check(requirement).await?;
}
self.prepare_assets().await
}
pub(in super::super) async fn prepare_assets(
&mut self,
) -> Result<(), Box<dyn std::error::Error>> {
if self.engine_probe {
let worker = self
.worker
.as_ref()
.ok_or("engine_probe requires an engine executable")?;
crate::engine_probe::check(&worker.executable).await?;
}
// Parse all manifests before any acquisition, including the source model.
if let Some(native) = &self.native_model {
crate::model::Manifest::load(&native.manifest).await?;
}
crate::asset_bundle::provision(&self.assets).await?;
if let Some(mtp) = self.mtp_pack.clone() {
let checked = mtp.clone();
tokio::task::spawn_blocking(move || crate::mtp_pack::check(&checked)).await??;
self.worker
.as_mut()
.ok_or("mtp_pack requires worker")?
.args
.extend([
"--mtp".to_owned(),
mtp.to_str().ok_or("MTP path must be UTF-8")?.to_owned(),
]);
}
if let Some(native) = &self.native_model {
let primary = native.ensure().await?;
let output = native.output.to_str().ok_or("pack path must be UTF-8")?;
let source = primary.to_str().ok_or("source path must be UTF-8")?;
self.worker
.as_mut()
.ok_or("native_model requires worker")?
.args
.extend([
"--pack".to_owned(),
output.to_owned(),
"--native".to_owned(),
source.to_owned(),
]);
}
Ok(())
}
/// Point-in-time driver policy check; never creates a CUDA context.
pub async fn check_host(&mut self) -> Result<(), Box<dyn std::error::Error>> {
if let Some(requirement) = self.gpu_requirement
&& !self.host_checked
{
crate::doctor::check(requirement).await?;
if let Some(policy) = self.cuda_memory {
let selected = policy.select().await?;
crate::elog!(
"cuda_memory: selected {} for declared {} + {} MiB; allocation is not reserved",
selected.uuid,
policy.required_mib,
policy.reserve_mib
);
self.worker
.as_mut()
.ok_or("cuda_memory requires worker")?
.cuda_memory = Some(selected);
}
self.host_checked = true;
}
Ok(())
}
}
@@ -0,0 +1,105 @@
//! Moved out of the parent module by STRA-338: impl ControlVector.
#[allow(unused_imports)]
use super::*;
impl ControlVector {
/// The engine arguments for this vector after checking the files (GGUF control vectors with
/// F32 `direction.<layer>` tensors of one width), so a typo stops the start, not the load.
pub(super) fn engine_args(&self) -> Result<Vec<String>, String> {
if self.files.is_empty() || self.files.len() > 16 {
return Err("control_vector.files needs 1 to 16 files".into());
}
let mode = match self.mode.as_deref() {
None => leleka_serving_policy::cvec::Mode::Add,
Some(text) => leleka_serving_policy::cvec::parse_mode(text)?,
};
let single = match self.dir.as_deref() {
None => -1,
Some(text) => leleka_serving_policy::cvec::parse_dir(text)?,
};
if single >= 0 && mode != leleka_serving_policy::cvec::Mode::Project {
return Err("control_vector.dir single:L needs mode project".into());
}
let mut width: Option<u64> = None;
let mut list = Vec::new();
for file in &self.files {
if !file.path.is_absolute()
|| file.path.to_str().is_none_or(|p| p.contains([',', '\n']))
{
return Err("control_vector file paths must be absolute, without commas".into());
}
if !file.scale.is_finite() {
return Err("control_vector scale must be finite".into());
}
let metadata = fs::metadata(&file.path)
.map_err(|error| format!("control_vector {}: {error}", file.path.display()))?;
if !metadata.is_file() || metadata.len() > 256 * 1024 * 1024 {
return Err(format!(
"control_vector {} must be a regular file of at most 256 MiB",
file.path.display()
));
}
let parsed = leleka_serving_policy::cvec::parse_gguf(
&fs::read(&file.path)
.map_err(|error| format!("control_vector {}: {error}", file.path.display()))?,
)
.map_err(|error| format!("control_vector {}: {error}", file.path.display()))?;
if parsed.architecture.as_deref() != Some("controlvector") {
return Err(format!(
"control_vector {}: not a control vector GGUF (general.architecture is not 'controlvector')",
file.path.display()
));
}
let mut found = false;
for tensor in parsed
.tensors
.iter()
.filter(|t| t.name.starts_with("direction."))
{
if tensor.kind != 0 {
return Err(format!(
"control_vector {}: {} must be f32",
file.path.display(),
tensor.name
));
}
if *width.get_or_insert(tensor.elements) != tensor.elements {
return Err(format!(
"control_vector {}: direction tensors differ in width",
file.path.display()
));
}
found = true;
}
if !found {
return Err(format!(
"control_vector {}: no direction.<layer> tensors",
file.path.display()
));
}
list.push(format!("{}:{}", file.path.display(), file.scale));
}
let mut args = vec!["--control-vector-scaled".to_owned(), list.join(",")];
args.extend([
"--cvec-mode".to_owned(),
if mode == leleka_serving_policy::cvec::Mode::Project {
"project"
} else {
"add"
}
.to_owned(),
]);
if let Some(dir) = &self.dir {
args.extend(["--cvec-dir".to_owned(), dir.clone()]);
}
if let Some([first, last]) = self.layer_range {
args.extend([
"--control-vector-layer-range".to_owned(),
first.to_string(),
last.to_string(),
]);
}
Ok(args)
}
}
+12
View File
@@ -0,0 +1,12 @@
//! Moved out of the parent module by STRA-338: fn optional_env.
#[allow(unused_imports)]
use super::*;
pub(super) fn optional_env(name: &str) -> Result<Option<String>, env::VarError> {
match env::var(name) {
Ok(value) => Ok(Some(value)),
Err(env::VarError::NotPresent) => Ok(None),
Err(error) => Err(error),
}
}
+325
View File
@@ -0,0 +1,325 @@
//! Unit tests of this module (moved out of the file by STRA-338; the test ids are unchanged).
use super::*;
use serde_json::json;
fn temp(name: &str) -> PathBuf {
let dir = env::temp_dir().join(format!("strata-config-{}-{name}", std::process::id()));
let _ = fs::remove_dir_all(&dir);
fs::create_dir_all(&dir).unwrap();
dir
}
fn load(dir: &Path, value: serde_json::Value) -> Result<Config, String> {
let path = dir.join("config.json");
fs::write(&path, value.to_string()).unwrap();
Config::load_with_path(Some(&path)).map_err(|e| e.to_string())
}
fn control_vector_file(
dir: &Path,
name: &str,
architecture: &str,
kind: u32,
elements: u64,
) -> PathBuf {
let mut bytes = b"GGUF".to_vec();
bytes.extend_from_slice(&3u32.to_le_bytes());
bytes.extend_from_slice(&1u64.to_le_bytes());
bytes.extend_from_slice(&1u64.to_le_bytes());
let key = b"general.architecture";
bytes.extend_from_slice(&(key.len() as u64).to_le_bytes());
bytes.extend_from_slice(key);
bytes.extend_from_slice(&8u32.to_le_bytes());
bytes.extend_from_slice(&(architecture.len() as u64).to_le_bytes());
bytes.extend_from_slice(architecture.as_bytes());
let tensor = b"direction.1";
bytes.extend_from_slice(&(tensor.len() as u64).to_le_bytes());
bytes.extend_from_slice(tensor);
bytes.extend_from_slice(&1u32.to_le_bytes());
bytes.extend_from_slice(&elements.to_le_bytes());
bytes.extend_from_slice(&kind.to_le_bytes());
bytes.extend_from_slice(&0u64.to_le_bytes());
while !bytes.len().is_multiple_of(32) {
bytes.push(0);
}
bytes.extend(std::iter::repeat_n(0u8, elements as usize * 4));
let path = dir.join(name);
fs::write(&path, bytes).unwrap();
path
}
#[test]
fn serving_settings_are_read_and_checked_at_start() {
let dir = temp("serving");
let config = load(
&dir,
json!({
"model": "strata-test",
"aliases": ["gpt-local", " strata-test ", "gpt-local"],
"cors_origins": ["https://chat.example.com/", "*"],
"trusted_origins": "https://strata.example.com",
"sampling": {"temperature": 0.6, "top_k": 30, "nonsense": 1},
"reasoning_budget_tokens": 128,
"engine": {"executable": "/bin/engine", "lazy_load": true, "idle_unload_s": 90,
"min_free_vram_mib": 20000, "before_load": "echo hook",
"stall_timeout_s": 120}
}),
)
.unwrap();
assert_eq!(config.aliases, vec!["gpt-local"]);
assert_eq!(config.cors_origins, vec!["https://chat.example.com", "*"]);
assert_eq!(config.trusted_origins, vec!["https://strata.example.com"]);
assert!(!config.api_monitor, "the request monitor is opt-in");
assert_eq!(config.sampling.sampling.top_k, Some(30));
assert_eq!(config.sampling.ignored, vec!["nonsense"]);
assert_eq!(config.idle_unload, Some(Duration::from_secs(90)));
assert_eq!(
config.shared_settings_file,
Some(dir.join("config.shared-settings.json"))
);
let worker = config.worker.unwrap();
assert!(worker.lazy);
assert_eq!(worker.min_free_vram_mib, 20000);
assert_eq!(worker.stall_timeout, Some(Duration::from_secs(120)));
assert_eq!(
worker.before_load,
Some(crate::worker::BeforeLoad::Shell("echo hook".into()))
);
let _ = fs::remove_dir_all(dir);
}
#[test]
fn tool_call_recovery_is_off_unless_the_config_or_the_environment_turns_it_on() {
let dir = temp("tool-call-recovery");
assert!(
!load(&dir, json!({"model": "m"}))
.unwrap()
.tool_call_recovery,
"experimental: opt-in"
);
assert!(
load(&dir, json!({"model": "m", "tool_call_recovery": true}))
.unwrap()
.tool_call_recovery
);
assert!(
!load(&dir, json!({"model": "m", "tool_call_recovery": false}))
.unwrap()
.tool_call_recovery
);
assert!(load(&dir, json!({"model": "m", "tool_call_recovery": "yes"})).is_err());
let _ = fs::remove_dir_all(dir);
}
#[test]
fn the_request_monitor_is_enabled_only_by_a_true_boolean() {
let dir = temp("api-monitor");
assert!(
load(&dir, json!({"model": "m", "api_monitor": true}))
.unwrap()
.api_monitor
);
assert!(
!load(&dir, json!({"model": "m", "api_monitor": false}))
.unwrap()
.api_monitor
);
assert!(load(&dir, json!({"model": "m", "api_monitor": "yes"})).is_err());
let _ = fs::remove_dir_all(dir);
}
#[test]
fn bad_serving_settings_stop_the_start() {
let dir = temp("serving-bad");
for (name, value) in [
("sampling", json!({"sampling": {"top_k": 100}})),
("cors", json!({"cors_origins": ["https://a.example/path"]})),
("trusted", json!({"trusted_origins": ["*"]})),
("aliases", json!({"aliases": [1]})),
("alias charset", json!({"aliases": ["has space"]})),
("budget", json!({"reasoning_budget_tokens": "many"})),
(
"stall",
json!({"engine": {"executable": "/bin/e", "stall_timeout_s": 0}}),
),
(
"idle",
json!({"engine": {"executable": "/bin/e", "idle_unload_s": -1}}),
),
] {
assert!(load(&dir, value).is_err(), "{name}");
}
let _ = fs::remove_dir_all(dir);
}
#[test]
fn a_runtime_block_excludes_every_way_of_starting_an_engine_itself() {
let dir = temp("runtime-exclusive");
let runtime = json!({
"address": "127.0.0.1:18766", "token_env": "LELEKA_RUNTIME_TOKEN_UNSET_IN_TESTS",
"tokenizer_dir": "/models/tokenizer",
"model": {"family": "f", "architecture": "a", "weight_format": "w",
"artifact_digest": format!("sha256:{}", "a".repeat(64))},
"mode": {"type": "native"}, "max_context": 4096
});
for (name, extra) in [
("engine", json!({"engine": {"executable": "/bin/e"}})),
("native_model", json!({"native_model": {}})),
("mtp_pack", json!({"mtp_pack": "/m"})),
("engine_probe", json!({"engine_probe": true})),
] {
let mut value = json!({"runtime": runtime});
for (key, item) in extra.as_object().unwrap() {
value[key] = item.clone();
}
let error = load(&dir, value).err().unwrap_or_default();
assert!(!error.is_empty(), "{name} must be refused");
}
// Alone it is accepted up to the credential, which comes from the environment.
let error = load(&dir, json!({"runtime": runtime})).err().unwrap();
assert!(
error.contains("LELEKA_RUNTIME_TOKEN_UNSET_IN_TESTS"),
"{error}"
);
let engine_error = load(
&dir,
json!({"runtime": runtime, "engine": {"executable": "/bin/e"}}),
)
.err()
.unwrap();
assert!(
engine_error.contains("mutually exclusive"),
"{engine_error}"
);
let _ = fs::remove_dir_all(dir);
}
/// The documented example stays a valid block: it parses completely and stops only at the
/// credential, which comes from the environment.
#[test]
fn the_runtime_example_config_is_valid_up_to_the_credential() {
let dir = temp("runtime-example");
let example: serde_json::Value =
serde_json::from_str(include_str!("../../config.runtime.example.json")).unwrap();
let mut value = example.clone();
value.as_object_mut().unwrap().remove("api_key_file");
let error = load(&dir, value).err().unwrap();
assert!(error.contains("LELEKA_RUNTIME_TOKEN is not set"), "{error}");
let _ = fs::remove_dir_all(dir);
}
#[test]
fn a_control_vector_becomes_engine_arguments_after_a_preflight() {
let dir = temp("cvec");
let good = control_vector_file(&dir, "good.gguf", "controlvector", 0, 8);
let config = load(
&dir,
json!({"engine": {"executable": "/bin/engine", "args": ["--max-context", "4096"],
"control_vector": {"files": [{"path": good, "scale": 0.5}], "mode": "project",
"dir": "single:3", "layer_range": [2, 40]}}}),
)
.unwrap();
let args = config.worker.unwrap().args;
assert_eq!(args[..2], ["--max-context", "4096"]);
assert_eq!(args[2], "--control-vector-scaled");
assert_eq!(args[3], format!("{}:0.5", good.display()));
assert_eq!(
args[4..],
[
"--cvec-mode",
"project",
"--cvec-dir",
"single:3",
"--control-vector-layer-range",
"2",
"40"
]
);
for (name, value) in [
(
"wrong arch",
control_vector_file(&dir, "arch.gguf", "llama", 0, 8),
),
(
"f16",
control_vector_file(&dir, "f16.gguf", "controlvector", 1, 8),
),
] {
let result = load(
&dir,
json!({"engine": {"executable": "/bin/e", "control_vector": {"files": [{"path": value, "scale": 1.0}]}}}),
);
assert!(result.is_err(), "{name}");
}
for bad in [
json!({"files": []}),
json!({"files": [{"path": "relative.gguf", "scale": 1.0}]}),
json!({"files": [{"path": dir.join("missing.gguf"), "scale": 1.0}]}),
json!({"files": [{"path": good, "scale": 1.0}], "dir": "single:2"}),
json!({"files": [{"path": good, "scale": 1.0}], "mode": "mix"}),
json!({"files": [{"path": good, "scale": 1.0}], "dir": "everywhere"}),
] {
assert!(
load(
&dir,
json!({"engine": {"executable": "/bin/e", "control_vector": bad}})
)
.is_err(),
"{bad}"
);
}
assert!(
load(
&dir,
json!({"engine": {"executable": "/bin/e", "args": ["--cvec-mode", "add"],
"control_vector": {"files": [{"path": good, "scale": 1.0}]}}})
)
.is_err(),
"owned arguments"
);
let _ = fs::remove_dir_all(dir);
}
#[test]
fn vision_section_needs_an_engine_and_is_text_only_when_lazy() {
let dir = temp("vision");
let vision = json!({"exe": "/v/strata-vision", "mmproj": "/v/mmproj.gguf", "model": "/v/model.gguf",
"gpu": true, "threads": 4, "max_tokens": 1024, "cuda_device": 1});
let config = load(
&dir,
json!({"engine": {"executable": "/bin/true"}, "vision": vision}),
)
.unwrap();
let loaded = config.vision.unwrap();
assert!(loaded.gpu);
assert_eq!(loaded.cuda_device, Some(1));
assert_eq!(loaded.max_tokens, Some(1024));
assert!(
config.worker.unwrap().vision.is_none(),
"serve hands the started encoder to the worker"
);
assert!(
load(&dir, json!({"vision": vision}))
.err()
.unwrap()
.contains("requires an engine")
);
assert!(
load(
&dir,
json!({"engine": {"executable": "/bin/true", "lazy_load": true}, "vision": vision})
)
.err()
.unwrap()
.contains("text-only")
);
assert!(
load(
&dir,
json!({"engine": {"executable": "/bin/true"}, "vision": {"exe": "x"}})
)
.is_err()
);
let _ = fs::remove_dir_all(dir);
}
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
+1 -917
View File
@@ -187,920 +187,4 @@ where
}
#[cfg(test)]
mod tests {
use super::*;
use std::io::Cursor;
#[test]
fn iq3_stream_spans_chunks_with_bounded_buffers() {
let mut block = [0u8; iq3_s::BLOCK_BYTES];
block[..2].copy_from_slice(&0x3c00u16.to_le_bytes());
let mut source = block.repeat(257);
let mut cursor = Cursor::new(&source);
let mut chunks = Vec::new();
let output_bytes = visit(&mut cursor, 0, 21, source.len() as u64, |raw, decoded| {
assert!(raw.len() <= SOURCE_CHUNK_BYTES);
assert!(decoded.len() <= 256 * iq3_s::BLOCK_ELEMENTS * 4);
assert!(
decoded
.as_chunks::<4>()
.0
.iter()
.all(|v| *v == 1f32.to_le_bytes())
);
chunks.push((raw.len(), decoded.len()));
Ok(())
})
.unwrap();
assert_eq!(chunks, [(SOURCE_CHUNK_BYTES, 262_144), (110, 1024)]);
assert_eq!(output_bytes, 257 * 256 * 4);
source.pop();
assert!(
visit(
&mut Cursor::new(source),
0,
21,
(257 * 110 - 1) as u64,
|_, _| Ok(())
)
.is_err()
);
}
#[test]
fn iq4_stream_spans_chunks_with_exact_c_parity_and_source_offsets() {
let blocks_per_chunk = SOURCE_CHUNK_BYTES / iq4_nl::BLOCK_BYTES;
let blocks = blocks_per_chunk + 257;
let prefix = 13;
let mut source = vec![0xa5; prefix];
for block_index in 0..blocks {
let mut block = [0u8; iq4_nl::BLOCK_BYTES];
let scale: u16 = [0x0001, 0x03ff, 0x0400, 0x3800, 0xbc00, 0x7bff][block_index % 6];
block[..2].copy_from_slice(&scale.to_le_bytes());
for (position, byte) in block[2..].iter_mut().enumerate() {
*byte = (block_index + position * 17) as u8;
}
source.extend_from_slice(&block);
}
let source_bytes = blocks * iq4_nl::BLOCK_BYTES;
source.extend_from_slice(&[0x5a; 31]);
let mut cursor = Cursor::new(&source);
let mut consumed = 0;
let mut chunks = Vec::new();
let output_bytes = visit(
&mut cursor,
prefix as u64,
20,
source_bytes as u64,
|raw, derived| {
assert!(raw.len() <= SOURCE_CHUNK_BYTES);
assert!(raw.len().is_multiple_of(iq4_nl::BLOCK_BYTES));
assert!(derived.len() <= blocks_per_chunk * iq4_nl::BLOCK_ELEMENTS * 4);
assert_eq!(
raw,
&source[prefix + consumed..prefix + consumed + raw.len()]
);
let mut reference =
vec![0.0; raw.len() / iq4_nl::BLOCK_BYTES * iq4_nl::BLOCK_ELEMENTS];
ggml_bridge::decode_into(20, raw, &mut reference).unwrap();
let reference_bytes: Vec<u8> = reference
.iter()
.flat_map(|value| value.to_le_bytes())
.collect();
assert_eq!(derived, reference_bytes);
consumed += raw.len();
chunks.push((raw.len(), derived.len()));
Ok(())
},
)
.unwrap();
assert_eq!(
chunks,
[
(
blocks_per_chunk * iq4_nl::BLOCK_BYTES,
blocks_per_chunk * iq4_nl::BLOCK_ELEMENTS * 4
),
(257 * iq4_nl::BLOCK_BYTES, 257 * iq4_nl::BLOCK_ELEMENTS * 4),
]
);
assert_eq!(consumed, source_bytes);
assert_eq!(output_bytes, (blocks * iq4_nl::BLOCK_ELEMENTS * 4) as u64);
assert_eq!(cursor.position(), (prefix + source_bytes) as u64);
}
#[test]
fn iq4_stream_refuses_invalid_shapes_before_seek_or_callback() {
for source_bytes in [0, 1, 17, 19, 37] {
let mut cursor = Cursor::new([0u8; 64]);
cursor.set_position(7);
let mut calls = 0;
let error = visit(&mut cursor, 13, 20, source_bytes, |_, _| {
calls += 1;
Ok(())
})
.unwrap_err();
assert_eq!(error, "GGUF source tensor is empty or not block-aligned");
assert_eq!(calls, 0);
assert_eq!(cursor.position(), 7);
}
}
#[test]
fn iq4_stream_truncation_never_delivers_an_incomplete_chunk() {
let chunk_bytes = SOURCE_CHUNK_BYTES / iq4_nl::BLOCK_BYTES * iq4_nl::BLOCK_BYTES;
for available in [
iq4_nl::BLOCK_BYTES - 1,
chunk_bytes + iq4_nl::BLOCK_BYTES - 1,
] {
let requested = if available < chunk_bytes {
iq4_nl::BLOCK_BYTES
} else {
chunk_bytes + iq4_nl::BLOCK_BYTES
};
let mut calls = 0;
let result = visit(
&mut Cursor::new(vec![0u8; available]),
0,
20,
requested as u64,
|raw, derived| {
calls += 1;
assert_eq!(raw.len(), chunk_bytes);
assert_eq!(
derived.len(),
chunk_bytes / iq4_nl::BLOCK_BYTES * iq4_nl::BLOCK_ELEMENTS * 4
);
Ok(())
},
);
assert!(result.is_err());
assert_eq!(calls, usize::from(available >= chunk_bytes));
}
}
#[test]
fn iq4_stream_callback_failure_stops_without_reading_the_next_chunk() {
let chunk_bytes = SOURCE_CHUNK_BYTES / iq4_nl::BLOCK_BYTES * iq4_nl::BLOCK_BYTES;
for fail_on in [1, 2] {
let mut cursor = Cursor::new(vec![0u8; chunk_bytes * 3]);
let mut calls = 0;
let error = visit(&mut cursor, 0, 20, (chunk_bytes * 3) as u64, |raw, _| {
calls += 1;
assert_eq!(raw.len(), chunk_bytes);
if calls == fail_on {
Err("owned callback failure".into())
} else {
Ok(())
}
})
.unwrap_err();
assert_eq!(error, "owned callback failure");
assert_eq!(calls, fail_on);
assert_eq!(cursor.position(), (chunk_bytes * fail_on) as u64);
}
}
#[test]
fn iq4_stream_preserves_existing_nonfinite_classification_and_infinity_signs() {
for scale in [0x7c00u16, 0xfc00, 0x7c01, 0x7fff, 0xfc01, 0xffff] {
let mut source = AlignedSource([0u8; SOURCE_CHUNK_BYTES]);
source.0[..2].copy_from_slice(&scale.to_le_bytes());
for (position, byte) in source.0[2..iq4_nl::BLOCK_BYTES].iter_mut().enumerate() {
*byte = ((position as u8) << 4) | (15 - position as u8);
}
let raw = &source.0[..iq4_nl::BLOCK_BYTES];
let mut reference = [0.0; iq4_nl::BLOCK_ELEMENTS];
ggml_bridge::decode_into(20, raw, &mut reference).unwrap();
let mut calls = 0;
let count = visit(
&mut Cursor::new(raw),
0,
20,
iq4_nl::BLOCK_BYTES as u64,
|_, derived| {
calls += 1;
for (word, reference) in derived.as_chunks::<4>().0.iter().zip(reference) {
let actual = f32::from_le_bytes(*word);
if reference.is_nan() {
assert!(actual.is_nan());
} else {
assert!(reference.is_infinite());
assert_eq!(actual.to_bits(), reference.to_bits());
}
}
assert_eq!(derived.len(), iq4_nl::BLOCK_ELEMENTS * 4);
Ok(())
},
)
.unwrap();
assert_eq!(calls, 1);
assert_eq!(count, (iq4_nl::BLOCK_ELEMENTS * 4) as u64);
}
}
#[test]
fn q8_and_iq4xs_streams_preserve_bounded_c_bytes_offsets_and_receipts() {
for kind in [8, 23] {
let (elements, bytes) = gguf::block_geometry(kind).unwrap();
let bytes = bytes as usize;
let per_chunk = SOURCE_CHUNK_BYTES / bytes;
let blocks = per_chunk + 17;
let prefix = 11;
let mut source = vec![0xa5; prefix];
for number in 0..blocks {
let mut block = vec![0u8; bytes];
let scale: u16 = [0, 0x8000, 1, 0x83ff, 0x0400, 0x3800, 0xbc00, 0x7bff][number % 8];
block[..2].copy_from_slice(&scale.to_le_bytes());
for (position, byte) in block[2..].iter_mut().enumerate() {
*byte = (number * 17 + position * 29) as u8;
}
source.extend_from_slice(&block);
}
let source_bytes = blocks * bytes;
source.extend_from_slice(&[0x5a; 19]);
let mut cursor = Cursor::new(&source);
let mut consumed = 0;
let mut chunks = Vec::new();
let receipt = visit(
&mut cursor,
prefix as u64,
kind,
source_bytes as u64,
|raw, derived| {
assert!(raw.len() <= SOURCE_CHUNK_BYTES);
assert_eq!(
raw,
&source[prefix + consumed..prefix + consumed + raw.len()]
);
let mut oracle = vec![0.0; raw.len() / bytes * elements as usize];
ggml_bridge::decode_into(kind, raw, &mut oracle).unwrap();
let expected: Vec<u8> = oracle
.iter()
.flat_map(|value| value.to_le_bytes())
.collect();
assert_eq!(derived, expected, "kind {kind}");
assert!(derived.len() <= per_chunk * elements as usize * 4);
chunks.push((raw.len(), derived.len()));
consumed += raw.len();
Ok(())
},
)
.unwrap();
assert_eq!(
chunks,
[
(per_chunk * bytes, per_chunk * elements as usize * 4),
(17 * bytes, 17 * elements as usize * 4)
]
);
assert_eq!(consumed, source_bytes);
assert_eq!(receipt, blocks as u64 * elements * 4);
assert_eq!(cursor.position(), (prefix + source_bytes) as u64);
let mut calls = 0;
assert!(
visit(
&mut Cursor::new(&source),
prefix as u64,
kind,
source_bytes as u64 - 1,
|_, _| {
calls += 1;
Ok(())
}
)
.is_err()
);
assert_eq!(calls, 0);
let mut truncated = Cursor::new(&source[..prefix + bytes - 1]);
assert!(
visit(&mut truncated, prefix as u64, kind, bytes as u64, |_, _| {
calls += 1;
Ok(())
})
.is_err()
);
assert_eq!(calls, 0);
let mut cursor = Cursor::new(&source);
let error = visit(
&mut cursor,
prefix as u64,
kind,
source_bytes as u64,
|_, _| {
calls += 1;
Err("owned callback abort".into())
},
)
.unwrap_err();
assert_eq!(error, "owned callback abort");
assert_eq!(calls, 1);
assert_eq!(cursor.position(), (prefix + per_chunk * bytes) as u64);
}
}
#[test]
fn q8_and_iq4xs_streams_preserve_nonfinite_classification_and_infinity_bits() {
for kind in [8, 23] {
let (elements, bytes) = gguf::block_geometry(kind).unwrap();
for scale in [0x7c00u16, 0xfc00, 0x7c01, 0xfc01, 0x7e00, 0xfe00] {
let mut block = vec![0u8; bytes as usize];
block[..2].copy_from_slice(&scale.to_le_bytes());
for (position, byte) in block[2..].iter_mut().enumerate() {
*byte = (position * 29) as u8;
}
let mut oracle = vec![0.0; elements as usize];
ggml_bridge::decode_into(kind, &block, &mut oracle).unwrap();
let mut calls = 0;
let receipt = visit(&mut Cursor::new(&block), 0, kind, bytes, |raw, derived| {
assert_eq!(raw, block);
for (actual, reference) in derived.as_chunks::<4>().0.iter().zip(&oracle) {
let actual = f32::from_le_bytes(*actual);
if reference.is_nan() {
assert!(actual.is_nan());
} else {
assert_eq!(actual.to_bits(), reference.to_bits());
}
}
calls += 1;
Ok(())
})
.unwrap();
assert_eq!(calls, 1);
assert_eq!(receipt, elements * 4);
}
}
}
#[test]
fn actual_target_quant_types_decode_one_block_each() {
for kind in [8, 12, 13, 14, 18, 20, 21, 22, 23, 42] {
let (elements, bytes) = gguf::block_geometry(kind).unwrap();
let source = vec![0u8; bytes as usize];
let mut output = Vec::new();
let count = visit(&mut Cursor::new(&source), 0, kind, bytes, |raw, derived| {
assert_eq!(raw.len() as u64, bytes);
output.extend_from_slice(derived);
Ok(())
})
.unwrap();
assert_eq!(count, elements * 4, "kind {kind}");
assert_eq!(output.len() as u64, elements * 4, "kind {kind}");
assert!(
output
.as_chunks::<4>()
.0
.iter()
.all(|word| f32::from_le_bytes(*word).is_finite()),
"kind {kind}"
);
}
}
#[test]
fn q4_q5_k_streams_preserve_bounded_c_bytes_offsets_receipts_and_failure_semantics() {
let edges = [
0x0000u16, 0x8000, 0x0001, 0x83ff, 0x0400, 0x3555, 0xbc00, 0x7bff,
];
for kind in [12, 13] {
let (elements, bytes) = gguf::block_geometry(kind).unwrap();
let bytes = bytes as usize;
let per_chunk = SOURCE_CHUNK_BYTES / bytes;
let blocks = per_chunk + 17;
let prefix = 11;
let mut source = vec![0xa5; prefix];
for number in 0..blocks {
let mut block = vec![0u8; bytes];
block[..2].copy_from_slice(&edges[number % edges.len()].to_le_bytes());
block[2..4].copy_from_slice(&edges[(number * 7 + 3) % edges.len()].to_le_bytes());
for (position, byte) in block[4..].iter_mut().enumerate() {
*byte = (number * 17 + position * 29) as u8;
}
source.extend_from_slice(&block);
}
let requested = blocks * bytes;
source.extend_from_slice(&[0x5a; 19]);
let mut cursor = Cursor::new(&source);
let mut consumed = 0;
let mut chunks = Vec::new();
let receipt = visit(
&mut cursor,
prefix as u64,
kind,
requested as u64,
|raw, derived| {
assert!(raw.len() <= SOURCE_CHUNK_BYTES);
assert_eq!(
raw,
&source[prefix + consumed..prefix + consumed + raw.len()]
);
let mut oracle = vec![0.0; raw.len() / bytes * elements as usize];
ggml_bridge::decode_into(kind, raw, &mut oracle).unwrap();
let expected: Vec<u8> = oracle
.iter()
.flat_map(|value| value.to_le_bytes())
.collect();
assert_eq!(derived, expected, "kind {kind}");
assert!(derived.len() <= per_chunk * elements as usize * 4);
chunks.push((raw.len(), derived.len()));
consumed += raw.len();
Ok(())
},
)
.unwrap();
assert_eq!(
chunks,
[
(per_chunk * bytes, per_chunk * elements as usize * 4),
(17 * bytes, 17 * elements as usize * 4)
]
);
assert_eq!(consumed, requested);
assert_eq!(receipt, blocks as u64 * elements * 4);
assert_eq!(cursor.position(), (prefix + requested) as u64);
for malformed in [0, 1, bytes - 1, bytes + 1] {
let mut cursor = Cursor::new(&source);
cursor.set_position(7);
let mut calls = 0;
assert!(
visit(
&mut cursor,
prefix as u64,
kind,
malformed as u64,
|_, _| {
calls += 1;
Ok(())
}
)
.is_err()
);
assert_eq!(calls, 0);
assert_eq!(cursor.position(), 7);
}
for delivered in [0, 1] {
let available = delivered * per_chunk * bytes + bytes - 1;
let required = delivered * per_chunk * bytes + bytes;
let mut calls = 0;
assert!(
visit(
&mut Cursor::new(&source[..prefix + available]),
prefix as u64,
kind,
required as u64,
|raw, derived| {
calls += 1;
assert_eq!(raw.len(), per_chunk * bytes);
assert_eq!(derived.len(), per_chunk * elements as usize * 4);
Ok(())
}
)
.is_err()
);
assert_eq!(calls, delivered);
}
for fail_on in [1, 2] {
let mut cursor = Cursor::new(&source);
let mut calls = 0;
let error = visit(
&mut cursor,
prefix as u64,
kind,
requested as u64,
|_, _| {
calls += 1;
if calls == fail_on {
Err("owned callback abort".into())
} else {
Ok(())
}
},
)
.unwrap_err();
assert_eq!(error, "owned callback abort");
assert_eq!(calls, fail_on);
assert_eq!(
cursor.position(),
(prefix
+ if fail_on == 1 {
per_chunk * bytes
} else {
requested
}) as u64
);
}
}
}
#[test]
fn q4_q5_k_streams_preserve_both_nonfinite_scale_roles_and_zero_packed_fields() {
let scales = [
0x0000u16, 0x8000, 0x3c00, 0xbc00, 0x7c00, 0xfc00, 0x7c01, 0xfc01, 0x7e00, 0xfe00,
];
for kind in [12, 13] {
let (elements, bytes) = gguf::block_geometry(kind).unwrap();
for d in scales {
for dmin in scales {
for zero_fields in [false, true] {
let mut block = vec![0u8; bytes as usize];
block[..2].copy_from_slice(&d.to_le_bytes());
block[2..4].copy_from_slice(&dmin.to_le_bytes());
if !zero_fields {
for (position, byte) in block[4..].iter_mut().enumerate() {
*byte = (position * 29 + 17) as u8;
}
}
let mut oracle = vec![0.0; elements as usize];
ggml_bridge::decode_into(kind, &block, &mut oracle).unwrap();
let mut calls = 0;
let receipt =
visit(&mut Cursor::new(&block), 0, kind, bytes, |raw, derived| {
assert_eq!(raw, block);
assert_eq!(derived.len(), elements as usize * 4);
for (actual, reference) in
derived.as_chunks::<4>().0.iter().zip(&oracle)
{
let actual = f32::from_le_bytes(*actual);
if reference.is_nan() {
assert!(actual.is_nan());
} else {
assert_eq!(actual.to_bits(), reference.to_bits());
}
}
calls += 1;
Ok(())
})
.unwrap();
assert_eq!(calls, 1);
assert_eq!(receipt, elements * 4);
}
}
}
}
}
#[test]
fn q6_q2_streams_preserve_bounded_c_bytes_offsets_receipts_and_failure_semantics() {
let edges = [
0x0000u16, 0x8000, 0x0001, 0x83ff, 0x0400, 0x3555, 0xbc00, 0x7bff,
];
for kind in [14, 42] {
let (elements, bytes) = gguf::block_geometry(kind).unwrap();
let bytes = bytes as usize;
let per_chunk = SOURCE_CHUNK_BYTES / bytes;
let blocks = per_chunk + 17;
let prefix = 11;
let mut source = vec![0xa5; prefix];
for number in 0..blocks {
let mut block = vec![0u8; bytes];
for (position, byte) in block.iter_mut().enumerate() {
*byte = (number * 17 + position * 29) as u8;
}
let header = if kind == 14 { 208 } else { 0 };
block[header..header + 2]
.copy_from_slice(&edges[number % edges.len()].to_le_bytes());
source.extend_from_slice(&block);
}
let requested = blocks * bytes;
source.extend_from_slice(&[0x5a; 19]);
let mut cursor = Cursor::new(&source);
let mut consumed = 0;
let mut chunks = Vec::new();
let receipt = visit(
&mut cursor,
prefix as u64,
kind,
requested as u64,
|raw, derived| {
assert!(raw.len() <= SOURCE_CHUNK_BYTES);
assert_eq!(
raw,
&source[prefix + consumed..prefix + consumed + raw.len()]
);
let mut oracle = vec![0.0; raw.len() / bytes * elements as usize];
ggml_bridge::decode_into(kind, raw, &mut oracle).unwrap();
let expected: Vec<u8> = oracle
.iter()
.flat_map(|value| value.to_le_bytes())
.collect();
assert_eq!(derived, expected, "kind {kind}");
assert!(derived.len() <= per_chunk * elements as usize * 4);
chunks.push((raw.len(), derived.len()));
consumed += raw.len();
Ok(())
},
)
.unwrap();
assert_eq!(
chunks,
[
(per_chunk * bytes, per_chunk * elements as usize * 4),
(17 * bytes, 17 * elements as usize * 4)
]
);
assert_eq!(consumed, requested);
assert_eq!(receipt, blocks as u64 * elements * 4);
assert_eq!(cursor.position(), (prefix + requested) as u64);
for malformed in [0, 1, bytes - 1, bytes + 1] {
let mut cursor = Cursor::new(&source);
cursor.set_position(7);
let mut calls = 0;
assert!(
visit(
&mut cursor,
prefix as u64,
kind,
malformed as u64,
|_, _| {
calls += 1;
Ok(())
}
)
.is_err()
);
assert_eq!(calls, 0);
assert_eq!(cursor.position(), 7);
}
for delivered in [0, 1] {
let available = delivered * per_chunk * bytes + bytes - 1;
let required = delivered * per_chunk * bytes + bytes;
let mut calls = 0;
assert!(
visit(
&mut Cursor::new(&source[..prefix + available]),
prefix as u64,
kind,
required as u64,
|raw, derived| {
calls += 1;
assert_eq!(raw.len(), per_chunk * bytes);
assert_eq!(derived.len(), per_chunk * elements as usize * 4);
Ok(())
}
)
.is_err()
);
assert_eq!(calls, delivered);
}
for fail_on in [1, 2] {
let mut cursor = Cursor::new(&source);
let mut calls = 0;
let error = visit(
&mut cursor,
prefix as u64,
kind,
requested as u64,
|_, _| {
calls += 1;
if calls == fail_on {
Err("owned callback abort".into())
} else {
Ok(())
}
},
)
.unwrap_err();
assert_eq!(error, "owned callback abort");
assert_eq!(calls, fail_on);
assert_eq!(
cursor.position(),
(prefix
+ if fail_on == 1 {
per_chunk * bytes
} else {
requested
}) as u64
);
}
}
}
#[test]
fn q6_q2_streams_preserve_nonfinite_headers_and_zero_factors() {
for kind in [14, 42] {
let (elements, bytes) = gguf::block_geometry(kind).unwrap();
for bits in [
0x0000u16, 0x8000, 0x7c00, 0xfc00, 0x7c01, 0xfc01, 0x7e00, 0xfe00,
] {
for variant in 0..3 {
let mut block = vec![0u8; bytes as usize];
for (position, byte) in block.iter_mut().enumerate() {
*byte = (position * 29 + 17) as u8;
}
if kind == 14 {
if variant == 1 {
block[192..208].fill(0);
}
if variant == 2 {
block[..128].fill(0);
block[128..192].fill(0xaa);
}
} else if variant != 0 {
block[2..].fill(if variant == 1 { 0x55 } else { 0 });
}
let header = if kind == 14 { 208 } else { 0 };
block[header..header + 2].copy_from_slice(&bits.to_le_bytes());
let mut oracle = vec![0.0; elements as usize];
ggml_bridge::decode_into(kind, &block, &mut oracle).unwrap();
let mut calls = 0;
let receipt =
visit(&mut Cursor::new(&block), 0, kind, bytes, |raw, derived| {
assert_eq!(raw, block);
assert_eq!(derived.len(), elements as usize * 4);
for (actual, reference) in
derived.as_chunks::<4>().0.iter().zip(&oracle)
{
let actual = f32::from_le_bytes(*actual);
if reference.is_nan() {
assert!(actual.is_nan());
} else {
assert_eq!(actual.to_bits(), reference.to_bits());
}
}
calls += 1;
Ok(())
})
.unwrap();
assert_eq!(calls, 1);
assert_eq!(receipt, elements * 4);
}
}
}
}
#[test]
fn iq2s_iq3xxs_streams_preserve_bounded_c_bytes_offsets_receipts_and_failure_semantics() {
let edges = [
0x0000u16, 0x8000, 0x0001, 0x83ff, 0x0400, 0x3555, 0xbc00, 0x7bff,
];
for kind in [22, 18] {
let (elements, bytes) = gguf::block_geometry(kind).unwrap();
let bytes = bytes as usize;
let per_chunk = SOURCE_CHUNK_BYTES / bytes;
let blocks = per_chunk + 17;
let prefix = 11;
let mut source = vec![0xa5; prefix];
for number in 0..blocks {
let mut block = vec![0u8; bytes];
for (position, byte) in block.iter_mut().enumerate() {
*byte = (number * 17 + position * 29) as u8;
}
let header = 0;
block[header..header + 2]
.copy_from_slice(&edges[number % edges.len()].to_le_bytes());
source.extend_from_slice(&block);
}
let requested = blocks * bytes;
source.extend_from_slice(&[0x5a; 19]);
let mut cursor = Cursor::new(&source);
let mut consumed = 0;
let mut chunks = Vec::new();
let receipt = visit(
&mut cursor,
prefix as u64,
kind,
requested as u64,
|raw, derived| {
assert!(raw.len() <= SOURCE_CHUNK_BYTES);
assert_eq!(
raw,
&source[prefix + consumed..prefix + consumed + raw.len()]
);
let mut oracle = vec![0.0; raw.len() / bytes * elements as usize];
ggml_bridge::decode_into(kind, raw, &mut oracle).unwrap();
let expected: Vec<u8> = oracle
.iter()
.flat_map(|value| value.to_le_bytes())
.collect();
assert_eq!(derived, expected, "kind {kind}");
assert!(derived.len() <= per_chunk * elements as usize * 4);
chunks.push((raw.len(), derived.len()));
consumed += raw.len();
Ok(())
},
)
.unwrap();
assert_eq!(
chunks,
[
(per_chunk * bytes, per_chunk * elements as usize * 4),
(17 * bytes, 17 * elements as usize * 4)
]
);
assert_eq!(consumed, requested);
assert_eq!(receipt, blocks as u64 * elements * 4);
assert_eq!(cursor.position(), (prefix + requested) as u64);
for malformed in [0, 1, bytes - 1, bytes + 1] {
let mut cursor = Cursor::new(&source);
cursor.set_position(7);
let mut calls = 0;
assert!(
visit(
&mut cursor,
prefix as u64,
kind,
malformed as u64,
|_, _| {
calls += 1;
Ok(())
}
)
.is_err()
);
assert_eq!(calls, 0);
assert_eq!(cursor.position(), 7);
}
for delivered in [0, 1] {
let available = delivered * per_chunk * bytes + bytes - 1;
let required = delivered * per_chunk * bytes + bytes;
let mut calls = 0;
assert!(
visit(
&mut Cursor::new(&source[..prefix + available]),
prefix as u64,
kind,
required as u64,
|raw, derived| {
calls += 1;
assert_eq!(raw.len(), per_chunk * bytes);
assert_eq!(derived.len(), per_chunk * elements as usize * 4);
Ok(())
}
)
.is_err()
);
assert_eq!(calls, delivered);
}
for fail_on in [1, 2] {
let mut cursor = Cursor::new(&source);
let mut calls = 0;
let error = visit(
&mut cursor,
prefix as u64,
kind,
requested as u64,
|_, _| {
calls += 1;
if calls == fail_on {
Err("owned callback abort".into())
} else {
Ok(())
}
},
)
.unwrap_err();
assert_eq!(error, "owned callback abort");
assert_eq!(calls, fail_on);
assert_eq!(
cursor.position(),
(prefix
+ if fail_on == 1 {
per_chunk * bytes
} else {
requested
}) as u64
);
}
}
}
#[test]
fn iq2s_iq3xxs_streams_preserve_nonfinite_signed_zero_and_zero_packed_fields() {
for kind in [22, 18] {
let (elements, bytes) = gguf::block_geometry(kind).unwrap();
for bits in [
0x0000u16, 0x8000, 0x7c00, 0xfc00, 0x7c01, 0xfc01, 0x7e00, 0xfe00,
] {
for zero_fields in [false, true] {
let mut block = vec![0; bytes as usize];
if !zero_fields {
for (field, byte) in block[2..].iter_mut().enumerate() {
*byte = (field * 29 + 17) as u8;
}
}
block[..2].copy_from_slice(&bits.to_le_bytes());
let mut oracle = vec![0.0; elements as usize];
ggml_bridge::decode_into(kind, &block, &mut oracle).unwrap();
let mut calls = 0;
let receipt =
visit(&mut Cursor::new(&block), 0, kind, bytes, |raw, derived| {
assert_eq!(raw, block);
assert_eq!(derived.len(), elements as usize * 4);
for (actual, expected) in derived.as_chunks::<4>().0.iter().zip(&oracle)
{
let actual = f32::from_le_bytes(*actual);
if expected.is_nan() {
assert!(actual.is_nan());
} else {
assert_eq!(actual.to_bits(), expected.to_bits());
}
}
calls += 1;
Ok(())
})
.unwrap();
assert_eq!(calls, 1);
assert_eq!(receipt, elements * 4);
}
}
}
}
}
mod tests;
+909
View File
@@ -0,0 +1,909 @@
//! Unit tests of this module (moved out of the file by STRA-338; the test ids are unchanged).
use super::*;
use std::io::Cursor;
#[test]
fn iq3_stream_spans_chunks_with_bounded_buffers() {
let mut block = [0u8; iq3_s::BLOCK_BYTES];
block[..2].copy_from_slice(&0x3c00u16.to_le_bytes());
let mut source = block.repeat(257);
let mut cursor = Cursor::new(&source);
let mut chunks = Vec::new();
let output_bytes = visit(&mut cursor, 0, 21, source.len() as u64, |raw, decoded| {
assert!(raw.len() <= SOURCE_CHUNK_BYTES);
assert!(decoded.len() <= 256 * iq3_s::BLOCK_ELEMENTS * 4);
assert!(
decoded
.as_chunks::<4>()
.0
.iter()
.all(|v| *v == 1f32.to_le_bytes())
);
chunks.push((raw.len(), decoded.len()));
Ok(())
})
.unwrap();
assert_eq!(chunks, [(SOURCE_CHUNK_BYTES, 262_144), (110, 1024)]);
assert_eq!(output_bytes, 257 * 256 * 4);
source.pop();
assert!(
visit(
&mut Cursor::new(source),
0,
21,
(257 * 110 - 1) as u64,
|_, _| Ok(())
)
.is_err()
);
}
#[test]
fn iq4_stream_spans_chunks_with_exact_c_parity_and_source_offsets() {
let blocks_per_chunk = SOURCE_CHUNK_BYTES / iq4_nl::BLOCK_BYTES;
let blocks = blocks_per_chunk + 257;
let prefix = 13;
let mut source = vec![0xa5; prefix];
for block_index in 0..blocks {
let mut block = [0u8; iq4_nl::BLOCK_BYTES];
let scale: u16 = [0x0001, 0x03ff, 0x0400, 0x3800, 0xbc00, 0x7bff][block_index % 6];
block[..2].copy_from_slice(&scale.to_le_bytes());
for (position, byte) in block[2..].iter_mut().enumerate() {
*byte = (block_index + position * 17) as u8;
}
source.extend_from_slice(&block);
}
let source_bytes = blocks * iq4_nl::BLOCK_BYTES;
source.extend_from_slice(&[0x5a; 31]);
let mut cursor = Cursor::new(&source);
let mut consumed = 0;
let mut chunks = Vec::new();
let output_bytes = visit(
&mut cursor,
prefix as u64,
20,
source_bytes as u64,
|raw, derived| {
assert!(raw.len() <= SOURCE_CHUNK_BYTES);
assert!(raw.len().is_multiple_of(iq4_nl::BLOCK_BYTES));
assert!(derived.len() <= blocks_per_chunk * iq4_nl::BLOCK_ELEMENTS * 4);
assert_eq!(
raw,
&source[prefix + consumed..prefix + consumed + raw.len()]
);
let mut reference = vec![0.0; raw.len() / iq4_nl::BLOCK_BYTES * iq4_nl::BLOCK_ELEMENTS];
ggml_bridge::decode_into(20, raw, &mut reference).unwrap();
let reference_bytes: Vec<u8> = reference
.iter()
.flat_map(|value| value.to_le_bytes())
.collect();
assert_eq!(derived, reference_bytes);
consumed += raw.len();
chunks.push((raw.len(), derived.len()));
Ok(())
},
)
.unwrap();
assert_eq!(
chunks,
[
(
blocks_per_chunk * iq4_nl::BLOCK_BYTES,
blocks_per_chunk * iq4_nl::BLOCK_ELEMENTS * 4
),
(257 * iq4_nl::BLOCK_BYTES, 257 * iq4_nl::BLOCK_ELEMENTS * 4),
]
);
assert_eq!(consumed, source_bytes);
assert_eq!(output_bytes, (blocks * iq4_nl::BLOCK_ELEMENTS * 4) as u64);
assert_eq!(cursor.position(), (prefix + source_bytes) as u64);
}
#[test]
fn iq4_stream_refuses_invalid_shapes_before_seek_or_callback() {
for source_bytes in [0, 1, 17, 19, 37] {
let mut cursor = Cursor::new([0u8; 64]);
cursor.set_position(7);
let mut calls = 0;
let error = visit(&mut cursor, 13, 20, source_bytes, |_, _| {
calls += 1;
Ok(())
})
.unwrap_err();
assert_eq!(error, "GGUF source tensor is empty or not block-aligned");
assert_eq!(calls, 0);
assert_eq!(cursor.position(), 7);
}
}
#[test]
fn iq4_stream_truncation_never_delivers_an_incomplete_chunk() {
let chunk_bytes = SOURCE_CHUNK_BYTES / iq4_nl::BLOCK_BYTES * iq4_nl::BLOCK_BYTES;
for available in [
iq4_nl::BLOCK_BYTES - 1,
chunk_bytes + iq4_nl::BLOCK_BYTES - 1,
] {
let requested = if available < chunk_bytes {
iq4_nl::BLOCK_BYTES
} else {
chunk_bytes + iq4_nl::BLOCK_BYTES
};
let mut calls = 0;
let result = visit(
&mut Cursor::new(vec![0u8; available]),
0,
20,
requested as u64,
|raw, derived| {
calls += 1;
assert_eq!(raw.len(), chunk_bytes);
assert_eq!(
derived.len(),
chunk_bytes / iq4_nl::BLOCK_BYTES * iq4_nl::BLOCK_ELEMENTS * 4
);
Ok(())
},
);
assert!(result.is_err());
assert_eq!(calls, usize::from(available >= chunk_bytes));
}
}
#[test]
fn iq4_stream_callback_failure_stops_without_reading_the_next_chunk() {
let chunk_bytes = SOURCE_CHUNK_BYTES / iq4_nl::BLOCK_BYTES * iq4_nl::BLOCK_BYTES;
for fail_on in [1, 2] {
let mut cursor = Cursor::new(vec![0u8; chunk_bytes * 3]);
let mut calls = 0;
let error = visit(&mut cursor, 0, 20, (chunk_bytes * 3) as u64, |raw, _| {
calls += 1;
assert_eq!(raw.len(), chunk_bytes);
if calls == fail_on {
Err("owned callback failure".into())
} else {
Ok(())
}
})
.unwrap_err();
assert_eq!(error, "owned callback failure");
assert_eq!(calls, fail_on);
assert_eq!(cursor.position(), (chunk_bytes * fail_on) as u64);
}
}
#[test]
fn iq4_stream_preserves_existing_nonfinite_classification_and_infinity_signs() {
for scale in [0x7c00u16, 0xfc00, 0x7c01, 0x7fff, 0xfc01, 0xffff] {
let mut source = AlignedSource([0u8; SOURCE_CHUNK_BYTES]);
source.0[..2].copy_from_slice(&scale.to_le_bytes());
for (position, byte) in source.0[2..iq4_nl::BLOCK_BYTES].iter_mut().enumerate() {
*byte = ((position as u8) << 4) | (15 - position as u8);
}
let raw = &source.0[..iq4_nl::BLOCK_BYTES];
let mut reference = [0.0; iq4_nl::BLOCK_ELEMENTS];
ggml_bridge::decode_into(20, raw, &mut reference).unwrap();
let mut calls = 0;
let count = visit(
&mut Cursor::new(raw),
0,
20,
iq4_nl::BLOCK_BYTES as u64,
|_, derived| {
calls += 1;
for (word, reference) in derived.as_chunks::<4>().0.iter().zip(reference) {
let actual = f32::from_le_bytes(*word);
if reference.is_nan() {
assert!(actual.is_nan());
} else {
assert!(reference.is_infinite());
assert_eq!(actual.to_bits(), reference.to_bits());
}
}
assert_eq!(derived.len(), iq4_nl::BLOCK_ELEMENTS * 4);
Ok(())
},
)
.unwrap();
assert_eq!(calls, 1);
assert_eq!(count, (iq4_nl::BLOCK_ELEMENTS * 4) as u64);
}
}
#[test]
fn q8_and_iq4xs_streams_preserve_bounded_c_bytes_offsets_and_receipts() {
for kind in [8, 23] {
let (elements, bytes) = gguf::block_geometry(kind).unwrap();
let bytes = bytes as usize;
let per_chunk = SOURCE_CHUNK_BYTES / bytes;
let blocks = per_chunk + 17;
let prefix = 11;
let mut source = vec![0xa5; prefix];
for number in 0..blocks {
let mut block = vec![0u8; bytes];
let scale: u16 = [0, 0x8000, 1, 0x83ff, 0x0400, 0x3800, 0xbc00, 0x7bff][number % 8];
block[..2].copy_from_slice(&scale.to_le_bytes());
for (position, byte) in block[2..].iter_mut().enumerate() {
*byte = (number * 17 + position * 29) as u8;
}
source.extend_from_slice(&block);
}
let source_bytes = blocks * bytes;
source.extend_from_slice(&[0x5a; 19]);
let mut cursor = Cursor::new(&source);
let mut consumed = 0;
let mut chunks = Vec::new();
let receipt = visit(
&mut cursor,
prefix as u64,
kind,
source_bytes as u64,
|raw, derived| {
assert!(raw.len() <= SOURCE_CHUNK_BYTES);
assert_eq!(
raw,
&source[prefix + consumed..prefix + consumed + raw.len()]
);
let mut oracle = vec![0.0; raw.len() / bytes * elements as usize];
ggml_bridge::decode_into(kind, raw, &mut oracle).unwrap();
let expected: Vec<u8> = oracle
.iter()
.flat_map(|value| value.to_le_bytes())
.collect();
assert_eq!(derived, expected, "kind {kind}");
assert!(derived.len() <= per_chunk * elements as usize * 4);
chunks.push((raw.len(), derived.len()));
consumed += raw.len();
Ok(())
},
)
.unwrap();
assert_eq!(
chunks,
[
(per_chunk * bytes, per_chunk * elements as usize * 4),
(17 * bytes, 17 * elements as usize * 4)
]
);
assert_eq!(consumed, source_bytes);
assert_eq!(receipt, blocks as u64 * elements * 4);
assert_eq!(cursor.position(), (prefix + source_bytes) as u64);
let mut calls = 0;
assert!(
visit(
&mut Cursor::new(&source),
prefix as u64,
kind,
source_bytes as u64 - 1,
|_, _| {
calls += 1;
Ok(())
}
)
.is_err()
);
assert_eq!(calls, 0);
let mut truncated = Cursor::new(&source[..prefix + bytes - 1]);
assert!(
visit(&mut truncated, prefix as u64, kind, bytes as u64, |_, _| {
calls += 1;
Ok(())
})
.is_err()
);
assert_eq!(calls, 0);
let mut cursor = Cursor::new(&source);
let error = visit(
&mut cursor,
prefix as u64,
kind,
source_bytes as u64,
|_, _| {
calls += 1;
Err("owned callback abort".into())
},
)
.unwrap_err();
assert_eq!(error, "owned callback abort");
assert_eq!(calls, 1);
assert_eq!(cursor.position(), (prefix + per_chunk * bytes) as u64);
}
}
#[test]
fn q8_and_iq4xs_streams_preserve_nonfinite_classification_and_infinity_bits() {
for kind in [8, 23] {
let (elements, bytes) = gguf::block_geometry(kind).unwrap();
for scale in [0x7c00u16, 0xfc00, 0x7c01, 0xfc01, 0x7e00, 0xfe00] {
let mut block = vec![0u8; bytes as usize];
block[..2].copy_from_slice(&scale.to_le_bytes());
for (position, byte) in block[2..].iter_mut().enumerate() {
*byte = (position * 29) as u8;
}
let mut oracle = vec![0.0; elements as usize];
ggml_bridge::decode_into(kind, &block, &mut oracle).unwrap();
let mut calls = 0;
let receipt = visit(&mut Cursor::new(&block), 0, kind, bytes, |raw, derived| {
assert_eq!(raw, block);
for (actual, reference) in derived.as_chunks::<4>().0.iter().zip(&oracle) {
let actual = f32::from_le_bytes(*actual);
if reference.is_nan() {
assert!(actual.is_nan());
} else {
assert_eq!(actual.to_bits(), reference.to_bits());
}
}
calls += 1;
Ok(())
})
.unwrap();
assert_eq!(calls, 1);
assert_eq!(receipt, elements * 4);
}
}
}
#[test]
fn actual_target_quant_types_decode_one_block_each() {
for kind in [8, 12, 13, 14, 18, 20, 21, 22, 23, 42] {
let (elements, bytes) = gguf::block_geometry(kind).unwrap();
let source = vec![0u8; bytes as usize];
let mut output = Vec::new();
let count = visit(&mut Cursor::new(&source), 0, kind, bytes, |raw, derived| {
assert_eq!(raw.len() as u64, bytes);
output.extend_from_slice(derived);
Ok(())
})
.unwrap();
assert_eq!(count, elements * 4, "kind {kind}");
assert_eq!(output.len() as u64, elements * 4, "kind {kind}");
assert!(
output
.as_chunks::<4>()
.0
.iter()
.all(|word| f32::from_le_bytes(*word).is_finite()),
"kind {kind}"
);
}
}
#[test]
fn q4_q5_k_streams_preserve_bounded_c_bytes_offsets_receipts_and_failure_semantics() {
let edges = [
0x0000u16, 0x8000, 0x0001, 0x83ff, 0x0400, 0x3555, 0xbc00, 0x7bff,
];
for kind in [12, 13] {
let (elements, bytes) = gguf::block_geometry(kind).unwrap();
let bytes = bytes as usize;
let per_chunk = SOURCE_CHUNK_BYTES / bytes;
let blocks = per_chunk + 17;
let prefix = 11;
let mut source = vec![0xa5; prefix];
for number in 0..blocks {
let mut block = vec![0u8; bytes];
block[..2].copy_from_slice(&edges[number % edges.len()].to_le_bytes());
block[2..4].copy_from_slice(&edges[(number * 7 + 3) % edges.len()].to_le_bytes());
for (position, byte) in block[4..].iter_mut().enumerate() {
*byte = (number * 17 + position * 29) as u8;
}
source.extend_from_slice(&block);
}
let requested = blocks * bytes;
source.extend_from_slice(&[0x5a; 19]);
let mut cursor = Cursor::new(&source);
let mut consumed = 0;
let mut chunks = Vec::new();
let receipt = visit(
&mut cursor,
prefix as u64,
kind,
requested as u64,
|raw, derived| {
assert!(raw.len() <= SOURCE_CHUNK_BYTES);
assert_eq!(
raw,
&source[prefix + consumed..prefix + consumed + raw.len()]
);
let mut oracle = vec![0.0; raw.len() / bytes * elements as usize];
ggml_bridge::decode_into(kind, raw, &mut oracle).unwrap();
let expected: Vec<u8> = oracle
.iter()
.flat_map(|value| value.to_le_bytes())
.collect();
assert_eq!(derived, expected, "kind {kind}");
assert!(derived.len() <= per_chunk * elements as usize * 4);
chunks.push((raw.len(), derived.len()));
consumed += raw.len();
Ok(())
},
)
.unwrap();
assert_eq!(
chunks,
[
(per_chunk * bytes, per_chunk * elements as usize * 4),
(17 * bytes, 17 * elements as usize * 4)
]
);
assert_eq!(consumed, requested);
assert_eq!(receipt, blocks as u64 * elements * 4);
assert_eq!(cursor.position(), (prefix + requested) as u64);
for malformed in [0, 1, bytes - 1, bytes + 1] {
let mut cursor = Cursor::new(&source);
cursor.set_position(7);
let mut calls = 0;
assert!(
visit(
&mut cursor,
prefix as u64,
kind,
malformed as u64,
|_, _| {
calls += 1;
Ok(())
}
)
.is_err()
);
assert_eq!(calls, 0);
assert_eq!(cursor.position(), 7);
}
for delivered in [0, 1] {
let available = delivered * per_chunk * bytes + bytes - 1;
let required = delivered * per_chunk * bytes + bytes;
let mut calls = 0;
assert!(
visit(
&mut Cursor::new(&source[..prefix + available]),
prefix as u64,
kind,
required as u64,
|raw, derived| {
calls += 1;
assert_eq!(raw.len(), per_chunk * bytes);
assert_eq!(derived.len(), per_chunk * elements as usize * 4);
Ok(())
}
)
.is_err()
);
assert_eq!(calls, delivered);
}
for fail_on in [1, 2] {
let mut cursor = Cursor::new(&source);
let mut calls = 0;
let error = visit(
&mut cursor,
prefix as u64,
kind,
requested as u64,
|_, _| {
calls += 1;
if calls == fail_on {
Err("owned callback abort".into())
} else {
Ok(())
}
},
)
.unwrap_err();
assert_eq!(error, "owned callback abort");
assert_eq!(calls, fail_on);
assert_eq!(
cursor.position(),
(prefix
+ if fail_on == 1 {
per_chunk * bytes
} else {
requested
}) as u64
);
}
}
}
#[test]
fn q4_q5_k_streams_preserve_both_nonfinite_scale_roles_and_zero_packed_fields() {
let scales = [
0x0000u16, 0x8000, 0x3c00, 0xbc00, 0x7c00, 0xfc00, 0x7c01, 0xfc01, 0x7e00, 0xfe00,
];
for kind in [12, 13] {
let (elements, bytes) = gguf::block_geometry(kind).unwrap();
for d in scales {
for dmin in scales {
for zero_fields in [false, true] {
let mut block = vec![0u8; bytes as usize];
block[..2].copy_from_slice(&d.to_le_bytes());
block[2..4].copy_from_slice(&dmin.to_le_bytes());
if !zero_fields {
for (position, byte) in block[4..].iter_mut().enumerate() {
*byte = (position * 29 + 17) as u8;
}
}
let mut oracle = vec![0.0; elements as usize];
ggml_bridge::decode_into(kind, &block, &mut oracle).unwrap();
let mut calls = 0;
let receipt =
visit(&mut Cursor::new(&block), 0, kind, bytes, |raw, derived| {
assert_eq!(raw, block);
assert_eq!(derived.len(), elements as usize * 4);
for (actual, reference) in
derived.as_chunks::<4>().0.iter().zip(&oracle)
{
let actual = f32::from_le_bytes(*actual);
if reference.is_nan() {
assert!(actual.is_nan());
} else {
assert_eq!(actual.to_bits(), reference.to_bits());
}
}
calls += 1;
Ok(())
})
.unwrap();
assert_eq!(calls, 1);
assert_eq!(receipt, elements * 4);
}
}
}
}
}
#[test]
fn q6_q2_streams_preserve_bounded_c_bytes_offsets_receipts_and_failure_semantics() {
let edges = [
0x0000u16, 0x8000, 0x0001, 0x83ff, 0x0400, 0x3555, 0xbc00, 0x7bff,
];
for kind in [14, 42] {
let (elements, bytes) = gguf::block_geometry(kind).unwrap();
let bytes = bytes as usize;
let per_chunk = SOURCE_CHUNK_BYTES / bytes;
let blocks = per_chunk + 17;
let prefix = 11;
let mut source = vec![0xa5; prefix];
for number in 0..blocks {
let mut block = vec![0u8; bytes];
for (position, byte) in block.iter_mut().enumerate() {
*byte = (number * 17 + position * 29) as u8;
}
let header = if kind == 14 { 208 } else { 0 };
block[header..header + 2].copy_from_slice(&edges[number % edges.len()].to_le_bytes());
source.extend_from_slice(&block);
}
let requested = blocks * bytes;
source.extend_from_slice(&[0x5a; 19]);
let mut cursor = Cursor::new(&source);
let mut consumed = 0;
let mut chunks = Vec::new();
let receipt = visit(
&mut cursor,
prefix as u64,
kind,
requested as u64,
|raw, derived| {
assert!(raw.len() <= SOURCE_CHUNK_BYTES);
assert_eq!(
raw,
&source[prefix + consumed..prefix + consumed + raw.len()]
);
let mut oracle = vec![0.0; raw.len() / bytes * elements as usize];
ggml_bridge::decode_into(kind, raw, &mut oracle).unwrap();
let expected: Vec<u8> = oracle
.iter()
.flat_map(|value| value.to_le_bytes())
.collect();
assert_eq!(derived, expected, "kind {kind}");
assert!(derived.len() <= per_chunk * elements as usize * 4);
chunks.push((raw.len(), derived.len()));
consumed += raw.len();
Ok(())
},
)
.unwrap();
assert_eq!(
chunks,
[
(per_chunk * bytes, per_chunk * elements as usize * 4),
(17 * bytes, 17 * elements as usize * 4)
]
);
assert_eq!(consumed, requested);
assert_eq!(receipt, blocks as u64 * elements * 4);
assert_eq!(cursor.position(), (prefix + requested) as u64);
for malformed in [0, 1, bytes - 1, bytes + 1] {
let mut cursor = Cursor::new(&source);
cursor.set_position(7);
let mut calls = 0;
assert!(
visit(
&mut cursor,
prefix as u64,
kind,
malformed as u64,
|_, _| {
calls += 1;
Ok(())
}
)
.is_err()
);
assert_eq!(calls, 0);
assert_eq!(cursor.position(), 7);
}
for delivered in [0, 1] {
let available = delivered * per_chunk * bytes + bytes - 1;
let required = delivered * per_chunk * bytes + bytes;
let mut calls = 0;
assert!(
visit(
&mut Cursor::new(&source[..prefix + available]),
prefix as u64,
kind,
required as u64,
|raw, derived| {
calls += 1;
assert_eq!(raw.len(), per_chunk * bytes);
assert_eq!(derived.len(), per_chunk * elements as usize * 4);
Ok(())
}
)
.is_err()
);
assert_eq!(calls, delivered);
}
for fail_on in [1, 2] {
let mut cursor = Cursor::new(&source);
let mut calls = 0;
let error = visit(
&mut cursor,
prefix as u64,
kind,
requested as u64,
|_, _| {
calls += 1;
if calls == fail_on {
Err("owned callback abort".into())
} else {
Ok(())
}
},
)
.unwrap_err();
assert_eq!(error, "owned callback abort");
assert_eq!(calls, fail_on);
assert_eq!(
cursor.position(),
(prefix
+ if fail_on == 1 {
per_chunk * bytes
} else {
requested
}) as u64
);
}
}
}
#[test]
fn q6_q2_streams_preserve_nonfinite_headers_and_zero_factors() {
for kind in [14, 42] {
let (elements, bytes) = gguf::block_geometry(kind).unwrap();
for bits in [
0x0000u16, 0x8000, 0x7c00, 0xfc00, 0x7c01, 0xfc01, 0x7e00, 0xfe00,
] {
for variant in 0..3 {
let mut block = vec![0u8; bytes as usize];
for (position, byte) in block.iter_mut().enumerate() {
*byte = (position * 29 + 17) as u8;
}
if kind == 14 {
if variant == 1 {
block[192..208].fill(0);
}
if variant == 2 {
block[..128].fill(0);
block[128..192].fill(0xaa);
}
} else if variant != 0 {
block[2..].fill(if variant == 1 { 0x55 } else { 0 });
}
let header = if kind == 14 { 208 } else { 0 };
block[header..header + 2].copy_from_slice(&bits.to_le_bytes());
let mut oracle = vec![0.0; elements as usize];
ggml_bridge::decode_into(kind, &block, &mut oracle).unwrap();
let mut calls = 0;
let receipt = visit(&mut Cursor::new(&block), 0, kind, bytes, |raw, derived| {
assert_eq!(raw, block);
assert_eq!(derived.len(), elements as usize * 4);
for (actual, reference) in derived.as_chunks::<4>().0.iter().zip(&oracle) {
let actual = f32::from_le_bytes(*actual);
if reference.is_nan() {
assert!(actual.is_nan());
} else {
assert_eq!(actual.to_bits(), reference.to_bits());
}
}
calls += 1;
Ok(())
})
.unwrap();
assert_eq!(calls, 1);
assert_eq!(receipt, elements * 4);
}
}
}
}
#[test]
fn iq2s_iq3xxs_streams_preserve_bounded_c_bytes_offsets_receipts_and_failure_semantics() {
let edges = [
0x0000u16, 0x8000, 0x0001, 0x83ff, 0x0400, 0x3555, 0xbc00, 0x7bff,
];
for kind in [22, 18] {
let (elements, bytes) = gguf::block_geometry(kind).unwrap();
let bytes = bytes as usize;
let per_chunk = SOURCE_CHUNK_BYTES / bytes;
let blocks = per_chunk + 17;
let prefix = 11;
let mut source = vec![0xa5; prefix];
for number in 0..blocks {
let mut block = vec![0u8; bytes];
for (position, byte) in block.iter_mut().enumerate() {
*byte = (number * 17 + position * 29) as u8;
}
let header = 0;
block[header..header + 2].copy_from_slice(&edges[number % edges.len()].to_le_bytes());
source.extend_from_slice(&block);
}
let requested = blocks * bytes;
source.extend_from_slice(&[0x5a; 19]);
let mut cursor = Cursor::new(&source);
let mut consumed = 0;
let mut chunks = Vec::new();
let receipt = visit(
&mut cursor,
prefix as u64,
kind,
requested as u64,
|raw, derived| {
assert!(raw.len() <= SOURCE_CHUNK_BYTES);
assert_eq!(
raw,
&source[prefix + consumed..prefix + consumed + raw.len()]
);
let mut oracle = vec![0.0; raw.len() / bytes * elements as usize];
ggml_bridge::decode_into(kind, raw, &mut oracle).unwrap();
let expected: Vec<u8> = oracle
.iter()
.flat_map(|value| value.to_le_bytes())
.collect();
assert_eq!(derived, expected, "kind {kind}");
assert!(derived.len() <= per_chunk * elements as usize * 4);
chunks.push((raw.len(), derived.len()));
consumed += raw.len();
Ok(())
},
)
.unwrap();
assert_eq!(
chunks,
[
(per_chunk * bytes, per_chunk * elements as usize * 4),
(17 * bytes, 17 * elements as usize * 4)
]
);
assert_eq!(consumed, requested);
assert_eq!(receipt, blocks as u64 * elements * 4);
assert_eq!(cursor.position(), (prefix + requested) as u64);
for malformed in [0, 1, bytes - 1, bytes + 1] {
let mut cursor = Cursor::new(&source);
cursor.set_position(7);
let mut calls = 0;
assert!(
visit(
&mut cursor,
prefix as u64,
kind,
malformed as u64,
|_, _| {
calls += 1;
Ok(())
}
)
.is_err()
);
assert_eq!(calls, 0);
assert_eq!(cursor.position(), 7);
}
for delivered in [0, 1] {
let available = delivered * per_chunk * bytes + bytes - 1;
let required = delivered * per_chunk * bytes + bytes;
let mut calls = 0;
assert!(
visit(
&mut Cursor::new(&source[..prefix + available]),
prefix as u64,
kind,
required as u64,
|raw, derived| {
calls += 1;
assert_eq!(raw.len(), per_chunk * bytes);
assert_eq!(derived.len(), per_chunk * elements as usize * 4);
Ok(())
}
)
.is_err()
);
assert_eq!(calls, delivered);
}
for fail_on in [1, 2] {
let mut cursor = Cursor::new(&source);
let mut calls = 0;
let error = visit(
&mut cursor,
prefix as u64,
kind,
requested as u64,
|_, _| {
calls += 1;
if calls == fail_on {
Err("owned callback abort".into())
} else {
Ok(())
}
},
)
.unwrap_err();
assert_eq!(error, "owned callback abort");
assert_eq!(calls, fail_on);
assert_eq!(
cursor.position(),
(prefix
+ if fail_on == 1 {
per_chunk * bytes
} else {
requested
}) as u64
);
}
}
}
#[test]
fn iq2s_iq3xxs_streams_preserve_nonfinite_signed_zero_and_zero_packed_fields() {
for kind in [22, 18] {
let (elements, bytes) = gguf::block_geometry(kind).unwrap();
for bits in [
0x0000u16, 0x8000, 0x7c00, 0xfc00, 0x7c01, 0xfc01, 0x7e00, 0xfe00,
] {
for zero_fields in [false, true] {
let mut block = vec![0; bytes as usize];
if !zero_fields {
for (field, byte) in block[2..].iter_mut().enumerate() {
*byte = (field * 29 + 17) as u8;
}
}
block[..2].copy_from_slice(&bits.to_le_bytes());
let mut oracle = vec![0.0; elements as usize];
ggml_bridge::decode_into(kind, &block, &mut oracle).unwrap();
let mut calls = 0;
let receipt = visit(&mut Cursor::new(&block), 0, kind, bytes, |raw, derived| {
assert_eq!(raw, block);
assert_eq!(derived.len(), elements as usize * 4);
for (actual, expected) in derived.as_chunks::<4>().0.iter().zip(&oracle) {
let actual = f32::from_le_bytes(*actual);
if expected.is_nan() {
assert!(actual.is_nan());
} else {
assert_eq!(actual.to_bits(), expected.to_bits());
}
}
calls += 1;
Ok(())
})
.unwrap();
assert_eq!(calls, 1);
assert_eq!(receipt, elements * 4);
}
}
}
}
+1 -232
View File
@@ -281,235 +281,4 @@ impl TokenDecoder for HarmonyDecoder {
}
#[cfg(test)]
mod tests {
use super::*;
/// A tiny vocabulary: the byte tokens, a few merges, and the Harmony markers as control tokens.
fn codec() -> GptOssCodec {
let chars = leleka_tokenizer::gguf_bpe::byte_alphabet();
let mut tokens: Vec<String> = chars.iter().map(|c| c.to_string()).collect();
let mut types = vec![1i64; 256];
for marker in [
"<|start|>",
"<|end|>",
"<|message|>",
"<|channel|>",
"<|call|>",
"<|return|>",
"<|constrain|>",
"<|endoftext|>",
] {
tokens.push(marker.to_owned());
types.push(3);
}
let t: Vec<&str> = tokens.iter().map(String::as_str).collect();
GptOssCodec::new(GgufBpe::from_parts(&t, &types, &[], None, None, None).unwrap()).unwrap()
}
/// Token ids for a script of text and markers.
fn script(c: &GptOssCodec, parts: &[&str]) -> Vec<u32> {
let mut ids = Vec::new();
for part in parts {
match c.bpe.token_id(part) {
Some(id) if part.starts_with("<|") => ids.push(id),
_ => ids.extend(c.bpe.encode(part, false)),
}
}
ids
}
fn decode(c: &GptOssCodec, ids: &[u32]) -> String {
String::from_utf8(crate::codec::decode_all(c, ids).unwrap()).unwrap()
}
#[test]
fn reasoning_then_an_answer_becomes_think_markup() {
let c = codec();
let ids = script(
&c,
&[
"<|channel|>",
"analysis",
"<|message|>",
"Let me think.",
"<|end|>",
"<|start|>",
"assistant",
"<|channel|>",
"final",
"<|message|>",
"Paris.",
],
);
assert_eq!(decode(&c, &ids), "Let me think.</think>\n\nParis.");
}
#[test]
fn an_answer_without_reasoning_still_closes_the_think_block() {
let c = codec();
let ids = script(&c, &["<|channel|>", "final", "<|message|>", "Hi"]);
assert_eq!(decode(&c, &ids), "</think>\n\nHi");
}
#[test]
fn a_tool_call_becomes_a_tool_call_block_and_is_closed_by_finish() {
let c = codec();
// the generation's last token <|call|> is terminal and never decoded
let ids = script(
&c,
&[
"<|channel|>",
"analysis",
"<|message|>",
"Need weather.",
"<|end|>",
"<|start|>",
"assistant",
"<|channel|>",
"commentary to=functions.get_weather ",
"<|constrain|>",
"json",
"<|message|>",
"{\"city\":\"Paris\",\"days\":3,\"deep\":true}",
],
);
assert_eq!(
decode(&c, &ids),
"Need weather.</think>\n\n<tool_call>\n<function=get_weather>\n<parameter=city>\nParis\n</parameter>\n<parameter=days>\n3\n</parameter>\n<parameter=deep>\ntrue\n</parameter>\n</function>\n</tool_call>"
);
}
#[test]
fn a_preamble_and_two_calls_keep_their_order() {
let c = codec();
let ids = script(
&c,
&[
"<|channel|>",
"commentary",
"<|message|>",
"Checking.",
"<|end|>",
"<|start|>",
"assistant",
"<|channel|>",
"commentary to=functions.a ",
"<|constrain|>",
"json",
"<|message|>",
"{}",
"<|end|>",
"<|start|>",
"assistant",
"<|channel|>",
"commentary to=functions.b ",
"<|constrain|>",
"json",
"<|message|>",
"{\"x\":\"1\"}",
],
);
assert_eq!(
decode(&c, &ids),
"</think>\n\nChecking.\n\n<tool_call>\n<function=a>\n</function>\n</tool_call>\n\n<tool_call>\n<function=b>\n<parameter=x>\n1\n</parameter>\n</function>\n</tool_call>"
);
}
#[test]
fn reasoning_only_closes_the_block_when_its_message_ended() {
let c = codec();
let ended = script(
&c,
&["<|channel|>", "analysis", "<|message|>", "Hmm", "<|end|>"],
);
assert_eq!(decode(&c, &ended), "Hmm</think>\n\n");
// cut off in the middle of the reasoning (length limit): no closing marker
let cut = script(&c, &["<|channel|>", "analysis", "<|message|>", "Hmm"]);
assert_eq!(decode(&c, &cut), "Hmm");
}
#[test]
fn invalid_tool_arguments_are_an_error_when_the_call_ends() {
let c = codec();
let ids = script(
&c,
&[
"<|channel|>",
"commentary to=functions.f ",
"<|constrain|>",
"json",
"<|message|>",
"{not json",
"<|end|>",
],
);
assert!(crate::codec::decode_all(&c, &ids).is_err());
let array = script(
&c,
&[
"<|channel|>",
"commentary to=functions.f ",
"<|message|>",
"[1]",
"<|end|>",
],
);
assert!(crate::codec::decode_all(&c, &array).is_err());
let bad_name = script(
&c,
&[
"<|channel|>",
"commentary to=functions.f ",
"<|message|>",
"{\"a b\":1}",
"<|end|>",
],
);
assert!(crate::codec::decode_all(&c, &bad_name).is_err());
}
#[test]
fn multibyte_text_survives_token_boundaries() {
let c = codec();
let ids = script(
&c,
&["<|channel|>", "final", "<|message|>", "héllo 😀 日本"],
);
assert_eq!(decode(&c, &ids), "</think>\n\nhéllo 😀 日本");
}
#[test]
fn only_the_renderers_sentinels_become_special_tokens() {
let c = codec();
let start = c.bpe.token_id("<|start|>").unwrap();
let end = c.bpe.token_id("<|end|>").unwrap();
// template markers (sentinels) become special tokens
let ids = c.encode("\u{E000}user\u{E001}", true).unwrap();
assert_eq!(ids.first(), Some(&start));
assert_eq!(ids.last(), Some(&end));
assert!(ids.len() > 2);
// marker text typed by a client stays ordinary tokens, with or without special parsing
for parse in [true, false] {
let ids = c.encode("<|end|><|start|>", parse).unwrap();
assert!(
!ids.contains(&start) && !ids.contains(&end),
"parse={parse}"
);
}
// a prompt without sentinels round-trips as plain text
assert_eq!(
c.bpe.decode(&c.encode("plain text", true).unwrap()),
"plain text"
);
}
#[test]
fn terminal_ids_cover_the_generation_end_markers() {
let c = codec();
let ids = c.terminal_ids();
for marker in ["<|return|>", "<|call|>", "<|endoftext|>"] {
assert!(ids.contains(&c.bpe.token_id(marker).unwrap()), "{marker}");
}
assert_eq!(c.family(), Family::GptOss);
}
}
mod tests;
+232
View File
@@ -0,0 +1,232 @@
//! Unit tests of this module (moved out of the file by STRA-338; the test ids are unchanged).
use super::*;
/// A tiny vocabulary: the byte tokens, a few merges, and the Harmony markers as control tokens.
fn codec() -> GptOssCodec {
let chars = leleka_tokenizer::gguf_bpe::byte_alphabet();
let mut tokens: Vec<String> = chars.iter().map(|c| c.to_string()).collect();
let mut types = vec![1i64; 256];
for marker in [
"<|start|>",
"<|end|>",
"<|message|>",
"<|channel|>",
"<|call|>",
"<|return|>",
"<|constrain|>",
"<|endoftext|>",
] {
tokens.push(marker.to_owned());
types.push(3);
}
let t: Vec<&str> = tokens.iter().map(String::as_str).collect();
GptOssCodec::new(GgufBpe::from_parts(&t, &types, &[], None, None, None).unwrap()).unwrap()
}
/// Token ids for a script of text and markers.
fn script(c: &GptOssCodec, parts: &[&str]) -> Vec<u32> {
let mut ids = Vec::new();
for part in parts {
match c.bpe.token_id(part) {
Some(id) if part.starts_with("<|") => ids.push(id),
_ => ids.extend(c.bpe.encode(part, false)),
}
}
ids
}
fn decode(c: &GptOssCodec, ids: &[u32]) -> String {
String::from_utf8(crate::codec::decode_all(c, ids).unwrap()).unwrap()
}
#[test]
fn reasoning_then_an_answer_becomes_think_markup() {
let c = codec();
let ids = script(
&c,
&[
"<|channel|>",
"analysis",
"<|message|>",
"Let me think.",
"<|end|>",
"<|start|>",
"assistant",
"<|channel|>",
"final",
"<|message|>",
"Paris.",
],
);
assert_eq!(decode(&c, &ids), "Let me think.</think>\n\nParis.");
}
#[test]
fn an_answer_without_reasoning_still_closes_the_think_block() {
let c = codec();
let ids = script(&c, &["<|channel|>", "final", "<|message|>", "Hi"]);
assert_eq!(decode(&c, &ids), "</think>\n\nHi");
}
#[test]
fn a_tool_call_becomes_a_tool_call_block_and_is_closed_by_finish() {
let c = codec();
// the generation's last token <|call|> is terminal and never decoded
let ids = script(
&c,
&[
"<|channel|>",
"analysis",
"<|message|>",
"Need weather.",
"<|end|>",
"<|start|>",
"assistant",
"<|channel|>",
"commentary to=functions.get_weather ",
"<|constrain|>",
"json",
"<|message|>",
"{\"city\":\"Paris\",\"days\":3,\"deep\":true}",
],
);
assert_eq!(
decode(&c, &ids),
"Need weather.</think>\n\n<tool_call>\n<function=get_weather>\n<parameter=city>\nParis\n</parameter>\n<parameter=days>\n3\n</parameter>\n<parameter=deep>\ntrue\n</parameter>\n</function>\n</tool_call>"
);
}
#[test]
fn a_preamble_and_two_calls_keep_their_order() {
let c = codec();
let ids = script(
&c,
&[
"<|channel|>",
"commentary",
"<|message|>",
"Checking.",
"<|end|>",
"<|start|>",
"assistant",
"<|channel|>",
"commentary to=functions.a ",
"<|constrain|>",
"json",
"<|message|>",
"{}",
"<|end|>",
"<|start|>",
"assistant",
"<|channel|>",
"commentary to=functions.b ",
"<|constrain|>",
"json",
"<|message|>",
"{\"x\":\"1\"}",
],
);
assert_eq!(
decode(&c, &ids),
"</think>\n\nChecking.\n\n<tool_call>\n<function=a>\n</function>\n</tool_call>\n\n<tool_call>\n<function=b>\n<parameter=x>\n1\n</parameter>\n</function>\n</tool_call>"
);
}
#[test]
fn reasoning_only_closes_the_block_when_its_message_ended() {
let c = codec();
let ended = script(
&c,
&["<|channel|>", "analysis", "<|message|>", "Hmm", "<|end|>"],
);
assert_eq!(decode(&c, &ended), "Hmm</think>\n\n");
// cut off in the middle of the reasoning (length limit): no closing marker
let cut = script(&c, &["<|channel|>", "analysis", "<|message|>", "Hmm"]);
assert_eq!(decode(&c, &cut), "Hmm");
}
#[test]
fn invalid_tool_arguments_are_an_error_when_the_call_ends() {
let c = codec();
let ids = script(
&c,
&[
"<|channel|>",
"commentary to=functions.f ",
"<|constrain|>",
"json",
"<|message|>",
"{not json",
"<|end|>",
],
);
assert!(crate::codec::decode_all(&c, &ids).is_err());
let array = script(
&c,
&[
"<|channel|>",
"commentary to=functions.f ",
"<|message|>",
"[1]",
"<|end|>",
],
);
assert!(crate::codec::decode_all(&c, &array).is_err());
let bad_name = script(
&c,
&[
"<|channel|>",
"commentary to=functions.f ",
"<|message|>",
"{\"a b\":1}",
"<|end|>",
],
);
assert!(crate::codec::decode_all(&c, &bad_name).is_err());
}
#[test]
fn multibyte_text_survives_token_boundaries() {
let c = codec();
let ids = script(
&c,
&["<|channel|>", "final", "<|message|>", "héllo 😀 日本"],
);
assert_eq!(decode(&c, &ids), "</think>\n\nhéllo 😀 日本");
}
#[test]
fn only_the_renderers_sentinels_become_special_tokens() {
let c = codec();
let start = c.bpe.token_id("<|start|>").unwrap();
let end = c.bpe.token_id("<|end|>").unwrap();
// template markers (sentinels) become special tokens
let ids = c.encode("\u{E000}user\u{E001}", true).unwrap();
assert_eq!(ids.first(), Some(&start));
assert_eq!(ids.last(), Some(&end));
assert!(ids.len() > 2);
// marker text typed by a client stays ordinary tokens, with or without special parsing
for parse in [true, false] {
let ids = c.encode("<|end|><|start|>", parse).unwrap();
assert!(
!ids.contains(&start) && !ids.contains(&end),
"parse={parse}"
);
}
// a prompt without sentinels round-trips as plain text
assert_eq!(
c.bpe.decode(&c.encode("plain text", true).unwrap()),
"plain text"
);
}
#[test]
fn terminal_ids_cover_the_generation_end_markers() {
let c = codec();
let ids = c.terminal_ids();
for marker in ["<|return|>", "<|call|>", "<|endoftext|>"] {
assert!(ids.contains(&c.bpe.token_id(marker).unwrap()), "{marker}");
}
assert_eq!(c.family(), Family::GptOss);
}
+1 -216
View File
@@ -295,219 +295,4 @@ pub fn verify_source_files(
}
#[cfg(test)]
mod tests {
use super::*;
use crate::model::ModelFile;
use crate::{kar_codec, kar_writer};
use std::fs;
fn put_u32(bytes: &mut [u8], offset: usize, value: u32) {
bytes[offset..offset + 4].copy_from_slice(&value.to_le_bytes());
}
fn put_u64(bytes: &mut [u8], offset: usize, value: u64) {
bytes[offset..offset + 8].copy_from_slice(&value.to_le_bytes());
}
#[test]
fn crc32_matches_iso_hdlc_reference() {
assert_eq!(crc32(b"123456789"), 0xcbf4_3926);
let first = crc32_step(!0, b"1234");
assert_eq!(!crc32_step(first, b"56789"), 0xcbf4_3926);
}
#[test]
fn source_identity_uses_verified_shards_in_filename_order() {
let root = std::env::temp_dir().join(format!("strata-kar-source-{}", std::process::id()));
fs::create_dir(&root).unwrap();
fs::write(root.join("b.gguf"), b"def").unwrap();
fs::write(root.join("a.gguf"), b"abc").unwrap();
let sha = |bytes: &[u8]| hex::encode(Sha256::digest(bytes));
let manifest = Manifest {
schema_version: 1,
files: vec![
ModelFile {
name: "b.gguf".into(),
url: "https://example.invalid/b".into(),
size: 3,
sha256: sha(b"def"),
},
ModelFile {
name: "a.gguf".into(),
url: "https://example.invalid/a".into(),
size: 3,
sha256: sha(b"abc"),
},
],
};
let mut digest = [0; 32];
digest.copy_from_slice(&Sha256::digest(b"abcdef"));
let summary = Summary {
archive_bytes: 1,
tensor_count: 1,
total_elements: 1,
source_total_elements: 1,
accounted_bpw: 8.0,
source_digest: digest,
source_bytes: 6,
max_planes: 0,
};
verify_source_files(&summary, &manifest, &root).unwrap();
fs::write(root.join("b.gguf"), b"xyz").unwrap();
assert!(
verify_source_files(&summary, &manifest, &root)
.unwrap_err()
.contains("SHA-256")
);
fs::remove_dir_all(root).unwrap();
}
#[test]
fn inspects_a_raw_archive_and_rejects_corruption() {
let mut archive = vec![0u8; 768];
let payload_crc = crc32(&archive[512..]);
let (header, rest) = archive.split_at_mut(256);
let (directory, string_and_payload) = rest.split_at_mut(192);
let names = &mut string_and_payload[..7];
names.copy_from_slice(b"weight\0");
put_u32(directory, 0, 0);
directory[4..6].copy_from_slice(&6u16.to_le_bytes());
directory[6] = 1;
directory[7] = 1;
for index in 0..4 {
put_u64(directory, 8 + index * 8, if index == 0 { 64 } else { 1 });
}
put_u64(directory, 48, 64);
put_u64(directory, 56, 64);
put_u64(directory, 112, 512);
put_u64(directory, 120, 256);
put_u32(directory, 108, payload_crc);
header[..8].copy_from_slice(b"KARCHIV2");
put_u32(header, 8, 2);
put_u32(header, 12, 0x04030201);
put_u32(header, 16, 256);
put_u32(header, 20, 192);
put_u64(header, 24, 256);
put_u32(header, 32, 1);
put_u64(header, 40, 448);
put_u64(header, 48, 7);
put_u64(header, 56, 512);
put_u64(header, 64, 768);
put_u64(header, 72, 64);
put_u64(header, 88, 64);
put_u64(header, 120, 256);
header[96..104].copy_from_slice(&96f64.to_le_bytes());
header[106] = 1;
let mut digest = Sha256::new();
digest.update(names);
digest.update(directory);
header[160..192].copy_from_slice(&digest.finalize());
let header_crc = crc32(&header[..192]);
put_u32(header, 192, header_crc);
let path = std::env::temp_dir().join(format!("strata-kar-test-{}", std::process::id()));
fs::write(&path, &archive).unwrap();
let summary = inspect(&path).unwrap();
assert_eq!(summary.tensor_count, 1);
assert_eq!(summary.accounted_bpw, 96.0);
assert_eq!(verify(&path).unwrap(), summary);
let mut decoder = VerifiedRangeDecoder::open(&path).unwrap();
assert_eq!(decoder.element_count("weight").unwrap(), 64);
assert_eq!(
decoder.decode_range("weight", 0, 8, 4).unwrap(),
vec![0.0; 4]
);
let mut nested = archive.clone();
let (header, rest) = nested.split_at_mut(256);
let (directory, string_and_payload) = rest.split_at_mut(192);
directory[7] = 0;
put_u64(directory, 8, 32);
put_u64(directory, 48, 32);
put_u64(directory, 56, 32);
directory[42..45].fill(1);
directory[46..48].copy_from_slice(&32u16.to_le_bytes());
put_u64(directory, 64, 512);
put_u64(directory, 72, 2);
put_u64(directory, 80, 528);
put_u64(directory, 88, 4);
put_u64(directory, 96, 544);
put_u32(directory, 104, 16);
put_u64(header, 72, 32);
put_u64(header, 80, 48);
put_u64(header, 88, 32);
header[96..104].copy_from_slice(&192f64.to_le_bytes());
header[104..106].fill(1);
let mut digest = Sha256::new();
digest.update(&string_and_payload[..7]);
digest.update(directory);
header[160..192].copy_from_slice(&digest.finalize());
let header_crc = crc32(&header[..192]);
put_u32(header, 192, header_crc);
fs::write(&path, &nested).unwrap();
let summary = inspect(&path).unwrap();
assert_eq!(summary.accounted_bpw, 192.0);
assert_eq!(verify(&path).unwrap(), summary);
nested[512] ^= 1;
fs::write(&path, &nested).unwrap();
assert_eq!(inspect(&path).unwrap(), summary);
assert!(verify(&path).unwrap_err().contains("payload CRC"));
archive[300] ^= 1;
fs::write(&path, &archive).unwrap();
assert!(inspect(&path).unwrap_err().contains("digest"));
archive.truncate(767);
fs::write(&path, &archive).unwrap();
assert!(inspect(&path).unwrap_err().contains("length"));
fs::remove_file(path).unwrap();
}
#[test]
fn bounded_archive_range_decode_crosses_scale_and_plane_groups() {
let weights = [-1.0f32, -0.25, 0.25, 1.0].repeat(24);
let encoded =
kar_codec::encode_with_boundaries(&weights, 32, &[-0.5, 0.0, 0.5], 2).unwrap();
let book1 = [0xb800u16, 0x3800];
let book2 = [0xba00u16, 0xb400, 0x3400, 0x3a00];
let books: [&[u16]; 2] = [&book1, &book2];
let planes = encoded.planes.iter().map(Vec::as_slice).collect::<Vec<_>>();
let source = kar_writer::SourceIdentity {
name: "range-fixture",
architecture: "synthetic",
builder: "strata-next/kar-range-test",
digest: Sha256::digest(b"source").into(),
total_elements: 96,
bytes: 384,
};
let tensor = [kar_writer::Tensor {
name: "expert",
dims: &[96],
source_dtype: 0,
source_digest: Sha256::digest(b"weights").into(),
source_offset: 0,
data: kar_writer::TensorData::Nested {
group: 32,
nesting: 0,
planes_min: 1,
planes_max: 2,
scales: &encoded.scales,
books: &books,
planes: &planes,
},
}];
let path =
std::env::temp_dir().join(format!("strata-kar-range-{}.kar", std::process::id()));
let _ = fs::remove_file(&path);
kar_writer::write_archive(&path, &source, &tensor).unwrap();
let full = decode_preview_tensor(&path, "expert", 2).unwrap();
for (start, count) in [(0, 1), (27, 10), (31, 34), (64, 32), (95, 1)] {
assert_eq!(
decode_tensor_range(&path, "expert", 2, start, count).unwrap(),
full[start..start + count]
);
}
assert!(decode_tensor_range(&path, "expert", 2, 96, 1).is_err());
assert!(decode_tensor_range(&path, "expert", 2, 0, 0).is_err());
fs::remove_file(path).unwrap();
}
}
mod tests;
+214
View File
@@ -0,0 +1,214 @@
//! Unit tests of this module (moved out of the file by STRA-338; the test ids are unchanged).
use super::*;
use crate::model::ModelFile;
use crate::{kar_codec, kar_writer};
use std::fs;
fn put_u32(bytes: &mut [u8], offset: usize, value: u32) {
bytes[offset..offset + 4].copy_from_slice(&value.to_le_bytes());
}
fn put_u64(bytes: &mut [u8], offset: usize, value: u64) {
bytes[offset..offset + 8].copy_from_slice(&value.to_le_bytes());
}
#[test]
fn crc32_matches_iso_hdlc_reference() {
assert_eq!(crc32(b"123456789"), 0xcbf4_3926);
let first = crc32_step(!0, b"1234");
assert_eq!(!crc32_step(first, b"56789"), 0xcbf4_3926);
}
#[test]
fn source_identity_uses_verified_shards_in_filename_order() {
let root = std::env::temp_dir().join(format!("strata-kar-source-{}", std::process::id()));
fs::create_dir(&root).unwrap();
fs::write(root.join("b.gguf"), b"def").unwrap();
fs::write(root.join("a.gguf"), b"abc").unwrap();
let sha = |bytes: &[u8]| hex::encode(Sha256::digest(bytes));
let manifest = Manifest {
schema_version: 1,
files: vec![
ModelFile {
name: "b.gguf".into(),
url: "https://example.invalid/b".into(),
size: 3,
sha256: sha(b"def"),
},
ModelFile {
name: "a.gguf".into(),
url: "https://example.invalid/a".into(),
size: 3,
sha256: sha(b"abc"),
},
],
};
let mut digest = [0; 32];
digest.copy_from_slice(&Sha256::digest(b"abcdef"));
let summary = Summary {
archive_bytes: 1,
tensor_count: 1,
total_elements: 1,
source_total_elements: 1,
accounted_bpw: 8.0,
source_digest: digest,
source_bytes: 6,
max_planes: 0,
};
verify_source_files(&summary, &manifest, &root).unwrap();
fs::write(root.join("b.gguf"), b"xyz").unwrap();
assert!(
verify_source_files(&summary, &manifest, &root)
.unwrap_err()
.contains("SHA-256")
);
fs::remove_dir_all(root).unwrap();
}
#[test]
fn inspects_a_raw_archive_and_rejects_corruption() {
let mut archive = vec![0u8; 768];
let payload_crc = crc32(&archive[512..]);
let (header, rest) = archive.split_at_mut(256);
let (directory, string_and_payload) = rest.split_at_mut(192);
let names = &mut string_and_payload[..7];
names.copy_from_slice(b"weight\0");
put_u32(directory, 0, 0);
directory[4..6].copy_from_slice(&6u16.to_le_bytes());
directory[6] = 1;
directory[7] = 1;
for index in 0..4 {
put_u64(directory, 8 + index * 8, if index == 0 { 64 } else { 1 });
}
put_u64(directory, 48, 64);
put_u64(directory, 56, 64);
put_u64(directory, 112, 512);
put_u64(directory, 120, 256);
put_u32(directory, 108, payload_crc);
header[..8].copy_from_slice(b"KARCHIV2");
put_u32(header, 8, 2);
put_u32(header, 12, 0x04030201);
put_u32(header, 16, 256);
put_u32(header, 20, 192);
put_u64(header, 24, 256);
put_u32(header, 32, 1);
put_u64(header, 40, 448);
put_u64(header, 48, 7);
put_u64(header, 56, 512);
put_u64(header, 64, 768);
put_u64(header, 72, 64);
put_u64(header, 88, 64);
put_u64(header, 120, 256);
header[96..104].copy_from_slice(&96f64.to_le_bytes());
header[106] = 1;
let mut digest = Sha256::new();
digest.update(names);
digest.update(directory);
header[160..192].copy_from_slice(&digest.finalize());
let header_crc = crc32(&header[..192]);
put_u32(header, 192, header_crc);
let path = std::env::temp_dir().join(format!("strata-kar-test-{}", std::process::id()));
fs::write(&path, &archive).unwrap();
let summary = inspect(&path).unwrap();
assert_eq!(summary.tensor_count, 1);
assert_eq!(summary.accounted_bpw, 96.0);
assert_eq!(verify(&path).unwrap(), summary);
let mut decoder = VerifiedRangeDecoder::open(&path).unwrap();
assert_eq!(decoder.element_count("weight").unwrap(), 64);
assert_eq!(
decoder.decode_range("weight", 0, 8, 4).unwrap(),
vec![0.0; 4]
);
let mut nested = archive.clone();
let (header, rest) = nested.split_at_mut(256);
let (directory, string_and_payload) = rest.split_at_mut(192);
directory[7] = 0;
put_u64(directory, 8, 32);
put_u64(directory, 48, 32);
put_u64(directory, 56, 32);
directory[42..45].fill(1);
directory[46..48].copy_from_slice(&32u16.to_le_bytes());
put_u64(directory, 64, 512);
put_u64(directory, 72, 2);
put_u64(directory, 80, 528);
put_u64(directory, 88, 4);
put_u64(directory, 96, 544);
put_u32(directory, 104, 16);
put_u64(header, 72, 32);
put_u64(header, 80, 48);
put_u64(header, 88, 32);
header[96..104].copy_from_slice(&192f64.to_le_bytes());
header[104..106].fill(1);
let mut digest = Sha256::new();
digest.update(&string_and_payload[..7]);
digest.update(directory);
header[160..192].copy_from_slice(&digest.finalize());
let header_crc = crc32(&header[..192]);
put_u32(header, 192, header_crc);
fs::write(&path, &nested).unwrap();
let summary = inspect(&path).unwrap();
assert_eq!(summary.accounted_bpw, 192.0);
assert_eq!(verify(&path).unwrap(), summary);
nested[512] ^= 1;
fs::write(&path, &nested).unwrap();
assert_eq!(inspect(&path).unwrap(), summary);
assert!(verify(&path).unwrap_err().contains("payload CRC"));
archive[300] ^= 1;
fs::write(&path, &archive).unwrap();
assert!(inspect(&path).unwrap_err().contains("digest"));
archive.truncate(767);
fs::write(&path, &archive).unwrap();
assert!(inspect(&path).unwrap_err().contains("length"));
fs::remove_file(path).unwrap();
}
#[test]
fn bounded_archive_range_decode_crosses_scale_and_plane_groups() {
let weights = [-1.0f32, -0.25, 0.25, 1.0].repeat(24);
let encoded = kar_codec::encode_with_boundaries(&weights, 32, &[-0.5, 0.0, 0.5], 2).unwrap();
let book1 = [0xb800u16, 0x3800];
let book2 = [0xba00u16, 0xb400, 0x3400, 0x3a00];
let books: [&[u16]; 2] = [&book1, &book2];
let planes = encoded.planes.iter().map(Vec::as_slice).collect::<Vec<_>>();
let source = kar_writer::SourceIdentity {
name: "range-fixture",
architecture: "synthetic",
builder: "strata-next/kar-range-test",
digest: Sha256::digest(b"source").into(),
total_elements: 96,
bytes: 384,
};
let tensor = [kar_writer::Tensor {
name: "expert",
dims: &[96],
source_dtype: 0,
source_digest: Sha256::digest(b"weights").into(),
source_offset: 0,
data: kar_writer::TensorData::Nested {
group: 32,
nesting: 0,
planes_min: 1,
planes_max: 2,
scales: &encoded.scales,
books: &books,
planes: &planes,
},
}];
let path = std::env::temp_dir().join(format!("strata-kar-range-{}.kar", std::process::id()));
let _ = fs::remove_file(&path);
kar_writer::write_archive(&path, &source, &tensor).unwrap();
let full = decode_preview_tensor(&path, "expert", 2).unwrap();
for (start, count) in [(0, 1), (27, 10), (31, 34), (64, 32), (95, 1)] {
assert_eq!(
decode_tensor_range(&path, "expert", 2, start, count).unwrap(),
full[start..start + count]
);
}
assert!(decode_tensor_range(&path, "expert", 2, 96, 1).is_err());
assert!(decode_tensor_range(&path, "expert", 2, 0, 0).is_err());
fs::remove_file(path).unwrap();
}
+15 -869
View File
@@ -41,22 +41,6 @@ struct BaseProvenance {
partitioned_tensors: Vec<PartitionedTensor>,
}
impl BaseProvenance {
fn supported_partition_policy(&self) -> bool {
match (self.schema.as_str(), self.ple_part_elements) {
("strata-next/sharded-stream-provenance-v4", None) => true,
("strata-next/sharded-stream-provenance-v5", Some(limit)) => {
(32..=crate::stream_parts::MAX_PART_ELEMENTS).contains(&limit)
&& self
.partitioned_tensors
.iter()
.any(|tensor| tensor.parent_name == crate::stream_parts::PLE_TENSOR_NAME)
}
_ => false,
}
}
}
#[derive(Deserialize)]
struct PartitionedTensor {
parent_name: String,
@@ -167,116 +151,6 @@ struct CandidateSource<'a> {
derived_bytes: u64,
}
fn candidate_source<'a>(
base: &'a BaseProvenance,
locations: &HashMap<String, Location>,
name: &str,
) -> Result<CandidateSource<'a>, String> {
if let Some(parent) = base
.partitioned_tensors
.iter()
.find(|parent| parent.parts.iter().any(|part| part.name == name))
{
let part = parent.parts.iter().find(|part| part.name == name).unwrap();
let original = base
.tensors
.iter()
.find(|tensor| tensor.name == parent.parent_name)
.ok_or("partition parent absent from base provenance")?;
let location = locations
.get(&parent.parent_name)
.ok_or("partition parent absent from GGUF source")?;
let (block_elements, block_bytes) =
gguf::block_geometry(parent.source_kind).ok_or("unsupported partition source kind")?;
let elements = part
.dimensions
.iter()
.try_fold(1u64, |n, dim| n.checked_mul(*dim))
.ok_or("partition shape overflow")?;
let raw_end = part
.source_byte_offset
.checked_add(part.source_bytes)
.ok_or("partition source offset overflow")?;
let derived_end = part
.derived_offset
.checked_add(part.derived_bytes)
.ok_or("partition derived offset overflow")?;
let expected_offset = original
.derived_offset
.checked_add(
part.source_byte_offset
.checked_div(block_bytes)
.and_then(|blocks| blocks.checked_mul(block_elements))
.and_then(|values| values.checked_mul(4))
.ok_or("partition virtual offset overflow")?,
)
.ok_or("partition virtual offset overflow")?;
if part.dimensions.is_empty()
|| parent.parent_dimensions != location.dimensions
|| parent.source_kind != location.kind
|| original.source_kind != location.kind
|| part.dimensions.len() != parent.parent_dimensions.len()
|| part.dimensions[..part.dimensions.len() - 1]
!= parent.parent_dimensions[..parent.parent_dimensions.len() - 1]
|| part.source_byte_offset % block_bytes != 0
|| elements == 0
|| elements % block_elements != 0
|| part.source_bytes != elements / block_elements * block_bytes
|| part.derived_bytes != elements.checked_mul(4).ok_or("F32 size overflow")?
|| raw_end > location.source_bytes
|| part.derived_offset != expected_offset
|| derived_end
> original
.derived_offset
.checked_add(original.derived_bytes)
.ok_or("parent derived offset overflow")?
{
return Err(format!("{name}: partition geometry differs from base"));
}
return Ok(CandidateSource {
location: Location {
path: location.path.clone(),
absolute: location
.absolute
.checked_add(part.source_byte_offset)
.ok_or("partition absolute offset overflow")?,
kind: location.kind,
source_bytes: part.source_bytes,
dimensions: part.dimensions.clone(),
},
source_sha256: &part.source_sha256,
f32_sha256: &part.f32_sha256,
derived_offset: part.derived_offset,
derived_bytes: part.derived_bytes,
});
}
if base
.partitioned_tensors
.iter()
.any(|parent| parent.parent_name == name)
{
return Err(format!("{name}: partition parent is not a KAR record"));
}
let original = base
.tensors
.iter()
.find(|tensor| tensor.name == name)
.ok_or("candidate absent from base provenance")?;
let location = locations
.get(name)
.ok_or("candidate absent from GGUF source")?;
if location.kind != original.source_kind {
return Err(format!("{name}: source kind differs from base"));
}
Ok(CandidateSource {
location: location.clone(),
source_sha256: &original.source_sha256,
f32_sha256: &original.f32_sha256,
derived_offset: original.derived_offset,
derived_bytes: original.derived_bytes,
})
}
struct Prepared {
name: String,
dimensions: Vec<u64>,
@@ -290,25 +164,11 @@ struct Prepared {
struct Staging(PathBuf);
impl Drop for Staging {
fn drop(&mut self) {
let _ = fs::remove_dir_all(&self.0);
}
}
struct PendingArchive {
path: PathBuf,
committed: bool,
}
impl Drop for PendingArchive {
fn drop(&mut self) {
if !self.committed {
let _ = fs::remove_file(&self.path);
}
}
}
pub struct Summary {
pub archive_bytes: u64,
pub archive_sha256: [u8; 32],
@@ -317,732 +177,18 @@ pub struct Summary {
pub provenance_path: PathBuf,
}
/// Verify both complete archives and bind every replacement to the same
/// virtual-F32 source record before a loader selects an archive by tensor name.
pub fn resolve_verified(base_archive: &Path, overlay_archive: &Path) -> Result<Resolution, String> {
let sidecar = |path: &Path| -> Result<PathBuf, String> {
let name = path.file_name().ok_or("KAR archive has no file name")?;
Ok(path.with_file_name(format!("{}.provenance.json", name.to_string_lossy())))
};
let base: BaseProvenance = serde_json::from_reader(
File::open(sidecar(base_archive)?).map_err(|error| error.to_string())?,
)
.map_err(|error| error.to_string())?;
let overlay: OverlayProvenance = serde_json::from_reader(
File::open(sidecar(overlay_archive)?).map_err(|error| error.to_string())?,
)
.map_err(|error| error.to_string())?;
if !base.supported_partition_policy()
|| overlay.schema != "strata-next/kar-overlay-provenance-v1"
|| overlay.base_archive_sha256 != base.archive_sha256
|| overlay.levels < 2
|| overlay.levels > 8
|| overlay.records.is_empty()
|| hex::encode(hash_file(base_archive)?) != base.archive_sha256
|| hex::encode(hash_file(overlay_archive)?) != overlay.overlay_archive_sha256
{
return Err("base or overlay archive differs from its provenance".into());
}
let (base_summary, base_sources) = kar::verify_with_sources(base_archive)?;
let (overlay_summary, overlay_sources) = kar::verify_with_sources(overlay_archive)?;
if base_summary.source_digest != parse_digest(&base.derived_f32_sha256)?
|| overlay_summary.source_digest != base_summary.source_digest
|| base_summary.source_bytes != base.derived_f32_bytes
|| overlay_summary.source_bytes != base_summary.source_bytes
|| overlay_sources.len() != overlay.records.len()
{
return Err("KAR directory differs from virtual-F32 provenance".into());
}
let mut recorded_base = HashMap::new();
for record in &base.tensors {
if recorded_base.insert(record.name.as_str(), record).is_some() {
return Err("duplicate base provenance tensor".into());
}
}
struct ExpectedSource<'a> {
offset: u64,
bytes: u64,
digest: &'a str,
dimensions: Option<&'a [u64]>,
}
let mut expected = HashMap::new();
let mut partitioned = HashSet::new();
for parent in &base.partitioned_tensors {
let original = recorded_base
.get(parent.parent_name.as_str())
.ok_or("partitioned parent absent from base provenance")?;
if !partitioned.insert(parent.parent_name.as_str())
|| parent.parts.len() < 2
|| parent.parent_dimensions.is_empty()
|| parent
.parent_dimensions
.iter()
.try_fold(1u64, |n, dim| n.checked_mul(*dim))
.and_then(|n| n.checked_mul(4))
!= Some(original.derived_bytes)
{
return Err("invalid partitioned tensor provenance".into());
}
let mut offset = original.derived_offset;
let mut last_dimension = 0u64;
for part in &parent.parts {
if part.dimensions.len() != parent.parent_dimensions.len()
|| part.dimensions[..part.dimensions.len() - 1]
!= parent.parent_dimensions[..parent.parent_dimensions.len() - 1]
|| part
.dimensions
.iter()
.try_fold(1u64, |n, dim| n.checked_mul(*dim))
.and_then(|n| n.checked_mul(4))
!= Some(part.derived_bytes)
|| part.derived_offset != offset
{
return Err(format!("{}: invalid partition geometry", part.name));
}
offset = offset
.checked_add(part.derived_bytes)
.ok_or("partitioned tensor offset overflow")?;
last_dimension = last_dimension
.checked_add(*part.dimensions.last().unwrap())
.ok_or("partitioned tensor shape overflow")?;
if expected
.insert(
part.name.as_str(),
ExpectedSource {
offset: part.derived_offset,
bytes: part.derived_bytes,
digest: &part.f32_sha256,
dimensions: Some(&part.dimensions),
},
)
.is_some()
{
return Err("duplicate partitioned tensor part".into());
}
}
if offset
!= original
.derived_offset
.checked_add(original.derived_bytes)
.ok_or("partitioned parent offset overflow")?
|| last_dimension != *parent.parent_dimensions.last().unwrap()
{
return Err("partitioned parts do not cover their parent".into());
}
}
for record in &base.tensors {
if partitioned.contains(record.name.as_str()) {
continue;
}
if expected
.insert(
record.name.as_str(),
ExpectedSource {
offset: record.derived_offset,
bytes: record.derived_bytes,
digest: &record.f32_sha256,
dimensions: None,
},
)
.is_some()
{
return Err("base provenance record collides with a partition".into());
}
}
if expected.len() != base_sources.len() {
return Err("base KAR record count differs from partitioned provenance".into());
}
for source in &base_sources {
let record = expected
.get(source.name.as_str())
.ok_or("base KAR tensor absent from provenance")?;
if source.digest != parse_digest(record.digest)?
|| source.offset != record.offset
|| source.dtype != 0
|| record
.dimensions
.is_some_and(|dims| source.dimensions != dims)
|| source
.dimensions
.iter()
.try_fold(1u64, |n, dim| n.checked_mul(*dim))
.and_then(|n| n.checked_mul(4))
!= Some(record.bytes)
{
return Err(format!("{}: base source mapping differs", source.name));
}
}
let mut replacements = HashMap::new();
for (index, source) in overlay_sources.iter().enumerate() {
let record = overlay
.records
.iter()
.find(|record| record.name == source.name)
.ok_or("overlay KAR tensor absent from provenance")?;
if replacements.insert(source.name.as_str(), index).is_some()
|| record.derived_offset != source.offset
|| record.f32_sha256 != hex::encode(source.digest)
|| record.section_bytes != source.section_bytes
|| !record.relative_l2.is_finite()
|| record.relative_l2 < 0.0
|| source.dtype != 0
{
return Err(format!("{}: overlay source mapping differs", source.name));
}
}
if replacements.len() != overlay.records.len() {
return Err("duplicate overlay provenance tensor".into());
}
let mut records = Vec::with_capacity(base_sources.len());
for (index, source) in base_sources.iter().enumerate() {
let replacement = replacements.get(source.name.as_str()).copied();
if let Some(overlay_index) = replacement {
let selected = &overlay_sources[overlay_index];
if selected.digest != source.digest
|| selected.offset != source.offset
|| selected.dimensions != source.dimensions
{
return Err(format!(
"{}: overlay replaces a different source tensor",
source.name
));
}
}
records.push(ResolvedRecord {
name: source.name.clone(),
archive: if replacement.is_some() {
"overlay"
} else {
"base"
},
archive_index: replacement.unwrap_or(index),
source_offset: source.offset,
source_sha256: hex::encode(source.digest),
dimensions: source.dimensions.clone(),
});
}
Ok(Resolution {
schema: "strata-next/verified-kar-overlay-selection-v1",
base_archive_sha256: base.archive_sha256,
overlay_archive_sha256: overlay.overlay_archive_sha256,
replacement_count: replacements.len(),
records,
})
}
pub fn prepare(
manifest: &Manifest,
source_dir: &Path,
base_archive: &Path,
candidate_path: &Path,
destination: &Path,
) -> Result<Summary, String> {
let sidecar = destination.with_file_name(format!(
"{}.provenance.json",
destination
.file_name()
.ok_or("overlay destination has no file name")?
.to_string_lossy()
));
if fs::symlink_metadata(destination).is_ok() || fs::symlink_metadata(&sidecar).is_ok() {
return Err("overlay archive or provenance destination already exists".into());
}
let candidates_bytes = fs::read(candidate_path).map_err(|error| error.to_string())?;
let candidates: Candidates =
serde_json::from_slice(&candidates_bytes).map_err(|error| error.to_string())?;
if candidates.schema != "strata-next/proposed-kar-precision-candidates-v1"
|| !(1..=8).contains(&candidates.proposed_levels)
|| candidates.records.is_empty()
{
return Err("invalid KAR overlay candidate policy".into());
}
let base_sidecar = base_archive.with_file_name(format!(
"{}.provenance.json",
base_archive
.file_name()
.ok_or("base archive has no file name")?
.to_string_lossy()
));
let base: BaseProvenance =
serde_json::from_reader(File::open(base_sidecar).map_err(|error| error.to_string())?)
.map_err(|error| error.to_string())?;
if !base.supported_partition_policy() || candidates.source_archive_sha256 != base.archive_sha256
{
return Err("candidate policy differs from base KAR provenance".into());
}
let base_digest = parse_digest(&base.archive_sha256)?;
let source_digest = parse_digest(&base.derived_f32_sha256)?;
let (base_summary, base_sources) = kar::inspect_with_sources(base_archive)?;
if base_summary.source_digest != source_digest
|| base_summary.source_bytes != base.derived_f32_bytes
{
return Err("base KAR header differs from provenance".into());
}
let mut manifest_files = manifest.files.iter().collect::<Vec<_>>();
manifest_files.sort_unstable_by(|a, b| a.name.as_bytes().cmp(b.name.as_bytes()));
if manifest.schema_version != 1 || manifest_files.len() != base.shards.len() {
return Err("source manifest differs from base provenance".into());
}
let mut locations = HashMap::new();
let mut architecture = None::<String>;
for (entry, recorded) in manifest_files.iter().zip(&base.shards) {
if entry.name != recorded.name
|| entry.size != recorded.gguf_bytes
|| entry.sha256 != recorded.gguf_sha256
|| !matches!(
Path::new(&entry.name).components().next(),
Some(Component::Normal(_))
)
|| Path::new(&entry.name).components().count() != 1
{
return Err("source manifest differs from base shard identity".into());
}
let path = source_dir.join(&entry.name);
let index = gguf::tensor_index(&path).map_err(|error| error.to_string())?;
if index.summary.file_size != entry.size {
return Err("source shard length changed since base preparation".into());
}
if let Some(arch) = index.summary.architecture {
if architecture.as_deref().is_some_and(|old| old != arch) {
return Err("GGUF shard architectures differ".into());
}
architecture.get_or_insert(arch);
}
for tensor in index.tensors {
let absolute = index
.summary
.data_start
.checked_add(tensor.offset)
.ok_or("GGUF tensor offset overflow")?;
if locations
.insert(
tensor.name,
Location {
path: path.clone(),
absolute,
kind: tensor.kind,
source_bytes: tensor.bytes,
dimensions: tensor.dimensions,
},
)
.is_some()
{
return Err("duplicate GGUF tensor name".into());
}
}
}
let base_tensors = base
.tensors
.iter()
.map(|tensor| (tensor.name.as_str(), tensor))
.collect::<HashMap<_, _>>();
if base_tensors.len() != base.tensors.len() {
return Err("duplicate tensor in base provenance".into());
}
let base_records = base_sources
.iter()
.map(|record| (record.name.as_str(), record))
.collect::<HashMap<_, _>>();
let staging = Staging(destination.with_file_name(format!(
"{}.overlay-sections-{}",
destination.file_name().unwrap().to_string_lossy(),
std::process::id()
)));
fs::create_dir(&staging.0).map_err(|error| error.to_string())?;
let mut prepared = Vec::with_capacity(candidates.records.len());
let mut seen = HashSet::new();
for candidate in &candidates.records {
if !seen.insert(candidate.name.as_str()) {
return Err("duplicate KAR overlay candidate".into());
}
let selected = candidate_source(&base, &locations, &candidate.name)?;
let location = &selected.location;
let elements = location
.dimensions
.iter()
.try_fold(1u64, |n, dim| n.checked_mul(*dim))
.ok_or("candidate tensor shape overflow")?;
let base_record = base_records
.get(candidate.name.as_str())
.ok_or("candidate is missing from base KAR directory")?;
if elements != candidate.elements
|| selected.derived_bytes != elements.checked_mul(4).ok_or("F32 size overflow")?
|| base_record.offset != selected.derived_offset
|| base_record.digest != parse_digest(selected.f32_sha256)?
|| base_record.dimensions != location.dimensions
{
return Err(format!(
"{}: candidate geometry differs from base",
candidate.name
));
}
let source_sha256 = parse_digest(selected.source_sha256)?;
let f32_sha256 = parse_digest(selected.f32_sha256)?;
let mut source = File::open(&location.path).map_err(|error| error.to_string())?;
let sample = kar_sample::sample_normalized(
&mut source,
location.absolute,
location.kind,
location.source_bytes,
elements,
source_sha256,
kar_sample::MAX_SAMPLE_VALUES,
)?;
let calibration = kar_codec::fit_topdown(&sample, candidates.proposed_levels)
.map_err(|error| format!("{}: {error}", candidate.name))?;
let section_path = staging.0.join(format!("{:06}.section", prepared.len()));
let section = kar_stream_encode::encode_section(
&mut source,
location.absolute,
location.kind,
location.source_bytes,
elements,
&calibration,
&section_path,
)?;
if section.source_digest != source_sha256 || section.derived_digest != f32_sha256 {
return Err(format!("{}: candidate source changed", candidate.name));
}
prepared.push(Prepared {
name: candidate.name.clone(),
dimensions: location.dimensions.clone(),
source_offset: selected.derived_offset,
f32_sha256,
section_path,
section_bytes: section.bytes,
section_sha256: section.digest,
relative_l2: section.relative_l2,
});
}
let tensors = prepared
.iter()
.map(|entry| kar_writer::Tensor {
name: &entry.name,
dims: &entry.dimensions,
source_dtype: 0,
source_digest: entry.f32_sha256,
source_offset: entry.source_offset,
data: kar_writer::TensorData::NestedFile {
group: 32,
nesting: 0,
planes_min: 1,
planes_max: candidates.proposed_levels,
levels: candidates.proposed_levels,
path: &entry.section_path,
offset: 0,
bytes: entry.section_bytes,
digest: entry.section_sha256,
},
})
.collect::<Vec<_>>();
let candidate_sha256: [u8; 32] = Sha256::digest(&candidates_bytes).into();
let builder = format!(
"strata-next/experimental-kar-overlay-v1:l{}:base{}:policy{}",
candidates.proposed_levels,
&base.archive_sha256[..16],
&hex::encode(candidate_sha256)[..16]
);
let source = kar_writer::SourceIdentity {
name: "gguf-shards#derived-f32-le-v4-overlay",
architecture: architecture.as_deref().ok_or("GGUF architecture missing")?,
builder: &builder,
digest: source_digest,
total_elements: base.derived_f32_bytes / 4,
bytes: base.derived_f32_bytes,
};
let archive = kar_writer::write_archive(destination, &source, &tensors)?;
let mut pending = PendingArchive {
path: destination.to_path_buf(),
committed: false,
};
let archive_sha256 = hash_file(destination)?;
let (verified, records) = kar::verify_with_sources(destination)?;
if verified != archive
|| records.len() != prepared.len()
|| records.iter().zip(&prepared).any(|(record, entry)| {
record.name != entry.name
|| record.digest != entry.f32_sha256
|| record.offset != entry.source_offset
})
{
return Err("overlay archive source records failed verification".into());
}
let provenance = serde_json::json!({
"schema": "strata-next/kar-overlay-provenance-v1",
"base_archive_sha256": hex::encode(base_digest),
"candidate_policy_sha256": hex::encode(candidate_sha256),
"overlay_archive_sha256": hex::encode(archive_sha256),
"derived_f32_sha256": hex::encode(source_digest),
"levels": candidates.proposed_levels,
"records": prepared.iter().map(|entry| serde_json::json!({
"name": entry.name,
"derived_offset": entry.source_offset,
"f32_sha256": hex::encode(entry.f32_sha256),
"section_bytes": entry.section_bytes,
"relative_l2": entry.relative_l2,
})).collect::<Vec<_>>(),
"serving_status": "experimental-not-approved",
});
write_provenance(&sidecar, &provenance)?;
pending.committed = true;
Ok(Summary {
archive_bytes: archive.archive_bytes,
archive_sha256,
record_count: prepared.len(),
maximum_relative_l2: prepared
.iter()
.map(|entry| entry.relative_l2)
.fold(0.0f64, f64::max),
provenance_path: sidecar,
})
}
/// Compare complete selected tensors against the verified source bytes.
/// The large base archive is assumed unchanged since its earlier full verify;
/// every selected GGUF tensor and the small overlay are checked in this run.
pub fn compare(
manifest: &Manifest,
source_dir: &Path,
base_archive: &Path,
overlay_archive: &Path,
) -> Result<Comparison, String> {
let base_sidecar = base_archive.with_file_name(format!(
"{}.provenance.json",
base_archive
.file_name()
.ok_or("base archive has no file name")?
.to_string_lossy()
));
let overlay_sidecar = overlay_archive.with_file_name(format!(
"{}.provenance.json",
overlay_archive
.file_name()
.ok_or("overlay archive has no file name")?
.to_string_lossy()
));
let base: BaseProvenance =
serde_json::from_reader(File::open(base_sidecar).map_err(|error| error.to_string())?)
.map_err(|error| error.to_string())?;
let overlay: OverlayProvenance =
serde_json::from_reader(File::open(overlay_sidecar).map_err(|error| error.to_string())?)
.map_err(|error| error.to_string())?;
if !base.supported_partition_policy()
|| overlay.schema != "strata-next/kar-overlay-provenance-v1"
|| overlay.base_archive_sha256 != base.archive_sha256
|| overlay.levels < 2
|| overlay.records.is_empty()
|| hex::encode(hash_file(overlay_archive)?) != overlay.overlay_archive_sha256
{
return Err("overlay provenance differs from base or overlay archive".into());
}
let (base_summary, base_sources) = kar::inspect_with_sources(base_archive)?;
let (overlay_summary, overlay_sources) = kar::verify_with_sources(overlay_archive)?;
if base_summary.source_digest != parse_digest(&base.derived_f32_sha256)?
|| overlay_summary.source_digest != base_summary.source_digest
|| base_summary.source_bytes != base.derived_f32_bytes
|| overlay_sources.len() != overlay.records.len()
{
return Err("KAR source identity differs from overlay provenance".into());
}
let base_records = base_sources
.iter()
.map(|record| (record.name.as_str(), record))
.collect::<HashMap<_, _>>();
if overlay
.records
.iter()
.map(|record| record.name.as_str())
.collect::<HashSet<_>>()
.len()
!= overlay.records.len()
{
return Err("duplicate overlay tensor name".into());
}
let mut manifest_files = manifest.files.iter().collect::<Vec<_>>();
manifest_files.sort_unstable_by(|a, b| a.name.as_bytes().cmp(b.name.as_bytes()));
if manifest.schema_version != 1 || manifest_files.len() != base.shards.len() {
return Err("source manifest differs from base provenance".into());
}
let mut locations = HashMap::new();
for (entry, shard) in manifest_files.iter().zip(&base.shards) {
if entry.name != shard.name
|| entry.size != shard.gguf_bytes
|| entry.sha256 != shard.gguf_sha256
{
return Err("source manifest differs from base provenance".into());
}
let path = source_dir.join(&entry.name);
let index = gguf::tensor_index(&path).map_err(|error| error.to_string())?;
if index.summary.file_size != entry.size {
return Err("GGUF shard length changed".into());
}
for tensor in index.tensors {
let absolute = index
.summary
.data_start
.checked_add(tensor.offset)
.ok_or("GGUF tensor offset overflow")?;
if locations
.insert(
tensor.name,
Location {
path: path.clone(),
absolute,
kind: tensor.kind,
source_bytes: tensor.bytes,
dimensions: tensor.dimensions,
},
)
.is_some()
{
return Err("duplicate GGUF tensor name".into());
}
}
}
let mut base_decoder = kar::VerifiedRangeDecoder::open_previously_verified(base_archive)?;
let mut overlay_decoder = kar::VerifiedRangeDecoder::open_previously_verified(overlay_archive)?;
let mut compared = Vec::with_capacity(overlay.records.len());
for (record, overlay_source) in overlay.records.iter().zip(&overlay_sources) {
let selected = candidate_source(&base, &locations, &record.name)?;
let base_source = base_records
.get(record.name.as_str())
.ok_or("selected tensor absent from base KAR directory")?;
let location = &selected.location;
let f32_digest = parse_digest(&record.f32_sha256)?;
let elements = location
.dimensions
.iter()
.try_fold(1u64, |n, dim| n.checked_mul(*dim))
.ok_or("GGUF tensor shape overflow")?;
if overlay_source.name != record.name
|| base_source.digest != f32_digest
|| overlay_source.digest != f32_digest
|| base_source.dimensions != location.dimensions
|| overlay_source.dimensions != location.dimensions
|| f32_digest != parse_digest(selected.f32_sha256)?
|| base_source.offset != selected.derived_offset
|| overlay_source.offset != selected.derived_offset
|| record.derived_offset != selected.derived_offset
|| selected.derived_bytes != elements.checked_mul(4).ok_or("F32 size overflow")?
{
return Err(format!("{}: selected source mapping differs", record.name));
}
let mut source = File::open(&location.path).map_err(|error| error.to_string())?;
let mut raw_hash = Sha256::new();
let mut f32_hash = Sha256::new();
let mut position = 0usize;
let mut reference_sum = 0.0f64;
let mut base_error = 0.0f64;
let mut overlay_error = 0.0f64;
let decoded_bytes = crate::gguf_f32_stream::visit(
&mut source,
location.absolute,
location.kind,
location.source_bytes,
|raw, f32_bytes| {
raw_hash.update(raw);
f32_hash.update(f32_bytes);
let count = f32_bytes.len() / 4;
let base_values = base_decoder.decode_range(&record.name, 2, position, count)?;
let overlay_values =
overlay_decoder.decode_range(&record.name, overlay.levels, position, count)?;
for ((word, base_value), overlay_value) in f32_bytes
.as_chunks::<4>()
.0
.iter()
.zip(&base_values)
.zip(&overlay_values)
{
let original = f64::from(f32::from_le_bytes(*word));
reference_sum += original * original;
base_error += (original - f64::from(*base_value)).powi(2);
overlay_error += (original - f64::from(*overlay_value)).powi(2);
}
position += count;
Ok(())
},
)?;
if decoded_bytes != elements * 4
|| position as u64 != elements
|| raw_hash.finalize().as_slice() != parse_digest(selected.source_sha256)?
|| f32_hash.finalize().as_slice() != f32_digest
{
return Err(format!(
"{}: selected GGUF source digest mismatch",
record.name
));
}
let denominator = if reference_sum == 0.0 {
1.0
} else {
reference_sum
};
let base_relative_l2 = (base_error / denominator).sqrt();
let overlay_relative_l2 = (overlay_error / denominator).sqrt();
if !base_relative_l2.is_finite()
|| !overlay_relative_l2.is_finite()
|| (overlay_relative_l2 - record.relative_l2).abs() > 1e-6
{
return Err(format!(
"{}: overlay reconstruction differs from encoding",
record.name
));
}
compared.push(ComparedRecord {
name: record.name.clone(),
elements,
base_relative_l2,
overlay_relative_l2,
});
}
Ok(Comparison {
schema: "strata-next/kar-overlay-comparison-v1",
base_archive_sha256: base.archive_sha256,
overlay_archive_sha256: overlay.overlay_archive_sha256,
verification: "prior-full-base-verification-assumed; selected-source-digests-and-overlay-verified-now",
records: compared,
})
}
pub fn write_comparison(path: &Path, comparison: &Comparison) -> Result<(), String> {
let value = serde_json::to_value(comparison).map_err(|error| error.to_string())?;
write_provenance(path, &value)
}
fn parse_digest(value: &str) -> Result<[u8; 32], String> {
hex::decode(value)
.map_err(|error| error.to_string())?
.try_into()
.map_err(|_| "SHA-256 digest is not 32 bytes".into())
}
fn hash_file(path: &Path) -> Result<[u8; 32], String> {
let mut file = File::open(path).map_err(|error| error.to_string())?;
let mut hash = Sha256::new();
let mut buffer = [0u8; 1024 * 1024];
loop {
let count = file.read(&mut buffer).map_err(|error| error.to_string())?;
if count == 0 {
break;
}
hash.update(&buffer[..count]);
}
Ok(hash.finalize().into())
}
fn write_provenance(path: &Path, value: &serde_json::Value) -> Result<(), String> {
let mut file = OpenOptions::new()
.write(true)
.create_new(true)
.open(path)
.map_err(|error| error.to_string())?;
let result = (|| -> Result<(), String> {
serde_json::to_writer_pretty(&mut file, value).map_err(|error| error.to_string())?;
file.write_all(b"\n").map_err(|error| error.to_string())?;
file.sync_all().map_err(|error| error.to_string())
})();
if result.is_err() {
let _ = fs::remove_file(path);
}
result
}
mod impl_baseprovenance;
#[allow(unused_imports)]
pub use impl_baseprovenance::*;
mod resolve_verified;
#[allow(unused_imports)]
pub use resolve_verified::*;
mod prepare;
#[allow(unused_imports)]
pub use prepare::*;
mod compare;
#[allow(unused_imports)]
pub use compare::*;
mod write_provenance;
#[allow(unused_imports)]
pub use write_provenance::*;
+237
View File
@@ -0,0 +1,237 @@
//! Moved out of the parent module by STRA-338: fn compare, fn write_comparison, fn parse_digest, fn hash_file.
#[allow(unused_imports)]
use super::*;
/// Compare complete selected tensors against the verified source bytes.
/// The large base archive is assumed unchanged since its earlier full verify;
/// every selected GGUF tensor and the small overlay are checked in this run.
pub fn compare(
manifest: &Manifest,
source_dir: &Path,
base_archive: &Path,
overlay_archive: &Path,
) -> Result<Comparison, String> {
let base_sidecar = base_archive.with_file_name(format!(
"{}.provenance.json",
base_archive
.file_name()
.ok_or("base archive has no file name")?
.to_string_lossy()
));
let overlay_sidecar = overlay_archive.with_file_name(format!(
"{}.provenance.json",
overlay_archive
.file_name()
.ok_or("overlay archive has no file name")?
.to_string_lossy()
));
let base: BaseProvenance =
serde_json::from_reader(File::open(base_sidecar).map_err(|error| error.to_string())?)
.map_err(|error| error.to_string())?;
let overlay: OverlayProvenance =
serde_json::from_reader(File::open(overlay_sidecar).map_err(|error| error.to_string())?)
.map_err(|error| error.to_string())?;
if !base.supported_partition_policy()
|| overlay.schema != "strata-next/kar-overlay-provenance-v1"
|| overlay.base_archive_sha256 != base.archive_sha256
|| overlay.levels < 2
|| overlay.records.is_empty()
|| hex::encode(hash_file(overlay_archive)?) != overlay.overlay_archive_sha256
{
return Err("overlay provenance differs from base or overlay archive".into());
}
let (base_summary, base_sources) = kar::inspect_with_sources(base_archive)?;
let (overlay_summary, overlay_sources) = kar::verify_with_sources(overlay_archive)?;
if base_summary.source_digest != parse_digest(&base.derived_f32_sha256)?
|| overlay_summary.source_digest != base_summary.source_digest
|| base_summary.source_bytes != base.derived_f32_bytes
|| overlay_sources.len() != overlay.records.len()
{
return Err("KAR source identity differs from overlay provenance".into());
}
let base_records = base_sources
.iter()
.map(|record| (record.name.as_str(), record))
.collect::<HashMap<_, _>>();
if overlay
.records
.iter()
.map(|record| record.name.as_str())
.collect::<HashSet<_>>()
.len()
!= overlay.records.len()
{
return Err("duplicate overlay tensor name".into());
}
let mut manifest_files = manifest.files.iter().collect::<Vec<_>>();
manifest_files.sort_unstable_by(|a, b| a.name.as_bytes().cmp(b.name.as_bytes()));
if manifest.schema_version != 1 || manifest_files.len() != base.shards.len() {
return Err("source manifest differs from base provenance".into());
}
let mut locations = HashMap::new();
for (entry, shard) in manifest_files.iter().zip(&base.shards) {
if entry.name != shard.name
|| entry.size != shard.gguf_bytes
|| entry.sha256 != shard.gguf_sha256
{
return Err("source manifest differs from base provenance".into());
}
let path = source_dir.join(&entry.name);
let index = gguf::tensor_index(&path).map_err(|error| error.to_string())?;
if index.summary.file_size != entry.size {
return Err("GGUF shard length changed".into());
}
for tensor in index.tensors {
let absolute = index
.summary
.data_start
.checked_add(tensor.offset)
.ok_or("GGUF tensor offset overflow")?;
if locations
.insert(
tensor.name,
Location {
path: path.clone(),
absolute,
kind: tensor.kind,
source_bytes: tensor.bytes,
dimensions: tensor.dimensions,
},
)
.is_some()
{
return Err("duplicate GGUF tensor name".into());
}
}
}
let mut base_decoder = kar::VerifiedRangeDecoder::open_previously_verified(base_archive)?;
let mut overlay_decoder = kar::VerifiedRangeDecoder::open_previously_verified(overlay_archive)?;
let mut compared = Vec::with_capacity(overlay.records.len());
for (record, overlay_source) in overlay.records.iter().zip(&overlay_sources) {
let selected = candidate_source(&base, &locations, &record.name)?;
let base_source = base_records
.get(record.name.as_str())
.ok_or("selected tensor absent from base KAR directory")?;
let location = &selected.location;
let f32_digest = parse_digest(&record.f32_sha256)?;
let elements = location
.dimensions
.iter()
.try_fold(1u64, |n, dim| n.checked_mul(*dim))
.ok_or("GGUF tensor shape overflow")?;
if overlay_source.name != record.name
|| base_source.digest != f32_digest
|| overlay_source.digest != f32_digest
|| base_source.dimensions != location.dimensions
|| overlay_source.dimensions != location.dimensions
|| f32_digest != parse_digest(selected.f32_sha256)?
|| base_source.offset != selected.derived_offset
|| overlay_source.offset != selected.derived_offset
|| record.derived_offset != selected.derived_offset
|| selected.derived_bytes != elements.checked_mul(4).ok_or("F32 size overflow")?
{
return Err(format!("{}: selected source mapping differs", record.name));
}
let mut source = File::open(&location.path).map_err(|error| error.to_string())?;
let mut raw_hash = Sha256::new();
let mut f32_hash = Sha256::new();
let mut position = 0usize;
let mut reference_sum = 0.0f64;
let mut base_error = 0.0f64;
let mut overlay_error = 0.0f64;
let decoded_bytes = crate::gguf_f32_stream::visit(
&mut source,
location.absolute,
location.kind,
location.source_bytes,
|raw, f32_bytes| {
raw_hash.update(raw);
f32_hash.update(f32_bytes);
let count = f32_bytes.len() / 4;
let base_values = base_decoder.decode_range(&record.name, 2, position, count)?;
let overlay_values =
overlay_decoder.decode_range(&record.name, overlay.levels, position, count)?;
for ((word, base_value), overlay_value) in f32_bytes
.as_chunks::<4>()
.0
.iter()
.zip(&base_values)
.zip(&overlay_values)
{
let original = f64::from(f32::from_le_bytes(*word));
reference_sum += original * original;
base_error += (original - f64::from(*base_value)).powi(2);
overlay_error += (original - f64::from(*overlay_value)).powi(2);
}
position += count;
Ok(())
},
)?;
if decoded_bytes != elements * 4
|| position as u64 != elements
|| raw_hash.finalize().as_slice() != parse_digest(selected.source_sha256)?
|| f32_hash.finalize().as_slice() != f32_digest
{
return Err(format!(
"{}: selected GGUF source digest mismatch",
record.name
));
}
let denominator = if reference_sum == 0.0 {
1.0
} else {
reference_sum
};
let base_relative_l2 = (base_error / denominator).sqrt();
let overlay_relative_l2 = (overlay_error / denominator).sqrt();
if !base_relative_l2.is_finite()
|| !overlay_relative_l2.is_finite()
|| (overlay_relative_l2 - record.relative_l2).abs() > 1e-6
{
return Err(format!(
"{}: overlay reconstruction differs from encoding",
record.name
));
}
compared.push(ComparedRecord {
name: record.name.clone(),
elements,
base_relative_l2,
overlay_relative_l2,
});
}
Ok(Comparison {
schema: "strata-next/kar-overlay-comparison-v1",
base_archive_sha256: base.archive_sha256,
overlay_archive_sha256: overlay.overlay_archive_sha256,
verification: "prior-full-base-verification-assumed; selected-source-digests-and-overlay-verified-now",
records: compared,
})
}
pub fn write_comparison(path: &Path, comparison: &Comparison) -> Result<(), String> {
let value = serde_json::to_value(comparison).map_err(|error| error.to_string())?;
write_provenance(path, &value)
}
pub(super) fn parse_digest(value: &str) -> Result<[u8; 32], String> {
hex::decode(value)
.map_err(|error| error.to_string())?
.try_into()
.map_err(|_| "SHA-256 digest is not 32 bytes".into())
}
pub(super) fn hash_file(path: &Path) -> Result<[u8; 32], String> {
let mut file = File::open(path).map_err(|error| error.to_string())?;
let mut hash = Sha256::new();
let mut buffer = [0u8; 1024 * 1024];
loop {
let count = file.read(&mut buffer).map_err(|error| error.to_string())?;
if count == 0 {
break;
}
hash.update(&buffer[..count]);
}
Ok(hash.finalize().into())
}
@@ -0,0 +1,144 @@
//! Moved out of the parent module by STRA-338: impl BaseProvenance, fn candidate_source, impl Drop_for_Staging, impl Drop_for_PendingArchive.
#[allow(unused_imports)]
use super::*;
impl BaseProvenance {
pub(super) fn supported_partition_policy(&self) -> bool {
match (self.schema.as_str(), self.ple_part_elements) {
("strata-next/sharded-stream-provenance-v4", None) => true,
("strata-next/sharded-stream-provenance-v5", Some(limit)) => {
(32..=crate::stream_parts::MAX_PART_ELEMENTS).contains(&limit)
&& self
.partitioned_tensors
.iter()
.any(|tensor| tensor.parent_name == crate::stream_parts::PLE_TENSOR_NAME)
}
_ => false,
}
}
}
pub(super) fn candidate_source<'a>(
base: &'a BaseProvenance,
locations: &HashMap<String, Location>,
name: &str,
) -> Result<CandidateSource<'a>, String> {
if let Some(parent) = base
.partitioned_tensors
.iter()
.find(|parent| parent.parts.iter().any(|part| part.name == name))
{
let part = parent.parts.iter().find(|part| part.name == name).unwrap();
let original = base
.tensors
.iter()
.find(|tensor| tensor.name == parent.parent_name)
.ok_or("partition parent absent from base provenance")?;
let location = locations
.get(&parent.parent_name)
.ok_or("partition parent absent from GGUF source")?;
let (block_elements, block_bytes) =
gguf::block_geometry(parent.source_kind).ok_or("unsupported partition source kind")?;
let elements = part
.dimensions
.iter()
.try_fold(1u64, |n, dim| n.checked_mul(*dim))
.ok_or("partition shape overflow")?;
let raw_end = part
.source_byte_offset
.checked_add(part.source_bytes)
.ok_or("partition source offset overflow")?;
let derived_end = part
.derived_offset
.checked_add(part.derived_bytes)
.ok_or("partition derived offset overflow")?;
let expected_offset = original
.derived_offset
.checked_add(
part.source_byte_offset
.checked_div(block_bytes)
.and_then(|blocks| blocks.checked_mul(block_elements))
.and_then(|values| values.checked_mul(4))
.ok_or("partition virtual offset overflow")?,
)
.ok_or("partition virtual offset overflow")?;
if part.dimensions.is_empty()
|| parent.parent_dimensions != location.dimensions
|| parent.source_kind != location.kind
|| original.source_kind != location.kind
|| part.dimensions.len() != parent.parent_dimensions.len()
|| part.dimensions[..part.dimensions.len() - 1]
!= parent.parent_dimensions[..parent.parent_dimensions.len() - 1]
|| part.source_byte_offset % block_bytes != 0
|| elements == 0
|| elements % block_elements != 0
|| part.source_bytes != elements / block_elements * block_bytes
|| part.derived_bytes != elements.checked_mul(4).ok_or("F32 size overflow")?
|| raw_end > location.source_bytes
|| part.derived_offset != expected_offset
|| derived_end
> original
.derived_offset
.checked_add(original.derived_bytes)
.ok_or("parent derived offset overflow")?
{
return Err(format!("{name}: partition geometry differs from base"));
}
return Ok(CandidateSource {
location: Location {
path: location.path.clone(),
absolute: location
.absolute
.checked_add(part.source_byte_offset)
.ok_or("partition absolute offset overflow")?,
kind: location.kind,
source_bytes: part.source_bytes,
dimensions: part.dimensions.clone(),
},
source_sha256: &part.source_sha256,
f32_sha256: &part.f32_sha256,
derived_offset: part.derived_offset,
derived_bytes: part.derived_bytes,
});
}
if base
.partitioned_tensors
.iter()
.any(|parent| parent.parent_name == name)
{
return Err(format!("{name}: partition parent is not a KAR record"));
}
let original = base
.tensors
.iter()
.find(|tensor| tensor.name == name)
.ok_or("candidate absent from base provenance")?;
let location = locations
.get(name)
.ok_or("candidate absent from GGUF source")?;
if location.kind != original.source_kind {
return Err(format!("{name}: source kind differs from base"));
}
Ok(CandidateSource {
location: location.clone(),
source_sha256: &original.source_sha256,
f32_sha256: &original.f32_sha256,
derived_offset: original.derived_offset,
derived_bytes: original.derived_bytes,
})
}
impl Drop for Staging {
fn drop(&mut self) {
let _ = fs::remove_dir_all(&self.0);
}
}
impl Drop for PendingArchive {
fn drop(&mut self) {
if !self.committed {
let _ = fs::remove_file(&self.path);
}
}
}
+271
View File
@@ -0,0 +1,271 @@
//! Moved out of the parent module by STRA-338: fn prepare.
#[allow(unused_imports)]
use super::*;
pub fn prepare(
manifest: &Manifest,
source_dir: &Path,
base_archive: &Path,
candidate_path: &Path,
destination: &Path,
) -> Result<Summary, String> {
let sidecar = destination.with_file_name(format!(
"{}.provenance.json",
destination
.file_name()
.ok_or("overlay destination has no file name")?
.to_string_lossy()
));
if fs::symlink_metadata(destination).is_ok() || fs::symlink_metadata(&sidecar).is_ok() {
return Err("overlay archive or provenance destination already exists".into());
}
let candidates_bytes = fs::read(candidate_path).map_err(|error| error.to_string())?;
let candidates: Candidates =
serde_json::from_slice(&candidates_bytes).map_err(|error| error.to_string())?;
if candidates.schema != "strata-next/proposed-kar-precision-candidates-v1"
|| !(1..=8).contains(&candidates.proposed_levels)
|| candidates.records.is_empty()
{
return Err("invalid KAR overlay candidate policy".into());
}
let base_sidecar = base_archive.with_file_name(format!(
"{}.provenance.json",
base_archive
.file_name()
.ok_or("base archive has no file name")?
.to_string_lossy()
));
let base: BaseProvenance =
serde_json::from_reader(File::open(base_sidecar).map_err(|error| error.to_string())?)
.map_err(|error| error.to_string())?;
if !base.supported_partition_policy() || candidates.source_archive_sha256 != base.archive_sha256
{
return Err("candidate policy differs from base KAR provenance".into());
}
let base_digest = parse_digest(&base.archive_sha256)?;
let source_digest = parse_digest(&base.derived_f32_sha256)?;
let (base_summary, base_sources) = kar::inspect_with_sources(base_archive)?;
if base_summary.source_digest != source_digest
|| base_summary.source_bytes != base.derived_f32_bytes
{
return Err("base KAR header differs from provenance".into());
}
let mut manifest_files = manifest.files.iter().collect::<Vec<_>>();
manifest_files.sort_unstable_by(|a, b| a.name.as_bytes().cmp(b.name.as_bytes()));
if manifest.schema_version != 1 || manifest_files.len() != base.shards.len() {
return Err("source manifest differs from base provenance".into());
}
let mut locations = HashMap::new();
let mut architecture = None::<String>;
for (entry, recorded) in manifest_files.iter().zip(&base.shards) {
if entry.name != recorded.name
|| entry.size != recorded.gguf_bytes
|| entry.sha256 != recorded.gguf_sha256
|| !matches!(
Path::new(&entry.name).components().next(),
Some(Component::Normal(_))
)
|| Path::new(&entry.name).components().count() != 1
{
return Err("source manifest differs from base shard identity".into());
}
let path = source_dir.join(&entry.name);
let index = gguf::tensor_index(&path).map_err(|error| error.to_string())?;
if index.summary.file_size != entry.size {
return Err("source shard length changed since base preparation".into());
}
if let Some(arch) = index.summary.architecture {
if architecture.as_deref().is_some_and(|old| old != arch) {
return Err("GGUF shard architectures differ".into());
}
architecture.get_or_insert(arch);
}
for tensor in index.tensors {
let absolute = index
.summary
.data_start
.checked_add(tensor.offset)
.ok_or("GGUF tensor offset overflow")?;
if locations
.insert(
tensor.name,
Location {
path: path.clone(),
absolute,
kind: tensor.kind,
source_bytes: tensor.bytes,
dimensions: tensor.dimensions,
},
)
.is_some()
{
return Err("duplicate GGUF tensor name".into());
}
}
}
let base_tensors = base
.tensors
.iter()
.map(|tensor| (tensor.name.as_str(), tensor))
.collect::<HashMap<_, _>>();
if base_tensors.len() != base.tensors.len() {
return Err("duplicate tensor in base provenance".into());
}
let base_records = base_sources
.iter()
.map(|record| (record.name.as_str(), record))
.collect::<HashMap<_, _>>();
let staging = Staging(destination.with_file_name(format!(
"{}.overlay-sections-{}",
destination.file_name().unwrap().to_string_lossy(),
std::process::id()
)));
fs::create_dir(&staging.0).map_err(|error| error.to_string())?;
let mut prepared = Vec::with_capacity(candidates.records.len());
let mut seen = HashSet::new();
for candidate in &candidates.records {
if !seen.insert(candidate.name.as_str()) {
return Err("duplicate KAR overlay candidate".into());
}
let selected = candidate_source(&base, &locations, &candidate.name)?;
let location = &selected.location;
let elements = location
.dimensions
.iter()
.try_fold(1u64, |n, dim| n.checked_mul(*dim))
.ok_or("candidate tensor shape overflow")?;
let base_record = base_records
.get(candidate.name.as_str())
.ok_or("candidate is missing from base KAR directory")?;
if elements != candidate.elements
|| selected.derived_bytes != elements.checked_mul(4).ok_or("F32 size overflow")?
|| base_record.offset != selected.derived_offset
|| base_record.digest != parse_digest(selected.f32_sha256)?
|| base_record.dimensions != location.dimensions
{
return Err(format!(
"{}: candidate geometry differs from base",
candidate.name
));
}
let source_sha256 = parse_digest(selected.source_sha256)?;
let f32_sha256 = parse_digest(selected.f32_sha256)?;
let mut source = File::open(&location.path).map_err(|error| error.to_string())?;
let sample = kar_sample::sample_normalized(
&mut source,
location.absolute,
location.kind,
location.source_bytes,
elements,
source_sha256,
kar_sample::MAX_SAMPLE_VALUES,
)?;
let calibration = kar_codec::fit_topdown(&sample, candidates.proposed_levels)
.map_err(|error| format!("{}: {error}", candidate.name))?;
let section_path = staging.0.join(format!("{:06}.section", prepared.len()));
let section = kar_stream_encode::encode_section(
&mut source,
location.absolute,
location.kind,
location.source_bytes,
elements,
&calibration,
&section_path,
)?;
if section.source_digest != source_sha256 || section.derived_digest != f32_sha256 {
return Err(format!("{}: candidate source changed", candidate.name));
}
prepared.push(Prepared {
name: candidate.name.clone(),
dimensions: location.dimensions.clone(),
source_offset: selected.derived_offset,
f32_sha256,
section_path,
section_bytes: section.bytes,
section_sha256: section.digest,
relative_l2: section.relative_l2,
});
}
let tensors = prepared
.iter()
.map(|entry| kar_writer::Tensor {
name: &entry.name,
dims: &entry.dimensions,
source_dtype: 0,
source_digest: entry.f32_sha256,
source_offset: entry.source_offset,
data: kar_writer::TensorData::NestedFile {
group: 32,
nesting: 0,
planes_min: 1,
planes_max: candidates.proposed_levels,
levels: candidates.proposed_levels,
path: &entry.section_path,
offset: 0,
bytes: entry.section_bytes,
digest: entry.section_sha256,
},
})
.collect::<Vec<_>>();
let candidate_sha256: [u8; 32] = Sha256::digest(&candidates_bytes).into();
let builder = format!(
"strata-next/experimental-kar-overlay-v1:l{}:base{}:policy{}",
candidates.proposed_levels,
&base.archive_sha256[..16],
&hex::encode(candidate_sha256)[..16]
);
let source = kar_writer::SourceIdentity {
name: "gguf-shards#derived-f32-le-v4-overlay",
architecture: architecture.as_deref().ok_or("GGUF architecture missing")?,
builder: &builder,
digest: source_digest,
total_elements: base.derived_f32_bytes / 4,
bytes: base.derived_f32_bytes,
};
let archive = kar_writer::write_archive(destination, &source, &tensors)?;
let mut pending = PendingArchive {
path: destination.to_path_buf(),
committed: false,
};
let archive_sha256 = hash_file(destination)?;
let (verified, records) = kar::verify_with_sources(destination)?;
if verified != archive
|| records.len() != prepared.len()
|| records.iter().zip(&prepared).any(|(record, entry)| {
record.name != entry.name
|| record.digest != entry.f32_sha256
|| record.offset != entry.source_offset
})
{
return Err("overlay archive source records failed verification".into());
}
let provenance = serde_json::json!({
"schema": "strata-next/kar-overlay-provenance-v1",
"base_archive_sha256": hex::encode(base_digest),
"candidate_policy_sha256": hex::encode(candidate_sha256),
"overlay_archive_sha256": hex::encode(archive_sha256),
"derived_f32_sha256": hex::encode(source_digest),
"levels": candidates.proposed_levels,
"records": prepared.iter().map(|entry| serde_json::json!({
"name": entry.name,
"derived_offset": entry.source_offset,
"f32_sha256": hex::encode(entry.f32_sha256),
"section_bytes": entry.section_bytes,
"relative_l2": entry.relative_l2,
})).collect::<Vec<_>>(),
"serving_status": "experimental-not-approved",
});
write_provenance(&sidecar, &provenance)?;
pending.committed = true;
Ok(Summary {
archive_bytes: archive.archive_bytes,
archive_sha256,
record_count: prepared.len(),
maximum_relative_l2: prepared
.iter()
.map(|entry| entry.relative_l2)
.fold(0.0f64, f64::max),
provenance_path: sidecar,
})
}
@@ -0,0 +1,217 @@
//! Moved out of the parent module by STRA-338: fn resolve_verified.
#[allow(unused_imports)]
use super::*;
/// Verify both complete archives and bind every replacement to the same
/// virtual-F32 source record before a loader selects an archive by tensor name.
pub fn resolve_verified(base_archive: &Path, overlay_archive: &Path) -> Result<Resolution, String> {
let sidecar = |path: &Path| -> Result<PathBuf, String> {
let name = path.file_name().ok_or("KAR archive has no file name")?;
Ok(path.with_file_name(format!("{}.provenance.json", name.to_string_lossy())))
};
let base: BaseProvenance = serde_json::from_reader(
File::open(sidecar(base_archive)?).map_err(|error| error.to_string())?,
)
.map_err(|error| error.to_string())?;
let overlay: OverlayProvenance = serde_json::from_reader(
File::open(sidecar(overlay_archive)?).map_err(|error| error.to_string())?,
)
.map_err(|error| error.to_string())?;
if !base.supported_partition_policy()
|| overlay.schema != "strata-next/kar-overlay-provenance-v1"
|| overlay.base_archive_sha256 != base.archive_sha256
|| overlay.levels < 2
|| overlay.levels > 8
|| overlay.records.is_empty()
|| hex::encode(hash_file(base_archive)?) != base.archive_sha256
|| hex::encode(hash_file(overlay_archive)?) != overlay.overlay_archive_sha256
{
return Err("base or overlay archive differs from its provenance".into());
}
let (base_summary, base_sources) = kar::verify_with_sources(base_archive)?;
let (overlay_summary, overlay_sources) = kar::verify_with_sources(overlay_archive)?;
if base_summary.source_digest != parse_digest(&base.derived_f32_sha256)?
|| overlay_summary.source_digest != base_summary.source_digest
|| base_summary.source_bytes != base.derived_f32_bytes
|| overlay_summary.source_bytes != base_summary.source_bytes
|| overlay_sources.len() != overlay.records.len()
{
return Err("KAR directory differs from virtual-F32 provenance".into());
}
let mut recorded_base = HashMap::new();
for record in &base.tensors {
if recorded_base.insert(record.name.as_str(), record).is_some() {
return Err("duplicate base provenance tensor".into());
}
}
struct ExpectedSource<'a> {
offset: u64,
bytes: u64,
digest: &'a str,
dimensions: Option<&'a [u64]>,
}
let mut expected = HashMap::new();
let mut partitioned = HashSet::new();
for parent in &base.partitioned_tensors {
let original = recorded_base
.get(parent.parent_name.as_str())
.ok_or("partitioned parent absent from base provenance")?;
if !partitioned.insert(parent.parent_name.as_str())
|| parent.parts.len() < 2
|| parent.parent_dimensions.is_empty()
|| parent
.parent_dimensions
.iter()
.try_fold(1u64, |n, dim| n.checked_mul(*dim))
.and_then(|n| n.checked_mul(4))
!= Some(original.derived_bytes)
{
return Err("invalid partitioned tensor provenance".into());
}
let mut offset = original.derived_offset;
let mut last_dimension = 0u64;
for part in &parent.parts {
if part.dimensions.len() != parent.parent_dimensions.len()
|| part.dimensions[..part.dimensions.len() - 1]
!= parent.parent_dimensions[..parent.parent_dimensions.len() - 1]
|| part
.dimensions
.iter()
.try_fold(1u64, |n, dim| n.checked_mul(*dim))
.and_then(|n| n.checked_mul(4))
!= Some(part.derived_bytes)
|| part.derived_offset != offset
{
return Err(format!("{}: invalid partition geometry", part.name));
}
offset = offset
.checked_add(part.derived_bytes)
.ok_or("partitioned tensor offset overflow")?;
last_dimension = last_dimension
.checked_add(*part.dimensions.last().unwrap())
.ok_or("partitioned tensor shape overflow")?;
if expected
.insert(
part.name.as_str(),
ExpectedSource {
offset: part.derived_offset,
bytes: part.derived_bytes,
digest: &part.f32_sha256,
dimensions: Some(&part.dimensions),
},
)
.is_some()
{
return Err("duplicate partitioned tensor part".into());
}
}
if offset
!= original
.derived_offset
.checked_add(original.derived_bytes)
.ok_or("partitioned parent offset overflow")?
|| last_dimension != *parent.parent_dimensions.last().unwrap()
{
return Err("partitioned parts do not cover their parent".into());
}
}
for record in &base.tensors {
if partitioned.contains(record.name.as_str()) {
continue;
}
if expected
.insert(
record.name.as_str(),
ExpectedSource {
offset: record.derived_offset,
bytes: record.derived_bytes,
digest: &record.f32_sha256,
dimensions: None,
},
)
.is_some()
{
return Err("base provenance record collides with a partition".into());
}
}
if expected.len() != base_sources.len() {
return Err("base KAR record count differs from partitioned provenance".into());
}
for source in &base_sources {
let record = expected
.get(source.name.as_str())
.ok_or("base KAR tensor absent from provenance")?;
if source.digest != parse_digest(record.digest)?
|| source.offset != record.offset
|| source.dtype != 0
|| record
.dimensions
.is_some_and(|dims| source.dimensions != dims)
|| source
.dimensions
.iter()
.try_fold(1u64, |n, dim| n.checked_mul(*dim))
.and_then(|n| n.checked_mul(4))
!= Some(record.bytes)
{
return Err(format!("{}: base source mapping differs", source.name));
}
}
let mut replacements = HashMap::new();
for (index, source) in overlay_sources.iter().enumerate() {
let record = overlay
.records
.iter()
.find(|record| record.name == source.name)
.ok_or("overlay KAR tensor absent from provenance")?;
if replacements.insert(source.name.as_str(), index).is_some()
|| record.derived_offset != source.offset
|| record.f32_sha256 != hex::encode(source.digest)
|| record.section_bytes != source.section_bytes
|| !record.relative_l2.is_finite()
|| record.relative_l2 < 0.0
|| source.dtype != 0
{
return Err(format!("{}: overlay source mapping differs", source.name));
}
}
if replacements.len() != overlay.records.len() {
return Err("duplicate overlay provenance tensor".into());
}
let mut records = Vec::with_capacity(base_sources.len());
for (index, source) in base_sources.iter().enumerate() {
let replacement = replacements.get(source.name.as_str()).copied();
if let Some(overlay_index) = replacement {
let selected = &overlay_sources[overlay_index];
if selected.digest != source.digest
|| selected.offset != source.offset
|| selected.dimensions != source.dimensions
{
return Err(format!(
"{}: overlay replaces a different source tensor",
source.name
));
}
}
records.push(ResolvedRecord {
name: source.name.clone(),
archive: if replacement.is_some() {
"overlay"
} else {
"base"
},
archive_index: replacement.unwrap_or(index),
source_offset: source.offset,
source_sha256: hex::encode(source.digest),
dimensions: source.dimensions.clone(),
});
}
Ok(Resolution {
schema: "strata-next/verified-kar-overlay-selection-v1",
base_archive_sha256: base.archive_sha256,
overlay_archive_sha256: overlay.overlay_archive_sha256,
replacement_count: replacements.len(),
records,
})
}
@@ -0,0 +1,21 @@
//! Moved out of the parent module by STRA-338: fn write_provenance.
#[allow(unused_imports)]
use super::*;
pub(super) fn write_provenance(path: &Path, value: &serde_json::Value) -> Result<(), String> {
let mut file = OpenOptions::new()
.write(true)
.create_new(true)
.open(path)
.map_err(|error| error.to_string())?;
let result = (|| -> Result<(), String> {
serde_json::to_writer_pretty(&mut file, value).map_err(|error| error.to_string())?;
file.write_all(b"\n").map_err(|error| error.to_string())?;
file.sync_all().map_err(|error| error.to_string())
})();
if result.is_err() {
let _ = fs::remove_file(path);
}
result
}
+7 -423
View File
@@ -91,428 +91,12 @@ pub struct SampleWindow {
pub elements: u64,
}
pub fn analyze(
manifest: &Manifest,
source_dir: &Path,
archive_path: &Path,
levels: u8,
) -> Result<Report, String> {
let summary =
prepare_preview::verify_sharded_streamed(manifest, source_dir, archive_path, levels)?;
let provenance_path = archive_path.with_file_name(format!(
"{}.provenance.json",
archive_path
.file_name()
.ok_or("KAR archive has no file name")?
.to_string_lossy()
));
let provenance: serde_json::Value =
serde_json::from_reader(File::open(provenance_path).map_err(|error| error.to_string())?)
.map_err(|error| error.to_string())?;
let archive_sha256 = provenance["archive_sha256"]
.as_str()
.ok_or("verified provenance has no archive digest")?
.to_owned();
let identity = derived_mixed::fingerprint_shards(manifest, source_dir)?;
if summary.source_digest != identity.derived_sha256 {
return Err("KAR source digest changed after verification".into());
}
let parts = stream_parts::plan_shards(&identity, source_dir)?;
sample_records(
source_dir,
&identity,
&parts,
VerifiedRangeDecoder::open(archive_path)?,
levels,
archive_sha256,
"full-derived-source-and-archive-verification",
)
}
/// Reuse a prior full verification of immutable source shards and archive.
/// Checks metadata and provenance mappings, then reads only sampled payloads.
pub fn analyze_previously_verified(
manifest: &Manifest,
source_dir: &Path,
archive_path: &Path,
levels: u8,
) -> Result<Report, String> {
let provenance_path = archive_path.with_file_name(format!(
"{}.provenance.json",
archive_path
.file_name()
.ok_or("KAR archive has no file name")?
.to_string_lossy()
));
let provenance: Provenance =
serde_json::from_reader(File::open(provenance_path).map_err(|error| error.to_string())?)
.map_err(|error| error.to_string())?;
if provenance.schema != "strata-next/sharded-stream-provenance-v4"
|| provenance.levels != levels
|| !(1..=8).contains(&levels)
{
return Err("KAR sampled analysis requires v4 provenance and matching levels".into());
}
let (summary, sources) = kar::inspect_with_sources(archive_path)?;
let derived_sha256 = parse_digest(&provenance.derived_f32_sha256)?;
parse_digest(&provenance.archive_sha256)?;
if summary.source_digest != derived_sha256
|| summary.source_bytes != provenance.derived_f32_bytes
|| summary.max_planes > levels
{
return Err("KAR metadata differs from recorded provenance".into());
}
let mut manifest_files = manifest.files.iter().collect::<Vec<_>>();
manifest_files.sort_unstable_by(|a, b| a.name.as_bytes().cmp(b.name.as_bytes()));
if manifest.schema_version != 1 || manifest_files.len() != provenance.shards.len() {
return Err("source manifest differs from recorded shard list".into());
}
let mut identity = derived_mixed::ShardedIdentity {
derived_sha256,
derived_bytes: provenance.derived_f32_bytes,
shards: Vec::with_capacity(provenance.shards.len()),
tensors: Vec::with_capacity(provenance.tensors.len()),
};
for (manifest_file, recorded) in manifest_files.iter().zip(&provenance.shards) {
if manifest_file.name != recorded.name
|| manifest_file.size != recorded.gguf_bytes
|| manifest_file.sha256 != recorded.gguf_sha256
{
return Err("source manifest differs from recorded provenance".into());
}
let path = source_dir.join(&recorded.name);
if File::open(path)
.and_then(|file| file.metadata())
.map_err(|error| error.to_string())?
.len()
!= recorded.gguf_bytes
{
return Err("source shard length changed since prior verification".into());
}
identity.shards.push(derived_mixed::ShardIdentity {
name: recorded.name.clone(),
gguf_sha256: parse_digest(&recorded.gguf_sha256)?,
gguf_bytes: recorded.gguf_bytes,
tensor_count: recorded.tensor_count,
});
}
for tensor in &provenance.tensors {
identity.tensors.push(derived_mixed::TensorIdentity {
name: tensor.name.clone(),
source_kind: tensor.source_kind,
source_sha256: parse_digest(&tensor.source_sha256)?,
derived_offset: tensor.derived_offset,
derived_bytes: tensor.derived_bytes,
f32_sha256: parse_digest(&tensor.f32_sha256)?,
});
}
let partitioned = provenance
.partitioned_tensors
.iter()
.map(|entry| (entry.parent_name.as_str(), entry))
.collect::<HashMap<_, _>>();
if partitioned.len() != provenance.partitioned_tensors.len() {
return Err("duplicate KAR partition parent".into());
}
let mut parts = Vec::with_capacity(identity.tensors.len());
let mut number = 0usize;
for shard in &identity.shards {
let index =
gguf::tensor_index(&source_dir.join(&shard.name)).map_err(|error| error.to_string())?;
if index.tensors.len() != shard.tensor_count || index.summary.file_size != shard.gguf_bytes
{
return Err("GGUF shard metadata changed since prior verification".into());
}
for tensor in &index.tensors {
let recorded = identity
.tensors
.get(number)
.ok_or("GGUF tensor count differs from provenance")?;
let elements = tensor
.dimensions
.iter()
.try_fold(1u64, |n, dim| n.checked_mul(*dim))
.ok_or("GGUF tensor shape overflow")?;
if recorded.name != tensor.name
|| recorded.source_kind != tensor.kind
|| recorded.derived_bytes != elements * 4
{
return Err("GGUF tensor metadata differs from provenance".into());
}
let group = if let Some(split) = partitioned.get(tensor.name.as_str()) {
if split.source_kind != tensor.kind || split.parts.len() < 2 {
return Err("invalid KAR partition metadata".into());
}
split
.parts
.iter()
.map(|part| {
Ok(stream_parts::PartIdentity {
name: part.name.clone(),
parent_name: tensor.name.clone(),
parent_dimensions: tensor.dimensions.clone(),
dimensions: part.dimensions.clone(),
source_kind: tensor.kind,
source_byte_offset: part.source_byte_offset,
source_bytes: part.source_bytes,
source_sha256: parse_digest(&part.source_sha256)?,
derived_offset: part.derived_offset,
derived_bytes: part.derived_bytes,
f32_sha256: parse_digest(&part.f32_sha256)?,
})
})
.collect::<Result<Vec<_>, String>>()?
} else {
vec![stream_parts::PartIdentity {
name: tensor.name.clone(),
parent_name: tensor.name.clone(),
parent_dimensions: tensor.dimensions.clone(),
dimensions: tensor.dimensions.clone(),
source_kind: tensor.kind,
source_byte_offset: 0,
source_bytes: tensor.bytes,
source_sha256: recorded.source_sha256,
derived_offset: recorded.derived_offset,
derived_bytes: recorded.derived_bytes,
f32_sha256: recorded.f32_sha256,
}]
};
let mut source_cursor = 0u64;
let mut derived_cursor = recorded.derived_offset;
for part in &group {
let part_elements = part
.dimensions
.iter()
.try_fold(1u64, |n, dim| n.checked_mul(*dim))
.ok_or("KAR part shape overflow")?;
if part.source_byte_offset != source_cursor
|| part.derived_offset != derived_cursor
|| part.derived_bytes != part_elements * 4
{
return Err("KAR part offsets or shape differ from provenance".into());
}
source_cursor = source_cursor
.checked_add(part.source_bytes)
.ok_or("KAR part source overflow")?;
derived_cursor = derived_cursor
.checked_add(part.derived_bytes)
.ok_or("KAR part derived overflow")?;
}
if source_cursor != tensor.bytes
|| derived_cursor != recorded.derived_offset + recorded.derived_bytes
{
return Err("KAR parts do not cover GGUF parent".into());
}
parts.push(group);
number += 1;
}
}
if number != identity.tensors.len()
|| partitioned.len() != parts.iter().filter(|group| group.len() > 1).count()
|| sources.len() != parts.iter().map(Vec::len).sum::<usize>()
{
return Err("KAR record count differs from provenance".into());
}
for (record, part) in sources.iter().zip(parts.iter().flatten()) {
if record.name != part.name
|| record.dimensions != part.dimensions
|| record.dtype != 0
|| record.digest != part.f32_sha256
|| record.offset != part.derived_offset
{
return Err("KAR directory differs from recorded source mapping".into());
}
}
sample_records(
source_dir,
&identity,
&parts,
VerifiedRangeDecoder::open_previously_verified(archive_path)?,
levels,
provenance.archive_sha256,
"previous-full-verification-assumed; metadata-checked-now",
)
}
fn parse_digest(value: &str) -> Result<[u8; 32], String> {
hex::decode(value)
.map_err(|error| error.to_string())?
.try_into()
.map_err(|_| "SHA-256 digest is not 32 bytes".into())
}
fn sample_records(
source_dir: &Path,
identity: &derived_mixed::ShardedIdentity,
parts: &[Vec<stream_parts::PartIdentity>],
mut decoder: VerifiedRangeDecoder,
levels: u8,
archive_sha256: String,
verification: &'static str,
) -> Result<Report, String> {
let mut records = Vec::with_capacity(parts.iter().map(Vec::len).sum());
let mut number = 0usize;
for shard in &identity.shards {
let path = source_dir.join(&shard.name);
let index = gguf::tensor_index(&path).map_err(|error| error.to_string())?;
let mut source = File::open(&path).map_err(|error| error.to_string())?;
for tensor in &index.tensors {
let group = parts.get(number).ok_or("KAR source part count changed")?;
for part in group {
let (block_elements, block_bytes) =
gguf::block_geometry(part.source_kind).ok_or("unsupported GGUF source kind")?;
let elements = part.derived_bytes / 4;
let windows = sample_windows(elements, block_elements)?;
let mut error_sum = 0.0f64;
let mut reference_sum = 0.0f64;
let mut sampled_elements = 0u64;
for window in &windows {
let absolute = index
.summary
.data_start
.checked_add(tensor.offset)
.and_then(|offset| offset.checked_add(part.source_byte_offset))
.and_then(|offset| {
offset.checked_add(window.start / block_elements * block_bytes)
})
.ok_or("GGUF sample offset overflow")?;
let source_bytes = window.elements / block_elements * block_bytes;
let mut original = Vec::with_capacity(window.elements as usize);
let decoded_bytes = gguf_f32_stream::visit(
&mut source,
absolute,
part.source_kind,
source_bytes,
|_, f32_bytes| {
original.extend(
f32_bytes
.as_chunks::<4>()
.0
.iter()
.map(|word| f32::from_le_bytes(*word)),
);
Ok(())
},
)?;
if decoded_bytes != window.elements * 4
|| original.len() != window.elements as usize
{
return Err(format!("{}: GGUF sample shape changed", part.name));
}
let reconstructed = decoder.decode_range(
&part.name,
levels,
window.start as usize,
window.elements as usize,
)?;
if reconstructed.len() != original.len() {
return Err(format!("{}: KAR sample shape changed", part.name));
}
for (expected, actual) in original.iter().zip(&reconstructed) {
let delta = f64::from(*expected) - f64::from(*actual);
error_sum += delta * delta;
reference_sum += f64::from(*expected).powi(2);
}
sampled_elements += window.elements;
}
let relative_l2 = if reference_sum == 0.0 {
error_sum.sqrt()
} else {
(error_sum / reference_sum).sqrt()
};
if !relative_l2.is_finite() {
return Err(format!("{}: non-finite KAR sample error", part.name));
}
records.push(RecordError {
name: part.name.clone(),
parent_name: part.parent_name.clone(),
source_kind: part.source_kind,
elements,
sampled_elements,
relative_l2,
windows,
});
}
number += 1;
}
}
if number != parts.len() || records.len() != parts.iter().map(Vec::len).sum::<usize>() {
return Err("KAR source records changed during analysis".into());
}
Ok(Report {
schema: "strata-next/kar-sampled-distortion-v1",
archive_sha256,
derived_f32_sha256: hex::encode(identity.derived_sha256),
levels,
method: "nonoverlapping-first-middle-last-aligned-4096-v2",
verification,
records,
})
}
fn sample_windows(elements: u64, block_elements: u64) -> Result<Vec<SampleWindow>, String> {
if elements == 0 || block_elements == 0 || !elements.is_multiple_of(block_elements) {
return Err("invalid GGUF sample geometry".into());
}
let count = elements.min(SAMPLE_ELEMENTS);
if !count.is_multiple_of(block_elements) {
return Err("GGUF block is larger than quality sample".into());
}
let end = elements - count;
let starts = if elements >= 3 * count {
vec![0, end / 2 / block_elements * block_elements, end]
} else if elements >= 2 * count {
vec![0, end]
} else {
vec![0]
};
let mut result = Vec::new();
for start in starts {
if result
.iter()
.all(|window: &SampleWindow| window.start != start)
{
result.push(SampleWindow {
start,
elements: count,
});
}
}
Ok(result)
}
pub fn write_report(path: &Path, report: &Report) -> Result<(), String> {
let mut file = std::fs::OpenOptions::new()
.write(true)
.create_new(true)
.open(path)
.map_err(|error| error.to_string())?;
let result = (|| -> Result<(), String> {
serde_json::to_writer_pretty(&mut file, report).map_err(|error| error.to_string())?;
file.write_all(b"\n").map_err(|error| error.to_string())?;
file.sync_all().map_err(|error| error.to_string())
})();
if result.is_err() {
let _ = std::fs::remove_file(path);
}
result
}
#[cfg(test)]
mod tests {
use super::*;
mod tests;
#[test]
fn sampled_windows_are_bounded_and_distinct() {
assert_eq!(sample_windows(256, 256).unwrap().len(), 1);
assert_eq!(sample_windows(5000, 1).unwrap().len(), 1);
assert_eq!(sample_windows(8192, 256).unwrap().len(), 2);
let windows = sample_windows(32_000, 256).unwrap();
assert_eq!(windows.len(), 3);
assert!(windows.iter().all(|window| {
window.start.is_multiple_of(256)
&& window.elements == 4096
&& window.start + window.elements <= 32_000
}));
}
}
mod analyze;
#[allow(unused_imports)]
pub use analyze::*;
mod parse_digest;
#[allow(unused_imports)]
pub use parse_digest::*;
+247
View File
@@ -0,0 +1,247 @@
//! Moved out of the parent module by STRA-338: fn analyze, fn analyze_previously_verified.
#[allow(unused_imports)]
use super::*;
pub fn analyze(
manifest: &Manifest,
source_dir: &Path,
archive_path: &Path,
levels: u8,
) -> Result<Report, String> {
let summary =
prepare_preview::verify_sharded_streamed(manifest, source_dir, archive_path, levels)?;
let provenance_path = archive_path.with_file_name(format!(
"{}.provenance.json",
archive_path
.file_name()
.ok_or("KAR archive has no file name")?
.to_string_lossy()
));
let provenance: serde_json::Value =
serde_json::from_reader(File::open(provenance_path).map_err(|error| error.to_string())?)
.map_err(|error| error.to_string())?;
let archive_sha256 = provenance["archive_sha256"]
.as_str()
.ok_or("verified provenance has no archive digest")?
.to_owned();
let identity = derived_mixed::fingerprint_shards(manifest, source_dir)?;
if summary.source_digest != identity.derived_sha256 {
return Err("KAR source digest changed after verification".into());
}
let parts = stream_parts::plan_shards(&identity, source_dir)?;
sample_records(
source_dir,
&identity,
&parts,
VerifiedRangeDecoder::open(archive_path)?,
levels,
archive_sha256,
"full-derived-source-and-archive-verification",
)
}
/// Reuse a prior full verification of immutable source shards and archive.
/// Checks metadata and provenance mappings, then reads only sampled payloads.
pub fn analyze_previously_verified(
manifest: &Manifest,
source_dir: &Path,
archive_path: &Path,
levels: u8,
) -> Result<Report, String> {
let provenance_path = archive_path.with_file_name(format!(
"{}.provenance.json",
archive_path
.file_name()
.ok_or("KAR archive has no file name")?
.to_string_lossy()
));
let provenance: Provenance =
serde_json::from_reader(File::open(provenance_path).map_err(|error| error.to_string())?)
.map_err(|error| error.to_string())?;
if provenance.schema != "strata-next/sharded-stream-provenance-v4"
|| provenance.levels != levels
|| !(1..=8).contains(&levels)
{
return Err("KAR sampled analysis requires v4 provenance and matching levels".into());
}
let (summary, sources) = kar::inspect_with_sources(archive_path)?;
let derived_sha256 = parse_digest(&provenance.derived_f32_sha256)?;
parse_digest(&provenance.archive_sha256)?;
if summary.source_digest != derived_sha256
|| summary.source_bytes != provenance.derived_f32_bytes
|| summary.max_planes > levels
{
return Err("KAR metadata differs from recorded provenance".into());
}
let mut manifest_files = manifest.files.iter().collect::<Vec<_>>();
manifest_files.sort_unstable_by(|a, b| a.name.as_bytes().cmp(b.name.as_bytes()));
if manifest.schema_version != 1 || manifest_files.len() != provenance.shards.len() {
return Err("source manifest differs from recorded shard list".into());
}
let mut identity = derived_mixed::ShardedIdentity {
derived_sha256,
derived_bytes: provenance.derived_f32_bytes,
shards: Vec::with_capacity(provenance.shards.len()),
tensors: Vec::with_capacity(provenance.tensors.len()),
};
for (manifest_file, recorded) in manifest_files.iter().zip(&provenance.shards) {
if manifest_file.name != recorded.name
|| manifest_file.size != recorded.gguf_bytes
|| manifest_file.sha256 != recorded.gguf_sha256
{
return Err("source manifest differs from recorded provenance".into());
}
let path = source_dir.join(&recorded.name);
if File::open(path)
.and_then(|file| file.metadata())
.map_err(|error| error.to_string())?
.len()
!= recorded.gguf_bytes
{
return Err("source shard length changed since prior verification".into());
}
identity.shards.push(derived_mixed::ShardIdentity {
name: recorded.name.clone(),
gguf_sha256: parse_digest(&recorded.gguf_sha256)?,
gguf_bytes: recorded.gguf_bytes,
tensor_count: recorded.tensor_count,
});
}
for tensor in &provenance.tensors {
identity.tensors.push(derived_mixed::TensorIdentity {
name: tensor.name.clone(),
source_kind: tensor.source_kind,
source_sha256: parse_digest(&tensor.source_sha256)?,
derived_offset: tensor.derived_offset,
derived_bytes: tensor.derived_bytes,
f32_sha256: parse_digest(&tensor.f32_sha256)?,
});
}
let partitioned = provenance
.partitioned_tensors
.iter()
.map(|entry| (entry.parent_name.as_str(), entry))
.collect::<HashMap<_, _>>();
if partitioned.len() != provenance.partitioned_tensors.len() {
return Err("duplicate KAR partition parent".into());
}
let mut parts = Vec::with_capacity(identity.tensors.len());
let mut number = 0usize;
for shard in &identity.shards {
let index =
gguf::tensor_index(&source_dir.join(&shard.name)).map_err(|error| error.to_string())?;
if index.tensors.len() != shard.tensor_count || index.summary.file_size != shard.gguf_bytes
{
return Err("GGUF shard metadata changed since prior verification".into());
}
for tensor in &index.tensors {
let recorded = identity
.tensors
.get(number)
.ok_or("GGUF tensor count differs from provenance")?;
let elements = tensor
.dimensions
.iter()
.try_fold(1u64, |n, dim| n.checked_mul(*dim))
.ok_or("GGUF tensor shape overflow")?;
if recorded.name != tensor.name
|| recorded.source_kind != tensor.kind
|| recorded.derived_bytes != elements * 4
{
return Err("GGUF tensor metadata differs from provenance".into());
}
let group = if let Some(split) = partitioned.get(tensor.name.as_str()) {
if split.source_kind != tensor.kind || split.parts.len() < 2 {
return Err("invalid KAR partition metadata".into());
}
split
.parts
.iter()
.map(|part| {
Ok(stream_parts::PartIdentity {
name: part.name.clone(),
parent_name: tensor.name.clone(),
parent_dimensions: tensor.dimensions.clone(),
dimensions: part.dimensions.clone(),
source_kind: tensor.kind,
source_byte_offset: part.source_byte_offset,
source_bytes: part.source_bytes,
source_sha256: parse_digest(&part.source_sha256)?,
derived_offset: part.derived_offset,
derived_bytes: part.derived_bytes,
f32_sha256: parse_digest(&part.f32_sha256)?,
})
})
.collect::<Result<Vec<_>, String>>()?
} else {
vec![stream_parts::PartIdentity {
name: tensor.name.clone(),
parent_name: tensor.name.clone(),
parent_dimensions: tensor.dimensions.clone(),
dimensions: tensor.dimensions.clone(),
source_kind: tensor.kind,
source_byte_offset: 0,
source_bytes: tensor.bytes,
source_sha256: recorded.source_sha256,
derived_offset: recorded.derived_offset,
derived_bytes: recorded.derived_bytes,
f32_sha256: recorded.f32_sha256,
}]
};
let mut source_cursor = 0u64;
let mut derived_cursor = recorded.derived_offset;
for part in &group {
let part_elements = part
.dimensions
.iter()
.try_fold(1u64, |n, dim| n.checked_mul(*dim))
.ok_or("KAR part shape overflow")?;
if part.source_byte_offset != source_cursor
|| part.derived_offset != derived_cursor
|| part.derived_bytes != part_elements * 4
{
return Err("KAR part offsets or shape differ from provenance".into());
}
source_cursor = source_cursor
.checked_add(part.source_bytes)
.ok_or("KAR part source overflow")?;
derived_cursor = derived_cursor
.checked_add(part.derived_bytes)
.ok_or("KAR part derived overflow")?;
}
if source_cursor != tensor.bytes
|| derived_cursor != recorded.derived_offset + recorded.derived_bytes
{
return Err("KAR parts do not cover GGUF parent".into());
}
parts.push(group);
number += 1;
}
}
if number != identity.tensors.len()
|| partitioned.len() != parts.iter().filter(|group| group.len() > 1).count()
|| sources.len() != parts.iter().map(Vec::len).sum::<usize>()
{
return Err("KAR record count differs from provenance".into());
}
for (record, part) in sources.iter().zip(parts.iter().flatten()) {
if record.name != part.name
|| record.dimensions != part.dimensions
|| record.dtype != 0
|| record.digest != part.f32_sha256
|| record.offset != part.derived_offset
{
return Err("KAR directory differs from recorded source mapping".into());
}
}
sample_records(
source_dir,
&identity,
&parts,
VerifiedRangeDecoder::open_previously_verified(archive_path)?,
levels,
provenance.archive_sha256,
"previous-full-verification-assumed; metadata-checked-now",
)
}
@@ -0,0 +1,171 @@
//! Moved out of the parent module by STRA-338: fn parse_digest, fn sample_records, fn sample_windows, fn write_report.
#[allow(unused_imports)]
use super::*;
pub(super) fn parse_digest(value: &str) -> Result<[u8; 32], String> {
hex::decode(value)
.map_err(|error| error.to_string())?
.try_into()
.map_err(|_| "SHA-256 digest is not 32 bytes".into())
}
pub(super) fn sample_records(
source_dir: &Path,
identity: &derived_mixed::ShardedIdentity,
parts: &[Vec<stream_parts::PartIdentity>],
mut decoder: VerifiedRangeDecoder,
levels: u8,
archive_sha256: String,
verification: &'static str,
) -> Result<Report, String> {
let mut records = Vec::with_capacity(parts.iter().map(Vec::len).sum());
let mut number = 0usize;
for shard in &identity.shards {
let path = source_dir.join(&shard.name);
let index = gguf::tensor_index(&path).map_err(|error| error.to_string())?;
let mut source = File::open(&path).map_err(|error| error.to_string())?;
for tensor in &index.tensors {
let group = parts.get(number).ok_or("KAR source part count changed")?;
for part in group {
let (block_elements, block_bytes) =
gguf::block_geometry(part.source_kind).ok_or("unsupported GGUF source kind")?;
let elements = part.derived_bytes / 4;
let windows = sample_windows(elements, block_elements)?;
let mut error_sum = 0.0f64;
let mut reference_sum = 0.0f64;
let mut sampled_elements = 0u64;
for window in &windows {
let absolute = index
.summary
.data_start
.checked_add(tensor.offset)
.and_then(|offset| offset.checked_add(part.source_byte_offset))
.and_then(|offset| {
offset.checked_add(window.start / block_elements * block_bytes)
})
.ok_or("GGUF sample offset overflow")?;
let source_bytes = window.elements / block_elements * block_bytes;
let mut original = Vec::with_capacity(window.elements as usize);
let decoded_bytes = gguf_f32_stream::visit(
&mut source,
absolute,
part.source_kind,
source_bytes,
|_, f32_bytes| {
original.extend(
f32_bytes
.as_chunks::<4>()
.0
.iter()
.map(|word| f32::from_le_bytes(*word)),
);
Ok(())
},
)?;
if decoded_bytes != window.elements * 4
|| original.len() != window.elements as usize
{
return Err(format!("{}: GGUF sample shape changed", part.name));
}
let reconstructed = decoder.decode_range(
&part.name,
levels,
window.start as usize,
window.elements as usize,
)?;
if reconstructed.len() != original.len() {
return Err(format!("{}: KAR sample shape changed", part.name));
}
for (expected, actual) in original.iter().zip(&reconstructed) {
let delta = f64::from(*expected) - f64::from(*actual);
error_sum += delta * delta;
reference_sum += f64::from(*expected).powi(2);
}
sampled_elements += window.elements;
}
let relative_l2 = if reference_sum == 0.0 {
error_sum.sqrt()
} else {
(error_sum / reference_sum).sqrt()
};
if !relative_l2.is_finite() {
return Err(format!("{}: non-finite KAR sample error", part.name));
}
records.push(RecordError {
name: part.name.clone(),
parent_name: part.parent_name.clone(),
source_kind: part.source_kind,
elements,
sampled_elements,
relative_l2,
windows,
});
}
number += 1;
}
}
if number != parts.len() || records.len() != parts.iter().map(Vec::len).sum::<usize>() {
return Err("KAR source records changed during analysis".into());
}
Ok(Report {
schema: "strata-next/kar-sampled-distortion-v1",
archive_sha256,
derived_f32_sha256: hex::encode(identity.derived_sha256),
levels,
method: "nonoverlapping-first-middle-last-aligned-4096-v2",
verification,
records,
})
}
pub(super) fn sample_windows(
elements: u64,
block_elements: u64,
) -> Result<Vec<SampleWindow>, String> {
if elements == 0 || block_elements == 0 || !elements.is_multiple_of(block_elements) {
return Err("invalid GGUF sample geometry".into());
}
let count = elements.min(SAMPLE_ELEMENTS);
if !count.is_multiple_of(block_elements) {
return Err("GGUF block is larger than quality sample".into());
}
let end = elements - count;
let starts = if elements >= 3 * count {
vec![0, end / 2 / block_elements * block_elements, end]
} else if elements >= 2 * count {
vec![0, end]
} else {
vec![0]
};
let mut result = Vec::new();
for start in starts {
if result
.iter()
.all(|window: &SampleWindow| window.start != start)
{
result.push(SampleWindow {
start,
elements: count,
});
}
}
Ok(result)
}
pub fn write_report(path: &Path, report: &Report) -> Result<(), String> {
let mut file = std::fs::OpenOptions::new()
.write(true)
.create_new(true)
.open(path)
.map_err(|error| error.to_string())?;
let result = (|| -> Result<(), String> {
serde_json::to_writer_pretty(&mut file, report).map_err(|error| error.to_string())?;
file.write_all(b"\n").map_err(|error| error.to_string())?;
file.sync_all().map_err(|error| error.to_string())
})();
if result.is_err() {
let _ = std::fs::remove_file(path);
}
result
}
+17
View File
@@ -0,0 +1,17 @@
//! Unit tests of this module (moved out of the file by STRA-338; the test ids are unchanged).
use super::*;
#[test]
fn sampled_windows_are_bounded_and_distinct() {
assert_eq!(sample_windows(256, 256).unwrap().len(), 1);
assert_eq!(sample_windows(5000, 1).unwrap().len(), 1);
assert_eq!(sample_windows(8192, 256).unwrap().len(), 2);
let windows = sample_windows(32_000, 256).unwrap();
assert_eq!(windows.len(), 3);
assert!(windows.iter().all(|window| {
window.start.is_multiple_of(256)
&& window.elements == 4096
&& window.start + window.elements <= 32_000
}));
}
+1 -152
View File
@@ -251,155 +251,4 @@ fn hash_file(path: &Path) -> Result<[u8; 32], String> {
}
#[cfg(test)]
mod tests {
use super::*;
use crate::{iq3_s, kar, kar_writer};
use std::io::Cursor;
use std::time::{SystemTime, UNIX_EPOCH};
#[test]
fn streamed_section_matches_existing_writer_and_forms_verified_archive() {
let root = std::env::temp_dir().join(format!(
"strata-stream-section-{}-{}",
std::process::id(),
SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap()
.as_nanos()
));
fs::create_dir(&root).unwrap();
let weights = (0..33)
.map(|number| [-1.0f32, -0.25, 0.25, 1.0][number % 4])
.collect::<Vec<_>>();
let source = weights
.iter()
.flat_map(|value| value.to_le_bytes())
.collect::<Vec<_>>();
let calibration = kar_codec::Calibration {
boundaries: vec![-0.5, 0.0, 0.5],
books: vec![vec![0xb800, 0x3800], vec![0xba00, 0xb400, 0x3400, 0x3a00]],
};
let expected =
kar_codec::encode_with_boundaries(&weights, 32, &calibration.boundaries, 2).unwrap();
let books = calibration
.books
.iter()
.map(Vec::as_slice)
.collect::<Vec<_>>();
let planes = expected
.planes
.iter()
.map(Vec::as_slice)
.collect::<Vec<_>>();
let source_digest: [u8; 32] = Sha256::digest(&source).into();
let reference = root.join("reference.section");
kar_writer::write_nested_section(
&reference,
&kar_writer::Tensor {
name: "expert",
dims: &[33],
source_dtype: 0,
source_digest,
source_offset: 0,
data: kar_writer::TensorData::Nested {
group: 32,
nesting: 0,
planes_min: 1,
planes_max: 2,
scales: &expected.scales,
books: &books,
planes: &planes,
},
},
)
.unwrap();
let output = root.join("streamed.section");
let streamed = encode_section(
&mut Cursor::new(&source),
0,
0,
source.len() as u64,
weights.len() as u64,
&calibration,
&output,
)
.unwrap();
assert_eq!(fs::read(&output).unwrap(), fs::read(&reference).unwrap());
assert_eq!(streamed.source_digest, source_digest);
assert_eq!(streamed.derived_digest, source_digest);
assert!(streamed.relative_l2.is_finite());
let archive = root.join("model.kar");
kar_writer::write_archive(
&archive,
&kar_writer::SourceIdentity {
name: "streamed-test",
architecture: "synthetic",
builder: "test-streamed-g32-l2",
digest: source_digest,
total_elements: 33,
bytes: source.len() as u64,
},
&[kar_writer::Tensor {
name: "expert",
dims: &[33],
source_dtype: 0,
source_digest,
source_offset: 0,
data: kar_writer::TensorData::NestedFile {
group: 32,
nesting: 0,
planes_min: 1,
planes_max: 2,
levels: 2,
path: &output,
offset: 0,
bytes: streamed.bytes,
digest: streamed.digest,
},
}],
)
.unwrap();
assert_eq!(kar::verify(&archive).unwrap().tensor_count, 1);
fs::remove_dir_all(root).unwrap();
}
#[test]
fn iq3_section_preserves_source_and_virtual_f32_identity_across_chunks() {
let mut block = [0u8; iq3_s::BLOCK_BYTES];
block[..2].copy_from_slice(&0x3c00u16.to_le_bytes());
let source = block.repeat(257);
let calibration = kar_codec::Calibration {
boundaries: vec![-0.5, 0.0, 0.5],
books: vec![vec![0xb800, 0x3800], vec![0xba00, 0xb400, 0x3400, 0x3a00]],
};
let path = std::env::temp_dir().join(format!(
"strata-iq3-stream-{}-{}.section",
std::process::id(),
SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap()
.as_nanos()
));
let result = encode_section(
&mut Cursor::new(&source),
0,
21,
source.len() as u64,
(257 * iq3_s::BLOCK_ELEMENTS) as u64,
&calibration,
&path,
)
.unwrap();
assert_eq!(
result.source_digest.as_slice(),
Sha256::digest(&source).as_slice()
);
let virtual_f32 = 1.0f32.to_le_bytes().repeat(257 * iq3_s::BLOCK_ELEMENTS);
assert_eq!(
result.derived_digest.as_slice(),
Sha256::digest(&virtual_f32).as_slice()
);
assert_eq!(result.relative_l2, 0.25);
fs::remove_file(path).unwrap();
}
}
mod tests;
@@ -0,0 +1,152 @@
//! Unit tests of this module (moved out of the file by STRA-338; the test ids are unchanged).
use super::*;
use crate::{iq3_s, kar, kar_writer};
use std::io::Cursor;
use std::time::{SystemTime, UNIX_EPOCH};
#[test]
fn streamed_section_matches_existing_writer_and_forms_verified_archive() {
let root = std::env::temp_dir().join(format!(
"strata-stream-section-{}-{}",
std::process::id(),
SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap()
.as_nanos()
));
fs::create_dir(&root).unwrap();
let weights = (0..33)
.map(|number| [-1.0f32, -0.25, 0.25, 1.0][number % 4])
.collect::<Vec<_>>();
let source = weights
.iter()
.flat_map(|value| value.to_le_bytes())
.collect::<Vec<_>>();
let calibration = kar_codec::Calibration {
boundaries: vec![-0.5, 0.0, 0.5],
books: vec![vec![0xb800, 0x3800], vec![0xba00, 0xb400, 0x3400, 0x3a00]],
};
let expected =
kar_codec::encode_with_boundaries(&weights, 32, &calibration.boundaries, 2).unwrap();
let books = calibration
.books
.iter()
.map(Vec::as_slice)
.collect::<Vec<_>>();
let planes = expected
.planes
.iter()
.map(Vec::as_slice)
.collect::<Vec<_>>();
let source_digest: [u8; 32] = Sha256::digest(&source).into();
let reference = root.join("reference.section");
kar_writer::write_nested_section(
&reference,
&kar_writer::Tensor {
name: "expert",
dims: &[33],
source_dtype: 0,
source_digest,
source_offset: 0,
data: kar_writer::TensorData::Nested {
group: 32,
nesting: 0,
planes_min: 1,
planes_max: 2,
scales: &expected.scales,
books: &books,
planes: &planes,
},
},
)
.unwrap();
let output = root.join("streamed.section");
let streamed = encode_section(
&mut Cursor::new(&source),
0,
0,
source.len() as u64,
weights.len() as u64,
&calibration,
&output,
)
.unwrap();
assert_eq!(fs::read(&output).unwrap(), fs::read(&reference).unwrap());
assert_eq!(streamed.source_digest, source_digest);
assert_eq!(streamed.derived_digest, source_digest);
assert!(streamed.relative_l2.is_finite());
let archive = root.join("model.kar");
kar_writer::write_archive(
&archive,
&kar_writer::SourceIdentity {
name: "streamed-test",
architecture: "synthetic",
builder: "test-streamed-g32-l2",
digest: source_digest,
total_elements: 33,
bytes: source.len() as u64,
},
&[kar_writer::Tensor {
name: "expert",
dims: &[33],
source_dtype: 0,
source_digest,
source_offset: 0,
data: kar_writer::TensorData::NestedFile {
group: 32,
nesting: 0,
planes_min: 1,
planes_max: 2,
levels: 2,
path: &output,
offset: 0,
bytes: streamed.bytes,
digest: streamed.digest,
},
}],
)
.unwrap();
assert_eq!(kar::verify(&archive).unwrap().tensor_count, 1);
fs::remove_dir_all(root).unwrap();
}
#[test]
fn iq3_section_preserves_source_and_virtual_f32_identity_across_chunks() {
let mut block = [0u8; iq3_s::BLOCK_BYTES];
block[..2].copy_from_slice(&0x3c00u16.to_le_bytes());
let source = block.repeat(257);
let calibration = kar_codec::Calibration {
boundaries: vec![-0.5, 0.0, 0.5],
books: vec![vec![0xb800, 0x3800], vec![0xba00, 0xb400, 0x3400, 0x3a00]],
};
let path = std::env::temp_dir().join(format!(
"strata-iq3-stream-{}-{}.section",
std::process::id(),
SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap()
.as_nanos()
));
let result = encode_section(
&mut Cursor::new(&source),
0,
21,
source.len() as u64,
(257 * iq3_s::BLOCK_ELEMENTS) as u64,
&calibration,
&path,
)
.unwrap();
assert_eq!(
result.source_digest.as_slice(),
Sha256::digest(&source).as_slice()
);
let virtual_f32 = 1.0f32.to_le_bytes().repeat(257 * iq3_s::BLOCK_ELEMENTS);
assert_eq!(
result.derived_digest.as_slice(),
Sha256::digest(&virtual_f32).as_slice()
);
assert_eq!(result.relative_l2, 0.25);
fs::remove_file(path).unwrap();
}
File diff suppressed because it is too large Load Diff
+336
View File
@@ -0,0 +1,336 @@
//! Unit tests of this module (moved out of the file by STRA-338; the test ids are unchanged).
use super::*;
#[test]
fn streams_canonical_nested_section_and_rejects_corruption() {
let source = SourceIdentity {
name: "nested-fixture",
architecture: "qwen35",
builder: "strata-next-test",
digest: Sha256::digest(b"source").into(),
total_elements: 32,
bytes: 6,
};
let book1 = [0xbc00, 0x3c00];
let book2 = [0xbe00, 0xb800, 0x3800, 0x3e00];
let books: [&[u16]; 2] = [&book1, &book2];
let plane1 = [0xaaaa_aaaa];
let plane2 = [0x5555_5555];
let planes: [&[u32]; 2] = [&plane1, &plane2];
let source_digest: [u8; 32] = Sha256::digest(b"weights").into();
let original = std::env::temp_dir().join(format!("strata-nested-{}.kar", std::process::id()));
let streamed =
std::env::temp_dir().join(format!("strata-nested-stream-{}.kar", std::process::id()));
let spool =
std::env::temp_dir().join(format!("strata-nested-spool-{}.bin", std::process::id()));
let _ = fs::remove_file(&original);
let _ = fs::remove_file(&streamed);
let nested = [Tensor {
name: "expert",
dims: &[32],
source_dtype: 1,
source_digest,
source_offset: 0,
data: TensorData::Nested {
group: 32,
nesting: 0,
planes_min: 1,
planes_max: 2,
scales: &[0x3c00],
books: &books,
planes: &planes,
},
}];
write_archive(&original, &source, &nested).unwrap();
let reference = fs::read(&original).unwrap();
let section_offset =
u64::from_le_bytes(reference[256 + 112..256 + 120].try_into().unwrap()) as usize;
let section_bytes =
u64::from_le_bytes(reference[256 + 120..256 + 128].try_into().unwrap()) as usize;
let section = &reference[section_offset..section_offset + section_bytes];
let native_spool = std::env::temp_dir().join(format!(
"strata-nested-native-spool-{}.bin",
std::process::id()
));
let _ = fs::remove_file(&native_spool);
let native_section = write_nested_section(&native_spool, &nested[0]).unwrap();
assert_eq!(native_section.bytes, section_bytes as u64);
assert_eq!(fs::read(&native_spool).unwrap(), section);
let expected_digest: [u8; 32] = Sha256::digest(section).into();
assert_eq!(native_section.digest, expected_digest);
let mut spool_bytes = vec![0xabu8; 11];
spool_bytes.extend_from_slice(section);
fs::write(&spool, &spool_bytes).unwrap();
let digest: [u8; 32] = Sha256::digest(section).into();
let file_tensor = |digest| {
[Tensor {
name: "expert",
dims: &[32],
source_dtype: 1,
source_digest,
source_offset: 0,
data: TensorData::NestedFile {
group: 32,
nesting: 0,
planes_min: 1,
planes_max: 2,
levels: 2,
path: &spool,
offset: 11,
bytes: section_bytes as u64,
digest,
},
}]
};
write_archive(&streamed, &source, &file_tensor(digest)).unwrap();
assert_eq!(fs::read(&streamed).unwrap(), reference);
fs::remove_file(&streamed).unwrap();
spool_bytes[11] = 0;
spool_bytes[12] = 0x7c;
fs::write(&spool, &spool_bytes).unwrap();
assert!(
write_archive(&streamed, &source, &file_tensor(digest))
.unwrap_err()
.contains("non-finite f16 scale")
);
assert!(!streamed.exists());
spool_bytes[11..11 + section_bytes].copy_from_slice(section);
spool_bytes[13] = 1;
fs::write(&spool, &spool_bytes).unwrap();
assert!(
write_archive(&streamed, &source, &file_tensor(digest))
.unwrap_err()
.contains("nonzero padding")
);
assert!(!streamed.exists());
spool_bytes[11..11 + section_bytes].copy_from_slice(section);
fs::write(&spool, &spool_bytes).unwrap();
assert!(
write_archive(&streamed, &source, &file_tensor([0; 32]))
.unwrap_err()
.contains("nested section digest mismatch")
);
assert!(!streamed.exists());
fs::remove_file(original).unwrap();
fs::remove_file(spool).unwrap();
fs::remove_file(native_spool).unwrap();
}
#[test]
fn streams_raw_tensor_across_buffer_boundary() {
let raw = vec![0x5au8; 1_048_580];
let source = SourceIdentity {
name: "large-synthetic",
architecture: "qwen35",
builder: "strata-next-test",
digest: Sha256::digest(&raw).into(),
total_elements: 262_145,
bytes: raw.len() as u64,
};
let input = std::env::temp_dir().join(format!("strata-kar-large-{}.bin", std::process::id()));
let output = std::env::temp_dir().join(format!("strata-kar-large-{}.kar", std::process::id()));
let _ = fs::remove_file(&output);
fs::write(&input, &raw).unwrap();
let tensors = [Tensor {
name: "large",
dims: &[262_145],
source_dtype: 0,
source_digest: Sha256::digest(&raw).into(),
source_offset: 0,
data: TensorData::RawFile {
path: &input,
offset: 0,
bytes: raw.len() as u64,
},
}];
let summary = write_archive(&output, &source, &tensors).unwrap();
assert_eq!(summary.tensor_count, 1);
assert_eq!(summary.total_elements, 262_145);
assert_eq!(kar::verify(&output).unwrap(), summary);
fs::remove_file(output).unwrap();
fs::remove_file(input).unwrap();
}
#[test]
fn consuming_writer_removes_staged_input_after_verified_copy() {
let raw = (0..32u32)
.flat_map(|value| (value as f32).to_le_bytes())
.collect::<Vec<_>>();
let root = std::env::temp_dir().join(format!("strata-kar-consume-{}", std::process::id()));
let _ = fs::remove_dir_all(&root);
fs::create_dir(&root).unwrap();
let input = root.join("section.bin");
let output = root.join("archive.kar");
fs::write(&input, &raw).unwrap();
let digest: [u8; 32] = Sha256::digest(&raw).into();
let source = SourceIdentity {
name: "synthetic",
architecture: "qwen35",
builder: "consume-test",
digest,
total_elements: 32,
bytes: raw.len() as u64,
};
let tensors = [Tensor {
name: "raw",
dims: &[32],
source_dtype: 0,
source_digest: digest,
source_offset: 0,
data: TensorData::RawFile {
path: &input,
offset: 0,
bytes: raw.len() as u64,
},
}];
let summary = write_archive_consuming_files(&output, &source, &tensors).unwrap();
assert!(!input.exists());
assert_eq!(kar::verify(&output).unwrap(), summary);
fs::remove_dir_all(root).unwrap();
}
#[test]
fn archive_bytes_match_pinned_koference_reference_writer() {
// Oracle: koference 806d2398, r08/code/kar_container.py, RAW + NESTED fixture.
let raw = (0..32)
.flat_map(|value| (value as f32).to_le_bytes())
.collect::<Vec<_>>();
let mut source_bytes = raw.clone();
source_bytes.extend_from_slice(b"weights");
let source = SourceIdentity {
name: "synthetic",
architecture: "qwen35",
builder: "kar_container.py/2",
digest: Sha256::digest(&source_bytes).into(),
total_elements: 64,
bytes: source_bytes.len() as u64,
};
let book1 = [0xbc00, 0x3c00];
let book2 = [0xbe00, 0xb800, 0x3800, 0x3e00];
let books: [&[u16]; 2] = [&book1, &book2];
let plane1 = [0xaaaa_aaaa];
let plane2 = [0x5555_5555];
let planes: [&[u32]; 2] = [&plane1, &plane2];
let tensors = [
Tensor {
name: "norm",
dims: &[32],
source_dtype: 0,
source_digest: Sha256::digest(&raw).into(),
source_offset: 0,
data: TensorData::Raw(&raw),
},
Tensor {
name: "expert",
dims: &[32],
source_dtype: 1,
source_digest: Sha256::digest(b"weights").into(),
source_offset: 0,
data: TensorData::Nested {
group: 32,
nesting: 0,
planes_min: 1,
planes_max: 2,
scales: &[0x3c00],
books: &books,
planes: &planes,
},
},
];
let path = std::env::temp_dir().join(format!("strata-kar-writer-{}.kar", std::process::id()));
let _ = fs::remove_file(&path);
let summary = write_archive(&path, &source, &tensors).unwrap();
assert_eq!(summary.archive_bytes, 1280);
assert_eq!(summary.tensor_count, 2);
assert_eq!(summary.accounted_bpw, 160.0);
let archive = fs::read(&path).unwrap();
assert_eq!(
hex::encode(Sha256::digest(&archive)),
"013d3daa3f8ee70feb7045eee29390cb51e16d2a8558444cc8d6cbb91918f4f2"
);
assert!(write_archive(&path, &source, &tensors).is_err());
let other = path.with_file_name(format!("strata-kar-stale-{}.kar", std::process::id()));
let stale = other.with_file_name(format!(
"{}.part",
other.file_name().unwrap().to_string_lossy()
));
fs::write(&stale, b"previous work").unwrap();
assert!(write_archive(&other, &source, &tensors).is_err());
assert_eq!(fs::read(&stale).unwrap(), b"previous work");
fs::remove_file(stale).unwrap();
let invalid = [Tensor {
name: "bad-scale",
dims: &[32],
source_dtype: 1,
source_digest: Sha256::digest(b"weights").into(),
source_offset: 0,
data: TensorData::Nested {
group: 32,
nesting: 0,
planes_min: 1,
planes_max: 2,
scales: &[0x7c00],
books: &books,
planes: &planes,
},
}];
assert!(
write_archive(&other, &source, &invalid)
.unwrap_err()
.contains("non-finite f16 scale")
);
assert!(!other.exists());
let raw_file = path.with_file_name(format!("strata-kar-raw-input-{}.bin", std::process::id()));
let mut padded_raw = vec![0u8; 17];
padded_raw.extend_from_slice(&raw);
fs::write(&raw_file, &padded_raw).unwrap();
let streamed_tensors = [
Tensor {
name: "norm",
dims: &[32],
source_dtype: 0,
source_digest: Sha256::digest(&raw).into(),
source_offset: 0,
data: TensorData::RawFile {
path: &raw_file,
offset: 17,
bytes: raw.len() as u64,
},
},
Tensor {
name: "expert",
dims: &[32],
source_dtype: 1,
source_digest: Sha256::digest(b"weights").into(),
source_offset: 0,
data: TensorData::Nested {
group: 32,
nesting: 0,
planes_min: 1,
planes_max: 2,
scales: &[0x3c00],
books: &books,
planes: &planes,
},
},
];
let streamed = path.with_file_name(format!("strata-kar-streamed-{}.kar", std::process::id()));
let _ = fs::remove_file(&streamed);
write_archive(&streamed, &source, &streamed_tensors).unwrap();
assert_eq!(fs::read(&streamed).unwrap(), archive);
padded_raw[17] ^= 1;
fs::write(&raw_file, padded_raw).unwrap();
let corrupt = path.with_file_name(format!("strata-kar-corrupt-{}.kar", std::process::id()));
let _ = fs::remove_file(&corrupt);
assert!(
write_archive(&corrupt, &source, &streamed_tensors)
.unwrap_err()
.contains("RAW source digest mismatch")
);
assert!(!corrupt.exists());
fs::remove_file(streamed).unwrap();
fs::remove_file(raw_file).unwrap();
fs::remove_file(path).unwrap();
}
@@ -0,0 +1,31 @@
//! Moved out of the parent module by STRA-338: fn write_archive, fn write_archive_consuming_files.
#[allow(unused_imports)]
use super::*;
pub fn write_archive(
destination: &Path,
source: &SourceIdentity<'_>,
tensors: &[Tensor<'_>],
) -> Result<kar::Summary, String> {
write_archive_inner(destination, source, tensors, false)
}
/// Consume caller-owned, private staging files as their sections are copied.
/// This bounds peak disk use during streamed model preparation. A failed build
/// must be restarted because some input sections may already be removed.
pub(crate) fn write_archive_consuming_files(
destination: &Path,
source: &SourceIdentity<'_>,
tensors: &[Tensor<'_>],
) -> Result<kar::Summary, String> {
if tensors.iter().any(|tensor| {
!matches!(
&tensor.data,
TensorData::RawFile { .. } | TensorData::NestedFile { .. }
)
}) {
return Err("consuming KAR writer requires file-backed tensors".into());
}
write_archive_inner(destination, source, tensors, true)
}
@@ -0,0 +1,277 @@
//! Moved out of the parent module by STRA-338: fn write_archive_inner.
#[allow(unused_imports)]
use super::*;
pub(super) fn write_archive_inner(
destination: &Path,
source: &SourceIdentity<'_>,
tensors: &[Tensor<'_>],
consume_files: bool,
) -> Result<kar::Summary, String> {
if fs::symlink_metadata(destination).is_ok() || tensors.is_empty() || tensors.len() > 100_000 {
return Err("KAR destination exists or tensor count is invalid".into());
}
if source.bytes == 0 || source.total_elements == 0 {
return Err("KAR source identity needs nonzero bytes and elements".into());
}
let mut names = Vec::new();
let mut name_offsets = Vec::with_capacity(tensors.len());
let mut unique = HashSet::new();
for tensor in tensors {
if tensor.name.is_empty() || !unique.insert(tensor.name) {
return Err("KAR tensor names must be nonempty and unique".into());
}
name_offsets.push(u32::try_from(names.len()).map_err(|_| "KAR string table is too large")?);
push_cstr(&mut names, tensor.name)?;
}
let source_name = u32::try_from(names.len()).map_err(|_| "KAR string table is too large")?;
push_cstr(&mut names, source.name)?;
let source_arch = u32::try_from(names.len()).map_err(|_| "KAR string table is too large")?;
push_cstr(&mut names, source.architecture)?;
let builder_name = u32::try_from(names.len()).map_err(|_| "KAR string table is too large")?;
push_cstr(&mut names, source.builder)?;
if names.len() > 64 * 1024 * 1024 {
return Err("KAR string table exceeds inspector limit".into());
}
let directory_offset = 256u64;
let directory_bytes = (tensors.len() as u64)
.checked_mul(192)
.ok_or("KAR directory overflow")?;
let string_offset = round_up(directory_offset + directory_bytes, 64)?;
let payload_offset = round_up(string_offset + names.len() as u64, 256)?;
let mut cursor = payload_offset;
let mut total_elements = 0u64;
let mut payload_bits = 0u64;
let mut min_planes = u8::MAX;
let mut max_planes = 0u8;
let mut placed = Vec::with_capacity(tensors.len());
for (tensor, &name_offset) in tensors.iter().zip(&name_offsets) {
let n_elements = validate_shape(tensor)?;
total_elements = total_elements
.checked_add(n_elements)
.ok_or("KAR element count overflow")?;
let (n_padded, section_bytes, scales_offset, books_offset, planes_offset, plane_stride) =
match &tensor.data {
TensorData::Raw(raw) => {
let width = if tensor.source_dtype == 0 { 4 } else { 2 };
if raw.len() as u64
!= n_elements
.checked_mul(width)
.ok_or("KAR RAW byte count overflow")?
{
return Err(format!(
"{}: RAW byte count differs from tensor shape",
tensor.name
));
}
(n_elements, round_up(raw.len() as u64, 256)?, 0, 0, 0, 0)
}
TensorData::RawFile { bytes, .. } => {
let width = if tensor.source_dtype == 0 { 4 } else { 2 };
if *bytes
!= n_elements
.checked_mul(width)
.ok_or("KAR RAW byte count overflow")?
{
return Err(format!(
"{}: RAW file byte count differs from tensor shape",
tensor.name
));
}
(n_elements, round_up(*bytes, 256)?, 0, 0, 0, 0)
}
TensorData::Nested {
group,
nesting,
planes_min,
planes_max,
scales,
books,
planes,
} => {
let levels = u8::try_from(planes.len()).map_err(|_| "too many KAR planes")?;
let layout = nested_layout(
cursor,
n_elements,
*group,
*nesting,
*planes_min,
*planes_max,
levels,
)?;
validate_nested_slices(tensor.name, &layout, *group, scales, books, planes)?;
payload_bits = payload_bits
.checked_add(layout.payload_bits)
.ok_or("KAR payload bit count overflow")?;
min_planes = min_planes.min(*planes_min);
max_planes = max_planes.max(*planes_max);
(
layout.n_padded,
layout.section_bytes,
layout.scales_offset,
layout.books_offset,
layout.planes_offset,
layout.plane_stride,
)
}
TensorData::NestedFile {
group,
nesting,
planes_min,
planes_max,
levels,
bytes,
..
} => {
let layout = nested_layout(
cursor,
n_elements,
*group,
*nesting,
*planes_min,
*planes_max,
*levels,
)?;
if *bytes != layout.section_bytes {
return Err(format!(
"{}: nested file section size mismatch",
tensor.name
));
}
payload_bits = payload_bits
.checked_add(layout.payload_bits)
.ok_or("KAR payload bit count overflow")?;
min_planes = min_planes.min(*planes_min);
max_planes = max_planes.max(*planes_max);
(
layout.n_padded,
layout.section_bytes,
layout.scales_offset,
layout.books_offset,
layout.planes_offset,
layout.plane_stride,
)
}
};
placed.push(Placed {
tensor,
name_offset,
n_elements,
n_padded,
section_offset: cursor,
section_bytes,
scales_offset,
books_offset,
planes_offset,
plane_stride,
payload_crc32: 0,
});
cursor = cursor
.checked_add(section_bytes)
.ok_or("KAR archive size overflow")?;
}
if total_elements > source.total_elements {
return Err("KAR tensors exceed source element count".into());
}
let archive_bytes = cursor;
let temporary = destination.with_file_name(format!(
"{}.part",
destination
.file_name()
.ok_or("KAR destination has no filename")?
.to_string_lossy()
));
let mut file = OpenOptions::new()
.write(true)
.create_new(true)
.open(&temporary)
.map_err(|error| error.to_string())?;
let result = (|| -> Result<(), String> {
file.set_len(payload_offset)
.map_err(|error| error.to_string())?;
file.seek(SeekFrom::Start(string_offset))
.map_err(|error| error.to_string())?;
file.write_all(&names).map_err(|error| error.to_string())?;
for entry in &mut placed {
entry.payload_crc32 = write_section(&mut file, entry)?;
if consume_files {
let path = match &entry.tensor.data {
TensorData::RawFile { path, .. } | TensorData::NestedFile { path, .. } => path,
_ => unreachable!(),
};
fs::remove_file(path).map_err(|error| error.to_string())?;
}
}
if file.metadata().map_err(|error| error.to_string())?.len() != archive_bytes {
return Err("KAR writer produced the wrong archive length".into());
}
let mut directory = vec![0u8; directory_bytes as usize];
let (records, remainder) = directory.as_chunks_mut::<192>();
debug_assert!(remainder.is_empty());
for (entry, record) in placed.iter().zip(records) {
write_record(record, entry)?;
}
file.seek(SeekFrom::Start(directory_offset))
.map_err(|error| error.to_string())?;
file.write_all(&directory)
.map_err(|error| error.to_string())?;
let mut digest = Sha256::new();
digest.update(&names);
digest.update(&directory);
let mut header = [0u8; 256];
header[..8].copy_from_slice(b"KARCHIV2");
put_u32(&mut header, 8, 2);
put_u32(&mut header, 12, 0x0403_0201);
put_u32(&mut header, 16, 256);
put_u32(&mut header, 20, 192);
put_u64(&mut header, 24, directory_offset);
put_u32(&mut header, 32, tensors.len() as u32);
put_u64(&mut header, 40, string_offset);
put_u64(&mut header, 48, names.len() as u64);
put_u64(&mut header, 56, payload_offset);
put_u64(&mut header, 64, archive_bytes);
put_u64(&mut header, 72, total_elements);
put_u64(&mut header, 80, payload_bits);
put_u64(&mut header, 88, source.total_elements);
header[96..104]
.copy_from_slice(&(archive_bytes as f64 * 8.0 / total_elements as f64).to_le_bytes());
header[104] = if min_planes == u8::MAX { 0 } else { min_planes };
header[105] = max_planes;
header[106] = 1;
put_u32(&mut header, 108, source_name);
put_u32(&mut header, 112, source_arch);
put_u32(&mut header, 116, builder_name);
put_u64(&mut header, 120, source.bytes);
header[128..160].copy_from_slice(&source.digest);
header[160..192].copy_from_slice(&digest.finalize());
let header_crc = kar::crc32(&header[..192]);
put_u32(&mut header, 192, header_crc);
file.seek(SeekFrom::Start(0))
.map_err(|error| error.to_string())?;
file.write_all(&header).map_err(|error| error.to_string())?;
file.sync_all().map_err(|error| error.to_string())?;
Ok(())
})();
drop(file);
if let Err(error) = result {
let _ = fs::remove_file(&temporary);
return Err(error);
}
let summary = match kar::verify(&temporary) {
Ok(summary) => summary,
Err(error) => {
let _ = fs::remove_file(&temporary);
return Err(error);
}
};
// A hard link publishes a fully written archive atomically without replacing
// an existing destination, even if another writer won the race after preflight.
if let Err(error) = fs::hard_link(&temporary, destination) {
let _ = fs::remove_file(&temporary);
return Err(error.to_string());
}
fs::remove_file(&temporary).map_err(|error| error.to_string())?;
Ok(summary)
}
@@ -0,0 +1,228 @@
//! Moved out of the parent module by STRA-338: fn write_nested_section, fn validate_shape, fn validate_nested_slices, fn push_cstr, fn round_up, fn nested_layout.
#[allow(unused_imports)]
use super::*;
/// Write one canonical NESTED section for later bounded-memory archive assembly.
/// The destination must not exist and is meant to live in a private staging dir.
pub fn write_nested_section(
destination: &Path,
tensor: &Tensor<'_>,
) -> Result<SectionSummary, String> {
let n_elements = validate_shape(tensor)?;
let TensorData::Nested {
group,
nesting,
planes_min,
planes_max,
scales,
books,
planes,
} = &tensor.data
else {
return Err("KAR section spool requires in-memory NESTED tensor".into());
};
let levels = u8::try_from(planes.len()).map_err(|_| "too many KAR planes")?;
let layout = nested_layout(
0,
n_elements,
*group,
*nesting,
*planes_min,
*planes_max,
levels,
)?;
validate_nested_slices(tensor.name, &layout, *group, scales, books, planes)?;
let entry = Placed {
tensor,
name_offset: 0,
n_elements,
n_padded: layout.n_padded,
section_offset: 0,
section_bytes: layout.section_bytes,
scales_offset: layout.scales_offset,
books_offset: layout.books_offset,
planes_offset: layout.planes_offset,
plane_stride: layout.plane_stride,
payload_crc32: 0,
};
let mut output = OpenOptions::new()
.write(true)
.create_new(true)
.open(destination)
.map_err(|error| error.to_string())?;
let result = (|| -> Result<(), String> {
write_section(&mut output, &entry)?;
if output.metadata().map_err(|error| error.to_string())?.len() != layout.section_bytes {
return Err("KAR section spool size mismatch".into());
}
output.sync_all().map_err(|error| error.to_string())?;
Ok(())
})();
drop(output);
if let Err(error) = result {
let _ = fs::remove_file(destination);
return Err(error);
}
let verified = (|| -> Result<SectionSummary, String> {
let mut file = File::open(destination).map_err(|error| error.to_string())?;
validate_nested_file(&mut file, &entry, 0, *group, levels)?;
file.seek(SeekFrom::Start(0))
.map_err(|error| error.to_string())?;
let mut digest = Sha256::new();
let mut buffer = [0u8; 1024 * 1024];
loop {
let count = file.read(&mut buffer).map_err(|error| error.to_string())?;
if count == 0 {
break;
}
digest.update(&buffer[..count]);
}
Ok(SectionSummary {
bytes: layout.section_bytes,
digest: digest.finalize().into(),
})
})();
if verified.is_err() {
let _ = fs::remove_file(destination);
}
verified
}
pub(super) fn validate_shape(tensor: &Tensor<'_>) -> Result<u64, String> {
if !(1..=4).contains(&tensor.dims.len()) || tensor.source_dtype > 2 {
return Err(format!(
"{}: unsupported KAR dimensions or dtype",
tensor.name
));
}
let n = tensor
.dims
.iter()
.try_fold(1u64, |acc, dim| acc.checked_mul(*dim))
.ok_or("KAR tensor shape overflow")?;
if n == 0 {
return Err("KAR tensor has zero elements".into());
}
Ok(n)
}
pub(super) fn validate_nested_slices(
name: &str,
layout: &NestedLayout,
group: u16,
scales: &[u16],
books: &[&[u16]],
planes: &[&[u32]],
) -> Result<(), String> {
if books.len() != planes.len() {
return Err(format!("{name}: level book count mismatch"));
}
if scales.len() as u64 != layout.n_padded / u64::from(group) {
return Err(format!("{name}: scale count mismatch"));
}
if scales.iter().any(|bits| bits & 0x7c00 == 0x7c00) {
return Err(format!("{name}: non-finite f16 scale"));
}
for (index, book) in books.iter().enumerate() {
if book.len() != 1usize << (index + 1) {
return Err(format!("{name}: level book size mismatch"));
}
if book.iter().any(|bits| bits & 0x7c00 == 0x7c00) {
return Err(format!("{name}: non-finite f16 codebook"));
}
}
if planes
.iter()
.any(|plane| plane.len() as u64 != layout.n_padded / 32)
{
return Err(format!("{name}: plane word count mismatch"));
}
Ok(())
}
pub(super) fn push_cstr(destination: &mut Vec<u8>, value: &str) -> Result<(), String> {
if value.contains('\0') {
return Err("KAR names cannot contain NUL".into());
}
destination.extend_from_slice(value.as_bytes());
destination.push(0);
Ok(())
}
pub(super) fn round_up(value: u64, alignment: u64) -> Result<u64, String> {
value
.div_ceil(alignment)
.checked_mul(alignment)
.ok_or("KAR aligned offset overflow".into())
}
pub(super) fn nested_layout(
cursor: u64,
n_elements: u64,
group: u16,
nesting: u8,
planes_min: u8,
planes_max: u8,
levels: u8,
) -> Result<NestedLayout, String> {
let group = u64::from(group);
if group == 0
|| group > 1024
|| !group.is_multiple_of(32)
|| !(1..=16).contains(&levels)
|| nesting > 1
|| planes_min == 0
|| planes_min > planes_max
|| planes_max > levels
{
return Err("invalid nested KAR parameters".into());
}
let n_padded = n_elements
.div_ceil(group)
.checked_mul(group)
.ok_or("KAR padded size overflow")?;
let groups = n_padded / group;
let words = n_padded / 32;
let scales_bytes = groups.checked_mul(2).ok_or("KAR scales overflow")?;
let books_offset = round_up(
cursor
.checked_add(scales_bytes)
.ok_or("KAR scales overflow")?,
16,
)?;
let book_bytes = (1u64 << (levels as u32 + 2)) - 4;
let planes_offset = round_up(
books_offset
.checked_add(book_bytes)
.ok_or("KAR books overflow")?,
16,
)?;
let stride = round_up(words.checked_mul(4).ok_or("KAR plane size overflow")?, 16)?;
let plane_stride = u32::try_from(stride).map_err(|_| "KAR plane stride exceeds u32")?;
let end = planes_offset
.checked_add(
(levels as u64)
.checked_mul(stride)
.ok_or("KAR planes overflow")?,
)
.ok_or("KAR planes overflow")?;
let section_bytes = round_up(
end.checked_sub(cursor)
.ok_or("KAR section offset underflow")?,
256,
)?;
let payload_bits = (levels as u64)
.checked_mul(n_padded)
.and_then(|value| value.checked_add(groups.checked_mul(16)?))
.ok_or("KAR payload bit count overflow")?;
Ok(NestedLayout {
n_padded,
section_bytes,
scales_offset: cursor,
books_offset,
planes_offset,
plane_stride,
payload_bits,
})
}
@@ -0,0 +1,89 @@
//! Moved out of the parent module by STRA-338: fn write_record, fn put_u16, fn put_u32, fn put_u64.
#[allow(unused_imports)]
use super::*;
pub(super) fn write_record(record: &mut [u8], entry: &Placed<'_>) -> Result<(), String> {
let tensor = entry.tensor;
put_u32(record, 0, entry.name_offset);
put_u16(
record,
4,
u16::try_from(tensor.name.len()).map_err(|_| "KAR tensor name too long")?,
);
record[6] = tensor.dims.len() as u8;
record[7] = u8::from(matches!(
tensor.data,
TensorData::Raw(_) | TensorData::RawFile { .. }
));
for index in 0..4 {
put_u64(
record,
8 + index * 8,
tensor.dims.get(index).copied().unwrap_or(1),
);
}
record[41] = tensor.source_dtype;
let nested = match &tensor.data {
TensorData::Nested {
group,
nesting,
planes_min,
planes_max,
planes,
..
} => Some((
*group,
*nesting,
*planes_min,
*planes_max,
planes.len() as u8,
)),
TensorData::NestedFile {
group,
nesting,
planes_min,
planes_max,
levels,
..
} => Some((*group, *nesting, *planes_min, *planes_max, *levels)),
_ => None,
};
if let Some((group, nesting, planes_min, planes_max, levels)) = nested {
record[42] = levels;
record[43] = planes_min;
record[44] = planes_max;
record[45] = nesting;
put_u16(record, 46, group);
put_u64(record, 64, entry.scales_offset);
put_u64(
record,
72,
(entry.n_padded / u64::from(group))
.checked_mul(2)
.ok_or("KAR scales overflow")?,
);
put_u64(record, 80, entry.books_offset);
put_u64(record, 88, (1u64 << (u32::from(levels) + 2)) - 4);
put_u64(record, 96, entry.planes_offset);
put_u32(record, 104, entry.plane_stride);
}
put_u64(record, 48, entry.n_elements);
put_u64(record, 56, entry.n_padded);
put_u32(record, 108, entry.payload_crc32);
put_u64(record, 112, entry.section_offset);
put_u64(record, 120, entry.section_bytes);
record[128..160].copy_from_slice(&tensor.source_digest);
put_u64(record, 160, tensor.source_offset);
Ok(())
}
pub(super) fn put_u16(bytes: &mut [u8], offset: usize, value: u16) {
bytes[offset..offset + 2].copy_from_slice(&value.to_le_bytes());
}
pub(super) fn put_u32(bytes: &mut [u8], offset: usize, value: u32) {
bytes[offset..offset + 4].copy_from_slice(&value.to_le_bytes());
}
pub(super) fn put_u64(bytes: &mut [u8], offset: usize, value: u64) {
bytes[offset..offset + 8].copy_from_slice(&value.to_le_bytes());
}
@@ -0,0 +1,251 @@
//! Moved out of the parent module by STRA-338: fn write_section, fn validate_nested_file, fn check_file_region, fn write_bytes, fn pad_to.
#[allow(unused_imports)]
use super::*;
pub(super) fn write_section(file: &mut File, entry: &Placed<'_>) -> Result<u32, String> {
file.seek(SeekFrom::Start(entry.section_offset))
.map_err(|error| error.to_string())?;
let mut crc = !0u32;
let mut written = 0u64;
match &entry.tensor.data {
TensorData::Raw(raw) => write_bytes(file, raw, &mut crc, &mut written)?,
TensorData::RawFile {
path,
offset,
bytes,
} => {
let mut source = File::open(path).map_err(|error| error.to_string())?;
let source_len = source.metadata().map_err(|error| error.to_string())?.len();
if offset
.checked_add(*bytes)
.is_none_or(|end| end > source_len)
{
return Err("KAR RAW source file is truncated".into());
}
source
.seek(SeekFrom::Start(*offset))
.map_err(|error| error.to_string())?;
let mut remaining = *bytes;
let mut buffer = vec![0u8; 1024 * 1024];
let mut digest = Sha256::new();
while remaining > 0 {
let count = remaining.min(buffer.len() as u64) as usize;
source
.read_exact(&mut buffer[..count])
.map_err(|error| error.to_string())?;
digest.update(&buffer[..count]);
write_bytes(file, &buffer[..count], &mut crc, &mut written)?;
remaining -= count as u64;
}
if digest.finalize().as_slice() != entry.tensor.source_digest {
return Err(format!("{}: RAW source digest mismatch", entry.tensor.name));
}
}
TensorData::NestedFile {
group,
levels,
path,
offset,
bytes,
digest,
..
} => {
let mut source = File::open(path).map_err(|error| error.to_string())?;
let source_len = source.metadata().map_err(|error| error.to_string())?.len();
if offset
.checked_add(*bytes)
.is_none_or(|end| end > source_len)
{
return Err("KAR nested source file is truncated".into());
}
validate_nested_file(&mut source, entry, *offset, *group, *levels)?;
source
.seek(SeekFrom::Start(*offset))
.map_err(|error| error.to_string())?;
let mut remaining = *bytes;
let mut buffer = vec![0u8; 1024 * 1024];
let mut actual_digest = Sha256::new();
while remaining > 0 {
let count = remaining.min(buffer.len() as u64) as usize;
source
.read_exact(&mut buffer[..count])
.map_err(|error| error.to_string())?;
actual_digest.update(&buffer[..count]);
write_bytes(file, &buffer[..count], &mut crc, &mut written)?;
remaining -= count as u64;
}
if actual_digest.finalize().as_slice() != *digest {
return Err(format!(
"{}: nested section digest mismatch",
entry.tensor.name
));
}
}
TensorData::Nested {
scales,
books,
planes,
..
} => {
for value in *scales {
write_bytes(file, &value.to_le_bytes(), &mut crc, &mut written)?;
}
pad_to(
file,
entry.books_offset - entry.section_offset,
&mut crc,
&mut written,
)?;
for book in *books {
for value in *book {
write_bytes(file, &value.to_le_bytes(), &mut crc, &mut written)?;
}
}
pad_to(
file,
entry.planes_offset - entry.section_offset,
&mut crc,
&mut written,
)?;
for plane in *planes {
let base = written;
for value in *plane {
write_bytes(file, &value.to_le_bytes(), &mut crc, &mut written)?;
}
pad_to(
file,
base + entry.plane_stride as u64,
&mut crc,
&mut written,
)?;
}
}
}
pad_to(file, entry.section_bytes, &mut crc, &mut written)?;
Ok(!crc)
}
pub(super) fn validate_nested_file(
source: &mut File,
entry: &Placed<'_>,
source_offset: u64,
group: u16,
levels: u8,
) -> Result<(), String> {
let scales_bytes = (entry.n_padded / u64::from(group)) * 2;
let books_start = entry.books_offset - entry.section_offset;
let books_bytes = (1u64 << (u32::from(levels) + 2)) - 4;
let planes_start = entry.planes_offset - entry.section_offset;
let plane_bytes = (entry.n_padded / 32) * 4;
let stride = u64::from(entry.plane_stride);
check_file_region(source, source_offset, scales_bytes, RegionRule::FiniteScale)?;
check_file_region(
source,
source_offset + scales_bytes,
books_start - scales_bytes,
RegionRule::ZeroPadding,
)?;
check_file_region(
source,
source_offset + books_start,
books_bytes,
RegionRule::FiniteBook,
)?;
check_file_region(
source,
source_offset + books_start + books_bytes,
planes_start - books_start - books_bytes,
RegionRule::ZeroPadding,
)?;
for level in 0..u64::from(levels) {
check_file_region(
source,
source_offset + planes_start + level * stride + plane_bytes,
stride - plane_bytes,
RegionRule::ZeroPadding,
)?;
}
let used_end = planes_start + u64::from(levels) * stride;
check_file_region(
source,
source_offset + used_end,
entry.section_bytes - used_end,
RegionRule::ZeroPadding,
)?;
Ok(())
}
pub(super) fn check_file_region(
source: &mut File,
offset: u64,
bytes: u64,
rule: RegionRule,
) -> Result<(), String> {
source
.seek(SeekFrom::Start(offset))
.map_err(|error| error.to_string())?;
let mut remaining = bytes;
let mut buffer = [0u8; 64 * 1024];
while remaining > 0 {
let count = remaining.min(buffer.len() as u64) as usize;
source
.read_exact(&mut buffer[..count])
.map_err(|error| error.to_string())?;
match rule {
RegionRule::FiniteScale | RegionRule::FiniteBook => {
if buffer[..count]
.as_chunks::<2>()
.0
.iter()
.any(|pair| u16::from_le_bytes(*pair) & 0x7c00 == 0x7c00)
{
let name = if matches!(rule, RegionRule::FiniteScale) {
"scale"
} else {
"codebook"
};
return Err(format!("non-finite f16 {name} in nested file"));
}
}
RegionRule::ZeroPadding => {
if buffer[..count].iter().any(|byte| *byte != 0) {
return Err("nonzero padding in nested file".into());
}
}
}
remaining -= count as u64;
}
Ok(())
}
pub(super) fn write_bytes(
file: &mut File,
bytes: &[u8],
crc: &mut u32,
written: &mut u64,
) -> Result<(), String> {
file.write_all(bytes).map_err(|error| error.to_string())?;
*crc = kar::crc32_step(*crc, bytes);
*written = written
.checked_add(bytes.len() as u64)
.ok_or("KAR section write overflow")?;
Ok(())
}
pub(super) fn pad_to(
file: &mut File,
target: u64,
crc: &mut u32,
written: &mut u64,
) -> Result<(), String> {
if *written > target {
return Err("KAR section exceeds planned layout".into());
}
let zeros = [0u8; 4096];
while *written < target {
let count = (target - *written).min(zeros.len() as u64) as usize;
write_bytes(file, &zeros[..count], crc, written)?;
}
Ok(())
}
+3 -3
View File
@@ -70,9 +70,9 @@ pub mod prefix_view;
pub mod preflight;
pub mod prepare_preview;
pub mod prometheus;
pub mod prompt;
pub use leleka_gateway_text::prompt;
pub mod request_monitor;
mod response_tools;
use leleka_gateway_text::response_tools;
pub mod responses;
pub mod runtime_config;
pub mod service_install;
@@ -81,7 +81,7 @@ pub mod stream_parts;
pub mod tensor_export;
pub use leleka_tokenizer as tokenizer;
pub mod tokenizer_assets;
pub mod tool_output;
pub use leleka_gateway_text::tool_output;
pub mod wire;
pub mod worker;
+28 -1377
View File
File diff suppressed because it is too large Load Diff
+139
View File
@@ -0,0 +1,139 @@
//! Moved out of the parent module by STRA-338: fn check_server, fn servers_from, fn settings_from.
#[allow(unused_imports)]
use super::*;
pub(super) fn check_server(
name: &str,
config: &Value,
location: &str,
) -> Result<Map<String, Value>, String> {
let Some(object) = config.as_object() else {
return Err(format!(
"[strata] {location}: MCP server {} must be an object with \"command\" or \"url\"",
leleka_serving_policy::shared::py_str_repr(name)
));
};
let quoted = leleka_serving_policy::shared::py_str_repr(name);
let truthy = |key: &str| object.get(key).is_some_and(|v| !falsy(v));
if truthy("url") {
if object.get("type") == Some(&json!("sse")) {
return Err(format!(
"[strata] {location}: MCP server {quoted} uses the old SSE transport (\"type\": \"sse\"); Strata speaks Streamable HTTP - most servers offer it at /mcp"
));
}
if object
.get("headers")
.is_some_and(|h| !falsy(h) && !h.is_object())
{
return Err(format!(
"[strata] {location}: MCP server {quoted}: \"headers\" must be an object"
));
}
return Ok(object.clone());
}
if object
.get("command")
.and_then(Value::as_str)
.is_none_or(|c| c.trim().is_empty())
{
return Err(format!(
"[strata] {location}: MCP server {quoted} needs \"command\" (a program to start) or \"url\""
));
}
if object
.get("args")
.is_some_and(|a| !falsy(a) && !a.is_array())
{
return Err(format!(
"[strata] {location}: MCP server {quoted}: \"args\" must be a list"
));
}
if object
.get("env")
.is_some_and(|e| !falsy(e) && !e.is_object())
{
return Err(format!(
"[strata] {location}: MCP server {quoted}: \"env\" must be an object"
));
}
Ok(object.clone())
}
/// `{"name": {...}}` with the entries checked; `"disabled": true` leaves one out.
pub fn servers_from(
block: &Value,
location: &str,
) -> Result<BTreeMap<String, Map<String, Value>>, String> {
let mut out = BTreeMap::new();
match block {
Value::Null => {}
Value::Object(map) => {
for (name, config) in map {
if config.get("disabled") == Some(&json!(true)) {
continue;
}
out.insert(name.clone(), check_server(name, config, location)?);
}
}
_ => {
return Err(format!(
"[strata] {location}: the MCP servers must be an object {{\"name\": {{...}}}}"
));
}
}
Ok(out)
}
/// The run config's optional `mcp` block: `timeout_s`, `max_result_chars`, `max_rounds`,
/// `start_timeout_s`.
pub fn settings_from(block: &Value) -> Result<Settings, String> {
let mut settings = Settings::default();
let Some(map) = block.as_object() else {
return Ok(settings);
};
for (key, value) in map {
let number = value.is_number();
let bad = |expected: &str| {
format!(
"[strata] config mcp.{key}={}: {expected}",
leleka_serving_policy::shared::py_repr(value)
)
};
match key.as_str() {
"timeout_s" | "start_timeout_s" => {
let seconds = value
.as_f64()
.filter(|v| number && *v > 0.0 && v.is_finite())
.ok_or_else(|| bad("expected a number of seconds > 0"))?;
if key == "timeout_s" {
settings.timeout_s = seconds;
} else {
settings.start_timeout_s = seconds;
}
}
"max_result_chars" | "max_rounds" => {
let count = value
.as_u64()
.filter(|v| *v >= 1)
.or_else(|| {
value
.as_f64()
.filter(|f| f.fract() == 0.0 && *f >= 1.0)
.map(|f| f as u64)
})
.ok_or_else(|| bad("expected a positive integer"))?;
if key == "max_result_chars" {
settings.max_result_chars = usize::try_from(count).unwrap_or(usize::MAX);
} else {
settings.max_rounds = usize::try_from(count).unwrap_or(usize::MAX);
}
}
other => crate::elog!(
"config mcp.{other}={}: unknown key, ignored",
leleka_serving_policy::shared::py_repr(value)
),
}
}
Ok(settings)
}
+69
View File
@@ -0,0 +1,69 @@
//! Moved out of the parent module by STRA-338: fn dispatch, fn cancelled, fn fmt_g.
#[allow(unused_imports)]
use super::*;
/// A message from the server: answers go to the waiting call; its own requests get `ping` answered
/// and anything else "method not supported" (this client offers no client features); notifications
/// (log messages, list changes) are not used.
pub(super) async fn dispatch(
message: &Value,
pending: &Arc<Mutex<HashMap<u64, Slot>>>,
writer: &Arc<AsyncMutex<Option<ChildStdin>>>,
) {
if let Some(method) = message.get("method") {
if let Some(id) = message.get("id") {
let reply = if method == "ping" {
json!({"jsonrpc": "2.0", "id": id, "result": {}})
} else {
json!({"jsonrpc": "2.0", "id": id, "error": {"code": -32601,
"message": format!("method not supported: {}", method.as_str().unwrap_or(""))}})
};
// Written from its own task: the reader must never wait on a full pipe.
let writer = writer.clone();
tokio::spawn(async move {
let mut data = serde_json::to_vec(&reply).expect("json");
data.push(b'\n');
if let Some(pipe) = writer.lock().await.as_mut() {
let _ = pipe.write_all(&data).await;
let _ = pipe.flush().await;
}
});
}
return;
}
let slot = message
.get("id")
.and_then(Value::as_u64)
.and_then(|id| pending.lock().expect("mcp pending").remove(&id));
if let Some(slot) = slot {
let _ = slot.send(Ok(message.clone()));
} // an answer to a call that timed out is simply dropped
}
pub(super) async fn cancelled(cancel: &mut Option<Cancel>) {
match cancel {
Some(receiver) => {
if *receiver.borrow() {
return;
}
while receiver.changed().await.is_ok() {
if *receiver.borrow() {
return;
}
}
std::future::pending::<()>().await;
}
None => std::future::pending::<()>().await,
}
}
/// Python's `f"{x:g}"` for the timeouts in messages.
pub(super) fn fmt_g(x: f64) -> String {
if x.fract() == 0.0 && x.abs() < 1e15 {
format!("{x:.0}")
} else {
let text = format!("{x:.6}");
text.trim_end_matches('0').trim_end_matches('.').to_owned()
}
}
@@ -0,0 +1,57 @@
//! Moved out of the parent module by STRA-338: impl Default_for_Settings, impl std_fmt_Display, fn failed, fn response_result.
#[allow(unused_imports)]
use super::*;
impl Default for Settings {
fn default() -> Self {
Self {
timeout_s: 60.0,
max_result_chars: 20_000,
max_rounds: 8,
start_timeout_s: 120.0,
}
}
}
impl std::fmt::Display for McpError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::Failed(m) | Self::Timeout(m) => f.write_str(m),
Self::Cancelled => f.write_str("stopped"),
}
}
}
pub(super) fn failed(message: impl Into<String>) -> McpError {
McpError::Failed(message.into())
}
/// A response `result`, or the error a JSON-RPC response carried (`_wait` of the Original).
pub(super) fn response_result(message: &Value) -> Result<Value, McpError> {
if let Some(error) = message.get("error") {
let (text, code) = match error {
Value::Object(object) => (
object
.get("message")
.and_then(Value::as_str)
.filter(|t| !t.is_empty())
.unwrap_or("error")
.to_owned(),
object.get("code").cloned().unwrap_or(Value::Null),
),
other => (other.to_string(), Value::Null),
};
let code = if code.is_null() {
"None".to_owned()
} else {
code.to_string()
};
return Err(failed(format!("{text} (code {code})")));
}
Ok(message
.get("result")
.filter(|v| !v.is_null())
.cloned()
.unwrap_or_else(|| json!({})))
}
+233
View File
@@ -0,0 +1,233 @@
//! Moved out of the parent module by STRA-338: impl Http, fn read_events.
#[allow(unused_imports)]
use super::*;
impl Http {
pub(super) fn new(config: &Map<String, Value>) -> Self {
let url = config
.get("url")
.and_then(Value::as_str)
.unwrap_or_default()
.to_owned();
let headers = config
.get("headers")
.and_then(Value::as_object)
.into_iter()
.flatten()
.map(|(k, v)| {
(
k.clone(),
v.as_str().map_or_else(|| v.to_string(), str::to_owned),
)
})
.collect();
Self {
url,
headers,
client: reqwest::Client::new(),
session: Mutex::new(None),
protocol: Mutex::new(None),
next_id: AtomicU64::new(0),
broken: Mutex::new(None),
}
}
pub(super) fn alive(&self) -> bool {
self.broken.lock().expect("mcp http").is_none()
}
pub(super) fn builder(
&self,
method: reqwest::Method,
timeout: Duration,
) -> reqwest::RequestBuilder {
let mut builder = self
.client
.request(method, &self.url)
.timeout(timeout)
.header("Content-Type", "application/json")
.header("Accept", "application/json, text/event-stream")
.header("User-Agent", "strata");
for (key, value) in &self.headers {
builder = builder.header(key.as_str(), value.as_str());
}
if let Some(session) = self.session.lock().expect("mcp http").clone() {
builder = builder.header("Mcp-Session-Id", session);
}
if let Some(protocol) = self.protocol.lock().expect("mcp http").clone() {
builder = builder.header("MCP-Protocol-Version", protocol);
}
builder
}
/// POST one message; for a request (`id` set) return the response that answers it.
pub(super) async fn post(
&self,
message: &Value,
id: Option<u64>,
timeout: Duration,
) -> Result<Option<Value>, McpError> {
let response = self
.builder(reqwest::Method::POST, timeout)
.body(serde_json::to_vec(message).expect("json"))
.send()
.await
.map_err(|error| failed(format!("could not reach {}: {error}", self.url)))?;
if let Some(session) = response
.headers()
.get("Mcp-Session-Id")
.and_then(|v| v.to_str().ok())
{
*self.session.lock().expect("mcp http") = Some(session.to_owned());
}
let status = response.status();
if !status.is_success() {
let had_session = self.session.lock().expect("mcp http").is_some();
let detail: String = response
.text()
.await
.unwrap_or_default()
.chars()
.take(300)
.collect();
if status.as_u16() == 404 && had_session {
// The session expired: a restart starts a new one.
*self.broken.lock().expect("mcp http") =
Some(failed("the server ended the session"));
}
return Err(failed(format!(
"HTTP {} {}{}",
status.as_u16(),
status.canonical_reason().unwrap_or(""),
if detail.is_empty() {
String::new()
} else {
format!(": {detail}")
}
)));
}
let Some(id) = id else { return Ok(None) }; // a notification: 202, nothing to read
let is_events = response
.headers()
.get("content-type")
.and_then(|v| v.to_str().ok())
.is_some_and(|t| t.contains("text/event-stream"));
let found = if is_events {
read_events(response, id).await
} else {
let body = response
.text()
.await
.map_err(|error| failed(format!("could not reach {}: {error}", self.url)))?;
if body.trim().is_empty() {
None
} else {
let parsed: Value = serde_json::from_str(&body)
.map_err(|error| failed(format!("could not reach {}: {error}", self.url)))?;
match parsed {
Value::Array(items) => items,
other => vec![other],
}
.into_iter()
.find(|m| {
m.get("id").and_then(Value::as_u64) == Some(id) && m.get("method").is_none()
})
}
};
found
.map(Some)
.ok_or_else(|| failed("the server's answer did not contain a response"))
}
pub(super) async fn request(
&self,
method: &str,
params: Value,
timeout: Duration,
mut cancel: Option<Cancel>,
) -> Result<Value, McpError> {
if let Some(error) = self.broken.lock().expect("mcp http").clone() {
return Err(error);
}
let id = self.next_id.fetch_add(1, Ordering::SeqCst) + 1;
let message = json!({"jsonrpc": "2.0", "id": id, "method": method, "params": params});
let outcome = tokio::select! {
answer = self.post(&message, Some(id), timeout + Duration::from_secs(5)) => {
return match answer {
Ok(Some(message)) => response_result(&message),
Ok(None) => Err(failed("the server's answer did not contain a response")),
Err(error) => Err(error),
};
}
() = tokio::time::sleep(timeout) => McpError::Timeout(format!("{method} timed out after {} s", fmt_g(timeout.as_secs_f64()))),
() = cancelled(&mut cancel) => McpError::Cancelled,
};
let _ = self
.notify(
"notifications/cancelled",
Some(json!({"requestId": id, "reason": outcome.to_string()})),
)
.await;
Err(outcome)
}
pub(super) async fn notify(&self, method: &str, params: Option<Value>) -> Result<(), McpError> {
let mut message = json!({"jsonrpc": "2.0", "method": method});
if let Some(params) = params {
message["params"] = params;
}
self.post(&message, None, Duration::from_secs(10))
.await
.map(|_| ())
}
pub(super) async fn close(&self) {
let Some(_) = self.session.lock().expect("mcp http").clone() else {
return;
};
// End the session on the server (it may not allow that).
let _ = self
.builder(reqwest::Method::DELETE, Duration::from_secs(3))
.send()
.await;
}
}
/// Read an event stream until the event that answers `id` (it may carry notifications first).
pub(super) async fn read_events(mut response: reqwest::Response, id: u64) -> Option<Value> {
let mut buffer = Vec::<u8>::new();
let mut data: Vec<String> = Vec::new();
loop {
let chunk = response.chunk().await.ok().flatten();
let finished = chunk.is_none();
if let Some(chunk) = chunk {
buffer.extend_from_slice(&chunk);
}
while let Some(newline) = buffer.iter().position(|b| *b == b'\n') {
let raw: Vec<u8> = buffer.drain(..=newline).collect();
let line = String::from_utf8_lossy(&raw)
.trim_end_matches(['\r', '\n'])
.to_owned();
if let Some(rest) = line.strip_prefix("data:") {
data.push(rest.trim_start_matches(' ').to_owned());
} else if line.is_empty() && !data.is_empty() {
let parsed = serde_json::from_str::<Value>(&data.join("\n")).ok();
data.clear();
let batch = match parsed {
Some(Value::Array(items)) => items,
Some(other) => vec![other],
None => Vec::new(),
};
if let Some(found) = batch.into_iter().find(|m| {
m.get("id").and_then(Value::as_u64) == Some(id) && m.get("method").is_none()
}) {
return Some(found);
}
}
}
if finished {
return None;
}
}
}
+208
View File
@@ -0,0 +1,208 @@
//! Moved out of the parent module by STRA-338: impl Hub, fn falsy.
#[allow(unused_imports)]
use super::*;
impl Hub {
pub fn new(servers: BTreeMap<String, Map<String, Value>>, settings: Settings) -> Self {
Self {
servers: servers
.into_iter()
.map(|(name, config)| Arc::new(Server::new(name, config, settings.clone())))
.collect(),
settings,
}
}
/// Start every server concurrently and wait for all of them (npx may download a package first;
/// callers that must not wait spawn this).
pub async fn start(&self) {
let mut tasks = tokio::task::JoinSet::new();
for server in &self.servers {
let server = server.clone();
tasks.spawn(async move { server.start().await });
}
while tasks.join_next().await.is_some() {}
}
/// tool name the model sees -> (server, the tool's own name). A server that stopped after it
/// was ready keeps its tools here: a call starts it again.
pub async fn routes(&self) -> Vec<(String, Arc<Server>, String)> {
let mut out: Vec<(String, Arc<Server>, String)> = Vec::new();
for server in &self.servers {
let state = server.state.lock().await;
if !matches!(state.status, Status::Ready | Status::Stopped) {
continue;
}
for tool in &state.tools {
let own = tool["name"].as_str().unwrap_or_default().to_owned();
let mut name: String = format!("{}__{}", clean(&server.name), clean(&own))
.chars()
.take(64)
.collect();
let mut n = 2;
while out.iter().any(|(existing, _, _)| *existing == name) {
// two names that differ only in cleaned characters
name = format!("{}_{n}", name.chars().take(60).collect::<String>());
n += 1;
}
out.push((name, server.clone(), own));
}
}
out
}
/// The tools in the chat template's form (`{name, description, parameters}`); `exclude`: names
/// the request brought itself (those win).
pub async fn template_tools(&self, exclude: &[String]) -> Vec<Value> {
let mut out = Vec::new();
for (name, server, own) in self.routes().await {
if exclude.contains(&name) {
continue;
}
let state = server.state.lock().await;
let Some(tool) = state.tools.iter().find(|t| t["name"] == own.as_str()) else {
continue;
};
let schema = tool
.get("inputSchema")
.filter(|s| s.as_object().is_some_and(|o| !o.is_empty()))
.cloned()
.unwrap_or_else(|| json!({"type": "object", "properties": {}}));
let description = [tool.get("description"), tool.get("title")]
.into_iter()
.flatten()
.filter_map(Value::as_str)
.find(|s| !s.is_empty())
.unwrap_or("");
out.push(json!({"name": name, "description": description, "parameters": schema}));
}
out
}
/// Run one tool. Errors become text starting with `error:`; only a stop (`cancel`) is an `Err`.
pub async fn call(
&self,
name: &str,
arguments: Value,
cancel: Option<Cancel>,
) -> Result<CallOutput, McpError> {
let started = Instant::now();
let route = self.routes().await.into_iter().find(|(n, _, _)| n == name);
let (server, tool) = match &route {
Some((_, server, tool)) => (Some(server.clone()), tool.clone()),
None => (None, name.to_owned()),
};
let (mut text, ok) = match &server {
None => (format!("error: there is no tool named {name:?}"), false),
Some(server) => {
let arguments = if arguments.is_object() {
arguments
} else {
json!({})
};
match server
.call(
&tool,
arguments,
Duration::from_secs_f64(self.settings.timeout_s),
cancel,
)
.await
{
Ok(result) => {
let text = result_text(&result);
let ok = !result.get("isError").is_some_and(|v| v == &json!(true));
if ok {
(text, true)
} else {
(
format!(
"error: {}",
if text.is_empty() {
"the tool reported an error".to_owned()
} else {
text
}
),
false,
)
}
}
Err(McpError::Cancelled) => return Err(McpError::Cancelled),
Err(error) => (format!("error: {error}"), false),
}
}
};
let cap = self.settings.max_result_chars;
let full = text.chars().count();
let truncated = cap > 0 && full > cap;
if truncated {
text = text.chars().take(cap).collect::<String>()
+ &format!(
"\n\n[... truncated: the tool returned {} characters; only the first {} are shown]",
group_thousands(full),
group_thousands(cap)
);
}
Ok(CallOutput {
ok,
text,
chars: full,
truncated,
ms: u64::try_from(started.elapsed().as_millis()).unwrap_or(u64::MAX),
server: server.as_ref().map(|s| s.name.clone()),
tool,
})
}
/// `GET /mcp`: every server, its state and its tools.
pub async fn status(&self) -> Value {
let routes = self.routes().await;
let mut servers = Vec::new();
for server in &self.servers {
let state = server.state.lock().await;
let tools: Vec<Value> = state
.tools
.iter()
.map(|tool| {
let own = tool["name"].as_str().unwrap_or_default();
let seen = routes
.iter()
.find(|(_, s, t)| Arc::ptr_eq(s, server) && t == own)
.map_or(own, |(n, _, _)| n.as_str());
json!({"name": seen, "tool": own,
"description": tool.get("description").and_then(Value::as_str).unwrap_or("")
.chars().take(300).collect::<String>()})
})
.collect();
servers.push(json!({"name": server.name, "transport": server.kind,
"status": state.status.as_str(), "error": state.error, "info": state.info,
"tools": tools}));
}
json!({"servers": servers, "tools": routes.len(),
"settings": {"timeout_s": self.settings.timeout_s,
"max_result_chars": self.settings.max_result_chars,
"max_rounds": self.settings.max_rounds}})
}
pub async fn close(&self) {
for server in &self.servers {
server.close().await;
}
}
}
// ------------------------------------------------------------------------------------------------ config
/// Python truthiness of a JSON value (`None`, `""`, `0`, `False`, `[]`, `{}`).
pub(super) fn falsy(value: &Value) -> bool {
match value {
Value::Null => true,
Value::Bool(b) => !b,
Value::Number(n) => n.as_f64() == Some(0.0),
Value::String(s) => s.is_empty(),
Value::Array(a) => a.is_empty(),
Value::Object(o) => o.is_empty(),
}
}
+219
View File
@@ -0,0 +1,219 @@
//! Moved out of the parent module by STRA-338: impl Server.
#[allow(unused_imports)]
use super::*;
impl Server {
pub(super) fn new(name: String, config: Map<String, Value>, settings: Settings) -> Self {
let kind = if config
.get("url")
.is_some_and(|u| u.as_str().is_some_and(|s| !s.is_empty()))
{
"http"
} else {
"stdio"
};
Self {
name,
config,
kind,
settings,
state: AsyncMutex::new(State {
status: Status::Idle,
error: None,
tools: Vec::new(),
info: Map::new(),
transport: None,
last_start: None,
}),
}
}
pub async fn start(&self) -> bool {
let mut state = self.state.lock().await;
self.start_locked(&mut state).await
}
pub(super) async fn start_locked(&self, state: &mut State) -> bool {
if let Some(old) = state.transport.take() {
old.close().await;
}
state.status = Status::Starting;
state.error = None;
state.last_start = Some(Instant::now());
let timeout = Duration::from_secs_f64(self.settings.start_timeout_s);
let transport = if self.kind == "http" {
Ok(Transport::Http(Http::new(&self.config)))
} else {
StdioTransport::spawn(&self.name, &self.config)
.await
.map(Transport::Stdio)
};
let result: StartResult = async {
let transport = Arc::new(transport.map_err(|e| (e, None))?);
let t = transport.clone();
let fail = |e: McpError| (e, Some(t.clone()));
let init = transport
.request(
"initialize",
json!({"protocolVersion": PROTOCOL, "capabilities": {},
"clientInfo": {"name": "strata", "title": "Strata", "version": "1"}}),
timeout,
None,
)
.await
.map_err(fail)?;
let protocol = init
.get("protocolVersion")
.and_then(Value::as_str)
.filter(|p| !p.is_empty())
.unwrap_or(PROTOCOL)
.to_owned();
if let Transport::Http(http) = &*transport {
*http.protocol.lock().expect("mcp http") = Some(protocol.clone());
}
let mut info: Map<String, Value> = init
.get("serverInfo")
.and_then(Value::as_object)
.map(|o| {
o.iter()
.filter(|(k, _)| matches!(k.as_str(), "name" | "title" | "version"))
.map(|(k, v)| (k.clone(), v.clone()))
.collect()
})
.unwrap_or_default();
info.insert("protocol".into(), json!(protocol));
transport.notify("notifications/initialized").await.map_err(fail)?;
let mut tools: Vec<Value> = Vec::new();
let mut cursor: Option<String> = None;
for _ in 0..100 {
// pages; a server that never stops paging is cut off
let params = cursor.as_ref().map_or_else(|| json!({}), |c| json!({"cursor": c}));
let page = match transport.request("tools/list", params, timeout, None).await {
Ok(page) => page,
// a server without tools (prompts/resources only)
Err(e) if e.to_string().contains("code -32601") && tools.is_empty() => break,
Err(e) => return Err(fail(e)),
};
tools.extend(
page.get("tools")
.and_then(Value::as_array)
.into_iter()
.flatten()
.filter(|t| t.get("name").and_then(Value::as_str).is_some_and(|n| !n.is_empty()))
.cloned(),
);
cursor = page
.get("nextCursor")
.and_then(Value::as_str)
.filter(|c| !c.is_empty())
.map(str::to_owned);
if cursor.is_none() {
break;
}
}
Ok((transport, tools, info))
}
.await;
match result {
Ok((transport, tools, info)) => {
let names = tools
.iter()
.take(8)
.filter_map(|t| t["name"].as_str())
.collect::<Vec<_>>()
.join(", ")
+ if tools.len() > 8 { ", ..." } else { "" };
crate::elog!(
"MCP server {:?}: {} tool{}{}",
self.name,
tools.len(),
if tools.len() == 1 { "" } else { "s" },
if tools.is_empty() {
String::new()
} else {
format!(" ({names})")
}
);
state.tools = tools;
state.info = info;
state.transport = Some(transport);
state.status = Status::Ready;
true
}
Err((error, transport)) => {
state.status = Status::Failed;
state.error = Some(error.to_string());
state.tools = Vec::new();
if let Some(transport) = transport {
transport.close().await;
}
crate::elog!(
"MCP server {:?} did not start: {error}. Its tools are left out; the chat works without them.",
self.name
);
false
}
}
}
pub async fn call(
&self,
tool: &str,
arguments: Value,
timeout: Duration,
cancel: Option<Cancel>,
) -> Result<Value, McpError> {
let transport = {
let mut state = self.state.lock().await;
if state.transport.as_ref().is_none_or(|t| !t.alive()) {
// It stopped since its last call (a crash, an expired session): start it again; one
// that failed to start is retried at most every 10 s.
if state.status == Status::Failed
&& state
.last_start
.is_some_and(|at| at.elapsed() < Duration::from_secs(10))
{
return Err(failed(format!(
"the server is not running ({})",
state.error.clone().unwrap_or_else(|| "it stopped".into())
)));
}
crate::elog!("MCP server {:?} had stopped; starting it again", self.name);
if !self.start_locked(&mut state).await {
return Err(failed(format!(
"the server could not be started again: {}",
state.error.clone().unwrap_or_default()
)));
}
}
state.transport.clone().expect("started")
};
let result = transport
.request(
"tools/call",
json!({"name": tool, "arguments": arguments}),
timeout,
cancel,
)
.await;
if let Err(error) = &result
&& !transport.alive()
{
let mut state = self.state.lock().await;
state.status = Status::Stopped;
state.error = Some(error.to_string());
}
result
}
pub async fn close(&self) {
let mut state = self.state.lock().await;
if let Some(transport) = state.transport.take() {
transport.close().await;
}
if matches!(state.status, Status::Ready | Status::Starting) {
state.status = Status::Stopped;
}
}
}
@@ -0,0 +1,245 @@
//! Moved out of the parent module by STRA-338: impl StdioTransport.
#[allow(unused_imports)]
use super::*;
impl StdioTransport {
pub(super) async fn spawn(name: &str, config: &Map<String, Value>) -> Result<Self, McpError> {
let command = config
.get("command")
.and_then(Value::as_str)
.unwrap_or_default()
.to_owned();
let mut process = Command::new(&command);
process
.args(
config
.get("args")
.and_then(Value::as_array)
.into_iter()
.flatten()
.map(|a| a.as_str().map_or_else(|| a.to_string(), str::to_owned)),
)
.stdin(Stdio::piped())
.stdout(Stdio::piped())
.stderr(Stdio::piped())
.kill_on_drop(true);
for (key, value) in config
.get("env")
.and_then(Value::as_object)
.into_iter()
.flatten()
{
process.env(
key,
value
.as_str()
.map_or_else(|| value.to_string(), str::to_owned),
);
}
if let Some(dir) = config
.get("cwd")
.and_then(Value::as_str)
.filter(|d| !d.is_empty())
{
process.current_dir(dir);
}
#[cfg(unix)]
process.process_group(0); // its own group, so closing it ends its children too
let mut child = process
.spawn()
.map_err(|error| failed(format!("could not start {command:?}: {error}")))?;
let stdin = child.stdin.take();
let stdout = child.stdout.take().expect("piped stdout");
let stderr = child.stderr.take().expect("piped stderr");
let pid = child.id();
let pending: Arc<Mutex<HashMap<u64, Slot>>> = Arc::default();
let log: Arc<Mutex<VecDeque<String>>> = Arc::default();
let ended = Arc::new(std::sync::atomic::AtomicBool::new(false));
// The server's stderr is its log; the last lines explain a failure.
let (done_tx, done_rx) = oneshot::channel::<()>();
{
let log = log.clone();
let label = name.to_owned();
tokio::spawn(async move {
let mut lines = BufReader::new(stderr).lines();
while let Ok(Some(line)) = lines.next_line().await {
let line = line.trim_end().to_owned();
if line.is_empty() {
continue;
}
if std::env::var_os("STRATA_DEBUG").is_some() {
crate::elog!("[mcp {label}] {line}");
}
let mut log = log.lock().expect("mcp log");
log.push_back(line);
if log.len() > 40 {
log.pop_front();
}
}
let _ = done_tx.send(());
});
}
let stdin = Arc::new(AsyncMutex::new(stdin));
let transport = Self {
name: name.to_owned(),
stdin: stdin.clone(),
child: AsyncMutex::new(Some(child)),
pid,
pending: pending.clone(),
next_id: AtomicU64::new(0),
stderr: log.clone(),
ended: ended.clone(),
};
// Reader: one JSON-RPC message per line; requests from the server get "not supported".
let writer = stdin;
tokio::spawn(async move {
let mut lines = BufReader::new(stdout).lines();
while let Ok(Some(line)) = lines.next_line().await {
let line = line.trim();
if line.is_empty() {
continue;
}
let Ok(message) = serde_json::from_str::<Value>(line) else {
let mut log = log.lock().expect("mcp log");
log.push_back(line.to_owned()); // a server that prints to stdout; the spec forbids it
continue;
};
let batch = match message {
Value::Array(items) => items,
other => vec![other],
};
for m in batch.into_iter().filter(Value::is_object) {
dispatch(&m, &pending, &writer).await;
}
}
ended.store(true, Ordering::SeqCst);
// Let the stderr reader take the last log line first (the pipe closes with the process).
let _ = tokio::time::timeout(Duration::from_secs(1), done_rx).await;
let tail = log
.lock()
.expect("mcp log")
.back()
.map(|l| format!(": {}", l.chars().take(300).collect::<String>()))
.unwrap_or_default();
let error = failed(format!("the server stopped{tail}"));
let slots: Vec<Slot> = pending
.lock()
.expect("mcp pending")
.drain()
.map(|(_, s)| s)
.collect();
for slot in slots {
let _ = slot.send(Err(error.clone()));
}
});
Ok(transport)
}
pub(super) fn tail(&self) -> String {
self.stderr
.lock()
.expect("mcp log")
.back()
.map(|l| format!(": {}", l.chars().take(300).collect::<String>()))
.unwrap_or_default()
}
pub(super) fn alive(&self) -> bool {
!self.ended.load(Ordering::SeqCst)
}
pub(super) async fn send(&self, message: &Value) -> Result<(), McpError> {
let mut data = serde_json::to_vec(message).expect("json");
data.push(b'\n');
let mut stdin = self.stdin.lock().await;
let Some(pipe) = stdin.as_mut() else {
return Err(failed(format!("the server stopped{}", self.tail())));
};
if pipe.write_all(&data).await.is_err() || pipe.flush().await.is_err() {
return Err(failed(format!("the server stopped{}", self.tail())));
}
Ok(())
}
pub(super) async fn request(
&self,
method: &str,
params: Value,
timeout: Duration,
mut cancel: Option<Cancel>,
) -> Result<Value, McpError> {
if !self.alive() {
return Err(failed(format!("the server is not running{}", self.tail())));
}
let id = self.next_id.fetch_add(1, Ordering::SeqCst) + 1;
let (slot, received) = oneshot::channel();
self.pending.lock().expect("mcp pending").insert(id, slot);
if let Err(error) = self
.send(&json!({"jsonrpc": "2.0", "id": id, "method": method, "params": params}))
.await
{
self.pending.lock().expect("mcp pending").remove(&id);
return Err(error);
}
let outcome = tokio::select! {
answer = received => match answer {
Ok(Ok(message)) => return response_result(&message),
Ok(Err(error)) => return Err(error),
Err(_) => return Err(failed(format!("the server stopped{}", self.tail()))),
},
() = tokio::time::sleep(timeout) => McpError::Timeout(format!("{method} timed out after {} s", fmt_g(timeout.as_secs_f64()))),
() = cancelled(&mut cancel) => McpError::Cancelled,
};
self.pending.lock().expect("mcp pending").remove(&id);
// Tell the server to stop working on it.
let _ = self
.notify(
"notifications/cancelled",
Some(json!({"requestId": id, "reason": outcome.to_string()})),
)
.await;
Err(outcome)
}
pub(super) async fn notify(&self, method: &str, params: Option<Value>) -> Result<(), McpError> {
let mut message = json!({"jsonrpc": "2.0", "method": method});
if let Some(params) = params {
message["params"] = params;
}
self.send(&message).await
}
/// As the spec says: close its stdin, give it a moment to exit, then end it and what it started.
pub(super) async fn close(&self) {
self.stdin.lock().await.take();
let child = self.child.lock().await.take();
let Some(mut child) = child else { return };
if tokio::time::timeout(Duration::from_secs(2), child.wait())
.await
.is_err()
{
if let Some(pid) = self.pid {
let _ = Command::new("kill")
.args(["-TERM", &format!("-{pid}")])
.stderr(Stdio::null())
.status()
.await;
if tokio::time::timeout(Duration::from_secs(2), child.wait())
.await
.is_err()
{
let _ = Command::new("kill")
.args(["-KILL", &format!("-{pid}")])
.stderr(Stdio::null())
.status()
.await;
}
}
let _ = child.start_kill();
let _ = child.wait().await;
}
let _ = &self.name;
}
}
+52
View File
@@ -0,0 +1,52 @@
//! Moved out of the parent module by STRA-338: impl Transport, impl Status.
#[allow(unused_imports)]
use super::*;
impl Transport {
pub(super) fn alive(&self) -> bool {
match self {
Self::Stdio(t) => t.alive(),
Self::Http(t) => t.alive(),
}
}
pub(super) async fn request(
&self,
method: &str,
params: Value,
timeout: Duration,
cancel: Option<Cancel>,
) -> Result<Value, McpError> {
match self {
Self::Stdio(t) => t.request(method, params, timeout, cancel).await,
Self::Http(t) => t.request(method, params, timeout, cancel).await,
}
}
pub(super) async fn notify(&self, method: &str) -> Result<(), McpError> {
match self {
Self::Stdio(t) => t.notify(method, None).await,
Self::Http(t) => t.notify(method, None).await,
}
}
pub(super) async fn close(&self) {
match self {
Self::Stdio(t) => t.close().await,
Self::Http(t) => t.close().await,
}
}
}
impl Status {
pub(super) fn as_str(&self) -> &'static str {
match self {
Self::Idle => "idle",
Self::Starting => "starting",
Self::Ready => "ready",
Self::Failed => "failed",
Self::Stopped => "stopped",
}
}
}
+102
View File
@@ -0,0 +1,102 @@
//! Moved out of the parent module by STRA-338: fn result_text, fn group_thousands, fn clean.
#[allow(unused_imports)]
use super::*;
// ------------------------------------------------------------------------------------------------ the hub
/// `result_text`: an MCP tool result as the text the model reads - text blocks as they are, other
/// blocks named.
pub fn result_text(result: &Value) -> String {
let mut parts: Vec<String> = Vec::new();
for block in result
.get("content")
.and_then(Value::as_array)
.into_iter()
.flatten()
{
let Some(block) = block.as_object() else {
continue;
};
let text = |key: &str| {
block
.get(key)
.map(|v| v.as_str().map_or_else(|| v.to_string(), str::to_owned))
.unwrap_or_default()
};
match block.get("type").and_then(Value::as_str) {
Some("text") => parts.push(text("text")),
Some("resource") => {
let resource = block.get("resource").and_then(Value::as_object);
parts.push(match resource.and_then(|r| r.get("text")) {
Some(v) => v.as_str().map_or_else(|| v.to_string(), str::to_owned),
None => format!(
"[resource {} ({}), not shown]",
resource
.and_then(|r| r.get("uri"))
.and_then(Value::as_str)
.unwrap_or(""),
resource
.and_then(|r| r.get("mimeType"))
.and_then(Value::as_str)
.unwrap_or("binary")
),
});
}
Some("resource_link") => parts.push(
format!("[resource link: {} {}]", text("name"), text("uri")).replace(" ", " "),
),
Some(kind @ ("image" | "audio")) => {
let size = block
.get("data")
.and_then(Value::as_str)
.map_or(0, str::len)
* 3
/ 4;
parts.push(format!(
"[{kind} ({}, {} bytes): not shown to the model]",
block.get("mimeType").and_then(Value::as_str).unwrap_or("?"),
group_thousands(size)
));
}
_ => parts.push(Value::Object(block.clone()).to_string()),
}
}
if parts.is_empty()
&& let Some(structured) = result.get("structuredContent").filter(|v| !v.is_null())
{
parts.push(structured.to_string());
}
parts.join("\n")
}
/// Python's `f"{n:,}"`.
pub(super) fn group_thousands(n: usize) -> String {
let digits = n.to_string();
let mut out = String::new();
for (i, c) in digits.chars().enumerate() {
if i > 0 && (digits.len() - i).is_multiple_of(3) {
out.push(',');
}
out.push(c);
}
out
}
pub(super) fn clean(name: &str) -> String {
let cleaned: String = name
.chars()
.map(|c| {
if c.is_ascii_alphanumeric() || c == '_' || c == '-' {
c
} else {
'_'
}
})
.collect();
if cleaned.is_empty() {
"x".into()
} else {
cleaned
}
}
+98
View File
@@ -0,0 +1,98 @@
//! Unit tests of this module (moved out of the file by STRA-338; the test ids are unchanged).
use super::*;
#[test]
fn results_read_as_text_with_other_blocks_named() {
// An unknown block prints as written (Python's `json.dumps(block)` in the Original keeps the server's key order; the
// separators differ, see json_order.rs). That needs serde_json's `preserve_order`, declared in control-plane/Cargo.toml.
let result = json!({"content": [
{"type": "text", "text": "hello"},
{"type": "resource", "resource": {"uri": "file:///a", "mimeType": "image/png"}},
{"type": "resource", "resource": {"text": "inline"}},
{"type": "resource_link", "name": "doc", "uri": "http://x"},
{"type": "image", "mimeType": "image/png", "data": "AAAAAAAA"},
{"type": "weird", "k": 1},
"not a block"
]});
assert_eq!(
result_text(&result),
"hello\n[resource file:///a (image/png), not shown]\ninline\n[resource link: doc http://x]\n[image (image/png, 6 bytes): not shown to the model]\n{\"type\":\"weird\",\"k\":1}"
);
assert_eq!(
result_text(&json!({"structuredContent": {"a": 1}})),
"{\"a\":1}"
);
assert_eq!(result_text(&json!({})), "");
assert_eq!(group_thousands(1234567), "1,234,567");
assert_eq!(group_thousands(12), "12");
}
#[test]
fn json_rpc_errors_read_like_the_originals() {
assert_eq!(
response_result(&json!({"error": {"code": -32602, "message": "unknown tool x"}}))
.unwrap_err(),
failed("unknown tool x (code -32602)")
);
assert_eq!(
response_result(&json!({"error": "plain"})).unwrap_err(),
failed("\"plain\" (code None)")
);
assert_eq!(response_result(&json!({"id": 1})).unwrap(), json!({}));
}
#[test]
fn server_entries_are_checked_at_start() {
let ok = servers_from(
&json!({"a": {"command": "npx", "args": ["x"]}, "b": {"url": "http://h/mcp", "headers": {"k": "v"}},
"off": {"command": "x", "disabled": true}}),
"config mcp_servers",
)
.unwrap();
assert_eq!(ok.keys().collect::<Vec<_>>(), vec!["a", "b"]);
for bad in [
json!({"a": "nope"}),
json!({"a": {}}),
json!({"a": {"command": " "}}),
json!({"a": {"command": "x", "args": "y"}}),
json!({"a": {"command": "x", "env": ["x"]}}),
json!({"a": {"url": "http://h", "type": "sse"}}),
json!({"a": {"url": "http://h", "headers": ["x"]}}),
json!([1]),
] {
assert!(servers_from(&bad, "w").is_err(), "{bad}");
}
assert!(servers_from(&Value::Null, "w").unwrap().is_empty());
}
#[test]
fn settings_block_is_checked() {
let s = settings_from(&json!({"timeout_s": 5, "max_result_chars": 100, "max_rounds": 3, "start_timeout_s": 7.5, "x": 1})).unwrap();
assert_eq!(
s,
Settings {
timeout_s: 5.0,
max_result_chars: 100,
max_rounds: 3,
start_timeout_s: 7.5
}
);
for bad in [
json!({"timeout_s": 0}),
json!({"timeout_s": "5"}),
json!({"max_rounds": 0}),
json!({"max_result_chars": 1.5}),
] {
assert!(settings_from(&bad).is_err(), "{bad}");
}
assert_eq!(settings_from(&Value::Null).unwrap(), Settings::default());
}
#[test]
fn tool_names_are_cleaned_and_made_unique() {
assert_eq!(clean("my server!"), "my_server_");
assert_eq!(clean(""), "x");
assert_eq!(fmt_g(60.0), "60");
assert_eq!(fmt_g(0.5), "0.5");
}
+10 -586
View File
@@ -50,57 +50,6 @@ struct CountRequest {
tool_choice: Option<Choice>,
thinking: Option<Value>,
}
impl CountRequest {
fn into_responses(self) -> Result<Value, String> {
// Use the serving converter, including its exact tool/history validation.
// This output limit is only for native request validation; no GEN is sent.
Request {
model: self.model,
max_tokens: 1,
messages: self.messages,
system: self.system,
stream: false,
tools: self.tools,
tool_choice: self.tool_choice,
temperature: None,
top_p: None,
thinking: self.thinking,
stop_sequences: None,
}
.into_responses()
.map(|(value, _)| value)
}
}
pub async fn count_tokens(
State(state): State<AppState>,
body: Result<Json<Value>, JsonRejection>,
) -> Response {
let value = match body {
Ok(Json(value)) => value,
Err(e) => return error(e.status(), &e.body_text()),
};
let request: CountRequest = match serde_json::from_value(value) {
Ok(request) => request,
Err(e) => return error(StatusCode::BAD_REQUEST, &e.to_string()),
};
let native = match request.into_responses() {
Ok(value) => value,
Err(e) => return error(StatusCode::BAD_REQUEST, &e),
};
let response = responses::count_input_tokens(State(state), Ok(Json(native))).await;
if !response.status().is_success() {
return response; // Route middleware normalizes native errors.
}
let bytes = to_bytes(response.into_body(), 1024).await;
if let Ok(bytes) = bytes
&& let Ok(value) = serde_json::from_slice::<Value>(&bytes)
&& let Some(count) = value["input_tokens"].as_u64()
{
return Json(json!({"input_tokens":count})).into_response();
}
error(StatusCode::BAD_GATEWAY, "invalid native token count")
}
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct Message {
@@ -149,542 +98,17 @@ enum Piece {
Text(String),
Image(String),
}
fn empty_tool_result() -> Value {
Value::String(String::new())
}
fn blocks(value: Value) -> Result<Vec<Block>, String> {
match value {
Value::String(text) => Ok(vec![Block::Text { text }]),
Value::Array(items) => items
.into_iter()
.map(|v| serde_json::from_value(v).map_err(|e| e.to_string()))
.collect(),
_ => Err("content must be a text string or supported blocks".into()),
}
}
fn text_only(value: Value) -> Result<String, String> {
let mut text = Vec::new();
for block in blocks(value)? {
match block {
Block::Text { text: t } => text.push(t),
_ => return Err("only text blocks are supported here".into()),
}
}
Ok(text.join("\n"))
}
impl Request {
fn into_responses(self) -> Result<(Value, bool), String> {
if self
.thinking
.is_some_and(|v| v != json!({"type":"disabled"}))
{
return Err("only disabled thinking is supported".into());
}
if self.stop_sequences.is_some_and(|s| !s.is_empty()) {
return Err("custom stop_sequences are not supported".into());
}
if self.messages.first().is_some_and(|m| m.role != "user")
|| self.messages.last().is_some_and(|m| m.role != "user")
{
return Err("this subset requires first and last user messages; assistant prefill is unsupported".into());
}
let mut turns: Vec<(String, Vec<Block>)> = Vec::new();
for message in self.messages {
if !matches!(message.role.as_str(), "user" | "assistant") {
return Err("messages role must be user or assistant; use top-level system".into());
}
let parts = blocks(message.content)?;
if parts.is_empty() {
return Err("message content must not be empty".into());
}
if let Some((role, previous)) = turns.last_mut()
&& *role == message.role
{
previous.extend(parts);
} else {
turns.push((message.role, parts));
}
}
let mut input = Vec::new();
for (role, parts) in turns {
// Text and pictures of the turn in the order they came; a picture-free run is one text message.
let mut run: Vec<Piece> = Vec::new();
let flush = |run: &mut Vec<Piece>, input: &mut Vec<Value>| {
if run.is_empty() {
return;
}
if run.iter().any(|piece| matches!(piece, Piece::Image(_))) {
// serve/frontend.py `_parts_of`: the items in order, no separator.
let content: Vec<Value> = run
.drain(..)
.map(|piece| match piece {
Piece::Text(text) => json!({"type":"input_text","text":text}),
Piece::Image(source) => {
json!({"type":"input_image","image_url":source})
}
})
.collect();
input.push(json!({"role":role,"content":content}));
} else {
let text: Vec<String> = run
.drain(..)
.filter_map(|piece| match piece {
Piece::Text(text) => Some(text),
Piece::Image(_) => None,
})
.collect();
input.push(json!({"role":role,"content":text.join("\n")}));
}
};
for part in parts {
match part {
Block::Text { text: t } => run.push(Piece::Text(t)),
Block::Image { source } if role == "user" => {
run.push(Piece::Image(leleka_serving_policy::vision::image_source(
&json!({"type":"image","source":source}),
)));
}
Block::ToolUse {
id,
name,
input: arguments,
} if role == "assistant" => {
flush(&mut run, &mut input);
if !arguments.is_object() {
return Err("tool_use.input must be an object".into());
}
input.push(json!({"type":"function_call","call_id":id,"name":name,"arguments":arguments.to_string()}));
}
Block::ToolResult {
tool_use_id,
content,
is_error,
} if role == "user" => {
flush(&mut run, &mut input);
let text = text_only(content)?;
// The local template has text tool outputs, not a separate error bit.
// Keep the bit and exact normalized content together in the tool role, as
// `{"content":...,"is_error":true}`: sorted keys, the oracle's bytes
// (`scripts/smoke-messages.py`), whatever serde_json's `preserve_order` says.
let output = if is_error == Some(true) {
crate::json_order::error_result_text(&text)
} else {
text
};
input.push(json!({"type":"function_call_output","call_id":tool_use_id,"output":output}));
}
Block::Image { .. } => {
return Err("images belong to user messages".into());
}
_ => {
return Err(
"tool_use belongs to assistant; tool_result belongs to user".into()
);
}
}
}
flush(&mut run, &mut input);
}
let tools: Vec<_> = self
.tools
.into_iter()
.map(|t| {
let mut v = json!({"type":"function","name":t.name,"parameters":t.input_schema});
if let Some(description) = t.description {
v["description"] = json!(description);
}
v
})
.collect();
let mut r = json!({"model":self.model,"input":input,"max_output_tokens":self.max_tokens,"stream":self.stream,"store":false,"reasoning":{"effort":"none"},"tools":tools});
if let Some(choice) = self.tool_choice {
r["tool_choice"] = match choice.kind.as_str() {
"auto" | "none" | "any" if choice.name.is_none() => {
json!(if choice.kind == "any" {
"required"
} else {
&choice.kind
})
}
"tool" => {
json!({"type":"function","name":choice.name.ok_or("tool choice requires name")?})
}
_ => return Err("unsupported tool_choice".into()),
};
if let Some(disabled) = choice.disable_parallel_tool_use {
r["parallel_tool_calls"] = json!(!disabled);
}
}
if let Some(system) = self.system {
r["instructions"] = json!(text_only(system)?);
}
if let Some(v) = self.temperature {
if !(0.0..=1.0).contains(&v) {
return Err("temperature must be in 0..1".into());
}
r["temperature"] = json!(v);
}
if let Some(v) = self.top_p {
r["top_p"] = json!(v);
}
Ok((r, self.stream))
}
}
fn error_type(status: StatusCode) -> &'static str {
match status.as_u16() {
401 => "authentication_error",
403 => "permission_error",
404 => "not_found_error",
413 => "request_too_large",
429 => "rate_limit_error",
503 | 529 => "overloaded_error",
500..=599 => "api_error",
_ => "invalid_request_error",
}
}
pub(crate) fn error_value(status: StatusCode, message: &str) -> Value {
json!({"type":"error","error":{"type":error_type(status),"message":message}})
}
fn error(status: StatusCode, message: &str) -> Response {
(status, Json(error_value(status, message))).into_response()
}
/// This wraps route admission and extraction errors, so they share the Messages envelope.
pub async fn protocol(request: HttpRequest, next: Next) -> Response {
let versions: Vec<_> = request
.headers()
.get_all("anthropic-version")
.iter()
.collect();
if versions.len() != 1 || versions[0] != "2023-06-01" {
return error(
StatusCode::BAD_REQUEST,
"anthropic-version must be 2023-06-01",
);
}
if request.headers().contains_key("anthropic-beta") {
return error(
StatusCode::BAD_REQUEST,
"anthropic-beta features are not supported",
);
}
let response = next.run(request).await;
if response.status().is_success() {
return response;
}
let status = response.status();
let preserved: Vec<_> = [header::ALLOW, header::RETRY_AFTER, header::WWW_AUTHENTICATE]
.into_iter()
.filter_map(|name| {
response
.headers()
.get(&name)
.cloned()
.map(|value| (name, value))
})
.collect();
let bytes = to_bytes(response.into_body(), 64 * 1024)
.await
.unwrap_or_default();
let value: Value = serde_json::from_slice(&bytes).unwrap_or(Value::Null);
let message = value["error"]["message"]
.as_str()
.unwrap_or("Request failed");
let mut result = error(status, message);
for (name, value) in preserved {
result.headers_mut().insert(name, value);
}
result
}
fn usage(r: &Value) -> Value {
let u = &r["usage"];
let cached = u["input_tokens_details"]["cached_tokens"]
.as_u64()
.unwrap_or(0);
json!({"input_tokens":u["input_tokens"].as_u64().unwrap_or(0).saturating_sub(cached),"output_tokens":u["output_tokens"].as_u64().unwrap_or(0),"cache_read_input_tokens":cached,"cache_creation_input_tokens":0})
}
fn stop(r: &Value) -> &'static str {
if r["status"] == "incomplete" {
"max_tokens"
} else if r["output"]
.as_array()
.is_some_and(|a| a.iter().any(|i| i["type"] == "function_call"))
{
"tool_use"
} else {
"end_turn"
}
}
fn tool(item: &Value) -> Result<Value, &'static str> {
let input: Value = serde_json::from_str(
item["arguments"]
.as_str()
.ok_or("missing native tool arguments")?,
)
.map_err(|_| "invalid native tool arguments")?;
if !input.is_object() {
return Err("native tool input must be an object");
}
Ok(json!({"type":"tool_use","id":item["call_id"],"name":item["name"],"input":input}))
}
fn message(r: &Value, initial: bool) -> Result<Value, &'static str> {
let mut content = Vec::new();
if !initial && let Some(items) = r["output"].as_array() {
for item in items {
if item["type"] == "function_call" {
content.push(tool(item)?);
}
if item["type"] == "message"
&& let Some(parts) = item["content"].as_array()
{
for p in parts {
if p["type"] == "output_text" {
content.push(json!({"type":"text","text":p["text"]}));
}
}
}
}
}
Ok(
json!({"id":format!("msg_{}",r["id"].as_str().unwrap_or("unknown")),"type":"message","role":"assistant","model":r["model"],"content":content,"stop_reason":if initial{Value::Null}else{json!(stop(r))},"stop_sequence":null,"usage":usage(r)}),
)
}
pub async fn create(
State(state): State<AppState>,
body: Result<Json<Value>, JsonRejection>,
) -> Response {
let Json(value) = match body {
Ok(v) => v,
Err(e) => return error(e.status(), &e.to_string()),
};
// Anthropic's own top_k plus the Original server's extensions go to the native request as written.
let (value, extensions) = crate::sampling::split_extensions(value);
let r: Request = match serde_json::from_value(value) {
Ok(r) => r,
Err(e) => return error(StatusCode::BAD_REQUEST, &e.to_string()),
};
let (mut r, stream) = match r.into_responses() {
Ok(r) => r,
Err(e) => return error(StatusCode::BAD_REQUEST, &e),
};
for (key, value) in extensions {
r[key] = value;
}
let response = responses::create(State(state), Ok(Json(r))).await;
if !response.status().is_success() {
return response;
}
if stream {
return stream_response(response.into_body());
}
let bytes = match to_bytes(response.into_body(), MAX_EVENT).await {
Ok(v) => v,
Err(_) => {
return error(
StatusCode::BAD_GATEWAY,
"native response exceeds adapter limit",
);
}
};
let value: Value = match serde_json::from_slice(&bytes) {
Ok(v) => v,
Err(_) => return error(StatusCode::BAD_GATEWAY, "invalid native response"),
};
match message(&value, false) {
Ok(v) => Json(v).into_response(),
Err(e) => error(StatusCode::BAD_GATEWAY, e),
}
}
struct Events(mpsc::Receiver<Event>);
impl Stream for Events {
type Item = Result<Event, Infallible>;
fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
self.0.poll_recv(cx).map(|v| v.map(Ok))
}
}
async fn send(sender: &mpsc::Sender<Event>, value: Value) -> Result<(), &'static str> {
let kind = value["type"].as_str().ok_or("missing event type")?;
sender
.send(Event::default().event(kind).data(value.to_string()))
.await
.map_err(|_| "client disconnected")
}
async fn close_text(
sender: &mpsc::Sender<Event>,
active: &mut bool,
index: &mut usize,
) -> Result<(), &'static str> {
if *active {
send(sender, json!({"type":"content_block_stop","index":*index})).await?;
*active = false;
*index += 1;
}
Ok(())
}
async fn adapt(body: &mut Body, sender: &mpsc::Sender<Event>) -> Result<(), &'static str> {
let mut reader = NativeEvents::new(body);
let mut index = 0;
let mut active = false;
loop {
let e = tokio::select! {_=sender.closed()=>return Ok(()),e=reader.next()=>e?};
match e["type"].as_str() {
Some("response.created") => {
send(
sender,
json!({"type":"message_start","message":message(&e["response"],true)?}),
)
.await?
}
Some("response.output_text.delta") => {
if !active {
send(sender,json!({"type":"content_block_start","index":index,"content_block":{"type":"text","text":""}})).await?;
active = true;
}
send(sender,json!({"type":"content_block_delta","index":index,"delta":{"type":"text_delta","text":e["delta"]}})).await?;
}
Some("response.output_text.done") => {
if !active && e["text"] == "" {
send(sender,json!({"type":"content_block_start","index":index,"content_block":{"type":"text","text":""}})).await?;
active = true;
}
close_text(sender, &mut active, &mut index).await?;
}
Some("response.output_item.done") if e["item"]["type"] == "function_call" => {
close_text(sender, &mut active, &mut index).await?;
let mut block = tool(&e["item"])?;
block["input"] = json!({});
send(
sender,
json!({"type":"content_block_start","index":index,"content_block":block}),
)
.await?;
send(sender,json!({"type":"content_block_delta","index":index,"delta":{"type":"input_json_delta","partial_json":e["item"]["arguments"]}})).await?;
send(sender, json!({"type":"content_block_stop","index":index})).await?;
index += 1;
}
Some("response.completed" | "response.incomplete") => {
close_text(sender, &mut active, &mut index).await?;
send(sender,json!({"type":"message_delta","delta":{"stop_reason":stop(&e["response"]),"stop_sequence":null},"usage":usage(&e["response"])})).await?;
send(sender, json!({"type":"message_stop"})).await?;
return Ok(());
}
Some("response.failed") => {
send(
sender,
error_value(
StatusCode::BAD_GATEWAY,
e["response"]["error"]["message"]
.as_str()
.unwrap_or("Generation failed"),
),
)
.await?;
return Ok(());
}
_ => {}
}
}
}
fn stream_response(mut body: Body) -> Response {
let (sender, receiver) = mpsc::channel(8);
tokio::spawn(async move {
let result = adapt(&mut body, &sender).await;
drop(body);
if let Err(message) = result {
let _ = send(&sender, error_value(StatusCode::BAD_GATEWAY, message)).await;
}
});
Sse::new(Events(receiver))
.keep_alive(crate::native_events::keep_alive())
.into_response()
}
#[cfg(test)]
mod tests {
use super::*;
mod tests;
/// The arguments string of a replayed `tool_use` keeps the order the client wrote (the Original is Python: `json.loads`,
/// then the template walks the dict in that order). It does not depend on a sort: `{"z":1,"a":2}` stays `z`, `a`.
#[test]
fn tool_use_arguments_keep_the_order_the_client_wrote() {
let (native, _) = serde_json::from_value::<Request>(json!({"model":"fixture","max_tokens":8,"messages":[
{"role":"user","content":"Do it"},
{"role":"assistant","content":[{"type":"tool_use","id":"call","name":"work","input":{"z":1,"a":{"y":true,"b":[{"d":1,"c":2}]}}}]},
{"role":"user","content":[{"type":"tool_result","tool_use_id":"call","content":"ok"}]}
]})).unwrap().into_responses().unwrap();
assert_eq!(
native["input"][1]["arguments"],
r#"{"z":1,"a":{"y":true,"b":[{"d":1,"c":2}]}}"#
);
}
#[test]
fn tool_results_preserve_errors_empty_content_and_success_bytes() {
let text = "failure 🌍\n\"quote\" \\ path\u{0000}";
let make = |result: Value| {
serde_json::from_value::<Request>(json!({"model":"fixture","max_tokens":8,"messages":[
{"role":"user","content":"Do it"},
{"role":"assistant","content":[{"type":"tool_use","id":"call","name":"work","input":{}}]},
{"role":"user","content":[result]}
]})).unwrap().into_responses()
};
for error in [None, Some(false), Some(true)] {
for content in [
None,
Some(json!(text)),
Some(json!([])),
Some(json!([
{"type":"text","text":text}, {"type":"text","text":"last"}
])),
] {
let normalized = match &content {
None => String::new(),
Some(Value::String(s)) => s.clone(),
Some(Value::Array(parts)) if parts.is_empty() => String::new(),
_ => format!("{text}\nlast"),
};
let mut result = json!({"type":"tool_result","tool_use_id":"call"});
if let Some(content) = content {
result["content"] = content;
}
if let Some(error) = error {
result["is_error"] = json!(error);
}
let (native, _) = make(result).unwrap();
let output = native["input"][2]["output"].as_str().unwrap();
assert_eq!(native["input"][2]["call_id"], "call");
assert_eq!(native["input"][2]["type"], "function_call_output");
assert_eq!(native["input"].as_array().unwrap().len(), 3);
if error == Some(true) {
// the exact bytes the model reads: sorted keys, compact, no ASCII escaping
// (`json.dumps(..., ensure_ascii=False, separators=(",", ":"), sort_keys=True)`)
assert_eq!(
output,
format!(
r#"{{"content":{},"is_error":true}}"#,
serde_json::to_string(&normalized).unwrap()
)
);
assert!(output.starts_with(r#"{"content":""#));
} else {
assert_eq!(output, normalized);
}
}
}
for content in [
Value::Null,
json!(3),
json!({}),
json!([{"type":"image","source":{}}]),
] {
assert!(make(json!({"type":"tool_result","tool_use_id":"call","content":content,"is_error":true})).is_err());
}
for flag in [json!("true"), json!(1), json!({})] {
assert!(
serde_json::from_value::<Block>(
json!({"type":"tool_result","tool_use_id":"call","is_error":flag})
)
.is_err()
);
}
}
}
mod impl_countrequest;
#[allow(unused_imports)]
pub use impl_countrequest::*;
mod error_type;
#[allow(unused_imports)]
pub use error_type::*;
mod adapt;
#[allow(unused_imports)]
pub use adapt::*;
+85
View File
@@ -0,0 +1,85 @@
//! Moved out of the parent module by STRA-338: fn adapt, fn stream_response.
#[allow(unused_imports)]
use super::*;
pub(super) async fn adapt(
body: &mut Body,
sender: &mpsc::Sender<Event>,
) -> Result<(), &'static str> {
let mut reader = NativeEvents::new(body);
let mut index = 0;
let mut active = false;
loop {
let e = tokio::select! {_=sender.closed()=>return Ok(()),e=reader.next()=>e?};
match e["type"].as_str() {
Some("response.created") => {
send(
sender,
json!({"type":"message_start","message":message(&e["response"],true)?}),
)
.await?
}
Some("response.output_text.delta") => {
if !active {
send(sender,json!({"type":"content_block_start","index":index,"content_block":{"type":"text","text":""}})).await?;
active = true;
}
send(sender,json!({"type":"content_block_delta","index":index,"delta":{"type":"text_delta","text":e["delta"]}})).await?;
}
Some("response.output_text.done") => {
if !active && e["text"] == "" {
send(sender,json!({"type":"content_block_start","index":index,"content_block":{"type":"text","text":""}})).await?;
active = true;
}
close_text(sender, &mut active, &mut index).await?;
}
Some("response.output_item.done") if e["item"]["type"] == "function_call" => {
close_text(sender, &mut active, &mut index).await?;
let mut block = tool(&e["item"])?;
block["input"] = json!({});
send(
sender,
json!({"type":"content_block_start","index":index,"content_block":block}),
)
.await?;
send(sender,json!({"type":"content_block_delta","index":index,"delta":{"type":"input_json_delta","partial_json":e["item"]["arguments"]}})).await?;
send(sender, json!({"type":"content_block_stop","index":index})).await?;
index += 1;
}
Some("response.completed" | "response.incomplete") => {
close_text(sender, &mut active, &mut index).await?;
send(sender,json!({"type":"message_delta","delta":{"stop_reason":stop(&e["response"]),"stop_sequence":null},"usage":usage(&e["response"])})).await?;
send(sender, json!({"type":"message_stop"})).await?;
return Ok(());
}
Some("response.failed") => {
send(
sender,
error_value(
StatusCode::BAD_GATEWAY,
e["response"]["error"]["message"]
.as_str()
.unwrap_or("Generation failed"),
),
)
.await?;
return Ok(());
}
_ => {}
}
}
}
pub(super) fn stream_response(mut body: Body) -> Response {
let (sender, receiver) = mpsc::channel(8);
tokio::spawn(async move {
let result = adapt(&mut body, &sender).await;
drop(body);
if let Err(message) = result {
let _ = send(&sender, error_value(StatusCode::BAD_GATEWAY, message)).await;
}
});
Sse::new(Events(receiver))
.keep_alive(crate::native_events::keep_alive())
.into_response()
}
+194
View File
@@ -0,0 +1,194 @@
//! Moved out of the parent module by STRA-338: fn error_type, fn error_value, fn error, fn protocol, fn usage, fn stop ....
#[allow(unused_imports)]
use super::*;
pub(super) fn error_type(status: StatusCode) -> &'static str {
match status.as_u16() {
401 => "authentication_error",
403 => "permission_error",
404 => "not_found_error",
413 => "request_too_large",
429 => "rate_limit_error",
503 | 529 => "overloaded_error",
500..=599 => "api_error",
_ => "invalid_request_error",
}
}
pub(crate) fn error_value(status: StatusCode, message: &str) -> Value {
json!({"type":"error","error":{"type":error_type(status),"message":message}})
}
pub(super) fn error(status: StatusCode, message: &str) -> Response {
(status, Json(error_value(status, message))).into_response()
}
/// This wraps route admission and extraction errors, so they share the Messages envelope.
pub async fn protocol(request: HttpRequest, next: Next) -> Response {
let versions: Vec<_> = request
.headers()
.get_all("anthropic-version")
.iter()
.collect();
if versions.len() != 1 || versions[0] != "2023-06-01" {
return error(
StatusCode::BAD_REQUEST,
"anthropic-version must be 2023-06-01",
);
}
if request.headers().contains_key("anthropic-beta") {
return error(
StatusCode::BAD_REQUEST,
"anthropic-beta features are not supported",
);
}
let response = next.run(request).await;
if response.status().is_success() {
return response;
}
let status = response.status();
let preserved: Vec<_> = [header::ALLOW, header::RETRY_AFTER, header::WWW_AUTHENTICATE]
.into_iter()
.filter_map(|name| {
response
.headers()
.get(&name)
.cloned()
.map(|value| (name, value))
})
.collect();
let bytes = to_bytes(response.into_body(), 64 * 1024)
.await
.unwrap_or_default();
let value: Value = serde_json::from_slice(&bytes).unwrap_or(Value::Null);
let message = value["error"]["message"]
.as_str()
.unwrap_or("Request failed");
let mut result = error(status, message);
for (name, value) in preserved {
result.headers_mut().insert(name, value);
}
result
}
pub(super) fn usage(r: &Value) -> Value {
let u = &r["usage"];
let cached = u["input_tokens_details"]["cached_tokens"]
.as_u64()
.unwrap_or(0);
json!({"input_tokens":u["input_tokens"].as_u64().unwrap_or(0).saturating_sub(cached),"output_tokens":u["output_tokens"].as_u64().unwrap_or(0),"cache_read_input_tokens":cached,"cache_creation_input_tokens":0})
}
pub(super) fn stop(r: &Value) -> &'static str {
if r["status"] == "incomplete" {
"max_tokens"
} else if r["output"]
.as_array()
.is_some_and(|a| a.iter().any(|i| i["type"] == "function_call"))
{
"tool_use"
} else {
"end_turn"
}
}
pub(super) fn tool(item: &Value) -> Result<Value, &'static str> {
let input: Value = serde_json::from_str(
item["arguments"]
.as_str()
.ok_or("missing native tool arguments")?,
)
.map_err(|_| "invalid native tool arguments")?;
if !input.is_object() {
return Err("native tool input must be an object");
}
Ok(json!({"type":"tool_use","id":item["call_id"],"name":item["name"],"input":input}))
}
pub(super) fn message(r: &Value, initial: bool) -> Result<Value, &'static str> {
let mut content = Vec::new();
if !initial && let Some(items) = r["output"].as_array() {
for item in items {
if item["type"] == "function_call" {
content.push(tool(item)?);
}
if item["type"] == "message"
&& let Some(parts) = item["content"].as_array()
{
for p in parts {
if p["type"] == "output_text" {
content.push(json!({"type":"text","text":p["text"]}));
}
}
}
}
}
Ok(
json!({"id":format!("msg_{}",r["id"].as_str().unwrap_or("unknown")),"type":"message","role":"assistant","model":r["model"],"content":content,"stop_reason":if initial{Value::Null}else{json!(stop(r))},"stop_sequence":null,"usage":usage(r)}),
)
}
pub async fn create(
State(state): State<AppState>,
body: Result<Json<Value>, JsonRejection>,
) -> Response {
let Json(value) = match body {
Ok(v) => v,
Err(e) => return error(e.status(), &e.to_string()),
};
// Anthropic's own top_k plus the Original server's extensions go to the native request as written.
let (value, extensions) = crate::sampling::split_extensions(value);
let r: Request = match serde_json::from_value(value) {
Ok(r) => r,
Err(e) => return error(StatusCode::BAD_REQUEST, &e.to_string()),
};
let (mut r, stream) = match r.into_responses() {
Ok(r) => r,
Err(e) => return error(StatusCode::BAD_REQUEST, &e),
};
for (key, value) in extensions {
r[key] = value;
}
let response = responses::create(State(state), Ok(Json(r))).await;
if !response.status().is_success() {
return response;
}
if stream {
return stream_response(response.into_body());
}
let bytes = match to_bytes(response.into_body(), MAX_EVENT).await {
Ok(v) => v,
Err(_) => {
return error(
StatusCode::BAD_GATEWAY,
"native response exceeds adapter limit",
);
}
};
let value: Value = match serde_json::from_slice(&bytes) {
Ok(v) => v,
Err(_) => return error(StatusCode::BAD_GATEWAY, "invalid native response"),
};
match message(&value, false) {
Ok(v) => Json(v).into_response(),
Err(e) => error(StatusCode::BAD_GATEWAY, e),
}
}
impl Stream for Events {
type Item = Result<Event, Infallible>;
fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
self.0.poll_recv(cx).map(|v| v.map(Ok))
}
}
pub(super) async fn send(sender: &mpsc::Sender<Event>, value: Value) -> Result<(), &'static str> {
let kind = value["type"].as_str().ok_or("missing event type")?;
sender
.send(Event::default().event(kind).data(value.to_string()))
.await
.map_err(|_| "client disconnected")
}
pub(super) async fn close_text(
sender: &mpsc::Sender<Event>,
active: &mut bool,
index: &mut usize,
) -> Result<(), &'static str> {
if *active {
send(sender, json!({"type":"content_block_stop","index":*index})).await?;
*active = false;
*index += 1;
}
Ok(())
}
@@ -0,0 +1,237 @@
//! Moved out of the parent module by STRA-338: impl CountRequest, fn count_tokens, fn empty_tool_result, fn blocks, fn text_only, impl Request.
#[allow(unused_imports)]
use super::*;
impl CountRequest {
pub(super) fn into_responses(self) -> Result<Value, String> {
// Use the serving converter, including its exact tool/history validation.
// This output limit is only for native request validation; no GEN is sent.
Request {
model: self.model,
max_tokens: 1,
messages: self.messages,
system: self.system,
stream: false,
tools: self.tools,
tool_choice: self.tool_choice,
temperature: None,
top_p: None,
thinking: self.thinking,
stop_sequences: None,
}
.into_responses()
.map(|(value, _)| value)
}
}
pub async fn count_tokens(
State(state): State<AppState>,
body: Result<Json<Value>, JsonRejection>,
) -> Response {
let value = match body {
Ok(Json(value)) => value,
Err(e) => return error(e.status(), &e.body_text()),
};
let request: CountRequest = match serde_json::from_value(value) {
Ok(request) => request,
Err(e) => return error(StatusCode::BAD_REQUEST, &e.to_string()),
};
let native = match request.into_responses() {
Ok(value) => value,
Err(e) => return error(StatusCode::BAD_REQUEST, &e),
};
let response = responses::count_input_tokens(State(state), Ok(Json(native))).await;
if !response.status().is_success() {
return response; // Route middleware normalizes native errors.
}
let bytes = to_bytes(response.into_body(), 1024).await;
if let Ok(bytes) = bytes
&& let Ok(value) = serde_json::from_slice::<Value>(&bytes)
&& let Some(count) = value["input_tokens"].as_u64()
{
return Json(json!({"input_tokens":count})).into_response();
}
error(StatusCode::BAD_GATEWAY, "invalid native token count")
}
pub(super) fn empty_tool_result() -> Value {
Value::String(String::new())
}
pub(super) fn blocks(value: Value) -> Result<Vec<Block>, String> {
match value {
Value::String(text) => Ok(vec![Block::Text { text }]),
Value::Array(items) => items
.into_iter()
.map(|v| serde_json::from_value(v).map_err(|e| e.to_string()))
.collect(),
_ => Err("content must be a text string or supported blocks".into()),
}
}
pub(super) fn text_only(value: Value) -> Result<String, String> {
let mut text = Vec::new();
for block in blocks(value)? {
match block {
Block::Text { text: t } => text.push(t),
_ => return Err("only text blocks are supported here".into()),
}
}
Ok(text.join("\n"))
}
impl Request {
pub(super) fn into_responses(self) -> Result<(Value, bool), String> {
if self
.thinking
.is_some_and(|v| v != json!({"type":"disabled"}))
{
return Err("only disabled thinking is supported".into());
}
if self.stop_sequences.is_some_and(|s| !s.is_empty()) {
return Err("custom stop_sequences are not supported".into());
}
if self.messages.first().is_some_and(|m| m.role != "user")
|| self.messages.last().is_some_and(|m| m.role != "user")
{
return Err("this subset requires first and last user messages; assistant prefill is unsupported".into());
}
let mut turns: Vec<(String, Vec<Block>)> = Vec::new();
for message in self.messages {
if !matches!(message.role.as_str(), "user" | "assistant") {
return Err("messages role must be user or assistant; use top-level system".into());
}
let parts = blocks(message.content)?;
if parts.is_empty() {
return Err("message content must not be empty".into());
}
if let Some((role, previous)) = turns.last_mut()
&& *role == message.role
{
previous.extend(parts);
} else {
turns.push((message.role, parts));
}
}
let mut input = Vec::new();
for (role, parts) in turns {
// Text and pictures of the turn in the order they came; a picture-free run is one text message.
let mut run: Vec<Piece> = Vec::new();
let flush = |run: &mut Vec<Piece>, input: &mut Vec<Value>| {
if run.is_empty() {
return;
}
if run.iter().any(|piece| matches!(piece, Piece::Image(_))) {
// serve/frontend.py `_parts_of`: the items in order, no separator.
let content: Vec<Value> = run
.drain(..)
.map(|piece| match piece {
Piece::Text(text) => json!({"type":"input_text","text":text}),
Piece::Image(source) => {
json!({"type":"input_image","image_url":source})
}
})
.collect();
input.push(json!({"role":role,"content":content}));
} else {
let text: Vec<String> = run
.drain(..)
.filter_map(|piece| match piece {
Piece::Text(text) => Some(text),
Piece::Image(_) => None,
})
.collect();
input.push(json!({"role":role,"content":text.join("\n")}));
}
};
for part in parts {
match part {
Block::Text { text: t } => run.push(Piece::Text(t)),
Block::Image { source } if role == "user" => {
run.push(Piece::Image(leleka_serving_policy::vision::image_source(
&json!({"type":"image","source":source}),
)));
}
Block::ToolUse {
id,
name,
input: arguments,
} if role == "assistant" => {
flush(&mut run, &mut input);
if !arguments.is_object() {
return Err("tool_use.input must be an object".into());
}
input.push(json!({"type":"function_call","call_id":id,"name":name,"arguments":arguments.to_string()}));
}
Block::ToolResult {
tool_use_id,
content,
is_error,
} if role == "user" => {
flush(&mut run, &mut input);
let text = text_only(content)?;
// The local template has text tool outputs, not a separate error bit.
// Keep the bit and exact normalized content together in the tool role, as
// `{"content":...,"is_error":true}`: sorted keys, the oracle's bytes
// (`scripts/smoke-messages.py`), whatever serde_json's `preserve_order` says.
let output = if is_error == Some(true) {
crate::json_order::error_result_text(&text)
} else {
text
};
input.push(json!({"type":"function_call_output","call_id":tool_use_id,"output":output}));
}
Block::Image { .. } => {
return Err("images belong to user messages".into());
}
_ => {
return Err(
"tool_use belongs to assistant; tool_result belongs to user".into()
);
}
}
}
flush(&mut run, &mut input);
}
let tools: Vec<_> = self
.tools
.into_iter()
.map(|t| {
let mut v = json!({"type":"function","name":t.name,"parameters":t.input_schema});
if let Some(description) = t.description {
v["description"] = json!(description);
}
v
})
.collect();
let mut r = json!({"model":self.model,"input":input,"max_output_tokens":self.max_tokens,"stream":self.stream,"store":false,"reasoning":{"effort":"none"},"tools":tools});
if let Some(choice) = self.tool_choice {
r["tool_choice"] = match choice.kind.as_str() {
"auto" | "none" | "any" if choice.name.is_none() => {
json!(if choice.kind == "any" {
"required"
} else {
&choice.kind
})
}
"tool" => {
json!({"type":"function","name":choice.name.ok_or("tool choice requires name")?})
}
_ => return Err("unsupported tool_choice".into()),
};
if let Some(disabled) = choice.disable_parallel_tool_use {
r["parallel_tool_calls"] = json!(!disabled);
}
}
if let Some(system) = self.system {
r["instructions"] = json!(text_only(system)?);
}
if let Some(v) = self.temperature {
if !(0.0..=1.0).contains(&v) {
return Err("temperature must be in 0..1".into());
}
r["temperature"] = json!(v);
}
if let Some(v) = self.top_p {
r["top_p"] = json!(v);
}
Ok((r, self.stream))
}
}
+94
View File
@@ -0,0 +1,94 @@
//! Unit tests of this module (moved out of the file by STRA-338; the test ids are unchanged).
use super::*;
/// The arguments string of a replayed `tool_use` keeps the order the client wrote (the Original is Python: `json.loads`,
/// then the template walks the dict in that order). It does not depend on a sort: `{"z":1,"a":2}` stays `z`, `a`.
#[test]
fn tool_use_arguments_keep_the_order_the_client_wrote() {
let (native, _) = serde_json::from_value::<Request>(json!({"model":"fixture","max_tokens":8,"messages":[
{"role":"user","content":"Do it"},
{"role":"assistant","content":[{"type":"tool_use","id":"call","name":"work","input":{"z":1,"a":{"y":true,"b":[{"d":1,"c":2}]}}}]},
{"role":"user","content":[{"type":"tool_result","tool_use_id":"call","content":"ok"}]}
]})).unwrap().into_responses().unwrap();
assert_eq!(
native["input"][1]["arguments"],
r#"{"z":1,"a":{"y":true,"b":[{"d":1,"c":2}]}}"#
);
}
#[test]
fn tool_results_preserve_errors_empty_content_and_success_bytes() {
let text = "failure 🌍\n\"quote\" \\ path\u{0000}";
let make = |result: Value| {
serde_json::from_value::<Request>(json!({"model":"fixture","max_tokens":8,"messages":[
{"role":"user","content":"Do it"},
{"role":"assistant","content":[{"type":"tool_use","id":"call","name":"work","input":{}}]},
{"role":"user","content":[result]}
]})).unwrap().into_responses()
};
for error in [None, Some(false), Some(true)] {
for content in [
None,
Some(json!(text)),
Some(json!([])),
Some(json!([
{"type":"text","text":text}, {"type":"text","text":"last"}
])),
] {
let normalized = match &content {
None => String::new(),
Some(Value::String(s)) => s.clone(),
Some(Value::Array(parts)) if parts.is_empty() => String::new(),
_ => format!("{text}\nlast"),
};
let mut result = json!({"type":"tool_result","tool_use_id":"call"});
if let Some(content) = content {
result["content"] = content;
}
if let Some(error) = error {
result["is_error"] = json!(error);
}
let (native, _) = make(result).unwrap();
let output = native["input"][2]["output"].as_str().unwrap();
assert_eq!(native["input"][2]["call_id"], "call");
assert_eq!(native["input"][2]["type"], "function_call_output");
assert_eq!(native["input"].as_array().unwrap().len(), 3);
if error == Some(true) {
// the exact bytes the model reads: sorted keys, compact, no ASCII escaping
// (`json.dumps(..., ensure_ascii=False, separators=(",", ":"), sort_keys=True)`)
assert_eq!(
output,
format!(
r#"{{"content":{},"is_error":true}}"#,
serde_json::to_string(&normalized).unwrap()
)
);
assert!(output.starts_with(r#"{"content":""#));
} else {
assert_eq!(output, normalized);
}
}
}
for content in [
Value::Null,
json!(3),
json!({}),
json!([{"type":"image","source":{}}]),
] {
assert!(
make(
json!({"type":"tool_result","tool_use_id":"call","content":content,"is_error":true})
)
.is_err()
);
}
for flag in [json!("true"), json!(1), json!({})] {
assert!(
serde_json::from_value::<Block>(
json!({"type":"tool_result","tool_use_id":"call","is_error":flag})
)
.is_err()
);
}
}
+7 -783
View File
@@ -40,788 +40,12 @@ pub struct ModelFile {
pub sha256: String,
}
impl Manifest {
pub async fn load(path: &Path) -> Result<Self> {
Self::parse(&fs::read(path).await?)
}
pub async fn from_spec(spec: &str) -> Result<Self> {
if spec == "qwen-iq3-s" {
Self::parse(include_bytes!(
"../../manifests/qwen3.8-flash-next-iq3-s.json"
))
} else {
Self::load(Path::new(spec)).await
}
}
fn parse(bytes: &[u8]) -> Result<Self> {
let manifest: Self = serde_json::from_slice(bytes)?;
if manifest.schema_version != 1 || manifest.files.is_empty() {
return Err("model manifest needs schema_version 1 and at least one file".into());
}
let mut names = std::collections::HashSet::new();
for file in &manifest.files {
let path = Path::new(&file.name);
if path.components().count() != 1
|| !matches!(path.components().next(), Some(Component::Normal(_)))
|| !names.insert(&file.name)
|| file.size == 0
|| file.sha256.len() != 64
|| !file.sha256.bytes().all(|byte| byte.is_ascii_hexdigit())
{
return Err(format!("invalid model file entry: {}", file.name).into());
}
let url = reqwest::Url::parse(&file.url)?;
if url.scheme() != "https"
&& !(url.scheme() == "http"
&& matches!(url.host_str(), Some("127.0.0.1" | "localhost")))
{
return Err(format!("model URL must use HTTPS: {}", file.name).into());
}
if !url.username().is_empty() || url.password().is_some() {
return Err(
format!("model URL must not contain credentials: {}", file.name).into(),
);
}
}
Ok(manifest)
}
}
pub async fn verify(manifest: &Manifest, output: &Path) -> Result<()> {
for file in &manifest.files {
let path = output.join(&file.name);
verify_one(file, &path).await?;
crate::elog!("verified {}", path.display());
}
Ok(())
}
/// The HTTP client every acquisition path uses: HTTPS with the bundled root set, loopback HTTP for local mirrors and
/// tests, no redirects to other schemes or with credentials.
pub(crate) fn http_client() -> Result<Client> {
// A scratch image and a standalone musl binary may have no host CA store.
// Keep certificate and hostname verification, with a root set in the binary.
let roots = webpki_root_certs::TLS_SERVER_ROOT_CERTS
.iter()
.map(|der| reqwest::Certificate::from_der(der.as_ref()))
.collect::<std::result::Result<Vec<_>, _>>()?;
Ok(Client::builder()
.tls_certs_only(roots)
.connect_timeout(Duration::from_secs(30))
.read_timeout(Duration::from_secs(120))
.redirect(reqwest::redirect::Policy::custom(|attempt| {
let url = attempt.url();
if attempt.previous().len() >= 10 {
attempt.error("too many redirects")
} else if url.scheme() == "https"
|| (url.scheme() == "http"
&& matches!(url.host_str(), Some("127.0.0.1" | "localhost")))
{
if url.username().is_empty() && url.password().is_none() {
attempt.follow()
} else {
attempt.error("refusing a model redirect containing credentials")
}
} else {
attempt.error("refusing a non-HTTPS model redirect")
}
}))
.build()?)
}
pub async fn fetch(manifest: &Manifest, output: &Path) -> Result<()> {
fs::create_dir_all(output).await?;
preflight_space(manifest, output).await?;
let client = http_client()?;
let hub_token = match std::env::var("HF_TOKEN") {
Ok(token) if token.is_empty() => None,
Ok(token) if token.chars().any(char::is_whitespace) => {
return Err("HF_TOKEN must not contain whitespace".into());
}
Ok(token) => Some(token),
Err(std::env::VarError::NotPresent) => None,
Err(std::env::VarError::NotUnicode(_)) => {
return Err("HF_TOKEN must contain valid UTF-8".into());
}
};
for file in &manifest.files {
fetch_one_with_retry(&client, file, output, hub_token.as_deref()).await?;
}
Ok(())
}
async fn fetch_one_with_retry(
client: &Client,
file: &ModelFile,
output: &Path,
hub_token: Option<&str>,
) -> Result<()> {
for attempt in 1..=FETCH_ATTEMPTS {
match fetch_one(client, file, output, hub_token).await {
Ok(()) => return Ok(()),
Err(error) if attempt < FETCH_ATTEMPTS && retryable_fetch_error(error.as_ref()) => {
let delay = Duration::from_secs(1 << (attempt - 1));
crate::elog!(
"temporary download failure for {} (attempt {attempt}/{FETCH_ATTEMPTS}): {error}; retrying in {}s",
file.name,
delay.as_secs()
);
tokio::time::sleep(delay).await;
}
Err(error) => return Err(error),
}
}
unreachable!("the final fetch attempt returns directly")
}
fn retryable_fetch_error(error: &(dyn Error + 'static)) -> bool {
if let Some(network) = error.downcast_ref::<reqwest::Error>() {
return network.is_connect()
|| network.is_timeout()
|| network.is_body()
|| network.status().is_some_and(|status| {
status.is_server_error()
|| status == StatusCode::TOO_MANY_REQUESTS
|| status == StatusCode::REQUEST_TIMEOUT
});
}
error
.downcast_ref::<io::Error>()
.is_some_and(|local| local.kind() == io::ErrorKind::UnexpectedEof)
}
fn model_request(
client: &Client,
file: &ModelFile,
offset: u64,
hub_token: Option<&str>,
) -> Result<RequestBuilder> {
let url = reqwest::Url::parse(&file.url)?;
let mut request = client.get(url.clone()).header(ACCEPT_ENCODING, "identity");
if is_hugging_face_url(&url)
&& let Some(token) = hub_token
{
request = request.bearer_auth(token);
}
if offset > 0 {
request = request.header(RANGE, format!("bytes={offset}-"));
}
Ok(request)
}
fn is_hugging_face_url(url: &reqwest::Url) -> bool {
url.scheme() == "https" && url.host_str() == Some("huggingface.co")
}
async fn fetch_one(
client: &Client,
file: &ModelFile,
output: &Path,
hub_token: Option<&str>,
) -> Result<()> {
let destination = output.join(&file.name);
reject_symlink(&destination).await?;
match fs::metadata(&destination).await {
Ok(_) => {
verify_one(file, &destination).await?;
crate::elog!("already verified {}", destination.display());
return Ok(());
}
Err(error) if error.kind() == io::ErrorKind::NotFound => {}
Err(error) => return Err(error.into()),
}
let partial = part_path(&destination);
reject_symlink(&partial).await?;
let mut offset = match fs::metadata(&partial).await {
Ok(metadata) => metadata.len(),
Err(error) if error.kind() == io::ErrorKind::NotFound => 0,
Err(error) => return Err(error.into()),
};
if offset > file.size {
return Err(format!("partial file is larger than manifest size: {}", file.name).into());
}
if offset == file.size {
verify_one(file, &partial).await?;
fs::rename(&partial, &destination).await?;
return Ok(());
}
let request = model_request(client, file, offset, hub_token)?;
let mut response = request.send().await?.error_for_status()?;
match response.status() {
StatusCode::PARTIAL_CONTENT => {
let expected = format!("bytes {offset}-{}/{}", file.size - 1, file.size);
let actual = response
.headers()
.get(CONTENT_RANGE)
.and_then(|value| value.to_str().ok());
if actual != Some(expected.as_str()) {
return Err(
format!("unexpected Content-Range for {}: {actual:?}", file.name).into(),
);
}
}
StatusCode::OK => offset = 0,
status => return Err(format!("unexpected HTTP {status} for {}", file.name).into()),
}
require_space(
destination
.parent()
.ok_or("model destination has no parent")?,
file.size - offset,
)?;
let mut hasher = Sha256::new();
if offset > 0 {
let (size, prefix_hash) = hash_file(&partial).await?;
if size != offset {
return Err("partial file changed during resume".into());
}
hasher = prefix_hash;
}
let mut writer = OpenOptions::new()
.create(true)
.write(true)
.append(offset > 0)
.truncate(offset == 0)
.open(&partial)
.await?;
let mut received = offset;
let mut progress_at = tokio::time::Instant::now();
crate::elog!("fetching {}: {received}/{} bytes", file.name, file.size);
while let Some(chunk) = response.chunk().await? {
received = received
.checked_add(chunk.len() as u64)
.ok_or("download length overflow")?;
if received > file.size {
return Err(format!("download exceeded manifest size: {}", file.name).into());
}
writer.write_all(&chunk).await?;
hasher.update(&chunk);
if progress_at.elapsed() >= Duration::from_secs(10) {
crate::elog!(
"fetching {}: {received}/{} bytes ({:.1}%)",
file.name,
file.size,
received as f64 * 100.0 / file.size as f64
);
progress_at = tokio::time::Instant::now();
}
}
writer.flush().await?;
writer.sync_all().await?;
drop(writer);
if received != file.size {
return Err(io::Error::new(
io::ErrorKind::UnexpectedEof,
format!(
"incomplete download for {}: {received}/{}",
file.name, file.size
),
)
.into());
}
let digest = hex::encode(hasher.finalize());
if !digest.eq_ignore_ascii_case(&file.sha256) {
fs::remove_file(&partial).await?;
return Err(format!("SHA-256 mismatch for {}", file.name).into());
}
fs::rename(&partial, &destination).await?;
crate::elog!("downloaded {}", destination.display());
Ok(())
}
async fn preflight_space(manifest: &Manifest, output: &Path) -> Result<()> {
let mut needed = 0u64;
for entry in &manifest.files {
let destination = output.join(&entry.name);
reject_symlink(&destination).await?;
let remaining = match fs::metadata(&destination).await {
Ok(metadata) if metadata.len() == entry.size => 0,
Ok(_) => {
return Err(
format!("existing model file has unexpected size: {}", entry.name).into(),
);
}
Err(error) if error.kind() == io::ErrorKind::NotFound => {
let partial = part_path(&destination);
reject_symlink(&partial).await?;
let offset = match fs::metadata(&partial).await {
Ok(metadata) => metadata.len(),
Err(error) if error.kind() == io::ErrorKind::NotFound => 0,
Err(error) => return Err(error.into()),
};
entry
.size
.checked_sub(offset)
.ok_or("partial file exceeds manifest size")?
}
Err(error) => return Err(error.into()),
};
needed = needed
.checked_add(remaining)
.ok_or("model disk-space requirement overflow")?;
}
require_space(output, needed)
}
pub(crate) fn require_space(directory: &Path, needed: u64) -> Result<()> {
let available = available_bytes(directory)?;
if available < needed {
return Err(format!(
"insufficient disk space: need {needed} additional bytes, have {available} available bytes in {}",
directory.display()
).into());
}
Ok(())
}
#[cfg(unix)]
fn available_bytes(directory: &Path) -> io::Result<u64> {
use std::{mem::MaybeUninit, os::unix::ffi::OsStrExt};
let path = CString::new(directory.as_os_str().as_bytes())
.map_err(|_| io::Error::new(io::ErrorKind::InvalidInput, "directory contains NUL"))?;
let mut stats = MaybeUninit::<libc::statvfs>::uninit();
// SAFETY: path is NUL-terminated and stats points to writable statvfs storage.
if unsafe { libc::statvfs(path.as_ptr(), stats.as_mut_ptr()) } != 0 {
return Err(io::Error::last_os_error());
}
// SAFETY: a successful statvfs call initialized every field of stats.
let stats = unsafe { stats.assume_init() };
// statvfs counters have different widths on macOS and Linux. Widen both
// before multiplying, then check the byte count at the public u64 bound.
u64::try_from(u128::from(stats.f_bavail) * u128::from(stats.f_frsize))
.map_err(|_| io::Error::new(io::ErrorKind::InvalidData, "available space overflow"))
}
#[cfg(not(unix))]
fn available_bytes(_directory: &Path) -> io::Result<u64> {
Err(io::Error::new(
io::ErrorKind::Unsupported,
"model fetch needs a Unix filesystem",
))
}
async fn verify_one(file: &ModelFile, path: &Path) -> Result<()> {
reject_symlink(path).await?;
let (size, hasher) = hash_file(path).await?;
if size != file.size || !hex::encode(hasher.finalize()).eq_ignore_ascii_case(&file.sha256) {
return Err(format!(
"model file failed size/SHA-256 verification: {}",
path.display()
)
.into());
}
Ok(())
}
async fn hash_file(path: &Path) -> Result<(u64, Sha256)> {
let mut reader = File::open(path).await?;
let mut hasher = Sha256::new();
let mut size = 0u64;
let mut buffer = vec![0u8; 1024 * 1024];
loop {
let read = reader.read(&mut buffer).await?;
if read == 0 {
break;
}
size = size
.checked_add(read as u64)
.ok_or("file length overflow")?;
hasher.update(&buffer[..read]);
}
Ok((size, hasher))
}
async fn reject_symlink(path: &Path) -> Result<()> {
match fs::symlink_metadata(path).await {
Ok(metadata) if metadata.file_type().is_symlink() => {
Err(format!("refusing symlink: {}", path.display()).into())
}
Ok(_) => Ok(()),
Err(error) if error.kind() == io::ErrorKind::NotFound => Ok(()),
Err(error) => Err(error.into()),
}
}
fn part_path(destination: &Path) -> PathBuf {
destination.with_file_name(format!(
"{}.part",
destination.file_name().unwrap().to_string_lossy()
))
}
#[cfg(test)]
mod tests {
use super::*;
use serde_json::json;
use std::time::{SystemTime, UNIX_EPOCH};
use tokio::{net::TcpListener, time::timeout};
mod tests;
#[cfg(unix)] // model fetch is an offline tool that needs statvfs
#[tokio::test]
async fn insufficient_space_stops_before_network_or_partial_file() {
let root = std::env::temp_dir().join(format!(
"strata-space-test-{}-{}",
std::process::id(),
SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap()
.as_nanos()
));
let manifest = Manifest {
schema_version: 1,
files: vec![ModelFile {
name: "huge.gguf".into(),
url: "https://example.invalid/huge.gguf".into(),
size: u64::MAX,
sha256: "0".repeat(64),
}],
};
let error = fetch(&manifest, &root).await.unwrap_err().to_string();
assert!(error.contains("insufficient disk space"));
assert!(!root.join("huge.gguf.part").exists());
fs::remove_dir_all(root).await.unwrap();
}
#[cfg(unix)] // model fetch is an offline tool that needs statvfs
#[tokio::test]
async fn interrupted_download_resumes_and_verifies() {
let base = std::env::temp_dir().join(format!(
"strata-model-test-{}-{}",
std::process::id(),
SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap()
.as_nanos()
));
fs::create_dir_all(&base).await.unwrap();
let output = base.join("model");
fs::create_dir_all(&output).await.unwrap();
fs::write(output.join("sample.bin.part"), b"abc")
.await
.unwrap();
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
let address = listener.local_addr().unwrap();
let server = tokio::spawn(async move {
let (mut socket, _) = listener.accept().await.unwrap();
let mut request = Vec::new();
let mut buffer = [0u8; 1024];
while !request.ends_with(b"\r\n\r\n") {
let count = socket.read(&mut buffer).await.unwrap();
assert!(count > 0);
request.extend_from_slice(&buffer[..count]);
}
let request = String::from_utf8(request).unwrap();
assert!(request.to_ascii_lowercase().contains("range: bytes=3-"));
socket
.write_all(b"HTTP/1.1 206 Partial Content\r\nContent-Length: 3\r\nContent-Range: bytes 3-5/6\r\nConnection: close\r\n\r\ndef")
.await
.unwrap();
});
let manifest_path = base.join("manifest.json");
fs::write(
&manifest_path,
serde_json::to_vec(&json!({
"schema_version": 1,
"files": [{
"name": "sample.bin",
"url": format!("http://{address}/sample.bin"),
"size": 6,
"sha256": hex::encode(Sha256::digest(b"abcdef"))
}]
}))
.unwrap(),
)
.await
.unwrap();
let manifest = Manifest::load(&manifest_path).await.unwrap();
timeout(Duration::from_secs(5), fetch(&manifest, &output))
.await
.unwrap()
.unwrap();
server.await.unwrap();
verify(&manifest, &output).await.unwrap();
assert_eq!(
fs::read(output.join("sample.bin")).await.unwrap(),
b"abcdef"
);
assert!(!output.join("sample.bin.part").exists());
fs::write(output.join("sample.bin"), b"xxxxxx")
.await
.unwrap();
assert!(verify(&manifest, &output).await.is_err());
fs::remove_dir_all(&base).await.unwrap();
}
#[cfg(unix)] // model fetch is an offline tool that needs statvfs
#[tokio::test]
async fn checksum_mismatch_never_publishes_download() {
let base = std::env::temp_dir().join(format!(
"strata-bad-download-{}-{}",
std::process::id(),
SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap()
.as_nanos()
));
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
let address = listener.local_addr().unwrap();
let server = tokio::spawn(async move {
let (mut socket, _) = listener.accept().await.unwrap();
let mut request = Vec::new();
let mut buffer = [0u8; 1024];
while !request.ends_with(b"\r\n\r\n") {
let count = socket.read(&mut buffer).await.unwrap();
assert!(count > 0);
request.extend_from_slice(&buffer[..count]);
}
socket
.write_all(
b"HTTP/1.1 200 OK\r\nContent-Length: 6\r\nConnection: close\r\n\r\nxxxxxx",
)
.await
.unwrap();
});
let manifest = Manifest {
schema_version: 1,
files: vec![ModelFile {
name: "sample.bin".into(),
url: format!("http://{address}/sample.bin"),
size: 6,
sha256: hex::encode(Sha256::digest(b"abcdef")),
}],
};
let error = timeout(Duration::from_secs(5), fetch(&manifest, &base))
.await
.unwrap()
.unwrap_err();
assert!(error.to_string().contains("SHA-256 mismatch"));
server.await.unwrap();
assert!(!base.join("sample.bin").exists());
assert!(!base.join("sample.bin.part").exists());
// Also cover a full-length partial left by a prior interrupted process.
fs::write(base.join("sample.bin.part"), b"xxxxxx")
.await
.unwrap();
let error = timeout(Duration::from_secs(5), fetch(&manifest, &base))
.await
.unwrap()
.unwrap_err();
assert!(error.to_string().contains("size/SHA-256 verification"));
assert!(!base.join("sample.bin").exists());
fs::remove_dir_all(base).await.unwrap();
}
#[cfg(unix)] // model fetch is an offline tool that needs statvfs
#[tokio::test]
async fn transient_server_failure_retries_the_same_partial_download() {
let base = std::env::temp_dir().join(format!(
"strata-retry-test-{}-{}",
std::process::id(),
SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap()
.as_nanos()
));
fs::create_dir_all(&base).await.unwrap();
fs::write(base.join("sample.bin.part"), b"abc")
.await
.unwrap();
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
let address = listener.local_addr().unwrap();
let server = tokio::spawn(async move {
for attempt in 0..2 {
let (mut socket, _) = listener.accept().await.unwrap();
let mut request = Vec::new();
let mut buffer = [0u8; 1024];
while !request.ends_with(b"\r\n\r\n") {
let count = socket.read(&mut buffer).await.unwrap();
assert!(count > 0);
request.extend_from_slice(&buffer[..count]);
}
assert!(
String::from_utf8(request)
.unwrap()
.to_ascii_lowercase()
.contains("range: bytes=3-")
);
if attempt == 0 {
socket
.write_all(
b"HTTP/1.1 503 Service Unavailable\r\nContent-Length: 0\r\nConnection: close\r\n\r\n",
)
.await
.unwrap();
} else {
socket
.write_all(b"HTTP/1.1 206 Partial Content\r\nContent-Length: 3\r\nContent-Range: bytes 3-5/6\r\nConnection: close\r\n\r\ndef")
.await
.unwrap();
}
}
});
let manifest = Manifest::parse(
&serde_json::to_vec(&json!({
"schema_version": 1,
"files": [{
"name": "sample.bin",
"url": format!("http://{address}/sample.bin"),
"size": 6,
"sha256": hex::encode(Sha256::digest(b"abcdef"))
}]
}))
.unwrap(),
)
.unwrap();
timeout(Duration::from_secs(5), fetch(&manifest, &base))
.await
.unwrap()
.unwrap();
server.await.unwrap();
assert_eq!(fs::read(base.join("sample.bin")).await.unwrap(), b"abcdef");
assert!(!base.join("sample.bin.part").exists());
fs::remove_dir_all(base).await.unwrap();
}
#[cfg(unix)] // model fetch is an offline tool that needs statvfs
#[tokio::test]
async fn short_response_resumes_from_new_partial_offset() {
let base = std::env::temp_dir().join(format!(
"strata-short-response-test-{}-{}",
std::process::id(),
SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap()
.as_nanos()
));
fs::create_dir_all(&base).await.unwrap();
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
let address = listener.local_addr().unwrap();
let server = tokio::spawn(async move {
for attempt in 0..2 {
let (mut socket, _) = listener.accept().await.unwrap();
let mut request = Vec::new();
let mut buffer = [0u8; 1024];
while !request.ends_with(b"\r\n\r\n") {
let count = socket.read(&mut buffer).await.unwrap();
assert!(count > 0);
request.extend_from_slice(&buffer[..count]);
}
let request = String::from_utf8(request).unwrap().to_ascii_lowercase();
if attempt == 0 {
assert!(!request.contains("range:"));
socket
.write_all(
b"HTTP/1.1 200 OK\r\nContent-Length: 3\r\nConnection: close\r\n\r\nabc",
)
.await
.unwrap();
} else {
assert!(request.contains("range: bytes=3-"));
socket
.write_all(b"HTTP/1.1 206 Partial Content\r\nContent-Length: 3\r\nContent-Range: bytes 3-5/6\r\nConnection: close\r\n\r\ndef")
.await
.unwrap();
}
}
});
let manifest = Manifest::parse(
&serde_json::to_vec(&json!({
"schema_version": 1,
"files": [{
"name": "sample.bin",
"url": format!("http://{address}/sample.bin"),
"size": 6,
"sha256": hex::encode(Sha256::digest(b"abcdef"))
}]
}))
.unwrap(),
)
.unwrap();
timeout(Duration::from_secs(5), fetch(&manifest, &base))
.await
.unwrap()
.unwrap();
server.await.unwrap();
assert_eq!(fs::read(base.join("sample.bin")).await.unwrap(), b"abcdef");
assert!(!base.join("sample.bin.part").exists());
fs::remove_dir_all(base).await.unwrap();
}
#[tokio::test]
async fn manifest_rejects_path_traversal() {
let path =
std::env::temp_dir().join(format!("strata-bad-manifest-{}.json", std::process::id()));
fs::write(&path, serde_json::to_vec(&json!({
"schema_version": 1,
"files": [{"name": "../escape", "url": "https://example.com/file", "size": 1, "sha256": "a".repeat(64)}]
})).unwrap()).await.unwrap();
assert!(Manifest::load(&path).await.is_err());
fs::remove_file(path).await.unwrap();
}
#[test]
fn hub_token_is_only_attached_to_exact_https_host() {
let client = Client::new();
for (url, expected_auth) in [
(
"https://huggingface.co/org/repo/resolve/commit/model.gguf",
true,
),
("https://huggingface.co.evil.example/model.gguf", false),
("https://example.com/model.gguf", false),
("http://localhost/model.gguf", false),
] {
let file = ModelFile {
name: "model.gguf".into(),
url: url.into(),
size: 1,
sha256: "0".repeat(64),
};
let request = model_request(&client, &file, 3, Some("test-secret"))
.unwrap()
.build()
.unwrap();
assert_eq!(
request
.headers()
.get(reqwest::header::AUTHORIZATION)
.is_some(),
expected_auth,
"{url}"
);
assert_eq!(request.headers().get(RANGE).unwrap(), "bytes=3-");
}
}
#[test]
fn manifest_rejects_url_credentials() {
let bytes = serde_json::to_vec(&json!({
"schema_version": 1,
"files": [{
"name": "model.gguf",
"url": "https://alice:secret@huggingface.co/model.gguf",
"size": 1,
"sha256": "0".repeat(64)
}]
}))
.unwrap();
assert!(Manifest::parse(&bytes).is_err());
}
#[tokio::test]
async fn builtin_profile_is_embedded_and_pinned() {
let manifest = Manifest::from_spec("qwen-iq3-s").await.unwrap();
assert_eq!(manifest.files.len(), 2);
assert_eq!(
manifest.files[0].size + manifest.files[1].size,
83_617_662_656
);
assert!(manifest.files.iter().all(|file| {
file.url
.contains("/resolve/ed59f92082b1e93c0e96d60a8b11aab089b52f09/")
}));
}
}
mod impl_manifest;
#[allow(unused_imports)]
pub use impl_manifest::*;
mod fetch_one;
#[allow(unused_imports)]
pub use fetch_one::*;
+240
View File
@@ -0,0 +1,240 @@
//! Moved out of the parent module by STRA-338: fn fetch_one, fn preflight_space, fn require_space, fn available_bytes, fn available_bytes, fn verify_one ....
#[allow(unused_imports)]
use super::*;
pub(super) async fn fetch_one(
client: &Client,
file: &ModelFile,
output: &Path,
hub_token: Option<&str>,
) -> Result<()> {
let destination = output.join(&file.name);
reject_symlink(&destination).await?;
match fs::metadata(&destination).await {
Ok(_) => {
verify_one(file, &destination).await?;
crate::elog!("already verified {}", destination.display());
return Ok(());
}
Err(error) if error.kind() == io::ErrorKind::NotFound => {}
Err(error) => return Err(error.into()),
}
let partial = part_path(&destination);
reject_symlink(&partial).await?;
let mut offset = match fs::metadata(&partial).await {
Ok(metadata) => metadata.len(),
Err(error) if error.kind() == io::ErrorKind::NotFound => 0,
Err(error) => return Err(error.into()),
};
if offset > file.size {
return Err(format!("partial file is larger than manifest size: {}", file.name).into());
}
if offset == file.size {
verify_one(file, &partial).await?;
fs::rename(&partial, &destination).await?;
return Ok(());
}
let request = model_request(client, file, offset, hub_token)?;
let mut response = request.send().await?.error_for_status()?;
match response.status() {
StatusCode::PARTIAL_CONTENT => {
let expected = format!("bytes {offset}-{}/{}", file.size - 1, file.size);
let actual = response
.headers()
.get(CONTENT_RANGE)
.and_then(|value| value.to_str().ok());
if actual != Some(expected.as_str()) {
return Err(
format!("unexpected Content-Range for {}: {actual:?}", file.name).into(),
);
}
}
StatusCode::OK => offset = 0,
status => return Err(format!("unexpected HTTP {status} for {}", file.name).into()),
}
require_space(
destination
.parent()
.ok_or("model destination has no parent")?,
file.size - offset,
)?;
let mut hasher = Sha256::new();
if offset > 0 {
let (size, prefix_hash) = hash_file(&partial).await?;
if size != offset {
return Err("partial file changed during resume".into());
}
hasher = prefix_hash;
}
let mut writer = OpenOptions::new()
.create(true)
.write(true)
.append(offset > 0)
.truncate(offset == 0)
.open(&partial)
.await?;
let mut received = offset;
let mut progress_at = tokio::time::Instant::now();
crate::elog!("fetching {}: {received}/{} bytes", file.name, file.size);
while let Some(chunk) = response.chunk().await? {
received = received
.checked_add(chunk.len() as u64)
.ok_or("download length overflow")?;
if received > file.size {
return Err(format!("download exceeded manifest size: {}", file.name).into());
}
writer.write_all(&chunk).await?;
hasher.update(&chunk);
if progress_at.elapsed() >= Duration::from_secs(10) {
crate::elog!(
"fetching {}: {received}/{} bytes ({:.1}%)",
file.name,
file.size,
received as f64 * 100.0 / file.size as f64
);
progress_at = tokio::time::Instant::now();
}
}
writer.flush().await?;
writer.sync_all().await?;
drop(writer);
if received != file.size {
return Err(io::Error::new(
io::ErrorKind::UnexpectedEof,
format!(
"incomplete download for {}: {received}/{}",
file.name, file.size
),
)
.into());
}
let digest = hex::encode(hasher.finalize());
if !digest.eq_ignore_ascii_case(&file.sha256) {
fs::remove_file(&partial).await?;
return Err(format!("SHA-256 mismatch for {}", file.name).into());
}
fs::rename(&partial, &destination).await?;
crate::elog!("downloaded {}", destination.display());
Ok(())
}
pub(super) async fn preflight_space(manifest: &Manifest, output: &Path) -> Result<()> {
let mut needed = 0u64;
for entry in &manifest.files {
let destination = output.join(&entry.name);
reject_symlink(&destination).await?;
let remaining = match fs::metadata(&destination).await {
Ok(metadata) if metadata.len() == entry.size => 0,
Ok(_) => {
return Err(
format!("existing model file has unexpected size: {}", entry.name).into(),
);
}
Err(error) if error.kind() == io::ErrorKind::NotFound => {
let partial = part_path(&destination);
reject_symlink(&partial).await?;
let offset = match fs::metadata(&partial).await {
Ok(metadata) => metadata.len(),
Err(error) if error.kind() == io::ErrorKind::NotFound => 0,
Err(error) => return Err(error.into()),
};
entry
.size
.checked_sub(offset)
.ok_or("partial file exceeds manifest size")?
}
Err(error) => return Err(error.into()),
};
needed = needed
.checked_add(remaining)
.ok_or("model disk-space requirement overflow")?;
}
require_space(output, needed)
}
pub(crate) fn require_space(directory: &Path, needed: u64) -> Result<()> {
let available = available_bytes(directory)?;
if available < needed {
return Err(format!(
"insufficient disk space: need {needed} additional bytes, have {available} available bytes in {}",
directory.display()
).into());
}
Ok(())
}
#[cfg(unix)]
pub(super) fn available_bytes(directory: &Path) -> io::Result<u64> {
use std::{mem::MaybeUninit, os::unix::ffi::OsStrExt};
let path = CString::new(directory.as_os_str().as_bytes())
.map_err(|_| io::Error::new(io::ErrorKind::InvalidInput, "directory contains NUL"))?;
let mut stats = MaybeUninit::<libc::statvfs>::uninit();
// SAFETY: path is NUL-terminated and stats points to writable statvfs storage.
if unsafe { libc::statvfs(path.as_ptr(), stats.as_mut_ptr()) } != 0 {
return Err(io::Error::last_os_error());
}
// SAFETY: a successful statvfs call initialized every field of stats.
let stats = unsafe { stats.assume_init() };
// statvfs counters have different widths on macOS and Linux. Widen both
// before multiplying, then check the byte count at the public u64 bound.
u64::try_from(u128::from(stats.f_bavail) * u128::from(stats.f_frsize))
.map_err(|_| io::Error::new(io::ErrorKind::InvalidData, "available space overflow"))
}
#[cfg(not(unix))]
pub(super) fn available_bytes(_directory: &Path) -> io::Result<u64> {
Err(io::Error::new(
io::ErrorKind::Unsupported,
"model fetch needs a Unix filesystem",
))
}
pub(super) async fn verify_one(file: &ModelFile, path: &Path) -> Result<()> {
reject_symlink(path).await?;
let (size, hasher) = hash_file(path).await?;
if size != file.size || !hex::encode(hasher.finalize()).eq_ignore_ascii_case(&file.sha256) {
return Err(format!(
"model file failed size/SHA-256 verification: {}",
path.display()
)
.into());
}
Ok(())
}
pub(super) async fn hash_file(path: &Path) -> Result<(u64, Sha256)> {
let mut reader = File::open(path).await?;
let mut hasher = Sha256::new();
let mut size = 0u64;
let mut buffer = vec![0u8; 1024 * 1024];
loop {
let read = reader.read(&mut buffer).await?;
if read == 0 {
break;
}
size = size
.checked_add(read as u64)
.ok_or("file length overflow")?;
hasher.update(&buffer[..read]);
}
Ok((size, hasher))
}
pub(super) async fn reject_symlink(path: &Path) -> Result<()> {
match fs::symlink_metadata(path).await {
Ok(metadata) if metadata.file_type().is_symlink() => {
Err(format!("refusing symlink: {}", path.display()).into())
}
Ok(_) => Ok(()),
Err(error) if error.kind() == io::ErrorKind::NotFound => Ok(()),
Err(error) => Err(error.into()),
}
}
pub(super) fn part_path(destination: &Path) -> PathBuf {
destination.with_file_name(format!(
"{}.part",
destination.file_name().unwrap().to_string_lossy()
))
}
+179
View File
@@ -0,0 +1,179 @@
//! Moved out of the parent module by STRA-338: impl Manifest, fn verify, fn http_client, fn fetch, fn fetch_one_with_retry, fn retryable_fetch_error ....
#[allow(unused_imports)]
use super::*;
impl Manifest {
pub async fn load(path: &Path) -> Result<Self> {
Self::parse(&fs::read(path).await?)
}
pub async fn from_spec(spec: &str) -> Result<Self> {
if spec == "qwen-iq3-s" {
Self::parse(include_bytes!(
"../../../manifests/qwen3.8-flash-next-iq3-s.json"
))
} else {
Self::load(Path::new(spec)).await
}
}
pub(super) fn parse(bytes: &[u8]) -> Result<Self> {
let manifest: Self = serde_json::from_slice(bytes)?;
if manifest.schema_version != 1 || manifest.files.is_empty() {
return Err("model manifest needs schema_version 1 and at least one file".into());
}
let mut names = std::collections::HashSet::new();
for file in &manifest.files {
let path = Path::new(&file.name);
if path.components().count() != 1
|| !matches!(path.components().next(), Some(Component::Normal(_)))
|| !names.insert(&file.name)
|| file.size == 0
|| file.sha256.len() != 64
|| !file.sha256.bytes().all(|byte| byte.is_ascii_hexdigit())
{
return Err(format!("invalid model file entry: {}", file.name).into());
}
let url = reqwest::Url::parse(&file.url)?;
if url.scheme() != "https"
&& !(url.scheme() == "http"
&& matches!(url.host_str(), Some("127.0.0.1" | "localhost")))
{
return Err(format!("model URL must use HTTPS: {}", file.name).into());
}
if !url.username().is_empty() || url.password().is_some() {
return Err(
format!("model URL must not contain credentials: {}", file.name).into(),
);
}
}
Ok(manifest)
}
}
pub async fn verify(manifest: &Manifest, output: &Path) -> Result<()> {
for file in &manifest.files {
let path = output.join(&file.name);
verify_one(file, &path).await?;
crate::elog!("verified {}", path.display());
}
Ok(())
}
/// The HTTP client every acquisition path uses: HTTPS with the bundled root set, loopback HTTP for local mirrors and
/// tests, no redirects to other schemes or with credentials.
pub(crate) fn http_client() -> Result<Client> {
// A scratch image and a standalone musl binary may have no host CA store.
// Keep certificate and hostname verification, with a root set in the binary.
let roots = webpki_root_certs::TLS_SERVER_ROOT_CERTS
.iter()
.map(|der| reqwest::Certificate::from_der(der.as_ref()))
.collect::<std::result::Result<Vec<_>, _>>()?;
Ok(Client::builder()
.tls_certs_only(roots)
.connect_timeout(Duration::from_secs(30))
.read_timeout(Duration::from_secs(120))
.redirect(reqwest::redirect::Policy::custom(|attempt| {
let url = attempt.url();
if attempt.previous().len() >= 10 {
attempt.error("too many redirects")
} else if url.scheme() == "https"
|| (url.scheme() == "http"
&& matches!(url.host_str(), Some("127.0.0.1" | "localhost")))
{
if url.username().is_empty() && url.password().is_none() {
attempt.follow()
} else {
attempt.error("refusing a model redirect containing credentials")
}
} else {
attempt.error("refusing a non-HTTPS model redirect")
}
}))
.build()?)
}
pub async fn fetch(manifest: &Manifest, output: &Path) -> Result<()> {
fs::create_dir_all(output).await?;
preflight_space(manifest, output).await?;
let client = http_client()?;
let hub_token = match std::env::var("HF_TOKEN") {
Ok(token) if token.is_empty() => None,
Ok(token) if token.chars().any(char::is_whitespace) => {
return Err("HF_TOKEN must not contain whitespace".into());
}
Ok(token) => Some(token),
Err(std::env::VarError::NotPresent) => None,
Err(std::env::VarError::NotUnicode(_)) => {
return Err("HF_TOKEN must contain valid UTF-8".into());
}
};
for file in &manifest.files {
fetch_one_with_retry(&client, file, output, hub_token.as_deref()).await?;
}
Ok(())
}
pub(super) async fn fetch_one_with_retry(
client: &Client,
file: &ModelFile,
output: &Path,
hub_token: Option<&str>,
) -> Result<()> {
for attempt in 1..=FETCH_ATTEMPTS {
match fetch_one(client, file, output, hub_token).await {
Ok(()) => return Ok(()),
Err(error) if attempt < FETCH_ATTEMPTS && retryable_fetch_error(error.as_ref()) => {
let delay = Duration::from_secs(1 << (attempt - 1));
crate::elog!(
"temporary download failure for {} (attempt {attempt}/{FETCH_ATTEMPTS}): {error}; retrying in {}s",
file.name,
delay.as_secs()
);
tokio::time::sleep(delay).await;
}
Err(error) => return Err(error),
}
}
unreachable!("the final fetch attempt returns directly")
}
pub(super) fn retryable_fetch_error(error: &(dyn Error + 'static)) -> bool {
if let Some(network) = error.downcast_ref::<reqwest::Error>() {
return network.is_connect()
|| network.is_timeout()
|| network.is_body()
|| network.status().is_some_and(|status| {
status.is_server_error()
|| status == StatusCode::TOO_MANY_REQUESTS
|| status == StatusCode::REQUEST_TIMEOUT
});
}
error
.downcast_ref::<io::Error>()
.is_some_and(|local| local.kind() == io::ErrorKind::UnexpectedEof)
}
pub(super) fn model_request(
client: &Client,
file: &ModelFile,
offset: u64,
hub_token: Option<&str>,
) -> Result<RequestBuilder> {
let url = reqwest::Url::parse(&file.url)?;
let mut request = client.get(url.clone()).header(ACCEPT_ENCODING, "identity");
if is_hugging_face_url(&url)
&& let Some(token) = hub_token
{
request = request.bearer_auth(token);
}
if offset > 0 {
request = request.header(RANGE, format!("bytes={offset}-"));
}
Ok(request)
}
pub(super) fn is_hugging_face_url(url: &reqwest::Url) -> bool {
url.scheme() == "https" && url.host_str() == Some("huggingface.co")
}
+371
View File
@@ -0,0 +1,371 @@
//! Unit tests of this module (moved out of the file by STRA-338; the test ids are unchanged).
use super::*;
use serde_json::json;
use std::time::{SystemTime, UNIX_EPOCH};
use tokio::{net::TcpListener, time::timeout};
#[cfg(unix)] // model fetch is an offline tool that needs statvfs
#[tokio::test]
async fn insufficient_space_stops_before_network_or_partial_file() {
let root = std::env::temp_dir().join(format!(
"strata-space-test-{}-{}",
std::process::id(),
SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap()
.as_nanos()
));
let manifest = Manifest {
schema_version: 1,
files: vec![ModelFile {
name: "huge.gguf".into(),
url: "https://example.invalid/huge.gguf".into(),
size: u64::MAX,
sha256: "0".repeat(64),
}],
};
let error = fetch(&manifest, &root).await.unwrap_err().to_string();
assert!(error.contains("insufficient disk space"));
assert!(!root.join("huge.gguf.part").exists());
fs::remove_dir_all(root).await.unwrap();
}
#[cfg(unix)] // model fetch is an offline tool that needs statvfs
#[tokio::test]
async fn interrupted_download_resumes_and_verifies() {
let base = std::env::temp_dir().join(format!(
"strata-model-test-{}-{}",
std::process::id(),
SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap()
.as_nanos()
));
fs::create_dir_all(&base).await.unwrap();
let output = base.join("model");
fs::create_dir_all(&output).await.unwrap();
fs::write(output.join("sample.bin.part"), b"abc")
.await
.unwrap();
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
let address = listener.local_addr().unwrap();
let server = tokio::spawn(async move {
let (mut socket, _) = listener.accept().await.unwrap();
let mut request = Vec::new();
let mut buffer = [0u8; 1024];
while !request.ends_with(b"\r\n\r\n") {
let count = socket.read(&mut buffer).await.unwrap();
assert!(count > 0);
request.extend_from_slice(&buffer[..count]);
}
let request = String::from_utf8(request).unwrap();
assert!(request.to_ascii_lowercase().contains("range: bytes=3-"));
socket
.write_all(b"HTTP/1.1 206 Partial Content\r\nContent-Length: 3\r\nContent-Range: bytes 3-5/6\r\nConnection: close\r\n\r\ndef")
.await
.unwrap();
});
let manifest_path = base.join("manifest.json");
fs::write(
&manifest_path,
serde_json::to_vec(&json!({
"schema_version": 1,
"files": [{
"name": "sample.bin",
"url": format!("http://{address}/sample.bin"),
"size": 6,
"sha256": hex::encode(Sha256::digest(b"abcdef"))
}]
}))
.unwrap(),
)
.await
.unwrap();
let manifest = Manifest::load(&manifest_path).await.unwrap();
timeout(Duration::from_secs(5), fetch(&manifest, &output))
.await
.unwrap()
.unwrap();
server.await.unwrap();
verify(&manifest, &output).await.unwrap();
assert_eq!(
fs::read(output.join("sample.bin")).await.unwrap(),
b"abcdef"
);
assert!(!output.join("sample.bin.part").exists());
fs::write(output.join("sample.bin"), b"xxxxxx")
.await
.unwrap();
assert!(verify(&manifest, &output).await.is_err());
fs::remove_dir_all(&base).await.unwrap();
}
#[cfg(unix)] // model fetch is an offline tool that needs statvfs
#[tokio::test]
async fn checksum_mismatch_never_publishes_download() {
let base = std::env::temp_dir().join(format!(
"strata-bad-download-{}-{}",
std::process::id(),
SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap()
.as_nanos()
));
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
let address = listener.local_addr().unwrap();
let server = tokio::spawn(async move {
let (mut socket, _) = listener.accept().await.unwrap();
let mut request = Vec::new();
let mut buffer = [0u8; 1024];
while !request.ends_with(b"\r\n\r\n") {
let count = socket.read(&mut buffer).await.unwrap();
assert!(count > 0);
request.extend_from_slice(&buffer[..count]);
}
socket
.write_all(b"HTTP/1.1 200 OK\r\nContent-Length: 6\r\nConnection: close\r\n\r\nxxxxxx")
.await
.unwrap();
});
let manifest = Manifest {
schema_version: 1,
files: vec![ModelFile {
name: "sample.bin".into(),
url: format!("http://{address}/sample.bin"),
size: 6,
sha256: hex::encode(Sha256::digest(b"abcdef")),
}],
};
let error = timeout(Duration::from_secs(5), fetch(&manifest, &base))
.await
.unwrap()
.unwrap_err();
assert!(error.to_string().contains("SHA-256 mismatch"));
server.await.unwrap();
assert!(!base.join("sample.bin").exists());
assert!(!base.join("sample.bin.part").exists());
// Also cover a full-length partial left by a prior interrupted process.
fs::write(base.join("sample.bin.part"), b"xxxxxx")
.await
.unwrap();
let error = timeout(Duration::from_secs(5), fetch(&manifest, &base))
.await
.unwrap()
.unwrap_err();
assert!(error.to_string().contains("size/SHA-256 verification"));
assert!(!base.join("sample.bin").exists());
fs::remove_dir_all(base).await.unwrap();
}
#[cfg(unix)] // model fetch is an offline tool that needs statvfs
#[tokio::test]
async fn transient_server_failure_retries_the_same_partial_download() {
let base = std::env::temp_dir().join(format!(
"strata-retry-test-{}-{}",
std::process::id(),
SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap()
.as_nanos()
));
fs::create_dir_all(&base).await.unwrap();
fs::write(base.join("sample.bin.part"), b"abc")
.await
.unwrap();
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
let address = listener.local_addr().unwrap();
let server = tokio::spawn(async move {
for attempt in 0..2 {
let (mut socket, _) = listener.accept().await.unwrap();
let mut request = Vec::new();
let mut buffer = [0u8; 1024];
while !request.ends_with(b"\r\n\r\n") {
let count = socket.read(&mut buffer).await.unwrap();
assert!(count > 0);
request.extend_from_slice(&buffer[..count]);
}
assert!(
String::from_utf8(request)
.unwrap()
.to_ascii_lowercase()
.contains("range: bytes=3-")
);
if attempt == 0 {
socket
.write_all(
b"HTTP/1.1 503 Service Unavailable\r\nContent-Length: 0\r\nConnection: close\r\n\r\n",
)
.await
.unwrap();
} else {
socket
.write_all(b"HTTP/1.1 206 Partial Content\r\nContent-Length: 3\r\nContent-Range: bytes 3-5/6\r\nConnection: close\r\n\r\ndef")
.await
.unwrap();
}
}
});
let manifest = Manifest::parse(
&serde_json::to_vec(&json!({
"schema_version": 1,
"files": [{
"name": "sample.bin",
"url": format!("http://{address}/sample.bin"),
"size": 6,
"sha256": hex::encode(Sha256::digest(b"abcdef"))
}]
}))
.unwrap(),
)
.unwrap();
timeout(Duration::from_secs(5), fetch(&manifest, &base))
.await
.unwrap()
.unwrap();
server.await.unwrap();
assert_eq!(fs::read(base.join("sample.bin")).await.unwrap(), b"abcdef");
assert!(!base.join("sample.bin.part").exists());
fs::remove_dir_all(base).await.unwrap();
}
#[cfg(unix)] // model fetch is an offline tool that needs statvfs
#[tokio::test]
async fn short_response_resumes_from_new_partial_offset() {
let base = std::env::temp_dir().join(format!(
"strata-short-response-test-{}-{}",
std::process::id(),
SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap()
.as_nanos()
));
fs::create_dir_all(&base).await.unwrap();
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
let address = listener.local_addr().unwrap();
let server = tokio::spawn(async move {
for attempt in 0..2 {
let (mut socket, _) = listener.accept().await.unwrap();
let mut request = Vec::new();
let mut buffer = [0u8; 1024];
while !request.ends_with(b"\r\n\r\n") {
let count = socket.read(&mut buffer).await.unwrap();
assert!(count > 0);
request.extend_from_slice(&buffer[..count]);
}
let request = String::from_utf8(request).unwrap().to_ascii_lowercase();
if attempt == 0 {
assert!(!request.contains("range:"));
socket
.write_all(
b"HTTP/1.1 200 OK\r\nContent-Length: 3\r\nConnection: close\r\n\r\nabc",
)
.await
.unwrap();
} else {
assert!(request.contains("range: bytes=3-"));
socket
.write_all(b"HTTP/1.1 206 Partial Content\r\nContent-Length: 3\r\nContent-Range: bytes 3-5/6\r\nConnection: close\r\n\r\ndef")
.await
.unwrap();
}
}
});
let manifest = Manifest::parse(
&serde_json::to_vec(&json!({
"schema_version": 1,
"files": [{
"name": "sample.bin",
"url": format!("http://{address}/sample.bin"),
"size": 6,
"sha256": hex::encode(Sha256::digest(b"abcdef"))
}]
}))
.unwrap(),
)
.unwrap();
timeout(Duration::from_secs(5), fetch(&manifest, &base))
.await
.unwrap()
.unwrap();
server.await.unwrap();
assert_eq!(fs::read(base.join("sample.bin")).await.unwrap(), b"abcdef");
assert!(!base.join("sample.bin.part").exists());
fs::remove_dir_all(base).await.unwrap();
}
#[tokio::test]
async fn manifest_rejects_path_traversal() {
let path =
std::env::temp_dir().join(format!("strata-bad-manifest-{}.json", std::process::id()));
fs::write(&path, serde_json::to_vec(&json!({
"schema_version": 1,
"files": [{"name": "../escape", "url": "https://example.com/file", "size": 1, "sha256": "a".repeat(64)}]
})).unwrap()).await.unwrap();
assert!(Manifest::load(&path).await.is_err());
fs::remove_file(path).await.unwrap();
}
#[test]
fn hub_token_is_only_attached_to_exact_https_host() {
let client = Client::new();
for (url, expected_auth) in [
(
"https://huggingface.co/org/repo/resolve/commit/model.gguf",
true,
),
("https://huggingface.co.evil.example/model.gguf", false),
("https://example.com/model.gguf", false),
("http://localhost/model.gguf", false),
] {
let file = ModelFile {
name: "model.gguf".into(),
url: url.into(),
size: 1,
sha256: "0".repeat(64),
};
let request = model_request(&client, &file, 3, Some("test-secret"))
.unwrap()
.build()
.unwrap();
assert_eq!(
request
.headers()
.get(reqwest::header::AUTHORIZATION)
.is_some(),
expected_auth,
"{url}"
);
assert_eq!(request.headers().get(RANGE).unwrap(), "bytes=3-");
}
}
#[test]
fn manifest_rejects_url_credentials() {
let bytes = serde_json::to_vec(&json!({
"schema_version": 1,
"files": [{
"name": "model.gguf",
"url": "https://alice:secret@huggingface.co/model.gguf",
"size": 1,
"sha256": "0".repeat(64)
}]
}))
.unwrap();
assert!(Manifest::parse(&bytes).is_err());
}
#[tokio::test]
async fn builtin_profile_is_embedded_and_pinned() {
let manifest = Manifest::from_spec("qwen-iq3-s").await.unwrap();
assert_eq!(manifest.files.len(), 2);
assert_eq!(
manifest.files[0].size + manifest.files[1].size,
83_617_662_656
);
assert!(manifest.files.iter().all(|file| {
file.url
.contains("/resolve/ed59f92082b1e93c0e96d60a8b11aab089b52f09/")
}));
}
+9 -488
View File
@@ -168,10 +168,6 @@ pub const SHA256: &[(&str, &str)] = &[
),
];
fn repo_url(revision: &str) -> String {
format!("https://huggingface.co/Qwen/Qwen3.8-Flash-Next/resolve/{revision}/")
}
/// One MTP tensor of the checkpoint: where its bytes are in which shard.
#[derive(Serialize, Clone, Debug, PartialEq, Eq)]
pub struct Row {
@@ -199,15 +195,6 @@ struct ManifestRow<'a> {
sha256: String,
}
/// Python's `json.dump(..., indent=1)`.
fn json_indent1<T: Serialize>(value: &T) -> Result<Vec<u8>> {
let mut out = Vec::new();
let formatter = serde_json::ser::PrettyFormatter::with_indent(b" ");
let mut serializer = serde_json::Serializer::with_formatter(&mut out, formatter);
value.serialize(&mut serializer)?;
Ok(out)
}
pub struct Fetcher {
client: Client,
/// Where the shards are read from (ends with `/`).
@@ -218,478 +205,12 @@ pub struct Fetcher {
backoff: fn(u32) -> Duration,
}
/// #327: a range read is only what was asked for when the server says so: 206 and `bytes START-END/...`.
pub fn check_range(status: u16, content_range: Option<&str>, start: u64, end: u64) -> Result<()> {
if status != 206 {
return Err(format!(
"range request not honoured: HTTP {status} instead of 206 (a mirror or proxy that ignores the Range header sends the whole file)"
)
.into());
}
let want = format!("bytes {start}-{end}/");
if !content_range.unwrap_or("").trim().starts_with(&want) {
return Err(format!(
"range request answered with Content-Range {content_range:?}, not {want}..."
)
.into());
}
Ok(())
}
fn sha256_of(path: &Path) -> Result<String> {
let mut hasher = Sha256::new();
let mut file = File::open(path)?;
let mut buffer = vec![0u8; 1 << 24];
loop {
let n = file.read(&mut buffer)?;
if n == 0 {
break;
}
hasher.update(&buffer[..n]);
}
Ok(hex::encode(hasher.finalize()))
}
impl Fetcher {
/// The production configuration: the pinned revision, or `STRATA_MTP_REVISION`.
pub fn from_env() -> Result<Self> {
let revision = std::env::var("STRATA_MTP_REVISION")
.ok()
.filter(|r| !r.is_empty())
.unwrap_or_else(|| PINNED_REVISION.to_owned());
Self::new(repo_url(&revision), repo_url(PINNED_REVISION))
}
pub fn new(repo: String, pinned: String) -> Result<Self> {
Ok(Self {
client: crate::model::http_client()?,
repo,
pinned,
sha256: SHA256
.iter()
.map(|(k, v)| ((*k).to_owned(), (*v).to_owned()))
.collect(),
backoff: |attempt| Duration::from_secs(1 << attempt),
})
}
/// Replace the SHA-256 table (local mirrors and tests).
pub fn with_hashes(mut self, table: BTreeMap<String, String>) -> Self {
self.sha256 = table;
self
}
pub fn without_backoff(mut self) -> Self {
self.backoff = |_| Duration::ZERO;
self
}
pub fn repo(&self) -> &str {
&self.repo
}
/// The tensors' hashes are the pinned revision's: they apply when this run reads that revision.
pub fn pinned(&self) -> bool {
self.repo == self.pinned
}
async fn get_once(&self, url: &str, range: Option<(u64, u64)>) -> Result<Vec<u8>> {
let mut request = self.client.get(url).header(USER_AGENT, "strata-mtp-fetch");
if let Some((start, end)) = range {
request = request.header(RANGE, format!("bytes={start}-{end}"));
}
let response = request.send().await?;
let status = response.status();
match range {
Some((start, end)) => {
let content_range = response
.headers()
.get(CONTENT_RANGE)
.and_then(|v| v.to_str().ok())
.map(str::to_owned);
check_range(status.as_u16(), content_range.as_deref(), start, end)?;
}
None if !status.is_success() => {
return Err(format!("HTTP {status} for {url}").into());
}
None => {}
}
let data = response.bytes().await?.to_vec();
if let Some((start, end)) = range
&& data.len() as u64 != end - start + 1
{
return Err(format!("short range read: {} of {}", data.len(), end - start + 1).into());
}
Ok(data)
}
/// `get`: network errors are retried (4 attempts, 1 s, 2 s, 4 s apart), then surfaced.
pub async fn get(&self, url: &str, range: Option<(u64, u64)>) -> Result<Vec<u8>> {
for attempt in 0..HEADERS_ATTEMPTS {
match self.get_once(url, range).await {
Ok(data) => return Ok(data),
Err(error) if attempt + 1 == HEADERS_ATTEMPTS => return Err(error),
Err(error) => {
tokio::time::sleep((self.backoff)(attempt)).await;
crate::elog!("retry {url}: {error}");
}
}
}
unreachable!("the last attempt returns")
}
/// The pinned revision's files, or the repository's current ones when that revision is gone (a 404 on its index).
pub async fn resolve_repo(&mut self) {
let url = format!("{}model.safetensors.index.json", self.repo);
let head = self
.client
.head(&url)
.header(USER_AGENT, "strata-mtp-fetch")
.send()
.await;
if let Ok(response) = head
&& response.status() == StatusCode::NOT_FOUND
&& !self.repo.contains("/resolve/main/")
{
crate::elog!(
"the checkpoint's pinned revision is gone: reading its current files (main)"
);
if let Some(at) = self.repo.rfind("/resolve/") {
self.repo = format!("{}/resolve/main/", &self.repo[..at]);
}
}
}
async fn shard_header(&self, shard: &str) -> Result<(u64, Map<String, Value>)> {
let url = format!("{}{shard}", self.repo);
let length: [u8; 8] = self
.get(&url, Some((0, 7)))
.await?
.try_into()
.map_err(|_| "short safetensors length prefix")?;
let n = u64::from_le_bytes(length);
let header = self.get(&url, Some((8, 8 + n - 1))).await?;
match serde_json::from_slice(&header)? {
Value::Object(map) => Ok((8 + n, map)),
_ => Err("safetensors header is not an object".into()),
}
}
pub async fn inventory(&self, out: &Path) -> Result<Vec<Row>> {
let index: Value = serde_json::from_slice(
&self
.get(&format!("{}model.safetensors.index.json", self.repo), None)
.await?,
)?;
let mtp: BTreeMap<String, String> = index["weight_map"]
.as_object()
.ok_or("index has no weight_map")?
.iter()
.filter(|(k, _)| k.starts_with("mtp."))
.map(|(k, v)| {
Ok((
k.clone(),
v.as_str().ok_or("shard name expected")?.to_owned(),
))
})
.collect::<Result<_>>()?;
let mut rows = Vec::new();
let mut total = 0u64;
for shard in mtp.values().collect::<BTreeSet<_>>() {
let (base, header) = self.shard_header(shard).await?;
for (name, meta) in &header {
if mtp.get(name) == Some(shard) {
let offsets = meta["data_offsets"]
.as_array()
.and_then(|o| Some((o.first()?.as_u64()?, o.get(1)?.as_u64()?)))
.ok_or("data_offsets must hold two numbers")?;
rows.push(Row {
name: name.clone(),
shard: shard.clone(),
dtype: meta["dtype"].as_str().unwrap_or_default().to_owned(),
shape: meta["shape"]
.as_array()
.map(|s| s.iter().filter_map(Value::as_u64).collect())
.unwrap_or_default(),
start: base + offsets.0,
end: base + offsets.1 - 1,
bytes: offsets.1 - offsets.0,
});
total += offsets.1 - offsets.0;
}
}
}
let found: BTreeSet<&String> = rows.iter().map(|r| &r.name).collect();
let missing: Vec<&String> = mtp.keys().filter(|k| !found.contains(k)).collect();
if !missing.is_empty() {
return Err(format!(
"tensors named in the index but absent from their shard headers: {missing:?}"
)
.into());
}
rows.sort_by(|a, b| a.name.cmp(&b.name));
fs::create_dir_all(out)?;
fs::write(
out.join("mtp-inventory.json"),
json_indent1(&Inventory {
repo: &self.repo,
total_bytes: total,
tensors: &rows,
})?,
)?;
let mut lines = vec![
"# MTP block in the BF16 checkpoint".to_owned(),
String::new(),
format!(
"{} tensors, {:.3} GB, in {} shards.",
rows.len(),
total as f64 / 1e9,
rows.iter().map(|r| &r.shard).collect::<BTreeSet<_>>().len()
),
String::new(),
"| tensor | dtype | shape | MB |".to_owned(),
"|---|---|---|---:|".to_owned(),
];
for r in &rows {
lines.push(format!(
"| `{}` | {} | {} | {:.1} |",
r.name,
r.dtype,
r.shape
.iter()
.map(u64::to_string)
.collect::<Vec<_>>()
.join("x"),
r.bytes as f64 / 1e6
));
}
let text = lines.join("\n") + "\n";
fs::write(out.join("mtp-inventory.md"), &text)?;
print!("{text}");
Ok(rows)
}
pub async fn fetch(&self, out: &Path, only: Option<&str>) -> Result<()> {
let tensors_dir = out.join("tensors");
let stored: Option<Value> = fs::read(out.join("mtp-inventory.json"))
.ok()
.and_then(|bytes| serde_json::from_slice(&bytes).ok());
// The byte ranges belong to one revision: an inventory read from another repository or revision is read again,
// and a tensor fetched from there is not resumed - it is kept only when it is the pinned revision's (sha256).
let same = stored
.as_ref()
.is_some_and(|inv| inv["repo"].as_str() == Some(self.repo.as_str()));
let rows: Vec<Row> = match (&stored, same) {
(Some(inv), true) => inv["tensors"]
.as_array()
.ok_or("inventory has no tensors")?
.iter()
.map(|t| {
Ok(Row {
name: t["name"].as_str().ok_or("name")?.to_owned(),
shard: t["shard"].as_str().ok_or("shard")?.to_owned(),
dtype: t["dtype"].as_str().unwrap_or_default().to_owned(),
shape: t["shape"]
.as_array()
.map(|s| s.iter().filter_map(Value::as_u64).collect())
.unwrap_or_default(),
start: t["start"].as_u64().ok_or("start")?,
end: t["end"].as_u64().ok_or("end")?,
bytes: t["bytes"].as_u64().ok_or("bytes")?,
})
})
.collect::<Result<_>>()?,
_ => self.inventory(out).await?,
};
fs::create_dir_all(&tensors_dir)?;
let mut manifest = Vec::new();
for row in &rows {
if only.is_some_and(|o| !row.name.contains(o)) {
continue;
}
let path = tensors_dir.join(format!("{}.bin", row.name));
let want = if self.pinned() {
self.sha256.get(&row.name).cloned()
} else {
None
};
if path.exists()
&& !same
&& (want.is_none()
|| fs::metadata(&path)?.len() != row.bytes
|| Some(sha256_of(&path)?) != want)
{
fs::remove_file(&path)?;
}
let mut digest = String::new();
for attempt in 0..2 {
let mut have = fs::metadata(&path).map_or(0, |m| m.len());
if have > row.bytes {
fs::remove_file(&path)?;
have = 0;
}
let mut file = OpenOptions::new().create(true).append(true).open(&path)?;
let mut position = row.start + have;
while position <= row.end {
let end = (position + CHUNK - 1).min(row.end);
let data = self
.get(
&format!("{}{}", self.repo, row.shard),
Some((position, end)),
)
.await?;
file.write_all(&data)?;
position = end + 1;
crate::elog!(
"{} {:.0}%",
row.name,
100.0 * (position - row.start) as f64 / row.bytes as f64
);
}
file.sync_all()?;
drop(file);
let size = fs::metadata(&path)?.len();
if size != row.bytes {
return Err(format!("{}: size {size} != {}", path.display(), row.bytes).into());
}
digest = sha256_of(&path)?;
if want.is_none() || want.as_deref() == Some(digest.as_str()) {
break;
}
fs::remove_file(&path)?; // wrong bytes (#327): the whole tensor again, once
if attempt > 0 {
return Err(format!(
"{}: sha256 {digest} is not the checkpoint's {} - the download source sends wrong data (a mirror that ignores Range requests?)",
row.name,
want.unwrap_or_default()
)
.into());
}
crate::elog!(
"{}: wrong bytes (sha256 {}...), fetching it again",
row.name,
&digest[..12]
);
}
manifest.push((
row,
path.strip_prefix(out)?.to_string_lossy().into_owned(),
digest,
));
}
let rows: Vec<ManifestRow> = manifest
.iter()
.map(|(row, file, sha)| ManifestRow {
row,
file: file.clone(),
sha256: sha.clone(),
})
.collect();
fs::write(out.join("mtp-manifest.json"), json_indent1(&rows)?)?;
Ok(())
}
/// #327: the fetched tensors against SHA-256 -> the names that are missing or wrong. Empty when they are right, or
/// when there is nothing to check (no `tensors/`, or another revision is in use). A tensor's verdict is kept in
/// `tensors/verified.json` by size and mtime, so a later run hashes only what changed.
pub fn verify(&self, out: &Path) -> Vec<String> {
let tensors_dir = out.join("tensors");
if !self.pinned() || !tensors_dir.is_dir() {
return Vec::new();
}
let stamp_path = tensors_dir.join("verified.json");
let stamps: BTreeMap<String, Value> = fs::read(&stamp_path)
.ok()
.and_then(|bytes| serde_json::from_slice(&bytes).ok())
.unwrap_or_default();
let (mut bad, mut good) = (Vec::new(), BTreeMap::new());
for (name, want) in &self.sha256 {
let path = tensors_dir.join(format!("{name}.bin"));
let Ok(metadata) = fs::metadata(&path) else {
bad.push(name.clone());
continue;
};
let key = serde_json::json!([metadata.len(), mtime_ns(&metadata), want]);
if stamps.get(name) != Some(&key) && sha256_of(&path).ok().as_deref() != Some(want) {
bad.push(name.clone());
continue;
}
good.insert(name.clone(), key);
}
if let Ok(bytes) = json_indent1(&good) {
let _ = fs::write(&stamp_path, bytes);
}
bad
}
}
#[cfg(unix)]
fn mtime_ns(metadata: &fs::Metadata) -> i128 {
use std::os::unix::fs::MetadataExt;
i128::from(metadata.mtime()) * 1_000_000_000 + i128::from(metadata.mtime_nsec())
}
#[cfg(not(unix))]
fn mtime_ns(metadata: &fs::Metadata) -> i128 {
metadata
.modified()
.ok()
.and_then(|t| t.duration_since(std::time::UNIX_EPOCH).ok())
.map_or(0, |d| d.as_nanos() as i128)
}
/// `strata-next tools mtp-fetch inventory|fetch|verify --out DIR [--only SUBSTR] [--repo URL] [--sha256-file FILE]`.
/// `--repo` points both the read and the pinned revision at a local mirror and `--sha256-file` (a JSON object of
/// name -> hex) replaces the pinned table; both exist for mirrors and for the differential harness. Returns the
/// process exit code.
pub async fn cli(args: &[String]) -> Result<i32> {
let [command, rest @ ..] = args else {
return Err(
"usage: tools mtp-fetch inventory|fetch|verify --out DIR [--only SUBSTR]".into(),
);
};
let value = |name: &str| -> Result<Option<&str>> {
match rest.iter().position(|a| a == name) {
None => Ok(None),
Some(at) => rest
.get(at + 1)
.map(|v| Some(v.as_str()))
.ok_or_else(|| format!("{name} needs a value").into()),
}
};
let out = PathBuf::from(value("--out")?.ok_or("--out is required")?);
let mut fetcher = match value("--repo")? {
Some(repo) => {
let repo = if repo.ends_with('/') {
repo.to_owned()
} else {
format!("{repo}/")
};
Fetcher::new(repo.clone(), repo)?
}
None => Fetcher::from_env()?,
};
if let Some(path) = value("--sha256-file")? {
fetcher = fetcher.with_hashes(serde_json::from_slice(&fs::read(path)?)?);
}
match command.as_str() {
"verify" => {
let bad = fetcher.verify(&out);
for name in &bad {
crate::elog!("MTP tensor missing or corrupt: {name}");
}
Ok(if bad.is_empty() { 0 } else { BAD })
}
"inventory" => {
fetcher.resolve_repo().await;
fetcher.inventory(&out).await?;
Ok(0)
}
"fetch" => {
fetcher.resolve_repo().await;
fetcher.fetch(&out, value("--only")?).await?;
Ok(0)
}
other => Err(format!("unknown mtp-fetch command {other}").into()),
}
}
mod repo_url;
#[allow(unused_imports)]
pub use repo_url::*;
mod impl_fetcher;
#[allow(unused_imports)]
pub use impl_fetcher::*;
mod mtime_ns;
#[allow(unused_imports)]
pub use mtime_ns::*;
+377
View File
@@ -0,0 +1,377 @@
//! Moved out of the parent module by STRA-338: impl Fetcher.
#[allow(unused_imports)]
use super::*;
impl Fetcher {
/// The production configuration: the pinned revision, or `STRATA_MTP_REVISION`.
pub fn from_env() -> Result<Self> {
let revision = std::env::var("STRATA_MTP_REVISION")
.ok()
.filter(|r| !r.is_empty())
.unwrap_or_else(|| PINNED_REVISION.to_owned());
Self::new(repo_url(&revision), repo_url(PINNED_REVISION))
}
pub fn new(repo: String, pinned: String) -> Result<Self> {
Ok(Self {
client: crate::model::http_client()?,
repo,
pinned,
sha256: SHA256
.iter()
.map(|(k, v)| ((*k).to_owned(), (*v).to_owned()))
.collect(),
backoff: |attempt| Duration::from_secs(1 << attempt),
})
}
/// Replace the SHA-256 table (local mirrors and tests).
pub fn with_hashes(mut self, table: BTreeMap<String, String>) -> Self {
self.sha256 = table;
self
}
pub fn without_backoff(mut self) -> Self {
self.backoff = |_| Duration::ZERO;
self
}
pub fn repo(&self) -> &str {
&self.repo
}
/// The tensors' hashes are the pinned revision's: they apply when this run reads that revision.
pub fn pinned(&self) -> bool {
self.repo == self.pinned
}
pub(super) async fn get_once(&self, url: &str, range: Option<(u64, u64)>) -> Result<Vec<u8>> {
let mut request = self.client.get(url).header(USER_AGENT, "strata-mtp-fetch");
if let Some((start, end)) = range {
request = request.header(RANGE, format!("bytes={start}-{end}"));
}
let response = request.send().await?;
let status = response.status();
match range {
Some((start, end)) => {
let content_range = response
.headers()
.get(CONTENT_RANGE)
.and_then(|v| v.to_str().ok())
.map(str::to_owned);
check_range(status.as_u16(), content_range.as_deref(), start, end)?;
}
None if !status.is_success() => {
return Err(format!("HTTP {status} for {url}").into());
}
None => {}
}
let data = response.bytes().await?.to_vec();
if let Some((start, end)) = range
&& data.len() as u64 != end - start + 1
{
return Err(format!("short range read: {} of {}", data.len(), end - start + 1).into());
}
Ok(data)
}
/// `get`: network errors are retried (4 attempts, 1 s, 2 s, 4 s apart), then surfaced.
pub async fn get(&self, url: &str, range: Option<(u64, u64)>) -> Result<Vec<u8>> {
for attempt in 0..HEADERS_ATTEMPTS {
match self.get_once(url, range).await {
Ok(data) => return Ok(data),
Err(error) if attempt + 1 == HEADERS_ATTEMPTS => return Err(error),
Err(error) => {
tokio::time::sleep((self.backoff)(attempt)).await;
crate::elog!("retry {url}: {error}");
}
}
}
unreachable!("the last attempt returns")
}
/// The pinned revision's files, or the repository's current ones when that revision is gone (a 404 on its index).
pub async fn resolve_repo(&mut self) {
let url = format!("{}model.safetensors.index.json", self.repo);
let head = self
.client
.head(&url)
.header(USER_AGENT, "strata-mtp-fetch")
.send()
.await;
if let Ok(response) = head
&& response.status() == StatusCode::NOT_FOUND
&& !self.repo.contains("/resolve/main/")
{
crate::elog!(
"the checkpoint's pinned revision is gone: reading its current files (main)"
);
if let Some(at) = self.repo.rfind("/resolve/") {
self.repo = format!("{}/resolve/main/", &self.repo[..at]);
}
}
}
pub(super) async fn shard_header(&self, shard: &str) -> Result<(u64, Map<String, Value>)> {
let url = format!("{}{shard}", self.repo);
let length: [u8; 8] = self
.get(&url, Some((0, 7)))
.await?
.try_into()
.map_err(|_| "short safetensors length prefix")?;
let n = u64::from_le_bytes(length);
let header = self.get(&url, Some((8, 8 + n - 1))).await?;
match serde_json::from_slice(&header)? {
Value::Object(map) => Ok((8 + n, map)),
_ => Err("safetensors header is not an object".into()),
}
}
pub async fn inventory(&self, out: &Path) -> Result<Vec<Row>> {
let index: Value = serde_json::from_slice(
&self
.get(&format!("{}model.safetensors.index.json", self.repo), None)
.await?,
)?;
let mtp: BTreeMap<String, String> = index["weight_map"]
.as_object()
.ok_or("index has no weight_map")?
.iter()
.filter(|(k, _)| k.starts_with("mtp."))
.map(|(k, v)| {
Ok((
k.clone(),
v.as_str().ok_or("shard name expected")?.to_owned(),
))
})
.collect::<Result<_>>()?;
let mut rows = Vec::new();
let mut total = 0u64;
for shard in mtp.values().collect::<BTreeSet<_>>() {
let (base, header) = self.shard_header(shard).await?;
for (name, meta) in &header {
if mtp.get(name) == Some(shard) {
let offsets = meta["data_offsets"]
.as_array()
.and_then(|o| Some((o.first()?.as_u64()?, o.get(1)?.as_u64()?)))
.ok_or("data_offsets must hold two numbers")?;
rows.push(Row {
name: name.clone(),
shard: shard.clone(),
dtype: meta["dtype"].as_str().unwrap_or_default().to_owned(),
shape: meta["shape"]
.as_array()
.map(|s| s.iter().filter_map(Value::as_u64).collect())
.unwrap_or_default(),
start: base + offsets.0,
end: base + offsets.1 - 1,
bytes: offsets.1 - offsets.0,
});
total += offsets.1 - offsets.0;
}
}
}
let found: BTreeSet<&String> = rows.iter().map(|r| &r.name).collect();
let missing: Vec<&String> = mtp.keys().filter(|k| !found.contains(k)).collect();
if !missing.is_empty() {
return Err(format!(
"tensors named in the index but absent from their shard headers: {missing:?}"
)
.into());
}
rows.sort_by(|a, b| a.name.cmp(&b.name));
fs::create_dir_all(out)?;
fs::write(
out.join("mtp-inventory.json"),
json_indent1(&Inventory {
repo: &self.repo,
total_bytes: total,
tensors: &rows,
})?,
)?;
let mut lines = vec![
"# MTP block in the BF16 checkpoint".to_owned(),
String::new(),
format!(
"{} tensors, {:.3} GB, in {} shards.",
rows.len(),
total as f64 / 1e9,
rows.iter().map(|r| &r.shard).collect::<BTreeSet<_>>().len()
),
String::new(),
"| tensor | dtype | shape | MB |".to_owned(),
"|---|---|---|---:|".to_owned(),
];
for r in &rows {
lines.push(format!(
"| `{}` | {} | {} | {:.1} |",
r.name,
r.dtype,
r.shape
.iter()
.map(u64::to_string)
.collect::<Vec<_>>()
.join("x"),
r.bytes as f64 / 1e6
));
}
let text = lines.join("\n") + "\n";
fs::write(out.join("mtp-inventory.md"), &text)?;
print!("{text}");
Ok(rows)
}
pub async fn fetch(&self, out: &Path, only: Option<&str>) -> Result<()> {
let tensors_dir = out.join("tensors");
let stored: Option<Value> = fs::read(out.join("mtp-inventory.json"))
.ok()
.and_then(|bytes| serde_json::from_slice(&bytes).ok());
// The byte ranges belong to one revision: an inventory read from another repository or revision is read again,
// and a tensor fetched from there is not resumed - it is kept only when it is the pinned revision's (sha256).
let same = stored
.as_ref()
.is_some_and(|inv| inv["repo"].as_str() == Some(self.repo.as_str()));
let rows: Vec<Row> = match (&stored, same) {
(Some(inv), true) => inv["tensors"]
.as_array()
.ok_or("inventory has no tensors")?
.iter()
.map(|t| {
Ok(Row {
name: t["name"].as_str().ok_or("name")?.to_owned(),
shard: t["shard"].as_str().ok_or("shard")?.to_owned(),
dtype: t["dtype"].as_str().unwrap_or_default().to_owned(),
shape: t["shape"]
.as_array()
.map(|s| s.iter().filter_map(Value::as_u64).collect())
.unwrap_or_default(),
start: t["start"].as_u64().ok_or("start")?,
end: t["end"].as_u64().ok_or("end")?,
bytes: t["bytes"].as_u64().ok_or("bytes")?,
})
})
.collect::<Result<_>>()?,
_ => self.inventory(out).await?,
};
fs::create_dir_all(&tensors_dir)?;
let mut manifest = Vec::new();
for row in &rows {
if only.is_some_and(|o| !row.name.contains(o)) {
continue;
}
let path = tensors_dir.join(format!("{}.bin", row.name));
let want = if self.pinned() {
self.sha256.get(&row.name).cloned()
} else {
None
};
if path.exists()
&& !same
&& (want.is_none()
|| fs::metadata(&path)?.len() != row.bytes
|| Some(sha256_of(&path)?) != want)
{
fs::remove_file(&path)?;
}
let mut digest = String::new();
for attempt in 0..2 {
let mut have = fs::metadata(&path).map_or(0, |m| m.len());
if have > row.bytes {
fs::remove_file(&path)?;
have = 0;
}
let mut file = OpenOptions::new().create(true).append(true).open(&path)?;
let mut position = row.start + have;
while position <= row.end {
let end = (position + CHUNK - 1).min(row.end);
let data = self
.get(
&format!("{}{}", self.repo, row.shard),
Some((position, end)),
)
.await?;
file.write_all(&data)?;
position = end + 1;
crate::elog!(
"{} {:.0}%",
row.name,
100.0 * (position - row.start) as f64 / row.bytes as f64
);
}
file.sync_all()?;
drop(file);
let size = fs::metadata(&path)?.len();
if size != row.bytes {
return Err(format!("{}: size {size} != {}", path.display(), row.bytes).into());
}
digest = sha256_of(&path)?;
if want.is_none() || want.as_deref() == Some(digest.as_str()) {
break;
}
fs::remove_file(&path)?; // wrong bytes (#327): the whole tensor again, once
if attempt > 0 {
return Err(format!(
"{}: sha256 {digest} is not the checkpoint's {} - the download source sends wrong data (a mirror that ignores Range requests?)",
row.name,
want.unwrap_or_default()
)
.into());
}
crate::elog!(
"{}: wrong bytes (sha256 {}...), fetching it again",
row.name,
&digest[..12]
);
}
manifest.push((
row,
path.strip_prefix(out)?.to_string_lossy().into_owned(),
digest,
));
}
let rows: Vec<ManifestRow> = manifest
.iter()
.map(|(row, file, sha)| ManifestRow {
row,
file: file.clone(),
sha256: sha.clone(),
})
.collect();
fs::write(out.join("mtp-manifest.json"), json_indent1(&rows)?)?;
Ok(())
}
/// #327: the fetched tensors against SHA-256 -> the names that are missing or wrong. Empty when they are right, or
/// when there is nothing to check (no `tensors/`, or another revision is in use). A tensor's verdict is kept in
/// `tensors/verified.json` by size and mtime, so a later run hashes only what changed.
pub fn verify(&self, out: &Path) -> Vec<String> {
let tensors_dir = out.join("tensors");
if !self.pinned() || !tensors_dir.is_dir() {
return Vec::new();
}
let stamp_path = tensors_dir.join("verified.json");
let stamps: BTreeMap<String, Value> = fs::read(&stamp_path)
.ok()
.and_then(|bytes| serde_json::from_slice(&bytes).ok())
.unwrap_or_default();
let (mut bad, mut good) = (Vec::new(), BTreeMap::new());
for (name, want) in &self.sha256 {
let path = tensors_dir.join(format!("{name}.bin"));
let Ok(metadata) = fs::metadata(&path) else {
bad.push(name.clone());
continue;
};
let key = serde_json::json!([metadata.len(), mtime_ns(&metadata), want]);
if stamps.get(name) != Some(&key) && sha256_of(&path).ok().as_deref() != Some(want) {
bad.push(name.clone());
continue;
}
good.insert(name.clone(), key);
}
if let Ok(bytes) = json_indent1(&good) {
let _ = fs::write(&stamp_path, bytes);
}
bad
}
}
+75
View File
@@ -0,0 +1,75 @@
//! Moved out of the parent module by STRA-338: fn mtime_ns, fn mtime_ns, fn cli.
#[allow(unused_imports)]
use super::*;
#[cfg(unix)]
pub(super) fn mtime_ns(metadata: &fs::Metadata) -> i128 {
use std::os::unix::fs::MetadataExt;
i128::from(metadata.mtime()) * 1_000_000_000 + i128::from(metadata.mtime_nsec())
}
#[cfg(not(unix))]
pub(super) fn mtime_ns(metadata: &fs::Metadata) -> i128 {
metadata
.modified()
.ok()
.and_then(|t| t.duration_since(std::time::UNIX_EPOCH).ok())
.map_or(0, |d| d.as_nanos() as i128)
}
/// `strata-next tools mtp-fetch inventory|fetch|verify --out DIR [--only SUBSTR] [--repo URL] [--sha256-file FILE]`.
/// `--repo` points both the read and the pinned revision at a local mirror and `--sha256-file` (a JSON object of
/// name -> hex) replaces the pinned table; both exist for mirrors and for the differential harness. Returns the
/// process exit code.
pub async fn cli(args: &[String]) -> Result<i32> {
let [command, rest @ ..] = args else {
return Err(
"usage: tools mtp-fetch inventory|fetch|verify --out DIR [--only SUBSTR]".into(),
);
};
let value = |name: &str| -> Result<Option<&str>> {
match rest.iter().position(|a| a == name) {
None => Ok(None),
Some(at) => rest
.get(at + 1)
.map(|v| Some(v.as_str()))
.ok_or_else(|| format!("{name} needs a value").into()),
}
};
let out = PathBuf::from(value("--out")?.ok_or("--out is required")?);
let mut fetcher = match value("--repo")? {
Some(repo) => {
let repo = if repo.ends_with('/') {
repo.to_owned()
} else {
format!("{repo}/")
};
Fetcher::new(repo.clone(), repo)?
}
None => Fetcher::from_env()?,
};
if let Some(path) = value("--sha256-file")? {
fetcher = fetcher.with_hashes(serde_json::from_slice(&fs::read(path)?)?);
}
match command.as_str() {
"verify" => {
let bad = fetcher.verify(&out);
for name in &bad {
crate::elog!("MTP tensor missing or corrupt: {name}");
}
Ok(if bad.is_empty() { 0 } else { BAD })
}
"inventory" => {
fetcher.resolve_repo().await;
fetcher.inventory(&out).await?;
Ok(0)
}
"fetch" => {
fetcher.resolve_repo().await;
fetcher.fetch(&out, value("--only")?).await?;
Ok(0)
}
other => Err(format!("unknown mtp-fetch command {other}").into()),
}
}
+49
View File
@@ -0,0 +1,49 @@
//! Moved out of the parent module by STRA-338: fn repo_url, fn json_indent1, fn check_range, fn sha256_of.
#[allow(unused_imports)]
use super::*;
pub(super) fn repo_url(revision: &str) -> String {
format!("https://huggingface.co/Qwen/Qwen3.8-Flash-Next/resolve/{revision}/")
}
/// Python's `json.dump(..., indent=1)`.
pub(super) fn json_indent1<T: Serialize>(value: &T) -> Result<Vec<u8>> {
let mut out = Vec::new();
let formatter = serde_json::ser::PrettyFormatter::with_indent(b" ");
let mut serializer = serde_json::Serializer::with_formatter(&mut out, formatter);
value.serialize(&mut serializer)?;
Ok(out)
}
/// #327: a range read is only what was asked for when the server says so: 206 and `bytes START-END/...`.
pub fn check_range(status: u16, content_range: Option<&str>, start: u64, end: u64) -> Result<()> {
if status != 206 {
return Err(format!(
"range request not honoured: HTTP {status} instead of 206 (a mirror or proxy that ignores the Range header sends the whole file)"
)
.into());
}
let want = format!("bytes {start}-{end}/");
if !content_range.unwrap_or("").trim().starts_with(&want) {
return Err(format!(
"range request answered with Content-Range {content_range:?}, not {want}..."
)
.into());
}
Ok(())
}
pub(super) fn sha256_of(path: &Path) -> Result<String> {
let mut hasher = Sha256::new();
let mut file = File::open(path)?;
let mut buffer = vec![0u8; 1 << 24];
loop {
let n = file.read(&mut buffer)?;
if n == 0 {
break;
}
hasher.update(&buffer[..n]);
}
Ok(hex::encode(hasher.finalize()))
}
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,239 @@
//! Moved out of the parent module by STRA-338: fn conversions_inexact, fn primary_shard, fn tokenizer_assets_preflight, fn copy_directory, fn write_experts_bin, fn base_files.
#[allow(unused_imports)]
use super::*;
/// Whether any recorded conversion rounded a weight (`exact: false`).
pub(super) fn conversions_inexact(stage: &Path) -> Result<bool> {
let value: serde_json::Value =
serde_json::from_slice(&fs::read(stage.join("conversions.json"))?)?;
Ok(value["tensors"]
.as_array()
.is_some_and(|t| t.iter().any(|r| r["exact"] == false)))
}
pub fn primary_shard(manifest: &model::Manifest, source: &Path) -> Result<PathBuf> {
Ok(shards(manifest, source)?[0].path.clone())
}
pub(super) fn tokenizer_assets_preflight(source: &Path) -> Result<()> {
gguf::tokenizer_metadata(source)?;
// `iq_pack.py` `hadamard_spec` (Strata 0.1.50) packs `prism.hadamard.*` experts (stored in a block-Hadamard-rotated basis)
// with a `hadamard.txt` and a v5 `native_experts.txt` so that an engine which cannot rotate refuses them. This packer writes
// neither, and a folded weight run on unrotated activations computes plausible garbage: refuse the model.
if let Some((key, _)) = gguf::metadata_entries(source)?
.into_iter()
.find(|(key, _)| key.starts_with("prism.hadamard."))
{
return Err(format!(
"{key}: Hadamard-folded experts need the hadamard.txt of tools/iq_pack.py (Strata 0.1.50), which this packer does not write"
)
.into());
}
Ok(())
}
pub(super) fn copy_directory(from: &Path, to: &Path) -> Result<PathBuf> {
fs::create_dir(to)?;
for entry in fs::read_dir(from)? {
let entry = entry?;
let kind = entry.file_type()?;
if !kind.is_file() || kind.is_symlink() {
return Err("base pack tokenizer must contain regular files only".into());
}
fs::copy(entry.path(), to.join(entry.file_name()))?;
File::open(to.join(entry.file_name()))?.sync_all()?;
}
File::open(to)?.sync_all()?;
Ok(to.to_owned())
}
/// `experts.bin`: per layer, `n_expert` blobs of `[gate row | up row | down row]`, the raw GGUF slices, plus the
/// `experts.bin.src.json` sidecar naming what it was cut from (shards, size, hash of `native_experts.txt`).
pub(super) fn write_experts_bin(shards: &[Shard], layout: &Layout, output: &Path) -> Result<()> {
let mut files = shards
.iter()
.map(|s| File::open(&s.path))
.collect::<std::io::Result<Vec<_>>>()?;
let mut out =
std::io::BufWriter::with_capacity(8 << 20, File::create(output.join("experts.bin"))?);
let mut buffer = Vec::new();
for roles in &layout.layers {
for expert in 0..layout.n_expert {
for (shard, tensor) in roles {
let per = tensor.bytes / layout.n_expert;
buffer.resize(per as usize, 0);
let at = shards[*shard].index.summary.data_start + tensor.offset + expert * per;
files[*shard].seek(SeekFrom::Start(at))?;
files[*shard].read_exact(&mut buffer)?;
out.write_all(&buffer)?;
}
}
}
out.flush()?;
out.into_inner().map_err(|e| e.into_error())?.sync_all()?;
let sidecar = json!({
"schema": 1,
"shards": shards.iter().map(|s| json!({"name": s.path.file_name().unwrap().to_str().unwrap(),
"size": s.index.summary.file_size})).collect::<Vec<_>>(),
"native_experts_sha256": hex::encode(Sha256::digest(layout.text.as_bytes())),
"bytes": layout.total,
});
write(
output.join("experts.bin.src.json"),
&serde_json::to_vec_pretty(&sidecar)?,
)
}
/// `tools/iq_pack.py::index_from_base`: the float tensors come from the base pack's `dense.bin` (byte-identical in
/// this model, checked), tensors that are float here but quantized there go to `extra.bin`, quantized ones are
/// served natively. Rows follow the base index.
pub(super) fn base_files(shards: &[Shard], output: &Path, base: &Path) -> Result<()> {
if shards.iter().skip(1).any(|s| {
s.index
.tensors
.iter()
.any(|t| t.name != "per_layer_token_embd.weight")
}) {
return Err("--base needs a model whose tensors are all in shard 1".into());
}
let manifest: serde_json::Value =
serde_json::from_slice(&fs::read(base.join("manifest.json"))?)?;
let base_source = manifest["source"]["shard1"]
.as_str()
.map(PathBuf::from)
.filter(|p| p.is_file())
.ok_or("cannot find the base pack's shard 1 from its manifest.json")?;
let base_index = gguf::tensor_index(&base_source)?;
let new: BTreeMap<&str, &gguf::TensorInfo> = shards
.iter()
.flat_map(|s| s.index.tensors.iter())
.map(|t| (t.name.as_str(), t))
.collect();
let old: BTreeMap<&str, &gguf::TensorInfo> = base_index
.tensors
.iter()
.map(|t| (t.name.as_str(), t))
.collect();
let mut rows: Vec<Vec<String>> = Vec::new();
let mut positions: BTreeMap<String, usize> = BTreeMap::new();
for line in fs::read_to_string(base.join("index.txt"))?.lines() {
if line.starts_with('#') {
continue;
}
let fields = line
.split_whitespace()
.map(str::to_owned)
.collect::<Vec<_>>();
if fields.len() < 9 {
return Err("base pack index row is too short".into());
}
match positions.get(&fields[0]) {
Some(&at) => rows[at] = fields,
None => {
positions.insert(fields[0].clone(), rows.len());
rows.push(fields);
}
}
}
let mut new_file = File::open(&shards[0].path)?;
let mut old_file = File::open(&base_source)?;
let mut extra: Vec<Vec<u8>> = Vec::new();
let mut new_rows = Vec::new();
for fields in &rows {
let name = fields[0].as_str();
let (Some(t), Some(bt)) = (new.get(name), old.get(name)) else {
return Err(format!("tensor {name} missing from one of the models").into());
};
let new_float = matches!(t.kind, 0 | 1 | 30);
let old_float = matches!(bt.kind, 0 | 1 | 30);
if new_float && old_float {
if t.kind != bt.kind
|| t.dimensions != bt.dimensions
|| !same_bytes(
&mut new_file,
shards[0].index.summary.data_start + t.offset,
&mut old_file,
base_index.summary.data_start + bt.offset,
t.bytes,
bt.bytes,
)?
{
return Err(format!(
"float tensor {name} differs from the base model; this pack cannot reuse its dense.bin"
)
.into());
}
new_rows.push(fields.clone());
} else if new_float {
if t.kind != 30 {
return Err(
format!("unexpected float type {} for {name}", kind_name(t.kind)).into(),
);
}
let offset: usize = extra
.iter()
.map(|b| b.len() + (64 - b.len() % 64) % 64)
.sum();
let mut bytes = vec![0u8; t.bytes as usize];
new_file.seek(SeekFrom::Start(
shards[0].index.summary.data_start + t.offset,
))?;
new_file.read_exact(&mut bytes)?;
extra.push(bytes);
let mut row = vec![
name.to_owned(),
"3".into(),
"4".into(),
offset.to_string(),
t.bytes.to_string(),
"0".into(),
t.bytes.to_string(),
fields[7].clone(),
fields[8].clone(),
];
row.extend(std::iter::repeat_n("0".to_owned(), 10));
new_rows.push(row);
} else {
let mut row = vec![
name.to_owned(),
fields[1].clone(),
"0".into(),
"0".into(),
"0".into(),
"0".into(),
"0".into(),
fields[7].clone(),
fields[8].clone(),
"8".into(),
"0".into(),
"32".into(),
];
row.extend(std::iter::repeat_n("0".to_owned(), 7));
new_rows.push(row);
}
}
let mut pool = 0u64;
let mut lines = Vec::new();
for row in &mut new_rows {
row[5] = pool.to_string();
pool += align(row[6].parse::<u64>()?)?;
lines.push(row.join(" ") + "\n");
}
write_index(output, shards, pool, &lines)?;
let mut extra_file = File::create(output.join("extra.bin"))?;
for bytes in &extra {
extra_file.write_all(bytes)?;
extra_file.write_all(&vec![0u8; (64 - bytes.len() % 64) % 64])?;
}
extra_file.sync_all()?;
let dense = output.join("dense.bin");
if fs::hard_link(base.join("dense.bin"), &dense).is_err() {
fs::copy(base.join("dense.bin"), &dense)?;
}
write_conversions(
output,
&json!({"schema":1,"tool":"strata-next","compat_bf16":false,
"base":base.to_str().unwrap_or_default(),"tensors":[]}),
)
}
@@ -0,0 +1,212 @@
//! Moved out of the parent module by STRA-338: fn convert_tensor, fn native_ple_key.
#[allow(unused_imports)]
use super::*;
/// The pack form of one tensor the engine reads from `dense.bin` when it is stored otherwise. Mirrors
/// `tools/iq_pack.py::convert` for every source kind: same accept/reject decision, same bytes, same record.
#[allow(clippy::too_many_arguments)]
pub(super) fn convert_tensor(
input: &mut File,
shard: &Shard,
tensor: &gguf::TensorInfo,
target: u32,
compat_bf16: bool,
dense: &mut File,
) -> Result<Converted> {
let src = tensor.kind;
let src_lower = kind_name(src).to_ascii_lowercase();
let float_source = matches!(src, 0 | 1 | 30);
let need_compat = |what: &str| -> Result<()> {
if compat_bf16 {
Ok(())
} else {
Err(format!(
"{}: stored as {what} but the engine reads {}; use --compat-bf16",
tensor.name,
kind_name(target)
)
.into())
}
};
let mut digest = Sha256::new();
let mut written = 0u64;
let mut write = |dense: &mut File, bytes: &[u8]| -> std::result::Result<(), String> {
dense.write_all(bytes).map_err(|e| e.to_string())?;
written += bytes.len() as u64;
Ok(())
};
let mut out = Vec::new();
match target {
30 => {
// F32 whose values are all exactly BF16 (low 16 bits zero): the exact path, whole tensor or nothing.
let all_bf16 = src == 0 && {
let mut all = true;
stream_f32(input, shard, tensor, |_, values| {
all &= values_of(values).all(|v| v.to_bits() & 0xffff == 0);
Ok(())
})?;
all
};
if all_bf16 {
stream_f32(input, shard, tensor, |raw, values| {
digest.update(raw);
out.clear();
for v in values_of(values) {
if !v.is_finite() {
return Err(format!(
"{} is F32 with non-finite values; refused rather than converted",
tensor.name
));
}
out.extend_from_slice(&((v.to_bits() >> 16) as u16).to_le_bytes());
}
write(dense, &out)
})?;
return Ok(Converted {
index_kind: 4,
written,
dst: written,
record: Some((
"f32->bf16: the values are BF16's (low 16 bits zero)".to_owned(),
true,
0.0,
)),
source_sha256: hex::encode(digest.finalize()),
});
}
need_compat(if src == 0 {
"F32 with values that are not BF16"
} else {
kind_name(src)
})?;
let mut stats = Error64::new();
stream_f32(input, shard, tensor, |raw, values| {
digest.update(raw);
out.clear();
for v in values_of(values) {
if !v.is_finite() {
return Err(format!(
"{}: cannot convert non-finite weights to BF16",
tensor.name
));
}
let bits = bf16_round_nearest_even(v);
let back = f32::from_bits(u32::from(bits) << 16);
if back.is_infinite() {
// iq_pack.py writes the infinity and records max_abs_err=inf; a pack must not carry it.
return Err(format!(
"{}: a value rounds beyond BF16's range, which the engine reads it as",
tensor.name
));
}
stats.note(back, v);
out.extend_from_slice(&bits.to_le_bytes());
}
write(dense, &out)
})?;
let method = if float_source {
format!("{src_lower}->bf16 round-to-nearest-even (--compat-bf16)")
} else {
"dequantize->bf16 round-to-nearest-even (--compat-bf16)".to_owned()
};
Ok(Converted {
index_kind: 4,
written,
dst: written,
record: Some((method, stats.exact, stats.max_abs_err)),
source_sha256: hex::encode(digest.finalize()),
})
}
1 => {
// The PLE conv kernel reads F16. F32 goes in as index kind 3 (the loader narrows it); anything else
// is narrowed here, which only --compat-bf16 allows.
if src != 0 {
need_compat(kind_name(src))?;
}
let mut stats = Error64::new();
stream_f32(input, shard, tensor, |raw, values| {
digest.update(raw);
out.clear();
for v in values_of(values) {
if !v.is_finite() {
return Err(format!(
"{}: cannot convert non-finite weights to F16",
tensor.name
));
}
let half = kar_codec::f32_to_f16_bits(v);
let back = kar_codec::f16_bits_to_f32(half);
if !back.is_finite() {
return Err(format!(
"{}: a value is beyond F16's range, which the engine reads it as",
tensor.name
));
}
stats.note(back, v);
if src == 0 {
// Index kind 3 stores F32; the existing loader narrows it.
out.extend_from_slice(&v.to_le_bytes());
} else {
out.extend_from_slice(&half.to_le_bytes());
}
}
write(dense, &out)
})?;
let (index_kind, dst, method) = if src == 0 {
(
3,
written / 2,
"f32->f16 by the loader (index kind 3, round-to-nearest-even)".to_owned(),
)
} else {
(
5,
written,
format!("{src_lower}->f16 round-to-nearest-even (--compat-bf16)"),
)
};
Ok(Converted {
index_kind,
written,
dst,
record: Some((method, stats.exact, stats.max_abs_err)),
source_sha256: hex::encode(digest.finalize()),
})
}
0 => {
if !float_source {
need_compat(kind_name(src))?;
}
stream_f32(input, shard, tensor, |raw, values| {
digest.update(raw);
if src != 1 {
return write(dense, values);
}
// F16 -> F32 as numpy/IEEE conversion does it: a signaling NaN comes out quiet.
out.clear();
for v in values_of(values) {
let bits = v.to_bits();
out.extend_from_slice(
&(if v.is_nan() { bits | 0x0040_0000 } else { bits }).to_le_bytes(),
);
}
write(dense, &out)
})?;
Ok(Converted {
index_kind: 2,
written,
dst: written,
record: Some((format!("{src_lower}->f32 widening"), true, 0.0)),
source_sha256: hex::encode(digest.finalize()),
})
}
_ => Err("unsupported native pack conversion target".into()),
}
}
/// `iq_pack.py` `NATIVE_PLE_KEY`: the PLE key encodings left in the GGUF for the engine's native PLE key (Q8_0, Q2_0, and since
/// Strata 0.1.50 IQ3_XXS and IQ4_XS, #381). Another quantized key takes the BF16 path (`--compat-bf16`).
pub(super) fn native_ple_key(kind: u32) -> bool {
matches!(kind, 8 | 42 | 18 | 23)
}
@@ -0,0 +1,250 @@
//! Moved out of the parent module by STRA-338: fn dense_files, fn write_index, fn write_conversions, fn write, fn prepare, fn prepare_with.
#[allow(unused_imports)]
use super::*;
/// `tools/iq_pack.py::index_standalone`: every non-expert tensor of the model. Floats the engine reads from the pack
/// go into `dense.bin` in the form it reads them; quantized ones are served natively from the GGUF.
pub(super) fn dense_files(shards: &[Shard], output: &Path, options: &Options) -> Result<()> {
let mut dense = File::create(output.join("dense.bin"))?;
let mut at = 0u64;
let mut pool = 0u64;
let mut rows = Vec::new();
let mut records = Vec::new();
let mut compat_entries = Vec::new();
for shard in shards {
let mut input = File::open(&shard.path)?;
let shard_name = shard.path.file_name().unwrap().to_str().unwrap();
for tensor in &shard.index.tensors {
if expert(&tensor.name) || tensor.name == "per_layer_token_embd.weight" {
continue;
}
if tensor.dimensions.len() > 2 {
return Err("dense pack index accepts at most two dimensions".into());
}
let ne0 = tensor.dimensions[0];
let ne1 = tensor.dimensions.get(1).copied().unwrap_or(0);
let float = matches!(tensor.kind, 0 | 1 | 30);
let required = form(&tensor.name);
let native = !float
&& (required.is_none()
|| (tensor.name == "blk.1.ple_key.weight" && native_ple_key(tensor.kind)));
if native {
rows.push(format!(
"{} 0 0 0 0 {pool} 0 {ne0} {ne1} 8 0 32 0 0 0 0 0 0 0\n",
tensor.name
));
continue;
}
let target = required.unwrap_or(tensor.kind);
let (index_kind, written, dst) = if target == tensor.kind {
// Stored as the engine reads it (or an unlisted float): copied verbatim.
let mut written = 0u64;
gguf_f32_stream::visit(
&mut input,
shard.index.summary.data_start + tensor.offset,
tensor.kind,
tensor.bytes,
|raw, _| {
dense.write_all(raw).map_err(|e| e.to_string())?;
written += raw.len() as u64;
Ok(())
},
)?;
let kind = match tensor.kind {
0 => 2,
1 => 5,
_ => 4,
};
(kind, written, written)
} else {
let converted = convert_tensor(
&mut input,
shard,
tensor,
target,
options.compat_bf16,
&mut dense,
)?;
let (method, exact, max_abs_err) = converted.record.clone().unwrap();
if method.contains("--compat-bf16") {
compat_entries.push(json!({"name":tensor.name,
"source_type":kind_name(tensor.kind), "bytes":converted.written}));
}
records.push(Record {
name: tensor.name.clone(),
shard: shard_name.to_owned(),
src_type: kind_name(tensor.kind),
dst_type: kind_name(target),
method,
exact,
max_abs_err,
source_sha256: converted.source_sha256,
});
(converted.index_kind, converted.written, converted.dst)
};
rows.push(format!(
"{} 0 {index_kind} {at} {written} {pool} {dst} {ne0} {ne1} 0 0 1 0 0 0 0 0 0 0\n",
tensor.name
));
let padded = align(written)?;
dense.write_all(&[0u8; 64][..(padded - written) as usize])?;
at = at.checked_add(padded).ok_or("dense file offset overflow")?;
pool = pool.checked_add(align(dst)?).ok_or("dense pool overflow")?;
}
}
dense.sync_all()?;
write_index(output, shards, pool, &rows)?;
let sources = shards
.iter()
.map(|s| {
json!({"name":s.path.file_name().unwrap().to_str().unwrap(),
"size":s.index.summary.file_size})
})
.collect::<Vec<_>>();
let tensors = records
.iter()
.map(|r| {
json!({"name":r.name, "shard":r.shard, "src_type":r.src_type, "dst_type":r.dst_type,
"method":r.method, "exact":r.exact, "max_abs_err":r.max_abs_err,
"source_sha256":r.source_sha256})
})
.collect::<Vec<_>>();
write_conversions(
output,
&json!({"schema":1,"tool":"strata-next","compat_bf16":options.compat_bf16,
"source_shards":sources,"tensors":tensors}),
)?;
if options.compat_bf16 {
write(
output.join("compat-bf16.json"),
&serde_json::to_vec_pretty(&json!({
"source": shards[0].path.to_str().unwrap_or_default(),
"rounding": "nearest-even", "tensors": compat_entries}))?,
)?;
}
Ok(())
}
pub(super) fn write_index(
output: &Path,
shards: &[Shard],
pool: u64,
rows: &[String],
) -> Result<()> {
let source = shards[0].path.file_name().unwrap().to_str().unwrap();
let text = format!(
"# strata pack index v3 -- generated by strata-next (native experts) from {source}\n# align 64 pool {pool} tensors {}\n{}",
rows.len(),
rows.concat()
);
write(output.join("index.txt"), text.as_bytes())
}
pub(super) fn write_conversions(output: &Path, value: &serde_json::Value) -> Result<()> {
write(
output.join("conversions.json"),
&serde_json::to_vec_pretty(value)?,
)
}
pub(super) fn write(path: PathBuf, bytes: &[u8]) -> Result<()> {
let mut file = File::create(path)?;
file.write_all(bytes)?;
file.sync_all()?;
Ok(())
}
pub async fn prepare(
manifest: &model::Manifest,
source: &Path,
output: &Path,
) -> Result<serde_json::Value> {
prepare_with(manifest, source, output, &Options::default()).await
}
pub async fn prepare_with(
manifest: &model::Manifest,
source: &Path,
output: &Path,
options: &Options,
) -> Result<serde_json::Value> {
if options.compat_bf16 && options.base.is_some() {
return Err("--compat-bf16 cannot reuse --base dense weights".into());
}
if output.exists() || output.is_symlink() {
return Err("native pack output already exists; choose a new versioned directory".into());
}
model::verify(manifest, source).await?;
let shards = shards(manifest, source)?;
let layout = expert_layout(&shards)?;
// Validate tokenizer before writing any pack files.
tokenizer_assets_preflight(&shards[0].path)?;
let parent = output
.parent()
.filter(|p| !p.as_os_str().is_empty())
.unwrap_or(Path::new("."));
fs::create_dir_all(parent)?;
let name = output
.file_name()
.ok_or("native pack output has no filename")?;
let mut stage_name = std::ffi::OsString::from(".");
stage_name.push(name);
stage_name.push(format!(".native-pack-{}.tmp", std::process::id()));
let stage = parent.join(stage_name);
let mut builder = fs::DirBuilder::new();
#[cfg(unix)]
{
use std::os::unix::fs::DirBuilderExt;
builder.mode(0o700);
}
builder.create(&stage)?;
let mut lossy = false;
let result = (|| -> Result<()> {
match &options.base {
Some(base) => base_files(&shards, &stage, base)?,
None => dense_files(&shards, &stage, options)?,
}
let base_tokenizer = options
.base
.as_ref()
.map(|b| b.join("tokenizer"))
.filter(|t| t.join("vocab.json").is_file() && t.join("chat_template.jinja").is_file());
let tokenizer_dir = match base_tokenizer {
Some(base_tokenizer) => copy_directory(&base_tokenizer, &stage.join("tokenizer"))?,
None => tokenizer_assets::extract(&shards[0].path, &stage)?,
};
tokenizer::Tokenizer::from_assets(&tokenizer_dir)?;
write(stage.join("native_experts.txt"), layout.text.as_bytes())?;
if options.experts_bin {
write_experts_bin(&shards, &layout, &stage)?;
}
lossy = conversions_inexact(&stage)?;
let sources = manifest
.files
.iter()
.map(|f| json!({"name":f.name,"size":f.size,"sha256":f.sha256}))
.collect::<Vec<_>>();
write(
stage.join("source.json"),
&serde_json::to_vec_pretty(
&json!({"schema":1,"kind":"native-gguf","source_shards":sources,"lossy_conversions":lossy}),
)?,
)?;
crate::native_model::write_receipt(manifest, &stage)?;
File::open(&stage)?.sync_all()?;
if output.exists() || output.is_symlink() {
return Err("native pack destination appeared during preparation".into());
}
crate::immutable_directory::publish(&stage, output)?;
File::open(parent)?.sync_all()?;
Ok(())
})();
if result.is_err() {
let _ = fs::remove_dir_all(&stage);
}
result?;
Ok(
json!({"prepared":true,"format":"native-gguf","source_shards":shards.len(),"lossy_conversions":lossy,"gpu_validated":false}),
)
}
@@ -0,0 +1,236 @@
//! Moved out of the parent module by STRA-338: fn expert_layout, fn kind_name, fn bf16_round_nearest_even, impl Error64, fn values_of, fn stream_f32.
#[allow(unused_imports)]
use super::*;
pub(super) fn expert_layout(shards: &[Shard]) -> Result<Layout<'_>> {
let mut tensors = BTreeMap::new();
let mut layers = 0u64;
for (shard, source) in shards.iter().enumerate() {
for tensor in &source.index.tensors {
tensors.insert(tensor.name.as_str(), (shard, tensor));
if expert(&tensor.name) {
let mut parts = tensor.name.split('.');
parts.next();
let layer = parts.next().ok_or("expert layer absent")?.parse::<u64>()?;
if layer > 1023 {
return Err("unreasonable expert layer count".into());
}
layers = layers.max(layer + 1);
if !["gate", "up", "down"]
.iter()
.any(|r| tensor.name == format!("blk.{layer}.ffn_{r}_exps.weight"))
{
return Err("unsupported expert role".into());
}
}
}
}
if layers == 0 {
return Err("native pack requires expert tensors".into());
}
let (_, router) = tensors
.get("blk.0.ffn_gate_inp.weight")
.ok_or("missing expert router")?;
if router.dimensions.len() != 2 {
return Err("router must have two dimensions".into());
}
let experts = router.dimensions[1];
let mut offset = 0u64;
let mut lines = Vec::new();
let mut split_roles = false;
let mut layer_roles = Vec::new();
for layer in 0..layers {
let router_name = format!("blk.{layer}.ffn_gate_inp.weight");
let (_, router) = tensors
.get(router_name.as_str())
.ok_or("missing layer router")?;
if router.dimensions.len() != 2 || router.dimensions[1] != experts {
return Err("routers disagree on expert count".into());
}
let mut roles = Vec::new();
for role in ["gate", "up", "down"] {
let name = format!("blk.{layer}.ffn_{role}_exps.weight");
let (shard, tensor) = *tensors.get(name.as_str()).ok_or("missing expert role")?;
if tensor.dimensions.len() != 3
|| tensor.dimensions[2] != experts
|| !tensor.bytes.is_multiple_of(experts)
{
return Err("invalid expert shape".into());
}
roles.push((shard, tensor));
}
layer_roles.push([roles[0], roles[1], roles[2]]);
let gate = roles[0].1;
let up = roles[1].1;
let down = roles[2].1;
// Strata 0.1.50 `expert_layout` gives an NVFP4 expert blob a 16-byte tail {s_gate, s_up, s_down, 0} read from the
// `blk.N.ffn_*_exps.scale` tensors and forces `experts.bin`. This packer does not write the tails, and the runtime
// here does not read them: a pack without them would be silently wrong, so it is refused.
if [gate, up, down].iter().any(|t| t.kind == 40) {
return Err(format!(
"layer {layer}: NVFP4 experts need the scale tails of tools/iq_pack.py (Strata 0.1.50), which this packer does not write"
)
.into());
}
if gate.kind != up.kind
|| gate.dimensions != up.dimensions
|| gate.dimensions[0] != down.dimensions[1]
|| gate.dimensions[1] != down.dimensions[0]
|| router.dimensions[0] != gate.dimensions[0]
{
return Err("expert gate/up/down geometry mismatch".into());
}
let blob = gate
.bytes
.checked_add(up.bytes)
.and_then(|n| n.checked_add(down.bytes))
.ok_or("expert byte count overflow")?
/ experts;
let absolute = roles
.iter()
.map(|(s, t)| shards[*s].index.summary.data_start + t.offset)
.collect::<Vec<_>>();
let filenames = roles
.iter()
.map(|(s, _)| {
if *s == 0 {
String::new()
} else {
shards[*s]
.path
.file_name()
.unwrap()
.to_str()
.unwrap()
.to_owned()
}
})
.collect::<Vec<_>>();
let same = filenames.iter().all(|f| f == &filenames[0]);
split_roles |= !same;
let column = if same {
filenames[0].clone()
} else {
filenames.join(",")
};
let column = if column.is_empty() {
column
} else {
format!(" {column}")
};
lines.push(format!(
"{layer} {} {} {offset} {blob} {} {} {}{column}\n",
gate.kind, down.kind, absolute[0], absolute[1], absolute[2]
));
offset = blob
.checked_mul(experts)
.and_then(|n| offset.checked_add(n))
.ok_or("expert arena overflow")?;
}
let name = shards[0].path.file_name().unwrap().to_str().unwrap();
let header = if split_roles {
format!(
"# strata native experts v4: layer gu_type d_type offset blob_bytes gate_off up_off down_off [shard | gate,up,down] (n_expert {experts}, total {offset}; absolute offsets in {name}, or in the named shard beside it - per role where the column is gate,up,down)\n"
)
} else {
format!(
"# strata native experts v3: layer gu_type d_type offset blob_bytes gate_off up_off down_off [shard] (n_expert {experts}, total {offset}; absolute offsets in {name}, or in the named shard beside it)\n"
)
};
Ok(Layout {
text: header + &lines.concat(),
n_expert: experts,
total: offset,
layers: layer_roles,
})
}
/// GGML type names as `tools/gguf_reader.py` spells them (`GGML_TYPES`).
pub(crate) fn kind_name(kind: u32) -> &'static str {
match kind {
0 => "F32",
1 => "F16",
2 => "Q4_0",
3 => "Q4_1",
6 => "Q5_0",
7 => "Q5_1",
8 => "Q8_0",
9 => "Q8_1",
10 => "Q2_K",
11 => "Q3_K",
12 => "Q4_K",
13 => "Q5_K",
14 => "Q6_K",
15 => "Q8_K",
16 => "IQ2_XXS",
17 => "IQ2_XS",
18 => "IQ3_XXS",
19 => "IQ1_S",
20 => "IQ4_NL",
21 => "IQ3_S",
22 => "IQ2_S",
23 => "IQ4_XS",
24 => "I8",
28 => "F64",
29 => "IQ1_M",
30 => "BF16",
39 => "MXFP4",
40 => "NVFP4",
42 => "Q2_0",
_ => "unsupported",
}
}
/// ggml's `ggml_compute_fp32_to_bf16`, as `gguf.quants.BF16.quantize_blocks` spells it: NaN is quieted, everything
/// else rounds to nearest even in 64-bit arithmetic and truncates to 16 bits.
pub(crate) fn bf16_round_nearest_even(value: f32) -> u16 {
let mut n = value.to_bits();
if n & 0x7fff_ffff > 0x7f80_0000 {
n = (n & 0xffff_0000) | (64 << 16);
}
((u64::from(n) + 0x7fff + u64::from((n >> 16) & 1)) >> 16) as u16
}
impl Error64 {
pub(super) fn new() -> Self {
Self {
exact: true,
max_abs_err: 0.0,
}
}
pub(super) fn note(&mut self, converted: f32, source: f32) {
if converted != source {
self.exact = false;
}
let err = (f64::from(converted) - f64::from(source)).abs();
if err > self.max_abs_err {
self.max_abs_err = err;
}
}
}
pub(super) fn values_of(bits: &[u8]) -> impl Iterator<Item = f32> + '_ {
bits.as_chunks::<4>()
.0
.iter()
.map(|b| f32::from_le_bytes(*b))
}
/// Stream one tensor's values as F32 (floats exactly, quantized kinds through the pinned dequantizers).
pub(super) fn stream_f32(
input: &mut File,
shard: &Shard,
tensor: &gguf::TensorInfo,
mut each: impl FnMut(&[u8], &[u8]) -> std::result::Result<(), String>,
) -> Result<()> {
gguf_f32_stream::visit(
input,
shard.index.summary.data_start + tensor.offset,
tensor.kind,
tensor.bytes,
&mut each,
)?;
Ok(())
}
+133
View File
@@ -0,0 +1,133 @@
//! Moved out of the parent module by STRA-338: fn safe_name, fn align, fn form, fn expert, fn shards.
#[allow(unused_imports)]
use super::*;
pub(super) fn safe_name(name: &str) -> bool {
!name.is_empty()
&& name
.bytes()
.all(|b| b.is_ascii_alphanumeric() || b"._-".contains(&b))
}
pub(super) fn align(bytes: u64) -> Result<u64> {
Ok(bytes.checked_add(63).ok_or("native pack size overflow")? / 64 * 64)
}
pub(super) fn form(name: &str) -> Option<u32> {
let name = if let Some(rest) = name.strip_prefix("blk.") {
rest.split_once('.').map_or(name, |(_, suffix)| suffix)
} else {
name
};
match name {
"ffn_gate_inp.weight"
| "ffn_gate_inp_shexp.weight"
| "hc_attn_down.weight"
| "hc_attn_up.weight"
| "hc_attn_inject.weight"
| "hc_ffn_down.weight"
| "hc_ffn_up.weight"
| "hc_ffn_inject.weight"
| "output_hc_down.weight"
| "output_hc_up.weight"
| "indexer.k_proj.weight"
| "indexer.q_proj.weight"
| "ssm_alpha.weight"
| "ssm_beta.weight"
| "ple_key.weight"
| "ple_value.weight" => Some(30),
"ple_conv1d.weight" => Some(1),
"attn_q_norm.weight"
| "attn_k_norm.weight"
| "hc_attn_norm.weight"
| "hc_ffn_norm.weight"
| "output_hc_norm.weight"
| "indexer.q_norm.weight"
| "indexer.k_norm.weight"
| "ple_norm_conv.weight"
| "ple_norm_key.weight"
| "ple_norm_query.weight"
| "ssm_a"
| "ssm_conv1d.weight"
| "ssm_dt.bias"
| "ssm_norm.weight" => Some(0),
_ => None,
}
}
pub(super) fn expert(name: &str) -> bool {
name.starts_with("blk.") && name.ends_with("_exps.weight")
}
pub(super) fn shards(manifest: &model::Manifest, source: &Path) -> Result<Vec<Shard>> {
let mut shards = Vec::new();
let mut names = HashSet::new();
for file in &manifest.files {
if !safe_name(&file.name) || !file.name.ends_with(".gguf") {
return Err("native pack manifest must contain GGUF shard filenames only".into());
}
let path = source.join(&file.name);
let index = gguf::tensor_index(&path)?;
for tensor in &index.tensors {
if !safe_name(&tensor.name) || !names.insert(tensor.name.clone()) {
return Err("invalid or duplicate tensor name across GGUF shards".into());
}
}
shards.push(Shard { path, index });
}
if shards.is_empty() {
return Err("native pack has no source shards".into());
}
shards.sort_by_key(|s| s.index.summary.split_no.unwrap_or(0));
let first = &shards[0].index.summary;
if first.architecture.as_deref() != Some("qwen4exp") {
return Err("native pack preparation currently requires qwen4exp architecture".into());
}
let count = shards.len() as u64;
let total = shards
.iter()
.try_fold(0u64, |sum, s| sum.checked_add(s.index.summary.tensors))
.ok_or("split tensor count overflow")?;
if count == 1 && (first.split_count.unwrap_or(1) != 1 || first.split_no.unwrap_or(0) != 0) {
return Err("manifest is missing GGUF shards".into());
}
let filename = shards[0].path.file_name().unwrap().to_str().unwrap();
let suffix = format!("-00001-of-{count:05}.gguf");
let prefix = if count > 1 {
Some(
filename
.strip_suffix(&suffix)
.ok_or("first shard filename does not match split count")?,
)
} else {
None
};
for (number, shard) in shards.iter().enumerate() {
let summary = &shard.index.summary;
if count > 1
&& (summary.split_no != Some(number as u64)
|| summary.split_count != Some(count)
|| summary.split_tensors_count != first.split_tensors_count)
{
return Err("inconsistent GGUF split identity".into());
}
if summary.split_tensors_count.is_some_and(|n| n != total) {
return Err("GGUF split tensor total does not match manifest shards".into());
}
if summary
.architecture
.as_ref()
.is_some_and(|arch| arch != "qwen4exp")
{
return Err("GGUF shard architecture mismatch".into());
}
if let Some(prefix) = prefix {
let expected = format!("{prefix}-{:05}-of-{count:05}.gguf", number + 1);
if shard.path.file_name().unwrap() != expected.as_str() {
return Err("GGUF shard names do not form a discoverable family".into());
}
}
}
Ok(shards)
}
@@ -0,0 +1,32 @@
//! Moved out of the parent module by STRA-338: fn same_bytes.
#[allow(unused_imports)]
use super::*;
pub(super) fn same_bytes(
a: &mut File,
a_at: u64,
b: &mut File,
b_at: u64,
a_len: u64,
b_len: u64,
) -> Result<bool> {
if a_len != b_len {
return Ok(false);
}
let mut left = vec![0u8; 1 << 20];
let mut right = vec![0u8; 1 << 20];
let mut done = 0u64;
while done < a_len {
let n = (a_len - done).min(left.len() as u64) as usize;
a.seek(SeekFrom::Start(a_at + done))?;
a.read_exact(&mut left[..n])?;
b.seek(SeekFrom::Start(b_at + done))?;
b.read_exact(&mut right[..n])?;
if left[..n] != right[..n] {
return Ok(false);
}
done += n as u64;
}
Ok(true)
}
+247
View File
@@ -0,0 +1,247 @@
//! Unit tests of this module (moved out of the file by STRA-338; the test ids are unchanged).
use super::*;
/// One layer of expert tensors of `kind`, the way a GGUF index lists them (no file behind it).
fn one_layer(kind: u32) -> Vec<Shard> {
let tensor = |name: &str, dimensions: Vec<u64>, bytes: u64, kind: u32| gguf::TensorInfo {
name: name.to_owned(),
dimensions,
kind,
offset: 0,
bytes,
};
vec![Shard {
path: PathBuf::from("m.gguf"),
index: gguf::TensorIndex {
summary: gguf::Summary {
tensors: 4,
metadata: 0,
architecture: None,
split_no: None,
split_count: None,
split_tensors_count: None,
data_start: 0,
file_size: 0,
types: Default::default(),
},
tensors: vec![
tensor("blk.0.ffn_gate_inp.weight", vec![64, 4], 1024, 0),
tensor("blk.0.ffn_gate_exps.weight", vec![64, 64, 4], 4096, kind),
tensor("blk.0.ffn_up_exps.weight", vec![64, 64, 4], 4096, kind),
tensor("blk.0.ffn_down_exps.weight", vec![64, 64, 4], 4096, kind),
],
},
}]
}
/// Strata 0.1.50 packs NVFP4 experts with a scale tail this packer does not write: it refuses them instead of writing a pack
/// whose experts the engine would read without their scales.
#[test]
fn nvfp4_experts_are_refused_and_other_experts_are_laid_out() {
let error = expert_layout(&one_layer(40))
.err()
.expect("NVFP4 is refused");
assert!(error.to_string().contains("NVFP4 experts"), "{error}");
let shards = one_layer(21);
let layout = expert_layout(&shards).expect("IQ3_S experts");
assert_eq!(layout.n_expert, 4);
assert!(layout.text.starts_with("# strata native experts v3:"));
}
/// `iq_pack.py` `NATIVE_PLE_KEY` = {Q2_0, Q8_0, IQ3_XXS, IQ4_XS} (Strata 0.1.50, #381); any other quantized key is converted.
#[test]
fn the_native_ple_key_encodings_are_the_originals() {
for (kind, native) in [
(42, true),
(8, true),
(18, true),
(23, true),
(21, false),
(14, false),
(12, false),
(16, false),
] {
assert_eq!(native_ple_key(kind), native, "kind {kind}");
}
}
/// Numpy (`astype(float16)`) and gguf-py (`BF16.quantize_blocks`) answers for 4096 f32 bit patterns, from
/// `scripts/offline/gen_goldens.py`. The packer's F32 -> F16 / BF16 helpers must match bit for bit.
#[test]
fn f16_and_bf16_rounding_match_numpy_and_gguf_py() {
let vectors = include_bytes!("../../tests/fixtures/offline/f16_bf16_vectors.golden");
assert_eq!(vectors.len() % 8, 0);
let mut checked = 0;
for record in vectors.as_chunks::<8>().0 {
let bits = u32::from_le_bytes(record[0..4].try_into().unwrap());
let f16 = u16::from_le_bytes(record[4..6].try_into().unwrap());
let bf16 = u16::from_le_bytes(record[6..8].try_into().unwrap());
let value = f32::from_bits(bits);
if value.is_finite() {
// the packer refuses non-finite inputs before rounding; NaN payloads are not compared
assert_eq!(
kar_codec::f32_to_f16_bits(value),
f16,
"f16 of {bits:#010x}"
);
}
assert_eq!(bf16_round_nearest_even(value), bf16, "bf16 of {bits:#010x}");
checked += 1;
}
assert!(checked >= 4000);
}
struct Golden {
header: String,
name: String,
experts: u64,
total: u64,
rows: Vec<Vec<String>>,
}
fn parse_golden(text: &str) -> Golden {
let header = text.lines().next().unwrap().to_owned();
let after = |marker: &str| {
header
.split(marker)
.nth(1)
.unwrap()
.split(|c: char| !c.is_ascii_alphanumeric() && c != '_' && c != '.' && c != '-')
.next()
.unwrap()
.to_owned()
};
Golden {
name: after("offsets in "),
experts: after("n_expert ").parse().unwrap(),
total: after("total ").parse().unwrap(),
rows: text
.lines()
.skip(1)
.map(|l| l.split(' ').map(str::to_owned).collect())
.collect(),
header,
}
}
/// Rebuild the tensor directories that produce a real layer table, then run the packer's own layout code.
/// Gate/up/down element counts follow from the blob size and the two quantization geometries; the hidden size
/// is the model's 2560.
fn shards_for(golden: &Golden) -> Vec<Shard> {
const HIDDEN: u64 = 2560;
let mut names = vec![golden.name.clone()];
let mut tensors: Vec<Vec<gguf::TensorInfo>> = vec![Vec::new()];
let at = |name: &str, names: &mut Vec<String>, tensors: &mut Vec<Vec<gguf::TensorInfo>>| {
if let Some(i) = names.iter().position(|n| n == name) {
return i;
}
names.push(name.to_owned());
tensors.push(Vec::new());
names.len() - 1
};
for row in &golden.rows {
let layer: u64 = row[0].parse().unwrap();
let (gu, d): (u32, u32) = (row[1].parse().unwrap(), row[2].parse().unwrap());
let blob: u64 = row[4].parse().unwrap();
let offsets: Vec<u64> = row[5..8].iter().map(|v| v.parse().unwrap()).collect();
let column = row.get(8).cloned().unwrap_or_default();
let files: Vec<String> = if column.contains(',') {
column.split(',').map(str::to_owned).collect()
} else {
vec![column; 3]
};
let (ge, gb) = gguf::block_geometry(gu).unwrap();
let (de, db) = gguf::block_geometry(d).unwrap();
// blob = 2 * X * gb/ge + X * db/de for X = HIDDEN * FF elements per expert
let numerator = blob * ge * de;
let denominator = 2 * gb * de + db * ge;
assert_eq!(numerator % denominator, 0, "layer {layer}");
let x = numerator / denominator;
assert_eq!(x % HIDDEN, 0);
let ff = x / HIDDEN;
let shard = |i: usize, names: &mut Vec<String>, t: &mut Vec<Vec<gguf::TensorInfo>>| {
if files[i].is_empty() {
0
} else {
at(&files[i], names, t)
}
};
let experts = golden.experts;
let roles = [
("gate", gu, vec![HIDDEN, ff, experts], x / ge * gb * experts),
("up", gu, vec![HIDDEN, ff, experts], x / ge * gb * experts),
("down", d, vec![ff, HIDDEN, experts], x / de * db * experts),
];
let router = gguf::TensorInfo {
name: format!("blk.{layer}.ffn_gate_inp.weight"),
dimensions: vec![HIDDEN, experts],
kind: 0,
offset: 0,
bytes: HIDDEN * experts * 4,
};
tensors[0].push(router);
for (i, (role, kind, dimensions, bytes)) in roles.into_iter().enumerate() {
let s = shard(i, &mut names, &mut tensors);
tensors[s].push(gguf::TensorInfo {
name: format!("blk.{layer}.ffn_{role}_exps.weight"),
dimensions,
kind,
offset: offsets[i],
bytes,
});
}
}
names
.into_iter()
.zip(tensors)
.map(|(name, tensors)| Shard {
path: PathBuf::from(name),
index: gguf::TensorIndex {
summary: gguf::Summary {
tensors: tensors.len() as u64,
metadata: 0,
architecture: Some("qwen4exp".into()),
split_no: None,
split_count: None,
split_tensors_count: None,
data_start: 0,
file_size: 0,
types: BTreeMap::new(),
},
tensors,
},
})
.collect()
}
/// The six real per-layer expert tables shipped with Strata (IQ3_S, IQ3_XXS, IQ2_XS, Q2_0 packs, the coder
/// IQ1_M pack, and Swift's IQ2_XS whose layers 13-47 live in the second shard): the Rust layout reproduces
/// every row byte for byte. The v2 files predate the shard column; their header wording differs, their rows
/// and totals do not.
#[test]
fn real_golden_expert_tables_are_reproduced() {
let goldens = [
include_str!("../../../engine/strata/tests/data/native_experts/iq3_s.txt"),
include_str!("../../../engine/strata/tests/data/native_experts/iq3_xxs.txt"),
include_str!("../../../engine/strata/tests/data/native_experts/iq2_xs.txt"),
include_str!("../../../engine/strata/tests/data/native_experts/q2_0.txt"),
include_str!("../../../engine/strata/tests/data/native_experts/coder-iq1_m.txt"),
include_str!("../../../engine/strata/tests/data/native_experts/swift-iq2_xs.txt"),
];
for text in goldens {
let golden = parse_golden(text);
let shards = shards_for(&golden);
let layout = expert_layout(&shards).unwrap();
assert_eq!(layout.n_expert, golden.experts);
assert_eq!(layout.total, golden.total, "{}", golden.name);
let produced = layout.text.lines().skip(1).collect::<Vec<_>>();
let wanted = text.lines().skip(1).collect::<Vec<_>>();
assert_eq!(produced, wanted, "{}", golden.name);
if golden.header.contains("native experts v3")
|| golden.header.contains("native experts v4")
{
assert_eq!(layout.text, text, "{}", golden.name);
}
}
}
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,244 @@
//! Moved out of the parent module by STRA-338: fn encode_preview_tensor, fn verify_iq3, fn verify_mixed, fn verify_sharded, fn verify_sharded_streamed, fn verify_sharded_streamed_ple ....
#[allow(unused_imports)]
use super::*;
pub(super) fn encode_preview_tensor(
name: &str,
dimensions: &[u64],
weights: &[f32],
source_digest: [u8; 32],
source_offset: u64,
section_path: &Path,
levels: u8,
) -> Result<(PreparedTensor, f64), String> {
let normalized = kar_codec::normalize_for_calibration(weights, 32)?;
let calibration = kar_codec::fit_topdown(&normalized.values, levels)?;
let encoded = kar_codec::encode_with_boundaries(weights, 32, &calibration.boundaries, levels)?;
let plane_refs = encoded.planes.iter().map(Vec::as_slice).collect::<Vec<_>>();
let mut decoded = vec![0.0f32; weights.len()];
kar_codec::decode_range(
&encoded.scales,
&calibration.books[usize::from(levels) - 1],
&plane_refs,
32,
0,
&mut decoded,
)?;
let (error_sum, reference_sum) = weights.iter().zip(&decoded).fold(
(0.0f64, 0.0f64),
|(error_sum, reference_sum), (original, rebuilt)| {
let delta = f64::from(*original) - f64::from(*rebuilt);
(
error_sum + delta * delta,
reference_sum + f64::from(*original).powi(2),
)
},
);
let relative_l2 = if reference_sum == 0.0 {
error_sum.sqrt()
} else {
(error_sum / reference_sum).sqrt()
};
let books = calibration
.books
.iter()
.map(Vec::as_slice)
.collect::<Vec<_>>();
let coded_tensor = kar_writer::Tensor {
name,
dims: dimensions,
source_dtype: 0,
source_digest,
source_offset,
data: kar_writer::TensorData::Nested {
group: 32,
nesting: 0,
planes_min: 1,
planes_max: levels,
scales: &encoded.scales,
books: &books,
planes: &plane_refs,
},
};
let section = kar_writer::write_nested_section(section_path, &coded_tensor)?;
Ok((
PreparedTensor {
name: name.to_owned(),
dims: dimensions.to_vec(),
source_digest,
source_offset,
section_path: section_path.to_path_buf(),
section_bytes: section.bytes,
section_digest: section.digest,
},
relative_l2,
))
}
pub fn verify_iq3(source_path: &Path, archive_path: &Path) -> Result<kar::Summary, String> {
verify_derived(source_path, archive_path, PreviewKind::Iq3)
}
pub fn verify_mixed(source_path: &Path, archive_path: &Path) -> Result<kar::Summary, String> {
verify_derived(source_path, archive_path, PreviewKind::Mixed)
}
pub fn verify_sharded(
manifest: &Manifest,
source_dir: &Path,
archive_path: &Path,
) -> Result<kar::Summary, String> {
verify_sharded_inner(
manifest,
source_dir,
archive_path,
None,
stream_parts::MAX_PART_ELEMENTS,
None,
)
}
pub fn verify_sharded_streamed(
manifest: &Manifest,
source_dir: &Path,
archive_path: &Path,
levels: u8,
) -> Result<kar::Summary, String> {
if !(1..=8).contains(&levels) {
return Err("streamed sharded verification requires 1..=8 KAR levels".into());
}
verify_sharded_inner(
manifest,
source_dir,
archive_path,
Some(levels),
stream_parts::MAX_PART_ELEMENTS,
None,
)
}
pub fn verify_sharded_streamed_ple(
manifest: &Manifest,
source_dir: &Path,
archive_path: &Path,
levels: u8,
ple_part_elements: u64,
) -> Result<kar::Summary, String> {
stream_parts::validate_ple_limit(ple_part_elements)?;
if !(1..=8).contains(&levels) {
return Err("streamed sharded verification requires 1..=8 KAR levels".into());
}
verify_sharded_inner(
manifest,
source_dir,
archive_path,
Some(levels),
stream_parts::MAX_PART_ELEMENTS,
Some(ple_part_elements),
)
}
pub(super) fn verify_sharded_inner(
manifest: &Manifest,
source_dir: &Path,
archive_path: &Path,
streamed_levels: Option<u8>,
max_part_elements: u64,
ple_part_elements: Option<u64>,
) -> Result<kar::Summary, String> {
let identity = derived_mixed::fingerprint_shards(manifest, source_dir)?;
let archive_parts = if streamed_levels.is_some() {
Some(if let Some(limit) = ple_part_elements {
stream_parts::plan_shards_with_ple_limit(&identity, source_dir, limit)?
} else {
stream_parts::plan_shards_with_limit(&identity, source_dir, max_part_elements)?
})
} else {
None
};
let (summary, sources) = kar::verify_with_sources(archive_path)?;
let expected_count = archive_parts
.as_ref()
.map_or(identity.tensors.len(), |parts| {
parts.iter().map(Vec::len).sum()
});
if summary.source_digest != identity.derived_sha256
|| summary.source_bytes != identity.derived_bytes
|| summary.source_total_elements.checked_mul(4) != Some(identity.derived_bytes)
|| sources.len() != expected_count
{
return Err("KAR header differs from sharded derived source".into());
}
if let Some(parts) = &archive_parts {
for (record, part) in sources.iter().zip(parts.iter().flatten()) {
let record_bytes = record
.dimensions
.iter()
.try_fold(4u64, |size, dim| size.checked_mul(*dim))
.ok_or("KAR tensor source byte count overflow")?;
if record.name != part.name
|| record.dimensions != part.dimensions
|| record.dtype != 0
|| record.digest != part.f32_sha256
|| record.offset != part.derived_offset
|| record_bytes != part.derived_bytes
{
return Err(format!("{}: sharded KAR part source mismatch", part.name));
}
}
} else {
for (record, tensor) in sources.iter().zip(&identity.tensors) {
let record_bytes = record
.dimensions
.iter()
.try_fold(4u64, |size, dim| size.checked_mul(*dim))
.ok_or("KAR tensor source byte count overflow")?;
if record.name != tensor.name
|| record.dtype != 0
|| record.digest != tensor.f32_sha256
|| record.offset != tensor.derived_offset
|| record_bytes != tensor.derived_bytes
{
return Err(format!(
"{}: sharded KAR tensor source mismatch",
tensor.name
));
}
}
}
let archive_digest = hash_file(archive_path)?;
let provenance = provenance_path(archive_path)?;
let file = File::open(provenance).map_err(|error| error.to_string())?;
let recorded: serde_json::Value =
serde_json::from_reader(file).map_err(|error| error.to_string())?;
let mut expected = sharded_provenance_value(&identity, archive_digest);
if let Some(levels) = streamed_levels {
if summary.max_planes > levels {
return Err("KAR stream levels exceed declared preparation level".into());
}
expected["schema"] = serde_json::json!(if ple_part_elements.is_some() {
"strata-next/sharded-stream-provenance-v5"
} else {
"strata-next/sharded-stream-provenance-v4"
});
expected["derivation"] =
serde_json::json!("strata-next/gguf-shards-to-f32-le-v4:ggml-3cf03257");
expected["levels"] = serde_json::json!(levels);
expected["sampling"] = serde_json::json!("digest-seeded-65536-normalized-v1");
expected["partitioned_tensors"] = partitioned_provenance(
archive_parts
.as_ref()
.ok_or("missing streamed KAR part plan")?,
);
if let Some(limit) = ple_part_elements {
expected["ple_part_elements"] = serde_json::json!(limit);
}
}
if recorded != expected {
return Err(
"sharded provenance differs from source, archive, or preparation policy".into(),
);
}
Ok(summary)
}
@@ -0,0 +1,102 @@
//! Moved out of the parent module by STRA-338: fn minimum_part_payload_bytes, impl DerivedIdentity, impl Drop_for_StagingDir, fn prepare_f32, fn prepare_iq3, fn prepare_mixed.
#[allow(unused_imports)]
use super::*;
pub(crate) fn minimum_part_payload_bytes(derived_bytes: u64, levels: u8) -> Result<u64, String> {
if !derived_bytes.is_multiple_of(4) || !(1..=8).contains(&levels) {
return Err("invalid KAR part F32 byte count or level".into());
}
let plane_bytes = (derived_bytes / 4)
.div_ceil(32)
.checked_mul(4 * u64::from(levels))
.ok_or("KAR minimum payload size overflow")?;
Ok(plane_bytes.min(derived_bytes))
}
impl DerivedIdentity {
pub(super) fn gguf_digest(&self) -> [u8; 32] {
match self {
Self::Iq3(identity) => identity.gguf_sha256,
Self::Mixed(identity) => identity.gguf_sha256,
}
}
pub(super) fn derived_digest(&self) -> [u8; 32] {
match self {
Self::Iq3(identity) => identity.derived_sha256,
Self::Mixed(identity) => identity.derived_sha256,
}
}
pub(super) fn derived_bytes(&self) -> u64 {
match self {
Self::Iq3(identity) => identity.derived_bytes,
Self::Mixed(identity) => identity.derived_bytes,
}
}
pub(super) fn tensor(&self, number: usize) -> DerivedTensorRef<'_> {
match self {
Self::Iq3(identity) => {
let tensor = &identity.tensors[number];
DerivedTensorRef {
name: &tensor.name,
source_kind: 21,
source_digest: &tensor.iq3_sha256,
f32_digest: &tensor.f32_sha256,
offset: tensor.derived_offset,
bytes: tensor.derived_bytes,
}
}
Self::Mixed(identity) => {
let tensor = &identity.tensors[number];
DerivedTensorRef {
name: &tensor.name,
source_kind: tensor.source_kind,
source_digest: &tensor.source_sha256,
f32_digest: &tensor.f32_sha256,
offset: tensor.derived_offset,
bytes: tensor.derived_bytes,
}
}
}
}
pub(super) fn tensor_count(&self) -> usize {
match self {
Self::Iq3(identity) => identity.tensors.len(),
Self::Mixed(identity) => identity.tensors.len(),
}
}
}
impl Drop for StagingDir {
fn drop(&mut self) {
let _ = fs::remove_dir_all(&self.0);
}
}
pub fn prepare_f32(
source_path: &Path,
destination: &Path,
levels: u8,
) -> Result<PreviewSummary, String> {
prepare(source_path, destination, levels, PreviewKind::F32)
}
pub fn prepare_iq3(
source_path: &Path,
destination: &Path,
levels: u8,
) -> Result<PreviewSummary, String> {
prepare(source_path, destination, levels, PreviewKind::Iq3)
}
pub fn prepare_mixed(
source_path: &Path,
destination: &Path,
levels: u8,
) -> Result<PreviewSummary, String> {
prepare(source_path, destination, levels, PreviewKind::Mixed)
}
@@ -0,0 +1,213 @@
//! Moved out of the parent module by STRA-338: fn prepare.
#[allow(unused_imports)]
use super::*;
pub(super) fn prepare(
source_path: &Path,
destination: &Path,
levels: u8,
kind: PreviewKind,
) -> Result<PreviewSummary, String> {
if !(1..=8).contains(&levels) {
return Err("F32 preview requires 1..=8 KAR levels".into());
}
let index = gguf::tensor_index(source_path).map_err(|error| error.to_string())?;
if index.summary.file_size > MAX_SOURCE_BYTES
|| index.tensors.is_empty()
|| index.tensors.len() > MAX_TENSORS
{
return Err("F32 preview exceeds its source or tensor-count limit".into());
}
let architecture = index
.summary
.architecture
.as_deref()
.ok_or("GGUF source has no architecture")?;
let filename = source_path
.file_name()
.ok_or("GGUF source has no file name")?
.to_string_lossy();
let derived_identity = match kind {
PreviewKind::F32 => None,
PreviewKind::Iq3 => Some(DerivedIdentity::Iq3(derived_iq3::fingerprint(source_path)?)),
PreviewKind::Mixed => Some(DerivedIdentity::Mixed(derived_mixed::fingerprint(
source_path,
)?)),
};
let source_name = match kind {
PreviewKind::F32 => filename.to_string(),
PreviewKind::Iq3 => format!("{filename}#derived-f32-le-v1"),
PreviewKind::Mixed => format!("{filename}#mixed-derived-f32-le-v1"),
};
let original_digest = match &derived_identity {
Some(identity) => identity.gguf_digest(),
None => hash_file(source_path)?,
};
let staging_name = format!(
"{}.parts-{}",
destination
.file_name()
.ok_or("KAR destination has no file name")?
.to_string_lossy(),
std::process::id()
);
let staging_path = destination.with_file_name(staging_name);
fs::create_dir(&staging_path).map_err(|error| error.to_string())?;
let staging = StagingDir(staging_path);
let mut source_file = File::open(source_path).map_err(|error| error.to_string())?;
let mut total_elements = 0u64;
let mut maximum_relative_l2 = 0.0f64;
let mut prepared = Vec::with_capacity(index.tensors.len());
for (number, tensor) in index.tensors.iter().enumerate() {
let supported = match kind {
PreviewKind::F32 => tensor.kind == 0,
PreviewKind::Iq3 => tensor.kind == 21,
PreviewKind::Mixed => matches!(tensor.kind, 0 | 1 | 21 | 30),
};
if !supported || tensor.dimensions.len() > 4 {
return Err(format!(
"{}: preview supports only {} tensors with up to four dimensions",
tensor.name,
match kind {
PreviewKind::F32 => "F32",
PreviewKind::Iq3 => "IQ3_S",
PreviewKind::Mixed => "F32/F16/BF16/IQ3_S",
}
));
}
let elements = tensor
.dimensions
.iter()
.try_fold(1u64, |product, dim| product.checked_mul(*dim))
.ok_or("GGUF tensor element count overflow")?;
total_elements = total_elements
.checked_add(elements)
.ok_or("GGUF model element count overflow")?;
if elements > MAX_TENSOR_ELEMENTS {
return Err("F32 preview exceeds its per-tensor element limit".into());
}
let absolute = index
.summary
.data_start
.checked_add(tensor.offset)
.ok_or("GGUF tensor offset overflow")?;
source_file
.seek(SeekFrom::Start(absolute))
.map_err(|error| error.to_string())?;
let mut raw = vec![0u8; tensor.bytes as usize];
source_file
.read_exact(&mut raw)
.map_err(|error| error.to_string())?;
let (weights, tensor_digest, source_offset) = if let Some(identity) = &derived_identity {
let derived = identity.tensor(number);
if derived.name != tensor.name
|| derived.source_kind != tensor.kind
|| Sha256::digest(&raw).as_slice() != derived.source_digest
{
return Err("GGUF tensor differs from derived source identity".into());
}
let weights = decode_source_tensor(tensor.kind, &raw, elements as usize)?;
let mut digest = Sha256::new();
for value in &weights {
digest.update(value.to_le_bytes());
}
if digest.finalize().as_slice() != derived.f32_digest || derived.bytes != elements * 4 {
return Err("decoded F32 tensor differs from derived source identity".into());
}
(weights, *derived.f32_digest, derived.offset)
} else {
let digest = Sha256::digest(&raw).into();
let weights = raw
.as_chunks::<4>()
.0
.iter()
.map(|chunk| f32::from_le_bytes(*chunk))
.collect::<Vec<_>>();
(weights, digest, absolute)
};
drop(raw);
let section_path = staging.0.join(format!("{number:06}.section"));
let (coded, relative_l2) = encode_preview_tensor(
&tensor.name,
&tensor.dimensions,
&weights,
tensor_digest,
source_offset,
&section_path,
levels,
)?;
maximum_relative_l2 = maximum_relative_l2.max(relative_l2);
prepared.push(coded);
}
if source_file
.metadata()
.map_err(|error| error.to_string())?
.len()
!= index.summary.file_size
|| hash_file(source_path)? != original_digest
{
return Err("GGUF source changed during F32 preparation".into());
}
let tensors = prepared
.iter()
.map(|tensor| kar_writer::Tensor {
name: &tensor.name,
dims: &tensor.dims,
source_dtype: 0,
source_digest: tensor.source_digest,
source_offset: tensor.source_offset,
data: kar_writer::TensorData::NestedFile {
group: 32,
nesting: 0,
planes_min: 1,
planes_max: levels,
levels,
path: &tensor.section_path,
offset: 0,
bytes: tensor.section_bytes,
digest: tensor.section_digest,
},
})
.collect::<Vec<_>>();
let builder = format!(
"strata-next/experimental-{}-topdown-v1:g32:l{levels}:sample-all",
match kind {
PreviewKind::F32 => "f32",
PreviewKind::Iq3 => "iq3-derived-f32",
PreviewKind::Mixed => "mixed-derived-f32",
}
);
let (source_digest, source_bytes) = derived_identity
.as_ref()
.map(|identity| (identity.derived_digest(), identity.derived_bytes()))
.unwrap_or((original_digest, index.summary.file_size));
let source = kar_writer::SourceIdentity {
name: &source_name,
architecture,
builder: &builder,
digest: source_digest,
total_elements,
bytes: source_bytes,
};
let archive = kar_writer::write_archive(destination, &source, &tensors)?;
let archive_digest = hash_file(destination)?;
let provenance_path = if let Some(identity) = derived_identity {
let path = provenance_path(destination)?;
let manifest = provenance_value(&identity, archive_digest);
if let Err(error) = write_provenance(&path, &manifest) {
let _ = fs::remove_file(destination);
return Err(error);
}
Some(path)
} else {
None
};
Ok(PreviewSummary {
archive,
archive_digest,
maximum_relative_l2,
tensor_distortions: Vec::new(),
provenance_path,
})
}
@@ -0,0 +1,233 @@
//! Moved out of the parent module by STRA-338: fn prepare_sharded, fn prepare_sharded_streamed, fn prepare_sharded_streamed_ple, fn prepare_sharded_streamed_with_limit.
#[allow(unused_imports)]
use super::*;
pub fn prepare_sharded(
manifest: &Manifest,
source_dir: &Path,
destination: &Path,
levels: u8,
) -> Result<PreviewSummary, String> {
if !(1..=8).contains(&levels) {
return Err("sharded preview requires 1..=8 KAR levels".into());
}
let total_source_bytes = manifest
.files
.iter()
.try_fold(0u64, |sum, file| sum.checked_add(file.size))
.ok_or("sharded GGUF source byte count overflow")?;
if total_source_bytes > MAX_SOURCE_BYTES {
return Err("sharded preview exceeds its 64 MiB source limit".into());
}
let identity = derived_mixed::fingerprint_shards(manifest, source_dir)?;
if identity.tensors.is_empty() || identity.tensors.len() > MAX_TENSORS {
return Err("sharded preview exceeds its tensor-count limit".into());
}
let staging_path = destination.with_file_name(format!(
"{}.parts-{}",
destination
.file_name()
.ok_or("KAR destination has no file name")?
.to_string_lossy(),
std::process::id()
));
fs::create_dir(&staging_path).map_err(|error| error.to_string())?;
let staging = StagingDir(staging_path);
let mut architecture = None::<String>;
let mut maximum_relative_l2 = 0.0f64;
let mut prepared = Vec::with_capacity(identity.tensors.len());
let mut number = 0usize;
for shard in &identity.shards {
let path = source_dir.join(&shard.name);
let index = gguf::tensor_index(&path).map_err(|error| error.to_string())?;
if let Some(shard_architecture) = index.summary.architecture.as_deref() {
if architecture
.as_deref()
.is_some_and(|expected| expected != shard_architecture)
{
return Err("GGUF shard architectures differ".into());
}
architecture.get_or_insert_with(|| shard_architecture.to_owned());
}
if index.tensors.len() != shard.tensor_count || index.summary.file_size != shard.gguf_bytes
{
return Err("GGUF shard changed after identity derivation".into());
}
let mut source = File::open(&path).map_err(|error| error.to_string())?;
for tensor in &index.tensors {
if tensor.dimensions.len() > 4 {
return Err(format!(
"{}: KAR preview supports up to four dimensions",
tensor.name
));
}
let elements = tensor
.dimensions
.iter()
.try_fold(1u64, |count, dim| count.checked_mul(*dim))
.ok_or("GGUF tensor element count overflow")?;
if elements > MAX_TENSOR_ELEMENTS {
return Err("sharded preview exceeds its per-tensor element limit".into());
}
let derived = &identity.tensors[number];
let absolute = index
.summary
.data_start
.checked_add(tensor.offset)
.ok_or("GGUF tensor offset overflow")?;
source
.seek(SeekFrom::Start(absolute))
.map_err(|error| error.to_string())?;
let mut raw = vec![0u8; tensor.bytes as usize];
source
.read_exact(&mut raw)
.map_err(|error| error.to_string())?;
if derived.name != tensor.name
|| derived.source_kind != tensor.kind
|| Sha256::digest(&raw).as_slice() != derived.source_sha256
|| derived.derived_bytes != elements * 4
{
return Err(format!(
"{}: sharded source tensor identity mismatch",
tensor.name
));
}
let weights = decode_source_tensor(tensor.kind, &raw, elements as usize)?;
let mut f32_digest = Sha256::new();
for value in &weights {
f32_digest.update(value.to_le_bytes());
}
if f32_digest.finalize().as_slice() != derived.f32_sha256 {
return Err(format!(
"{}: sharded derived F32 tensor mismatch",
tensor.name
));
}
let section_path = staging.0.join(format!("{number:06}.section"));
let (coded, relative_l2) = encode_preview_tensor(
&tensor.name,
&tensor.dimensions,
&weights,
derived.f32_sha256,
derived.derived_offset,
&section_path,
levels,
)?;
maximum_relative_l2 = maximum_relative_l2.max(relative_l2);
prepared.push(coded);
number += 1;
}
if source.metadata().map_err(|error| error.to_string())?.len() != shard.gguf_bytes
|| hash_file(&path)? != shard.gguf_sha256
{
return Err(format!(
"{}: GGUF shard changed during preparation",
shard.name
));
}
}
let tensors = prepared
.iter()
.map(|tensor| kar_writer::Tensor {
name: &tensor.name,
dims: &tensor.dims,
source_dtype: 0,
source_digest: tensor.source_digest,
source_offset: tensor.source_offset,
data: kar_writer::TensorData::NestedFile {
group: 32,
nesting: 0,
planes_min: 1,
planes_max: levels,
levels,
path: &tensor.section_path,
offset: 0,
bytes: tensor.section_bytes,
digest: tensor.section_digest,
},
})
.collect::<Vec<_>>();
let builder =
format!("strata-next/experimental-sharded-derived-f32-topdown-v1:g32:l{levels}:sample-all");
let source = kar_writer::SourceIdentity {
name: "gguf-shards#derived-f32-le-v1",
architecture: architecture
.as_deref()
.ok_or("GGUF shards have no architecture")?,
builder: &builder,
digest: identity.derived_sha256,
total_elements: identity.derived_bytes / 4,
bytes: identity.derived_bytes,
};
let archive = kar_writer::write_archive(destination, &source, &tensors)?;
let archive_digest = hash_file(destination)?;
let provenance_path = provenance_path(destination)?;
if let Err(error) = write_provenance(
&provenance_path,
&sharded_provenance_value(&identity, archive_digest),
) {
let _ = fs::remove_file(destination);
return Err(error);
}
Ok(PreviewSummary {
archive,
archive_digest,
maximum_relative_l2,
tensor_distortions: Vec::new(),
provenance_path: Some(provenance_path),
})
}
/// Experimental full-size preparation. Tensor payloads are decoded, sampled,
/// and encoded in bounded chunks; each source shard is pinned by the manifest.
/// This path does not grant a model-quality or serving approval.
pub fn prepare_sharded_streamed(
manifest: &Manifest,
source_dir: &Path,
destination: &Path,
levels: u8,
) -> Result<PreviewSummary, String> {
prepare_sharded_streamed_with_limit(
manifest,
source_dir,
destination,
levels,
stream_parts::MAX_PART_ELEMENTS,
)
}
pub fn prepare_sharded_streamed_ple(
manifest: &Manifest,
source_dir: &Path,
destination: &Path,
levels: u8,
ple_part_elements: u64,
) -> Result<PreviewSummary, String> {
stream_parts::validate_ple_limit(ple_part_elements)?;
prepare_sharded_streamed_with_policy(
manifest,
source_dir,
destination,
levels,
stream_parts::MAX_PART_ELEMENTS,
Some(ple_part_elements),
)
}
pub(super) fn prepare_sharded_streamed_with_limit(
manifest: &Manifest,
source_dir: &Path,
destination: &Path,
levels: u8,
max_part_elements: u64,
) -> Result<PreviewSummary, String> {
prepare_sharded_streamed_with_policy(
manifest,
source_dir,
destination,
levels,
max_part_elements,
None,
)
}
@@ -0,0 +1,271 @@
//! Moved out of the parent module by STRA-338: fn prepare_sharded_streamed_with_policy.
#[allow(unused_imports)]
use super::*;
pub(super) fn prepare_sharded_streamed_with_policy(
manifest: &Manifest,
source_dir: &Path,
destination: &Path,
levels: u8,
max_part_elements: u64,
ple_part_elements: Option<u64>,
) -> Result<PreviewSummary, String> {
if !(1..=8).contains(&levels) {
return Err("streamed sharded preparation requires 1..=8 KAR levels".into());
}
if fs::symlink_metadata(destination).is_ok()
|| fs::symlink_metadata(provenance_path(destination)?).is_ok()
{
return Err("KAR archive or provenance destination already exists".into());
}
let identity = derived_mixed::fingerprint_shards(manifest, source_dir)?;
let archive_parts = if let Some(limit) = ple_part_elements {
stream_parts::plan_shards_with_ple_limit(&identity, source_dir, limit)?
} else {
stream_parts::plan_shards_with_limit(&identity, source_dir, max_part_elements)?
};
let archive_tensor_count = archive_parts.iter().map(Vec::len).sum::<usize>();
if archive_tensor_count == 0 || archive_tensor_count > 100_000 {
return Err("streamed sharded tensor count exceeds KAR-2 limits".into());
}
// Every nested part stores at least `levels` four-byte plane words per
// 32 values; a RAW fallback stores four bytes per value. The smaller of
// these is a safe lower bound before section files are created. Passing
// this gate does not guarantee enough space for scales and metadata.
let minimum_payload_bytes = archive_parts
.iter()
.flat_map(|parts| parts.iter())
.try_fold(0u64, |sum, part| {
sum.checked_add(minimum_part_payload_bytes(part.derived_bytes, levels)?)
.ok_or_else(|| "KAR minimum payload size overflow".to_string())
})?;
let destination_parent = destination
.parent()
.filter(|parent| !parent.as_os_str().is_empty())
.unwrap_or(Path::new("."));
model::require_space(destination_parent, minimum_payload_bytes)
.map_err(|error| format!("KAR minimum payload does not fit: {error}"))?;
let staging_path = destination.with_file_name(format!(
"{}.stream-parts-{}",
destination
.file_name()
.ok_or("KAR destination has no file name")?
.to_string_lossy(),
std::process::id()
));
fs::create_dir(&staging_path).map_err(|error| error.to_string())?;
let staging = StagingDir(staging_path);
let mut architecture = None::<String>;
let mut prepared = Vec::with_capacity(archive_tensor_count);
let mut maximum_relative_l2 = 0.0f64;
let mut tensor_distortions = Vec::with_capacity(archive_tensor_count);
let mut number = 0usize;
for shard in &identity.shards {
let path = source_dir.join(&shard.name);
let index = gguf::tensor_index(&path).map_err(|error| error.to_string())?;
if let Some(shard_architecture) = index.summary.architecture.as_deref() {
if architecture
.as_deref()
.is_some_and(|expected| expected != shard_architecture)
{
return Err("GGUF shard architectures differ".into());
}
architecture.get_or_insert_with(|| shard_architecture.to_owned());
}
if index.tensors.len() != shard.tensor_count || index.summary.file_size != shard.gguf_bytes
{
return Err("GGUF shard changed after identity derivation".into());
}
let mut source = File::open(&path).map_err(|error| error.to_string())?;
for tensor in &index.tensors {
if tensor.dimensions.len() > 4 {
return Err(format!(
"{}: KAR-2 supports up to four dimensions",
tensor.name
));
}
let elements = tensor
.dimensions
.iter()
.try_fold(1u64, |count, dim| count.checked_mul(*dim))
.ok_or("GGUF tensor element count overflow")?;
let derived = &identity.tensors[number];
if derived.name != tensor.name
|| derived.source_kind != tensor.kind
|| derived.derived_bytes
!= elements
.checked_mul(4)
.ok_or("F32 tensor byte count overflow")?
{
return Err(format!("{}: sharded tensor identity mismatch", tensor.name));
}
let absolute_base = index
.summary
.data_start
.checked_add(tensor.offset)
.ok_or("GGUF tensor offset overflow")?;
for part in &archive_parts[number] {
let absolute = absolute_base
.checked_add(part.source_byte_offset)
.ok_or("GGUF part offset overflow")?;
let sample = kar_sample::sample_normalized(
&mut source,
absolute,
part.source_kind,
part.source_bytes,
part.derived_bytes / 4,
part.source_sha256,
kar_sample::MAX_SAMPLE_VALUES,
)?;
let calibration = kar_codec::fit_topdown(&sample, levels).ok();
let section_path = staging.0.join(format!("{:06}.section", prepared.len()));
let (section_bytes, section_digest, nested, relative_l2) =
if let Some(calibration) = calibration {
let result = kar_stream_encode::encode_section(
&mut source,
absolute,
part.source_kind,
part.source_bytes,
part.derived_bytes / 4,
&calibration,
&section_path,
)?;
if result.source_digest != part.source_sha256
|| result.derived_digest != part.f32_sha256
{
return Err(format!(
"{}: streamed source or F32 digest mismatch",
part.name
));
}
(result.bytes, result.digest, true, result.relative_l2)
} else {
let result = spool_raw_f32(
&mut source,
absolute,
part.source_kind,
part.source_bytes,
&section_path,
)?;
if result.0 != part.source_sha256
|| result.1 != part.f32_sha256
|| result.2 != part.derived_bytes
{
return Err(format!(
"{}: streamed RAW source or F32 digest mismatch",
part.name
));
}
(result.2, result.1, false, 0.0)
};
maximum_relative_l2 = maximum_relative_l2.max(relative_l2);
tensor_distortions.push(TensorDistortion {
name: part.name.clone(),
relative_l2,
source_kind: part.source_kind,
section_bytes,
});
prepared.push(StreamedTensor {
prepared: PreparedTensor {
name: part.name.clone(),
dims: part.dimensions.clone(),
source_digest: part.f32_sha256,
source_offset: part.derived_offset,
section_path,
section_bytes,
section_digest,
},
nested,
});
}
number += 1;
}
if source.metadata().map_err(|error| error.to_string())?.len() != shard.gguf_bytes
|| hash_file(&path)? != shard.gguf_sha256
{
return Err(format!(
"{}: GGUF shard changed during preparation",
shard.name
));
}
}
let tensors = prepared
.iter()
.map(|entry| {
let tensor = &entry.prepared;
kar_writer::Tensor {
name: &tensor.name,
dims: &tensor.dims,
source_dtype: 0,
source_digest: tensor.source_digest,
source_offset: tensor.source_offset,
data: if entry.nested {
kar_writer::TensorData::NestedFile {
group: 32,
nesting: 0,
planes_min: 1,
planes_max: levels,
levels,
path: &tensor.section_path,
offset: 0,
bytes: tensor.section_bytes,
digest: tensor.section_digest,
}
} else {
kar_writer::TensorData::RawFile {
path: &tensor.section_path,
offset: 0,
bytes: tensor.section_bytes,
}
},
}
})
.collect::<Vec<_>>();
let builder = if let Some(limit) = ple_part_elements {
format!(
"strata-next/experimental-sharded-stream-v5:g32:l{levels}:sample65536:plepart{limit}"
)
} else {
format!("strata-next/experimental-sharded-stream-v4:g32:l{levels}:sample65536")
};
let source_identity = kar_writer::SourceIdentity {
name: "gguf-shards#derived-f32-le-v4",
architecture: architecture
.as_deref()
.ok_or("GGUF shards have no architecture")?,
builder: &builder,
digest: identity.derived_sha256,
total_elements: identity.derived_bytes / 4,
bytes: identity.derived_bytes,
};
let archive =
kar_writer::write_archive_consuming_files(destination, &source_identity, &tensors)?;
let archive_digest = hash_file(destination)?;
let provenance_path = provenance_path(destination)?;
let mut provenance = sharded_provenance_value(&identity, archive_digest);
provenance["schema"] = serde_json::json!(if ple_part_elements.is_some() {
"strata-next/sharded-stream-provenance-v5"
} else {
"strata-next/sharded-stream-provenance-v4"
});
provenance["derivation"] =
serde_json::json!("strata-next/gguf-shards-to-f32-le-v4:ggml-3cf03257");
provenance["levels"] = serde_json::json!(levels);
provenance["sampling"] = serde_json::json!("digest-seeded-65536-normalized-v1");
provenance["partitioned_tensors"] = partitioned_provenance(&archive_parts);
if let Some(limit) = ple_part_elements {
provenance["ple_part_elements"] = serde_json::json!(limit);
}
if let Err(error) = write_provenance(&provenance_path, &provenance) {
let _ = fs::remove_file(destination);
return Err(error);
}
Ok(PreviewSummary {
archive,
archive_digest,
maximum_relative_l2,
tensor_distortions,
provenance_path: Some(provenance_path),
})
}
@@ -0,0 +1,50 @@
//! Moved out of the parent module by STRA-338: fn spool_raw_f32.
#[allow(unused_imports)]
use super::*;
pub(super) fn spool_raw_f32<R: Read + Seek>(
reader: &mut R,
absolute: u64,
source_kind: u32,
source_bytes: u64,
path: &Path,
) -> Result<([u8; 32], [u8; 32], u64), String> {
let file = fs::OpenOptions::new()
.write(true)
.create_new(true)
.open(path)
.map_err(|error| error.to_string())?;
let result = (|| {
let mut writer = BufWriter::new(file);
let mut source_hash = Sha256::new();
let mut derived_hash = Sha256::new();
let bytes = gguf_f32_stream::visit(
reader,
absolute,
source_kind,
source_bytes,
|raw, f32_bytes| {
source_hash.update(raw);
derived_hash.update(f32_bytes);
writer
.write_all(f32_bytes)
.map_err(|error| error.to_string())
},
)?;
writer.flush().map_err(|error| error.to_string())?;
writer
.get_ref()
.sync_all()
.map_err(|error| error.to_string())?;
Ok((
source_hash.finalize().into(),
derived_hash.finalize().into(),
bytes,
))
})();
if result.is_err() {
let _ = fs::remove_file(path);
}
result
}
+808
View File
@@ -0,0 +1,808 @@
//! Unit tests of this module (moved out of the file by STRA-338; the test ids are unchanged).
use super::*;
#[test]
fn kar_payload_preflight_rejects_too_small_volumes_conservatively() {
assert_eq!(
minimum_part_payload_bytes(707_775_598_080, 2).unwrap(),
44_235_974_880
);
assert!(minimum_part_payload_bytes(707_775_598_080, 2).unwrap() > 23 * (1 << 30));
assert_eq!(minimum_part_payload_bytes(4, 8).unwrap(), 4);
assert!(minimum_part_payload_bytes(u64::MAX, 8).is_err());
}
use crate::model::ModelFile;
fn string(out: &mut Vec<u8>, value: &str) {
out.extend_from_slice(&(value.len() as u64).to_le_bytes());
out.extend_from_slice(value.as_bytes());
}
fn one_shard(name: &str, kind: u32, elements: u64, payload: &[u8]) -> Vec<u8> {
one_shard_with_arch(name, kind, elements, payload, true)
}
fn one_shard_with_arch(
name: &str,
kind: u32,
elements: u64,
payload: &[u8],
include_architecture: bool,
) -> Vec<u8> {
let mut gguf = b"GGUF".to_vec();
gguf.extend_from_slice(&3u32.to_le_bytes());
gguf.extend_from_slice(&1u64.to_le_bytes());
gguf.extend_from_slice(&u64::from(include_architecture).to_le_bytes());
if include_architecture {
string(&mut gguf, "general.architecture");
gguf.extend_from_slice(&8u32.to_le_bytes());
string(&mut gguf, "qwen35");
}
string(&mut gguf, name);
gguf.extend_from_slice(&1u32.to_le_bytes());
gguf.extend_from_slice(&elements.to_le_bytes());
gguf.extend_from_slice(&kind.to_le_bytes());
gguf.extend_from_slice(&0u64.to_le_bytes());
gguf.resize(gguf.len().div_ceil(32) * 32, 0);
gguf.extend_from_slice(payload);
gguf
}
fn ple_shard(payload: &[u8]) -> Vec<u8> {
let mut gguf = b"GGUF".to_vec();
gguf.extend_from_slice(&3u32.to_le_bytes());
gguf.extend_from_slice(&1u64.to_le_bytes());
gguf.extend_from_slice(&1u64.to_le_bytes());
string(&mut gguf, "general.architecture");
gguf.extend_from_slice(&8u32.to_le_bytes());
string(&mut gguf, "qwen35");
string(&mut gguf, stream_parts::PLE_TENSOR_NAME);
gguf.extend_from_slice(&2u32.to_le_bytes());
gguf.extend_from_slice(&32u64.to_le_bytes());
gguf.extend_from_slice(&16u64.to_le_bytes());
gguf.extend_from_slice(&0u32.to_le_bytes());
gguf.extend_from_slice(&0u64.to_le_bytes());
gguf.resize(gguf.len().div_ceil(32) * 32, 0);
gguf.extend_from_slice(payload);
gguf
}
#[test]
fn converts_two_small_f32_gguf_tensors_and_rejects_duplicate_output() {
let mut gguf = b"GGUF".to_vec();
gguf.extend_from_slice(&3u32.to_le_bytes());
gguf.extend_from_slice(&2u64.to_le_bytes());
gguf.extend_from_slice(&1u64.to_le_bytes());
string(&mut gguf, "general.architecture");
gguf.extend_from_slice(&8u32.to_le_bytes());
string(&mut gguf, "qwen35");
for (name, offset) in [("first", 0u64), ("second", 128)] {
string(&mut gguf, name);
gguf.extend_from_slice(&1u32.to_le_bytes());
gguf.extend_from_slice(&32u64.to_le_bytes());
gguf.extend_from_slice(&0u32.to_le_bytes());
gguf.extend_from_slice(&offset.to_le_bytes());
}
let data_start = gguf.len().div_ceil(32) * 32;
gguf.resize(data_start, 0);
for index in 0..64 {
let value = [-1.0f32, -0.25, 0.25, 1.0][index % 4];
gguf.extend_from_slice(&value.to_le_bytes());
}
let source_path =
std::env::temp_dir().join(format!("strata-preview-{}.gguf", std::process::id()));
let output = std::env::temp_dir().join(format!("strata-preview-{}.kar", std::process::id()));
let _ = fs::remove_file(&output);
fs::write(&source_path, &gguf).unwrap();
let summary = prepare_f32(&source_path, &output, 2).unwrap();
assert_eq!(summary.archive.tensor_count, 2);
assert_eq!(summary.archive.total_elements, 64);
assert!(summary.maximum_relative_l2.is_finite());
assert_eq!(
summary.archive.source_digest,
hash_file(&source_path).unwrap()
);
assert_eq!(summary.archive_digest, hash_file(&output).unwrap());
let staging = output.with_file_name(format!(
"{}.parts-{}",
output.file_name().unwrap().to_string_lossy(),
std::process::id()
));
assert!(!staging.exists());
assert!(prepare_f32(&source_path, &output, 2).is_err());
assert!(!staging.exists());
let failed_source =
std::env::temp_dir().join(format!("strata-preview-bad-{}.gguf", std::process::id()));
let failed_output =
std::env::temp_dir().join(format!("strata-preview-bad-{}.kar", std::process::id()));
let _ = fs::remove_file(&failed_output);
let mut broken = gguf.clone();
let last = broken.len() - 4;
broken[last..].copy_from_slice(&f32::NAN.to_le_bytes());
fs::write(&failed_source, broken).unwrap();
assert!(
prepare_f32(&failed_source, &failed_output, 2)
.unwrap_err()
.contains("invalid KAR normalization input")
);
assert!(!failed_output.exists());
let failed_staging = failed_output.with_file_name(format!(
"{}.parts-{}",
failed_output.file_name().unwrap().to_string_lossy(),
std::process::id()
));
assert!(!failed_staging.exists());
fs::remove_file(failed_source).unwrap();
fs::remove_file(&output).unwrap();
fs::remove_file(&source_path).unwrap();
}
#[test]
fn refuses_quantized_gguf_until_source_decoder_is_available() {
let mut gguf = b"GGUF".to_vec();
gguf.extend_from_slice(&3u32.to_le_bytes());
gguf.extend_from_slice(&1u64.to_le_bytes());
gguf.extend_from_slice(&1u64.to_le_bytes());
string(&mut gguf, "general.architecture");
gguf.extend_from_slice(&8u32.to_le_bytes());
string(&mut gguf, "qwen35");
string(&mut gguf, "expert");
gguf.extend_from_slice(&1u32.to_le_bytes());
gguf.extend_from_slice(&256u64.to_le_bytes());
gguf.extend_from_slice(&21u32.to_le_bytes());
gguf.extend_from_slice(&0u64.to_le_bytes());
gguf.resize(gguf.len().div_ceil(32) * 32, 0);
gguf.extend_from_slice(&[0u8; 110]);
let source_path =
std::env::temp_dir().join(format!("strata-preview-iq3-{}.gguf", std::process::id()));
let output =
std::env::temp_dir().join(format!("strata-preview-iq3-{}.kar", std::process::id()));
let _ = fs::remove_file(&output);
fs::write(&source_path, gguf).unwrap();
assert!(
prepare_f32(&source_path, &output, 2)
.unwrap_err()
.contains("supports only F32")
);
assert!(!output.exists());
fs::remove_file(source_path).unwrap();
}
#[test]
fn prepares_iq3_preview_with_virtual_f32_source_and_provenance() {
let mut gguf = b"GGUF".to_vec();
gguf.extend_from_slice(&3u32.to_le_bytes());
gguf.extend_from_slice(&1u64.to_le_bytes());
gguf.extend_from_slice(&1u64.to_le_bytes());
string(&mut gguf, "general.architecture");
gguf.extend_from_slice(&8u32.to_le_bytes());
string(&mut gguf, "qwen35");
string(&mut gguf, "expert");
gguf.extend_from_slice(&1u32.to_le_bytes());
gguf.extend_from_slice(&256u64.to_le_bytes());
gguf.extend_from_slice(&21u32.to_le_bytes());
gguf.extend_from_slice(&0u64.to_le_bytes());
gguf.resize(gguf.len().div_ceil(32) * 32, 0);
let mut block = [0u8; iq3_s::BLOCK_BYTES];
block[..2].copy_from_slice(&0x3c00u16.to_le_bytes());
for (index, byte) in block[2..66].iter_mut().enumerate() {
*byte = (index as u8).wrapping_mul(3);
}
block[74] = 0x55;
gguf.extend_from_slice(&block);
let base = std::env::temp_dir().join(format!("strata-preview-iq3-good-{}", std::process::id()));
let source_path = base.with_extension("gguf");
let output = base.with_extension("kar");
let provenance = output.with_file_name(format!(
"{}.provenance.json",
output.file_name().unwrap().to_string_lossy()
));
let _ = fs::remove_file(&output);
let _ = fs::remove_file(&provenance);
fs::write(&source_path, gguf).unwrap();
let identity = derived_iq3::fingerprint(&source_path).unwrap();
let result = prepare_iq3(&source_path, &output, 2).unwrap();
assert_eq!(result.archive.source_digest, identity.derived_sha256);
assert_eq!(result.archive.source_bytes, identity.derived_bytes);
assert_eq!(
result.provenance_path.as_deref(),
Some(provenance.as_path())
);
assert_eq!(kar::verify(&output).unwrap(), result.archive);
let record: serde_json::Value =
serde_json::from_slice(&fs::read(&provenance).unwrap()).unwrap();
assert_eq!(
record["original_gguf_sha256"],
hex::encode(identity.gguf_sha256)
);
assert_eq!(
record["derived_f32_sha256"],
hex::encode(identity.derived_sha256)
);
assert_eq!(record["archive_sha256"], hex::encode(result.archive_digest));
assert!(result.maximum_relative_l2.is_finite());
assert_eq!(verify_iq3(&source_path, &output).unwrap(), result.archive);
let saved_provenance = fs::read(&provenance).unwrap();
let mut changed = record.clone();
changed["archive_sha256"] = serde_json::Value::String("00".repeat(32));
fs::write(&provenance, serde_json::to_vec(&changed).unwrap()).unwrap();
assert!(
verify_iq3(&source_path, &output)
.unwrap_err()
.contains("provenance differs")
);
fs::write(&provenance, saved_provenance).unwrap();
assert!(verify_iq3(&source_path, &output).is_ok());
let blocked_output = base.with_file_name(format!(
"strata-preview-iq3-blocked-{}.kar",
std::process::id()
));
let blocked_provenance = blocked_output.with_file_name(format!(
"{}.provenance.json",
blocked_output.file_name().unwrap().to_string_lossy()
));
let _ = fs::remove_file(&blocked_output);
fs::write(&blocked_provenance, b"reserved").unwrap();
assert!(
prepare_iq3(&source_path, &blocked_output, 2)
.unwrap_err()
.contains("provenance destination already exists")
);
assert!(!blocked_output.exists());
fs::remove_file(blocked_provenance).unwrap();
fs::remove_file(provenance).unwrap();
fs::remove_file(output).unwrap();
fs::remove_file(source_path).unwrap();
}
#[test]
fn prepares_and_verifies_mixed_preview_with_each_source_kind() {
let tensors = [
("bf16", 30u32, 320u64, 32u64),
("iq3", 21, 0, 256),
("f16", 1, 256, 32),
("f32", 0, 128, 32),
];
let mut gguf = b"GGUF".to_vec();
gguf.extend_from_slice(&3u32.to_le_bytes());
gguf.extend_from_slice(&(tensors.len() as u64).to_le_bytes());
gguf.extend_from_slice(&1u64.to_le_bytes());
string(&mut gguf, "general.architecture");
gguf.extend_from_slice(&8u32.to_le_bytes());
string(&mut gguf, "qwen35");
for (name, kind, offset, elements) in tensors {
string(&mut gguf, name);
gguf.extend_from_slice(&1u32.to_le_bytes());
gguf.extend_from_slice(&elements.to_le_bytes());
gguf.extend_from_slice(&kind.to_le_bytes());
gguf.extend_from_slice(&offset.to_le_bytes());
}
gguf.resize(gguf.len().div_ceil(32) * 32, 0);
let mut payload = vec![0u8; 384];
payload[..2].copy_from_slice(&0x3c00u16.to_le_bytes());
for (index, byte) in payload[2..66].iter_mut().enumerate() {
*byte = (index as u8).wrapping_mul(3);
}
payload[74] = 0x55;
let values = [-1.0f32, -0.25, 0.25, 1.0];
for index in 0..32 {
let value = values[index % values.len()];
payload[128 + 4 * index..132 + 4 * index].copy_from_slice(&value.to_le_bytes());
let f16 = kar_codec::f32_to_f16_bits(value).to_le_bytes();
payload[256 + 2 * index..258 + 2 * index].copy_from_slice(&f16);
let bf16 = (value.to_bits() >> 16) as u16;
payload[320 + 2 * index..322 + 2 * index].copy_from_slice(&bf16.to_le_bytes());
}
gguf.extend_from_slice(&payload);
let base = std::env::temp_dir().join(format!("strata-preview-mixed-{}", std::process::id()));
let source_path = base.with_extension("gguf");
let output = base.with_extension("kar");
let provenance = provenance_path(&output).unwrap();
let _ = fs::remove_file(&output);
let _ = fs::remove_file(&provenance);
fs::write(&source_path, gguf).unwrap();
let identity = derived_mixed::fingerprint(&source_path).unwrap();
let result = prepare_mixed(&source_path, &output, 2).unwrap();
assert_eq!(result.archive.source_digest, identity.derived_sha256);
assert_eq!(result.archive.source_bytes, identity.derived_bytes);
assert_eq!(result.archive.tensor_count, 4);
assert_eq!(verify_mixed(&source_path, &output).unwrap(), result.archive);
assert!(verify_iq3(&source_path, &output).is_err());
let record: serde_json::Value =
serde_json::from_slice(&fs::read(&provenance).unwrap()).unwrap();
assert_eq!(record["schema"], "strata-next/mixed-preview-provenance-v1");
assert_eq!(record["tensors"][0]["source_kind"], 30);
assert!(result.maximum_relative_l2.is_finite());
fs::remove_file(provenance).unwrap();
fs::remove_file(output).unwrap();
fs::remove_file(source_path).unwrap();
}
#[cfg(unix)] // archive preparation is an offline Unix tool
#[tokio::test]
async fn prepares_and_verifies_manifest_pinned_sharded_preview() {
let directory =
std::env::temp_dir().join(format!("strata-preview-shards-{}", std::process::id()));
let _ = fs::remove_dir_all(&directory);
fs::create_dir(&directory).unwrap();
let mut dense = Vec::new();
for index in 0..32 {
dense.extend_from_slice(&[-1.0f32, -0.25, 0.25, 1.0][index % 4].to_le_bytes());
}
let f32 = one_shard("dense", 0, 32, &dense);
let mut block = [0u8; iq3_s::BLOCK_BYTES];
block[..2].copy_from_slice(&0x3c00u16.to_le_bytes());
for (index, byte) in block[2..66].iter_mut().enumerate() {
*byte = (index as u8).wrapping_mul(3);
}
block[74] = 0x55;
let iq3 = one_shard_with_arch("expert", 21, 256, &block, false);
fs::write(directory.join("a-f32.gguf"), &f32).unwrap();
fs::write(directory.join("z-iq3.gguf"), &iq3).unwrap();
let mut manifest = Manifest {
schema_version: 1,
files: vec![
ModelFile {
name: "z-iq3.gguf".into(),
url: "https://example.invalid/z".into(),
size: iq3.len() as u64,
sha256: hex::encode(Sha256::digest(&iq3)),
},
ModelFile {
name: "a-f32.gguf".into(),
url: "https://example.invalid/a".into(),
size: f32.len() as u64,
sha256: hex::encode(Sha256::digest(&f32)),
},
],
};
let output = directory.join("sharded.kar");
let identity = derived_mixed::fingerprint_shards(&manifest, &directory).unwrap();
let result = prepare_sharded(&manifest, &directory, &output, 2).unwrap();
assert_eq!(result.archive.tensor_count, 2);
assert_eq!(result.archive.source_digest, identity.derived_sha256);
assert_eq!(result.archive.source_bytes, identity.derived_bytes);
assert_eq!(
verify_sharded(&manifest, &directory, &output).unwrap(),
result.archive
);
assert!(matches!(
crate::model_pipeline::ensure_sharded_preview(&manifest, &directory, &output, 2)
.await
.unwrap(),
crate::model_pipeline::PreviewOutcome::Reused(_)
));
assert!(
crate::model_pipeline::ensure_sharded_preview(&manifest, &directory, &output, 3)
.await
.is_err()
);
let record: serde_json::Value =
serde_json::from_slice(&fs::read(result.provenance_path.unwrap()).unwrap()).unwrap();
assert_eq!(
record["schema"],
"strata-next/sharded-preview-provenance-v1"
);
assert_eq!(record["shards"][0]["name"], "a-f32.gguf");
assert_eq!(record["tensors"][1]["derived_offset"], 128);
let streamed_output = directory.join("streamed.kar");
let streamed = prepare_sharded_streamed(&manifest, &directory, &streamed_output, 2).unwrap();
assert_eq!(streamed.archive.source_digest, identity.derived_sha256);
assert_eq!(streamed.archive.tensor_count, 2);
let decoded = kar::decode_preview_tensor(&streamed_output, "dense", 2).unwrap();
let reference = dense
.as_chunks::<4>()
.0
.iter()
.map(|word| f32::from_le_bytes(*word))
.collect::<Vec<_>>();
assert_eq!(decoded.len(), reference.len());
assert!(
decoded
.iter()
.zip(&reference)
.all(|(actual, expected)| (actual - expected).abs() < 0.1)
);
assert_eq!(
verify_sharded_streamed(&manifest, &directory, &streamed_output, 2).unwrap(),
streamed.archive
);
let sampled = crate::kar_quality::analyze(&manifest, &directory, &streamed_output, 2).unwrap();
assert_eq!(
sampled.records.len(),
streamed.archive.tensor_count as usize
);
assert!(
sampled
.records
.iter()
.all(|record| { record.sampled_elements > 0 && record.relative_l2.is_finite() })
);
let reused =
crate::kar_quality::analyze_previously_verified(&manifest, &directory, &streamed_output, 2)
.unwrap();
assert!(
reused
.records
.iter()
.zip(&sampled.records)
.all(|(a, b)| { a.name == b.name && a.relative_l2 == b.relative_l2 })
);
assert!(verify_sharded_streamed(&manifest, &directory, &streamed_output, 3).is_err());
assert!(verify_sharded(&manifest, &directory, &streamed_output).is_err());
let streamed_record: serde_json::Value =
serde_json::from_slice(&fs::read(streamed.provenance_path.unwrap()).unwrap()).unwrap();
assert_eq!(
streamed_record["schema"],
"strata-next/sharded-stream-provenance-v4"
);
assert_eq!(
streamed_record["partitioned_tensors"],
serde_json::json!([])
);
assert_eq!(streamed_record["levels"], 2);
assert!(prepare_sharded_streamed(&manifest, &directory, &streamed_output, 2).is_err());
manifest.files[0].sha256 = "00".repeat(32);
assert!(verify_sharded(&manifest, &directory, &output).is_err());
assert!(verify_sharded_streamed(&manifest, &directory, &streamed_output, 2).is_err());
manifest.files[0].sha256 = hex::encode(Sha256::digest(&iq3));
let mut corrupted = fs::read(&output).unwrap();
let last = corrupted.len() - 1;
corrupted[last] ^= 1;
fs::write(&output, corrupted).unwrap();
assert!(
crate::model_pipeline::ensure_sharded_preview(&manifest, &directory, &output, 2)
.await
.is_err()
);
fs::remove_dir_all(directory).unwrap();
}
#[cfg(unix)] // archive preparation is an offline Unix tool
#[test]
fn streamed_preparation_keeps_unsplittable_tensors_exact() {
let directory = std::env::temp_dir().join(format!("strata-stream-raw-{}", std::process::id()));
let _ = fs::remove_dir_all(&directory);
fs::create_dir(&directory).unwrap();
let mut files = Vec::new();
for (name, kind, elements, payload) in [
("a", 21, 256, vec![0u8; iq3_s::BLOCK_BYTES]),
("b", 20, 32, vec![0u8; 18]),
] {
let bytes = one_shard_with_arch(name, kind, elements, &payload, name == "a");
let filename = format!("{name}.gguf");
fs::write(directory.join(&filename), &bytes).unwrap();
files.push(ModelFile {
name: filename,
url: "https://example.invalid/source".into(),
size: bytes.len() as u64,
sha256: hex::encode(Sha256::digest(&bytes)),
});
}
let manifest = Manifest {
schema_version: 1,
files,
};
let archive = directory.join("raw.kar");
let result = prepare_sharded_streamed(&manifest, &directory, &archive, 2).unwrap();
assert_eq!(result.archive.max_planes, 0);
assert_eq!(result.maximum_relative_l2, 0.0);
let sampled = crate::kar_quality::analyze(&manifest, &directory, &archive, 2).unwrap();
assert_eq!(sampled.records.len(), 2);
assert!(
sampled
.records
.iter()
.all(|record| record.relative_l2 == 0.0)
);
let reused =
crate::kar_quality::analyze_previously_verified(&manifest, &directory, &archive, 2)
.unwrap();
assert!(
reused
.records
.iter()
.all(|record| record.relative_l2 == 0.0)
);
assert_eq!(
verify_sharded_streamed(&manifest, &directory, &archive, 2).unwrap(),
result.archive
);
fs::remove_dir_all(directory).unwrap();
}
#[cfg(unix)] // archive preparation is an offline Unix tool
#[test]
fn selected_overlay_reconstructs_source_and_cleans_staging() {
let directory = std::env::temp_dir().join(format!("strata-overlay-{}", std::process::id()));
let _ = fs::remove_dir_all(&directory);
fs::create_dir(&directory).unwrap();
let values = (0..256)
.map(|index| (index as f32 - 127.5) / 128.0)
.collect::<Vec<_>>();
let dense = values
.iter()
.flat_map(|value| value.to_le_bytes())
.collect::<Vec<_>>();
let files = [
("a.gguf", one_shard("dense", 0, 256, &dense)),
(
"b.gguf",
one_shard_with_arch("extra", 21, 256, &[0u8; iq3_s::BLOCK_BYTES], false),
),
]
.into_iter()
.map(|(name, bytes)| {
fs::write(directory.join(name), &bytes).unwrap();
ModelFile {
name: name.into(),
url: "https://example.invalid/source".into(),
size: bytes.len() as u64,
sha256: hex::encode(Sha256::digest(&bytes)),
}
})
.collect();
let manifest = Manifest {
schema_version: 1,
files,
};
let base = directory.join("base.kar");
let prepared = prepare_sharded_streamed(&manifest, &directory, &base, 2).unwrap();
let policy = directory.join("candidates.json");
fs::write(
&policy,
serde_json::to_vec(&serde_json::json!({
"schema": "strata-next/proposed-kar-precision-candidates-v1",
"source_archive_sha256": hex::encode(prepared.archive_digest),
"proposed_levels": 3,
"records": [{"name": "dense", "elements": 256}],
}))
.unwrap(),
)
.unwrap();
let overlay = directory.join("overlay.kar");
let result =
crate::kar_overlay::prepare(&manifest, &directory, &base, &policy, &overlay).unwrap();
assert_eq!(result.record_count, 1);
assert_eq!(kar::verify(&overlay).unwrap().max_planes, 3);
assert!(result.maximum_relative_l2.is_finite());
let decoded = kar::decode_preview_tensor(&overlay, "dense", 3).unwrap();
let error_sum = decoded
.iter()
.zip(&values)
.map(|(actual, expected)| f64::from(actual - expected).powi(2))
.sum::<f64>();
let reference_sum = values
.iter()
.map(|value| f64::from(*value).powi(2))
.sum::<f64>();
assert!(((error_sum / reference_sum).sqrt() - result.maximum_relative_l2).abs() < 1e-7);
assert!(result.provenance_path.exists());
let comparison = crate::kar_overlay::compare(&manifest, &directory, &base, &overlay).unwrap();
assert_eq!(comparison.records.len(), 1);
assert_eq!(comparison.records[0].name, "dense");
let selection = crate::kar_overlay::resolve_verified(&base, &overlay).unwrap();
assert_eq!(selection.replacement_count, 1);
assert_eq!(selection.records.len(), 2);
assert_eq!(selection.records[0].name, "dense");
assert_eq!(selection.records[0].archive, "overlay");
assert_eq!(selection.records[1].archive, "base");
let mut provenance: serde_json::Value =
serde_json::from_slice(&fs::read(&result.provenance_path).unwrap()).unwrap();
provenance["records"][0]["f32_sha256"] = serde_json::json!("00".repeat(32));
fs::write(
&result.provenance_path,
serde_json::to_vec(&provenance).unwrap(),
)
.unwrap();
assert!(crate::kar_overlay::resolve_verified(&base, &overlay).is_err());
assert!((comparison.records[0].overlay_relative_l2 - result.maximum_relative_l2).abs() < 1e-7);
assert!(
!directory
.join(format!(
"overlay.kar.overlay-sections-{}",
std::process::id()
))
.exists()
);
fs::remove_dir_all(directory).unwrap();
}
#[cfg(unix)] // archive preparation is an offline Unix tool
#[test]
fn streamed_sharded_archive_roundtrips_partitioned_tensor_records() {
let directory =
std::env::temp_dir().join(format!("strata-stream-split-{}", std::process::id()));
let _ = fs::remove_dir_all(&directory);
fs::create_dir(&directory).unwrap();
let dense = (0..512)
.flat_map(|index| [-1.0f32, -0.25, 0.25, 1.0][index % 4].to_le_bytes())
.collect::<Vec<_>>();
let dense_shard = one_shard("dense", 0, 512, &dense);
let mut block = [0u8; iq3_s::BLOCK_BYTES];
block[..2].copy_from_slice(&0x3c00u16.to_le_bytes());
let iq3_shard = one_shard_with_arch("expert", 21, 256, &block, false);
let files = [("a-dense.gguf", dense_shard), ("z-iq3.gguf", iq3_shard)]
.into_iter()
.map(|(name, bytes)| {
fs::write(directory.join(name), &bytes).unwrap();
ModelFile {
name: name.into(),
url: "https://example.invalid/source".into(),
size: bytes.len() as u64,
sha256: hex::encode(Sha256::digest(&bytes)),
}
})
.collect();
let manifest = Manifest {
schema_version: 1,
files,
};
let archive = directory.join("split.kar");
let result =
prepare_sharded_streamed_with_limit(&manifest, &directory, &archive, 2, 256).unwrap();
assert_eq!(result.archive.tensor_count, 3);
assert_eq!(result.tensor_distortions.len(), 3);
assert_eq!(
result.maximum_relative_l2,
result
.tensor_distortions
.iter()
.map(|entry| entry.relative_l2)
.fold(0.0f64, f64::max)
);
assert!(
result
.tensor_distortions
.iter()
.all(|entry| entry.section_bytes > 0 && entry.relative_l2.is_finite())
);
assert_eq!(
verify_sharded_inner(&manifest, &directory, &archive, Some(2), 256, None).unwrap(),
result.archive
);
assert!(verify_sharded_streamed(&manifest, &directory, &archive, 2).is_err());
let provenance: serde_json::Value =
serde_json::from_slice(&fs::read(result.provenance_path.unwrap()).unwrap()).unwrap();
let parts = provenance["partitioned_tensors"][0]["parts"]
.as_array()
.unwrap();
assert_eq!(parts.len(), 2);
assert_eq!(parts[0]["dimensions"], serde_json::json!([256]));
assert_eq!(parts[1]["derived_offset"], 1024);
for (number, part) in parts.iter().enumerate() {
let name = part["name"].as_str().unwrap();
let decoded = kar::decode_preview_tensor(&archive, name, 2).unwrap();
assert_eq!(decoded.len(), 256);
for (actual, original) in decoded.iter().zip(
dense[number * 1024..(number + 1) * 1024]
.as_chunks::<4>()
.0
.iter()
.map(|word| f32::from_le_bytes(*word)),
) {
assert!((actual - original).abs() < 0.1);
}
}
fs::remove_dir_all(directory).unwrap();
}
#[cfg(unix)] // archive preparation is an offline Unix tool
#[test]
fn ple_partition_policy_is_versioned_and_verified() {
let directory = std::env::temp_dir().join(format!(
"strata-ple-parts-{}-{}",
std::process::id(),
std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.unwrap()
.as_nanos()
));
fs::create_dir(&directory).unwrap();
let ple_values = (0..512)
.flat_map(|index| ((index as f32 - 255.5) / 256.0).to_le_bytes())
.collect::<Vec<_>>();
let mut block = [0u8; iq3_s::BLOCK_BYTES];
block[..2].copy_from_slice(&0x3c00u16.to_le_bytes());
let dense_values = (0..256)
.map(|index| (index as f32 - 127.5) / 128.0)
.flat_map(f32::to_le_bytes)
.collect::<Vec<_>>();
let files = [
("a-ple.gguf", ple_shard(&ple_values)),
(
"m-dense.gguf",
one_shard_with_arch("dense", 0, 256, &dense_values, false),
),
(
"z-expert.gguf",
one_shard_with_arch("expert", 21, 256, &block, false),
),
]
.into_iter()
.map(|(name, bytes)| {
fs::write(directory.join(name), &bytes).unwrap();
ModelFile {
name: name.into(),
url: "https://example.invalid/source".into(),
size: bytes.len() as u64,
sha256: hex::encode(Sha256::digest(&bytes)),
}
})
.collect();
let manifest = Manifest {
schema_version: 1,
files,
};
let archive = directory.join("ple.kar");
let prepared = prepare_sharded_streamed_ple(&manifest, &directory, &archive, 2, 128).unwrap();
assert_eq!(prepared.archive.tensor_count, 6);
assert_eq!(
verify_sharded_streamed_ple(&manifest, &directory, &archive, 2, 128).unwrap(),
prepared.archive
);
assert!(verify_sharded_streamed(&manifest, &directory, &archive, 2).is_err());
assert!(verify_sharded_streamed_ple(&manifest, &directory, &archive, 2, 256).is_err());
let provenance: serde_json::Value =
serde_json::from_slice(&fs::read(prepared.provenance_path.unwrap()).unwrap()).unwrap();
assert_eq!(
provenance["schema"],
"strata-next/sharded-stream-provenance-v5"
);
assert_eq!(provenance["ple_part_elements"], 128);
assert_eq!(
provenance["partitioned_tensors"][0]["parts"]
.as_array()
.unwrap()
.len(),
4
);
let policy = directory.join("candidates.json");
fs::write(
&policy,
serde_json::to_vec(&serde_json::json!({
"schema": "strata-next/proposed-kar-precision-candidates-v1",
"source_archive_sha256": hex::encode(prepared.archive_digest),
"proposed_levels": 3,
"records": [
{"name": "dense", "elements": 256},
{"name": "per_layer_token_embd.weight#strata-part-001-of-004", "elements": 128}
],
}))
.unwrap(),
)
.unwrap();
let overlay = directory.join("overlay.kar");
crate::kar_overlay::prepare(&manifest, &directory, &archive, &policy, &overlay).unwrap();
let selection = crate::kar_overlay::resolve_verified(&archive, &overlay).unwrap();
assert_eq!(selection.replacement_count, 2);
assert_eq!(selection.records.len(), 6);
let memory = crate::kar_memory::plan_selected(&archive, &overlay, 2, 3, 1 << 20).unwrap();
assert_eq!(memory.record_count, 6);
assert_eq!(memory.replacement_count, 2);
assert!(memory.selected_overlay_compressed_bytes > 0);
assert_eq!(
memory
.largest_records
.iter()
.filter(|record| record.archive == "overlay")
.count(),
2
);
assert_eq!(
memory.selected_compressed_bytes,
memory.selected_base_compressed_bytes + memory.selected_overlay_compressed_bytes
);
let comparison =
crate::kar_overlay::compare(&manifest, &directory, &archive, &overlay).unwrap();
assert_eq!(comparison.records.len(), 2);
assert_eq!(comparison.records[1].elements, 128);
let sidecar = archive.with_file_name("ple.kar.provenance.json");
let mut corrupted: serde_json::Value =
serde_json::from_slice(&fs::read(&sidecar).unwrap()).unwrap();
corrupted["partitioned_tensors"][0]["parts"][0]["source_byte_offset"] = 4.into();
fs::write(&sidecar, serde_json::to_vec(&corrupted).unwrap()).unwrap();
assert!(crate::kar_overlay::compare(&manifest, &directory, &archive, &overlay).is_err());
fs::remove_dir_all(directory).unwrap();
}
@@ -0,0 +1,237 @@
//! Moved out of the parent module by STRA-338: fn verify_derived, fn decode_source_tensor, fn provenance_path, fn provenance_value, fn sharded_provenance_value, fn partitioned_provenance ....
#[allow(unused_imports)]
use super::*;
pub(super) fn verify_derived(
source_path: &Path,
archive_path: &Path,
kind: PreviewKind,
) -> Result<kar::Summary, String> {
let identity = match kind {
PreviewKind::F32 => return Err("F32 preview does not use derived provenance".into()),
PreviewKind::Iq3 => DerivedIdentity::Iq3(derived_iq3::fingerprint(source_path)?),
PreviewKind::Mixed => DerivedIdentity::Mixed(derived_mixed::fingerprint(source_path)?),
};
let (summary, sources) = kar::verify_with_sources(archive_path)?;
if summary.source_digest != identity.derived_digest()
|| summary.source_bytes != identity.derived_bytes()
|| summary.source_total_elements.checked_mul(4) != Some(identity.derived_bytes())
|| sources.len() != identity.tensor_count()
{
return Err("KAR header differs from derived F32 source identity".into());
}
for (number, record) in sources.iter().enumerate() {
let tensor = identity.tensor(number);
let record_bytes = record
.dimensions
.iter()
.try_fold(4u64, |size, dim| size.checked_mul(*dim))
.ok_or("KAR tensor source byte count overflow")?;
if record.name != tensor.name
|| record.dtype != 0
|| &record.digest != tensor.f32_digest
|| record.offset != tensor.offset
|| record_bytes != tensor.bytes
{
return Err(format!(
"{}: KAR tensor source identity mismatch",
tensor.name
));
}
}
let archive_digest = hash_file(archive_path)?;
let provenance = provenance_path(archive_path)?;
let file = File::open(provenance).map_err(|error| error.to_string())?;
let recorded: serde_json::Value =
serde_json::from_reader(file).map_err(|error| error.to_string())?;
if recorded != provenance_value(&identity, archive_digest) {
return Err("derived preview provenance differs from source or archive".into());
}
Ok(summary)
}
pub(super) fn decode_source_tensor(
kind: u32,
raw: &[u8],
elements: usize,
) -> Result<Vec<f32>, String> {
let weights = match kind {
0 => raw
.as_chunks::<4>()
.0
.iter()
.map(|chunk| f32::from_le_bytes(*chunk))
.collect(),
1 | 30 => raw
.as_chunks::<2>()
.0
.iter()
.map(|pair| {
let bits = u16::from_le_bytes(*pair);
if kind == 1 {
kar_codec::f16_bits_to_f32(bits)
} else {
f32::from_bits(u32::from(bits) << 16)
}
})
.collect(),
21 => {
let mut values = vec![0.0f32; elements];
iq3_s::decode_into(raw, &mut values)?;
values
}
_ => return Err("unsupported GGUF tensor source kind".into()),
};
if weights.len() != elements {
return Err("decoded GGUF tensor size differs from shape".into());
}
Ok(weights)
}
pub(super) fn provenance_path(destination: &Path) -> Result<PathBuf, String> {
Ok(destination.with_file_name(format!(
"{}.provenance.json",
destination
.file_name()
.ok_or("KAR destination has no file name")?
.to_string_lossy()
)))
}
pub(super) fn provenance_value(
identity: &DerivedIdentity,
archive_digest: [u8; 32],
) -> serde_json::Value {
match identity {
DerivedIdentity::Iq3(identity) => serde_json::json!({
"schema": "strata-next/iq3-preview-provenance-v1",
"derivation": "strata-next/iq3_s-to-f32-le-v1",
"original_gguf_sha256": hex::encode(identity.gguf_sha256),
"derived_f32_sha256": hex::encode(identity.derived_sha256),
"derived_f32_bytes": identity.derived_bytes,
"archive_sha256": hex::encode(archive_digest),
"tensors": identity.tensors.iter().map(|tensor| serde_json::json!({
"name": tensor.name,
"derived_offset": tensor.derived_offset,
"derived_bytes": tensor.derived_bytes,
"iq3_sha256": hex::encode(tensor.iq3_sha256),
"f32_sha256": hex::encode(tensor.f32_sha256),
})).collect::<Vec<_>>(),
}),
DerivedIdentity::Mixed(identity) => serde_json::json!({
"schema": "strata-next/mixed-preview-provenance-v1",
"derivation": "strata-next/gguf-mixed-to-f32-le-v1",
"original_gguf_sha256": hex::encode(identity.gguf_sha256),
"derived_f32_sha256": hex::encode(identity.derived_sha256),
"derived_f32_bytes": identity.derived_bytes,
"archive_sha256": hex::encode(archive_digest),
"tensors": identity.tensors.iter().map(|tensor| serde_json::json!({
"name": tensor.name,
"source_kind": tensor.source_kind,
"source_sha256": hex::encode(tensor.source_sha256),
"derived_offset": tensor.derived_offset,
"derived_bytes": tensor.derived_bytes,
"f32_sha256": hex::encode(tensor.f32_sha256),
})).collect::<Vec<_>>(),
}),
}
}
pub(super) fn sharded_provenance_value(
identity: &derived_mixed::ShardedIdentity,
archive_digest: [u8; 32],
) -> serde_json::Value {
serde_json::json!({
"schema": "strata-next/sharded-preview-provenance-v1",
"derivation": "strata-next/gguf-shards-to-f32-le-v1",
"derived_f32_sha256": hex::encode(identity.derived_sha256),
"derived_f32_bytes": identity.derived_bytes,
"archive_sha256": hex::encode(archive_digest),
"shards": identity.shards.iter().map(|shard| serde_json::json!({
"name": shard.name,
"gguf_sha256": hex::encode(shard.gguf_sha256),
"gguf_bytes": shard.gguf_bytes,
"tensor_count": shard.tensor_count,
})).collect::<Vec<_>>(),
"tensors": identity.tensors.iter().map(|tensor| serde_json::json!({
"name": tensor.name,
"source_kind": tensor.source_kind,
"source_sha256": hex::encode(tensor.source_sha256),
"derived_offset": tensor.derived_offset,
"derived_bytes": tensor.derived_bytes,
"f32_sha256": hex::encode(tensor.f32_sha256),
})).collect::<Vec<_>>(),
})
}
pub(super) fn partitioned_provenance(
parts: &[Vec<stream_parts::PartIdentity>],
) -> serde_json::Value {
serde_json::json!(
parts
.iter()
.filter(|group| group.len() > 1)
.map(|group| {
serde_json::json!({
"parent_name": group[0].parent_name,
"parent_dimensions": group[0].parent_dimensions,
"source_kind": group[0].source_kind,
"parts": group.iter().map(|part| serde_json::json!({
"name": part.name,
"dimensions": part.dimensions,
"source_byte_offset": part.source_byte_offset,
"source_bytes": part.source_bytes,
"source_sha256": hex::encode(part.source_sha256),
"derived_offset": part.derived_offset,
"derived_bytes": part.derived_bytes,
"f32_sha256": hex::encode(part.f32_sha256),
})).collect::<Vec<_>>(),
})
})
.collect::<Vec<_>>()
)
}
pub(super) fn write_provenance(path: &Path, value: &serde_json::Value) -> Result<(), String> {
if fs::symlink_metadata(path).is_ok() {
return Err("provenance destination already exists".into());
}
let temporary = path.with_file_name(format!(
"{}.part",
path.file_name()
.ok_or("provenance path has no file name")?
.to_string_lossy()
));
let result = (|| {
let mut file = fs::OpenOptions::new()
.write(true)
.create_new(true)
.open(&temporary)
.map_err(|error| error.to_string())?;
serde_json::to_writer_pretty(&mut file, value).map_err(|error| error.to_string())?;
use std::io::Write;
file.write_all(b"\n").map_err(|error| error.to_string())?;
file.sync_all().map_err(|error| error.to_string())?;
fs::hard_link(&temporary, path).map_err(|error| error.to_string())?;
Ok(())
})();
let _ = fs::remove_file(&temporary);
result
}
pub(super) fn hash_file(path: &Path) -> Result<[u8; 32], String> {
let mut source = File::open(path).map_err(|error| error.to_string())?;
let mut digest = Sha256::new();
let mut buffer = [0u8; 1024 * 1024];
loop {
let count = source
.read(&mut buffer)
.map_err(|error| error.to_string())?;
if count == 0 {
break;
}
digest.update(&buffer[..count]);
}
Ok(digest.finalize().into())
}
+4 -309
View File
@@ -28,57 +28,6 @@ struct Series {
label: Option<(&'static str, &'static str)>,
}
const fn counter(name: &'static str, help: &'static str, from: &'static str, scale: f64) -> Series {
Series {
name,
kind: Kind::Counter,
help,
from,
scale,
label: None,
}
}
const fn gauge(name: &'static str, help: &'static str, from: &'static str, scale: f64) -> Series {
Series {
name,
kind: Kind::Gauge,
help,
from,
scale,
label: None,
}
}
const fn labelled_counter(
name: &'static str,
help: &'static str,
from: &'static str,
label: (&'static str, &'static str),
) -> Series {
Series {
name,
kind: Kind::Counter,
help,
from,
scale: 1.0,
label: Some(label),
}
}
const fn labelled(
name: &'static str,
help: &'static str,
from: &'static str,
label: (&'static str, &'static str),
) -> Series {
Series {
name,
kind: Kind::Gauge,
help,
from,
scale: 1.0,
label: Some(label),
}
}
const SERIES: &[Series] = &[
counter(
"leleka_generations_started_total",
@@ -484,263 +433,9 @@ const THROTTLE_REASONS: [(u64, &str); 5] = [
(0x80, "hw_power_brake"),
];
fn escape(text: &str) -> String {
text.replace('\\', "\\\\")
.replace('\n', "\\n")
.replace('"', "\\\"")
}
fn format_value(value: f64) -> String {
if value.fract() == 0.0 && value.abs() < 1e15 {
format!("{}", value as i64)
} else {
format!("{value}")
}
}
/// Render the `/metrics` document. `model` (when the document has one) labels `leleka_info`.
pub fn render(document: &Value) -> String {
let mut out = String::new();
let mut described: Vec<&str> = Vec::new();
for series in SERIES {
let Some(raw) = document.pointer(series.from) else {
continue;
};
let value = match raw {
Value::Bool(flag) => f64::from(u8::from(*flag)),
other => match other.as_f64() {
Some(number) if number.is_finite() => number * series.scale,
_ => continue,
},
};
if !described.contains(&series.name) {
described.push(series.name);
let kind = if series.kind == Kind::Counter {
"counter"
} else {
"gauge"
};
let _ = writeln!(out, "# HELP {} {}", series.name, series.help);
let _ = writeln!(out, "# TYPE {} {kind}", series.name);
}
match series.label {
Some((name, label)) => {
let _ = writeln!(
out,
"{}{{{name}=\"{label}\"}} {}",
series.name,
format_value(value)
);
}
None => {
let _ = writeln!(out, "{} {}", series.name, format_value(value));
}
}
}
if let Some(phase) = document.pointer("/telemetry/phase").and_then(Value::as_str) {
let _ = writeln!(
out,
"# HELP leleka_engine_phase 1 for the phase the engine is in."
);
let _ = writeln!(out, "# TYPE leleka_engine_phase gauge");
for candidate in PHASES {
let _ = writeln!(
out,
"leleka_engine_phase{{phase=\"{candidate}\"}} {}",
u8::from(candidate == phase)
);
}
}
if let Some(mask) = document
.pointer("/telemetry/gpu/throttle_reasons")
.and_then(Value::as_u64)
{
// The reasons that cost speed, one-hot (the full mask is `leleka_gpu_throttle_reasons`).
let _ = writeln!(
out,
"# HELP leleka_gpu_throttled 1 while the driver holds the GPU clocks down for this reason."
);
let _ = writeln!(out, "# TYPE leleka_gpu_throttled gauge");
for (bit, reason) in THROTTLE_REASONS {
let _ = writeln!(
out,
"leleka_gpu_throttled{{reason=\"{reason}\"}} {}",
u8::from(mask & bit != 0)
);
}
}
let _ = writeln!(out, "# HELP leleka_info The served model.");
let _ = writeln!(out, "# TYPE leleka_info gauge");
let model = document.get("model").and_then(Value::as_str).unwrap_or("");
let _ = writeln!(out, "leleka_info{{model=\"{}\"}} 1", escape(model));
crate::request_log::render_prometheus(&mut out);
out
}
/// Whether a request asks for the text exposition: `?format=prometheus` (or `openmetrics`/`text`), or an `Accept` that lists
/// `text/plain` or OpenMetrics (what a Prometheus scraper sends) and does not ask for JSON first.
pub fn wanted(query: Option<&str>, accept: Option<&str>) -> bool {
if let Some(query) = query {
for pair in query.split('&') {
if let Some(("format", value)) = pair.split_once('=') {
return matches!(value, "prometheus" | "openmetrics" | "text");
}
}
}
let Some(accept) = accept else { return false };
let accept = accept.to_ascii_lowercase();
let text = accept
.find("text/plain")
.or_else(|| accept.find("openmetrics-text"));
let json = accept.find("application/json");
match (text, json) {
(Some(text), Some(json)) => text < json,
(Some(_), None) => true,
_ => false,
}
}
#[cfg(test)]
mod tests {
use super::*;
use serde_json::json;
mod tests;
fn document() -> Value {
json!({
"model": "qwen \"3.8\"", "up": true, "queue_used": 1, "queue_capacity": 64,
"generation": {"started": 5, "completed": 3, "cancelled": 1, "failed_or_interrupted": 1},
"totals": {"prompt_tokens": 1000, "reused": 400, "output_tokens": 250, "prompt_ms": 2500.0, "decode_ms": 1250.0, "drafts_offered": 90, "drafts_accepted": 60},
"memory": {"gate_rejections": 2},
"live": {"active": true, "elapsed_s": 3.5, "queued": 0},
"engine": {"max_context": 262144},
"hardware": {"gpu_util": 91, "gpu_mem_used": 31457280000u64, "gpu_temp": 61, "gpu_power": 480.5, "cpu": 31.0, "tok_s": 128.4, "tok_s_mean": 120.0, "prefill_tok_s_mean": 5050.0, "ram_used": 5.0e10},
"telemetry": {"phase": "decode", "context": {"live_tokens": 101200, "used_pct": 38.6},
"throughput": {"decode_tok_s_last": 100.0, "decode_tok_s_lifetime": null},
"cache": {"requests": 2, "hit_ratio": 0.5}},
})
}
#[test]
fn counters_gauges_and_labels_render_in_the_text_format() {
let text = render(&document());
assert!(text.contains(
"# TYPE leleka_generations_started_total counter\nleleka_generations_started_total 5\n"
));
assert!(text.contains("leleka_prefill_seconds_total 2.5\n"));
assert!(text.contains("leleka_decode_seconds_total 1.25\n"));
assert!(text.contains("leleka_up 1\n") && text.contains("leleka_generation_active 1\n"));
assert!(text.contains(
"# TYPE leleka_gpu_memory_used_bytes gauge\nleleka_gpu_memory_used_bytes 31457280000\n"
));
assert!(text.contains("leleka_gpu_power_watts 480.5\n"));
assert!(text.contains("leleka_context_live_tokens 101200\n"));
// one HELP/TYPE per metric, a series per label value
assert_eq!(
text.matches("# TYPE leleka_decode_tokens_per_second")
.count(),
1
);
assert!(text.contains("leleka_decode_tokens_per_second{window=\"live\"} 128.4\n"));
assert!(text.contains("leleka_decode_tokens_per_second{window=\"last\"} 100\n"));
assert!(text.contains("leleka_decode_tokens_per_second{window=\"average\"} 120\n"));
assert!(
text.contains("leleka_engine_phase{phase=\"decode\"} 1\n")
&& text.contains("leleka_engine_phase{phase=\"idle\"} 0\n")
);
assert!(text.contains("leleka_info{model=\"qwen \\\"3.8\\\"\"} 1\n"));
}
#[test]
fn engine_gauges_counters_and_throttle_reasons_are_exposed_with_fixed_labels() {
let mut doc = document();
doc["api_uptime_s"] = json!(120);
doc["supervisor"] = json!({"uptime_s": 86400, "restarts_total": 3});
doc["telemetry"]["uptime_s"] = json!(3600);
doc["telemetry"]["gpu"] = json!({"mem_clock_mhz": 14001, "pcie_rx_kb_s": 2048, "pcie_tx_kb_s": 1024, "throttle_reasons": 0x44});
doc["telemetry"]["spec"] = json!({"rounds": 100, "tokens": 320, "tokens_per_round": 3.2});
doc["telemetry"]["expert_tier"] = json!({"vram_entries": 900, "pcie_entries": 60, "cpu_entries": 40, "swaps": 7, "vram_ratio": 0.9});
let text = render(&doc);
for expected in [
"leleka_gpu_pcie_receive_bytes_per_second 2097152\n",
"leleka_gpu_pcie_transmit_bytes_per_second 1048576\n",
"leleka_gpu_memory_clock_megahertz 14001\n",
"# TYPE leleka_engine_restarts_total counter\nleleka_engine_restarts_total 3\n",
"leleka_service_uptime_seconds 86400\n",
"leleka_api_uptime_seconds 120\n",
"leleka_engine_uptime_seconds 3600\n",
"leleka_spec_tokens_per_round 3.2\n",
"leleka_expert_tier_entries_total{tier=\"vram\"} 900\n",
"leleka_expert_tier_entries_total{tier=\"pcie\"} 60\n",
"leleka_expert_tier_vram_ratio 0.9\n",
"leleka_gpu_throttled{reason=\"hw_thermal\"} 1\n",
"leleka_gpu_throttled{reason=\"sw_power_cap\"} 1\n",
"leleka_gpu_throttled{reason=\"hw_slowdown\"} 0\n",
"leleka_request_ttft_seconds_bucket{le=\"+Inf\"}",
"leleka_engine_lost_total ",
] {
assert!(text.contains(expected), "{expected} missing:\n{text}");
}
// not eprintln!: tests/log_failure_sse.rs forbids it in this crate (it panics when stderr is unwritable)
let _ = std::io::Write::write_fmt(
&mut std::io::stderr(),
format_args!(
"PROM-SAMPLE
{text}
"
),
);
// one TYPE line per metric even with three tier series
assert_eq!(
text.matches("# TYPE leleka_expert_tier_entries_total")
.count(),
1
);
// every label value comes from a fixed list, never from a request
for line in text
.lines()
.filter(|l| l.contains('{') && !l.starts_with('#'))
{
assert!(!line.contains("req-") && !line.contains("s-"), "{line}");
}
}
#[test]
fn unmeasured_figures_are_not_exposed() {
let text = render(&document());
// null in the document: no lifetime decode rate, no GPU clock, no swap
assert!(!text.contains("window=\"lifetime\""));
assert!(!text.contains("leleka_gpu_sm_clock_megahertz"));
let bare = render(&json!({"model": "m", "up": false}));
assert!(bare.contains("leleka_up 0\n"));
assert!(!bare.contains("leleka_gpu_") && !bare.contains("leleka_engine_phase"));
// every line is HELP, TYPE or a sample
for line in text.lines() {
assert!(
line.starts_with("# HELP ")
|| line.starts_with("# TYPE ")
|| line.starts_with("leleka_"),
"{line}"
);
}
}
#[test]
fn the_format_is_chosen_by_query_or_accept() {
assert!(wanted(Some("format=prometheus"), None));
assert!(wanted(Some("requests=all&format=openmetrics"), None));
assert!(!wanted(Some("format=json"), Some("text/plain")));
assert!(!wanted(None, None));
assert!(!wanted(None, Some("*/*")));
assert!(!wanted(None, Some("application/json")));
// what a Prometheus server sends
assert!(wanted(
None,
Some(
"application/openmetrics-text;version=1.0.0,text/plain;version=0.0.4;q=0.5,*/*;q=0.1"
)
));
assert!(wanted(None, Some("text/plain")));
// a browser or SDK that prefers JSON keeps the JSON document
assert!(!wanted(None, Some("application/json, text/plain, */*")));
}
}
mod counter;
#[allow(unused_imports)]
pub use counter::*;
+181
View File
@@ -0,0 +1,181 @@
//! Moved out of the parent module by STRA-338: fn counter, fn gauge, fn labelled_counter, fn labelled, fn escape, fn format_value ....
#[allow(unused_imports)]
use super::*;
pub(super) const fn counter(
name: &'static str,
help: &'static str,
from: &'static str,
scale: f64,
) -> Series {
Series {
name,
kind: Kind::Counter,
help,
from,
scale,
label: None,
}
}
pub(super) const fn gauge(
name: &'static str,
help: &'static str,
from: &'static str,
scale: f64,
) -> Series {
Series {
name,
kind: Kind::Gauge,
help,
from,
scale,
label: None,
}
}
pub(super) const fn labelled_counter(
name: &'static str,
help: &'static str,
from: &'static str,
label: (&'static str, &'static str),
) -> Series {
Series {
name,
kind: Kind::Counter,
help,
from,
scale: 1.0,
label: Some(label),
}
}
pub(super) const fn labelled(
name: &'static str,
help: &'static str,
from: &'static str,
label: (&'static str, &'static str),
) -> Series {
Series {
name,
kind: Kind::Gauge,
help,
from,
scale: 1.0,
label: Some(label),
}
}
pub(super) fn escape(text: &str) -> String {
text.replace('\\', "\\\\")
.replace('\n', "\\n")
.replace('"', "\\\"")
}
pub(super) fn format_value(value: f64) -> String {
if value.fract() == 0.0 && value.abs() < 1e15 {
format!("{}", value as i64)
} else {
format!("{value}")
}
}
/// Render the `/metrics` document. `model` (when the document has one) labels `leleka_info`.
pub fn render(document: &Value) -> String {
let mut out = String::new();
let mut described: Vec<&str> = Vec::new();
for series in SERIES {
let Some(raw) = document.pointer(series.from) else {
continue;
};
let value = match raw {
Value::Bool(flag) => f64::from(u8::from(*flag)),
other => match other.as_f64() {
Some(number) if number.is_finite() => number * series.scale,
_ => continue,
},
};
if !described.contains(&series.name) {
described.push(series.name);
let kind = if series.kind == Kind::Counter {
"counter"
} else {
"gauge"
};
let _ = writeln!(out, "# HELP {} {}", series.name, series.help);
let _ = writeln!(out, "# TYPE {} {kind}", series.name);
}
match series.label {
Some((name, label)) => {
let _ = writeln!(
out,
"{}{{{name}=\"{label}\"}} {}",
series.name,
format_value(value)
);
}
None => {
let _ = writeln!(out, "{} {}", series.name, format_value(value));
}
}
}
if let Some(phase) = document.pointer("/telemetry/phase").and_then(Value::as_str) {
let _ = writeln!(
out,
"# HELP leleka_engine_phase 1 for the phase the engine is in."
);
let _ = writeln!(out, "# TYPE leleka_engine_phase gauge");
for candidate in PHASES {
let _ = writeln!(
out,
"leleka_engine_phase{{phase=\"{candidate}\"}} {}",
u8::from(candidate == phase)
);
}
}
if let Some(mask) = document
.pointer("/telemetry/gpu/throttle_reasons")
.and_then(Value::as_u64)
{
// The reasons that cost speed, one-hot (the full mask is `leleka_gpu_throttle_reasons`).
let _ = writeln!(
out,
"# HELP leleka_gpu_throttled 1 while the driver holds the GPU clocks down for this reason."
);
let _ = writeln!(out, "# TYPE leleka_gpu_throttled gauge");
for (bit, reason) in THROTTLE_REASONS {
let _ = writeln!(
out,
"leleka_gpu_throttled{{reason=\"{reason}\"}} {}",
u8::from(mask & bit != 0)
);
}
}
let _ = writeln!(out, "# HELP leleka_info The served model.");
let _ = writeln!(out, "# TYPE leleka_info gauge");
let model = document.get("model").and_then(Value::as_str).unwrap_or("");
let _ = writeln!(out, "leleka_info{{model=\"{}\"}} 1", escape(model));
crate::request_log::render_prometheus(&mut out);
out
}
/// Whether a request asks for the text exposition: `?format=prometheus` (or `openmetrics`/`text`), or an `Accept` that lists
/// `text/plain` or OpenMetrics (what a Prometheus scraper sends) and does not ask for JSON first.
pub fn wanted(query: Option<&str>, accept: Option<&str>) -> bool {
if let Some(query) = query {
for pair in query.split('&') {
if let Some(("format", value)) = pair.split_once('=') {
return matches!(value, "prometheus" | "openmetrics" | "text");
}
}
}
let Some(accept) = accept else { return false };
let accept = accept.to_ascii_lowercase();
let text = accept
.find("text/plain")
.or_else(|| accept.find("openmetrics-text"));
let json = accept.find("application/json");
match (text, json) {
(Some(text), Some(json)) => text < json,
(Some(_), None) => true,
_ => false,
}
}

Some files were not shown because too many files have changed in this diff Show More