From 6b5fcd242ee4e5d5dc9e7e101be1e859e2152209 Mon Sep 17 00:00:00 2001 From: Pavlo Ratushnyi Date: Thu, 5 Nov 2026 15:29:39 +0100 Subject: [PATCH] STRA-338 S12b: fns and impl blocks of 59 cold oversize modules move into child modules (model-format, gateway, desktop-core, leaf libraries) scripts/dev/split_module.py (lexer-based, with 16 self-tests) moves the top-level fn and impl items of 59 oversize module files in control-plane, desktop-core, model-format, gateway-text, leleka-memory, experimental-ref, context, serving-policy, tokenizer, backend-api, quant-core, harmony, igpu, libc-shim, npu-service and runtime-client into foo/.rs groups of about 250 lines; types, constants, macros, nested modules and tests stay, every path stays valid through pub use re-exports, restricted visibilities keep their scope one level down, include paths and super:: paths are shifted. Not touched: leleka-runtime, cuda-driver, native-cpu-expert, sampler-ref and cpu-* (hot path, next wave) and the files kar-off-ab edits. The baseline drops from 311 to 263 oversize files and from 273,600 to about 233,000 lines; the path-include ratchet ignores dir/name.rs child declarations. --- architecture-baseline.json | 72 +- architecture.json | 2 +- control-plane/src/app.rs | 405 +---- .../src/app/impl_default_for_appstate.rs | 236 +++ control-plane/src/app/metrics_document.rs | 170 ++ control-plane/src/backend_worker.rs | 744 +-------- control-plane/src/backend_worker/conclude.rs | 136 ++ .../src/backend_worker/request_id.rs | 146 ++ .../src/backend_worker/run_backend_worker.rs | 227 +++ control-plane/src/backend_worker/serve_one.rs | 240 +++ control-plane/src/chat.rs | 579 +------ control-plane/src/chat/completion.rs | 239 +++ control-plane/src/chat/impl_request.rs | 227 +++ control-plane/src/chat/invalid.rs | 105 ++ control-plane/src/chat/stream_response.rs | 19 + control-plane/src/config.rs | 635 +------- control-plane/src/config/impl_config.rs | 520 ++++++ .../src/config/impl_controlvector.rs | 105 ++ control-plane/src/config/optional_env.rs | 12 + control-plane/src/kar_overlay.rs | 884 +--------- control-plane/src/kar_overlay/compare.rs | 237 +++ .../src/kar_overlay/impl_baseprovenance.rs | 144 ++ control-plane/src/kar_overlay/prepare.rs | 271 +++ .../src/kar_overlay/resolve_verified.rs | 217 +++ .../src/kar_overlay/write_provenance.rs | 21 + control-plane/src/kar_quality.rs | 414 +---- control-plane/src/kar_quality/analyze.rs | 247 +++ control-plane/src/kar_quality/parse_digest.rs | 171 ++ control-plane/src/kar_writer.rs | 867 +--------- control-plane/src/kar_writer/write_archive.rs | 31 + .../src/kar_writer/write_archive_inner.rs | 277 ++++ .../src/kar_writer/write_nested_section.rs | 228 +++ control-plane/src/kar_writer/write_record.rs | 89 + control-plane/src/kar_writer/write_section.rs | 251 +++ control-plane/src/mcp.rs | 1308 +-------------- control-plane/src/mcp/check_server.rs | 139 ++ control-plane/src/mcp/dispatch.rs | 69 + .../src/mcp/impl_default_for_settings.rs | 57 + control-plane/src/mcp/impl_http.rs | 233 +++ control-plane/src/mcp/impl_hub.rs | 208 +++ control-plane/src/mcp/impl_server.rs | 219 +++ control-plane/src/mcp/impl_stdiotransport.rs | 245 +++ control-plane/src/mcp/impl_transport.rs | 52 + control-plane/src/mcp/result_text.rs | 102 ++ control-plane/src/messages.rs | 508 +----- control-plane/src/messages/adapt.rs | 85 + control-plane/src/messages/error_type.rs | 194 +++ .../src/messages/impl_countrequest.rs | 237 +++ control-plane/src/model.rs | 418 +---- control-plane/src/model/fetch_one.rs | 240 +++ control-plane/src/model/impl_manifest.rs | 179 ++ control-plane/src/mtp_fetch.rs | 497 +----- control-plane/src/mtp_fetch/impl_fetcher.rs | 377 +++++ control-plane/src/mtp_fetch/mtime_ns.rs | 75 + control-plane/src/mtp_fetch/repo_url.rs | 49 + control-plane/src/native_pack.rs | 1092 +------------ .../src/native_pack/conversions_inexact.rs | 239 +++ .../src/native_pack/convert_tensor.rs | 212 +++ control-plane/src/native_pack/dense_files.rs | 250 +++ .../src/native_pack/expert_layout.rs | 236 +++ control-plane/src/native_pack/safe_name.rs | 133 ++ control-plane/src/native_pack/same_bytes.rs | 32 + control-plane/src/prepare_preview.rs | 1335 +-------------- .../prepare_preview/encode_preview_tensor.rs | 244 +++ .../minimum_part_payload_bytes.rs | 102 ++ control-plane/src/prepare_preview/prepare.rs | 213 +++ .../src/prepare_preview/prepare_sharded.rs | 233 +++ .../prepare_sharded_streamed_with_policy.rs | 271 +++ .../src/prepare_preview/spool_raw_f32.rs | 50 + .../src/prepare_preview/verify_derived.rs | 237 +++ control-plane/src/prometheus.rs | 171 +- control-plane/src/prometheus/counter.rs | 181 ++ control-plane/src/reasoning_budget.rs | 329 +--- .../src/reasoning_budget/reasoning_budget.rs | 239 +++ control-plane/src/reasoning_budget/run.rs | 91 ++ control-plane/src/request_log.rs | 559 +------ .../src/request_log/endpoint_index.rs | 201 +++ .../src/request_log/impl_obshandle.rs | 237 +++ .../src/request_log/note_engine_attached.rs | 123 ++ control-plane/src/request_monitor.rs | 492 +----- .../src/request_monitor/impl_record.rs | 231 +++ .../request_monitor/impl_requestmonitor.rs | 227 +++ control-plane/src/request_monitor/now_unix.rs | 36 + control-plane/src/responses/harmony_prompt.rs | 417 +---- .../responses/harmony_prompt/civil_date.rs | 187 +++ .../responses/harmony_prompt/conversation.rs | 231 +++ control-plane/src/server_api.rs | 664 +------- control-plane/src/server_api/error_body.rs | 224 +++ control-plane/src/server_api/model_busy.rs | 204 +++ control-plane/src/server_api/slots.rs | 244 +++ control-plane/src/service_install.rs | 371 +---- control-plane/src/service_install/control.rs | 186 +++ control-plane/src/service_install/parse.rs | 188 +++ control-plane/src/service_switch.rs | 491 +----- .../src/service_switch/provision_budget.rs | 188 +++ control-plane/src/service_switch/reconcile.rs | 99 ++ control-plane/src/service_switch/run.rs | 210 +++ control-plane/src/vision.rs | 397 +---- .../src/vision/impl_drop_for_vision.rs | 45 + control-plane/src/vision/impl_vision.rs | 276 ++++ control-plane/src/vision/impl_visionconfig.rs | 82 + control-plane/src/worker.rs | 931 +---------- control-plane/src/worker/combine_done.rs | 255 +++ control-plane/src/worker/finish.rs | 121 ++ .../src/worker/impl_generationresult.rs | 181 ++ control-plane/src/worker/run_session.rs | 240 +++ control-plane/src/worker/run_supervised.rs | 143 ++ crates/backend-api/src/scripted.rs | 451 +---- .../impl_backend_for_scriptedengine.rs | 190 +++ .../backend-api/src/scripted/impl_script.rs | 161 ++ crates/backend-api/src/scripted/play.rs | 102 ++ crates/context/src/memory_plan.rs | 347 +--- .../memory_plan/impl_default_for_geometry.rs | 227 +++ .../src/memory_plan/plan_with_per_token.rs | 126 ++ crates/context/src/rope_scaling.rs | 518 +----- .../src/rope_scaling/fill_rope_table.rs | 238 +++ .../src/rope_scaling/impl_fmt_display_for.rs | 50 + .../src/rope_scaling/impl_ropescalingtype.rs | 232 +++ crates/experimental-ref/src/cvec.rs | 381 +---- .../src/cvec/impl_std_fmt_display.rs | 176 ++ .../src/cvec/load_control_vectors.rs | 208 +++ crates/experimental-ref/src/kv_stream.rs | 324 +--- .../src/kv_stream/impl_streammap.rs | 233 +++ .../src/kv_stream/map_bytes.rs | 94 ++ crates/gateway-text/src/prompt.rs | 790 +-------- crates/gateway-text/src/prompt/impl_json.rs | 237 +++ .../gateway-text/src/prompt/impl_renderer.rs | 243 +++ crates/gateway-text/src/prompt/json_string.rs | 200 +++ .../src/prompt/without_empty_turns.rs | 109 ++ crates/gateway-text/src/tool_output.rs | 1086 +----------- .../src/tool_output/find_parameter_end.rs | 104 ++ .../src/tool_output/impl_incremental.rs | 223 +++ .../src/tool_output/impl_notes.rs | 69 + .../src/tool_output/parameter_value.rs | 246 +++ .../src/tool_output/parse_text.rs | 243 +++ .../src/tool_output/starts_batched_call.rs | 211 +++ crates/harmony/src/render.rs | 463 +----- .../harmony/src/render/impl_renderoptions.rs | 238 +++ crates/harmony/src/render/render_namespace.rs | 230 +++ crates/igpu/src/shaders.rs | 190 +-- crates/igpu/src/shaders/gemm.rs | 193 +++ crates/leleka-memory/src/governor.rs | 839 +--------- .../governor/impl_drop_for_samplerguard.rs | 14 + .../src/governor/impl_governor.rs | 739 +++++++++ .../src/governor/impl_governorconfig.rs | 91 ++ crates/leleka-memory/src/lock.rs | 94 +- .../leleka-memory/src/lock/impl_lockmode.rs | 95 ++ crates/leleka-memory/src/plan.rs | 261 +-- .../src/plan/auto_prefix_budget.rs | 25 + crates/leleka-memory/src/plan/impl_policy.rs | 239 +++ crates/leleka-memory/src/telemetry.rs | 368 +---- crates/leleka-memory/src/telemetry/lock.rs | 233 +++ crates/leleka-memory/src/telemetry/render.rs | 138 ++ crates/libc-shim/src/cuda_trace.rs | 322 +--- crates/libc-shim/src/cuda_trace/enabled.rs | 219 +++ crates/libc-shim/src/cuda_trace/w_launch.rs | 106 ++ crates/model-format/src/bulk_read.rs | 336 +--- .../src/bulk_read/for_each_chunk.rs | 121 ++ .../src/bulk_read/impl_strategy.rs | 218 +++ crates/model-format/src/gguf.rs | 1230 +------------- crates/model-format/src/gguf/impl_cursor.rs | 270 +++ .../src/gguf/impl_verifiedgguffile.rs | 243 +++ .../src/gguf/parse_artifact_digest.rs | 187 +++ .../model-format/src/gguf/read_index_file.rs | 216 +++ ...ead_metadata_snapshot_with_architecture.rs | 209 +++ .../src/gguf/stream_buffer_bytes.rs | 33 + crates/model-format/src/gguf/value_width.rs | 85 + crates/model-format/src/gguf_resident.rs | 396 +---- .../gguf_resident/impl_verifiedgguffile.rs | 232 +++ .../gguf_resident/impl_verifiedgguffile_2.rs | 93 ++ .../src/gguf_resident/next_source_id.rs | 73 + crates/model-format/src/kar.rs | 1404 +--------------- .../src/kar/decode_record_range.rs | 140 ++ .../src/kar/impl_karpleprofile.rs | 92 ++ .../src/kar/impl_std_fmt_display.rs | 245 +++ .../src/kar/impl_verifiedkarpleartifact.rs | 239 +++ .../src/kar/independent_handles.rs | 211 +++ crates/model-format/src/kar/inspect_file.rs | 286 ++++ crates/model-format/src/kar/read_region.rs | 204 +++ crates/model-format/src/kar_extents.rs | 412 +---- .../src/kar_extents/impl_extent.rs | 203 +++ .../src/kar_extents/impl_karinspection.rs | 212 +++ crates/model-format/src/kar_kernel_model.rs | 412 +---- .../kar_kernel_model/decode_params_valid.rs | 194 +++ .../kar_kernel_model/impl_fmt_display_for.rs | 221 +++ crates/model-format/src/kar_levels.rs | 501 +----- .../src/kar_levels/expert_scratch.rs | 54 + .../src/kar_levels/impl_fmt_display_for.rs | 227 +++ .../src/kar_levels/impl_selection.rs | 227 +++ crates/model-format/src/ple_reader.rs | 700 +------- .../src/ple_reader/impl_fmt_debug_for.rs | 20 + .../ple_reader/impl_pagesource_for_file.rs | 220 +++ .../src/ple_reader/impl_plereader.rs | 257 +++ .../model-format/src/ple_reader/impl_state.rs | 210 +++ crates/model-format/src/qwen4exp.rs | 1449 +---------------- .../src/qwen4exp/expected_inventory.rs | 317 ++++ .../src/qwen4exp/impl_fmt_display_for.rs | 114 ++ .../src/qwen4exp/impl_qwen4expartifact.rs | 253 +++ .../src/qwen4exp/impl_qwen4expartifact_2.rs | 38 + .../src/qwen4exp/plan_stream_rows.rs | 252 +++ .../src/qwen4exp/validate_logical_views.rs | 61 + .../qwen4exp/validate_owner_index_split.rs | 241 +++ .../src/qwen4exp/validate_role_inventory.rs | 188 +++ .../src/qwen4exp_digest_capture.rs | 794 +-------- .../qwen4exp_digest_capture/capture_admit.rs | 72 + .../impl_provisionalexpertsource.rs | 211 +++ .../impl_provisionalexpertsource_2.rs | 199 +++ .../impl_provisionalexpertsource_3.rs | 80 + .../impl_qwen4expartifact.rs | 236 +++ .../src/qwen4exp_expert_source_bank.rs | 576 +------ .../impl_qwen4expartifact.rs | 252 +++ .../impl_qwen4expartifact_2.rs | 136 ++ .../retention_metadata_bytes.rs | 190 +++ crates/npu-service/src/engine.rs | 357 +--- crates/npu-service/src/engine/impl_engine.rs | 206 +++ crates/npu-service/src/engine/impl_weights.rs | 154 ++ crates/runtime-client/src/backend.rs | 422 +---- .../src/backend/consumer_gone.rs | 54 + .../src/backend/impl_api_backend_for.rs | 273 ++++ .../runtime-client/src/backend/log_status.rs | 103 ++ crates/serving-policy/src/cvec.rs | 353 +--- .../serving-policy/src/cvec/build_tables.rs | 170 ++ crates/serving-policy/src/cvec/impl_cursor.rs | 184 +++ crates/serving-policy/src/shared.rs | 358 +--- .../src/shared/impl_shareddefaults.rs | 192 +++ .../shared/sampling_defaults_from_config.rs | 167 ++ crates/tokenizer/src/fast.rs | 387 +---- crates/tokenizer/src/fast/impl_fast.rs | 162 ++ crates/tokenizer/src/fast/unicode_ranges.rs | 226 +++ crates/tokenizer/src/gguf_bpe.rs | 381 +---- .../src/gguf_bpe/impl_fmt_display_for.rs | 38 + crates/tokenizer/src/gguf_bpe/impl_ggufbpe.rs | 295 ++++ .../tokenizer/src/gguf_bpe/impl_utf8stream.rs | 50 + desktop-core/src/gateway.rs | 525 +----- .../src/gateway/impl_drop_for_inflight.rs | 54 + desktop-core/src/gateway/responses.rs | 237 +++ desktop-core/src/gateway/secret.rs | 241 +++ desktop-core/src/managed_worker.rs | 433 +---- .../managed_worker/default_capabilities.rs | 248 +++ desktop-core/src/managed_worker/start.rs | 193 +++ desktop-core/src/runtime_gateway.rs | 877 +--------- .../buffered_tool_generation.rs | 193 +++ .../src/runtime_gateway/credential.rs | 210 +++ desktop-core/src/runtime_gateway/load.rs | 246 +++ .../src/runtime_gateway/response_value.rs | 245 +++ desktop-core/src/runtime_rpc.rs | 1003 +----------- desktop-core/src/runtime_rpc/clear_active.rs | 233 +++ .../src/runtime_rpc/event_to_proto.rs | 58 + .../impl_proto_runtime_server_runtime.rs | 463 ++++++ .../src/runtime_rpc/impl_runtimeserver.rs | 150 ++ desktop-core/src/runtime_rpc/lock.rs | 104 ++ desktop-core/src/runtime_tools.rs | 674 +------- desktop-core/src/runtime_tools/fields.rs | 93 ++ desktop-core/src/runtime_tools/history.rs | 174 ++ .../src/runtime_tools/impl_toolpolicy.rs | 243 +++ .../src/runtime_tools/impl_write_for_count.rs | 174 ++ scripts/dev/rustsplit/__init__.py | 1 + scripts/dev/rustsplit/items.py | 149 ++ scripts/dev/rustsplit/lexer.py | 120 ++ scripts/dev/rustsplit/retarget.py | 83 + scripts/dev/rustsplit/split.py | 82 + scripts/dev/rustsplit_test.py | 138 ++ scripts/dev/split_module.py | 84 + 263 files changed, 36565 insertions(+), 34333 deletions(-) create mode 100644 control-plane/src/app/impl_default_for_appstate.rs create mode 100644 control-plane/src/app/metrics_document.rs create mode 100644 control-plane/src/backend_worker/conclude.rs create mode 100644 control-plane/src/backend_worker/request_id.rs create mode 100644 control-plane/src/backend_worker/run_backend_worker.rs create mode 100644 control-plane/src/backend_worker/serve_one.rs create mode 100644 control-plane/src/chat/completion.rs create mode 100644 control-plane/src/chat/impl_request.rs create mode 100644 control-plane/src/chat/invalid.rs create mode 100644 control-plane/src/chat/stream_response.rs create mode 100644 control-plane/src/config/impl_config.rs create mode 100644 control-plane/src/config/impl_controlvector.rs create mode 100644 control-plane/src/config/optional_env.rs create mode 100644 control-plane/src/kar_overlay/compare.rs create mode 100644 control-plane/src/kar_overlay/impl_baseprovenance.rs create mode 100644 control-plane/src/kar_overlay/prepare.rs create mode 100644 control-plane/src/kar_overlay/resolve_verified.rs create mode 100644 control-plane/src/kar_overlay/write_provenance.rs create mode 100644 control-plane/src/kar_quality/analyze.rs create mode 100644 control-plane/src/kar_quality/parse_digest.rs create mode 100644 control-plane/src/kar_writer/write_archive.rs create mode 100644 control-plane/src/kar_writer/write_archive_inner.rs create mode 100644 control-plane/src/kar_writer/write_nested_section.rs create mode 100644 control-plane/src/kar_writer/write_record.rs create mode 100644 control-plane/src/kar_writer/write_section.rs create mode 100644 control-plane/src/mcp/check_server.rs create mode 100644 control-plane/src/mcp/dispatch.rs create mode 100644 control-plane/src/mcp/impl_default_for_settings.rs create mode 100644 control-plane/src/mcp/impl_http.rs create mode 100644 control-plane/src/mcp/impl_hub.rs create mode 100644 control-plane/src/mcp/impl_server.rs create mode 100644 control-plane/src/mcp/impl_stdiotransport.rs create mode 100644 control-plane/src/mcp/impl_transport.rs create mode 100644 control-plane/src/mcp/result_text.rs create mode 100644 control-plane/src/messages/adapt.rs create mode 100644 control-plane/src/messages/error_type.rs create mode 100644 control-plane/src/messages/impl_countrequest.rs create mode 100644 control-plane/src/model/fetch_one.rs create mode 100644 control-plane/src/model/impl_manifest.rs create mode 100644 control-plane/src/mtp_fetch/impl_fetcher.rs create mode 100644 control-plane/src/mtp_fetch/mtime_ns.rs create mode 100644 control-plane/src/mtp_fetch/repo_url.rs create mode 100644 control-plane/src/native_pack/conversions_inexact.rs create mode 100644 control-plane/src/native_pack/convert_tensor.rs create mode 100644 control-plane/src/native_pack/dense_files.rs create mode 100644 control-plane/src/native_pack/expert_layout.rs create mode 100644 control-plane/src/native_pack/safe_name.rs create mode 100644 control-plane/src/native_pack/same_bytes.rs create mode 100644 control-plane/src/prepare_preview/encode_preview_tensor.rs create mode 100644 control-plane/src/prepare_preview/minimum_part_payload_bytes.rs create mode 100644 control-plane/src/prepare_preview/prepare.rs create mode 100644 control-plane/src/prepare_preview/prepare_sharded.rs create mode 100644 control-plane/src/prepare_preview/prepare_sharded_streamed_with_policy.rs create mode 100644 control-plane/src/prepare_preview/spool_raw_f32.rs create mode 100644 control-plane/src/prepare_preview/verify_derived.rs create mode 100644 control-plane/src/prometheus/counter.rs create mode 100644 control-plane/src/reasoning_budget/reasoning_budget.rs create mode 100644 control-plane/src/reasoning_budget/run.rs create mode 100644 control-plane/src/request_log/endpoint_index.rs create mode 100644 control-plane/src/request_log/impl_obshandle.rs create mode 100644 control-plane/src/request_log/note_engine_attached.rs create mode 100644 control-plane/src/request_monitor/impl_record.rs create mode 100644 control-plane/src/request_monitor/impl_requestmonitor.rs create mode 100644 control-plane/src/request_monitor/now_unix.rs create mode 100644 control-plane/src/responses/harmony_prompt/civil_date.rs create mode 100644 control-plane/src/responses/harmony_prompt/conversation.rs create mode 100644 control-plane/src/server_api/error_body.rs create mode 100644 control-plane/src/server_api/model_busy.rs create mode 100644 control-plane/src/server_api/slots.rs create mode 100644 control-plane/src/service_install/control.rs create mode 100644 control-plane/src/service_install/parse.rs create mode 100644 control-plane/src/service_switch/provision_budget.rs create mode 100644 control-plane/src/service_switch/reconcile.rs create mode 100644 control-plane/src/service_switch/run.rs create mode 100644 control-plane/src/vision/impl_drop_for_vision.rs create mode 100644 control-plane/src/vision/impl_vision.rs create mode 100644 control-plane/src/vision/impl_visionconfig.rs create mode 100644 control-plane/src/worker/combine_done.rs create mode 100644 control-plane/src/worker/finish.rs create mode 100644 control-plane/src/worker/impl_generationresult.rs create mode 100644 control-plane/src/worker/run_session.rs create mode 100644 control-plane/src/worker/run_supervised.rs create mode 100644 crates/backend-api/src/scripted/impl_backend_for_scriptedengine.rs create mode 100644 crates/backend-api/src/scripted/impl_script.rs create mode 100644 crates/backend-api/src/scripted/play.rs create mode 100644 crates/context/src/memory_plan/impl_default_for_geometry.rs create mode 100644 crates/context/src/memory_plan/plan_with_per_token.rs create mode 100644 crates/context/src/rope_scaling/fill_rope_table.rs create mode 100644 crates/context/src/rope_scaling/impl_fmt_display_for.rs create mode 100644 crates/context/src/rope_scaling/impl_ropescalingtype.rs create mode 100644 crates/experimental-ref/src/cvec/impl_std_fmt_display.rs create mode 100644 crates/experimental-ref/src/cvec/load_control_vectors.rs create mode 100644 crates/experimental-ref/src/kv_stream/impl_streammap.rs create mode 100644 crates/experimental-ref/src/kv_stream/map_bytes.rs create mode 100644 crates/gateway-text/src/prompt/impl_json.rs create mode 100644 crates/gateway-text/src/prompt/impl_renderer.rs create mode 100644 crates/gateway-text/src/prompt/json_string.rs create mode 100644 crates/gateway-text/src/prompt/without_empty_turns.rs create mode 100644 crates/gateway-text/src/tool_output/find_parameter_end.rs create mode 100644 crates/gateway-text/src/tool_output/impl_incremental.rs create mode 100644 crates/gateway-text/src/tool_output/impl_notes.rs create mode 100644 crates/gateway-text/src/tool_output/parameter_value.rs create mode 100644 crates/gateway-text/src/tool_output/parse_text.rs create mode 100644 crates/gateway-text/src/tool_output/starts_batched_call.rs create mode 100644 crates/harmony/src/render/impl_renderoptions.rs create mode 100644 crates/harmony/src/render/render_namespace.rs create mode 100644 crates/igpu/src/shaders/gemm.rs create mode 100644 crates/leleka-memory/src/governor/impl_drop_for_samplerguard.rs create mode 100644 crates/leleka-memory/src/governor/impl_governor.rs create mode 100644 crates/leleka-memory/src/governor/impl_governorconfig.rs create mode 100644 crates/leleka-memory/src/lock/impl_lockmode.rs create mode 100644 crates/leleka-memory/src/plan/auto_prefix_budget.rs create mode 100644 crates/leleka-memory/src/plan/impl_policy.rs create mode 100644 crates/leleka-memory/src/telemetry/lock.rs create mode 100644 crates/leleka-memory/src/telemetry/render.rs create mode 100644 crates/libc-shim/src/cuda_trace/enabled.rs create mode 100644 crates/libc-shim/src/cuda_trace/w_launch.rs create mode 100644 crates/model-format/src/bulk_read/for_each_chunk.rs create mode 100644 crates/model-format/src/bulk_read/impl_strategy.rs create mode 100644 crates/model-format/src/gguf/impl_cursor.rs create mode 100644 crates/model-format/src/gguf/impl_verifiedgguffile.rs create mode 100644 crates/model-format/src/gguf/parse_artifact_digest.rs create mode 100644 crates/model-format/src/gguf/read_index_file.rs create mode 100644 crates/model-format/src/gguf/read_metadata_snapshot_with_architecture.rs create mode 100644 crates/model-format/src/gguf/stream_buffer_bytes.rs create mode 100644 crates/model-format/src/gguf/value_width.rs create mode 100644 crates/model-format/src/gguf_resident/impl_verifiedgguffile.rs create mode 100644 crates/model-format/src/gguf_resident/impl_verifiedgguffile_2.rs create mode 100644 crates/model-format/src/gguf_resident/next_source_id.rs create mode 100644 crates/model-format/src/kar/decode_record_range.rs create mode 100644 crates/model-format/src/kar/impl_karpleprofile.rs create mode 100644 crates/model-format/src/kar/impl_std_fmt_display.rs create mode 100644 crates/model-format/src/kar/impl_verifiedkarpleartifact.rs create mode 100644 crates/model-format/src/kar/independent_handles.rs create mode 100644 crates/model-format/src/kar/inspect_file.rs create mode 100644 crates/model-format/src/kar/read_region.rs create mode 100644 crates/model-format/src/kar_extents/impl_extent.rs create mode 100644 crates/model-format/src/kar_extents/impl_karinspection.rs create mode 100644 crates/model-format/src/kar_kernel_model/decode_params_valid.rs create mode 100644 crates/model-format/src/kar_kernel_model/impl_fmt_display_for.rs create mode 100644 crates/model-format/src/kar_levels/expert_scratch.rs create mode 100644 crates/model-format/src/kar_levels/impl_fmt_display_for.rs create mode 100644 crates/model-format/src/kar_levels/impl_selection.rs create mode 100644 crates/model-format/src/ple_reader/impl_fmt_debug_for.rs create mode 100644 crates/model-format/src/ple_reader/impl_pagesource_for_file.rs create mode 100644 crates/model-format/src/ple_reader/impl_plereader.rs create mode 100644 crates/model-format/src/ple_reader/impl_state.rs create mode 100644 crates/model-format/src/qwen4exp/expected_inventory.rs create mode 100644 crates/model-format/src/qwen4exp/impl_fmt_display_for.rs create mode 100644 crates/model-format/src/qwen4exp/impl_qwen4expartifact.rs create mode 100644 crates/model-format/src/qwen4exp/impl_qwen4expartifact_2.rs create mode 100644 crates/model-format/src/qwen4exp/plan_stream_rows.rs create mode 100644 crates/model-format/src/qwen4exp/validate_logical_views.rs create mode 100644 crates/model-format/src/qwen4exp/validate_owner_index_split.rs create mode 100644 crates/model-format/src/qwen4exp/validate_role_inventory.rs create mode 100644 crates/model-format/src/qwen4exp_digest_capture/capture_admit.rs create mode 100644 crates/model-format/src/qwen4exp_digest_capture/impl_provisionalexpertsource.rs create mode 100644 crates/model-format/src/qwen4exp_digest_capture/impl_provisionalexpertsource_2.rs create mode 100644 crates/model-format/src/qwen4exp_digest_capture/impl_provisionalexpertsource_3.rs create mode 100644 crates/model-format/src/qwen4exp_digest_capture/impl_qwen4expartifact.rs create mode 100644 crates/model-format/src/qwen4exp_expert_source_bank/impl_qwen4expartifact.rs create mode 100644 crates/model-format/src/qwen4exp_expert_source_bank/impl_qwen4expartifact_2.rs create mode 100644 crates/model-format/src/qwen4exp_expert_source_bank/retention_metadata_bytes.rs create mode 100644 crates/npu-service/src/engine/impl_engine.rs create mode 100644 crates/npu-service/src/engine/impl_weights.rs create mode 100644 crates/runtime-client/src/backend/consumer_gone.rs create mode 100644 crates/runtime-client/src/backend/impl_api_backend_for.rs create mode 100644 crates/runtime-client/src/backend/log_status.rs create mode 100644 crates/serving-policy/src/cvec/build_tables.rs create mode 100644 crates/serving-policy/src/cvec/impl_cursor.rs create mode 100644 crates/serving-policy/src/shared/impl_shareddefaults.rs create mode 100644 crates/serving-policy/src/shared/sampling_defaults_from_config.rs create mode 100644 crates/tokenizer/src/fast/impl_fast.rs create mode 100644 crates/tokenizer/src/fast/unicode_ranges.rs create mode 100644 crates/tokenizer/src/gguf_bpe/impl_fmt_display_for.rs create mode 100644 crates/tokenizer/src/gguf_bpe/impl_ggufbpe.rs create mode 100644 crates/tokenizer/src/gguf_bpe/impl_utf8stream.rs create mode 100644 desktop-core/src/gateway/impl_drop_for_inflight.rs create mode 100644 desktop-core/src/gateway/responses.rs create mode 100644 desktop-core/src/gateway/secret.rs create mode 100644 desktop-core/src/managed_worker/default_capabilities.rs create mode 100644 desktop-core/src/managed_worker/start.rs create mode 100644 desktop-core/src/runtime_gateway/buffered_tool_generation.rs create mode 100644 desktop-core/src/runtime_gateway/credential.rs create mode 100644 desktop-core/src/runtime_gateway/load.rs create mode 100644 desktop-core/src/runtime_gateway/response_value.rs create mode 100644 desktop-core/src/runtime_rpc/clear_active.rs create mode 100644 desktop-core/src/runtime_rpc/event_to_proto.rs create mode 100644 desktop-core/src/runtime_rpc/impl_proto_runtime_server_runtime.rs create mode 100644 desktop-core/src/runtime_rpc/impl_runtimeserver.rs create mode 100644 desktop-core/src/runtime_rpc/lock.rs create mode 100644 desktop-core/src/runtime_tools/fields.rs create mode 100644 desktop-core/src/runtime_tools/history.rs create mode 100644 desktop-core/src/runtime_tools/impl_toolpolicy.rs create mode 100644 desktop-core/src/runtime_tools/impl_write_for_count.rs create mode 100644 scripts/dev/rustsplit/__init__.py create mode 100644 scripts/dev/rustsplit/items.py create mode 100644 scripts/dev/rustsplit/lexer.py create mode 100644 scripts/dev/rustsplit/retarget.py create mode 100644 scripts/dev/rustsplit/split.py create mode 100644 scripts/dev/rustsplit_test.py create mode 100644 scripts/dev/split_module.py diff --git a/architecture-baseline.json b/architecture-baseline.json index a3f9fb42..3a2b9207 100644 --- a/architecture-baseline.json +++ b/architecture-baseline.json @@ -6,44 +6,23 @@ ], "oversize": { "control-plane/examples/cp_replay.rs": 946, - "control-plane/src/app.rs": 474, - "control-plane/src/backend_worker.rs": 841, - "control-plane/src/chat.rs": 664, - "control-plane/src/config.rs": 788, + "control-plane/src/config/impl_config.rs": 520, "control-plane/src/ggml_bridge/tests.rs": 1286, "control-plane/src/gguf_f32_stream/tests.rs": 909, - "control-plane/src/kar_overlay.rs": 1048, - "control-plane/src/kar_quality.rs": 502, - "control-plane/src/kar_writer.rs": 952, "control-plane/src/main.rs": 1156, - "control-plane/src/mcp.rs": 1423, - "control-plane/src/messages.rs": 602, - "control-plane/src/model.rs": 455, - "control-plane/src/mtp_fetch.rs": 695, - "control-plane/src/native_pack.rs": 1144, - "control-plane/src/prepare_preview.rs": 1393, "control-plane/src/prepare_preview/tests.rs": 808, - "control-plane/src/prometheus.rs": 604, - "control-plane/src/reasoning_budget.rs": 402, - "control-plane/src/request_log.rs": 732, - "control-plane/src/request_monitor.rs": 574, + "control-plane/src/prometheus.rs": 441, "control-plane/src/responses.rs": 2780, - "control-plane/src/responses/harmony_prompt.rs": 621, "control-plane/src/responses/tests.rs": 2961, - "control-plane/src/server_api.rs": 692, - "control-plane/src/service_install.rs": 793, - "control-plane/src/service_switch.rs": 677, - "control-plane/src/vision.rs": 779, - "control-plane/src/worker.rs": 2170, + "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/backend-api/src/scripted.rs": 553, - "crates/context/src/memory_plan.rs": 467, - "crates/context/src/rope_scaling.rs": 674, "crates/context/tests/rope_plan_golden.rs": 412, "crates/cpu-kernels/src/lib.rs": 464, "crates/cpu-sys/src/c_reference.rs": 486, @@ -167,12 +146,8 @@ "crates/deploy/src/winfront.rs": 886, "crates/deploy/src/wsl.rs": 496, "crates/deploy/tests/e2e.rs": 2118, - "crates/experimental-ref/src/cvec.rs": 476, - "crates/experimental-ref/src/kv_stream.rs": 437, "crates/experimental-ref/tests/emulated_kernels.rs": 467, - "crates/gateway-text/src/prompt.rs": 882, "crates/gateway-text/src/prompt/tests.rs": 492, - "crates/gateway-text/src/tool_output.rs": 1184, "crates/gateway-text/src/tool_output/tests.rs": 654, "crates/gguf/src/lib.rs": 560, "crates/gguf/tests/synthetic.rs": 460, @@ -180,13 +155,10 @@ "crates/gptoss-npu/src/lib.rs": 809, "crates/gptoss/src/lib.rs": 1788, "crates/gptoss/tests/synthetic_model.rs": 922, - "crates/harmony/src/render.rs": 511, "crates/igpu/src/lib.rs": 1386, - "crates/igpu/src/shaders.rs": 624, - "crates/leleka-memory/src/governor.rs": 1004, - "crates/leleka-memory/src/lock.rs": 518, - "crates/leleka-memory/src/plan.rs": 408, - "crates/leleka-memory/src/telemetry.rs": 630, + "crates/igpu/src/shaders.rs": 440, + "crates/leleka-memory/src/governor/impl_governor.rs": 739, + "crates/leleka-memory/src/lock.rs": 432, "crates/leleka-runtime/src/backend.rs": 3770, "crates/leleka-runtime/src/backend_original_prompt.rs": 529, "crates/leleka-runtime/src/backend_original_serve.rs": 1115, @@ -270,19 +242,9 @@ "crates/leleka-runtime/src/qwen_forward/session_chunk.rs": 2642, "crates/leleka-runtime/src/qwen_forward/session_chunk_verify.rs": 665, "crates/leleka-runtime/src/qwen_forward/session_original_prompt.rs": 610, - "crates/libc-shim/src/cuda_trace.rs": 449, - "crates/model-format/src/bulk_read.rs": 417, - "crates/model-format/src/gguf.rs": 2285, - "crates/model-format/src/gguf_resident.rs": 613, - "crates/model-format/src/kar.rs": 1751, - "crates/model-format/src/kar_extents.rs": 530, - "crates/model-format/src/kar_kernel_model.rs": 520, - "crates/model-format/src/kar_levels.rs": 666, - "crates/model-format/src/ple_reader.rs": 890, + "crates/model-format/src/gguf.rs": 1099, "crates/model-format/src/ple_reader/tests.rs": 750, - "crates/model-format/src/qwen4exp.rs": 2024, - "crates/model-format/src/qwen4exp_digest_capture.rs": 819, - "crates/model-format/src/qwen4exp_expert_source_bank.rs": 643, + "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, @@ -291,25 +253,15 @@ "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/npu-service/src/engine.rs": 470, "crates/obs/src/lib.rs": 603, "crates/openvino/src/lib.rs": 676, "crates/quant-core/src/iq2s_grid.rs": 1032, - "crates/runtime-client/src/backend.rs": 469, "crates/runtime-client/tests/grpc_backend.rs": 689, - "crates/serving-policy/src/cvec.rs": 421, - "crates/serving-policy/src/shared.rs": 409, "crates/shm/src/lib.rs": 432, - "crates/tokenizer/src/fast.rs": 435, - "crates/tokenizer/src/gguf_bpe.rs": 438, "crates/tokenizer/src/lib.rs": 840, "desktop-core/src/bin/leleka-inference.rs": 1487, - "desktop-core/src/gateway.rs": 596, - "desktop-core/src/managed_worker.rs": 476, - "desktop-core/src/runtime_gateway.rs": 945, - "desktop-core/src/runtime_rpc.rs": 1077, + "desktop-core/src/runtime_rpc/impl_proto_runtime_server_runtime.rs": 463, "desktop-core/src/runtime_rpc/tests.rs": 628, - "desktop-core/src/runtime_tools.rs": 724, "desktop-core/tests/api_over_runtime.rs": 638, "desktop-core/tests/gateway.rs": 403, "desktop-core/tests/managed_worker.rs": 500, @@ -373,7 +325,7 @@ "path-include:leleka-cuda-driver": 115, "path-include:leleka-model-format": 12, "path-include:leleka-native-cpu-expert": 2, - "path-include:leleka-runtime": 108, + "path-include:leleka-runtime": 107, "path-include:strata-desktop-core": 2, "process-global:leleka-cuda-driver": 110, "process-global:leleka-gateway-text": 5, diff --git a/architecture.json b/architecture.json index cd622785..26d1e873 100644 --- a/architecture.json +++ b/architecture.json @@ -41,7 +41,7 @@ "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\")", "why": "a file compiled into two crates must be one crate (S8); a tests.rs beside its module is not an include"}, + {"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"} ] diff --git a/control-plane/src/app.rs b/control-plane/src/app.rs index 09b6765b..a3613c96 100644 --- a/control-plane/src/app.rs +++ b/control-plane/src/app.rs @@ -53,34 +53,6 @@ pub struct AppState { pub monitor: Arc, } -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,378 +69,15 @@ struct StatusResponse { max_context: Option, } -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 { - Json(HealthResponse { status: "ok" }) -} - -async fn lifecycle_status(State(state): State) -> Json { - 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 { - 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::().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, 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, 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, - 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::(&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) -> (StatusCode, Json) { - 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) -> Json { - 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, -) -> 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; + +mod impl_default_for_appstate; +#[allow(unused_imports)] +pub use impl_default_for_appstate::*; +mod metrics_document; +#[allow(unused_imports)] +pub use metrics_document::*; diff --git a/control-plane/src/app/impl_default_for_appstate.rs b/control-plane/src/app/impl_default_for_appstate.rs new file mode 100644 index 00000000..407c8e3c --- /dev/null +++ b/control-plane/src/app/impl_default_for_appstate.rs @@ -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 { + Json(HealthResponse { status: "ok" }) +} + +pub(super) async fn lifecycle_status(State(state): State) -> Json { + 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 { + 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::().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, 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, 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, + 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() +} diff --git a/control-plane/src/app/metrics_document.rs b/control-plane/src/app/metrics_document.rs new file mode 100644 index 00000000..4a0c4861 --- /dev/null +++ b/control-plane/src/app/metrics_document.rs @@ -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::(&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) -> (StatusCode, Json) { + 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) -> Json { + 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, +) -> 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, + } +} diff --git a/control-plane/src/backend_worker.rs b/control-plane/src/backend_worker.rs index 122c75f2..4756ea11 100644 --- a/control-plane/src/backend_worker.rs +++ b/control-plane/src/backend_worker.rs @@ -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( - engine: &Engine, - call: impl FnOnce(&mut dyn api::Backend) -> T + Send + 'static, -) -> Result { - 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 { - 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, 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 { - 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, - config: BackendWorkerConfig, - status: Arc>, - mut shutdown: watch::Receiver, - mut requests: mpsc::Receiver, - mut control: mpsc::Receiver, -) { - let engine: Engine = Arc::new(Mutex::new(backend)); - let mut waiting: Vec = 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, - shutdown: &mut watch::Receiver, - 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, - shutdown: &mut watch::Receiver, - 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::>(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 = Vec::new(); - let mut usage: Option = None; - let mut cancel: Option = None; - let mut first_delta: Option = 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 = 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, 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, - mut buffered: Vec, - 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::*; diff --git a/control-plane/src/backend_worker/conclude.rs b/control-plane/src/backend_worker/conclude.rs new file mode 100644 index 00000000..f8f90c68 --- /dev/null +++ b/control-plane/src/backend_worker/conclude.rs @@ -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, + mut buffered: Vec, + 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 + } + } +} diff --git a/control-plane/src/backend_worker/request_id.rs b/control-plane/src/backend_worker/request_id.rs new file mode 100644 index 00000000..fe9aff10 --- /dev/null +++ b/control-plane/src/backend_worker/request_id.rs @@ -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( + engine: &Engine, + call: impl FnOnce(&mut dyn api::Backend) -> T + Send + 'static, +) -> Result { + 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 { + 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, 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 { + 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, + }, + }) +} diff --git a/control-plane/src/backend_worker/run_backend_worker.rs b/control-plane/src/backend_worker/run_backend_worker.rs new file mode 100644 index 00000000..dfb0b788 --- /dev/null +++ b/control-plane/src/backend_worker/run_backend_worker.rs @@ -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, + config: BackendWorkerConfig, + status: Arc>, + mut shutdown: watch::Receiver, + mut requests: mpsc::Receiver, + mut control: mpsc::Receiver, +) { + let engine: Engine = Arc::new(Mutex::new(backend)); + let mut waiting: Vec = 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; +} diff --git a/control-plane/src/backend_worker/serve_one.rs b/control-plane/src/backend_worker/serve_one.rs new file mode 100644 index 00000000..9acae8e5 --- /dev/null +++ b/control-plane/src/backend_worker/serve_one.rs @@ -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, + shutdown: &mut watch::Receiver, + 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, + shutdown: &mut watch::Receiver, + 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::>(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 = Vec::new(); + let mut usage: Option = None; + let mut cancel: Option = None; + let mut first_delta: Option = 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 = 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; + } + } + } +} diff --git a/control-plane/src/chat.rs b/control-plane/src/chat.rs index c38683b7..4f49ca08 100644 --- a/control-plane/src/chat.rs +++ b/control-plane/src/chat.rs @@ -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), } -impl Content { - fn text(self) -> Option { - 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) -> Result { - 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, role: &str) -> Result, 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, - body: Result, 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); -impl Stream for Events { - type Item = Result; - fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { - self.0.poll_recv(cx).map(|v| v.map(Ok)) - } -} -async fn send(sender: &mpsc::Sender, 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, - 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::*; diff --git a/control-plane/src/chat/completion.rs b/control-plane/src/chat/completion.rs new file mode 100644 index 00000000..693da0e8 --- /dev/null +++ b/control-plane/src/chat/completion.rs @@ -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, + body: Result, 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; + fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { + self.0.poll_recv(cx).map(|v| v.map(Ok)) + } +} +pub(super) async fn send(sender: &mpsc::Sender, 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, + 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(()); + } + _ => {} + } + } +} diff --git a/control-plane/src/chat/impl_request.rs b/control-plane/src/chat/impl_request.rs new file mode 100644 index 00000000..1b3c2a29 --- /dev/null +++ b/control-plane/src/chat/impl_request.rs @@ -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"]}) +} diff --git a/control-plane/src/chat/invalid.rs b/control-plane/src/chat/invalid.rs new file mode 100644 index 00000000..d9e33227 --- /dev/null +++ b/control-plane/src/chat/invalid.rs @@ -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 { + 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) -> Result { + 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, role: &str) -> Result, 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")), + } +} diff --git a/control-plane/src/chat/stream_response.rs b/control-plane/src/chat/stream_response.rs new file mode 100644 index 00000000..87fe4337 --- /dev/null +++ b/control-plane/src/chat/stream_response.rs @@ -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() +} diff --git a/control-plane/src/config.rs b/control-plane/src/config.rs index f4676995..0022b85f 100644 --- a/control-plane/src/config.rs +++ b/control-plane/src/config.rs @@ -159,630 +159,15 @@ struct ControlVectorFile { scale: f32, } -impl ControlVector { - /// The engine arguments for this vector after checking the files (GGUF control vectors with - /// F32 `direction.` tensors of one width), so a typo stops the start, not the load. - fn engine_args(&self) -> Result, 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 = 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. 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::load_with_path(None) - } - - /// An explicit CLI config path takes precedence over STRATA_CONFIG. - pub fn load_with_path(path: Option<&Path>) -> Result> { - 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::(&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::()) - .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::()) - .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::()) - .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::>(&value)) - .transpose()?; - let timeout_override = optional_env("STRATA_STARTUP_TIMEOUT_S")? - .map(|value| value.parse::()) - .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::()) - .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::()) - .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> { - 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> { - if let Some(requirement) = self.gpu_requirement { - crate::doctor::check(requirement).await?; - } - self.prepare_assets().await - } - - async fn prepare_assets(&mut self) -> Result<(), Box> { - 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> { - 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, 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; + +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::*; diff --git a/control-plane/src/config/impl_config.rs b/control-plane/src/config/impl_config.rs new file mode 100644 index 00000000..7c14a269 --- /dev/null +++ b/control-plane/src/config/impl_config.rs @@ -0,0 +1,520 @@ +//! Moved out of the parent module by STRA-338: impl Config. + +#[allow(unused_imports)] +use super::*; + +impl Config { + pub fn load() -> Result> { + Self::load_with_path(None) + } + + /// An explicit CLI config path takes precedence over STRATA_CONFIG. + pub fn load_with_path(path: Option<&Path>) -> Result> { + 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::(&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::()) + .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::()) + .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::()) + .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::>(&value)) + .transpose()?; + let timeout_override = optional_env("STRATA_STARTUP_TIMEOUT_S")? + .map(|value| value.parse::()) + .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::()) + .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::()) + .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> { + 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> { + if let Some(requirement) = self.gpu_requirement { + crate::doctor::check(requirement).await?; + } + self.prepare_assets().await + } + + pub(super) async fn prepare_assets(&mut self) -> Result<(), Box> { + 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> { + 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(()) + } +} diff --git a/control-plane/src/config/impl_controlvector.rs b/control-plane/src/config/impl_controlvector.rs new file mode 100644 index 00000000..ddb40361 --- /dev/null +++ b/control-plane/src/config/impl_controlvector.rs @@ -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.` tensors of one width), so a typo stops the start, not the load. + pub(super) fn engine_args(&self) -> Result, 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 = 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. 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) + } +} diff --git a/control-plane/src/config/optional_env.rs b/control-plane/src/config/optional_env.rs new file mode 100644 index 00000000..10b8e851 --- /dev/null +++ b/control-plane/src/config/optional_env.rs @@ -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, env::VarError> { + match env::var(name) { + Ok(value) => Ok(Some(value)), + Err(env::VarError::NotPresent) => Ok(None), + Err(error) => Err(error), + } +} diff --git a/control-plane/src/kar_overlay.rs b/control-plane/src/kar_overlay.rs index ffa8396d..68e4e75d 100644 --- a/control-plane/src/kar_overlay.rs +++ b/control-plane/src/kar_overlay.rs @@ -41,22 +41,6 @@ struct BaseProvenance { partitioned_tensors: Vec, } -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, - name: &str, -) -> Result, 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, @@ -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 { - let sidecar = |path: &Path| -> Result { - 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 { - 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::>(); - 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::; - 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::>(); - 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::>(); - 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, - §ion_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::>(); - 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::>(), - "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 { - 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::>(); - if overlay - .records - .iter() - .map(|record| record.name.as_str()) - .collect::>() - .len() - != overlay.records.len() - { - return Err("duplicate overlay tensor name".into()); - } - let mut manifest_files = manifest.files.iter().collect::>(); - 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::*; diff --git a/control-plane/src/kar_overlay/compare.rs b/control-plane/src/kar_overlay/compare.rs new file mode 100644 index 00000000..1194c7c7 --- /dev/null +++ b/control-plane/src/kar_overlay/compare.rs @@ -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 { + 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::>(); + if overlay + .records + .iter() + .map(|record| record.name.as_str()) + .collect::>() + .len() + != overlay.records.len() + { + return Err("duplicate overlay tensor name".into()); + } + let mut manifest_files = manifest.files.iter().collect::>(); + 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()) +} diff --git a/control-plane/src/kar_overlay/impl_baseprovenance.rs b/control-plane/src/kar_overlay/impl_baseprovenance.rs new file mode 100644 index 00000000..7a7e13d5 --- /dev/null +++ b/control-plane/src/kar_overlay/impl_baseprovenance.rs @@ -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, + name: &str, +) -> Result, 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); + } + } +} diff --git a/control-plane/src/kar_overlay/prepare.rs b/control-plane/src/kar_overlay/prepare.rs new file mode 100644 index 00000000..393b19de --- /dev/null +++ b/control-plane/src/kar_overlay/prepare.rs @@ -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 { + 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::>(); + 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::; + 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::>(); + 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::>(); + 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, + §ion_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::>(); + 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::>(), + "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, + }) +} diff --git a/control-plane/src/kar_overlay/resolve_verified.rs b/control-plane/src/kar_overlay/resolve_verified.rs new file mode 100644 index 00000000..f486f374 --- /dev/null +++ b/control-plane/src/kar_overlay/resolve_verified.rs @@ -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 { + let sidecar = |path: &Path| -> Result { + 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, + }) +} diff --git a/control-plane/src/kar_overlay/write_provenance.rs b/control-plane/src/kar_overlay/write_provenance.rs new file mode 100644 index 00000000..fedf24e1 --- /dev/null +++ b/control-plane/src/kar_overlay/write_provenance.rs @@ -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 +} diff --git a/control-plane/src/kar_quality.rs b/control-plane/src/kar_quality.rs index b6870c9b..88ca3249 100644 --- a/control-plane/src/kar_quality.rs +++ b/control-plane/src/kar_quality.rs @@ -91,412 +91,12 @@ pub struct SampleWindow { pub elements: u64, } -pub fn analyze( - manifest: &Manifest, - source_dir: &Path, - archive_path: &Path, - levels: u8, -) -> Result { - 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 { - 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::>(); - 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::>(); - 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::, 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::() - { - 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], - mut decoder: VerifiedRangeDecoder, - levels: u8, - archive_sha256: String, - verification: &'static str, -) -> Result { - 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::() { - 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, 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; + +mod analyze; +#[allow(unused_imports)] +pub use analyze::*; +mod parse_digest; +#[allow(unused_imports)] +pub use parse_digest::*; diff --git a/control-plane/src/kar_quality/analyze.rs b/control-plane/src/kar_quality/analyze.rs new file mode 100644 index 00000000..fa64fb87 --- /dev/null +++ b/control-plane/src/kar_quality/analyze.rs @@ -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 { + 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 { + 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::>(); + 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::>(); + 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::, 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::() + { + 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", + ) +} diff --git a/control-plane/src/kar_quality/parse_digest.rs b/control-plane/src/kar_quality/parse_digest.rs new file mode 100644 index 00000000..89153d28 --- /dev/null +++ b/control-plane/src/kar_quality/parse_digest.rs @@ -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], + mut decoder: VerifiedRangeDecoder, + levels: u8, + archive_sha256: String, + verification: &'static str, +) -> Result { + 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::() { + 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, 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 +} diff --git a/control-plane/src/kar_writer.rs b/control-plane/src/kar_writer.rs index 3ba3f39e..842ab6ee 100644 --- a/control-plane/src/kar_writer.rs +++ b/control-plane/src/kar_writer.rs @@ -85,658 +85,11 @@ struct Placed<'a> { payload_crc32: u32, } -pub fn write_archive( - destination: &Path, - source: &SourceIdentity<'_>, - tensors: &[Tensor<'_>], -) -> Result { - 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 { - 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) -} - -fn write_archive_inner( - destination: &Path, - source: &SourceIdentity<'_>, - tensors: &[Tensor<'_>], - consume_files: bool, -) -> Result { - 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) -} - pub struct SectionSummary { pub bytes: u64, pub digest: [u8; 32], } -/// 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 { - 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 { - 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 -} - -fn validate_shape(tensor: &Tensor<'_>) -> Result { - 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) -} - -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(()) -} - -fn push_cstr(destination: &mut Vec, 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(()) -} - -fn round_up(value: u64, alignment: u64) -> Result { - value - .div_ceil(alignment) - .checked_mul(alignment) - .ok_or("KAR aligned offset overflow".into()) -} - -fn nested_layout( - cursor: u64, - n_elements: u64, - group: u16, - nesting: u8, - planes_min: u8, - planes_max: u8, - levels: u8, -) -> Result { - 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, - }) -} - -fn write_section(file: &mut File, entry: &Placed<'_>) -> Result { - 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) -} - #[derive(Clone, Copy)] enum RegionRule { FiniteScale, @@ -744,209 +97,21 @@ enum RegionRule { ZeroPadding, } -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(()) -} - -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(()) -} - -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(()) -} - -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(()) -} - -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(()) -} - -fn put_u16(bytes: &mut [u8], offset: usize, value: u16) { - bytes[offset..offset + 2].copy_from_slice(&value.to_le_bytes()); -} -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()); -} - #[cfg(test)] mod tests; + +mod write_archive; +#[allow(unused_imports)] +pub use write_archive::*; +mod write_archive_inner; +#[allow(unused_imports)] +pub use write_archive_inner::*; +mod write_nested_section; +#[allow(unused_imports)] +pub use write_nested_section::*; +mod write_section; +#[allow(unused_imports)] +pub use write_section::*; +mod write_record; +#[allow(unused_imports)] +pub use write_record::*; diff --git a/control-plane/src/kar_writer/write_archive.rs b/control-plane/src/kar_writer/write_archive.rs new file mode 100644 index 00000000..8de12b10 --- /dev/null +++ b/control-plane/src/kar_writer/write_archive.rs @@ -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 { + 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 { + 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) +} diff --git a/control-plane/src/kar_writer/write_archive_inner.rs b/control-plane/src/kar_writer/write_archive_inner.rs new file mode 100644 index 00000000..9af56692 --- /dev/null +++ b/control-plane/src/kar_writer/write_archive_inner.rs @@ -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 { + 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) +} diff --git a/control-plane/src/kar_writer/write_nested_section.rs b/control-plane/src/kar_writer/write_nested_section.rs new file mode 100644 index 00000000..288b0f59 --- /dev/null +++ b/control-plane/src/kar_writer/write_nested_section.rs @@ -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 { + 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 { + 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 { + 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, 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 { + 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 { + 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, + }) +} diff --git a/control-plane/src/kar_writer/write_record.rs b/control-plane/src/kar_writer/write_record.rs new file mode 100644 index 00000000..e4b9dec3 --- /dev/null +++ b/control-plane/src/kar_writer/write_record.rs @@ -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()); +} diff --git a/control-plane/src/kar_writer/write_section.rs b/control-plane/src/kar_writer/write_section.rs new file mode 100644 index 00000000..63f482a8 --- /dev/null +++ b/control-plane/src/kar_writer/write_section.rs @@ -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 { + 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(()) +} diff --git a/control-plane/src/mcp.rs b/control-plane/src/mcp.rs index c6c64f09..d14f1739 100644 --- a/control-plane/src/mcp.rs +++ b/control-plane/src/mcp.rs @@ -46,17 +46,6 @@ pub struct Settings { pub start_timeout_s: f64, } -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, - } - } -} - #[derive(Clone, Debug, PartialEq)] pub enum McpError { /// A server answered with an error, stopped, or could not be reached. @@ -66,50 +55,8 @@ pub enum McpError { Cancelled, } -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"), - } - } -} - -fn failed(message: impl Into) -> McpError { - McpError::Failed(message.into()) -} - pub type Cancel = watch::Receiver; -/// A response `result`, or the error a JSON-RPC response carried (`_wait` of the Original). -fn response_result(message: &Value) -> Result { - 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!({}))) -} - type Slot = oneshot::Sender>; // ------------------------------------------------------------------------------------------------ stdio @@ -125,312 +72,6 @@ struct StdioTransport { ended: Arc, } -impl StdioTransport { - async fn spawn(name: &str, config: &Map) -> Result { - 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>> = Arc::default(); - let log: Arc>> = 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::(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::())) - .unwrap_or_default(); - let error = failed(format!("the server stopped{tail}")); - let slots: Vec = pending - .lock() - .expect("mcp pending") - .drain() - .map(|(_, s)| s) - .collect(); - for slot in slots { - let _ = slot.send(Err(error.clone())); - } - }); - Ok(transport) - } - - fn tail(&self) -> String { - self.stderr - .lock() - .expect("mcp log") - .back() - .map(|l| format!(": {}", l.chars().take(300).collect::())) - .unwrap_or_default() - } - - fn alive(&self) -> bool { - !self.ended.load(Ordering::SeqCst) - } - - 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(()) - } - - async fn request( - &self, - method: &str, - params: Value, - timeout: Duration, - mut cancel: Option, - ) -> Result { - 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) - } - - async fn notify(&self, method: &str, params: Option) -> 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. - 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; - } -} - -/// 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. -async fn dispatch( - message: &Value, - pending: &Arc>>, - writer: &Arc>>, -) { - 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 -} - -async fn cancelled(cancel: &mut Option) { - 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. -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() - } -} - // ------------------------------------------------------------------------------------------------ http struct Http { @@ -443,231 +84,6 @@ struct Http { broken: Mutex>, } -impl Http { - fn new(config: &Map) -> 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), - } - } - - fn alive(&self) -> bool { - self.broken.lock().expect("mcp http").is_none() - } - - 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. - async fn post( - &self, - message: &Value, - id: Option, - timeout: Duration, - ) -> Result, 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")) - } - - async fn request( - &self, - method: &str, - params: Value, - timeout: Duration, - mut cancel: Option, - ) -> Result { - 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) - } - - async fn notify(&self, method: &str, params: Option) -> 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(|_| ()) - } - - 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). -async fn read_events(mut response: reqwest::Response, id: u64) -> Option { - let mut buffer = Vec::::new(); - let mut data: Vec = 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 = 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::(&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; - } - } -} - // ------------------------------------------------------------------------------------------------ one server type StartResult = @@ -678,42 +94,6 @@ enum Transport { Http(Http), } -impl Transport { - fn alive(&self) -> bool { - match self { - Self::Stdio(t) => t.alive(), - Self::Http(t) => t.alive(), - } - } - - async fn request( - &self, - method: &str, - params: Value, - timeout: Duration, - cancel: Option, - ) -> Result { - match self { - Self::Stdio(t) => t.request(method, params, timeout, cancel).await, - Self::Http(t) => t.request(method, params, timeout, cancel).await, - } - } - - 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, - } - } - - async fn close(&self) { - match self { - Self::Stdio(t) => t.close().await, - Self::Http(t) => t.close().await, - } - } -} - #[derive(Clone, Debug, PartialEq, Eq)] pub enum Status { Idle, @@ -723,18 +103,6 @@ pub enum Status { Stopped, } -impl Status { - fn as_str(&self) -> &'static str { - match self { - Self::Idle => "idle", - Self::Starting => "starting", - Self::Ready => "ready", - Self::Failed => "failed", - Self::Stopped => "stopped", - } - } -} - struct State { status: Status, error: Option, @@ -752,319 +120,6 @@ pub struct Server { state: AsyncMutex, } -impl Server { - fn new(name: String, config: Map, 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 - } - - 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 = 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 = Vec::new(); - let mut cursor: Option = 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::>() - .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, - ) -> Result { - 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; - } - } -} - -// ------------------------------------------------------------------------------------------------ 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 = 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:,}"`. -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 -} - -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 - } -} - /// One tool call's outcome (`McpHub.call`). #[derive(Clone, Debug, PartialEq)] pub struct CallOutput { @@ -1084,340 +139,33 @@ pub struct Hub { settings: Settings, } -impl Hub { - pub fn new(servers: BTreeMap>, 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, String)> { - let mut out: Vec<(String, Arc, 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::()); - 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 { - 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, - ) -> Result { - 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::() - + &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 = 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::()}) - }) - .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`, `[]`, `{}`). -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(), - } -} - -fn check_server(name: &str, config: &Value, location: &str) -> Result, 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>, 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 { - 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) -} - #[cfg(test)] mod tests; + +mod impl_default_for_settings; +#[allow(unused_imports)] +pub use impl_default_for_settings::*; +mod impl_stdiotransport; +#[allow(unused_imports)] +pub use impl_stdiotransport::*; +mod dispatch; +#[allow(unused_imports)] +pub use dispatch::*; +mod impl_http; +#[allow(unused_imports)] +pub use impl_http::*; +mod impl_transport; +#[allow(unused_imports)] +pub use impl_transport::*; +mod impl_server; +#[allow(unused_imports)] +pub use impl_server::*; +mod result_text; +#[allow(unused_imports)] +pub use result_text::*; +mod impl_hub; +#[allow(unused_imports)] +pub use impl_hub::*; +mod check_server; +#[allow(unused_imports)] +pub use check_server::*; diff --git a/control-plane/src/mcp/check_server.rs b/control-plane/src/mcp/check_server.rs new file mode 100644 index 00000000..312aaeea --- /dev/null +++ b/control-plane/src/mcp/check_server.rs @@ -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, 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>, 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 { + 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) +} diff --git a/control-plane/src/mcp/dispatch.rs b/control-plane/src/mcp/dispatch.rs new file mode 100644 index 00000000..a1d7e398 --- /dev/null +++ b/control-plane/src/mcp/dispatch.rs @@ -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>>, + writer: &Arc>>, +) { + 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) { + 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() + } +} diff --git a/control-plane/src/mcp/impl_default_for_settings.rs b/control-plane/src/mcp/impl_default_for_settings.rs new file mode 100644 index 00000000..653fe35d --- /dev/null +++ b/control-plane/src/mcp/impl_default_for_settings.rs @@ -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) -> 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 { + 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!({}))) +} diff --git a/control-plane/src/mcp/impl_http.rs b/control-plane/src/mcp/impl_http.rs new file mode 100644 index 00000000..ff4c7304 --- /dev/null +++ b/control-plane/src/mcp/impl_http.rs @@ -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) -> 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, + timeout: Duration, + ) -> Result, 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, + ) -> Result { + 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) -> 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 { + let mut buffer = Vec::::new(); + let mut data: Vec = 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 = 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::(&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; + } + } +} diff --git a/control-plane/src/mcp/impl_hub.rs b/control-plane/src/mcp/impl_hub.rs new file mode 100644 index 00000000..168d5ae5 --- /dev/null +++ b/control-plane/src/mcp/impl_hub.rs @@ -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>, 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, String)> { + let mut out: Vec<(String, Arc, 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::()); + 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 { + 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, + ) -> Result { + 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::() + + &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 = 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::()}) + }) + .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(), + } +} diff --git a/control-plane/src/mcp/impl_server.rs b/control-plane/src/mcp/impl_server.rs new file mode 100644 index 00000000..38744a80 --- /dev/null +++ b/control-plane/src/mcp/impl_server.rs @@ -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, 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 = 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 = Vec::new(); + let mut cursor: Option = 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::>() + .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, + ) -> Result { + 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; + } + } +} diff --git a/control-plane/src/mcp/impl_stdiotransport.rs b/control-plane/src/mcp/impl_stdiotransport.rs new file mode 100644 index 00000000..8e81ee6e --- /dev/null +++ b/control-plane/src/mcp/impl_stdiotransport.rs @@ -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) -> Result { + 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>> = Arc::default(); + let log: Arc>> = 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::(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::())) + .unwrap_or_default(); + let error = failed(format!("the server stopped{tail}")); + let slots: Vec = 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::())) + .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, + ) -> Result { + 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) -> 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; + } +} diff --git a/control-plane/src/mcp/impl_transport.rs b/control-plane/src/mcp/impl_transport.rs new file mode 100644 index 00000000..929f36e8 --- /dev/null +++ b/control-plane/src/mcp/impl_transport.rs @@ -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, + ) -> Result { + 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", + } + } +} diff --git a/control-plane/src/mcp/result_text.rs b/control-plane/src/mcp/result_text.rs new file mode 100644 index 00000000..a032b428 --- /dev/null +++ b/control-plane/src/mcp/result_text.rs @@ -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 = 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 + } +} diff --git a/control-plane/src/messages.rs b/control-plane/src/messages.rs index 5320191d..8bad90b1 100644 --- a/control-plane/src/messages.rs +++ b/control-plane/src/messages.rs @@ -50,57 +50,6 @@ struct CountRequest { tool_choice: Option, thinking: Option, } -impl CountRequest { - fn into_responses(self) -> Result { - // 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, - body: Result, 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::(&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,454 +98,17 @@ enum Piece { Text(String), Image(String), } -fn empty_tool_result() -> Value { - Value::String(String::new()) -} -fn blocks(value: Value) -> Result, 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 { - 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)> = 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 = Vec::new(); - let flush = |run: &mut Vec, input: &mut Vec| { - 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 = 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 = 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 { - 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 { - 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, - body: Result, 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); -impl Stream for Events { - type Item = Result; - fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { - self.0.poll_recv(cx).map(|v| v.map(Ok)) - } -} -async fn send(sender: &mpsc::Sender, 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, - 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) -> 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; + +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::*; diff --git a/control-plane/src/messages/adapt.rs b/control-plane/src/messages/adapt.rs new file mode 100644 index 00000000..78619de8 --- /dev/null +++ b/control-plane/src/messages/adapt.rs @@ -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, +) -> 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() +} diff --git a/control-plane/src/messages/error_type.rs b/control-plane/src/messages/error_type.rs new file mode 100644 index 00000000..38a044d4 --- /dev/null +++ b/control-plane/src/messages/error_type.rs @@ -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 { + 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 { + 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, + body: Result, 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; + fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { + self.0.poll_recv(cx).map(|v| v.map(Ok)) + } +} +pub(super) async fn send(sender: &mpsc::Sender, 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, + 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(()) +} diff --git a/control-plane/src/messages/impl_countrequest.rs b/control-plane/src/messages/impl_countrequest.rs new file mode 100644 index 00000000..996abc50 --- /dev/null +++ b/control-plane/src/messages/impl_countrequest.rs @@ -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 { + // 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, + body: Result, 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::(&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, 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 { + 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)> = 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 = Vec::new(); + let flush = |run: &mut Vec, input: &mut Vec| { + 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 = 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 = 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)) + } +} diff --git a/control-plane/src/model.rs b/control-plane/src/model.rs index 21332082..91268f8d 100644 --- a/control-plane/src/model.rs +++ b/control-plane/src/model.rs @@ -40,416 +40,12 @@ pub struct ModelFile { pub sha256: String, } -impl Manifest { - pub async fn load(path: &Path) -> Result { - Self::parse(&fs::read(path).await?) - } - - pub async fn from_spec(spec: &str) -> Result { - 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 { - 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 { - // 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::, _>>()?; - 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::() { - 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::() - .is_some_and(|local| local.kind() == io::ErrorKind::UnexpectedEof) -} - -fn model_request( - client: &Client, - file: &ModelFile, - offset: u64, - hub_token: Option<&str>, -) -> Result { - 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 { - 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::::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 { - 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; + +mod impl_manifest; +#[allow(unused_imports)] +pub use impl_manifest::*; +mod fetch_one; +#[allow(unused_imports)] +pub use fetch_one::*; diff --git a/control-plane/src/model/fetch_one.rs b/control-plane/src/model/fetch_one.rs new file mode 100644 index 00000000..c36dbabb --- /dev/null +++ b/control-plane/src/model/fetch_one.rs @@ -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 { + 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::::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 { + 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() + )) +} diff --git a/control-plane/src/model/impl_manifest.rs b/control-plane/src/model/impl_manifest.rs new file mode 100644 index 00000000..e8e63bb7 --- /dev/null +++ b/control-plane/src/model/impl_manifest.rs @@ -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::parse(&fs::read(path).await?) + } + + pub async fn from_spec(spec: &str) -> Result { + 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 { + 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 { + // 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::, _>>()?; + 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::() { + 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::() + .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 { + 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") +} diff --git a/control-plane/src/mtp_fetch.rs b/control-plane/src/mtp_fetch.rs index f1f76aef..40622a61 100644 --- a/control-plane/src/mtp_fetch.rs +++ b/control-plane/src/mtp_fetch.rs @@ -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(value: &T) -> Result> { - 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 { - 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 { - 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 { - 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) -> 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> { - 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> { - 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)> { - 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> { - let index: Value = serde_json::from_slice( - &self - .get(&format!("{}model.safetensors.index.json", self.repo), None) - .await?, - )?; - let mtp: BTreeMap = 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::>()?; - let mut rows = Vec::new(); - let mut total = 0u64; - for shard in mtp.values().collect::>() { - 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::>().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::>() - .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 = 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 = 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::>()?, - _ => 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 = 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 { - 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 = 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 { - let [command, rest @ ..] = args else { - return Err( - "usage: tools mtp-fetch inventory|fetch|verify --out DIR [--only SUBSTR]".into(), - ); - }; - let value = |name: &str| -> Result> { - 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::*; diff --git a/control-plane/src/mtp_fetch/impl_fetcher.rs b/control-plane/src/mtp_fetch/impl_fetcher.rs new file mode 100644 index 00000000..576f6a89 --- /dev/null +++ b/control-plane/src/mtp_fetch/impl_fetcher.rs @@ -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 { + 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 { + 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) -> 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> { + 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> { + 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)> { + 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> { + let index: Value = serde_json::from_slice( + &self + .get(&format!("{}model.safetensors.index.json", self.repo), None) + .await?, + )?; + let mtp: BTreeMap = 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::>()?; + let mut rows = Vec::new(); + let mut total = 0u64; + for shard in mtp.values().collect::>() { + 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::>().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::>() + .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 = 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 = 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::>()?, + _ => 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 = 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 { + 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 = 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 + } +} diff --git a/control-plane/src/mtp_fetch/mtime_ns.rs b/control-plane/src/mtp_fetch/mtime_ns.rs new file mode 100644 index 00000000..87ca6d7d --- /dev/null +++ b/control-plane/src/mtp_fetch/mtime_ns.rs @@ -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 { + let [command, rest @ ..] = args else { + return Err( + "usage: tools mtp-fetch inventory|fetch|verify --out DIR [--only SUBSTR]".into(), + ); + }; + let value = |name: &str| -> Result> { + 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()), + } +} diff --git a/control-plane/src/mtp_fetch/repo_url.rs b/control-plane/src/mtp_fetch/repo_url.rs new file mode 100644 index 00000000..bdeb52f1 --- /dev/null +++ b/control-plane/src/mtp_fetch/repo_url.rs @@ -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(value: &T) -> Result> { + 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 { + 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())) +} diff --git a/control-plane/src/native_pack.rs b/control-plane/src/native_pack.rs index 4f4238cb..560072f9 100644 --- a/control-plane/src/native_pack.rs +++ b/control-plane/src/native_pack.rs @@ -20,135 +20,6 @@ struct Shard { index: gguf::TensorIndex, } -fn safe_name(name: &str) -> bool { - !name.is_empty() - && name - .bytes() - .all(|b| b.is_ascii_alphanumeric() || b"._-".contains(&b)) -} - -fn align(bytes: u64) -> Result { - Ok(bytes.checked_add(63).ok_or("native pack size overflow")? / 64 * 64) -} - -fn form(name: &str) -> Option { - 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, - } -} - -fn expert(name: &str) -> bool { - name.starts_with("blk.") && name.ends_with("_exps.weight") -} - -fn shards(manifest: &model::Manifest, source: &Path) -> Result> { - 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) -} - struct Layout<'a> { text: String, n_expert: u64, @@ -157,220 +28,12 @@ struct Layout<'a> { layers: Vec<[(usize, &'a gguf::TensorInfo); 3]>, } -fn expert_layout(shards: &[Shard]) -> Result> { - 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::()?; - 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::>(); - let filenames = roles - .iter() - .map(|(s, _)| { - if *s == 0 { - String::new() - } else { - shards[*s] - .path - .file_name() - .unwrap() - .to_str() - .unwrap() - .to_owned() - } - }) - .collect::>(); - 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 -} - /// Running comparison of converted values with their sources, as `iq_pack.convert` reports it. struct Error64 { exact: bool, max_abs_err: f64, } -impl Error64 { - fn new() -> Self { - Self { - exact: true, - max_abs_err: 0.0, - } - } - - 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; - } - } -} - struct Record { name: String, shard: String, @@ -392,385 +55,6 @@ struct Converted { source_sha256: String, } -fn values_of(bits: &[u8]) -> impl Iterator + '_ { - 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). -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(()) -} - -/// 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)] -fn convert_tensor( - input: &mut File, - shard: &Shard, - tensor: &gguf::TensorInfo, - target: u32, - compat_bf16: bool, - dense: &mut File, -) -> Result { - 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`). -fn native_ple_key(kind: u32) -> bool { - matches!(kind, 8 | 42 | 18 | 23) -} - -/// `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. -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::>(); - 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::>(); - 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(()) -} - -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()) -} - -fn write_conversions(output: &Path, value: &serde_json::Value) -> Result<()> { - write( - output.join("conversions.json"), - &serde_json::to_vec_pretty(value)?, - ) -} - -fn write(path: PathBuf, bytes: &[u8]) -> Result<()> { - let mut file = File::create(path)?; - file.write_all(bytes)?; - file.sync_all()?; - Ok(()) -} - /// Optional parts of `tools/iq_pack.py` beyond the exact default pack. #[derive(Clone, Debug, Default)] pub struct Options { @@ -783,362 +67,24 @@ pub struct Options { pub base: Option, } -pub async fn prepare( - manifest: &model::Manifest, - source: &Path, - output: &Path, -) -> Result { - prepare_with(manifest, source, output, &Options::default()).await -} - -pub async fn prepare_with( - manifest: &model::Manifest, - source: &Path, - output: &Path, - options: &Options, -) -> Result { - 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::>(); - 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}), - ) -} - -/// Whether any recorded conversion rounded a weight (`exact: false`). -fn conversions_inexact(stage: &Path) -> Result { - 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 { - Ok(shards(manifest, source)?[0].path.clone()) -} - -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(()) -} - -fn copy_directory(from: &Path, to: &Path) -> Result { - 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`). -fn write_experts_bin(shards: &[Shard], layout: &Layout, output: &Path) -> Result<()> { - let mut files = shards - .iter() - .map(|s| File::open(&s.path)) - .collect::>>()?; - 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::>(), - "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. -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::new(); - let mut positions: BTreeMap = 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::>(); - 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::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::()?)?; - 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":[]}), - ) -} - -fn same_bytes( - a: &mut File, - a_at: u64, - b: &mut File, - b_at: u64, - a_len: u64, - b_len: u64, -) -> Result { - 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) -} - #[cfg(test)] mod tests; + +mod safe_name; +#[allow(unused_imports)] +pub use safe_name::*; +mod expert_layout; +#[allow(unused_imports)] +pub use expert_layout::*; +mod convert_tensor; +#[allow(unused_imports)] +pub use convert_tensor::*; +mod dense_files; +#[allow(unused_imports)] +pub use dense_files::*; +mod conversions_inexact; +#[allow(unused_imports)] +pub use conversions_inexact::*; +mod same_bytes; +#[allow(unused_imports)] +pub use same_bytes::*; diff --git a/control-plane/src/native_pack/conversions_inexact.rs b/control-plane/src/native_pack/conversions_inexact.rs new file mode 100644 index 00000000..7ec71287 --- /dev/null +++ b/control-plane/src/native_pack/conversions_inexact.rs @@ -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 { + 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 { + 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 { + 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::>>()?; + 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::>(), + "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::new(); + let mut positions: BTreeMap = 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::>(); + 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::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::()?)?; + 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":[]}), + ) +} diff --git a/control-plane/src/native_pack/convert_tensor.rs b/control-plane/src/native_pack/convert_tensor.rs new file mode 100644 index 00000000..f6cedc2c --- /dev/null +++ b/control-plane/src/native_pack/convert_tensor.rs @@ -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 { + 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) +} diff --git a/control-plane/src/native_pack/dense_files.rs b/control-plane/src/native_pack/dense_files.rs new file mode 100644 index 00000000..d9938257 --- /dev/null +++ b/control-plane/src/native_pack/dense_files.rs @@ -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::>(); + 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::>(); + 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 { + prepare_with(manifest, source, output, &Options::default()).await +} + +pub async fn prepare_with( + manifest: &model::Manifest, + source: &Path, + output: &Path, + options: &Options, +) -> Result { + 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::>(); + 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}), + ) +} diff --git a/control-plane/src/native_pack/expert_layout.rs b/control-plane/src/native_pack/expert_layout.rs new file mode 100644 index 00000000..6414bfb0 --- /dev/null +++ b/control-plane/src/native_pack/expert_layout.rs @@ -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> { + 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::()?; + 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::>(); + let filenames = roles + .iter() + .map(|(s, _)| { + if *s == 0 { + String::new() + } else { + shards[*s] + .path + .file_name() + .unwrap() + .to_str() + .unwrap() + .to_owned() + } + }) + .collect::>(); + 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 + '_ { + 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(()) +} diff --git a/control-plane/src/native_pack/safe_name.rs b/control-plane/src/native_pack/safe_name.rs new file mode 100644 index 00000000..a444b8c7 --- /dev/null +++ b/control-plane/src/native_pack/safe_name.rs @@ -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 { + Ok(bytes.checked_add(63).ok_or("native pack size overflow")? / 64 * 64) +} + +pub(super) fn form(name: &str) -> Option { + 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> { + 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) +} diff --git a/control-plane/src/native_pack/same_bytes.rs b/control-plane/src/native_pack/same_bytes.rs new file mode 100644 index 00000000..da0f1b53 --- /dev/null +++ b/control-plane/src/native_pack/same_bytes.rs @@ -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 { + 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) +} diff --git a/control-plane/src/prepare_preview.rs b/control-plane/src/prepare_preview.rs index b6cd965b..bbcab8b8 100644 --- a/control-plane/src/prepare_preview.rs +++ b/control-plane/src/prepare_preview.rs @@ -21,17 +21,6 @@ const MAX_SOURCE_BYTES: u64 = 64 * 1024 * 1024; const MAX_TENSORS: usize = 1000; const MAX_TENSOR_ELEMENTS: u64 = 1_000_000; -pub(crate) fn minimum_part_payload_bytes(derived_bytes: u64, levels: u8) -> Result { - 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)) -} - #[derive(Clone, Copy)] enum PreviewKind { F32, @@ -53,63 +42,6 @@ struct DerivedTensorRef<'a> { bytes: u64, } -impl DerivedIdentity { - fn gguf_digest(&self) -> [u8; 32] { - match self { - Self::Iq3(identity) => identity.gguf_sha256, - Self::Mixed(identity) => identity.gguf_sha256, - } - } - - fn derived_digest(&self) -> [u8; 32] { - match self { - Self::Iq3(identity) => identity.derived_sha256, - Self::Mixed(identity) => identity.derived_sha256, - } - } - - fn derived_bytes(&self) -> u64 { - match self { - Self::Iq3(identity) => identity.derived_bytes, - Self::Mixed(identity) => identity.derived_bytes, - } - } - - 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, - } - } - } - } - - fn tensor_count(&self) -> usize { - match self { - Self::Iq3(identity) => identity.tensors.len(), - Self::Mixed(identity) => identity.tensors.len(), - } - } -} - #[derive(Debug)] pub struct PreviewSummary { pub archive: kar::Summary, @@ -144,1250 +76,27 @@ struct StreamedTensor { struct StagingDir(PathBuf); -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 { - prepare(source_path, destination, levels, PreviewKind::F32) -} - -pub fn prepare_iq3( - source_path: &Path, - destination: &Path, - levels: u8, -) -> Result { - prepare(source_path, destination, levels, PreviewKind::Iq3) -} - -pub fn prepare_mixed( - source_path: &Path, - destination: &Path, - levels: u8, -) -> Result { - prepare(source_path, destination, levels, PreviewKind::Mixed) -} - -pub fn prepare_sharded( - manifest: &Manifest, - source_dir: &Path, - destination: &Path, - levels: u8, -) -> Result { - 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::; - 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, - §ion_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::>(); - 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 { - 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 { - 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), - ) -} - -fn prepare_sharded_streamed_with_limit( - manifest: &Manifest, - source_dir: &Path, - destination: &Path, - levels: u8, - max_part_elements: u64, -) -> Result { - prepare_sharded_streamed_with_policy( - manifest, - source_dir, - destination, - levels, - max_part_elements, - None, - ) -} - -fn prepare_sharded_streamed_with_policy( - manifest: &Manifest, - source_dir: &Path, - destination: &Path, - levels: u8, - max_part_elements: u64, - ple_part_elements: Option, -) -> Result { - 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::(); - 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::; - 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, - §ion_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, - §ion_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::>(); - 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), - }) -} - -fn spool_raw_f32( - 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 -} - -fn prepare( - source_path: &Path, - destination: &Path, - levels: u8, - kind: PreviewKind, -) -> Result { - 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::>(); - (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, - §ion_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::>(); - 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, - }) -} - -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::>(); - 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::>(); - 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 { - verify_derived(source_path, archive_path, PreviewKind::Iq3) -} - -pub fn verify_mixed(source_path: &Path, archive_path: &Path) -> Result { - verify_derived(source_path, archive_path, PreviewKind::Mixed) -} - -pub fn verify_sharded( - manifest: &Manifest, - source_dir: &Path, - archive_path: &Path, -) -> Result { - 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 { - 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 { - 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), - ) -} - -fn verify_sharded_inner( - manifest: &Manifest, - source_dir: &Path, - archive_path: &Path, - streamed_levels: Option, - max_part_elements: u64, - ple_part_elements: Option, -) -> Result { - 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) -} - -fn verify_derived( - source_path: &Path, - archive_path: &Path, - kind: PreviewKind, -) -> Result { - 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) -} - -fn decode_source_tensor(kind: u32, raw: &[u8], elements: usize) -> Result, 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) -} - -fn provenance_path(destination: &Path) -> Result { - Ok(destination.with_file_name(format!( - "{}.provenance.json", - destination - .file_name() - .ok_or("KAR destination has no file name")? - .to_string_lossy() - ))) -} - -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::>(), - }), - 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::>(), - }), - } -} - -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::>(), - "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::>(), - }) -} - -fn partitioned_provenance(parts: &[Vec]) -> 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::>(), - }) - }) - .collect::>() - ) -} - -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 -} - -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()) -} - #[cfg(test)] mod tests; + +mod minimum_part_payload_bytes; +#[allow(unused_imports)] +pub use minimum_part_payload_bytes::*; +mod prepare_sharded; +#[allow(unused_imports)] +pub use prepare_sharded::*; +mod prepare_sharded_streamed_with_policy; +#[allow(unused_imports)] +pub use prepare_sharded_streamed_with_policy::*; +mod spool_raw_f32; +#[allow(unused_imports)] +pub use spool_raw_f32::*; +mod prepare; +#[allow(unused_imports)] +pub use prepare::*; +mod encode_preview_tensor; +#[allow(unused_imports)] +pub use encode_preview_tensor::*; +mod verify_derived; +#[allow(unused_imports)] +pub use verify_derived::*; diff --git a/control-plane/src/prepare_preview/encode_preview_tensor.rs b/control-plane/src/prepare_preview/encode_preview_tensor.rs new file mode 100644 index 00000000..2912a861 --- /dev/null +++ b/control-plane/src/prepare_preview/encode_preview_tensor.rs @@ -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::>(); + 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::>(); + 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 { + verify_derived(source_path, archive_path, PreviewKind::Iq3) +} + +pub fn verify_mixed(source_path: &Path, archive_path: &Path) -> Result { + verify_derived(source_path, archive_path, PreviewKind::Mixed) +} + +pub fn verify_sharded( + manifest: &Manifest, + source_dir: &Path, + archive_path: &Path, +) -> Result { + 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 { + 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 { + 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, + max_part_elements: u64, + ple_part_elements: Option, +) -> Result { + 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) +} diff --git a/control-plane/src/prepare_preview/minimum_part_payload_bytes.rs b/control-plane/src/prepare_preview/minimum_part_payload_bytes.rs new file mode 100644 index 00000000..f6233719 --- /dev/null +++ b/control-plane/src/prepare_preview/minimum_part_payload_bytes.rs @@ -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 { + 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 { + prepare(source_path, destination, levels, PreviewKind::F32) +} + +pub fn prepare_iq3( + source_path: &Path, + destination: &Path, + levels: u8, +) -> Result { + prepare(source_path, destination, levels, PreviewKind::Iq3) +} + +pub fn prepare_mixed( + source_path: &Path, + destination: &Path, + levels: u8, +) -> Result { + prepare(source_path, destination, levels, PreviewKind::Mixed) +} diff --git a/control-plane/src/prepare_preview/prepare.rs b/control-plane/src/prepare_preview/prepare.rs new file mode 100644 index 00000000..2de0cbc0 --- /dev/null +++ b/control-plane/src/prepare_preview/prepare.rs @@ -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 { + 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::>(); + (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, + §ion_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::>(); + 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, + }) +} diff --git a/control-plane/src/prepare_preview/prepare_sharded.rs b/control-plane/src/prepare_preview/prepare_sharded.rs new file mode 100644 index 00000000..adbc03a1 --- /dev/null +++ b/control-plane/src/prepare_preview/prepare_sharded.rs @@ -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 { + 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::; + 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, + §ion_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::>(); + 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 { + 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 { + 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 { + prepare_sharded_streamed_with_policy( + manifest, + source_dir, + destination, + levels, + max_part_elements, + None, + ) +} diff --git a/control-plane/src/prepare_preview/prepare_sharded_streamed_with_policy.rs b/control-plane/src/prepare_preview/prepare_sharded_streamed_with_policy.rs new file mode 100644 index 00000000..dc1cf75e --- /dev/null +++ b/control-plane/src/prepare_preview/prepare_sharded_streamed_with_policy.rs @@ -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, +) -> Result { + 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::(); + 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::; + 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, + §ion_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, + §ion_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::>(); + 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), + }) +} diff --git a/control-plane/src/prepare_preview/spool_raw_f32.rs b/control-plane/src/prepare_preview/spool_raw_f32.rs new file mode 100644 index 00000000..f116b78f --- /dev/null +++ b/control-plane/src/prepare_preview/spool_raw_f32.rs @@ -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( + 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 +} diff --git a/control-plane/src/prepare_preview/verify_derived.rs b/control-plane/src/prepare_preview/verify_derived.rs new file mode 100644 index 00000000..b1b57307 --- /dev/null +++ b/control-plane/src/prepare_preview/verify_derived.rs @@ -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 { + 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, 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 { + 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::>(), + }), + 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::>(), + }), + } +} + +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::>(), + "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::>(), + }) +} + +pub(super) fn partitioned_provenance( + parts: &[Vec], +) -> 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::>(), + }) + }) + .collect::>() + ) +} + +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()) +} diff --git a/control-plane/src/prometheus.rs b/control-plane/src/prometheus.rs index a5cac408..d68bd7f5 100644 --- a/control-plane/src/prometheus.rs +++ b/control-plane/src/prometheus.rs @@ -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,121 +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; + +mod counter; +#[allow(unused_imports)] +pub use counter::*; diff --git a/control-plane/src/prometheus/counter.rs b/control-plane/src/prometheus/counter.rs new file mode 100644 index 00000000..5858d3a3 --- /dev/null +++ b/control-plane/src/prometheus/counter.rs @@ -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, + } +} diff --git a/control-plane/src/reasoning_budget.rs b/control-plane/src/reasoning_budget.rs index 65c767d7..4e05fd65 100644 --- a/control-plane/src/reasoning_budget.rs +++ b/control-plane/src/reasoning_budget.rs @@ -15,173 +15,6 @@ pub const REASONING_WRAP_UP: &str = "\n\nI have thought about this long enough; time to give my answer.\n\n\n"; const THINK_END: &str = ""; -/// `Service.reasoning_budget`: the request's `reasoning_budget_tokens`, else the configured default; 0 or less (and an -/// absent budget) mean no budget. An `Err` is the message of the 400. -pub fn reasoning_budget(request: Option<&Value>, default: &Value) -> Result, String> { - let from_request = request - .and_then(Value::as_object) - .and_then(|object| object.get("reasoning_budget_tokens")) - .filter(|value| !value.is_null()); - let value = from_request.unwrap_or(default); - let whole = match value { - Value::Number(number) => { - if let Some(unsigned) = number.as_u64() { - Some(i128::from(unsigned)) - } else if let Some(signed) = number.as_i64() { - Some(i128::from(signed)) - } else { - number - .as_f64() - .filter(|float| float.is_finite() && float.fract() == 0.0) - .map(|float| float as i128) - } - } - _ => None, - }; - match whole { - Some(count) if count > 0 => Ok(Some(u64::try_from(count).unwrap_or(u64::MAX))), - Some(_) => Ok(None), - None => Err(format!( - "reasoning_budget_tokens={}: expected a whole number of tokens (0: no budget)", - python_repr(value) - )), - } -} - -/// Python's `repr()` of a JSON value, for the 400 message. Dict keys come out in serde_json's (sorted) order. -/// Strings with characters outside the categories listed in [`is_printable`] may differ from Python's `isprintable`. -pub fn python_repr(value: &Value) -> String { - match value { - Value::Null => "None".into(), - Value::Bool(true) => "True".into(), - Value::Bool(false) => "False".into(), - Value::Number(number) => { - if let Some(unsigned) = number.as_u64() { - unsigned.to_string() - } else if let Some(signed) = number.as_i64() { - signed.to_string() - } else { - float_repr(number.as_f64().unwrap_or(f64::NAN)) - } - } - Value::String(text) => string_repr(text), - Value::Array(items) => { - let parts: Vec = items.iter().map(python_repr).collect(); - format!("[{}]", parts.join(", ")) - } - Value::Object(map) => { - let parts: Vec = map - .iter() - .map(|(key, item)| format!("{}: {}", string_repr(key), python_repr(item))) - .collect(); - format!("{{{}}}", parts.join(", ")) - } - } -} - -fn float_repr(value: f64) -> String { - if value.is_nan() { - return "nan".into(); - } - if value.is_infinite() { - return if value > 0.0 { "inf" } else { "-inf" }.into(); - } - if value == 0.0 { - return if value.is_sign_negative() { - "-0.0" - } else { - "0.0" - } - .into(); - } - let scientific = format!("{value:e}"); - let (mantissa, exponent) = scientific.split_once('e').unwrap_or((&scientific, "0")); - let exponent: i32 = exponent.parse().unwrap_or(0); - if (-4..16).contains(&exponent) { - let positional = format!("{value}"); - if positional.contains('.') { - positional - } else { - format!("{positional}.0") - } - } else { - let sign = if exponent < 0 { '-' } else { '+' }; - format!("{mantissa}e{sign}{:02}", exponent.abs()) - } -} - -fn string_repr(text: &str) -> String { - let quote = if text.contains('\'') && !text.contains('"') { - '"' - } else { - '\'' - }; - let mut out = String::with_capacity(text.len() + 2); - out.push(quote); - for c in text.chars() { - match c { - '\\' => out.push_str("\\\\"), - '\t' => out.push_str("\\t"), - '\n' => out.push_str("\\n"), - '\r' => out.push_str("\\r"), - c if c == quote => { - out.push('\\'); - out.push(c); - } - c if is_printable(c) => out.push(c), - c if (c as u32) < 0x100 => { - let _ = write!(out, "\\x{:02x}", c as u32); - } - c if (c as u32) < 0x10000 => { - let _ = write!(out, "\\u{:04x}", c as u32); - } - c => { - let _ = write!(out, "\\U{:08x}", c as u32); - } - } - } - out.push(quote); - out -} - -/// `str.isprintable` for one character, from the categories Rust's standard library cannot name: Cc, Zs/Zl/Zp, the -/// Cf and Co blocks. Unassigned code points (Cn) are treated as printable. -fn is_printable(c: char) -> bool { - if c == ' ' { - return true; - } - let code = c as u32; - if c.is_control() { - return false; - } - let separators = matches!( - code, - 0xA0 | 0x1680 | 0x2000..=0x200A | 0x2028 | 0x2029 | 0x202F | 0x205F | 0x3000 - ); - let format = matches!( - code, - 0xAD | 0x600..=0x605 - | 0x61C - | 0x6DD - | 0x70F - | 0x8E2 - | 0x180E - | 0x200B..=0x200F - | 0x202A..=0x202E - | 0x2060..=0x2064 - | 0x2066..=0x206F - | 0xFEFF - | 0xFFF9..=0xFFFB - | 0x110BD - | 0x1BCA0..=0x1BCA3 - | 0x1D173..=0x1D17A - | 0xE0001 - | 0xE0020..=0xE007F - ); - let private = matches!(code, 0xE000..=0xF8FF | 0xF0000..=0xFFFFD | 0x100000..=0x10FFFD); - !(separators || format || private) -} - /// An incremental UTF-8 decoder with replacement (`codecs.getincrementaldecoder("utf-8")(errors="replace")`): complete /// characters come out, a character split across tokens is held until it is whole. #[derive(Debug, Default)] @@ -189,44 +22,6 @@ pub struct Utf8Stream { held: Vec, } -impl Utf8Stream { - /// A character is split across the tokens so far: its first bytes are held. - pub fn pending(&self) -> bool { - !self.held.is_empty() - } - - pub fn push(&mut self, bytes: &[u8]) -> String { - self.held.extend_from_slice(bytes); - let mut out = String::new(); - let mut at = 0; - loop { - match std::str::from_utf8(&self.held[at..]) { - Ok(valid) => { - out.push_str(valid); - at = self.held.len(); - break; - } - Err(error) => { - let good = at + error.valid_up_to(); - out.push_str(std::str::from_utf8(&self.held[at..good]).unwrap_or_default()); - match error.error_len() { - Some(bad) => { - out.push('\u{FFFD}'); - at = good + bad; - } - None => { - at = good; - break; - } - } - } - } - } - self.held.drain(..at); - out - } -} - /// The part of `OutputParser` the budget depends on: whether the output is still inside the thinking, and the text it /// holds back (a possible start of ``). #[derive(Debug)] @@ -235,26 +30,6 @@ struct ReasoningScan { held: String, } -impl ReasoningScan { - fn feed(&mut self, delta: &str) { - if !self.reasoning { - return; - } - self.held.push_str(delta); - if self.held.contains(THINK_END) { - self.held.clear(); - self.reasoning = false; - return; - } - let keep = (1..THINK_END.len()) - .rev() - .find(|&len| self.held.ends_with(&THINK_END[..len])) - .unwrap_or(0); - let cut = self.held.len() - keep; - self.held.drain(..cut); - } -} - /// The engine as the loop sees it: tokens for a prompt, at most `max_new` of them. Dropping the iterator is the /// `gen.close()` (stop and drain). pub trait TokenEngine { @@ -272,16 +47,6 @@ pub trait TokenCodec { fn wrap_up_ids(&self) -> Vec; } -impl TokenCodec for leleka_tokenizer::Tokenizer { - fn token_bytes(&self, id: u32) -> Vec { - self.decode_bytes(&[id]).unwrap_or_default() - } - - fn wrap_up_ids(&self) -> Vec { - self.encode(REASONING_WRAP_UP, true).unwrap_or_default() - } -} - #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum Finish { Length, @@ -311,92 +76,12 @@ pub struct Run { pub text: String, } -/// The generation loop of `Service.run`. `cancel` is polled where Python reads `cancel.is_set()`. -pub fn run( - engine: &mut E, - codec: &C, - request: &RunRequest<'_>, - cancel: &dyn Fn() -> bool, -) -> Result { - let mut budget = if request.thinking { - request.budget - } else { - None - }; - let mut scan = ReasoningScan { - reasoning: request.thinking, - held: String::new(), - }; - let mut detok = Utf8Stream::default(); - let (mut prompt, mut thought, mut n) = (request.prompt.to_vec(), 0u64, 0usize); - let mut finish = Finish::Length; - let (mut raw_ids, mut text, mut wrapped_after) = (Vec::new(), String::new(), None); - loop { - let mut segment = Vec::new(); - let mut wrap = false; - { - let tokens = engine.generate(&prompt, request.max_new.saturating_sub(n)); - for token in tokens { - let token = token?; - n += 1; - if request.stop_ids.contains(&token) { - finish = Finish::Stop; - raw_ids.push(token); - break; - } - raw_ids.push(token); - segment.push(token); - let delta = detok.push(&codec.token_bytes(token)); - scan.feed(&delta); - text.push_str(&delta); - if budget.is_some() && scan.reasoning { - thought += 1; - // at a clean point: no tag held back, no character split across tokens - if thought >= budget.unwrap_or(u64::MAX) - && scan.held.is_empty() - && !detok.pending() - { - wrap = true; - break; - } - } - } - } - if !wrap || cancel() { - break; - } - budget = None; - let extra = codec.wrap_up_ids(); - if request - .max_new - .saturating_sub(n) - .saturating_sub(extra.len()) - < 1 - { - break; // no room left to answer: "length", as without a budget - } - wrapped_after = Some(thought); - for &token in &extra { - n += 1; - raw_ids.push(token); - let delta = detok.push(&codec.token_bytes(token)); - scan.feed(&delta); - text.push_str(&delta); - } - prompt.extend_from_slice(&segment); - prompt.extend_from_slice(&extra); - } - if cancel() { - finish = Finish::Cancel; - } - Ok(Run { - finish, - completion_tokens: n, - generated: raw_ids, - wrapped_after, - text, - }) -} - #[cfg(test)] mod tests; + +mod reasoning_budget; +#[allow(unused_imports)] +pub use reasoning_budget::*; +mod run; +#[allow(unused_imports)] +pub use run::*; diff --git a/control-plane/src/reasoning_budget/reasoning_budget.rs b/control-plane/src/reasoning_budget/reasoning_budget.rs new file mode 100644 index 00000000..43fb42c4 --- /dev/null +++ b/control-plane/src/reasoning_budget/reasoning_budget.rs @@ -0,0 +1,239 @@ +//! Moved out of the parent module by STRA-338: fn reasoning_budget, fn python_repr, fn float_repr, fn string_repr, fn is_printable, impl Utf8Stream .... + +#[allow(unused_imports)] +use super::*; + +/// `Service.reasoning_budget`: the request's `reasoning_budget_tokens`, else the configured default; 0 or less (and an +/// absent budget) mean no budget. An `Err` is the message of the 400. +pub fn reasoning_budget(request: Option<&Value>, default: &Value) -> Result, String> { + let from_request = request + .and_then(Value::as_object) + .and_then(|object| object.get("reasoning_budget_tokens")) + .filter(|value| !value.is_null()); + let value = from_request.unwrap_or(default); + let whole = match value { + Value::Number(number) => { + if let Some(unsigned) = number.as_u64() { + Some(i128::from(unsigned)) + } else if let Some(signed) = number.as_i64() { + Some(i128::from(signed)) + } else { + number + .as_f64() + .filter(|float| float.is_finite() && float.fract() == 0.0) + .map(|float| float as i128) + } + } + _ => None, + }; + match whole { + Some(count) if count > 0 => Ok(Some(u64::try_from(count).unwrap_or(u64::MAX))), + Some(_) => Ok(None), + None => Err(format!( + "reasoning_budget_tokens={}: expected a whole number of tokens (0: no budget)", + python_repr(value) + )), + } +} + +/// Python's `repr()` of a JSON value, for the 400 message. Dict keys come out in serde_json's (sorted) order. +/// Strings with characters outside the categories listed in [`is_printable`] may differ from Python's `isprintable`. +pub fn python_repr(value: &Value) -> String { + match value { + Value::Null => "None".into(), + Value::Bool(true) => "True".into(), + Value::Bool(false) => "False".into(), + Value::Number(number) => { + if let Some(unsigned) = number.as_u64() { + unsigned.to_string() + } else if let Some(signed) = number.as_i64() { + signed.to_string() + } else { + float_repr(number.as_f64().unwrap_or(f64::NAN)) + } + } + Value::String(text) => string_repr(text), + Value::Array(items) => { + let parts: Vec = items.iter().map(python_repr).collect(); + format!("[{}]", parts.join(", ")) + } + Value::Object(map) => { + let parts: Vec = map + .iter() + .map(|(key, item)| format!("{}: {}", string_repr(key), python_repr(item))) + .collect(); + format!("{{{}}}", parts.join(", ")) + } + } +} + +pub(super) fn float_repr(value: f64) -> String { + if value.is_nan() { + return "nan".into(); + } + if value.is_infinite() { + return if value > 0.0 { "inf" } else { "-inf" }.into(); + } + if value == 0.0 { + return if value.is_sign_negative() { + "-0.0" + } else { + "0.0" + } + .into(); + } + let scientific = format!("{value:e}"); + let (mantissa, exponent) = scientific.split_once('e').unwrap_or((&scientific, "0")); + let exponent: i32 = exponent.parse().unwrap_or(0); + if (-4..16).contains(&exponent) { + let positional = format!("{value}"); + if positional.contains('.') { + positional + } else { + format!("{positional}.0") + } + } else { + let sign = if exponent < 0 { '-' } else { '+' }; + format!("{mantissa}e{sign}{:02}", exponent.abs()) + } +} + +pub(super) fn string_repr(text: &str) -> String { + let quote = if text.contains('\'') && !text.contains('"') { + '"' + } else { + '\'' + }; + let mut out = String::with_capacity(text.len() + 2); + out.push(quote); + for c in text.chars() { + match c { + '\\' => out.push_str("\\\\"), + '\t' => out.push_str("\\t"), + '\n' => out.push_str("\\n"), + '\r' => out.push_str("\\r"), + c if c == quote => { + out.push('\\'); + out.push(c); + } + c if is_printable(c) => out.push(c), + c if (c as u32) < 0x100 => { + let _ = write!(out, "\\x{:02x}", c as u32); + } + c if (c as u32) < 0x10000 => { + let _ = write!(out, "\\u{:04x}", c as u32); + } + c => { + let _ = write!(out, "\\U{:08x}", c as u32); + } + } + } + out.push(quote); + out +} + +/// `str.isprintable` for one character, from the categories Rust's standard library cannot name: Cc, Zs/Zl/Zp, the +/// Cf and Co blocks. Unassigned code points (Cn) are treated as printable. +pub(super) fn is_printable(c: char) -> bool { + if c == ' ' { + return true; + } + let code = c as u32; + if c.is_control() { + return false; + } + let separators = matches!( + code, + 0xA0 | 0x1680 | 0x2000..=0x200A | 0x2028 | 0x2029 | 0x202F | 0x205F | 0x3000 + ); + let format = matches!( + code, + 0xAD | 0x600..=0x605 + | 0x61C + | 0x6DD + | 0x70F + | 0x8E2 + | 0x180E + | 0x200B..=0x200F + | 0x202A..=0x202E + | 0x2060..=0x2064 + | 0x2066..=0x206F + | 0xFEFF + | 0xFFF9..=0xFFFB + | 0x110BD + | 0x1BCA0..=0x1BCA3 + | 0x1D173..=0x1D17A + | 0xE0001 + | 0xE0020..=0xE007F + ); + let private = matches!(code, 0xE000..=0xF8FF | 0xF0000..=0xFFFFD | 0x100000..=0x10FFFD); + !(separators || format || private) +} + +impl Utf8Stream { + /// A character is split across the tokens so far: its first bytes are held. + pub fn pending(&self) -> bool { + !self.held.is_empty() + } + + pub fn push(&mut self, bytes: &[u8]) -> String { + self.held.extend_from_slice(bytes); + let mut out = String::new(); + let mut at = 0; + loop { + match std::str::from_utf8(&self.held[at..]) { + Ok(valid) => { + out.push_str(valid); + at = self.held.len(); + break; + } + Err(error) => { + let good = at + error.valid_up_to(); + out.push_str(std::str::from_utf8(&self.held[at..good]).unwrap_or_default()); + match error.error_len() { + Some(bad) => { + out.push('\u{FFFD}'); + at = good + bad; + } + None => { + at = good; + break; + } + } + } + } + } + self.held.drain(..at); + out + } +} + +impl ReasoningScan { + pub(super) fn feed(&mut self, delta: &str) { + if !self.reasoning { + return; + } + self.held.push_str(delta); + if self.held.contains(THINK_END) { + self.held.clear(); + self.reasoning = false; + return; + } + let keep = (1..THINK_END.len()) + .rev() + .find(|&len| self.held.ends_with(&THINK_END[..len])) + .unwrap_or(0); + let cut = self.held.len() - keep; + self.held.drain(..cut); + } +} + +impl TokenCodec for leleka_tokenizer::Tokenizer { + fn token_bytes(&self, id: u32) -> Vec { + self.decode_bytes(&[id]).unwrap_or_default() + } + + fn wrap_up_ids(&self) -> Vec { + self.encode(REASONING_WRAP_UP, true).unwrap_or_default() + } +} diff --git a/control-plane/src/reasoning_budget/run.rs b/control-plane/src/reasoning_budget/run.rs new file mode 100644 index 00000000..222fd544 --- /dev/null +++ b/control-plane/src/reasoning_budget/run.rs @@ -0,0 +1,91 @@ +//! Moved out of the parent module by STRA-338: fn run. + +#[allow(unused_imports)] +use super::*; + +/// The generation loop of `Service.run`. `cancel` is polled where Python reads `cancel.is_set()`. +pub fn run( + engine: &mut E, + codec: &C, + request: &RunRequest<'_>, + cancel: &dyn Fn() -> bool, +) -> Result { + let mut budget = if request.thinking { + request.budget + } else { + None + }; + let mut scan = ReasoningScan { + reasoning: request.thinking, + held: String::new(), + }; + let mut detok = Utf8Stream::default(); + let (mut prompt, mut thought, mut n) = (request.prompt.to_vec(), 0u64, 0usize); + let mut finish = Finish::Length; + let (mut raw_ids, mut text, mut wrapped_after) = (Vec::new(), String::new(), None); + loop { + let mut segment = Vec::new(); + let mut wrap = false; + { + let tokens = engine.generate(&prompt, request.max_new.saturating_sub(n)); + for token in tokens { + let token = token?; + n += 1; + if request.stop_ids.contains(&token) { + finish = Finish::Stop; + raw_ids.push(token); + break; + } + raw_ids.push(token); + segment.push(token); + let delta = detok.push(&codec.token_bytes(token)); + scan.feed(&delta); + text.push_str(&delta); + if budget.is_some() && scan.reasoning { + thought += 1; + // at a clean point: no tag held back, no character split across tokens + if thought >= budget.unwrap_or(u64::MAX) + && scan.held.is_empty() + && !detok.pending() + { + wrap = true; + break; + } + } + } + } + if !wrap || cancel() { + break; + } + budget = None; + let extra = codec.wrap_up_ids(); + if request + .max_new + .saturating_sub(n) + .saturating_sub(extra.len()) + < 1 + { + break; // no room left to answer: "length", as without a budget + } + wrapped_after = Some(thought); + for &token in &extra { + n += 1; + raw_ids.push(token); + let delta = detok.push(&codec.token_bytes(token)); + scan.feed(&delta); + text.push_str(&delta); + } + prompt.extend_from_slice(&segment); + prompt.extend_from_slice(&extra); + } + if cancel() { + finish = Finish::Cancel; + } + Ok(Run { + finish, + completion_tokens: n, + generated: raw_ids, + wrapped_after, + text, + }) +} diff --git a/control-plane/src/request_log.rs b/control-plane/src/request_log.rs index 5e331adc..0b481ba6 100644 --- a/control-plane/src/request_log.rs +++ b/control-plane/src/request_log.rs @@ -68,64 +68,6 @@ const SESSION_HEADERS: [&str; 4] = [ "x-conversation-id", ]; -pub fn endpoint_index(path: &str) -> usize { - match path { - "/v1/responses" => 0, - "/v1/chat/completions" => 1, - "/v1/messages" => 2, - _ => 3, - } -} - -/// The session id of the log: a short digest of what the client sent, so lines of one conversation correlate and the -/// client's own identifier (which could be a user id) is not written down. -pub fn session_tag(headers: &HeaderMap) -> Option { - let raw = SESSION_HEADERS - .iter() - .find_map(|name| headers.get(*name)) - .and_then(|v| v.to_str().ok()) - .map(str::trim) - .filter(|v| !v.is_empty())?; - let digest = Sha256::digest(raw.as_bytes()); - Some(format!("s-{}", hex::encode(&digest[..5]))) -} - -/// A short error class and whether the message is our own wording (safe to log) rather than something that might echo input. -pub fn classify_error(message: &str) -> (&'static str, bool) { - let m = message; - if m.starts_with("engine made no progress") { - ("stall", true) - } else if m.contains("exceeded configured execution deadline") { - ("deadline", true) - } else if m.contains("memory_pressure") { - ("memory_pressure", true) - } else if m.starts_with("engine refused the generation") { - ("engine_refused", true) - } else if m.starts_with("engine stream ended") || m.contains("without a terminal event") { - ("stream_ended", true) - } else if m.starts_with("engine did not terminate the generation") { - ("cancel_timeout", true) - } else if m.contains("worker is restarting") - || m.contains("not attached to the engine") - || m.contains("runtime restarted") - || m.contains("stopped before completing") - { - ("engine_lost", true) - } else { - ("other", false) - } -} - -/// The class of a rejection by HTTP status (a request that never reached the engine). -pub fn class_of_status(status: u16) -> &'static str { - match status { - 400 | 404 | 405 | 413 | 415 | 422 => "bad_request", - 429 => "overloaded", - 503 => "unavailable", - _ => "other", - } -} - #[derive(Clone, Debug, Default)] struct DoneInfo { prompt_tokens: u64, @@ -159,199 +101,14 @@ pub struct ReqCtx { state: Mutex, } -impl ReqCtx { - pub fn new( - id: String, - endpoint: usize, - sid: Option, - model: Option, - memory: Option>, - ) -> Self { - Self { - state: Mutex::new(Live { - id, - sid, - endpoint, - stream: None, - model, - profile: std::env::var("LELEKA_PROFILE") - .ok() - .filter(|p| !p.is_empty()), - admitted: Instant::now(), - engine_start: None, - first_token: None, - done: None, - error: None, - http_status: None, - restart: false, - emitted: false, - memory, - }), - } - } - - fn with(&self, f: impl FnOnce(&mut Live) -> T) -> Option { - self.state.lock().ok().map(|mut s| f(&mut s)) - } - - pub fn id(&self) -> String { - self.with(|s| s.id.clone()).unwrap_or_default() - } - - pub fn set_stream(&self, stream: bool) { - self.with(|s| s.stream = Some(stream)); - } - - pub fn set_http_status(&self, status: u16) { - self.with(|s| s.http_status = Some(status)); - } - - /// The worker handed the request to the engine: the queue wait ends. - pub fn engine_start(&self) { - self.with(|s| { - s.engine_start.get_or_insert_with(Instant::now); - }); - } - - pub fn first_token(&self) { - self.with(|s| { - s.first_token.get_or_insert_with(Instant::now); - }); - } - - pub fn done(&self, done: &Done, disconnected: bool) { - self.with(|s| { - s.done = Some(DoneInfo { - prompt_tokens: done.prompt_tokens, - cached_tokens: done.reused.unwrap_or(0), - output_tokens: done.generated, - decode_ms: done.decode_ms, - finish: match done.finish { - Finish::Stop => "stop", - Finish::Length => "length", - Finish::Cancel => "cancel", - }, - disconnected, - }); - }); - } - - pub fn error(&self, message: &str) { - let (class, ours) = classify_error(message); - let shown = if ours { - leleka_obs::redact::clip(message, 160).to_owned() - } else { - format!("{} bytes", message.len()) - }; - self.with(|s| { - if s.error.is_none() { - s.error = Some((class, shown)); - } - }); - } - - /// The engine was lost while this request was in flight. - pub fn engine_restarted(&self) { - self.with(|s| s.restart = true); - } - - /// Write the record now (once). - pub fn finalize(&self) { - let record = self.with(|s| { - if s.emitted { - return None; - } - s.emitted = true; - Some(Record::from_state(s)) - }); - if let Some(Some(record)) = record { - record.publish(); - } - } -} - -impl Drop for ReqCtx { - fn drop(&mut self) { - let record = match self.state.get_mut() { - Ok(state) if !state.emitted => { - state.emitted = true; - Some(Record::from_state(state)) - } - _ => None, - }; - if let Some(record) = record { - record.publish(); - } - } -} - /// What the request middleware leaves for the handler and the worker. #[derive(Clone, Default)] pub struct ObsHandle(pub Option>); -impl std::fmt::Debug for ObsHandle { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - f.write_str("ObsHandle") - } -} - -impl PartialEq for ObsHandle { - /// Never part of a request's identity. - fn eq(&self, _: &Self) -> bool { - true - } -} - tokio::task_local! { static CURRENT: Arc; } -impl ObsHandle { - /// The request being served by the current task, if the `observe` middleware wrapped it. - pub fn current() -> Self { - Self(CURRENT.try_with(Arc::clone).ok()) - } - - pub fn id(&self) -> Option { - self.0.as_ref().map(|c| c.id()) - } - pub fn set_stream(&self, stream: bool) { - if let Some(c) = &self.0 { - c.set_stream(stream); - } - } - pub fn engine_start(&self) { - if let Some(c) = &self.0 { - c.engine_start(); - } - } - pub fn first_token(&self) { - if let Some(c) = &self.0 { - c.first_token(); - } - } - pub fn done(&self, done: &Done, disconnected: bool) { - if let Some(c) = &self.0 { - c.done(done, disconnected); - } - } - pub fn error(&self, message: &str) { - if let Some(c) = &self.0 { - c.error(message); - } - } - pub fn engine_restarted(&self) { - if let Some(c) = &self.0 { - c.engine_restarted(); - } - } - pub fn finalize(&self) { - if let Some(c) = &self.0 { - c.finalize(); - } - } -} - /// What the middleware needs from the application. #[derive(Clone)] pub struct Observe { @@ -359,26 +116,6 @@ pub struct Observe { pub memory: Arc, } -/// Outermost layer of the three generation routes: gives the request an id (and a response header carrying it), reads the -/// session header, and keeps the record for the handler. A rejection (status 4xx/5xx before the engine) is recorded here. -pub async fn observe(State(observe): State, request: Request, next: Next) -> Response { - let endpoint = endpoint_index(request.uri().path()); - let ctx = Arc::new(ReqCtx::new( - uuid::Uuid::new_v4().to_string(), - endpoint, - session_tag(request.headers()), - observe.model.clone(), - Some(observe.memory.clone()), - )); - let id = ctx.id(); - let mut response = CURRENT.scope(ctx.clone(), next.run(request)).await; - ctx.set_http_status(response.status().as_u16()); - if let Ok(value) = HeaderValue::from_str(&id) { - response.headers_mut().insert(REQUEST_ID_HEADER, value); - } - response -} - /// Everything the line says, resolved. #[derive(Debug, Clone, PartialEq)] pub struct Record { @@ -404,128 +141,6 @@ pub struct Record { pub hardware: Option, } -fn round1(v: f64) -> f64 { - (v * 10.0).round() / 10.0 -} - -impl Record { - fn from_state(s: &Live) -> Record { - let now = Instant::now(); - let ms = |from: Instant, to: Instant| { - u64::try_from(to.saturating_duration_since(from).as_millis()).unwrap_or(u64::MAX) - }; - let queue_ms = s.engine_start.map(|t| ms(s.admitted, t)); - let ttft_ms = s.first_token.map(|t| ms(s.admitted, t)); - let (prompt_tokens, cached_tokens, output_tokens) = match &s.done { - Some(d) => ( - Some(d.prompt_tokens), - Some(d.cached_tokens), - Some(d.output_tokens), - ), - None => (None, None, None), - }; - let prefill_tps = match (&s.done, s.engine_start, s.first_token) { - (Some(d), Some(start), Some(first)) => { - let fresh = d.prompt_tokens.saturating_sub(d.cached_tokens); - let secs = first.saturating_duration_since(start).as_secs_f64(); - (fresh > 0 && secs > 0.0).then(|| round1(fresh as f64 / secs)) - } - _ => None, - }; - let decode_tps = s - .done - .as_ref() - .and_then(|d| { - (d.output_tokens > 1) - .then(|| crate::metrics::token_rate(d.output_tokens, d.decode_ms)) - .flatten() - }) - .map(round1); - let http_failed = s.http_status.is_some_and(|c| c >= 400); - let outcome = match (&s.done, &s.error) { - (Some(d), _) if d.disconnected => "disconnect", - (Some(d), _) => d.finish, - (None, Some(_)) if s.engine_start.is_some() => "error", - (None, Some(_)) => "rejected", - (None, None) if http_failed => "rejected", - (None, None) => "abandoned", - }; - let (error_class, error) = match (&s.error, http_failed, outcome) { - (Some((class, text)), _, _) => (*class, Some(text.clone())), - (None, true, _) => (class_of_status(s.http_status.unwrap_or(0)), None), - _ => ("none", None), - }; - Record { - id: s.id.clone(), - sid: s.sid.clone(), - endpoint: s.endpoint, - stream: s.stream, - model: s.model.clone(), - profile: s.profile.clone(), - status: s.http_status, - outcome, - prompt_tokens, - cached_tokens, - output_tokens, - queue_ms, - ttft_ms, - prefill_tps, - decode_tps, - total_ms: ms(s.admitted, now), - restart: s.restart, - error_class, - error, - hardware: s.memory.as_ref().and_then(|m| m.brief()), - } - } - - /// The fields of the line, in order. A figure that was not measured is left out (a missing key means unknown), which - /// also keeps the line short. - pub fn fields(&self) -> Vec> { - let mut f: Vec> = Vec::with_capacity(28); - macro_rules! put { - ($key:expr, $value:expr) => {{ - let value: V<'_> = $value; - if !matches!(value, V::Null) { - f.push(($key, value)); - } - }}; - } - put!("rid", V::Str(&self.id)); - put!("sid", self.sid.as_deref().into()); - put!("ep", V::Str(ENDPOINTS[self.endpoint])); - put!("stream", self.stream.into()); - put!("model", self.model.as_deref().into()); - put!("prof", self.profile.as_deref().into()); - put!("http", self.status.map(u64::from).into()); - put!("fin", V::Str(self.outcome)); - put!("ptok", self.prompt_tokens.into()); - put!("ctok", self.cached_tokens.into()); - put!("otok", self.output_tokens.into()); - put!("q_ms", self.queue_ms.into()); - put!("ttft_ms", self.ttft_ms.into()); - put!("pf_tps", self.prefill_tps.into()); - put!("dec_tps", self.decode_tps.into()); - put!("ms", V::UInt(self.total_ms)); - put!("restart", V::Bool(self.restart)); - put!("err", V::Str(self.error_class)); - put!("err_msg", self.error.as_deref().into()); - if let Some(h) = &self.hardware { - put!("gpu_mhz", h.sm_clock_mhz.into()); - put!("gpu_c", h.temp_c.into()); - put!("thr", h.throttle.into()); - put!("mem", h.gate.as_deref().into()); - put!("ram_free_mb", h.ram_available_mib.into()); - } - f - } - - fn publish(&self) { - REGISTRY.observe(self); - leleka_obs::record("api", "request", &self.fields()); - } -} - struct Registry { requests: Vec, errors: Vec, @@ -564,169 +179,15 @@ static REGISTRY: LazyLock = LazyLock::new(|| Registry { prefill_tps: Histogram::new(&[100.0, 500.0, 1000.0, 2000.0, 4000.0, 8000.0, 16000.0]), }); -impl Registry { - fn observe(&self, r: &Record) { - let outcome = OUTCOMES - .iter() - .position(|o| *o == r.outcome) - .unwrap_or(OUTCOMES.len() - 1); - self.requests[r.endpoint * OUTCOMES.len() + outcome].fetch_add(1, Ordering::Relaxed); - if r.error_class != "none" { - let class = ERROR_CLASSES - .iter() - .position(|c| *c == r.error_class) - .unwrap_or(ERROR_CLASSES.len() - 1); - self.errors[class].fetch_add(1, Ordering::Relaxed); - } - if r.restart { - self.restarts.fetch_add(1, Ordering::Relaxed); - } - self.duration.observe(r.total_ms as f64 / 1000.0); - if let Some(q) = r.queue_ms { - self.queue.observe(q as f64 / 1000.0); - } - if let Some(t) = r.ttft_ms { - self.ttft.observe(t as f64 / 1000.0); - } - if let Some(p) = r.prompt_tokens { - self.prompt_tokens.observe(p as f64); - } - if let Some(o) = r.output_tokens { - self.output_tokens.observe(o as f64); - } - if let Some(v) = r.decode_tps { - self.decode_tps.observe(v); - } - if let Some(v) = r.prefill_tps { - self.prefill_tps.observe(v); - } - } -} - -/// The worker lost the engine (a structured warning is logged; the count feeds `leleka_engine_lost_total`). -pub fn note_engine_lost(reason: &str) { - REGISTRY.engine_lost.fetch_add(1, Ordering::Relaxed); - leleka_obs::warn("api", "engine_lost", &[("reason", reason.into())]); -} - -/// The worker attached to a loaded engine (at start and after every restart). -pub fn note_engine_attached() { - let n = REGISTRY.engine_attached.fetch_add(1, Ordering::Relaxed) + 1; - leleka_obs::emit_always( - leleka_obs::Level::Info, - "api", - "engine_attached", - &[("attaches", n.into())], - ); -} - -/// Append the request metrics in the Prometheus text format. -pub fn render_prometheus(out: &mut String) { - let reg = &*REGISTRY; - leleka_obs::hist::header( - "leleka_requests_total", - "Generation requests by endpoint and how they ended.", - "counter", - out, - ); - let mut any = false; - for (e, endpoint) in ENDPOINTS.iter().enumerate() { - for (o, outcome) in OUTCOMES.iter().enumerate() { - let n = reg.requests[e * OUTCOMES.len() + o].load(Ordering::Relaxed); - if n > 0 { - any = true; - let _ = writeln!( - out, - "leleka_requests_total{{endpoint=\"{endpoint}\",outcome=\"{outcome}\"}} {n}" - ); - } - } - } - if !any { - let _ = writeln!( - out, - "leleka_requests_total{{endpoint=\"responses\",outcome=\"stop\"}} 0" - ); - } - leleka_obs::hist::header( - "leleka_request_errors_total", - "Failed or rejected requests by error class.", - "counter", - out, - ); - for (c, class) in ERROR_CLASSES.iter().enumerate().skip(1) { - let n = reg.errors[c].load(Ordering::Relaxed); - let _ = writeln!(out, "leleka_request_errors_total{{class=\"{class}\"}} {n}"); - } - leleka_obs::hist::header( - "leleka_engine_lost_total", - "Times the API lost the engine (it restarted, hung or stopped answering).", - "counter", - out, - ); - let _ = writeln!( - out, - "leleka_engine_lost_total {}", - reg.engine_lost.load(Ordering::Relaxed) - ); - leleka_obs::hist::header( - "leleka_engine_attached_total", - "Times the API attached to a loaded engine (the first start counts).", - "counter", - out, - ); - let _ = writeln!( - out, - "leleka_engine_attached_total {}", - reg.engine_attached.load(Ordering::Relaxed) - ); - leleka_obs::hist::header( - "leleka_requests_engine_restart_total", - "Requests during which the engine was lost.", - "counter", - out, - ); - let _ = writeln!( - out, - "leleka_requests_engine_restart_total {}", - reg.restarts.load(Ordering::Relaxed) - ); - reg.ttft.render( - "leleka_request_ttft_seconds", - "Time from arrival to the first generated token.", - out, - ); - reg.duration.render( - "leleka_request_duration_seconds", - "Time from arrival to the end of the request.", - out, - ); - reg.queue.render( - "leleka_request_queue_wait_seconds", - "Time a request waited before the engine took it.", - out, - ); - reg.prompt_tokens.render( - "leleka_request_prompt_tokens", - "Prompt tokens per request.", - out, - ); - reg.output_tokens.render( - "leleka_request_output_tokens", - "Output tokens per request.", - out, - ); - reg.decode_tps.render( - "leleka_request_decode_tokens_per_second", - "Decode rate per request.", - out, - ); - reg.prefill_tps.render( - "leleka_request_prefill_tokens_per_second", - "Prefill rate per request (uncached prompt tokens).", - out, - ); -} - #[cfg(test)] mod tests; + +mod endpoint_index; +#[allow(unused_imports)] +pub use endpoint_index::*; +mod impl_obshandle; +#[allow(unused_imports)] +pub use impl_obshandle::*; +mod note_engine_attached; +#[allow(unused_imports)] +pub use note_engine_attached::*; diff --git a/control-plane/src/request_log/endpoint_index.rs b/control-plane/src/request_log/endpoint_index.rs new file mode 100644 index 00000000..3102a976 --- /dev/null +++ b/control-plane/src/request_log/endpoint_index.rs @@ -0,0 +1,201 @@ +//! Moved out of the parent module by STRA-338: fn endpoint_index, fn session_tag, fn classify_error, fn class_of_status, impl ReqCtx, impl Drop_for_ReqCtx .... + +#[allow(unused_imports)] +use super::*; + +pub fn endpoint_index(path: &str) -> usize { + match path { + "/v1/responses" => 0, + "/v1/chat/completions" => 1, + "/v1/messages" => 2, + _ => 3, + } +} + +/// The session id of the log: a short digest of what the client sent, so lines of one conversation correlate and the +/// client's own identifier (which could be a user id) is not written down. +pub fn session_tag(headers: &HeaderMap) -> Option { + let raw = SESSION_HEADERS + .iter() + .find_map(|name| headers.get(*name)) + .and_then(|v| v.to_str().ok()) + .map(str::trim) + .filter(|v| !v.is_empty())?; + let digest = Sha256::digest(raw.as_bytes()); + Some(format!("s-{}", hex::encode(&digest[..5]))) +} + +/// A short error class and whether the message is our own wording (safe to log) rather than something that might echo input. +pub fn classify_error(message: &str) -> (&'static str, bool) { + let m = message; + if m.starts_with("engine made no progress") { + ("stall", true) + } else if m.contains("exceeded configured execution deadline") { + ("deadline", true) + } else if m.contains("memory_pressure") { + ("memory_pressure", true) + } else if m.starts_with("engine refused the generation") { + ("engine_refused", true) + } else if m.starts_with("engine stream ended") || m.contains("without a terminal event") { + ("stream_ended", true) + } else if m.starts_with("engine did not terminate the generation") { + ("cancel_timeout", true) + } else if m.contains("worker is restarting") + || m.contains("not attached to the engine") + || m.contains("runtime restarted") + || m.contains("stopped before completing") + { + ("engine_lost", true) + } else { + ("other", false) + } +} + +/// The class of a rejection by HTTP status (a request that never reached the engine). +pub fn class_of_status(status: u16) -> &'static str { + match status { + 400 | 404 | 405 | 413 | 415 | 422 => "bad_request", + 429 => "overloaded", + 503 => "unavailable", + _ => "other", + } +} + +impl ReqCtx { + pub fn new( + id: String, + endpoint: usize, + sid: Option, + model: Option, + memory: Option>, + ) -> Self { + Self { + state: Mutex::new(Live { + id, + sid, + endpoint, + stream: None, + model, + profile: std::env::var("LELEKA_PROFILE") + .ok() + .filter(|p| !p.is_empty()), + admitted: Instant::now(), + engine_start: None, + first_token: None, + done: None, + error: None, + http_status: None, + restart: false, + emitted: false, + memory, + }), + } + } + + pub(super) fn with(&self, f: impl FnOnce(&mut Live) -> T) -> Option { + self.state.lock().ok().map(|mut s| f(&mut s)) + } + + pub fn id(&self) -> String { + self.with(|s| s.id.clone()).unwrap_or_default() + } + + pub fn set_stream(&self, stream: bool) { + self.with(|s| s.stream = Some(stream)); + } + + pub fn set_http_status(&self, status: u16) { + self.with(|s| s.http_status = Some(status)); + } + + /// The worker handed the request to the engine: the queue wait ends. + pub fn engine_start(&self) { + self.with(|s| { + s.engine_start.get_or_insert_with(Instant::now); + }); + } + + pub fn first_token(&self) { + self.with(|s| { + s.first_token.get_or_insert_with(Instant::now); + }); + } + + pub fn done(&self, done: &Done, disconnected: bool) { + self.with(|s| { + s.done = Some(DoneInfo { + prompt_tokens: done.prompt_tokens, + cached_tokens: done.reused.unwrap_or(0), + output_tokens: done.generated, + decode_ms: done.decode_ms, + finish: match done.finish { + Finish::Stop => "stop", + Finish::Length => "length", + Finish::Cancel => "cancel", + }, + disconnected, + }); + }); + } + + pub fn error(&self, message: &str) { + let (class, ours) = classify_error(message); + let shown = if ours { + leleka_obs::redact::clip(message, 160).to_owned() + } else { + format!("{} bytes", message.len()) + }; + self.with(|s| { + if s.error.is_none() { + s.error = Some((class, shown)); + } + }); + } + + /// The engine was lost while this request was in flight. + pub fn engine_restarted(&self) { + self.with(|s| s.restart = true); + } + + /// Write the record now (once). + pub fn finalize(&self) { + let record = self.with(|s| { + if s.emitted { + return None; + } + s.emitted = true; + Some(Record::from_state(s)) + }); + if let Some(Some(record)) = record { + record.publish(); + } + } +} + +impl Drop for ReqCtx { + fn drop(&mut self) { + let record = match self.state.get_mut() { + Ok(state) if !state.emitted => { + state.emitted = true; + Some(Record::from_state(state)) + } + _ => None, + }; + if let Some(record) = record { + record.publish(); + } + } +} + +impl std::fmt::Debug for ObsHandle { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.write_str("ObsHandle") + } +} + +impl PartialEq for ObsHandle { + /// Never part of a request's identity. + fn eq(&self, _: &Self) -> bool { + true + } +} diff --git a/control-plane/src/request_log/impl_obshandle.rs b/control-plane/src/request_log/impl_obshandle.rs new file mode 100644 index 00000000..d8db903d --- /dev/null +++ b/control-plane/src/request_log/impl_obshandle.rs @@ -0,0 +1,237 @@ +//! Moved out of the parent module by STRA-338: impl ObsHandle, fn observe, fn round1, impl Record, impl Registry, fn note_engine_lost. + +#[allow(unused_imports)] +use super::*; + +impl ObsHandle { + /// The request being served by the current task, if the `observe` middleware wrapped it. + pub fn current() -> Self { + Self(CURRENT.try_with(Arc::clone).ok()) + } + + pub fn id(&self) -> Option { + self.0.as_ref().map(|c| c.id()) + } + pub fn set_stream(&self, stream: bool) { + if let Some(c) = &self.0 { + c.set_stream(stream); + } + } + pub fn engine_start(&self) { + if let Some(c) = &self.0 { + c.engine_start(); + } + } + pub fn first_token(&self) { + if let Some(c) = &self.0 { + c.first_token(); + } + } + pub fn done(&self, done: &Done, disconnected: bool) { + if let Some(c) = &self.0 { + c.done(done, disconnected); + } + } + pub fn error(&self, message: &str) { + if let Some(c) = &self.0 { + c.error(message); + } + } + pub fn engine_restarted(&self) { + if let Some(c) = &self.0 { + c.engine_restarted(); + } + } + pub fn finalize(&self) { + if let Some(c) = &self.0 { + c.finalize(); + } + } +} + +/// Outermost layer of the three generation routes: gives the request an id (and a response header carrying it), reads the +/// session header, and keeps the record for the handler. A rejection (status 4xx/5xx before the engine) is recorded here. +pub async fn observe(State(observe): State, request: Request, next: Next) -> Response { + let endpoint = endpoint_index(request.uri().path()); + let ctx = Arc::new(ReqCtx::new( + uuid::Uuid::new_v4().to_string(), + endpoint, + session_tag(request.headers()), + observe.model.clone(), + Some(observe.memory.clone()), + )); + let id = ctx.id(); + let mut response = CURRENT.scope(ctx.clone(), next.run(request)).await; + ctx.set_http_status(response.status().as_u16()); + if let Ok(value) = HeaderValue::from_str(&id) { + response.headers_mut().insert(REQUEST_ID_HEADER, value); + } + response +} + +pub(super) fn round1(v: f64) -> f64 { + (v * 10.0).round() / 10.0 +} + +impl Record { + pub(super) fn from_state(s: &Live) -> Record { + let now = Instant::now(); + let ms = |from: Instant, to: Instant| { + u64::try_from(to.saturating_duration_since(from).as_millis()).unwrap_or(u64::MAX) + }; + let queue_ms = s.engine_start.map(|t| ms(s.admitted, t)); + let ttft_ms = s.first_token.map(|t| ms(s.admitted, t)); + let (prompt_tokens, cached_tokens, output_tokens) = match &s.done { + Some(d) => ( + Some(d.prompt_tokens), + Some(d.cached_tokens), + Some(d.output_tokens), + ), + None => (None, None, None), + }; + let prefill_tps = match (&s.done, s.engine_start, s.first_token) { + (Some(d), Some(start), Some(first)) => { + let fresh = d.prompt_tokens.saturating_sub(d.cached_tokens); + let secs = first.saturating_duration_since(start).as_secs_f64(); + (fresh > 0 && secs > 0.0).then(|| round1(fresh as f64 / secs)) + } + _ => None, + }; + let decode_tps = s + .done + .as_ref() + .and_then(|d| { + (d.output_tokens > 1) + .then(|| crate::metrics::token_rate(d.output_tokens, d.decode_ms)) + .flatten() + }) + .map(round1); + let http_failed = s.http_status.is_some_and(|c| c >= 400); + let outcome = match (&s.done, &s.error) { + (Some(d), _) if d.disconnected => "disconnect", + (Some(d), _) => d.finish, + (None, Some(_)) if s.engine_start.is_some() => "error", + (None, Some(_)) => "rejected", + (None, None) if http_failed => "rejected", + (None, None) => "abandoned", + }; + let (error_class, error) = match (&s.error, http_failed, outcome) { + (Some((class, text)), _, _) => (*class, Some(text.clone())), + (None, true, _) => (class_of_status(s.http_status.unwrap_or(0)), None), + _ => ("none", None), + }; + Record { + id: s.id.clone(), + sid: s.sid.clone(), + endpoint: s.endpoint, + stream: s.stream, + model: s.model.clone(), + profile: s.profile.clone(), + status: s.http_status, + outcome, + prompt_tokens, + cached_tokens, + output_tokens, + queue_ms, + ttft_ms, + prefill_tps, + decode_tps, + total_ms: ms(s.admitted, now), + restart: s.restart, + error_class, + error, + hardware: s.memory.as_ref().and_then(|m| m.brief()), + } + } + + /// The fields of the line, in order. A figure that was not measured is left out (a missing key means unknown), which + /// also keeps the line short. + pub fn fields(&self) -> Vec> { + let mut f: Vec> = Vec::with_capacity(28); + macro_rules! put { + ($key:expr, $value:expr) => {{ + let value: V<'_> = $value; + if !matches!(value, V::Null) { + f.push(($key, value)); + } + }}; + } + put!("rid", V::Str(&self.id)); + put!("sid", self.sid.as_deref().into()); + put!("ep", V::Str(ENDPOINTS[self.endpoint])); + put!("stream", self.stream.into()); + put!("model", self.model.as_deref().into()); + put!("prof", self.profile.as_deref().into()); + put!("http", self.status.map(u64::from).into()); + put!("fin", V::Str(self.outcome)); + put!("ptok", self.prompt_tokens.into()); + put!("ctok", self.cached_tokens.into()); + put!("otok", self.output_tokens.into()); + put!("q_ms", self.queue_ms.into()); + put!("ttft_ms", self.ttft_ms.into()); + put!("pf_tps", self.prefill_tps.into()); + put!("dec_tps", self.decode_tps.into()); + put!("ms", V::UInt(self.total_ms)); + put!("restart", V::Bool(self.restart)); + put!("err", V::Str(self.error_class)); + put!("err_msg", self.error.as_deref().into()); + if let Some(h) = &self.hardware { + put!("gpu_mhz", h.sm_clock_mhz.into()); + put!("gpu_c", h.temp_c.into()); + put!("thr", h.throttle.into()); + put!("mem", h.gate.as_deref().into()); + put!("ram_free_mb", h.ram_available_mib.into()); + } + f + } + + pub(super) fn publish(&self) { + REGISTRY.observe(self); + leleka_obs::record("api", "request", &self.fields()); + } +} + +impl Registry { + pub(super) fn observe(&self, r: &Record) { + let outcome = OUTCOMES + .iter() + .position(|o| *o == r.outcome) + .unwrap_or(OUTCOMES.len() - 1); + self.requests[r.endpoint * OUTCOMES.len() + outcome].fetch_add(1, Ordering::Relaxed); + if r.error_class != "none" { + let class = ERROR_CLASSES + .iter() + .position(|c| *c == r.error_class) + .unwrap_or(ERROR_CLASSES.len() - 1); + self.errors[class].fetch_add(1, Ordering::Relaxed); + } + if r.restart { + self.restarts.fetch_add(1, Ordering::Relaxed); + } + self.duration.observe(r.total_ms as f64 / 1000.0); + if let Some(q) = r.queue_ms { + self.queue.observe(q as f64 / 1000.0); + } + if let Some(t) = r.ttft_ms { + self.ttft.observe(t as f64 / 1000.0); + } + if let Some(p) = r.prompt_tokens { + self.prompt_tokens.observe(p as f64); + } + if let Some(o) = r.output_tokens { + self.output_tokens.observe(o as f64); + } + if let Some(v) = r.decode_tps { + self.decode_tps.observe(v); + } + if let Some(v) = r.prefill_tps { + self.prefill_tps.observe(v); + } + } +} + +/// The worker lost the engine (a structured warning is logged; the count feeds `leleka_engine_lost_total`). +pub fn note_engine_lost(reason: &str) { + REGISTRY.engine_lost.fetch_add(1, Ordering::Relaxed); + leleka_obs::warn("api", "engine_lost", &[("reason", reason.into())]); +} diff --git a/control-plane/src/request_log/note_engine_attached.rs b/control-plane/src/request_log/note_engine_attached.rs new file mode 100644 index 00000000..314e76fa --- /dev/null +++ b/control-plane/src/request_log/note_engine_attached.rs @@ -0,0 +1,123 @@ +//! Moved out of the parent module by STRA-338: fn note_engine_attached, fn render_prometheus. + +#[allow(unused_imports)] +use super::*; + +/// The worker attached to a loaded engine (at start and after every restart). +pub fn note_engine_attached() { + let n = REGISTRY.engine_attached.fetch_add(1, Ordering::Relaxed) + 1; + leleka_obs::emit_always( + leleka_obs::Level::Info, + "api", + "engine_attached", + &[("attaches", n.into())], + ); +} + +/// Append the request metrics in the Prometheus text format. +pub fn render_prometheus(out: &mut String) { + let reg = &*REGISTRY; + leleka_obs::hist::header( + "leleka_requests_total", + "Generation requests by endpoint and how they ended.", + "counter", + out, + ); + let mut any = false; + for (e, endpoint) in ENDPOINTS.iter().enumerate() { + for (o, outcome) in OUTCOMES.iter().enumerate() { + let n = reg.requests[e * OUTCOMES.len() + o].load(Ordering::Relaxed); + if n > 0 { + any = true; + let _ = writeln!( + out, + "leleka_requests_total{{endpoint=\"{endpoint}\",outcome=\"{outcome}\"}} {n}" + ); + } + } + } + if !any { + let _ = writeln!( + out, + "leleka_requests_total{{endpoint=\"responses\",outcome=\"stop\"}} 0" + ); + } + leleka_obs::hist::header( + "leleka_request_errors_total", + "Failed or rejected requests by error class.", + "counter", + out, + ); + for (c, class) in ERROR_CLASSES.iter().enumerate().skip(1) { + let n = reg.errors[c].load(Ordering::Relaxed); + let _ = writeln!(out, "leleka_request_errors_total{{class=\"{class}\"}} {n}"); + } + leleka_obs::hist::header( + "leleka_engine_lost_total", + "Times the API lost the engine (it restarted, hung or stopped answering).", + "counter", + out, + ); + let _ = writeln!( + out, + "leleka_engine_lost_total {}", + reg.engine_lost.load(Ordering::Relaxed) + ); + leleka_obs::hist::header( + "leleka_engine_attached_total", + "Times the API attached to a loaded engine (the first start counts).", + "counter", + out, + ); + let _ = writeln!( + out, + "leleka_engine_attached_total {}", + reg.engine_attached.load(Ordering::Relaxed) + ); + leleka_obs::hist::header( + "leleka_requests_engine_restart_total", + "Requests during which the engine was lost.", + "counter", + out, + ); + let _ = writeln!( + out, + "leleka_requests_engine_restart_total {}", + reg.restarts.load(Ordering::Relaxed) + ); + reg.ttft.render( + "leleka_request_ttft_seconds", + "Time from arrival to the first generated token.", + out, + ); + reg.duration.render( + "leleka_request_duration_seconds", + "Time from arrival to the end of the request.", + out, + ); + reg.queue.render( + "leleka_request_queue_wait_seconds", + "Time a request waited before the engine took it.", + out, + ); + reg.prompt_tokens.render( + "leleka_request_prompt_tokens", + "Prompt tokens per request.", + out, + ); + reg.output_tokens.render( + "leleka_request_output_tokens", + "Output tokens per request.", + out, + ); + reg.decode_tps.render( + "leleka_request_decode_tokens_per_second", + "Decode rate per request.", + out, + ); + reg.prefill_tps.render( + "leleka_request_prefill_tokens_per_second", + "Prefill rate per request (uncached prompt tokens).", + out, + ); +} diff --git a/control-plane/src/request_monitor.rs b/control-plane/src/request_monitor.rs index 02cd259f..dc75f008 100644 --- a/control-plane/src/request_monitor.rs +++ b/control-plane/src/request_monitor.rs @@ -71,265 +71,6 @@ struct Record { clock: Instant, } -fn now_unix() -> f64 { - SystemTime::now() - .duration_since(UNIX_EPOCH) - .map_or(0.0, |d| d.as_secs_f64()) -} - -fn seconds(since: Instant) -> f64 { - (since.elapsed().as_secs_f64() * 1000.0).round() / 1000.0 -} - -/// Append `add` to `target` without exceeding [`CAP`] bytes (cut at a character boundary); true when something was left out. -fn append_clipped(target: &mut String, flag: &mut bool, add: &str) { - let room = CAP.saturating_sub(target.len()); - if add.len() <= room { - target.push_str(add); - return; - } - let mut end = room; - while end > 0 && !add.is_char_boundary(end) { - end -= 1; - } - target.push_str(&add[..end]); - *flag = true; -} - -fn clipped(text: &str) -> (String, bool) { - let mut out = String::new(); - let mut flag = false; - append_clipped(&mut out, &mut flag, text); - (out, flag) -} - -impl Record { - fn first_text(&mut self) { - if self.first_token_s.is_none() { - self.first_token_s = Some(seconds(self.clock)); - self.state = "generating"; - } - } - - fn add_output(&mut self, text: Option<&str>) { - if let Some(text) = text.filter(|t| !t.is_empty()) { - self.first_text(); - append_clipped(&mut self.output, &mut self.output_truncated, text); - } - } - - fn add_reasoning(&mut self, text: Option<&str>) { - if let Some(text) = text.filter(|t| !t.is_empty()) { - self.first_text(); - append_clipped(&mut self.reasoning, &mut self.reasoning_truncated, text); - } - } - - /// One server-sent event (`data:` payload) of any of the three dialects. - fn absorb_event(&mut self, event: &Value) { - if let Some(choices) = event.get("choices").and_then(Value::as_array) { - if let Some(delta) = choices.first().and_then(|choice| choice.get("delta")) { - self.add_output(delta.get("content").and_then(Value::as_str)); - self.add_reasoning( - delta - .get("reasoning_content") - .or_else(|| delta.get("reasoning")) - .and_then(Value::as_str), - ); - } - if let Some(usage) = event.get("usage").filter(|u| u.is_object()) { - self.usage = Some(usage.clone()); - } - return; - } - match event.get("type").and_then(Value::as_str) { - Some("content_block_delta") => { - let delta = &event["delta"]; - self.add_output(delta.get("text").and_then(Value::as_str)); - self.add_reasoning(delta.get("thinking").and_then(Value::as_str)); - } - Some("message_start") => { - if let Some(usage) = event.pointer("/message/usage").filter(|u| u.is_object()) { - self.usage = Some(usage.clone()); - } - } - Some("message_delta") => { - if let Some(update) = event.get("usage").and_then(Value::as_object) { - let mut merged = self - .usage - .as_ref() - .and_then(Value::as_object) - .cloned() - .unwrap_or_default(); - merged.extend(update.clone()); - self.usage = Some(Value::Object(merged)); - } - } - Some("response.output_text.delta") => { - self.add_output(event.get("delta").and_then(Value::as_str)) - } - Some("response.reasoning_text.delta" | "response.reasoning_summary_text.delta") => { - self.add_reasoning(event.get("delta").and_then(Value::as_str)); - } - Some("response.completed" | "response.incomplete") => { - if let Some(usage) = event.pointer("/response/usage").filter(|u| u.is_object()) { - self.usage = Some(usage.clone()); - } - } - Some("response.failed") => { - self.error = Some( - event - .pointer("/response/error") - .cloned() - .unwrap_or_else(|| event.clone()), - ); - } - Some("error") => { - self.error = Some(event.get("error").cloned().unwrap_or_else(|| event.clone())) - } - _ => {} - } - } - - /// A response that was sent whole (any dialect). - fn absorb_response(&mut self, body: &Value) { - if let Some(error) = body.get("error").filter(|e| !e.is_null()) { - self.error = Some(error.clone()); - } - if let Some(usage) = body.get("usage").filter(|u| u.is_object()) { - self.usage = Some(usage.clone()); - } - // Chat Completions - if let Some(message) = body.pointer("/choices/0/message") { - self.add_output(message.get("content").and_then(Value::as_str)); - self.add_reasoning( - message - .get("reasoning_content") - .or_else(|| message.get("reasoning")) - .and_then(Value::as_str), - ); - } - // Messages - if let Some(blocks) = body.get("content").and_then(Value::as_array) { - for block in blocks { - match block.get("type").and_then(Value::as_str) { - Some("text") => self.add_output(block.get("text").and_then(Value::as_str)), - Some("thinking") => { - self.add_reasoning(block.get("thinking").and_then(Value::as_str)) - } - _ => {} - } - } - } - // Responses - if let Some(items) = body.get("output").and_then(Value::as_array) { - for item in items { - let parts = item - .get("content") - .and_then(Value::as_array) - .into_iter() - .flatten(); - match item.get("type").and_then(Value::as_str) { - Some("message") => { - for part in parts { - if part.get("type").and_then(Value::as_str) == Some("output_text") { - self.add_output(part.get("text").and_then(Value::as_str)); - } - } - } - Some("reasoning") => { - for part in parts.chain( - item.get("summary") - .and_then(Value::as_array) - .into_iter() - .flatten(), - ) { - self.add_reasoning(part.get("text").and_then(Value::as_str)); - } - } - _ => {} - } - } - } - if let Ok(pretty) = serde_json::to_string_pretty(body) { - let (text, truncated) = clipped(&pretty); - self.response = Some(text); - self.response_truncated = truncated; - } - } - - fn settle(&mut self, outcome: Option<&'static str>) { - if self.finished_at.is_some() { - return; - } - self.wallclock_s = Some(seconds(self.clock)); - self.finished_at = Some(now_unix()); - if let Some(outcome) = outcome { - self.outcome = Some(outcome); - } - let failed = self.error.is_some() || self.http_status.is_some_and(|status| status >= 400); - self.state = if failed { - "error" - } else if self.outcome == Some("disconnected") { - "disconnected" - } else { - "completed" - }; - } - - /// The summary row (no prompts or answers) or the whole record. - fn render(&self, detail: bool) -> Value { - let mut out = Map::new(); - let mut put = |key: &str, value: Value| { - out.insert(key.to_owned(), value); - }; - put("id", json!(self.id)); - put("path", json!(self.path)); - put("model", self.model.clone()); - put("started_at", json!(self.started_at)); - put("state", json!(self.state)); - put("stream", json!(self.stream)); - put("response_format", self.response_format.clone()); - put("input_truncated", json!(self.input_truncated)); - put("output_truncated", json!(self.output_truncated)); - put("reasoning_truncated", json!(self.reasoning_truncated)); - put("queue_s", Value::Null); - put("load_s", Value::Null); - put("first_token_s", json!(self.first_token_s)); - put( - "wallclock_s", - json!(self.wallclock_s.unwrap_or_else(|| seconds(self.clock))), - ); - if let Some(status) = self.http_status { - put("http_status", json!(status)); - } - if let Some(at) = self.finished_at { - put("finished_at", json!(at)); - } - if let Some(outcome) = self.outcome { - put("outcome", json!(outcome)); - } - if let Some(usage) = &self.usage { - put("usage", usage.clone()); - } - if let Some(error) = &self.error { - put("error", error.clone()); - } - if self.response.is_some() { - put("response_truncated", json!(self.response_truncated)); - } - if detail { - put("input", json!(self.input)); - put("output", json!(self.output)); - put("reasoning", json!(self.reasoning)); - if let Some(response) = &self.response { - put("response", json!(response)); - } - } - Value::Object(out) - } -} - type Shared = Arc>; /// The monitor: disabled (nothing is kept) or a bounded list of request records. @@ -339,96 +80,6 @@ pub struct RequestMonitor { records: Mutex>, } -impl RequestMonitor { - pub fn new(enabled: bool) -> Self { - Self { - enabled, - records: Mutex::new(VecDeque::new()), - } - } - - pub fn enabled(&self) -> bool { - self.enabled - } - - fn begin(&self, path: &str, body: &[u8]) -> Shared { - let request: Value = serde_json::from_slice(body).unwrap_or(Value::Null); - let raw = if request.is_null() { - String::from_utf8_lossy(body).into_owned() - } else { - serde_json::to_string_pretty(&request).unwrap_or_default() - }; - let (input, input_truncated) = clipped(&raw); - let record = Arc::new(Mutex::new(Record { - id: uuid::Uuid::new_v4().simple().to_string()[..12].to_owned(), - path: path.to_owned(), - model: request - .get("model") - .filter(|m| m.is_string()) - .cloned() - .unwrap_or(Value::Null), - started_at: now_unix(), - state: "queued", - outcome: None, - stream: request.get("stream") == Some(&json!(true)), - response_format: request - .get("response_format") - .and_then(|f| f.get("type")) - .or_else(|| request.pointer("/text/format/type")) - .cloned() - .unwrap_or(Value::Null), - input, - input_truncated, - output: String::new(), - output_truncated: false, - reasoning: String::new(), - reasoning_truncated: false, - first_token_s: None, - usage: None, - error: None, - http_status: None, - response: None, - response_truncated: false, - wallclock_s: None, - finished_at: None, - clock: Instant::now(), - })); - if let Ok(mut records) = self.records.lock() { - if records.len() == RETENTION { - records.pop_front(); - } - records.push_back(record.clone()); - } - record - } - - /// Newest first, without prompts and answers. - pub fn summaries(&self) -> Vec { - let records: Vec = self - .records - .lock() - .map(|r| r.iter().rev().cloned().collect()) - .unwrap_or_default(); - records - .iter() - .filter_map(|record| record.lock().ok().map(|r| r.render(false))) - .collect() - } - - /// One whole record, `None` once it was evicted (or never existed). - pub fn detail(&self, id: &str) -> Option { - let record = self - .records - .lock() - .ok()? - .iter() - .find(|r| r.lock().is_ok_and(|r| r.id == id))? - .clone(); - let rendered = record.lock().ok()?.render(true); - Some(rendered) - } -} - /// An event stream passed through unchanged while its events are read into the record. struct Tap { inner: axum::body::BodyDataStream, @@ -437,138 +88,15 @@ struct Tap { done: bool, } -impl Tap { - fn absorb(&mut self, chunk: &[u8]) { - self.pending.extend_from_slice(chunk); - let Ok(mut record) = self.record.lock() else { - return; - }; - while let Some(newline) = self.pending.iter().position(|b| *b == b'\n') { - let line: Vec = self.pending.drain(..=newline).collect(); - let line = String::from_utf8_lossy(&line); - let Some(data) = line.trim_end_matches(['\r', '\n']).strip_prefix("data:") else { - continue; - }; - let data = data.trim(); - if data.is_empty() || data == "[DONE]" || data.len() > LINE_LIMIT { - continue; - } - if let Ok(event) = serde_json::from_str::(data) { - record.absorb_event(&event); - } - } - if self.pending.len() > LINE_LIMIT { - self.pending.clear(); - } - } - - fn settle(&mut self, outcome: Option<&'static str>) { - self.done = true; - if let Ok(mut record) = self.record.lock() { - record.settle(outcome); - } - } -} - -impl Stream for Tap { - type Item = Result; - - fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { - match Pin::new(&mut self.inner).poll_next(cx) { - Poll::Ready(Some(Ok(chunk))) => { - self.absorb(&chunk); - Poll::Ready(Some(Ok(chunk))) - } - Poll::Ready(Some(Err(error))) => { - self.settle(Some("disconnected")); - Poll::Ready(Some(Err(error))) - } - Poll::Ready(None) => { - self.settle(None); - Poll::Ready(None) - } - Poll::Pending => Poll::Pending, - } - } -} - -impl Drop for Tap { - fn drop(&mut self) { - if !self.done { - // the consumer went away before the stream ended - self.settle(Some("disconnected")); - } - } -} - -fn too_large() -> Response { - let body = - json!({"error": {"message": "request body too large", "type": "invalid_request_error"}}); - (StatusCode::PAYLOAD_TOO_LARGE, axum::Json(body)).into_response() -} - -/// Middleware for the generation routes: record the request and its answer when the monitor is on; a no-op otherwise. -pub async fn capture( - State(monitor): State>, - request: Request, - next: Next, -) -> Response { - if !monitor.enabled { - return next.run(request).await; - } - let path = request.uri().path().to_owned(); - let (parts, body) = request.into_parts(); - let Ok(bytes) = axum::body::to_bytes(body, BODY_LIMIT).await else { - return too_large(); - }; - let record = monitor.begin(&path, &bytes); - let response = next - .run(Request::from_parts(parts, Body::from(bytes))) - .await; - let (mut parts, body) = response.into_parts(); - if let Ok(mut r) = record.lock() { - r.http_status = Some(parts.status.as_u16()); - } - let streaming = parts - .headers - .get(header::CONTENT_TYPE) - .and_then(|v| v.to_str().ok()) - .is_some_and(|v| v.starts_with("text/event-stream")); - if streaming { - let tap = Tap { - inner: body.into_data_stream(), - record, - pending: Vec::new(), - done: false, - }; - return Response::from_parts(parts, Body::from_stream(tap)); - } - match axum::body::to_bytes(body, RESPONSE_LIMIT).await { - Ok(bytes) => { - if let Ok(mut r) = record.lock() { - if let Ok(value) = serde_json::from_slice::(&bytes) { - r.absorb_response(&value); - } - r.settle(None); - } - if let Ok(length) = HeaderValue::from_str(&bytes.len().to_string()) { - parts.headers.insert(header::CONTENT_LENGTH, length); - } - Response::from_parts(parts, Body::from(bytes)) - } - Err(error) => { - if let Ok(mut r) = record.lock() { - r.settle(Some("disconnected")); - } - crate::elog!("request monitor: could not read a response body: {error}"); - ( - StatusCode::INTERNAL_SERVER_ERROR, - "response body unavailable", - ) - .into_response() - } - } -} - #[cfg(test)] mod tests; + +mod now_unix; +#[allow(unused_imports)] +pub use now_unix::*; +mod impl_record; +#[allow(unused_imports)] +pub use impl_record::*; +mod impl_requestmonitor; +#[allow(unused_imports)] +pub use impl_requestmonitor::*; diff --git a/control-plane/src/request_monitor/impl_record.rs b/control-plane/src/request_monitor/impl_record.rs new file mode 100644 index 00000000..e281afea --- /dev/null +++ b/control-plane/src/request_monitor/impl_record.rs @@ -0,0 +1,231 @@ +//! Moved out of the parent module by STRA-338: impl Record. + +#[allow(unused_imports)] +use super::*; + +impl Record { + pub(super) fn first_text(&mut self) { + if self.first_token_s.is_none() { + self.first_token_s = Some(seconds(self.clock)); + self.state = "generating"; + } + } + + pub(super) fn add_output(&mut self, text: Option<&str>) { + if let Some(text) = text.filter(|t| !t.is_empty()) { + self.first_text(); + append_clipped(&mut self.output, &mut self.output_truncated, text); + } + } + + pub(super) fn add_reasoning(&mut self, text: Option<&str>) { + if let Some(text) = text.filter(|t| !t.is_empty()) { + self.first_text(); + append_clipped(&mut self.reasoning, &mut self.reasoning_truncated, text); + } + } + + /// One server-sent event (`data:` payload) of any of the three dialects. + pub(super) fn absorb_event(&mut self, event: &Value) { + if let Some(choices) = event.get("choices").and_then(Value::as_array) { + if let Some(delta) = choices.first().and_then(|choice| choice.get("delta")) { + self.add_output(delta.get("content").and_then(Value::as_str)); + self.add_reasoning( + delta + .get("reasoning_content") + .or_else(|| delta.get("reasoning")) + .and_then(Value::as_str), + ); + } + if let Some(usage) = event.get("usage").filter(|u| u.is_object()) { + self.usage = Some(usage.clone()); + } + return; + } + match event.get("type").and_then(Value::as_str) { + Some("content_block_delta") => { + let delta = &event["delta"]; + self.add_output(delta.get("text").and_then(Value::as_str)); + self.add_reasoning(delta.get("thinking").and_then(Value::as_str)); + } + Some("message_start") => { + if let Some(usage) = event.pointer("/message/usage").filter(|u| u.is_object()) { + self.usage = Some(usage.clone()); + } + } + Some("message_delta") => { + if let Some(update) = event.get("usage").and_then(Value::as_object) { + let mut merged = self + .usage + .as_ref() + .and_then(Value::as_object) + .cloned() + .unwrap_or_default(); + merged.extend(update.clone()); + self.usage = Some(Value::Object(merged)); + } + } + Some("response.output_text.delta") => { + self.add_output(event.get("delta").and_then(Value::as_str)) + } + Some("response.reasoning_text.delta" | "response.reasoning_summary_text.delta") => { + self.add_reasoning(event.get("delta").and_then(Value::as_str)); + } + Some("response.completed" | "response.incomplete") => { + if let Some(usage) = event.pointer("/response/usage").filter(|u| u.is_object()) { + self.usage = Some(usage.clone()); + } + } + Some("response.failed") => { + self.error = Some( + event + .pointer("/response/error") + .cloned() + .unwrap_or_else(|| event.clone()), + ); + } + Some("error") => { + self.error = Some(event.get("error").cloned().unwrap_or_else(|| event.clone())) + } + _ => {} + } + } + + /// A response that was sent whole (any dialect). + pub(super) fn absorb_response(&mut self, body: &Value) { + if let Some(error) = body.get("error").filter(|e| !e.is_null()) { + self.error = Some(error.clone()); + } + if let Some(usage) = body.get("usage").filter(|u| u.is_object()) { + self.usage = Some(usage.clone()); + } + // Chat Completions + if let Some(message) = body.pointer("/choices/0/message") { + self.add_output(message.get("content").and_then(Value::as_str)); + self.add_reasoning( + message + .get("reasoning_content") + .or_else(|| message.get("reasoning")) + .and_then(Value::as_str), + ); + } + // Messages + if let Some(blocks) = body.get("content").and_then(Value::as_array) { + for block in blocks { + match block.get("type").and_then(Value::as_str) { + Some("text") => self.add_output(block.get("text").and_then(Value::as_str)), + Some("thinking") => { + self.add_reasoning(block.get("thinking").and_then(Value::as_str)) + } + _ => {} + } + } + } + // Responses + if let Some(items) = body.get("output").and_then(Value::as_array) { + for item in items { + let parts = item + .get("content") + .and_then(Value::as_array) + .into_iter() + .flatten(); + match item.get("type").and_then(Value::as_str) { + Some("message") => { + for part in parts { + if part.get("type").and_then(Value::as_str) == Some("output_text") { + self.add_output(part.get("text").and_then(Value::as_str)); + } + } + } + Some("reasoning") => { + for part in parts.chain( + item.get("summary") + .and_then(Value::as_array) + .into_iter() + .flatten(), + ) { + self.add_reasoning(part.get("text").and_then(Value::as_str)); + } + } + _ => {} + } + } + } + if let Ok(pretty) = serde_json::to_string_pretty(body) { + let (text, truncated) = clipped(&pretty); + self.response = Some(text); + self.response_truncated = truncated; + } + } + + pub(super) fn settle(&mut self, outcome: Option<&'static str>) { + if self.finished_at.is_some() { + return; + } + self.wallclock_s = Some(seconds(self.clock)); + self.finished_at = Some(now_unix()); + if let Some(outcome) = outcome { + self.outcome = Some(outcome); + } + let failed = self.error.is_some() || self.http_status.is_some_and(|status| status >= 400); + self.state = if failed { + "error" + } else if self.outcome == Some("disconnected") { + "disconnected" + } else { + "completed" + }; + } + + /// The summary row (no prompts or answers) or the whole record. + pub(super) fn render(&self, detail: bool) -> Value { + let mut out = Map::new(); + let mut put = |key: &str, value: Value| { + out.insert(key.to_owned(), value); + }; + put("id", json!(self.id)); + put("path", json!(self.path)); + put("model", self.model.clone()); + put("started_at", json!(self.started_at)); + put("state", json!(self.state)); + put("stream", json!(self.stream)); + put("response_format", self.response_format.clone()); + put("input_truncated", json!(self.input_truncated)); + put("output_truncated", json!(self.output_truncated)); + put("reasoning_truncated", json!(self.reasoning_truncated)); + put("queue_s", Value::Null); + put("load_s", Value::Null); + put("first_token_s", json!(self.first_token_s)); + put( + "wallclock_s", + json!(self.wallclock_s.unwrap_or_else(|| seconds(self.clock))), + ); + if let Some(status) = self.http_status { + put("http_status", json!(status)); + } + if let Some(at) = self.finished_at { + put("finished_at", json!(at)); + } + if let Some(outcome) = self.outcome { + put("outcome", json!(outcome)); + } + if let Some(usage) = &self.usage { + put("usage", usage.clone()); + } + if let Some(error) = &self.error { + put("error", error.clone()); + } + if self.response.is_some() { + put("response_truncated", json!(self.response_truncated)); + } + if detail { + put("input", json!(self.input)); + put("output", json!(self.output)); + put("reasoning", json!(self.reasoning)); + if let Some(response) = &self.response { + put("response", json!(response)); + } + } + Value::Object(out) + } +} diff --git a/control-plane/src/request_monitor/impl_requestmonitor.rs b/control-plane/src/request_monitor/impl_requestmonitor.rs new file mode 100644 index 00000000..118083a1 --- /dev/null +++ b/control-plane/src/request_monitor/impl_requestmonitor.rs @@ -0,0 +1,227 @@ +//! Moved out of the parent module by STRA-338: impl RequestMonitor, impl Tap, impl Stream_for_Tap, impl Drop_for_Tap, fn too_large, fn capture. + +#[allow(unused_imports)] +use super::*; + +impl RequestMonitor { + pub fn new(enabled: bool) -> Self { + Self { + enabled, + records: Mutex::new(VecDeque::new()), + } + } + + pub fn enabled(&self) -> bool { + self.enabled + } + + pub(super) fn begin(&self, path: &str, body: &[u8]) -> Shared { + let request: Value = serde_json::from_slice(body).unwrap_or(Value::Null); + let raw = if request.is_null() { + String::from_utf8_lossy(body).into_owned() + } else { + serde_json::to_string_pretty(&request).unwrap_or_default() + }; + let (input, input_truncated) = clipped(&raw); + let record = Arc::new(Mutex::new(Record { + id: uuid::Uuid::new_v4().simple().to_string()[..12].to_owned(), + path: path.to_owned(), + model: request + .get("model") + .filter(|m| m.is_string()) + .cloned() + .unwrap_or(Value::Null), + started_at: now_unix(), + state: "queued", + outcome: None, + stream: request.get("stream") == Some(&json!(true)), + response_format: request + .get("response_format") + .and_then(|f| f.get("type")) + .or_else(|| request.pointer("/text/format/type")) + .cloned() + .unwrap_or(Value::Null), + input, + input_truncated, + output: String::new(), + output_truncated: false, + reasoning: String::new(), + reasoning_truncated: false, + first_token_s: None, + usage: None, + error: None, + http_status: None, + response: None, + response_truncated: false, + wallclock_s: None, + finished_at: None, + clock: Instant::now(), + })); + if let Ok(mut records) = self.records.lock() { + if records.len() == RETENTION { + records.pop_front(); + } + records.push_back(record.clone()); + } + record + } + + /// Newest first, without prompts and answers. + pub fn summaries(&self) -> Vec { + let records: Vec = self + .records + .lock() + .map(|r| r.iter().rev().cloned().collect()) + .unwrap_or_default(); + records + .iter() + .filter_map(|record| record.lock().ok().map(|r| r.render(false))) + .collect() + } + + /// One whole record, `None` once it was evicted (or never existed). + pub fn detail(&self, id: &str) -> Option { + let record = self + .records + .lock() + .ok()? + .iter() + .find(|r| r.lock().is_ok_and(|r| r.id == id))? + .clone(); + let rendered = record.lock().ok()?.render(true); + Some(rendered) + } +} + +impl Tap { + pub(super) fn absorb(&mut self, chunk: &[u8]) { + self.pending.extend_from_slice(chunk); + let Ok(mut record) = self.record.lock() else { + return; + }; + while let Some(newline) = self.pending.iter().position(|b| *b == b'\n') { + let line: Vec = self.pending.drain(..=newline).collect(); + let line = String::from_utf8_lossy(&line); + let Some(data) = line.trim_end_matches(['\r', '\n']).strip_prefix("data:") else { + continue; + }; + let data = data.trim(); + if data.is_empty() || data == "[DONE]" || data.len() > LINE_LIMIT { + continue; + } + if let Ok(event) = serde_json::from_str::(data) { + record.absorb_event(&event); + } + } + if self.pending.len() > LINE_LIMIT { + self.pending.clear(); + } + } + + pub(super) fn settle(&mut self, outcome: Option<&'static str>) { + self.done = true; + if let Ok(mut record) = self.record.lock() { + record.settle(outcome); + } + } +} + +impl Stream for Tap { + type Item = Result; + + fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { + match Pin::new(&mut self.inner).poll_next(cx) { + Poll::Ready(Some(Ok(chunk))) => { + self.absorb(&chunk); + Poll::Ready(Some(Ok(chunk))) + } + Poll::Ready(Some(Err(error))) => { + self.settle(Some("disconnected")); + Poll::Ready(Some(Err(error))) + } + Poll::Ready(None) => { + self.settle(None); + Poll::Ready(None) + } + Poll::Pending => Poll::Pending, + } + } +} + +impl Drop for Tap { + fn drop(&mut self) { + if !self.done { + // the consumer went away before the stream ended + self.settle(Some("disconnected")); + } + } +} + +pub(super) fn too_large() -> Response { + let body = + json!({"error": {"message": "request body too large", "type": "invalid_request_error"}}); + (StatusCode::PAYLOAD_TOO_LARGE, axum::Json(body)).into_response() +} + +/// Middleware for the generation routes: record the request and its answer when the monitor is on; a no-op otherwise. +pub async fn capture( + State(monitor): State>, + request: Request, + next: Next, +) -> Response { + if !monitor.enabled { + return next.run(request).await; + } + let path = request.uri().path().to_owned(); + let (parts, body) = request.into_parts(); + let Ok(bytes) = axum::body::to_bytes(body, BODY_LIMIT).await else { + return too_large(); + }; + let record = monitor.begin(&path, &bytes); + let response = next + .run(Request::from_parts(parts, Body::from(bytes))) + .await; + let (mut parts, body) = response.into_parts(); + if let Ok(mut r) = record.lock() { + r.http_status = Some(parts.status.as_u16()); + } + let streaming = parts + .headers + .get(header::CONTENT_TYPE) + .and_then(|v| v.to_str().ok()) + .is_some_and(|v| v.starts_with("text/event-stream")); + if streaming { + let tap = Tap { + inner: body.into_data_stream(), + record, + pending: Vec::new(), + done: false, + }; + return Response::from_parts(parts, Body::from_stream(tap)); + } + match axum::body::to_bytes(body, RESPONSE_LIMIT).await { + Ok(bytes) => { + if let Ok(mut r) = record.lock() { + if let Ok(value) = serde_json::from_slice::(&bytes) { + r.absorb_response(&value); + } + r.settle(None); + } + if let Ok(length) = HeaderValue::from_str(&bytes.len().to_string()) { + parts.headers.insert(header::CONTENT_LENGTH, length); + } + Response::from_parts(parts, Body::from(bytes)) + } + Err(error) => { + if let Ok(mut r) = record.lock() { + r.settle(Some("disconnected")); + } + crate::elog!("request monitor: could not read a response body: {error}"); + ( + StatusCode::INTERNAL_SERVER_ERROR, + "response body unavailable", + ) + .into_response() + } + } +} diff --git a/control-plane/src/request_monitor/now_unix.rs b/control-plane/src/request_monitor/now_unix.rs new file mode 100644 index 00000000..7c73a091 --- /dev/null +++ b/control-plane/src/request_monitor/now_unix.rs @@ -0,0 +1,36 @@ +//! Moved out of the parent module by STRA-338: fn now_unix, fn seconds, fn append_clipped, fn clipped. + +#[allow(unused_imports)] +use super::*; + +pub(super) fn now_unix() -> f64 { + SystemTime::now() + .duration_since(UNIX_EPOCH) + .map_or(0.0, |d| d.as_secs_f64()) +} + +pub(super) fn seconds(since: Instant) -> f64 { + (since.elapsed().as_secs_f64() * 1000.0).round() / 1000.0 +} + +/// Append `add` to `target` without exceeding [`CAP`] bytes (cut at a character boundary); true when something was left out. +pub(super) fn append_clipped(target: &mut String, flag: &mut bool, add: &str) { + let room = CAP.saturating_sub(target.len()); + if add.len() <= room { + target.push_str(add); + return; + } + let mut end = room; + while end > 0 && !add.is_char_boundary(end) { + end -= 1; + } + target.push_str(&add[..end]); + *flag = true; +} + +pub(super) fn clipped(text: &str) -> (String, bool) { + let mut out = String::new(); + let mut flag = false; + append_clipped(&mut out, &mut flag, text); + (out, flag) +} diff --git a/control-plane/src/responses/harmony_prompt.rs b/control-plane/src/responses/harmony_prompt.rs index 82c827d8..0759af96 100644 --- a/control-plane/src/responses/harmony_prompt.rs +++ b/control-plane/src/responses/harmony_prompt.rs @@ -15,26 +15,6 @@ use std::time::{SystemTime, UNIX_EPOCH}; use super::{CreateRequest, Effort, TextFormat, reasoning_effort}; use crate::response_tools::{Catalog, alias}; -/// `YYYY-MM-DD` (UTC) for a count of seconds since the Unix epoch. -pub(super) fn civil_date(seconds: u64) -> String { - // days since 1970-01-01 to a proleptic Gregorian date (Howard Hinnant's algorithm) - let days = (seconds / 86_400) as i64 + 719_468; - let era = days.div_euclid(146_097); - let day_of_era = days.rem_euclid(146_097); - let year_of_era = - (day_of_era - day_of_era / 1_460 + day_of_era / 36_524 - day_of_era / 146_096) / 365; - let day_of_year = day_of_era - (365 * year_of_era + year_of_era / 4 - year_of_era / 100); - let month_index = (5 * day_of_year + 2) / 153; - let day = day_of_year - (153 * month_index + 2) / 5 + 1; - let month = if month_index < 10 { - month_index + 3 - } else { - month_index - 9 - }; - let year = year_of_era + era * 400 + i64::from(month <= 2); - format!("{year:04}-{month:02}-{day:02}") -} - /// What the system message says about the date (`prompt_date` in the config, `STRATA_PROMPT_DATE`). /// /// The gpt-oss template writes `Current date: YYYY-MM-DD`, so the date is part of the prefix that a worker's cache @@ -48,398 +28,8 @@ pub enum PromptDate { Fixed(String), } -impl PromptDate { - /// `utc`, `none` or a date `YYYY-MM-DD`. - pub fn parse(text: &str) -> Result { - match text.trim() { - "utc" => Ok(Self::Utc), - "none" => Ok(Self::None), - date => { - let parts: Vec<&str> = date.split('-').collect(); - let number = |part: &str, digits: usize| { - (part.len() == digits && part.bytes().all(|b| b.is_ascii_digit())) - .then(|| part.parse::().ok()) - .flatten() - }; - if let [year, month, day] = parts[..] - && let (Some(year), Some(month), Some(day)) = - (number(year, 4), number(month, 2), number(day, 2)) - && (1..=12).contains(&month) - && (1..=days_in_month(year, month)).contains(&day) - { - return Ok(Self::Fixed(date.to_owned())); - } - Err(format!( - "prompt_date must be utc, none or a date YYYY-MM-DD, not {text:?}" - )) - } - } - } -} - -fn days_in_month(year: u32, month: u32) -> u32 { - match month { - 2 if year.is_multiple_of(4) && (!year.is_multiple_of(100) || year.is_multiple_of(400)) => { - 29 - } - 2 => 28, - 4 | 6 | 9 | 11 => 30, - _ => 31, - } -} - static PROMPT_DATE: OnceLock = OnceLock::new(); -/// Choose the date mode for the rest of the process (once, at start; later calls are ignored). -pub fn set_prompt_date(mode: PromptDate) { - let _ = PROMPT_DATE.set(mode); -} - -fn today() -> String { - civil_date( - SystemTime::now() - .duration_since(UNIX_EPOCH) - .unwrap_or_default() - .as_secs(), - ) -} - -/// Instruction texts for the developer message: the request's instructions, then the constraints that -/// `tool_choice`, `parallel_tool_calls` and `text.format` put on this response. -fn instruction_texts(request: &CreateRequest) -> Vec { - let mut texts = Vec::new(); - if let Some(instructions) = &request.instructions { - texts.push(instructions.clone()); - } - if let Some(name) = request.forced_tool() { - texts.push(format!( - "Call exactly one function in this response: {name}. Do not call any other tool." - )); - } else if request.tools_required() { - texts.push("Call at least one tool in this response.".to_owned()); - } - if let Some(allowed) = request.allowed_tools() { - texts.push(if allowed.is_empty() { - "Do not call any tools in this response.".to_owned() - } else { - format!( - "Only these tools may be called in this response: {}. Do not call any other tool.", - serde_json::to_string(allowed).expect("selector serialization") - ) - }); - } - if request.parallel_tool_calls == Some(false) - && !request.tools_disabled() - && !request.tools.is_empty() - { - texts.push("Use at most one tool call in this response.".to_owned()); - } - if let Some(options) = &request.text { - let instruction = match &options.format { - TextFormat::Text => None, - TextFormat::JsonObject => Some("Return exactly one JSON object as your final text response. Do not add Markdown fences or commentary.".to_owned()), - TextFormat::JsonSchema { schema, .. } => Some(format!("Return exactly one JSON object matching this JSON Schema as your final text response. Do not add Markdown fences or commentary.\nJSON Schema: {schema}")), - }; - if let Some(mut instruction) = instruction { - if !request.tools_disabled() && !request.tools.is_empty() { - instruction.push_str(" Function calls still use the tool-call channel; this JSON requirement applies to your final text answer after any necessary tool results."); - } - texts.push(instruction); - } - } - texts -} - -fn message_text(item: &Value) -> Result { - match item.get("content") { - Some(Value::String(text)) => Ok(text.clone()), - Some(Value::Array(parts)) => { - let mut text = String::new(); - for part in parts { - if !matches!( - part.get("type").and_then(Value::as_str), - Some("input_text" | "output_text") - ) { - return Err("only text content parts are supported".into()); - } - text.push_str( - part.get("text") - .and_then(Value::as_str) - .ok_or("text part needs text")?, - ); - } - Ok(text) - } - _ => Err("input message needs text content".into()), - } -} - -fn reasoning_text(item: &Value) -> Result { - if item.get("encrypted_content").is_some_and(|v| !v.is_null()) { - return Err("encrypted reasoning replay is not supported".into()); - } - let parts = item - .get("content") - .and_then(Value::as_array) - .ok_or("reasoning replay requires raw reasoning_text content")?; - let mut text = String::new(); - for part in parts { - if part.get("type").and_then(Value::as_str) != Some("reasoning_text") { - return Err("reasoning replay requires reasoning_text parts".into()); - } - text.push_str( - part.get("text") - .and_then(Value::as_str) - .ok_or("reasoning_text needs text")?, - ); - } - Ok(text) -} - -fn output_text(item: &Value) -> Result { - match item.get("output") { - Some(Value::String(text)) => Ok(text.clone()), - Some(Value::Array(parts)) => Ok(parts - .iter() - .map(|part| { - if part["type"] != "input_text" { - return Err("tool output supports only input_text content parts"); - } - part["text"].as_str().ok_or("tool output part needs text") - }) - .collect::, _>>()? - .join("\n")), - _ => Err("tool output needs text or input_text parts".into()), - } -} - -/// The conversation of `request` (without the developer message) and any instruction messages found -/// in the input. -fn conversation(request: &CreateRequest) -> Result<(Vec, Vec), String> { - let mut messages = Vec::new(); - let mut instructions = Vec::new(); - if let Some(input) = request.input.as_str() { - messages.push(Message::new(Role::User, input)); - return Ok((messages, instructions)); - } - let items = request - .input - .as_array() - .ok_or("input must be a string or array")?; - let mut calls = Vec::<(String, ToolCall)>::new(); - let mut outputs = Vec::<(String, String)>::new(); - let mut reasoning = None::; - for item in items { - let kind = item - .get("type") - .and_then(Value::as_str) - .unwrap_or("message"); - match kind { - "reasoning" => { - if reasoning.is_some() || !calls.is_empty() { - return Err("reasoning must precede its assistant message or tool calls".into()); - } - reasoning = Some(reasoning_text(item)?); - } - "message" => { - if !calls.is_empty() { - return Err( - "every replayed function call needs an output before the next message" - .into(), - ); - } - let text = message_text(item)?; - match item.get("role").and_then(Value::as_str) { - Some("system" | "developer") => instructions.push(text), - Some("user") => { - reasoning = None; - messages.push(Message::new(Role::User, text)); - } - Some("assistant") => { - let mut message = Message::new(Role::Assistant, text); - message.thinking = reasoning.take(); - messages.push(message); - } - _ => return Err("unsupported input message role".into()), - } - } - "function_call" => { - if !outputs.is_empty() { - return Err("new function calls cannot interrupt tool outputs".into()); - } - let call_id = item - .get("call_id") - .and_then(Value::as_str) - .ok_or("function call needs call_id")?; - let name = item - .get("name") - .and_then(Value::as_str) - .ok_or("function call needs name")?; - let namespace = match item.get("namespace") { - None | Some(Value::Null) => None, - Some(Value::String(value)) => Some(value.as_str()), - _ => return Err("function namespace must be a string".into()), - }; - let name = alias(name, namespace)?; - if call_id.is_empty() - || name.is_empty() - || !name - .bytes() - .all(|byte| byte.is_ascii_alphanumeric() || byte == b'_' || byte == b'-') - || calls.iter().any(|(id, _)| id == call_id) - { - return Err("function call has an invalid or duplicate identity".into()); - } - if item.get("input").is_some() { - return Err("function call uses arguments, not input".into()); - } - let arguments: Value = serde_json::from_str( - item["arguments"] - .as_str() - .ok_or("function call needs JSON arguments")?, - ) - .map_err(|_| "function call arguments are not JSON")?; - if !arguments.is_object() { - return Err("function call arguments must be an object".into()); - } - calls.push(( - call_id.to_owned(), - ToolCall { - name, - arguments, - content_type: None, - }, - )); - } - "custom_tool_call" | "custom_tool_call_output" => { - return Err("custom tools are not supported by this model".into()); - } - "function_call_output" => { - let call_id = item - .get("call_id") - .and_then(Value::as_str) - .ok_or("tool output needs call_id")?; - if !calls.iter().any(|(id, _)| id == call_id) - || outputs.iter().any(|(id, _)| id == call_id) - { - return Err("tool output must match one preceding unresolved call_id".into()); - } - outputs.push((call_id.to_owned(), output_text(item)?)); - if outputs.len() == calls.len() { - // the template renders one call per assistant message, each followed by its output - for (index, (call_id, call)) in calls.drain(..).enumerate() { - let assistant = Message { - role: Role::Assistant, - content: None, - thinking: if index == 0 { reasoning.take() } else { None }, - tool_calls: vec![call], - }; - messages.push(assistant); - let (_, value) = outputs - .iter() - .find(|(id, _)| *id == call_id) - .expect("every call has an output"); - messages.push(Message::new(Role::Tool, value.clone())); - } - outputs.clear(); - } - } - _ => return Err("unsupported Responses input item".into()), - } - } - if !calls.is_empty() { - return Err("replayed function calls need all tool outputs".into()); - } - if reasoning.is_some() { - return Err( - "reasoning replay needs a following assistant message, tool call, or user turn".into(), - ); - } - Ok((messages, instructions)) -} - -fn harmony_effort(effort: Effort) -> &'static str { - match effort { - Effort::None | Effort::Low => "low", - Effort::Medium => "medium", - Effort::High | Effort::XHigh => "high", - } -} - -/// Render the Harmony prompt for `request` as of `date` (`YYYY-MM-DD`). -#[cfg(test)] -pub(super) fn render_at( - request: &CreateRequest, - date: &str, - sentinel_markers: bool, -) -> Result { - render_dated(request, Some(date), sentinel_markers) -} - -/// As [`render_at`]; without a date the system message has no `Current date:` line. -fn render_dated( - request: &CreateRequest, - date: Option<&str>, - sentinel_markers: bool, -) -> Result { - let (mut messages, input_instructions) = conversation(request)?; - if !matches!( - messages.last().map(|m| m.role), - Some(Role::User | Role::Tool) - ) { - return Err("generation needs a final user message or tool output".into()); - } - let mut developer = instruction_texts(request); - developer.extend(input_instructions); - developer.retain(|text| !text.trim().is_empty()); - if !developer.is_empty() { - messages.insert(0, Message::new(Role::Developer, developer.join("\n\n"))); - } - let tools: Vec = if request.tools_disabled() { - Vec::new() - } else { - Catalog::new(&request.tools)? - .flat - .iter() - .map(|tool| { - Ok(Tool { - name: tool - .get("name") - .and_then(Value::as_str) - .ok_or("tool needs a name")? - .to_owned(), - description: tool - .get("description") - .and_then(Value::as_str) - .map(str::to_owned), - parameters: tool - .get("parameters") - .cloned() - .unwrap_or_else(|| serde_json::json!({})), - }) - }) - .collect::>()? - }; - let mut options = RenderOptions::new(date.unwrap_or_default()); - options.omit_date = date.is_none(); - options.sentinel_markers = sentinel_markers; - options.reasoning_effort = - harmony_effort(reasoning_effort(request).map_err(|(_, message)| message.to_owned())?) - .to_owned(); - leleka_harmony::render(&messages, &tools, &options).map_err(|e| e.to_string()) -} - -/// Render the Harmony prompt for `request` with today's date. The special markers are written as -/// sentinel characters, which the gpt-oss codec turns into the special tokens: text from the client can -/// never forge a marker. -pub(super) fn render(request: &CreateRequest) -> Result { - match PROMPT_DATE.get().unwrap_or(&PromptDate::Utc) { - PromptDate::Utc => render_dated(request, Some(&today()), true), - PromptDate::Fixed(date) => render_dated(request, Some(date), true), - PromptDate::None => render_dated(request, None, true), - } -} - #[cfg(test)] mod tests { use super::*; @@ -619,3 +209,10 @@ mod prompt_date_tests { assert_ne!(with, tomorrow); } } + +mod civil_date; +#[allow(unused_imports)] +pub use civil_date::*; +mod conversation; +#[allow(unused_imports)] +pub use conversation::*; diff --git a/control-plane/src/responses/harmony_prompt/civil_date.rs b/control-plane/src/responses/harmony_prompt/civil_date.rs new file mode 100644 index 00000000..8be5088e --- /dev/null +++ b/control-plane/src/responses/harmony_prompt/civil_date.rs @@ -0,0 +1,187 @@ +//! Moved out of the parent module by STRA-338: fn civil_date, impl PromptDate, fn days_in_month, fn set_prompt_date, fn today, fn instruction_texts .... + +#[allow(unused_imports)] +use super::*; + +/// `YYYY-MM-DD` (UTC) for a count of seconds since the Unix epoch. +pub(in super::super) fn civil_date(seconds: u64) -> String { + // days since 1970-01-01 to a proleptic Gregorian date (Howard Hinnant's algorithm) + let days = (seconds / 86_400) as i64 + 719_468; + let era = days.div_euclid(146_097); + let day_of_era = days.rem_euclid(146_097); + let year_of_era = + (day_of_era - day_of_era / 1_460 + day_of_era / 36_524 - day_of_era / 146_096) / 365; + let day_of_year = day_of_era - (365 * year_of_era + year_of_era / 4 - year_of_era / 100); + let month_index = (5 * day_of_year + 2) / 153; + let day = day_of_year - (153 * month_index + 2) / 5 + 1; + let month = if month_index < 10 { + month_index + 3 + } else { + month_index - 9 + }; + let year = year_of_era + era * 400 + i64::from(month <= 2); + format!("{year:04}-{month:02}-{day:02}") +} + +impl PromptDate { + /// `utc`, `none` or a date `YYYY-MM-DD`. + pub fn parse(text: &str) -> Result { + match text.trim() { + "utc" => Ok(Self::Utc), + "none" => Ok(Self::None), + date => { + let parts: Vec<&str> = date.split('-').collect(); + let number = |part: &str, digits: usize| { + (part.len() == digits && part.bytes().all(|b| b.is_ascii_digit())) + .then(|| part.parse::().ok()) + .flatten() + }; + if let [year, month, day] = parts[..] + && let (Some(year), Some(month), Some(day)) = + (number(year, 4), number(month, 2), number(day, 2)) + && (1..=12).contains(&month) + && (1..=days_in_month(year, month)).contains(&day) + { + return Ok(Self::Fixed(date.to_owned())); + } + Err(format!( + "prompt_date must be utc, none or a date YYYY-MM-DD, not {text:?}" + )) + } + } + } +} + +pub(super) fn days_in_month(year: u32, month: u32) -> u32 { + match month { + 2 if year.is_multiple_of(4) && (!year.is_multiple_of(100) || year.is_multiple_of(400)) => { + 29 + } + 2 => 28, + 4 | 6 | 9 | 11 => 30, + _ => 31, + } +} + +/// Choose the date mode for the rest of the process (once, at start; later calls are ignored). +pub fn set_prompt_date(mode: PromptDate) { + let _ = PROMPT_DATE.set(mode); +} + +pub(super) fn today() -> String { + civil_date( + SystemTime::now() + .duration_since(UNIX_EPOCH) + .unwrap_or_default() + .as_secs(), + ) +} + +/// Instruction texts for the developer message: the request's instructions, then the constraints that +/// `tool_choice`, `parallel_tool_calls` and `text.format` put on this response. +pub(super) fn instruction_texts(request: &CreateRequest) -> Vec { + let mut texts = Vec::new(); + if let Some(instructions) = &request.instructions { + texts.push(instructions.clone()); + } + if let Some(name) = request.forced_tool() { + texts.push(format!( + "Call exactly one function in this response: {name}. Do not call any other tool." + )); + } else if request.tools_required() { + texts.push("Call at least one tool in this response.".to_owned()); + } + if let Some(allowed) = request.allowed_tools() { + texts.push(if allowed.is_empty() { + "Do not call any tools in this response.".to_owned() + } else { + format!( + "Only these tools may be called in this response: {}. Do not call any other tool.", + serde_json::to_string(allowed).expect("selector serialization") + ) + }); + } + if request.parallel_tool_calls == Some(false) + && !request.tools_disabled() + && !request.tools.is_empty() + { + texts.push("Use at most one tool call in this response.".to_owned()); + } + if let Some(options) = &request.text { + let instruction = match &options.format { + TextFormat::Text => None, + TextFormat::JsonObject => Some("Return exactly one JSON object as your final text response. Do not add Markdown fences or commentary.".to_owned()), + TextFormat::JsonSchema { schema, .. } => Some(format!("Return exactly one JSON object matching this JSON Schema as your final text response. Do not add Markdown fences or commentary.\nJSON Schema: {schema}")), + }; + if let Some(mut instruction) = instruction { + if !request.tools_disabled() && !request.tools.is_empty() { + instruction.push_str(" Function calls still use the tool-call channel; this JSON requirement applies to your final text answer after any necessary tool results."); + } + texts.push(instruction); + } + } + texts +} + +pub(super) fn message_text(item: &Value) -> Result { + match item.get("content") { + Some(Value::String(text)) => Ok(text.clone()), + Some(Value::Array(parts)) => { + let mut text = String::new(); + for part in parts { + if !matches!( + part.get("type").and_then(Value::as_str), + Some("input_text" | "output_text") + ) { + return Err("only text content parts are supported".into()); + } + text.push_str( + part.get("text") + .and_then(Value::as_str) + .ok_or("text part needs text")?, + ); + } + Ok(text) + } + _ => Err("input message needs text content".into()), + } +} + +pub(super) fn reasoning_text(item: &Value) -> Result { + if item.get("encrypted_content").is_some_and(|v| !v.is_null()) { + return Err("encrypted reasoning replay is not supported".into()); + } + let parts = item + .get("content") + .and_then(Value::as_array) + .ok_or("reasoning replay requires raw reasoning_text content")?; + let mut text = String::new(); + for part in parts { + if part.get("type").and_then(Value::as_str) != Some("reasoning_text") { + return Err("reasoning replay requires reasoning_text parts".into()); + } + text.push_str( + part.get("text") + .and_then(Value::as_str) + .ok_or("reasoning_text needs text")?, + ); + } + Ok(text) +} + +pub(super) fn output_text(item: &Value) -> Result { + match item.get("output") { + Some(Value::String(text)) => Ok(text.clone()), + Some(Value::Array(parts)) => Ok(parts + .iter() + .map(|part| { + if part["type"] != "input_text" { + return Err("tool output supports only input_text content parts"); + } + part["text"].as_str().ok_or("tool output part needs text") + }) + .collect::, _>>()? + .join("\n")), + _ => Err("tool output needs text or input_text parts".into()), + } +} diff --git a/control-plane/src/responses/harmony_prompt/conversation.rs b/control-plane/src/responses/harmony_prompt/conversation.rs new file mode 100644 index 00000000..39afe80f --- /dev/null +++ b/control-plane/src/responses/harmony_prompt/conversation.rs @@ -0,0 +1,231 @@ +//! Moved out of the parent module by STRA-338: fn conversation, fn harmony_effort, fn render_at, fn render_dated, fn render. + +#[allow(unused_imports)] +use super::*; + +/// The conversation of `request` (without the developer message) and any instruction messages found +/// in the input. +pub(super) fn conversation(request: &CreateRequest) -> Result<(Vec, Vec), String> { + let mut messages = Vec::new(); + let mut instructions = Vec::new(); + if let Some(input) = request.input.as_str() { + messages.push(Message::new(Role::User, input)); + return Ok((messages, instructions)); + } + let items = request + .input + .as_array() + .ok_or("input must be a string or array")?; + let mut calls = Vec::<(String, ToolCall)>::new(); + let mut outputs = Vec::<(String, String)>::new(); + let mut reasoning = None::; + for item in items { + let kind = item + .get("type") + .and_then(Value::as_str) + .unwrap_or("message"); + match kind { + "reasoning" => { + if reasoning.is_some() || !calls.is_empty() { + return Err("reasoning must precede its assistant message or tool calls".into()); + } + reasoning = Some(reasoning_text(item)?); + } + "message" => { + if !calls.is_empty() { + return Err( + "every replayed function call needs an output before the next message" + .into(), + ); + } + let text = message_text(item)?; + match item.get("role").and_then(Value::as_str) { + Some("system" | "developer") => instructions.push(text), + Some("user") => { + reasoning = None; + messages.push(Message::new(Role::User, text)); + } + Some("assistant") => { + let mut message = Message::new(Role::Assistant, text); + message.thinking = reasoning.take(); + messages.push(message); + } + _ => return Err("unsupported input message role".into()), + } + } + "function_call" => { + if !outputs.is_empty() { + return Err("new function calls cannot interrupt tool outputs".into()); + } + let call_id = item + .get("call_id") + .and_then(Value::as_str) + .ok_or("function call needs call_id")?; + let name = item + .get("name") + .and_then(Value::as_str) + .ok_or("function call needs name")?; + let namespace = match item.get("namespace") { + None | Some(Value::Null) => None, + Some(Value::String(value)) => Some(value.as_str()), + _ => return Err("function namespace must be a string".into()), + }; + let name = alias(name, namespace)?; + if call_id.is_empty() + || name.is_empty() + || !name + .bytes() + .all(|byte| byte.is_ascii_alphanumeric() || byte == b'_' || byte == b'-') + || calls.iter().any(|(id, _)| id == call_id) + { + return Err("function call has an invalid or duplicate identity".into()); + } + if item.get("input").is_some() { + return Err("function call uses arguments, not input".into()); + } + let arguments: Value = serde_json::from_str( + item["arguments"] + .as_str() + .ok_or("function call needs JSON arguments")?, + ) + .map_err(|_| "function call arguments are not JSON")?; + if !arguments.is_object() { + return Err("function call arguments must be an object".into()); + } + calls.push(( + call_id.to_owned(), + ToolCall { + name, + arguments, + content_type: None, + }, + )); + } + "custom_tool_call" | "custom_tool_call_output" => { + return Err("custom tools are not supported by this model".into()); + } + "function_call_output" => { + let call_id = item + .get("call_id") + .and_then(Value::as_str) + .ok_or("tool output needs call_id")?; + if !calls.iter().any(|(id, _)| id == call_id) + || outputs.iter().any(|(id, _)| id == call_id) + { + return Err("tool output must match one preceding unresolved call_id".into()); + } + outputs.push((call_id.to_owned(), output_text(item)?)); + if outputs.len() == calls.len() { + // the template renders one call per assistant message, each followed by its output + for (index, (call_id, call)) in calls.drain(..).enumerate() { + let assistant = Message { + role: Role::Assistant, + content: None, + thinking: if index == 0 { reasoning.take() } else { None }, + tool_calls: vec![call], + }; + messages.push(assistant); + let (_, value) = outputs + .iter() + .find(|(id, _)| *id == call_id) + .expect("every call has an output"); + messages.push(Message::new(Role::Tool, value.clone())); + } + outputs.clear(); + } + } + _ => return Err("unsupported Responses input item".into()), + } + } + if !calls.is_empty() { + return Err("replayed function calls need all tool outputs".into()); + } + if reasoning.is_some() { + return Err( + "reasoning replay needs a following assistant message, tool call, or user turn".into(), + ); + } + Ok((messages, instructions)) +} + +pub(super) fn harmony_effort(effort: Effort) -> &'static str { + match effort { + Effort::None | Effort::Low => "low", + Effort::Medium => "medium", + Effort::High | Effort::XHigh => "high", + } +} + +/// Render the Harmony prompt for `request` as of `date` (`YYYY-MM-DD`). +#[cfg(test)] +pub(in super::super) fn render_at( + request: &CreateRequest, + date: &str, + sentinel_markers: bool, +) -> Result { + render_dated(request, Some(date), sentinel_markers) +} + +/// As [`render_at`]; without a date the system message has no `Current date:` line. +pub(super) fn render_dated( + request: &CreateRequest, + date: Option<&str>, + sentinel_markers: bool, +) -> Result { + let (mut messages, input_instructions) = conversation(request)?; + if !matches!( + messages.last().map(|m| m.role), + Some(Role::User | Role::Tool) + ) { + return Err("generation needs a final user message or tool output".into()); + } + let mut developer = instruction_texts(request); + developer.extend(input_instructions); + developer.retain(|text| !text.trim().is_empty()); + if !developer.is_empty() { + messages.insert(0, Message::new(Role::Developer, developer.join("\n\n"))); + } + let tools: Vec = if request.tools_disabled() { + Vec::new() + } else { + Catalog::new(&request.tools)? + .flat + .iter() + .map(|tool| { + Ok(Tool { + name: tool + .get("name") + .and_then(Value::as_str) + .ok_or("tool needs a name")? + .to_owned(), + description: tool + .get("description") + .and_then(Value::as_str) + .map(str::to_owned), + parameters: tool + .get("parameters") + .cloned() + .unwrap_or_else(|| serde_json::json!({})), + }) + }) + .collect::>()? + }; + let mut options = RenderOptions::new(date.unwrap_or_default()); + options.omit_date = date.is_none(); + options.sentinel_markers = sentinel_markers; + options.reasoning_effort = + harmony_effort(reasoning_effort(request).map_err(|(_, message)| message.to_owned())?) + .to_owned(); + leleka_harmony::render(&messages, &tools, &options).map_err(|e| e.to_string()) +} + +/// Render the Harmony prompt for `request` with today's date. The special markers are written as +/// sentinel characters, which the gpt-oss codec turns into the special tokens: text from the client can +/// never forge a marker. +pub(in super::super) fn render(request: &CreateRequest) -> Result { + match PROMPT_DATE.get().unwrap_or(&PromptDate::Utc) { + PromptDate::Utc => render_dated(request, Some(&today()), true), + PromptDate::Fixed(date) => render_dated(request, Some(date), true), + PromptDate::None => render_dated(request, None, true), + } +} diff --git a/control-plane/src/server_api.rs b/control-plane/src/server_api.rs index 80c30f2d..bc230f62 100644 --- a/control-plane/src/server_api.rs +++ b/control-plane/src/server_api.rs @@ -35,658 +35,12 @@ use crate::{ pub const DEFAULT_CHAT_TEMPLATE: &str = include_str!("../../engine/strata/serve/chat_template.jinja"); -fn error_body(kind: Option<&str>, message: &str) -> Value { - match kind { - Some(kind) => json!({"error": {"type": kind, "message": message}}), - None => json!({"error": {"message": message}}), - } -} - -fn reply(status: StatusCode, body: Value) -> Response { - (status, Json(body)).into_response() -} - -fn now_s() -> u64 { - SystemTime::now() - .duration_since(UNIX_EPOCH) - .map_or(0, |d| d.as_secs()) -} - -fn header_str<'a>(headers: &'a HeaderMap, name: &str) -> Option<&'a str> { - headers.get(name).and_then(|v| v.to_str().ok()) -} - -fn is_loaded(worker: &WorkerStatus) -> bool { - worker.state == WorkerState::Ready -} - -/// Whether a request is running or waiting for the engine. -fn is_busy(state: &AppState, worker: &WorkerStatus) -> bool { - worker.metrics.active_since.is_some() || state.lifecycle.snapshot().generation_jobs > 0 -} - -fn context_of(worker: &WorkerStatus) -> usize { - worker.max_context.or(worker.known_max_context).unwrap_or(0) -} - -// ------------------------------------------------------------------------------------------------ loading - -/// Start the engine if it is unloaded (the Original's `Service.load`, called at the start of every -/// request). Stamps the activity time so the idle timer does not unload between this and the -/// request's own start. `Err` is a ready-made error response. -pub async fn ensure_loaded(state: &AppState) -> Result<(), Box> { - let unloaded = { - let mut worker = state.worker.write().await; - worker.last_activity = Some(tokio::time::Instant::now()); - worker.state == WorkerState::Unloaded - }; - if !unloaded { - return Ok(()); - } - match load(state).await { - Ok(()) => Ok(()), - Err(error) => Err(Box::new(load_error_response(&error))), - } -} - -/// Ask the supervisor to load and wait until it is ready. -pub async fn load(state: &AppState) -> Result<(), LoadError> { - let Some(control) = &state.control else { - return Err(LoadError::Failed( - "the engine cannot be loaded on demand".into(), - )); - }; - let (answer, received) = oneshot::channel(); - control - .send(Control::Load { reply: answer }) - .await - .map_err(|_| LoadError::Failed("the server is shutting down".into()))?; - received - .await - .map_err(|_| LoadError::Failed("the server is shutting down".into()))? -} - -/// `POST /unload`'s core (also the idle thread): the outcome string of the Original. -pub async fn unload(state: &AppState, idle_for: Option) -> Outcome { - let Some(control) = &state.control else { - return Outcome::Unsupported; - }; - { - let worker = state.worker.read().await; - if is_loaded(&worker) && is_busy(state, &worker) { - return Outcome::Busy; - } - } - let (answer, received) = oneshot::channel(); - if control - .send(Control::Unload { - idle_for, - reply: answer, - }) - .await - .is_err() - { - return Outcome::NotLoaded; - } - received.await.unwrap_or(Outcome::NotLoaded) -} - -fn load_error_response(error: &LoadError) -> Response { - let message = match error { - LoadError::GpuBusy(m) | LoadError::Failed(m) => m, - }; - api_server_error(message) -} - -fn api_server_error(message: &str) -> Response { - reply( - StatusCode::SERVICE_UNAVAILABLE, - error_body(Some("server_error"), message), - ) -} - -/// The idle thread of `--idle-unload`: every `poll` seconds, give the engine back if no request ran -/// within `idle`. Returns when the control channel closes. -pub async fn idle_unload_loop(state: AppState, idle: Duration, poll: Duration) { - loop { - tokio::time::sleep(poll).await; - if state.control.as_ref().is_none_or(mpsc::Sender::is_closed) { - return; - } - let outcome = unload(&state, Some(idle)).await; - if outcome == Outcome::Unloaded { - crate::elog!( - "model unloaded after {:.0} s idle; the next request loads it again", - idle.as_secs_f64() - ); - } - } -} - -// ------------------------------------------------------------------------------------------------ handlers - -/// `GET /api/health` (the Python server's `/health`): who answers and whether the engine is loaded. -pub async fn api_health(State(state): State) -> Response { - let worker = *state.worker.read().await; - reply( - StatusCode::OK, - json!({"status": "ok", "max_context": context_of(&worker), "model": state.model, - "images": state.vision.is_some(), "api_key": state.api_key.is_some(), - "loaded": is_loaded(&worker), "service": "strata"}), - ) -} - -fn model_names(state: &AppState) -> Vec { - state - .model - .iter() - .cloned() - .chain(state.aliases.iter().cloned()) - .collect() -} - -/// The first non-blank value of `name` (Python's `parse_qs` drops blank values). -fn query_param(query: Option<&str>, name: &str) -> Option { - query?.split('&').find_map(|pair| { - let (key, value) = pair.split_once('=')?; - (percent_decode(key) == name && !value.is_empty()).then(|| percent_decode(value)) - }) -} - -fn percent_decode(text: &str) -> String { - let bytes = text.as_bytes(); - let mut out = Vec::with_capacity(bytes.len()); - let mut i = 0; - while i < bytes.len() { - match bytes[i] { - b'+' => out.push(b' '), - b'%' if i + 2 < bytes.len() => { - match std::str::from_utf8(&bytes[i + 1..i + 3]) - .ok() - .and_then(|hex| u8::from_str_radix(hex, 16).ok()) - { - Some(byte) => { - out.push(byte); - i += 2; - } - None => out.push(b'%'), - } - } - byte => out.push(byte), - } - i += 1; - } - String::from_utf8_lossy(&out).into_owned() -} - -/// `GET /props` (llama-server compatible): the default generation settings, the chat template and -/// what this server can do. -pub async fn props(State(state): State, request: Request) -> Response { - let asked = query_param(request.uri().query(), "model") - .or_else(|| state.model.clone()) - .unwrap_or_default(); - if !model_names(&state).contains(&asked) { - return reply(StatusCode::NOT_FOUND, error_body(None, "model not found")); - } - let worker = *state.worker.read().await; - if !is_loaded(&worker) && worker.state != WorkerState::Unloaded { - return reply( - StatusCode::SERVICE_UNAVAILABLE, - error_body(None, "the engine is not running"), - ); - } - let merged = state.settings.merged(); - let shared = state.settings.shared(); - reply( - StatusCode::OK, - json!({ - "default_generation_settings": { - "n_ctx": context_of(&worker), - "params": merged.props_params(&shared), - }, - "total_slots": 1, - "model_alias": state.model, - "chat_template": state.chat_template.as_deref().unwrap_or(DEFAULT_CHAT_TEMPLATE), - "modalities": {"vision": state.vision.is_some()}, - "models_autoload": state.control.is_some(), - "is_sleeping": !is_loaded(&worker), - "build_info": format!("Strata Next {}", env!("CARGO_PKG_VERSION")), - }), - ) -} - -/// `GET /slots`: one slot while the engine is loaded, none otherwise. -pub async fn slots(State(state): State) -> Response { - let worker = *state.worker.read().await; - if !is_loaded(&worker) { - return reply(StatusCode::OK, json!([])); - } - reply( - StatusCode::OK, - json!([{"id": 0, "n_ctx": context_of(&worker), - "is_processing": is_busy(&state, &worker)}]), - ) -} - -/// `POST /v1/prefix_match`: how many tokens of a prompt this runtime's prefix cache holds, for a pool router. -/// Body `{"block_hashes": ["<16 hex>", ...], "namespace": "<16 hex>"}`: the chain values of the prompt's full blocks in order -/// (see `docs/prefix-cache.md`); `namespace` is optional. The answer comes from the engine's last summary. -pub async fn v1_prefix_match(State(state): State, body: Bytes) -> Response { - let parsed: Result = serde_json::from_slice(&body); - let Ok(request) = parsed else { - return reply( - StatusCode::BAD_REQUEST, - json!({"error": {"message": "the body must be a JSON object", "type": "invalid_request"}}), - ); - }; - let hashes: Option> = request["block_hashes"] - .as_array() - .and_then(|list| list.iter().map(|h| h.as_str().map(str::to_owned)).collect()); - let Some(hashes) = hashes else { - return reply( - StatusCode::BAD_REQUEST, - json!({"error": {"message": "block_hashes must be an array of hex strings", "type": "invalid_request"}}), - ); - }; - match state - .prefix_cache - .prefix_match(request["namespace"].as_str(), &hashes) - { - Ok(answer) => reply(StatusCode::OK, answer), - Err(error) => reply( - StatusCode::BAD_REQUEST, - json!({"error": {"message": format!("{error:?}: at most {} lowercase-hex 16-digit chain values", crate::prefix_view::MAX_HASHES), "type": "invalid_request"}}), - ), - } -} - -/// `GET /v1/status`: what this server is and does, for a client that would rather ask than guess. -pub async fn v1_status(State(state): State) -> Response { - reply(StatusCode::OK, status_value(&state).await) -} - -async fn status_value(state: &AppState) -> Value { - let worker = *state.worker.read().await; - let lifecycle = state.lifecycle.snapshot(); - let busy = worker.metrics.active_since.is_some(); - let queued = lifecycle.generation_jobs.saturating_sub(usize::from(busy)); - let context = context_of(&worker); - let last_at = worker - .last_activity - .map(|at| now_s().saturating_sub(at.elapsed().as_secs())); - let started = state - .started_at - .duration_since(UNIX_EPOCH) - .map_or(0, |d| d.as_secs()); - let timings = worker.metrics.last_done.map(|done| { - let mut value = leleka_serving_policy::timings::request_timings( - &leleka_serving_policy::timings::Last { - prompt_tokens: done.prompt_tokens, - generated: done.generated_tokens, - prompt_ms: done.prefill_ms, - decode_ms: done.decode_ms, - reused: done.reused_tokens, - drafts_offered: done.drafts_offered, - drafts_accepted: done.drafts_accepted, - }, - done.generated_tokens, - ); - value["at"] = json!(now_s()); - value - }); - let mut body = json!({ - "service": "strata", "model": state.model, - "loaded": is_loaded(&worker), "auto_load": state.control.is_some(), - "structured_output": {"formats": ["json_object", "json_schema"], "method": "prompt_and_validate", - "constrained_decoding": false, "stream_buffered": true}, - "engine": env!("CARGO_PKG_VERSION"), - "started": started, - "uptime_s": state.started_at.elapsed().map_or(0, |d| d.as_secs()), - "cache_max_tokens": context, - "context": {"native": context, "max_positions": context}, - "concurrency": {"serving": 1, "requested": 1}, - "dialects": ["/v1/chat/completions", "/v1/messages", "/v1/responses"], - "vision": {"enabled": state.vision.is_some(), "available": state.vision.is_some(), "error": null}, - "activity": {"requests": worker.metrics.started, "in_flight": usize::from(busy) + queued, - "last_request_at": last_at}, - "last_timings": timings, - "machine": machine_view(&state.memory), - "memory": state.memory.status(), - }); - // Present only when a prefix cache exists: the Python server's status has no such key (golden http_surface). - let prefix = json!(state.prefix_cache.status()); - if !prefix.is_null() { - body["prefix_cache"] = prefix; - } - body -} - -/// `GET /settings`. -pub async fn settings_get(State(state): State) -> Response { - let shared = state.settings.shared(); - reply( - StatusCode::OK, - json!({"shared": !shared.is_empty(), "defaults": shared.to_json()}), - ) -} - -fn own_page_check(state: &AppState, headers: &HeaderMap, what: &str) -> Result<(), Box> { - own_page( - what, - header_str(headers, "content-type"), - header_str(headers, "origin"), - header_str(headers, "host"), - &state.trusted_origins, - ) - .map_err(|e| { - Box::new(reply( - StatusCode::from_u16(e.status()).unwrap_or(StatusCode::FORBIDDEN), - error_body(None, &e.message()), - )) - }) -} - -/// `POST /settings`: replace the Chat settings every client gets for what it leaves out. They change -/// what every client gets, so only the app's own page may set them. -pub async fn settings_post( - State(state): State, - headers: HeaderMap, - body: Bytes, -) -> Response { - if let Err(response) = own_page_check(&state, &headers, "settings can be changed") { - return *response; - } - let value: Value = if body.is_empty() { - json!({}) - } else { - match serde_json::from_slice(&body) { - Ok(value) => value, - Err(error) => { - return reply( - StatusCode::BAD_REQUEST, - error_body(Some("invalid_request_error"), &error.to_string()), - ); - } - } - }; - let defaults = value.get("defaults").cloned().unwrap_or(Value::Null); - match state.settings.set_shared(&defaults) { - Ok(shared) => { - if shared.is_empty() { - crate::elog!("other apps use their own settings again"); - } else { - crate::elog!("other apps now use the Chat settings: {}", shared.to_json()); - } - reply( - StatusCode::OK, - json!({"shared": !shared.is_empty(), "defaults": shared.to_json()}), - ) - } - Err(message) => reply( - StatusCode::BAD_REQUEST, - error_body(Some("invalid_request_error"), &message), - ), - } -} - -/// `POST /unload`: give the GPU back now (between requests). -pub async fn unload_post(State(state): State) -> Response { - let outcome = unload(&state, None).await; - reply( - if outcome == Outcome::Busy { - StatusCode::CONFLICT - } else { - StatusCode::OK - }, - json!({"status": outcome.as_str()}), - ) -} - -/// `POST /load`: load now, e.g. ahead of a request. -pub async fn load_post(State(state): State) -> Response { - state.worker.write().await.last_activity = Some(tokio::time::Instant::now()); - if state.worker.read().await.state == WorkerState::Ready { - return reply(StatusCode::OK, json!({"status": "loaded"})); - } - match load(&state).await { - Ok(()) => reply(StatusCode::OK, json!({"status": "loaded"})), - Err(error) => load_error_response(&error), - } -} - -/// The shared prelude of `POST /v1/load` and `/v1/unload`: a JSON object body, own page only, and -/// the right model. -fn model_control_prelude( - state: &AppState, - headers: &HeaderMap, - body: &Bytes, -) -> Result<(), Box> { - let value: Value = if body.is_empty() { - json!({}) - } else { - serde_json::from_slice(body).map_err(|error| { - Box::new(reply( - StatusCode::BAD_REQUEST, - error_body(Some("invalid_request_error"), &error.to_string()), - )) - })? - }; - let Some(object) = value.as_object() else { - return Err(Box::new(reply( - StatusCode::BAD_REQUEST, - error_body(Some("invalid_request_error"), "send a JSON object"), - ))); - }; - own_page_check(state, headers, "the model can be loaded or unloaded")?; - match object.get("model") { - None | Some(Value::Null) => {} - Some(Value::String(name)) if state.model.as_deref() == Some(name.as_str()) => {} - Some(_) => { - return Err(Box::new(reply( - StatusCode::NOT_FOUND, - error_body(None, "model not found"), - ))); - } - } - Ok(()) -} - -fn model_busy() -> Response { - reply( - StatusCode::CONFLICT, - error_body(Some("model_busy"), "a request is running or queued"), - ) -} - -pub async fn v1_unload(State(state): State, headers: HeaderMap, body: Bytes) -> Response { - if let Err(response) = model_control_prelude(&state, &headers, &body) { - return *response; - } - let outcome = unload(&state, None).await; - if outcome == Outcome::Busy { - return model_busy(); - } - let mut value = status_value(&state).await; - value["status"] = json!(outcome.as_str()); - reply(StatusCode::OK, value) -} - -pub async fn v1_load(State(state): State, headers: HeaderMap, body: Bytes) -> Response { - if let Err(response) = model_control_prelude(&state, &headers, &body) { - return *response; - } - { - let worker = state.worker.read().await; - if is_busy(&state, &worker) { - return model_busy(); - } - } - state.worker.write().await.last_activity = Some(tokio::time::Instant::now()); - if state.worker.read().await.state != WorkerState::Ready - && let Err(error) = load(&state).await - { - return load_error_response(&error); - } - let mut value = status_value(&state).await; - value["status"] = json!("loaded"); - reply(StatusCode::OK, value) -} - -/// `POST /v1/reconfigure`: change the inference settings of the running engine without reloading the model (context length, -/// prefix cache, prefill chunk, CPU workers...). The body is a JSON object with any of: `context_tokens`, `prefill_capacity`, -/// `kv_resident` (only the value in force), `prefix_cache_mib`, `prefix_cache_tail`, `prefix_cache_block`, `prefix_retention_min`, -/// `cpu_workers` (1..=15), `spec_min_p`. The call waits for the request in flight, the engine reopens its serve stack (about 7 s on -/// the 5090; requests meanwhile wait in the queue) and the answer carries the effective settings; a refused change leaves the -/// previous settings in place. -pub async fn v1_reconfigure( - State(state): State, - headers: HeaderMap, - body: Bytes, -) -> Response { - if let Err(response) = own_page_check(&state, &headers, "the engine settings can be changed") { - return *response; - } - let parsed: Result = serde_json::from_slice(&body); - let Ok(settings) = parsed else { - return reply( - StatusCode::BAD_REQUEST, - error_body( - Some("invalid_request_error"), - "send a JSON object of settings", - ), - ); - }; - if !settings.is_object() { - return reply( - StatusCode::BAD_REQUEST, - error_body( - Some("invalid_request_error"), - "send a JSON object of settings", - ), - ); - } - let Some(control) = &state.control else { - return reply( - StatusCode::NOT_IMPLEMENTED, - error_body(None, "this server has no engine to reconfigure"), - ); - }; - let (answer, response) = tokio::sync::oneshot::channel(); - if control - .send(Control::Reconfigure { - settings: settings.to_string(), - reply: answer, - }) - .await - .is_err() - { - return reply( - StatusCode::SERVICE_UNAVAILABLE, - error_body(None, "the worker is gone"), - ); - } - match tokio::time::timeout(std::time::Duration::from_secs(1900), response).await { - Ok(Ok(Ok(effective))) => { - let settings: Value = serde_json::from_str(&effective).unwrap_or(Value::Null); - reply( - StatusCode::OK, - json!({"status": "reconfigured", "settings": settings}), - ) - } - Ok(Ok(Err((status, message)))) => reply( - StatusCode::from_u16(status).unwrap_or(StatusCode::INTERNAL_SERVER_ERROR), - error_body(Some("reconfigure_refused"), &message), - ), - _ => reply( - StatusCode::GATEWAY_TIMEOUT, - error_body(None, "the engine did not answer the reconfigure in time"), - ), - } -} - -/// `GET /api/requests`: the request monitor (`api_monitor` in the config; 404 while it is off, as in the Original). Without -/// `id` the retained requests, newest first, without prompts and answers; with `?id=` one whole record, or 404 once evicted. -pub async fn api_requests(State(state): State, RawQuery(query): RawQuery) -> Response { - if !state.monitor.enabled() { - return not_found().await; - } - let id = query.as_deref().and_then(|query| { - query - .split('&') - .find_map(|pair| pair.strip_prefix("id=").map(|id| id.to_owned())) - }); - if let Some(id) = id { - return match state.monitor.detail(&id) { - Some(record) => reply(StatusCode::OK, record), - None => reply( - StatusCode::NOT_FOUND, - error_body(None, "request no longer retained"), - ), - }; - } - let worker = *state.worker.read().await; - reply( - StatusCode::OK, - json!({"requests": state.monitor.summaries(), "retention": crate::request_monitor::RETENTION, "persistent": false, - "loaded": is_loaded(&worker), "auto_load": state.control.is_some()}), - ) -} - -/// Unknown paths: a JSON error, like the Original's `{"error": {"message": "not found"}}`. -pub async fn not_found() -> Response { - reply(StatusCode::NOT_FOUND, error_body(None, "not found")) -} - -// ------------------------------------------------------------------------------------------------ CORS - -/// CORS for `/v1/*` (config `cors_origins`) and the preflight: the outermost layer, so a browser's -/// credential-less `OPTIONS` is answered before authentication, as the Original does. -pub async fn cors_layer(State(cors): State>, request: Request, next: Next) -> Response { - let target = request.uri().path_and_query().map_or_else( - || request.uri().path().to_owned(), - |p| p.as_str().to_owned(), - ); - let headers = cors.headers( - &target, - header_str(request.headers(), "origin"), - header_str(request.headers(), "access-control-request-headers"), - ); - let mut response = if request.method() == Method::OPTIONS { - let mut response = StatusCode::NO_CONTENT.into_response(); - response - .headers_mut() - .insert(header::CONTENT_LENGTH, HeaderValue::from_static("0")); - response - } else { - next.run(request).await - }; - for (name, value) in headers { - if let (Ok(name), Ok(value)) = ( - HeaderName::from_bytes(name.as_bytes()), - HeaderValue::from_str(&value), - ) { - response.headers_mut().insert(name, value); - } - } - response -} - -/// `GET /mcp`: the configured MCP servers, their state and tools (empty when there are none). -pub async fn mcp_status(State(state): State) -> Response { - let body = match &state.mcp { - Some(hub) => hub.status().await, - None => json!({"servers": [], "tools": 0}), - }; - reply(StatusCode::OK, body) -} - -/// `machine` of `GET /v1/status`: the engine's telemetry (GPU load and VRAM, RAM, CPU cores, throughput, cache hits, context) -/// when it reports any; the legacy `{at, gpu, ram}` shape with nulls otherwise. -fn machine_view(memory: &crate::memory_view::MemoryView) -> Value { - let mut view = memory.telemetry_status(); - if !view.is_object() { - return json!({"at": now_s(), "gpu": null, "ram": null}); - } - view["at"] = json!(now_s()); - view -} +mod error_body; +#[allow(unused_imports)] +pub use error_body::*; +mod slots; +#[allow(unused_imports)] +pub use slots::*; +mod model_busy; +#[allow(unused_imports)] +pub use model_busy::*; diff --git a/control-plane/src/server_api/error_body.rs b/control-plane/src/server_api/error_body.rs new file mode 100644 index 00000000..ee745c99 --- /dev/null +++ b/control-plane/src/server_api/error_body.rs @@ -0,0 +1,224 @@ +//! Moved out of the parent module by STRA-338: fn error_body, fn reply, fn now_s, fn header_str, fn is_loaded, fn is_busy .... + +#[allow(unused_imports)] +use super::*; + +pub(super) fn error_body(kind: Option<&str>, message: &str) -> Value { + match kind { + Some(kind) => json!({"error": {"type": kind, "message": message}}), + None => json!({"error": {"message": message}}), + } +} + +pub(super) fn reply(status: StatusCode, body: Value) -> Response { + (status, Json(body)).into_response() +} + +pub(super) fn now_s() -> u64 { + SystemTime::now() + .duration_since(UNIX_EPOCH) + .map_or(0, |d| d.as_secs()) +} + +pub(super) fn header_str<'a>(headers: &'a HeaderMap, name: &str) -> Option<&'a str> { + headers.get(name).and_then(|v| v.to_str().ok()) +} + +pub(super) fn is_loaded(worker: &WorkerStatus) -> bool { + worker.state == WorkerState::Ready +} + +/// Whether a request is running or waiting for the engine. +pub(super) fn is_busy(state: &AppState, worker: &WorkerStatus) -> bool { + worker.metrics.active_since.is_some() || state.lifecycle.snapshot().generation_jobs > 0 +} + +pub(super) fn context_of(worker: &WorkerStatus) -> usize { + worker.max_context.or(worker.known_max_context).unwrap_or(0) +} + +// ------------------------------------------------------------------------------------------------ loading + +/// Start the engine if it is unloaded (the Original's `Service.load`, called at the start of every +/// request). Stamps the activity time so the idle timer does not unload between this and the +/// request's own start. `Err` is a ready-made error response. +pub async fn ensure_loaded(state: &AppState) -> Result<(), Box> { + let unloaded = { + let mut worker = state.worker.write().await; + worker.last_activity = Some(tokio::time::Instant::now()); + worker.state == WorkerState::Unloaded + }; + if !unloaded { + return Ok(()); + } + match load(state).await { + Ok(()) => Ok(()), + Err(error) => Err(Box::new(load_error_response(&error))), + } +} + +/// Ask the supervisor to load and wait until it is ready. +pub async fn load(state: &AppState) -> Result<(), LoadError> { + let Some(control) = &state.control else { + return Err(LoadError::Failed( + "the engine cannot be loaded on demand".into(), + )); + }; + let (answer, received) = oneshot::channel(); + control + .send(Control::Load { reply: answer }) + .await + .map_err(|_| LoadError::Failed("the server is shutting down".into()))?; + received + .await + .map_err(|_| LoadError::Failed("the server is shutting down".into()))? +} + +/// `POST /unload`'s core (also the idle thread): the outcome string of the Original. +pub async fn unload(state: &AppState, idle_for: Option) -> Outcome { + let Some(control) = &state.control else { + return Outcome::Unsupported; + }; + { + let worker = state.worker.read().await; + if is_loaded(&worker) && is_busy(state, &worker) { + return Outcome::Busy; + } + } + let (answer, received) = oneshot::channel(); + if control + .send(Control::Unload { + idle_for, + reply: answer, + }) + .await + .is_err() + { + return Outcome::NotLoaded; + } + received.await.unwrap_or(Outcome::NotLoaded) +} + +pub(super) fn load_error_response(error: &LoadError) -> Response { + let message = match error { + LoadError::GpuBusy(m) | LoadError::Failed(m) => m, + }; + api_server_error(message) +} + +pub(super) fn api_server_error(message: &str) -> Response { + reply( + StatusCode::SERVICE_UNAVAILABLE, + error_body(Some("server_error"), message), + ) +} + +/// The idle thread of `--idle-unload`: every `poll` seconds, give the engine back if no request ran +/// within `idle`. Returns when the control channel closes. +pub async fn idle_unload_loop(state: AppState, idle: Duration, poll: Duration) { + loop { + tokio::time::sleep(poll).await; + if state.control.as_ref().is_none_or(mpsc::Sender::is_closed) { + return; + } + let outcome = unload(&state, Some(idle)).await; + if outcome == Outcome::Unloaded { + crate::elog!( + "model unloaded after {:.0} s idle; the next request loads it again", + idle.as_secs_f64() + ); + } + } +} + +// ------------------------------------------------------------------------------------------------ handlers + +/// `GET /api/health` (the Python server's `/health`): who answers and whether the engine is loaded. +pub async fn api_health(State(state): State) -> Response { + let worker = *state.worker.read().await; + reply( + StatusCode::OK, + json!({"status": "ok", "max_context": context_of(&worker), "model": state.model, + "images": state.vision.is_some(), "api_key": state.api_key.is_some(), + "loaded": is_loaded(&worker), "service": "strata"}), + ) +} + +pub(super) fn model_names(state: &AppState) -> Vec { + state + .model + .iter() + .cloned() + .chain(state.aliases.iter().cloned()) + .collect() +} + +/// The first non-blank value of `name` (Python's `parse_qs` drops blank values). +pub(super) fn query_param(query: Option<&str>, name: &str) -> Option { + query?.split('&').find_map(|pair| { + let (key, value) = pair.split_once('=')?; + (percent_decode(key) == name && !value.is_empty()).then(|| percent_decode(value)) + }) +} + +pub(super) fn percent_decode(text: &str) -> String { + let bytes = text.as_bytes(); + let mut out = Vec::with_capacity(bytes.len()); + let mut i = 0; + while i < bytes.len() { + match bytes[i] { + b'+' => out.push(b' '), + b'%' if i + 2 < bytes.len() => { + match std::str::from_utf8(&bytes[i + 1..i + 3]) + .ok() + .and_then(|hex| u8::from_str_radix(hex, 16).ok()) + { + Some(byte) => { + out.push(byte); + i += 2; + } + None => out.push(b'%'), + } + } + byte => out.push(byte), + } + i += 1; + } + String::from_utf8_lossy(&out).into_owned() +} + +/// `GET /props` (llama-server compatible): the default generation settings, the chat template and +/// what this server can do. +pub async fn props(State(state): State, request: Request) -> Response { + let asked = query_param(request.uri().query(), "model") + .or_else(|| state.model.clone()) + .unwrap_or_default(); + if !model_names(&state).contains(&asked) { + return reply(StatusCode::NOT_FOUND, error_body(None, "model not found")); + } + let worker = *state.worker.read().await; + if !is_loaded(&worker) && worker.state != WorkerState::Unloaded { + return reply( + StatusCode::SERVICE_UNAVAILABLE, + error_body(None, "the engine is not running"), + ); + } + let merged = state.settings.merged(); + let shared = state.settings.shared(); + reply( + StatusCode::OK, + json!({ + "default_generation_settings": { + "n_ctx": context_of(&worker), + "params": merged.props_params(&shared), + }, + "total_slots": 1, + "model_alias": state.model, + "chat_template": state.chat_template.as_deref().unwrap_or(DEFAULT_CHAT_TEMPLATE), + "modalities": {"vision": state.vision.is_some()}, + "models_autoload": state.control.is_some(), + "is_sleeping": !is_loaded(&worker), + "build_info": format!("Strata Next {}", env!("CARGO_PKG_VERSION")), + }), + ) +} diff --git a/control-plane/src/server_api/model_busy.rs b/control-plane/src/server_api/model_busy.rs new file mode 100644 index 00000000..58b75b31 --- /dev/null +++ b/control-plane/src/server_api/model_busy.rs @@ -0,0 +1,204 @@ +//! Moved out of the parent module by STRA-338: fn model_busy, fn v1_unload, fn v1_load, fn v1_reconfigure, fn api_requests, fn not_found .... + +#[allow(unused_imports)] +use super::*; + +pub(super) fn model_busy() -> Response { + reply( + StatusCode::CONFLICT, + error_body(Some("model_busy"), "a request is running or queued"), + ) +} + +pub async fn v1_unload(State(state): State, headers: HeaderMap, body: Bytes) -> Response { + if let Err(response) = model_control_prelude(&state, &headers, &body) { + return *response; + } + let outcome = unload(&state, None).await; + if outcome == Outcome::Busy { + return model_busy(); + } + let mut value = status_value(&state).await; + value["status"] = json!(outcome.as_str()); + reply(StatusCode::OK, value) +} + +pub async fn v1_load(State(state): State, headers: HeaderMap, body: Bytes) -> Response { + if let Err(response) = model_control_prelude(&state, &headers, &body) { + return *response; + } + { + let worker = state.worker.read().await; + if is_busy(&state, &worker) { + return model_busy(); + } + } + state.worker.write().await.last_activity = Some(tokio::time::Instant::now()); + if state.worker.read().await.state != WorkerState::Ready + && let Err(error) = load(&state).await + { + return load_error_response(&error); + } + let mut value = status_value(&state).await; + value["status"] = json!("loaded"); + reply(StatusCode::OK, value) +} + +/// `POST /v1/reconfigure`: change the inference settings of the running engine without reloading the model (context length, +/// prefix cache, prefill chunk, CPU workers...). The body is a JSON object with any of: `context_tokens`, `prefill_capacity`, +/// `kv_resident` (only the value in force), `prefix_cache_mib`, `prefix_cache_tail`, `prefix_cache_block`, `prefix_retention_min`, +/// `cpu_workers` (1..=15), `spec_min_p`. The call waits for the request in flight, the engine reopens its serve stack (about 7 s on +/// the 5090; requests meanwhile wait in the queue) and the answer carries the effective settings; a refused change leaves the +/// previous settings in place. +pub async fn v1_reconfigure( + State(state): State, + headers: HeaderMap, + body: Bytes, +) -> Response { + if let Err(response) = own_page_check(&state, &headers, "the engine settings can be changed") { + return *response; + } + let parsed: Result = serde_json::from_slice(&body); + let Ok(settings) = parsed else { + return reply( + StatusCode::BAD_REQUEST, + error_body( + Some("invalid_request_error"), + "send a JSON object of settings", + ), + ); + }; + if !settings.is_object() { + return reply( + StatusCode::BAD_REQUEST, + error_body( + Some("invalid_request_error"), + "send a JSON object of settings", + ), + ); + } + let Some(control) = &state.control else { + return reply( + StatusCode::NOT_IMPLEMENTED, + error_body(None, "this server has no engine to reconfigure"), + ); + }; + let (answer, response) = tokio::sync::oneshot::channel(); + if control + .send(Control::Reconfigure { + settings: settings.to_string(), + reply: answer, + }) + .await + .is_err() + { + return reply( + StatusCode::SERVICE_UNAVAILABLE, + error_body(None, "the worker is gone"), + ); + } + match tokio::time::timeout(std::time::Duration::from_secs(1900), response).await { + Ok(Ok(Ok(effective))) => { + let settings: Value = serde_json::from_str(&effective).unwrap_or(Value::Null); + reply( + StatusCode::OK, + json!({"status": "reconfigured", "settings": settings}), + ) + } + Ok(Ok(Err((status, message)))) => reply( + StatusCode::from_u16(status).unwrap_or(StatusCode::INTERNAL_SERVER_ERROR), + error_body(Some("reconfigure_refused"), &message), + ), + _ => reply( + StatusCode::GATEWAY_TIMEOUT, + error_body(None, "the engine did not answer the reconfigure in time"), + ), + } +} + +/// `GET /api/requests`: the request monitor (`api_monitor` in the config; 404 while it is off, as in the Original). Without +/// `id` the retained requests, newest first, without prompts and answers; with `?id=` one whole record, or 404 once evicted. +pub async fn api_requests(State(state): State, RawQuery(query): RawQuery) -> Response { + if !state.monitor.enabled() { + return not_found().await; + } + let id = query.as_deref().and_then(|query| { + query + .split('&') + .find_map(|pair| pair.strip_prefix("id=").map(|id| id.to_owned())) + }); + if let Some(id) = id { + return match state.monitor.detail(&id) { + Some(record) => reply(StatusCode::OK, record), + None => reply( + StatusCode::NOT_FOUND, + error_body(None, "request no longer retained"), + ), + }; + } + let worker = *state.worker.read().await; + reply( + StatusCode::OK, + json!({"requests": state.monitor.summaries(), "retention": crate::request_monitor::RETENTION, "persistent": false, + "loaded": is_loaded(&worker), "auto_load": state.control.is_some()}), + ) +} + +/// Unknown paths: a JSON error, like the Original's `{"error": {"message": "not found"}}`. +pub async fn not_found() -> Response { + reply(StatusCode::NOT_FOUND, error_body(None, "not found")) +} + +// ------------------------------------------------------------------------------------------------ CORS + +/// CORS for `/v1/*` (config `cors_origins`) and the preflight: the outermost layer, so a browser's +/// credential-less `OPTIONS` is answered before authentication, as the Original does. +pub async fn cors_layer(State(cors): State>, request: Request, next: Next) -> Response { + let target = request.uri().path_and_query().map_or_else( + || request.uri().path().to_owned(), + |p| p.as_str().to_owned(), + ); + let headers = cors.headers( + &target, + header_str(request.headers(), "origin"), + header_str(request.headers(), "access-control-request-headers"), + ); + let mut response = if request.method() == Method::OPTIONS { + let mut response = StatusCode::NO_CONTENT.into_response(); + response + .headers_mut() + .insert(header::CONTENT_LENGTH, HeaderValue::from_static("0")); + response + } else { + next.run(request).await + }; + for (name, value) in headers { + if let (Ok(name), Ok(value)) = ( + HeaderName::from_bytes(name.as_bytes()), + HeaderValue::from_str(&value), + ) { + response.headers_mut().insert(name, value); + } + } + response +} + +/// `GET /mcp`: the configured MCP servers, their state and tools (empty when there are none). +pub async fn mcp_status(State(state): State) -> Response { + let body = match &state.mcp { + Some(hub) => hub.status().await, + None => json!({"servers": [], "tools": 0}), + }; + reply(StatusCode::OK, body) +} + +/// `machine` of `GET /v1/status`: the engine's telemetry (GPU load and VRAM, RAM, CPU cores, throughput, cache hits, context) +/// when it reports any; the legacy `{at, gpu, ram}` shape with nulls otherwise. +pub(super) fn machine_view(memory: &crate::memory_view::MemoryView) -> Value { + let mut view = memory.telemetry_status(); + if !view.is_object() { + return json!({"at": now_s(), "gpu": null, "ram": null}); + } + view["at"] = json!(now_s()); + view +} diff --git a/control-plane/src/server_api/slots.rs b/control-plane/src/server_api/slots.rs new file mode 100644 index 00000000..e4fdee61 --- /dev/null +++ b/control-plane/src/server_api/slots.rs @@ -0,0 +1,244 @@ +//! Moved out of the parent module by STRA-338: fn slots, fn v1_prefix_match, fn v1_status, fn status_value, fn settings_get, fn own_page_check .... + +#[allow(unused_imports)] +use super::*; + +/// `GET /slots`: one slot while the engine is loaded, none otherwise. +pub async fn slots(State(state): State) -> Response { + let worker = *state.worker.read().await; + if !is_loaded(&worker) { + return reply(StatusCode::OK, json!([])); + } + reply( + StatusCode::OK, + json!([{"id": 0, "n_ctx": context_of(&worker), + "is_processing": is_busy(&state, &worker)}]), + ) +} + +/// `POST /v1/prefix_match`: how many tokens of a prompt this runtime's prefix cache holds, for a pool router. +/// Body `{"block_hashes": ["<16 hex>", ...], "namespace": "<16 hex>"}`: the chain values of the prompt's full blocks in order +/// (see `docs/prefix-cache.md`); `namespace` is optional. The answer comes from the engine's last summary. +pub async fn v1_prefix_match(State(state): State, body: Bytes) -> Response { + let parsed: Result = serde_json::from_slice(&body); + let Ok(request) = parsed else { + return reply( + StatusCode::BAD_REQUEST, + json!({"error": {"message": "the body must be a JSON object", "type": "invalid_request"}}), + ); + }; + let hashes: Option> = request["block_hashes"] + .as_array() + .and_then(|list| list.iter().map(|h| h.as_str().map(str::to_owned)).collect()); + let Some(hashes) = hashes else { + return reply( + StatusCode::BAD_REQUEST, + json!({"error": {"message": "block_hashes must be an array of hex strings", "type": "invalid_request"}}), + ); + }; + match state + .prefix_cache + .prefix_match(request["namespace"].as_str(), &hashes) + { + Ok(answer) => reply(StatusCode::OK, answer), + Err(error) => reply( + StatusCode::BAD_REQUEST, + json!({"error": {"message": format!("{error:?}: at most {} lowercase-hex 16-digit chain values", crate::prefix_view::MAX_HASHES), "type": "invalid_request"}}), + ), + } +} + +/// `GET /v1/status`: what this server is and does, for a client that would rather ask than guess. +pub async fn v1_status(State(state): State) -> Response { + reply(StatusCode::OK, status_value(&state).await) +} + +pub(super) async fn status_value(state: &AppState) -> Value { + let worker = *state.worker.read().await; + let lifecycle = state.lifecycle.snapshot(); + let busy = worker.metrics.active_since.is_some(); + let queued = lifecycle.generation_jobs.saturating_sub(usize::from(busy)); + let context = context_of(&worker); + let last_at = worker + .last_activity + .map(|at| now_s().saturating_sub(at.elapsed().as_secs())); + let started = state + .started_at + .duration_since(UNIX_EPOCH) + .map_or(0, |d| d.as_secs()); + let timings = worker.metrics.last_done.map(|done| { + let mut value = leleka_serving_policy::timings::request_timings( + &leleka_serving_policy::timings::Last { + prompt_tokens: done.prompt_tokens, + generated: done.generated_tokens, + prompt_ms: done.prefill_ms, + decode_ms: done.decode_ms, + reused: done.reused_tokens, + drafts_offered: done.drafts_offered, + drafts_accepted: done.drafts_accepted, + }, + done.generated_tokens, + ); + value["at"] = json!(now_s()); + value + }); + let mut body = json!({ + "service": "strata", "model": state.model, + "loaded": is_loaded(&worker), "auto_load": state.control.is_some(), + "structured_output": {"formats": ["json_object", "json_schema"], "method": "prompt_and_validate", + "constrained_decoding": false, "stream_buffered": true}, + "engine": env!("CARGO_PKG_VERSION"), + "started": started, + "uptime_s": state.started_at.elapsed().map_or(0, |d| d.as_secs()), + "cache_max_tokens": context, + "context": {"native": context, "max_positions": context}, + "concurrency": {"serving": 1, "requested": 1}, + "dialects": ["/v1/chat/completions", "/v1/messages", "/v1/responses"], + "vision": {"enabled": state.vision.is_some(), "available": state.vision.is_some(), "error": null}, + "activity": {"requests": worker.metrics.started, "in_flight": usize::from(busy) + queued, + "last_request_at": last_at}, + "last_timings": timings, + "machine": machine_view(&state.memory), + "memory": state.memory.status(), + }); + // Present only when a prefix cache exists: the Python server's status has no such key (golden http_surface). + let prefix = json!(state.prefix_cache.status()); + if !prefix.is_null() { + body["prefix_cache"] = prefix; + } + body +} + +/// `GET /settings`. +pub async fn settings_get(State(state): State) -> Response { + let shared = state.settings.shared(); + reply( + StatusCode::OK, + json!({"shared": !shared.is_empty(), "defaults": shared.to_json()}), + ) +} + +pub(super) fn own_page_check( + state: &AppState, + headers: &HeaderMap, + what: &str, +) -> Result<(), Box> { + own_page( + what, + header_str(headers, "content-type"), + header_str(headers, "origin"), + header_str(headers, "host"), + &state.trusted_origins, + ) + .map_err(|e| { + Box::new(reply( + StatusCode::from_u16(e.status()).unwrap_or(StatusCode::FORBIDDEN), + error_body(None, &e.message()), + )) + }) +} + +/// `POST /settings`: replace the Chat settings every client gets for what it leaves out. They change +/// what every client gets, so only the app's own page may set them. +pub async fn settings_post( + State(state): State, + headers: HeaderMap, + body: Bytes, +) -> Response { + if let Err(response) = own_page_check(&state, &headers, "settings can be changed") { + return *response; + } + let value: Value = if body.is_empty() { + json!({}) + } else { + match serde_json::from_slice(&body) { + Ok(value) => value, + Err(error) => { + return reply( + StatusCode::BAD_REQUEST, + error_body(Some("invalid_request_error"), &error.to_string()), + ); + } + } + }; + let defaults = value.get("defaults").cloned().unwrap_or(Value::Null); + match state.settings.set_shared(&defaults) { + Ok(shared) => { + if shared.is_empty() { + crate::elog!("other apps use their own settings again"); + } else { + crate::elog!("other apps now use the Chat settings: {}", shared.to_json()); + } + reply( + StatusCode::OK, + json!({"shared": !shared.is_empty(), "defaults": shared.to_json()}), + ) + } + Err(message) => reply( + StatusCode::BAD_REQUEST, + error_body(Some("invalid_request_error"), &message), + ), + } +} + +/// `POST /unload`: give the GPU back now (between requests). +pub async fn unload_post(State(state): State) -> Response { + let outcome = unload(&state, None).await; + reply( + if outcome == Outcome::Busy { + StatusCode::CONFLICT + } else { + StatusCode::OK + }, + json!({"status": outcome.as_str()}), + ) +} + +/// `POST /load`: load now, e.g. ahead of a request. +pub async fn load_post(State(state): State) -> Response { + state.worker.write().await.last_activity = Some(tokio::time::Instant::now()); + if state.worker.read().await.state == WorkerState::Ready { + return reply(StatusCode::OK, json!({"status": "loaded"})); + } + match load(&state).await { + Ok(()) => reply(StatusCode::OK, json!({"status": "loaded"})), + Err(error) => load_error_response(&error), + } +} + +/// The shared prelude of `POST /v1/load` and `/v1/unload`: a JSON object body, own page only, and +/// the right model. +pub(super) fn model_control_prelude( + state: &AppState, + headers: &HeaderMap, + body: &Bytes, +) -> Result<(), Box> { + let value: Value = if body.is_empty() { + json!({}) + } else { + serde_json::from_slice(body).map_err(|error| { + Box::new(reply( + StatusCode::BAD_REQUEST, + error_body(Some("invalid_request_error"), &error.to_string()), + )) + })? + }; + let Some(object) = value.as_object() else { + return Err(Box::new(reply( + StatusCode::BAD_REQUEST, + error_body(Some("invalid_request_error"), "send a JSON object"), + ))); + }; + own_page_check(state, headers, "the model can be loaded or unloaded")?; + match object.get("model") { + None | Some(Value::Null) => {} + Some(Value::String(name)) if state.model.as_deref() == Some(name.as_str()) => {} + Some(_) => { + return Err(Box::new(reply( + StatusCode::NOT_FOUND, + error_body(None, "model not found"), + ))); + } + } + Ok(()) +} diff --git a/control-plane/src/service_install.rs b/control-plane/src/service_install.rs index 134690c0..50fd80cb 100644 --- a/control-plane/src/service_install.rs +++ b/control-plane/src/service_install.rs @@ -14,372 +14,8 @@ struct Options { enable: bool, } -fn parse(args: &[String]) -> Result { - let mut values = std::collections::BTreeMap::new(); - let mut start = false; - let mut enable = false; - let mut args = args.iter(); - while let Some(flag) = args.next() { - if flag == "--start" && !start { - start = true; - } else if flag == "--enable" && !enable { - enable = true; - } else if matches!( - flag.as_str(), - "--config" | "--working-dir" | "--env-file" | "--unit" - ) { - let value = args.next().ok_or(USAGE)?; - if values.insert(flag.as_str(), value).is_some() { - return Err(USAGE.into()); - } - } else { - return Err(USAGE.into()); - } - } - let unit = values - .get("--unit") - .map(|s| s.as_str()) - .unwrap_or("strata-next.service"); - validate_name(unit)?; - Ok(Options { - config: PathBuf::from(values.get("--config").ok_or(USAGE)?), - working_dir: PathBuf::from(values.get("--working-dir").ok_or(USAGE)?), - env_file: values.get("--env-file").map(PathBuf::from), - unit: unit.into(), - start, - enable, - }) -} - -fn validate_name(name: &str) -> Result<(), String> { - let suffix = name - .strip_prefix("strata-next") - .and_then(|s| s.strip_suffix(".service")); - if name.len() <= 120 - && suffix.is_some_and(|s| { - s.is_empty() - || (s.starts_with('-') - && s.len() > 1 - && s[1..] - .bytes() - .all(|b| b.is_ascii_alphanumeric() || b == b'-' || b == b'_')) - }) - { - Ok(()) - } else { - Err("unit must be strata-next.service or strata-next-NAME.service (ASCII letters, digits, dash, underscore)".into()) - } -} - -fn install_options(args: &[String]) -> Result<(Options, Option>), String> { - let mut service = Vec::new(); - let mut readiness = Vec::new(); - let mut start_ready = false; - let mut args = args.iter(); - while let Some(flag) = args.next() { - if flag == "--start-ready" { - if start_ready { - return Err(INSTALL_READY_USAGE.into()); - } - start_ready = true; - } else if matches!( - flag.as_str(), - "--ready-url" | "--ready-model" | "--ready-key-file" | "--ready-timeout-s" - ) { - readiness.push(flag.replacen("--ready-", "--", 1)); - readiness.push(args.next().ok_or(INSTALL_READY_USAGE)?.clone()); - } else { - service.push(flag.clone()); - if matches!( - flag.as_str(), - "--config" | "--working-dir" | "--env-file" | "--unit" - ) { - service.push(args.next().ok_or(USAGE)?.clone()); - } - } - } - let mut options = parse(&service)?; - if start_ready { - if options.start { - return Err(INSTALL_READY_USAGE.into()); - } - crate::wait_ready::validate(&readiness)?; - options.start = true; - } else if !readiness.is_empty() { - return Err(INSTALL_READY_USAGE.into()); - } - Ok((options, start_ready.then_some(readiness))) -} - -fn ready_control_args(options: &Options, readiness: &[String]) -> Vec { - let mut args = vec![ - "start-ready".into(), - "--config".into(), - options.config.to_string_lossy().into_owned(), - "--working-dir".into(), - options.working_dir.to_string_lossy().into_owned(), - "--unit".into(), - options.unit.clone(), - ]; - if let Some(file) = &options.env_file { - args.extend(["--env-file".into(), file.to_string_lossy().into_owned()]); - } - for [flag, value] in readiness.as_chunks::<2>().0 { - args.extend([flag.replacen("--", "--ready-", 1), value.clone()]); - } - args -} - const CONTROL_USAGE: &str = "usage: strata-next service-control status|start|stop|restart|enable|disable|start-ready|restart-ready|drain-stop|resume --config ABSOLUTE_FILE --working-dir ABSOLUTE_DIR [--env-file ABSOLUTE_FILE] [--unit strata-next[-NAME].service] [--ready-url LOOPBACK_ORIGIN --ready-model ID [--ready-key-file FILE] [--ready-timeout-s N]]"; -fn control_options(args: &[String]) -> Result<(&str, Options, Option>), String> { - let (action, args) = args.split_first().ok_or(CONTROL_USAGE)?; - if !matches!( - action.as_str(), - "status" - | "start" - | "stop" - | "restart" - | "enable" - | "disable" - | "start-ready" - | "restart-ready" - | "drain-stop" - | "resume" - ) { - return Err(CONTROL_USAGE.into()); - } - let mut service_args = Vec::new(); - let mut readiness_args = Vec::new(); - let mut args = args.iter(); - while let Some(flag) = args.next() { - if matches!( - flag.as_str(), - "--ready-url" | "--ready-model" | "--ready-key-file" | "--ready-timeout-s" - ) { - readiness_args.push(flag.replacen("--ready-", "--", 1)); - readiness_args.push(args.next().ok_or(CONTROL_USAGE)?.clone()); - } else { - service_args.push(flag.clone()); - if matches!( - flag.as_str(), - "--config" | "--working-dir" | "--env-file" | "--unit" - ) { - service_args.push(args.next().ok_or(CONTROL_USAGE)?.clone()); - } - } - } - let ready = matches!( - action.as_str(), - "start-ready" | "restart-ready" | "drain-stop" | "resume" - ); - if ready { - crate::wait_ready::validate(&readiness_args)?; - } else if !readiness_args.is_empty() { - return Err(CONTROL_USAGE.into()); - } - let options = - parse(&service_args).map_err(|e| if e == USAGE { CONTROL_USAGE.into() } else { e })?; - if options.start || options.enable { - return Err(CONTROL_USAGE.into()); - } - Ok((action, options, ready.then_some(readiness_args))) -} - -#[cfg(unix)] -fn unit_directory() -> Result { - let config = match std::env::var_os("XDG_CONFIG_HOME") { - Some(value) if !value.is_empty() => PathBuf::from(value), - _ => PathBuf::from(std::env::var_os("HOME").ok_or("HOME is missing")?).join(".config"), - }; - if !config.is_absolute() { - return Err("user config directory must be absolute".into()); - } - Ok(config.join("systemd/user")) -} - -pub async fn control(args: &[String]) -> Result { - let (action, options, readiness_args) = control_options(args)?; - if !cfg!(target_os = "linux") { - return Err("service-control requires Linux with a running systemd user manager".into()); - } - let waiter = readiness_args - .as_ref() - .map(|args| crate::wait_ready::Waiter::new(args)) - .transpose()?; - #[cfg(unix)] - { - let content = crate::service_unit::render( - &std::env::current_exe().map_err(|e| e.to_string())?, - &options.config, - &options.working_dir, - options.env_file.as_deref(), - )?; - let directory = unit_directory()?; - unix::check_directory(&directory)?; - let path = directory.join(&options.unit); - unix::same_file(&path, content.as_bytes()) - .map_err(|e| format!("refusing service control: {e}; use the installed executable and exact unit configuration"))?; - unix::verify_loaded_unit(&options.unit, &path).await?; - if matches!(action, "enable" | "disable") { - unix::check_activation_link(&path)?; - } - if matches!(action, "drain-stop" | "resume") { - let manager = unix::status(&options.unit).await?; - let pid = active_pid(&manager)?; - let admission = waiter.ok_or("missing lifecycle client")?.admission(pid, action == "drain-stop").await - .map_err(|e| format!("{e}; no manager stop requested; admission may have changed, reconcile explicitly"))?; - unix::same_file(&path, content.as_bytes()) - .map_err(|_| "unit changed during drain; no stop requested")?; - unix::verify_loaded_unit(&options.unit, &path).await?; - let current = unix::status(&options.unit).await?; - if active_pid(¤t)? != pid { - return Err( - "managed process changed; no stop requested, reconcile admission explicitly" - .into(), - ); - } - let manager = if action == "drain-stop" { - unix::systemctl("stop", &options.unit, std::time::Duration::from_secs(60)) - .await - .map_err(|e| { - format!("{e}; stop may be pending; inspect status before retrying") - })?; - unix::status(&options.unit).await? - } else { - current - }; - if action == "drain-stop" - && (manager["main_pid"] != 0 || manager["active_state"] != "inactive") - { - return Err( - "stop was requested but service is not inactive; reconcile explicitly".into(), - ); - } - return Ok( - serde_json::json!({"unit":options.unit,"action":action,"manager":manager, - "action_requested":true,"model_readiness":"not_checked", "admission":admission}), - ); - } - if action != "status" { - let manager_action = match action { - "start-ready" => "start", - "restart-ready" => "restart", - other => other, - }; - unix::systemctl(manager_action, &options.unit, std::time::Duration::from_secs(60)).await - .map_err(|e| format!("{e}; manager action may be pending; inspect service-control status before retrying"))?; - } - if matches!(action, "enable" | "disable") { - unix::verify_loaded_unit(&options.unit, &path) - .await - .map_err(|e| { - format!( - "{e}; {action} was requested; reconcile identity before further control" - ) - })?; - } - let manager = unix::status(&options.unit).await.map_err(|e| { - format!("{e}; {action} outcome needs reconciliation; no action was replayed") - })?; - let mut result = serde_json::json!({"unit":options.unit,"action":action,"manager":manager, - "action_requested":action != "status", "model_readiness":"not_checked"}); - if let Some(waiter) = waiter { - let pid = active_pid(&manager)?; - let readiness = waiter.wait(Some(pid)).await.map_err(|error| format!( - "{error}; {action} was requested; service left for explicit reconciliation, no lifecycle action was replayed" - ))?; - unix::same_file(&path, content.as_bytes()) - .map_err(|_| "unit changed during readiness wait; reconcile explicitly")?; - unix::verify_loaded_unit(&options.unit, &path).await?; - let current = unix::status(&options.unit).await?; - if active_pid(¤t)? != pid { - return Err( - "managed process changed during readiness wait; reconcile explicitly".into(), - ); - } - result["manager"] = current; - result["model_readiness"] = serde_json::json!("ready"); - result["readiness"] = readiness; - } - Ok(result) - } - #[cfg(not(unix))] - Err("service-control requires Linux".into()) -} - -fn active_pid(manager: &serde_json::Value) -> Result { - if manager["active_state"] != "active" || manager["sub_state"] != "running" { - return Err("managed service is not running; readiness cannot be confirmed".into()); - } - manager["main_pid"] - .as_u64() - .and_then(|n| u32::try_from(n).ok()) - .filter(|n| *n > 0) - .ok_or_else(|| "managed service has no valid active PID".into()) -} - -pub async fn run(args: &[String]) -> Result { - let (options, readiness) = install_options(args)?; - // Validate private credentials and client policy before publishing anything. - if let Some(args) = &readiness { - let _ = crate::wait_ready::Waiter::new(args)?; - } - let content = crate::service_unit::render( - &std::env::current_exe().map_err(|e| e.to_string())?, - &options.config, - &options.working_dir, - options.env_file.as_deref(), - )?; - if !cfg!(target_os = "linux") { - return Err("service-install requires Linux with a running systemd user manager".into()); - } - #[cfg(unix)] - { - let directory = unit_directory()?; - let path = directory.join(&options.unit); - let created = unix::publish(&directory, &options.unit, content.as_bytes())?; - let mut actions = vec!["daemon-reload"]; - if options.enable { - actions.push("enable"); - } - if options.start && readiness.is_none() { - actions.push("start"); - } - for action in actions { - if matches!(action, "start" | "enable") { - unix::verify_loaded_unit(&options.unit, &path) - .await - .map_err(|e| { - format!( - "{e}; unit retained at {}; {action} was not requested", - path.display() - ) - })?; - } - if action == "enable" { - unix::check_activation_link(&path)?; - } - unix::systemctl(action, &options.unit, std::time::Duration::from_secs(30)).await - .map_err(|e| format!("{e}; unit retained at {} for explicit retry. Activation may be pending; inspect systemctl --user status {}. Model readiness has not been checked", path.display(), options.unit))?; - if action == "enable" { - unix::verify_loaded_unit(&options.unit, &path).await?; - } - } - let mut result = serde_json::json!({"unit":options.unit,"path":path,"created":created,"reused":!created,"daemon_reloaded":true,"start_requested":options.start,"model_readiness":"not_checked","enable_requested":options.enable}); - if let Some(readiness) = readiness { - let started = control(&ready_control_args(&options, &readiness)).await - .map_err(|error| format!("{error}; installed unit retained at {}; inspect status before another lifecycle action",path.display()))?; - result["model_readiness"] = started["model_readiness"].clone(); - result["manager"] = started["manager"].clone(); - result["readiness"] = started["readiness"].clone(); - } - Ok(result) - } - #[cfg(not(unix))] - Err("service-install requires Linux".into()) -} - #[cfg(unix)] mod unix { use super::*; @@ -791,3 +427,10 @@ mod unix { #[cfg(test)] mod tests; + +mod parse; +#[allow(unused_imports)] +pub use parse::*; +mod control; +#[allow(unused_imports)] +pub use control::*; diff --git a/control-plane/src/service_install/control.rs b/control-plane/src/service_install/control.rs new file mode 100644 index 00000000..9aba354d --- /dev/null +++ b/control-plane/src/service_install/control.rs @@ -0,0 +1,186 @@ +//! Moved out of the parent module by STRA-338: fn control, fn active_pid, fn run. + +#[allow(unused_imports)] +use super::*; + +pub async fn control(args: &[String]) -> Result { + let (action, options, readiness_args) = control_options(args)?; + if !cfg!(target_os = "linux") { + return Err("service-control requires Linux with a running systemd user manager".into()); + } + let waiter = readiness_args + .as_ref() + .map(|args| crate::wait_ready::Waiter::new(args)) + .transpose()?; + #[cfg(unix)] + { + let content = crate::service_unit::render( + &std::env::current_exe().map_err(|e| e.to_string())?, + &options.config, + &options.working_dir, + options.env_file.as_deref(), + )?; + let directory = unit_directory()?; + unix::check_directory(&directory)?; + let path = directory.join(&options.unit); + unix::same_file(&path, content.as_bytes()) + .map_err(|e| format!("refusing service control: {e}; use the installed executable and exact unit configuration"))?; + unix::verify_loaded_unit(&options.unit, &path).await?; + if matches!(action, "enable" | "disable") { + unix::check_activation_link(&path)?; + } + if matches!(action, "drain-stop" | "resume") { + let manager = unix::status(&options.unit).await?; + let pid = active_pid(&manager)?; + let admission = waiter.ok_or("missing lifecycle client")?.admission(pid, action == "drain-stop").await + .map_err(|e| format!("{e}; no manager stop requested; admission may have changed, reconcile explicitly"))?; + unix::same_file(&path, content.as_bytes()) + .map_err(|_| "unit changed during drain; no stop requested")?; + unix::verify_loaded_unit(&options.unit, &path).await?; + let current = unix::status(&options.unit).await?; + if active_pid(¤t)? != pid { + return Err( + "managed process changed; no stop requested, reconcile admission explicitly" + .into(), + ); + } + let manager = if action == "drain-stop" { + unix::systemctl("stop", &options.unit, std::time::Duration::from_secs(60)) + .await + .map_err(|e| { + format!("{e}; stop may be pending; inspect status before retrying") + })?; + unix::status(&options.unit).await? + } else { + current + }; + if action == "drain-stop" + && (manager["main_pid"] != 0 || manager["active_state"] != "inactive") + { + return Err( + "stop was requested but service is not inactive; reconcile explicitly".into(), + ); + } + return Ok( + serde_json::json!({"unit":options.unit,"action":action,"manager":manager, + "action_requested":true,"model_readiness":"not_checked", "admission":admission}), + ); + } + if action != "status" { + let manager_action = match action { + "start-ready" => "start", + "restart-ready" => "restart", + other => other, + }; + unix::systemctl(manager_action, &options.unit, std::time::Duration::from_secs(60)).await + .map_err(|e| format!("{e}; manager action may be pending; inspect service-control status before retrying"))?; + } + if matches!(action, "enable" | "disable") { + unix::verify_loaded_unit(&options.unit, &path) + .await + .map_err(|e| { + format!( + "{e}; {action} was requested; reconcile identity before further control" + ) + })?; + } + let manager = unix::status(&options.unit).await.map_err(|e| { + format!("{e}; {action} outcome needs reconciliation; no action was replayed") + })?; + let mut result = serde_json::json!({"unit":options.unit,"action":action,"manager":manager, + "action_requested":action != "status", "model_readiness":"not_checked"}); + if let Some(waiter) = waiter { + let pid = active_pid(&manager)?; + let readiness = waiter.wait(Some(pid)).await.map_err(|error| format!( + "{error}; {action} was requested; service left for explicit reconciliation, no lifecycle action was replayed" + ))?; + unix::same_file(&path, content.as_bytes()) + .map_err(|_| "unit changed during readiness wait; reconcile explicitly")?; + unix::verify_loaded_unit(&options.unit, &path).await?; + let current = unix::status(&options.unit).await?; + if active_pid(¤t)? != pid { + return Err( + "managed process changed during readiness wait; reconcile explicitly".into(), + ); + } + result["manager"] = current; + result["model_readiness"] = serde_json::json!("ready"); + result["readiness"] = readiness; + } + Ok(result) + } + #[cfg(not(unix))] + Err("service-control requires Linux".into()) +} + +pub(super) fn active_pid(manager: &serde_json::Value) -> Result { + if manager["active_state"] != "active" || manager["sub_state"] != "running" { + return Err("managed service is not running; readiness cannot be confirmed".into()); + } + manager["main_pid"] + .as_u64() + .and_then(|n| u32::try_from(n).ok()) + .filter(|n| *n > 0) + .ok_or_else(|| "managed service has no valid active PID".into()) +} + +pub async fn run(args: &[String]) -> Result { + let (options, readiness) = install_options(args)?; + // Validate private credentials and client policy before publishing anything. + if let Some(args) = &readiness { + let _ = crate::wait_ready::Waiter::new(args)?; + } + let content = crate::service_unit::render( + &std::env::current_exe().map_err(|e| e.to_string())?, + &options.config, + &options.working_dir, + options.env_file.as_deref(), + )?; + if !cfg!(target_os = "linux") { + return Err("service-install requires Linux with a running systemd user manager".into()); + } + #[cfg(unix)] + { + let directory = unit_directory()?; + let path = directory.join(&options.unit); + let created = unix::publish(&directory, &options.unit, content.as_bytes())?; + let mut actions = vec!["daemon-reload"]; + if options.enable { + actions.push("enable"); + } + if options.start && readiness.is_none() { + actions.push("start"); + } + for action in actions { + if matches!(action, "start" | "enable") { + unix::verify_loaded_unit(&options.unit, &path) + .await + .map_err(|e| { + format!( + "{e}; unit retained at {}; {action} was not requested", + path.display() + ) + })?; + } + if action == "enable" { + unix::check_activation_link(&path)?; + } + unix::systemctl(action, &options.unit, std::time::Duration::from_secs(30)).await + .map_err(|e| format!("{e}; unit retained at {} for explicit retry. Activation may be pending; inspect systemctl --user status {}. Model readiness has not been checked", path.display(), options.unit))?; + if action == "enable" { + unix::verify_loaded_unit(&options.unit, &path).await?; + } + } + let mut result = serde_json::json!({"unit":options.unit,"path":path,"created":created,"reused":!created,"daemon_reloaded":true,"start_requested":options.start,"model_readiness":"not_checked","enable_requested":options.enable}); + if let Some(readiness) = readiness { + let started = control(&ready_control_args(&options, &readiness)).await + .map_err(|error| format!("{error}; installed unit retained at {}; inspect status before another lifecycle action",path.display()))?; + result["model_readiness"] = started["model_readiness"].clone(); + result["manager"] = started["manager"].clone(); + result["readiness"] = started["readiness"].clone(); + } + Ok(result) + } + #[cfg(not(unix))] + Err("service-install requires Linux".into()) +} diff --git a/control-plane/src/service_install/parse.rs b/control-plane/src/service_install/parse.rs new file mode 100644 index 00000000..ad9849a7 --- /dev/null +++ b/control-plane/src/service_install/parse.rs @@ -0,0 +1,188 @@ +//! Moved out of the parent module by STRA-338: fn parse, fn validate_name, fn install_options, fn ready_control_args, fn control_options, fn unit_directory. + +#[allow(unused_imports)] +use super::*; + +pub(super) fn parse(args: &[String]) -> Result { + let mut values = std::collections::BTreeMap::new(); + let mut start = false; + let mut enable = false; + let mut args = args.iter(); + while let Some(flag) = args.next() { + if flag == "--start" && !start { + start = true; + } else if flag == "--enable" && !enable { + enable = true; + } else if matches!( + flag.as_str(), + "--config" | "--working-dir" | "--env-file" | "--unit" + ) { + let value = args.next().ok_or(USAGE)?; + if values.insert(flag.as_str(), value).is_some() { + return Err(USAGE.into()); + } + } else { + return Err(USAGE.into()); + } + } + let unit = values + .get("--unit") + .map(|s| s.as_str()) + .unwrap_or("strata-next.service"); + validate_name(unit)?; + Ok(Options { + config: PathBuf::from(values.get("--config").ok_or(USAGE)?), + working_dir: PathBuf::from(values.get("--working-dir").ok_or(USAGE)?), + env_file: values.get("--env-file").map(PathBuf::from), + unit: unit.into(), + start, + enable, + }) +} + +pub(super) fn validate_name(name: &str) -> Result<(), String> { + let suffix = name + .strip_prefix("strata-next") + .and_then(|s| s.strip_suffix(".service")); + if name.len() <= 120 + && suffix.is_some_and(|s| { + s.is_empty() + || (s.starts_with('-') + && s.len() > 1 + && s[1..] + .bytes() + .all(|b| b.is_ascii_alphanumeric() || b == b'-' || b == b'_')) + }) + { + Ok(()) + } else { + Err("unit must be strata-next.service or strata-next-NAME.service (ASCII letters, digits, dash, underscore)".into()) + } +} + +pub(super) fn install_options(args: &[String]) -> Result<(Options, Option>), String> { + let mut service = Vec::new(); + let mut readiness = Vec::new(); + let mut start_ready = false; + let mut args = args.iter(); + while let Some(flag) = args.next() { + if flag == "--start-ready" { + if start_ready { + return Err(INSTALL_READY_USAGE.into()); + } + start_ready = true; + } else if matches!( + flag.as_str(), + "--ready-url" | "--ready-model" | "--ready-key-file" | "--ready-timeout-s" + ) { + readiness.push(flag.replacen("--ready-", "--", 1)); + readiness.push(args.next().ok_or(INSTALL_READY_USAGE)?.clone()); + } else { + service.push(flag.clone()); + if matches!( + flag.as_str(), + "--config" | "--working-dir" | "--env-file" | "--unit" + ) { + service.push(args.next().ok_or(USAGE)?.clone()); + } + } + } + let mut options = parse(&service)?; + if start_ready { + if options.start { + return Err(INSTALL_READY_USAGE.into()); + } + crate::wait_ready::validate(&readiness)?; + options.start = true; + } else if !readiness.is_empty() { + return Err(INSTALL_READY_USAGE.into()); + } + Ok((options, start_ready.then_some(readiness))) +} + +pub(super) fn ready_control_args(options: &Options, readiness: &[String]) -> Vec { + let mut args = vec![ + "start-ready".into(), + "--config".into(), + options.config.to_string_lossy().into_owned(), + "--working-dir".into(), + options.working_dir.to_string_lossy().into_owned(), + "--unit".into(), + options.unit.clone(), + ]; + if let Some(file) = &options.env_file { + args.extend(["--env-file".into(), file.to_string_lossy().into_owned()]); + } + for [flag, value] in readiness.as_chunks::<2>().0 { + args.extend([flag.replacen("--", "--ready-", 1), value.clone()]); + } + args +} + +pub(super) fn control_options( + args: &[String], +) -> Result<(&str, Options, Option>), String> { + let (action, args) = args.split_first().ok_or(CONTROL_USAGE)?; + if !matches!( + action.as_str(), + "status" + | "start" + | "stop" + | "restart" + | "enable" + | "disable" + | "start-ready" + | "restart-ready" + | "drain-stop" + | "resume" + ) { + return Err(CONTROL_USAGE.into()); + } + let mut service_args = Vec::new(); + let mut readiness_args = Vec::new(); + let mut args = args.iter(); + while let Some(flag) = args.next() { + if matches!( + flag.as_str(), + "--ready-url" | "--ready-model" | "--ready-key-file" | "--ready-timeout-s" + ) { + readiness_args.push(flag.replacen("--ready-", "--", 1)); + readiness_args.push(args.next().ok_or(CONTROL_USAGE)?.clone()); + } else { + service_args.push(flag.clone()); + if matches!( + flag.as_str(), + "--config" | "--working-dir" | "--env-file" | "--unit" + ) { + service_args.push(args.next().ok_or(CONTROL_USAGE)?.clone()); + } + } + } + let ready = matches!( + action.as_str(), + "start-ready" | "restart-ready" | "drain-stop" | "resume" + ); + if ready { + crate::wait_ready::validate(&readiness_args)?; + } else if !readiness_args.is_empty() { + return Err(CONTROL_USAGE.into()); + } + let options = + parse(&service_args).map_err(|e| if e == USAGE { CONTROL_USAGE.into() } else { e })?; + if options.start || options.enable { + return Err(CONTROL_USAGE.into()); + } + Ok((action, options, ready.then_some(readiness_args))) +} + +#[cfg(unix)] +pub(super) fn unit_directory() -> Result { + let config = match std::env::var_os("XDG_CONFIG_HOME") { + Some(value) if !value.is_empty() => PathBuf::from(value), + _ => PathBuf::from(std::env::var_os("HOME").ok_or("HOME is missing")?).join(".config"), + }; + if !config.is_absolute() { + return Err("user config directory must be absolute".into()); + } + Ok(config.join("systemd/user")) +} diff --git a/control-plane/src/service_switch.rs b/control-plane/src/service_switch.rs index fb0c2afc..708b691e 100644 --- a/control-plane/src/service_switch.rs +++ b/control-plane/src/service_switch.rs @@ -20,12 +20,6 @@ struct Catalog { #[serde(default = "provision_budget")] provision_timeout_s: u64, } -fn provision_budget() -> u64 { - 3600 -} -fn ready_budget() -> u64 { - 300 -} #[derive(Deserialize)] #[serde(deny_unknown_fields)] struct Profile { @@ -38,144 +32,6 @@ struct Profile { #[serde(default = "ready_budget")] timeout_s: u64, } -impl Profile { - fn readiness(&self) -> Vec { - let mut args = vec![ - "--url".into(), - self.url.clone(), - "--model".into(), - self.model.clone(), - "--timeout-s".into(), - self.timeout_s.to_string(), - ]; - if let Some(key) = &self.key_file { - args.extend(["--key-file".into(), key.to_string_lossy().into_owned()]); - } - args - } - async fn control(&self, action: &str) -> Result { - let mut args = vec![ - action.into(), - "--config".into(), - self.config.to_string_lossy().into_owned(), - "--working-dir".into(), - self.working_dir.to_string_lossy().into_owned(), - "--unit".into(), - self.unit.clone(), - ]; - if matches!(action, "start-ready" | "drain-stop") { - let ready = self.readiness(); - for pair in ready.as_chunks::<2>().0 { - args.extend([pair[0].replacen("--", "--ready-", 1), pair[1].clone()]); - } - } - crate::service_install::control(&args).await - } -} -fn arguments(args: &[String]) -> Result, String> { - let mut values = BTreeMap::new(); - let mut iter = args.iter(); - while let Some(flag) = iter.next() { - if !matches!( - flag.as_str(), - "--catalog" | "--from" | "--to" | "--state-dir" - ) { - return Err(USAGE.into()); - } - if values - .insert(flag.clone(), iter.next().ok_or(USAGE)?.clone()) - .is_some() - { - return Err(USAGE.into()); - } - } - if !["--catalog", "--to", "--state-dir"] - .iter() - .all(|k| values.contains_key(*k)) - { - return Err(USAGE.into()); - } - for key in ["--from", "--to"] { - let Some(id) = values.get(key) else { continue }; - if id.is_empty() - || id.len() > 64 - || !id - .bytes() - .all(|b| b.is_ascii_alphanumeric() || b"-_".contains(&b)) - { - return Err("profile IDs need 1..64 ASCII letters, digits, dash or underscore".into()); - } - } - if values.get("--from") == values.get("--to") { - return Err("switch needs distinct previous and target profiles".into()); - } - Ok(values) -} -fn pid(value: &Value) -> Result { - if value["manager"]["active_state"] != "active" || value["manager"]["sub_state"] != "running" { - return Err("previous managed service is not running".into()); - } - value["manager"]["main_pid"] - .as_u64() - .and_then(|n| u32::try_from(n).ok()) - .filter(|n| *n > 0) - .ok_or_else(|| "previous service PID invalid".into()) -} -fn inactive(value: &Value) -> bool { - value["manager"]["main_pid"] == 0 && value["manager"]["active_state"] == "inactive" -} - -fn select_active(states: &[(String, Value)]) -> Result, String> { - let mut active = None; - for (id, state) in states { - if inactive(state) { - continue; - } - let running = pid(state).map_err(|_| "catalog contains a failed, transitional or unknown service; reconcile before selection")?; - if active.replace((id.clone(), running)).is_some() { - return Err("multiple catalog services are active; selection is ambiguous".into()); - } - } - Ok(active) -} - -async fn discover(catalog: &Catalog) -> Result, String> { - let mut states = Vec::new(); - for (id, profile) in &catalog.profiles { - states.push((id.clone(), profile.control("status").await?)); - } - select_active(&states) -} - -#[cfg(unix)] -fn validate_auto(catalog: &Catalog, target: &Profile) -> Result, String> { - use std::collections::BTreeSet; - let mut units = BTreeSet::new(); - let mut paths = BTreeSet::new(); - let mut digests = BTreeMap::new(); - for (id, profile) in &catalog.profiles { - if profile.key_file.as_ref().is_some_and(|k| !k.is_absolute()) { - return Err("catalog key_file paths must be absolute".into()); - } - let _ = crate::wait_ready::Waiter::new(&profile.readiness())?; - if !units.insert(&profile.unit) - || !paths.insert( - profile - .config - .canonicalize() - .map_err(|_| "cannot resolve catalog config")?, - ) - || reqwest::Url::parse(&profile.url).ok() != reqwest::Url::parse(&target.url).ok() - { - return Err( - "automatic selection needs distinct units/configs sharing one loopback origin" - .into(), - ); - } - digests.insert(id.clone(), storage::digest(&profile.config)?); - } - Ok(digests) -} #[cfg(unix)] mod storage { @@ -336,342 +192,15 @@ mod storage { } } -async fn prepare(profile: &Profile, budget: u64) -> Result<(), String> { - use std::process::Stdio; - let mut command = tokio::process::Command::new( - std::env::current_exe().map_err(|_| "cannot locate native executable")?, - ); - command - .arg("provision") - .arg("--config") - .arg(&profile.config) - .arg("--defer-memory-check") - .current_dir(&profile.working_dir) - .stdin(Stdio::null()) - .stdout(Stdio::null()) - .stderr(Stdio::null()) - .kill_on_drop(true); - for (key, _) in std::env::vars_os() { - if key.to_string_lossy().starts_with("STRATA_") { - command.env_remove(key); - } - } - let mut child = command - .spawn() - .map_err(|_| "cannot start target provision")?; - match tokio::time::timeout(Duration::from_secs(budget), child.wait()).await { - Ok(Ok(status)) if status.success() => Ok(()), - Ok(_) => Err("target provision failed before previous service drain".into()), - Err(_) => { - child - .kill() - .await - .map_err(|_| "provision timed out; kill/reap failed")?; - Err("target provision timed out before previous service drain".into()) - } - } -} - -pub async fn run(args: &[String]) -> Result { - if args.first().is_some_and(|arg| arg == "reconcile") { - return reconcile(&args[1..]).await; - } - let args = arguments(args)?; - if !cfg!(target_os = "linux") { - return Err("service-switch requires Linux systemd user services".into()); - } - #[cfg(unix)] - { - use storage::{Journal, digest, read}; - let bytes = read(Path::new(&args["--catalog"]), true, 65536)?; - let catalog: Catalog = - serde_json::from_slice(&bytes).map_err(|_| "invalid native service catalog")?; - if catalog.schema_version != 1 - || catalog.profiles.is_empty() - || catalog.profiles.len() > 16 - || !(1..=86400).contains(&catalog.provision_timeout_s) - { - return Err("invalid catalog version/count/provision budget".into()); - } - let to = &args["--to"]; - let new = catalog.profiles.get(to).ok_or("target profile absent")?; - let auto = !args.contains_key("--from"); - let auto_digests = if auto { - Some(validate_auto(&catalog, new)?) - } else { - None - }; - let mut journal = Journal::open( - Path::new(&args["--state-dir"]), - json!({"schema_version":1,"from":args.get("--from"),"to":to,"catalog_sha256":hex::encode(Sha256::digest(&bytes))}), - )?; - let discovered = if auto { - discover(&catalog).await? - } else { - None - }; - let from = args - .get("--from") - .cloned() - .or_else(|| discovered.as_ref().map(|(id, _)| id.clone())); - if auto && from.as_ref() == Some(to) { - let expected_pid = discovered.as_ref().unwrap().1; - let readiness = crate::wait_ready::Waiter::new(&new.readiness())? - .wait(Some(expected_pid)) - .await?; - if discover(&catalog).await? != discovered - || Some(validate_auto(&catalog, new)?) != auto_digests - { - return Err("catalog changed during readiness; selection refused".into()); - } - journal.value["from"] = json!(to); - journal.phase("reused")?; - return Ok(json!({"profile":to,"reused":true,"switched":false,"readiness":readiness})); - } - if from.is_none() { - journal.value["target_config_sha256"] = json!(digest(&new.config)?); - journal.phase("preparing")?; - if let Err(error) = prepare(new, catalog.provision_timeout_s).await { - journal.phase("preflight_failed")?; - return Err(error); - } - if discover(&catalog).await?.is_some() - || Some(validate_auto(&catalog, new)?) != auto_digests - { - journal.phase("needs_reconciliation")?; - return Err("catalog changed during cold preparation; target not started".into()); - } - journal.phase("starting_target")?; - if let Ok(target) = new.control("start-ready").await { - journal.phase("committed")?; - return Ok( - json!({"profile":to,"cold_started":true,"switched":false,"manager":target["manager"],"readiness":target["readiness"]}), - ); - } - journal.phase("stopping_failed_target")?; - if !new.control("stop").await.as_ref().is_ok_and(inactive) { - journal.phase("needs_reconciliation")?; - return Err( - "cold start failed; target stop unconfirmed, reconcile services".into(), - ); - } - journal.phase("cold_failed")?; - return Err("cold start failed; target stopped (cold_failed)".into()); - } - let from = from.unwrap(); - let old = catalog - .profiles - .get(&from) - .ok_or("previous profile absent")?; - if [old, new] - .iter() - .any(|p| p.key_file.as_ref().is_some_and(|key| !key.is_absolute())) - { - return Err("catalog key_file paths must be absolute".into()); - } - // Construct both clients before any admission or manager mutation. - let old_ready = crate::wait_ready::Waiter::new(&old.readiness())?; - let _ = crate::wait_ready::Waiter::new(&new.readiness())?; - if old.unit == new.unit - || reqwest::Url::parse(&old.url).ok() != reqwest::Url::parse(&new.url).ok() - || old.config.canonicalize().ok() == new.config.canonicalize().ok() - { - return Err("profiles need distinct units/configs and the same loopback origin".into()); - } - let old_sha = digest(&old.config)?; - let new_sha = digest(&new.config)?; - journal.value["from"] = json!(from); - journal.value["previous_config_sha256"] = json!(old_sha); - journal.value["target_config_sha256"] = json!(new_sha); - let previous = old.control("status").await?; - let old_pid = pid(&previous)?; - if !inactive(&new.control("status").await?) { - return Err("target service must be installed and inactive before switch".into()); - } - old_ready.wait(Some(old_pid)).await?; - journal.phase("preparing")?; - if let Err(error) = prepare(new, catalog.provision_timeout_s).await { - journal.phase("preflight_failed")?; - return Err(error); - } - if digest(&old.config)? != old_sha - || digest(&new.config)? != new_sha - || pid(&old.control("status").await?)? != old_pid - || !inactive(&new.control("status").await?) - || (auto - && (discover(&catalog).await? != discovered - || Some(validate_auto(&catalog, new)?) != auto_digests)) - { - journal.phase("needs_reconciliation")?; - return Err("profile or service changed during preparation; no drain requested".into()); - } - journal.phase("draining_previous")?; - if old.control("drain-stop").await.is_err() { - journal.phase("needs_reconciliation")?; - return Err( - "previous drain/stop outcome needs reconciliation; target was not started".into(), - ); - } - journal.phase("starting_target")?; - let target = if digest(&new.config)? == new_sha { - new.control("start-ready").await - } else { - Err("target config changed".into()) - }; - if let Ok(target) = target { - journal.phase("committed")?; - return Ok( - json!({"switched":true,"profile":to,"previous_profile":from,"manager":target["manager"],"readiness":target["readiness"]}), - ); - } - journal.phase("stopping_failed_target")?; - let stopped = new.control("stop").await; - if !stopped.as_ref().is_ok_and(inactive) { - journal.phase("needs_reconciliation")?; - return Err("target failed; target stop unconfirmed, previous restart withheld".into()); - } - journal.phase("restoring_previous")?; - if digest(&old.config)? != old_sha || old.control("start-ready").await.is_err() { - journal.phase("needs_reconciliation")?; - return Err( - "target failed and previous readiness could not be restored; reconcile services" - .into(), - ); - } - journal.phase("rolled_back")?; - Err( - "target startup failed; previous native profile restored and ready (rolled_back)" - .into(), - ) - } - #[cfg(not(unix))] - Err("service-switch requires Linux".into()) -} - -fn reconcile_arguments(args: &[String]) -> Result, String> { - const HELP: &str = "usage: service-switch reconcile --catalog FILE --state-dir DIR --expected-journal-sha SHA256"; - let mut result = BTreeMap::new(); - let (pairs, remainder) = args.as_chunks::<2>(); - if !remainder.is_empty() { - return Err(HELP.into()); - } - for [flag, value] in pairs { - if !matches!( - flag.as_str(), - "--catalog" | "--state-dir" | "--expected-journal-sha" - ) || result.insert(flag.clone(), value.clone()).is_some() - { - return Err(HELP.into()); - } - } - if result.len() != 3 { - return Err(HELP.into()); - } - let sha = &result["--expected-journal-sha"]; - if sha.len() != 64 - || !sha - .bytes() - .all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b)) - { - return Err("expected journal SHA must be 64 lowercase hex digits".into()); - } - Ok(result) -} - -async fn reconcile(args: &[String]) -> Result { - let args = reconcile_arguments(args)?; - if !cfg!(target_os = "linux") { - return Err("reconciliation requires Linux systemd user services".into()); - } - #[cfg(unix)] - { - use storage::{Journal, read}; - let state = Path::new(&args["--state-dir"]); - let mut journal = Journal::reconciliation(state)?; - let path = state.join("transaction.json"); - let bytes = read(&path, true, 65536)?; - let sha = hex::encode(Sha256::digest(&bytes)); - if sha != args["--expected-journal-sha"] { - return Err("journal acknowledgment mismatch; no reconciliation recorded".into()); - } - let prior: Value = - serde_json::from_slice(&bytes).map_err(|_| "invalid transaction journal")?; - if prior["schema_version"] != 1 - || !matches!( - prior["phase"].as_str(), - Some( - "preparing" - | "draining_previous" - | "starting_target" - | "stopping_failed_target" - | "restoring_previous" - | "needs_reconciliation" - ) - ) - { - return Err("reconciliation requires a known interrupted phase".into()); - } - let catalog_bytes = read(Path::new(&args["--catalog"]), true, 65536)?; - if prior["catalog_sha256"] != hex::encode(Sha256::digest(&catalog_bytes)) { - return Err("catalog differs from interrupted transaction".into()); - } - let catalog: Catalog = - serde_json::from_slice(&catalog_bytes).map_err(|_| "invalid native catalog")?; - if catalog.schema_version != 1 || catalog.profiles.is_empty() || catalog.profiles.len() > 16 - { - return Err("invalid catalog schema/count".into()); - } - let target = prior["to"] - .as_str() - .and_then(|id| catalog.profiles.get(id)) - .ok_or("journal target absent from catalog")?; - let digests = validate_auto(&catalog, target)?; - for (id_field, sha_field) in [ - ("from", "previous_config_sha256"), - ("to", "target_config_sha256"), - ] { - if let Some(id) = prior[id_field].as_str() { - if !digests - .get(id) - .is_some_and(|digest| prior[sha_field].as_str() == Some(digest.as_str())) - { - return Err( - "recorded configuration differs; reconcile configuration explicitly first" - .into(), - ); - } - } else if !prior[id_field].is_null() { - return Err("invalid recorded profile identity".into()); - } - } - let current = discover(&catalog).await?; - let readiness = if let Some((id, pid)) = ¤t { - Some( - crate::wait_ready::Waiter::new(&catalog.profiles[id].readiness())? - .wait(Some(*pid)) - .await?, - ) - } else { - None - }; - if discover(&catalog).await? != current - || validate_auto(&catalog, target)? != digests - || read(&path, true, 65536)? != bytes - { - return Err("state changed during reconciliation; no record written".into()); - } - journal.value = json!({"schema_version":1,"catalog_sha256":prior["catalog_sha256"], - "prior_journal_sha256":sha,"prior_phase":prior["phase"],"from":prior["from"],"to":prior["to"], - "verified_profile":current.as_ref().map(|(id,_)|id),"verified_pid":current.as_ref().map(|(_,pid)|pid)}); - journal.phase("reconciled")?; - Ok( - json!({"reconciled":true,"lifecycle_action_requested":false,"profile":current.as_ref().map(|(id,_)|id), - "pid":current.as_ref().map(|(_,pid)|pid),"prior_journal_sha256":sha,"readiness":readiness}), - ) - } - #[cfg(not(unix))] - Err("reconciliation requires Linux".into()) -} - #[cfg(test)] mod tests; + +mod provision_budget; +#[allow(unused_imports)] +pub use provision_budget::*; +mod run; +#[allow(unused_imports)] +pub use run::*; +mod reconcile; +#[allow(unused_imports)] +pub use reconcile::*; diff --git a/control-plane/src/service_switch/provision_budget.rs b/control-plane/src/service_switch/provision_budget.rs new file mode 100644 index 00000000..fe44d6ab --- /dev/null +++ b/control-plane/src/service_switch/provision_budget.rs @@ -0,0 +1,188 @@ +//! Moved out of the parent module by STRA-338: fn provision_budget, fn ready_budget, impl Profile, fn arguments, fn pid, fn inactive .... + +#[allow(unused_imports)] +use super::*; + +pub(super) fn provision_budget() -> u64 { + 3600 +} +pub(super) fn ready_budget() -> u64 { + 300 +} +impl Profile { + pub(super) fn readiness(&self) -> Vec { + let mut args = vec![ + "--url".into(), + self.url.clone(), + "--model".into(), + self.model.clone(), + "--timeout-s".into(), + self.timeout_s.to_string(), + ]; + if let Some(key) = &self.key_file { + args.extend(["--key-file".into(), key.to_string_lossy().into_owned()]); + } + args + } + pub(super) async fn control(&self, action: &str) -> Result { + let mut args = vec![ + action.into(), + "--config".into(), + self.config.to_string_lossy().into_owned(), + "--working-dir".into(), + self.working_dir.to_string_lossy().into_owned(), + "--unit".into(), + self.unit.clone(), + ]; + if matches!(action, "start-ready" | "drain-stop") { + let ready = self.readiness(); + for pair in ready.as_chunks::<2>().0 { + args.extend([pair[0].replacen("--", "--ready-", 1), pair[1].clone()]); + } + } + crate::service_install::control(&args).await + } +} +pub(super) fn arguments(args: &[String]) -> Result, String> { + let mut values = BTreeMap::new(); + let mut iter = args.iter(); + while let Some(flag) = iter.next() { + if !matches!( + flag.as_str(), + "--catalog" | "--from" | "--to" | "--state-dir" + ) { + return Err(USAGE.into()); + } + if values + .insert(flag.clone(), iter.next().ok_or(USAGE)?.clone()) + .is_some() + { + return Err(USAGE.into()); + } + } + if !["--catalog", "--to", "--state-dir"] + .iter() + .all(|k| values.contains_key(*k)) + { + return Err(USAGE.into()); + } + for key in ["--from", "--to"] { + let Some(id) = values.get(key) else { continue }; + if id.is_empty() + || id.len() > 64 + || !id + .bytes() + .all(|b| b.is_ascii_alphanumeric() || b"-_".contains(&b)) + { + return Err("profile IDs need 1..64 ASCII letters, digits, dash or underscore".into()); + } + } + if values.get("--from") == values.get("--to") { + return Err("switch needs distinct previous and target profiles".into()); + } + Ok(values) +} +pub(super) fn pid(value: &Value) -> Result { + if value["manager"]["active_state"] != "active" || value["manager"]["sub_state"] != "running" { + return Err("previous managed service is not running".into()); + } + value["manager"]["main_pid"] + .as_u64() + .and_then(|n| u32::try_from(n).ok()) + .filter(|n| *n > 0) + .ok_or_else(|| "previous service PID invalid".into()) +} +pub(super) fn inactive(value: &Value) -> bool { + value["manager"]["main_pid"] == 0 && value["manager"]["active_state"] == "inactive" +} + +pub(super) fn select_active(states: &[(String, Value)]) -> Result, String> { + let mut active = None; + for (id, state) in states { + if inactive(state) { + continue; + } + let running = pid(state).map_err(|_| "catalog contains a failed, transitional or unknown service; reconcile before selection")?; + if active.replace((id.clone(), running)).is_some() { + return Err("multiple catalog services are active; selection is ambiguous".into()); + } + } + Ok(active) +} + +pub(super) async fn discover(catalog: &Catalog) -> Result, String> { + let mut states = Vec::new(); + for (id, profile) in &catalog.profiles { + states.push((id.clone(), profile.control("status").await?)); + } + select_active(&states) +} + +#[cfg(unix)] +pub(super) fn validate_auto( + catalog: &Catalog, + target: &Profile, +) -> Result, String> { + use std::collections::BTreeSet; + let mut units = BTreeSet::new(); + let mut paths = BTreeSet::new(); + let mut digests = BTreeMap::new(); + for (id, profile) in &catalog.profiles { + if profile.key_file.as_ref().is_some_and(|k| !k.is_absolute()) { + return Err("catalog key_file paths must be absolute".into()); + } + let _ = crate::wait_ready::Waiter::new(&profile.readiness())?; + if !units.insert(&profile.unit) + || !paths.insert( + profile + .config + .canonicalize() + .map_err(|_| "cannot resolve catalog config")?, + ) + || reqwest::Url::parse(&profile.url).ok() != reqwest::Url::parse(&target.url).ok() + { + return Err( + "automatic selection needs distinct units/configs sharing one loopback origin" + .into(), + ); + } + digests.insert(id.clone(), storage::digest(&profile.config)?); + } + Ok(digests) +} + +pub(super) async fn prepare(profile: &Profile, budget: u64) -> Result<(), String> { + use std::process::Stdio; + let mut command = tokio::process::Command::new( + std::env::current_exe().map_err(|_| "cannot locate native executable")?, + ); + command + .arg("provision") + .arg("--config") + .arg(&profile.config) + .arg("--defer-memory-check") + .current_dir(&profile.working_dir) + .stdin(Stdio::null()) + .stdout(Stdio::null()) + .stderr(Stdio::null()) + .kill_on_drop(true); + for (key, _) in std::env::vars_os() { + if key.to_string_lossy().starts_with("STRATA_") { + command.env_remove(key); + } + } + let mut child = command + .spawn() + .map_err(|_| "cannot start target provision")?; + match tokio::time::timeout(Duration::from_secs(budget), child.wait()).await { + Ok(Ok(status)) if status.success() => Ok(()), + Ok(_) => Err("target provision failed before previous service drain".into()), + Err(_) => { + child + .kill() + .await + .map_err(|_| "provision timed out; kill/reap failed")?; + Err("target provision timed out before previous service drain".into()) + } + } +} diff --git a/control-plane/src/service_switch/reconcile.rs b/control-plane/src/service_switch/reconcile.rs new file mode 100644 index 00000000..59d7bf28 --- /dev/null +++ b/control-plane/src/service_switch/reconcile.rs @@ -0,0 +1,99 @@ +//! Moved out of the parent module by STRA-338: fn reconcile. + +#[allow(unused_imports)] +use super::*; + +pub(super) async fn reconcile(args: &[String]) -> Result { + let args = reconcile_arguments(args)?; + if !cfg!(target_os = "linux") { + return Err("reconciliation requires Linux systemd user services".into()); + } + #[cfg(unix)] + { + use storage::{Journal, read}; + let state = Path::new(&args["--state-dir"]); + let mut journal = Journal::reconciliation(state)?; + let path = state.join("transaction.json"); + let bytes = read(&path, true, 65536)?; + let sha = hex::encode(Sha256::digest(&bytes)); + if sha != args["--expected-journal-sha"] { + return Err("journal acknowledgment mismatch; no reconciliation recorded".into()); + } + let prior: Value = + serde_json::from_slice(&bytes).map_err(|_| "invalid transaction journal")?; + if prior["schema_version"] != 1 + || !matches!( + prior["phase"].as_str(), + Some( + "preparing" + | "draining_previous" + | "starting_target" + | "stopping_failed_target" + | "restoring_previous" + | "needs_reconciliation" + ) + ) + { + return Err("reconciliation requires a known interrupted phase".into()); + } + let catalog_bytes = read(Path::new(&args["--catalog"]), true, 65536)?; + if prior["catalog_sha256"] != hex::encode(Sha256::digest(&catalog_bytes)) { + return Err("catalog differs from interrupted transaction".into()); + } + let catalog: Catalog = + serde_json::from_slice(&catalog_bytes).map_err(|_| "invalid native catalog")?; + if catalog.schema_version != 1 || catalog.profiles.is_empty() || catalog.profiles.len() > 16 + { + return Err("invalid catalog schema/count".into()); + } + let target = prior["to"] + .as_str() + .and_then(|id| catalog.profiles.get(id)) + .ok_or("journal target absent from catalog")?; + let digests = validate_auto(&catalog, target)?; + for (id_field, sha_field) in [ + ("from", "previous_config_sha256"), + ("to", "target_config_sha256"), + ] { + if let Some(id) = prior[id_field].as_str() { + if !digests + .get(id) + .is_some_and(|digest| prior[sha_field].as_str() == Some(digest.as_str())) + { + return Err( + "recorded configuration differs; reconcile configuration explicitly first" + .into(), + ); + } + } else if !prior[id_field].is_null() { + return Err("invalid recorded profile identity".into()); + } + } + let current = discover(&catalog).await?; + let readiness = if let Some((id, pid)) = ¤t { + Some( + crate::wait_ready::Waiter::new(&catalog.profiles[id].readiness())? + .wait(Some(*pid)) + .await?, + ) + } else { + None + }; + if discover(&catalog).await? != current + || validate_auto(&catalog, target)? != digests + || read(&path, true, 65536)? != bytes + { + return Err("state changed during reconciliation; no record written".into()); + } + journal.value = json!({"schema_version":1,"catalog_sha256":prior["catalog_sha256"], + "prior_journal_sha256":sha,"prior_phase":prior["phase"],"from":prior["from"],"to":prior["to"], + "verified_profile":current.as_ref().map(|(id,_)|id),"verified_pid":current.as_ref().map(|(_,pid)|pid)}); + journal.phase("reconciled")?; + Ok( + json!({"reconciled":true,"lifecycle_action_requested":false,"profile":current.as_ref().map(|(id,_)|id), + "pid":current.as_ref().map(|(_,pid)|pid),"prior_journal_sha256":sha,"readiness":readiness}), + ) + } + #[cfg(not(unix))] + Err("reconciliation requires Linux".into()) +} diff --git a/control-plane/src/service_switch/run.rs b/control-plane/src/service_switch/run.rs new file mode 100644 index 00000000..82759f93 --- /dev/null +++ b/control-plane/src/service_switch/run.rs @@ -0,0 +1,210 @@ +//! Moved out of the parent module by STRA-338: fn run, fn reconcile_arguments. + +#[allow(unused_imports)] +use super::*; + +pub async fn run(args: &[String]) -> Result { + if args.first().is_some_and(|arg| arg == "reconcile") { + return reconcile(&args[1..]).await; + } + let args = arguments(args)?; + if !cfg!(target_os = "linux") { + return Err("service-switch requires Linux systemd user services".into()); + } + #[cfg(unix)] + { + use storage::{Journal, digest, read}; + let bytes = read(Path::new(&args["--catalog"]), true, 65536)?; + let catalog: Catalog = + serde_json::from_slice(&bytes).map_err(|_| "invalid native service catalog")?; + if catalog.schema_version != 1 + || catalog.profiles.is_empty() + || catalog.profiles.len() > 16 + || !(1..=86400).contains(&catalog.provision_timeout_s) + { + return Err("invalid catalog version/count/provision budget".into()); + } + let to = &args["--to"]; + let new = catalog.profiles.get(to).ok_or("target profile absent")?; + let auto = !args.contains_key("--from"); + let auto_digests = if auto { + Some(validate_auto(&catalog, new)?) + } else { + None + }; + let mut journal = Journal::open( + Path::new(&args["--state-dir"]), + json!({"schema_version":1,"from":args.get("--from"),"to":to,"catalog_sha256":hex::encode(Sha256::digest(&bytes))}), + )?; + let discovered = if auto { + discover(&catalog).await? + } else { + None + }; + let from = args + .get("--from") + .cloned() + .or_else(|| discovered.as_ref().map(|(id, _)| id.clone())); + if auto && from.as_ref() == Some(to) { + let expected_pid = discovered.as_ref().unwrap().1; + let readiness = crate::wait_ready::Waiter::new(&new.readiness())? + .wait(Some(expected_pid)) + .await?; + if discover(&catalog).await? != discovered + || Some(validate_auto(&catalog, new)?) != auto_digests + { + return Err("catalog changed during readiness; selection refused".into()); + } + journal.value["from"] = json!(to); + journal.phase("reused")?; + return Ok(json!({"profile":to,"reused":true,"switched":false,"readiness":readiness})); + } + if from.is_none() { + journal.value["target_config_sha256"] = json!(digest(&new.config)?); + journal.phase("preparing")?; + if let Err(error) = prepare(new, catalog.provision_timeout_s).await { + journal.phase("preflight_failed")?; + return Err(error); + } + if discover(&catalog).await?.is_some() + || Some(validate_auto(&catalog, new)?) != auto_digests + { + journal.phase("needs_reconciliation")?; + return Err("catalog changed during cold preparation; target not started".into()); + } + journal.phase("starting_target")?; + if let Ok(target) = new.control("start-ready").await { + journal.phase("committed")?; + return Ok( + json!({"profile":to,"cold_started":true,"switched":false,"manager":target["manager"],"readiness":target["readiness"]}), + ); + } + journal.phase("stopping_failed_target")?; + if !new.control("stop").await.as_ref().is_ok_and(inactive) { + journal.phase("needs_reconciliation")?; + return Err( + "cold start failed; target stop unconfirmed, reconcile services".into(), + ); + } + journal.phase("cold_failed")?; + return Err("cold start failed; target stopped (cold_failed)".into()); + } + let from = from.unwrap(); + let old = catalog + .profiles + .get(&from) + .ok_or("previous profile absent")?; + if [old, new] + .iter() + .any(|p| p.key_file.as_ref().is_some_and(|key| !key.is_absolute())) + { + return Err("catalog key_file paths must be absolute".into()); + } + // Construct both clients before any admission or manager mutation. + let old_ready = crate::wait_ready::Waiter::new(&old.readiness())?; + let _ = crate::wait_ready::Waiter::new(&new.readiness())?; + if old.unit == new.unit + || reqwest::Url::parse(&old.url).ok() != reqwest::Url::parse(&new.url).ok() + || old.config.canonicalize().ok() == new.config.canonicalize().ok() + { + return Err("profiles need distinct units/configs and the same loopback origin".into()); + } + let old_sha = digest(&old.config)?; + let new_sha = digest(&new.config)?; + journal.value["from"] = json!(from); + journal.value["previous_config_sha256"] = json!(old_sha); + journal.value["target_config_sha256"] = json!(new_sha); + let previous = old.control("status").await?; + let old_pid = pid(&previous)?; + if !inactive(&new.control("status").await?) { + return Err("target service must be installed and inactive before switch".into()); + } + old_ready.wait(Some(old_pid)).await?; + journal.phase("preparing")?; + if let Err(error) = prepare(new, catalog.provision_timeout_s).await { + journal.phase("preflight_failed")?; + return Err(error); + } + if digest(&old.config)? != old_sha + || digest(&new.config)? != new_sha + || pid(&old.control("status").await?)? != old_pid + || !inactive(&new.control("status").await?) + || (auto + && (discover(&catalog).await? != discovered + || Some(validate_auto(&catalog, new)?) != auto_digests)) + { + journal.phase("needs_reconciliation")?; + return Err("profile or service changed during preparation; no drain requested".into()); + } + journal.phase("draining_previous")?; + if old.control("drain-stop").await.is_err() { + journal.phase("needs_reconciliation")?; + return Err( + "previous drain/stop outcome needs reconciliation; target was not started".into(), + ); + } + journal.phase("starting_target")?; + let target = if digest(&new.config)? == new_sha { + new.control("start-ready").await + } else { + Err("target config changed".into()) + }; + if let Ok(target) = target { + journal.phase("committed")?; + return Ok( + json!({"switched":true,"profile":to,"previous_profile":from,"manager":target["manager"],"readiness":target["readiness"]}), + ); + } + journal.phase("stopping_failed_target")?; + let stopped = new.control("stop").await; + if !stopped.as_ref().is_ok_and(inactive) { + journal.phase("needs_reconciliation")?; + return Err("target failed; target stop unconfirmed, previous restart withheld".into()); + } + journal.phase("restoring_previous")?; + if digest(&old.config)? != old_sha || old.control("start-ready").await.is_err() { + journal.phase("needs_reconciliation")?; + return Err( + "target failed and previous readiness could not be restored; reconcile services" + .into(), + ); + } + journal.phase("rolled_back")?; + Err( + "target startup failed; previous native profile restored and ready (rolled_back)" + .into(), + ) + } + #[cfg(not(unix))] + Err("service-switch requires Linux".into()) +} + +pub(super) fn reconcile_arguments(args: &[String]) -> Result, String> { + const HELP: &str = "usage: service-switch reconcile --catalog FILE --state-dir DIR --expected-journal-sha SHA256"; + let mut result = BTreeMap::new(); + let (pairs, remainder) = args.as_chunks::<2>(); + if !remainder.is_empty() { + return Err(HELP.into()); + } + for [flag, value] in pairs { + if !matches!( + flag.as_str(), + "--catalog" | "--state-dir" | "--expected-journal-sha" + ) || result.insert(flag.clone(), value.clone()).is_some() + { + return Err(HELP.into()); + } + } + if result.len() != 3 { + return Err(HELP.into()); + } + let sha = &result["--expected-journal-sha"]; + if sha.len() != 64 + || !sha + .bytes() + .all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b)) + { + return Err("expected journal SHA must be 64 lowercase hex digits".into()); + } + Ok(result) +} diff --git a/control-plane/src/vision.rs b/control-plane/src/vision.rs index 2a0e4bab..560fbd8f 100644 --- a/control-plane/src/vision.rs +++ b/control-plane/src/vision.rs @@ -58,52 +58,6 @@ pub struct VisionConfig { pub cuda_device: Option, } -impl VisionConfig { - /// `Vision.__init__`'s arguments. - pub fn args(&self) -> Vec { - let mut args = vec![ - "--mmproj".to_owned(), - self.mmproj.to_string_lossy().into_owned(), - "--model".to_owned(), - self.model.to_string_lossy().into_owned(), - ]; - if self.gpu { - args.push("--gpu".into()); - } - if let Some(threads) = self.threads.filter(|t| *t > 0) { - args.extend(["--threads".to_owned(), threads.to_string()]); - } - if let Some(max) = self.max_tokens.filter(|t| *t > 0) { - args.extend(["--max-tokens".to_owned(), max.to_string()]); - } - args - } - - /// `vision_env`: the environment overrides of the encoder process. - pub fn env(&self) -> Vec<(&'static str, String)> { - match self.cuda_device { - Some(device) => vec![ - ("CUDA_DEVICE_ORDER", "PCI_BUS_ID".to_owned()), - ("CUDA_VISIBLE_DEVICES", device.to_string()), - ], - None => Vec::new(), - } - } - - pub fn validate(&self) -> Result<(), String> { - for (name, path) in [ - ("exe", &self.exe), - ("mmproj", &self.mmproj), - ("model", &self.model), - ] { - if path.as_os_str().is_empty() { - return Err(format!("vision.{name} must not be empty")); - } - } - Ok(()) - } -} - #[derive(Debug, Clone, PartialEq, Eq)] pub enum VisionError { /// The caller's image is the problem: HTTP 400 (`ValueError` in Python). @@ -112,16 +66,6 @@ pub enum VisionError { Failed(String), } -impl std::fmt::Display for VisionError { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - match self { - Self::Invalid(message) | Self::Failed(message) => f.write_str(message), - } - } -} - -impl std::error::Error for VisionError {} - /// One encoded image: its SVE1 file and the number of image tokens it stands for. #[derive(Clone, Debug, PartialEq, Eq)] pub struct Encoded { @@ -133,31 +77,9 @@ pub struct Encoded { #[derive(Clone, Debug, Default)] pub struct Keep(Option>); -impl Keep { - pub fn none() -> Self { - Self(None) - } -} - -impl PartialEq for Keep { - fn eq(&self, other: &Self) -> bool { - match (&self.0, &other.0) { - (None, None) => true, - (Some(a), Some(b)) => Arc::ptr_eq(a, b), - _ => false, - } - } -} - #[derive(Debug)] struct TempFile(PathBuf); -impl Drop for TempFile { - fn drop(&mut self) { - let _ = std::fs::remove_file(&self.0); - } -} - struct Proc { child: Child, stdin: ChildStdin, @@ -184,315 +106,6 @@ pub struct Vision { static NEXT_DIR: AtomicU64 = AtomicU64::new(0); -impl Vision { - /// Start the encoder and wait for its `READY` line (`Vision.__init__`). - pub async fn start(config: VisionConfig) -> Result, VisionError> { - let vision = Self::unstarted(config)?; - { - let mut inner = vision.inner.lock().await; - vision.spawn(&mut inner).await?; - } - Ok(Arc::new(vision)) - } - - /// A client whose process is started by the first [`Vision::restart`] or [`Vision::ensure_running`]. - pub fn unstarted(config: VisionConfig) -> Result { - let dir = std::env::temp_dir().join(format!( - "strata-vision-{}-{}", - std::process::id(), - NEXT_DIR.fetch_add(1, Ordering::Relaxed) - )); - std::fs::create_dir_all(&dir) - .map_err(|e| VisionError::Failed(format!("cannot create {}: {e}", dir.display())))?; - Ok(Self { - config, - dir, - inner: Mutex::new(Inner::default()), - stopped: AtomicBool::new(true), - serial: AtomicU64::new(0), - gate: Arc::new(Mutex::new(())), - }) - } - - pub fn dir(&self) -> &Path { - &self.dir - } - - async fn spawn(&self, inner: &mut Inner) -> Result<(), VisionError> { - let mut command = Command::new(&self.config.exe); - command - .args(self.config.args()) - .stdin(Stdio::piped()) - .stdout(Stdio::piped()) - .stderr(Stdio::inherit()) - .kill_on_drop(true); - for (name, value) in self.config.env() { - command.env(name, value); - } - let mut child = command.spawn().map_err(|e| { - VisionError::Failed(format!( - "the vision encoder did not start: {}: {e}", - self.config.exe.display() - )) - })?; - let stdin = child.stdin.take().expect("piped encoder stdin"); - let stdout = child.stdout.take().expect("piped encoder stdout"); - let mut lines = BufReader::new(stdout).lines(); - let first = match timeout(START_TIMEOUT, lines.next_line()).await { - Ok(Ok(Some(line))) => line, - Ok(Ok(None)) => String::new(), - Ok(Err(e)) => { - return Err(VisionError::Failed(format!( - "the vision encoder did not start: {e}" - ))); - } - Err(_) => { - let _ = child.kill().await; - return Err(VisionError::Failed( - "the vision encoder did not start: no READY line in time".into(), - )); - } - }; - if !first.starts_with("READY") { - let _ = child.kill().await; - return Err(VisionError::Failed(format!( - "the vision encoder did not start: {}", - first.trim() - ))); - } - inner.proc = Some(Proc { - child, - stdin, - lines, - }); - self.stopped.store(false, Ordering::Release); - Ok(()) - } - - /// `Vision.alive`: started, not unloaded, and the process still runs. - pub async fn alive(&self) -> bool { - if self.stopped.load(Ordering::Acquire) { - return false; - } - let mut inner = self.inner.lock().await; - inner - .proc - .as_mut() - .is_some_and(|proc| matches!(proc.child.try_wait(), Ok(None))) - } - - async fn close_inner(inner: &mut Inner) { - let Some(mut proc) = inner.proc.take() else { - return; - }; - let quit = async { - proc.stdin.write_all(b"QUIT\n").await.ok()?; - proc.stdin.flush().await.ok()?; - drop(proc.stdin); - timeout(Duration::from_secs(10), proc.child.wait()) - .await - .ok()? - .ok() - }; - if quit.await.is_none() { - let _ = proc.child.kill().await; - } - } - - /// `Vision.close`: ask the encoder to quit, kill it if it does not. - pub async fn close(&self) { - let mut inner = self.inner.lock().await; - Self::close_inner(&mut inner).await; - self.stopped.store(true, Ordering::Release); - } - - /// `Vision.unload`: stop the process (its VRAM or RAM goes back); the encoded images stay cached on disk. - pub async fn unload(&self) { - self.close().await; - } - - /// `Vision.restart`: start the process again after an unload or a death; the cache is kept. - pub async fn restart(&self) -> Result<(), VisionError> { - let mut inner = self.inner.lock().await; - if let Some(mut proc) = inner.proc.take() { - let _ = proc.child.kill().await; - } - self.spawn(&mut inner).await - } - - /// `Service.ensure_loaded`'s vision step: start the encoder again unless it runs. Done before the engine starts - /// (a GPU encoder takes its VRAM first, the engine sizes its cache from what is left). - pub async fn ensure_running(&self) -> Result<(), VisionError> { - if self.alive().await { - return Ok(()); - } - crate::elog!("starting the vision encoder again ..."); - self.restart().await - } - - /// `Vision.load`: the bytes behind an image source (a `data:` URL, an http(s) URL or a local path). - pub async fn load(source: &str) -> Result, VisionError> { - if let Some(rest) = source.strip_prefix("data:") { - let (_, payload) = rest.split_once(',').ok_or_else(|| { - VisionError::Invalid("an image data: URL needs a comma before its data".into()) - })?; - return policy::b64decode(payload).map_err(VisionError::Invalid); - } - if source.starts_with("http://") || source.starts_with("https://") { - return fetch(source).await; - } - let path = source.strip_prefix("file://").unwrap_or(source); - if !path.is_empty() && tokio::fs::metadata(path).await.is_ok_and(|m| m.is_file()) { - return tokio::fs::read(path) - .await - .map_err(|e| VisionError::Invalid(format!("the image could not be read ({e})"))); - } - Err(VisionError::Invalid( - "an image must be a data: URL, an http(s) URL or a local file path".into(), - )) - } - - /// `Vision.normalize` without an image library: the formats `strata-vision`'s decoder reads pass through. - pub fn normalize(data: Vec) -> Result, VisionError> { - if policy::is_native_image_format(&data) { - Ok(data) - } else { - Err(VisionError::Invalid( - "this image format is not supported (JPEG, PNG, BMP and GIF are; convert WebP, TIFF, AVIF, ... first)" - .into(), - )) - } - } - - /// `Vision.encode`: the embeddings file of an image and its number of image tokens; the same picture - /// (by content) is encoded once. - pub async fn encode(&self, source: &str) -> Result { - let data = Self::normalize(Self::load(source).await?)?; - let key = hex::encode(Sha256::digest(&data))[..32].to_owned(); - let mut inner = self.inner.lock().await; - if let Some((_, hit)) = inner.cache.iter().find(|(k, _)| *k == key) { - return Ok(hit.clone()); - } - let image = self.dir.join(format!("{key}.img")); - let out = self.dir.join(format!("{key}.sve")); - tokio::fs::write(&image, &data) - .await - .map_err(|e| VisionError::Failed(format!("cannot write {}: {e}", image.display())))?; - let reply = Self::exchange(&mut inner, &image, &out).await; - let _ = tokio::fs::remove_file(&image).await; // #352: also when the encoder's pipe is gone - let line = reply?; - if !line.starts_with("OK") { - return Err(VisionError::Invalid(format!( - "the image could not be read: {}", - match line.strip_prefix("ERR") { - Some(_) => line.get(4..).unwrap_or(""), - None => "the vision encoder stopped", - } - ))); - } - let tokens = line - .split_whitespace() - .nth(1) - .and_then(|n| n.parse::().ok()) - .ok_or_else(|| { - VisionError::Failed(format!("unexpected vision encoder reply: {line}")) - })?; - let encoded = Encoded { path: out, tokens }; - inner.cache.push_back((key, encoded.clone())); - if inner.cache.len() > CACHE_LIMIT - && let Some((_, old)) = inner.cache.pop_front() - { - let _ = tokio::fs::remove_file(&old.path).await; // oldest first - } - Ok(encoded) - } - - /// One `ENC` line and its reply (`""` when the encoder's output ended). - async fn exchange(inner: &mut Inner, image: &Path, out: &Path) -> Result { - let proc = inner - .proc - .as_mut() - .ok_or_else(|| VisionError::Failed("the vision encoder is not running".into()))?; - let line = format!("ENC {} {}\n", image.display(), out.display()); - proc.stdin - .write_all(line.as_bytes()) - .await - .map_err(|e| VisionError::Failed(format!("the vision encoder is gone: {e}")))?; - proc.stdin - .flush() - .await - .map_err(|e| VisionError::Failed(format!("the vision encoder is gone: {e}")))?; - match proc.lines.next_line().await { - Ok(Some(reply)) => Ok(reply.trim().to_owned()), - Ok(None) => Ok(String::new()), - Err(e) => Err(VisionError::Failed(format!( - "the vision encoder is gone: {e}" - ))), - } - } - - /// The concatenation of the images' SVE1 files in prompt order: `GENI`'s embeddings file for one request. - pub async fn combine(&self, images: &[Encoded]) -> Result<(PathBuf, Keep), VisionError> { - let name = format!( - "req-{:x}-{:x}.sve", - std::process::id(), - self.serial.fetch_add(1, Ordering::Relaxed) - ); - let path = self.dir.join(name); - let mut bytes = Vec::new(); - for image in images { - bytes.extend(tokio::fs::read(&image.path).await.map_err(|e| { - VisionError::Failed(format!("cannot read {}: {e}", image.path.display())) - })?); - } - tokio::fs::write(&path, bytes) - .await - .map_err(|e| VisionError::Failed(format!("cannot write {}: {e}", path.display())))?; - Ok((path.clone(), Keep(Some(Arc::new(TempFile(path)))))) - } -} - -impl Drop for Vision { - fn drop(&mut self) { - let _ = std::fs::remove_dir_all(&self.dir); - } -} - -async fn fetch(url: &str) -> Result, VisionError> { - let fail = |e: &dyn std::fmt::Display| { - VisionError::Invalid(format!("the image could not be fetched ({e})")) - }; - let roots = webpki_root_certs::TLS_SERVER_ROOT_CERTS - .iter() - .map(|der| reqwest::Certificate::from_der(der.as_ref())) - .collect::, _>>() - .map_err(|e| fail(&e))?; - let client = reqwest::Client::builder() - .tls_certs_only(roots) - .timeout(FETCH_TIMEOUT) - .user_agent("strata") - .build() - .map_err(|e| fail(&e))?; - let mut response = client - .get(url) - .send() - .await - .map_err(|e| fail(&e))? - .error_for_status() - .map_err(|e| fail(&e))?; - let mut data = Vec::new(); - while let Some(chunk) = response.chunk().await.map_err(|e| fail(&e))? { - data.extend_from_slice(&chunk); - if data.len() > MAX_IMAGE_BYTES { - return Err(VisionError::Invalid(format!( - "the image is larger than {} MiB", - MAX_IMAGE_BYTES >> 20 - ))); - } - } - Ok(data) -} - #[cfg(all(test, unix))] mod tests { use super::*; @@ -777,3 +390,13 @@ mod tests { vision.close().await; } } + +mod impl_visionconfig; +#[allow(unused_imports)] +pub use impl_visionconfig::*; +mod impl_vision; +#[allow(unused_imports)] +pub use impl_vision::*; +mod impl_drop_for_vision; +#[allow(unused_imports)] +pub use impl_drop_for_vision::*; diff --git a/control-plane/src/vision/impl_drop_for_vision.rs b/control-plane/src/vision/impl_drop_for_vision.rs new file mode 100644 index 00000000..a9b5cc7e --- /dev/null +++ b/control-plane/src/vision/impl_drop_for_vision.rs @@ -0,0 +1,45 @@ +//! Moved out of the parent module by STRA-338: impl Drop_for_Vision, fn fetch. + +#[allow(unused_imports)] +use super::*; + +impl Drop for Vision { + fn drop(&mut self) { + let _ = std::fs::remove_dir_all(&self.dir); + } +} + +pub(super) async fn fetch(url: &str) -> Result, VisionError> { + let fail = |e: &dyn std::fmt::Display| { + VisionError::Invalid(format!("the image could not be fetched ({e})")) + }; + let roots = webpki_root_certs::TLS_SERVER_ROOT_CERTS + .iter() + .map(|der| reqwest::Certificate::from_der(der.as_ref())) + .collect::, _>>() + .map_err(|e| fail(&e))?; + let client = reqwest::Client::builder() + .tls_certs_only(roots) + .timeout(FETCH_TIMEOUT) + .user_agent("strata") + .build() + .map_err(|e| fail(&e))?; + let mut response = client + .get(url) + .send() + .await + .map_err(|e| fail(&e))? + .error_for_status() + .map_err(|e| fail(&e))?; + let mut data = Vec::new(); + while let Some(chunk) = response.chunk().await.map_err(|e| fail(&e))? { + data.extend_from_slice(&chunk); + if data.len() > MAX_IMAGE_BYTES { + return Err(VisionError::Invalid(format!( + "the image is larger than {} MiB", + MAX_IMAGE_BYTES >> 20 + ))); + } + } + Ok(data) +} diff --git a/control-plane/src/vision/impl_vision.rs b/control-plane/src/vision/impl_vision.rs new file mode 100644 index 00000000..cb26f669 --- /dev/null +++ b/control-plane/src/vision/impl_vision.rs @@ -0,0 +1,276 @@ +//! Moved out of the parent module by STRA-338: impl Vision. + +#[allow(unused_imports)] +use super::*; + +impl Vision { + /// Start the encoder and wait for its `READY` line (`Vision.__init__`). + pub async fn start(config: VisionConfig) -> Result, VisionError> { + let vision = Self::unstarted(config)?; + { + let mut inner = vision.inner.lock().await; + vision.spawn(&mut inner).await?; + } + Ok(Arc::new(vision)) + } + + /// A client whose process is started by the first [`Vision::restart`] or [`Vision::ensure_running`]. + pub fn unstarted(config: VisionConfig) -> Result { + let dir = std::env::temp_dir().join(format!( + "strata-vision-{}-{}", + std::process::id(), + NEXT_DIR.fetch_add(1, Ordering::Relaxed) + )); + std::fs::create_dir_all(&dir) + .map_err(|e| VisionError::Failed(format!("cannot create {}: {e}", dir.display())))?; + Ok(Self { + config, + dir, + inner: Mutex::new(Inner::default()), + stopped: AtomicBool::new(true), + serial: AtomicU64::new(0), + gate: Arc::new(Mutex::new(())), + }) + } + + pub fn dir(&self) -> &Path { + &self.dir + } + + pub(super) async fn spawn(&self, inner: &mut Inner) -> Result<(), VisionError> { + let mut command = Command::new(&self.config.exe); + command + .args(self.config.args()) + .stdin(Stdio::piped()) + .stdout(Stdio::piped()) + .stderr(Stdio::inherit()) + .kill_on_drop(true); + for (name, value) in self.config.env() { + command.env(name, value); + } + let mut child = command.spawn().map_err(|e| { + VisionError::Failed(format!( + "the vision encoder did not start: {}: {e}", + self.config.exe.display() + )) + })?; + let stdin = child.stdin.take().expect("piped encoder stdin"); + let stdout = child.stdout.take().expect("piped encoder stdout"); + let mut lines = BufReader::new(stdout).lines(); + let first = match timeout(START_TIMEOUT, lines.next_line()).await { + Ok(Ok(Some(line))) => line, + Ok(Ok(None)) => String::new(), + Ok(Err(e)) => { + return Err(VisionError::Failed(format!( + "the vision encoder did not start: {e}" + ))); + } + Err(_) => { + let _ = child.kill().await; + return Err(VisionError::Failed( + "the vision encoder did not start: no READY line in time".into(), + )); + } + }; + if !first.starts_with("READY") { + let _ = child.kill().await; + return Err(VisionError::Failed(format!( + "the vision encoder did not start: {}", + first.trim() + ))); + } + inner.proc = Some(Proc { + child, + stdin, + lines, + }); + self.stopped.store(false, Ordering::Release); + Ok(()) + } + + /// `Vision.alive`: started, not unloaded, and the process still runs. + pub async fn alive(&self) -> bool { + if self.stopped.load(Ordering::Acquire) { + return false; + } + let mut inner = self.inner.lock().await; + inner + .proc + .as_mut() + .is_some_and(|proc| matches!(proc.child.try_wait(), Ok(None))) + } + + pub(super) async fn close_inner(inner: &mut Inner) { + let Some(mut proc) = inner.proc.take() else { + return; + }; + let quit = async { + proc.stdin.write_all(b"QUIT\n").await.ok()?; + proc.stdin.flush().await.ok()?; + drop(proc.stdin); + timeout(Duration::from_secs(10), proc.child.wait()) + .await + .ok()? + .ok() + }; + if quit.await.is_none() { + let _ = proc.child.kill().await; + } + } + + /// `Vision.close`: ask the encoder to quit, kill it if it does not. + pub async fn close(&self) { + let mut inner = self.inner.lock().await; + Self::close_inner(&mut inner).await; + self.stopped.store(true, Ordering::Release); + } + + /// `Vision.unload`: stop the process (its VRAM or RAM goes back); the encoded images stay cached on disk. + pub async fn unload(&self) { + self.close().await; + } + + /// `Vision.restart`: start the process again after an unload or a death; the cache is kept. + pub async fn restart(&self) -> Result<(), VisionError> { + let mut inner = self.inner.lock().await; + if let Some(mut proc) = inner.proc.take() { + let _ = proc.child.kill().await; + } + self.spawn(&mut inner).await + } + + /// `Service.ensure_loaded`'s vision step: start the encoder again unless it runs. Done before the engine starts + /// (a GPU encoder takes its VRAM first, the engine sizes its cache from what is left). + pub async fn ensure_running(&self) -> Result<(), VisionError> { + if self.alive().await { + return Ok(()); + } + crate::elog!("starting the vision encoder again ..."); + self.restart().await + } + + /// `Vision.load`: the bytes behind an image source (a `data:` URL, an http(s) URL or a local path). + pub async fn load(source: &str) -> Result, VisionError> { + if let Some(rest) = source.strip_prefix("data:") { + let (_, payload) = rest.split_once(',').ok_or_else(|| { + VisionError::Invalid("an image data: URL needs a comma before its data".into()) + })?; + return policy::b64decode(payload).map_err(VisionError::Invalid); + } + if source.starts_with("http://") || source.starts_with("https://") { + return fetch(source).await; + } + let path = source.strip_prefix("file://").unwrap_or(source); + if !path.is_empty() && tokio::fs::metadata(path).await.is_ok_and(|m| m.is_file()) { + return tokio::fs::read(path) + .await + .map_err(|e| VisionError::Invalid(format!("the image could not be read ({e})"))); + } + Err(VisionError::Invalid( + "an image must be a data: URL, an http(s) URL or a local file path".into(), + )) + } + + /// `Vision.normalize` without an image library: the formats `strata-vision`'s decoder reads pass through. + pub fn normalize(data: Vec) -> Result, VisionError> { + if policy::is_native_image_format(&data) { + Ok(data) + } else { + Err(VisionError::Invalid( + "this image format is not supported (JPEG, PNG, BMP and GIF are; convert WebP, TIFF, AVIF, ... first)" + .into(), + )) + } + } + + /// `Vision.encode`: the embeddings file of an image and its number of image tokens; the same picture + /// (by content) is encoded once. + pub async fn encode(&self, source: &str) -> Result { + let data = Self::normalize(Self::load(source).await?)?; + let key = hex::encode(Sha256::digest(&data))[..32].to_owned(); + let mut inner = self.inner.lock().await; + if let Some((_, hit)) = inner.cache.iter().find(|(k, _)| *k == key) { + return Ok(hit.clone()); + } + let image = self.dir.join(format!("{key}.img")); + let out = self.dir.join(format!("{key}.sve")); + tokio::fs::write(&image, &data) + .await + .map_err(|e| VisionError::Failed(format!("cannot write {}: {e}", image.display())))?; + let reply = Self::exchange(&mut inner, &image, &out).await; + let _ = tokio::fs::remove_file(&image).await; // #352: also when the encoder's pipe is gone + let line = reply?; + if !line.starts_with("OK") { + return Err(VisionError::Invalid(format!( + "the image could not be read: {}", + match line.strip_prefix("ERR") { + Some(_) => line.get(4..).unwrap_or(""), + None => "the vision encoder stopped", + } + ))); + } + let tokens = line + .split_whitespace() + .nth(1) + .and_then(|n| n.parse::().ok()) + .ok_or_else(|| { + VisionError::Failed(format!("unexpected vision encoder reply: {line}")) + })?; + let encoded = Encoded { path: out, tokens }; + inner.cache.push_back((key, encoded.clone())); + if inner.cache.len() > CACHE_LIMIT + && let Some((_, old)) = inner.cache.pop_front() + { + let _ = tokio::fs::remove_file(&old.path).await; // oldest first + } + Ok(encoded) + } + + /// One `ENC` line and its reply (`""` when the encoder's output ended). + pub(super) async fn exchange( + inner: &mut Inner, + image: &Path, + out: &Path, + ) -> Result { + let proc = inner + .proc + .as_mut() + .ok_or_else(|| VisionError::Failed("the vision encoder is not running".into()))?; + let line = format!("ENC {} {}\n", image.display(), out.display()); + proc.stdin + .write_all(line.as_bytes()) + .await + .map_err(|e| VisionError::Failed(format!("the vision encoder is gone: {e}")))?; + proc.stdin + .flush() + .await + .map_err(|e| VisionError::Failed(format!("the vision encoder is gone: {e}")))?; + match proc.lines.next_line().await { + Ok(Some(reply)) => Ok(reply.trim().to_owned()), + Ok(None) => Ok(String::new()), + Err(e) => Err(VisionError::Failed(format!( + "the vision encoder is gone: {e}" + ))), + } + } + + /// The concatenation of the images' SVE1 files in prompt order: `GENI`'s embeddings file for one request. + pub async fn combine(&self, images: &[Encoded]) -> Result<(PathBuf, Keep), VisionError> { + let name = format!( + "req-{:x}-{:x}.sve", + std::process::id(), + self.serial.fetch_add(1, Ordering::Relaxed) + ); + let path = self.dir.join(name); + let mut bytes = Vec::new(); + for image in images { + bytes.extend(tokio::fs::read(&image.path).await.map_err(|e| { + VisionError::Failed(format!("cannot read {}: {e}", image.path.display())) + })?); + } + tokio::fs::write(&path, bytes) + .await + .map_err(|e| VisionError::Failed(format!("cannot write {}: {e}", path.display())))?; + Ok((path.clone(), Keep(Some(Arc::new(TempFile(path)))))) + } +} diff --git a/control-plane/src/vision/impl_visionconfig.rs b/control-plane/src/vision/impl_visionconfig.rs new file mode 100644 index 00000000..c3873e82 --- /dev/null +++ b/control-plane/src/vision/impl_visionconfig.rs @@ -0,0 +1,82 @@ +//! Moved out of the parent module by STRA-338: impl VisionConfig, impl std_fmt_Display, impl std_error_Error, impl Keep, impl PartialEq_for_Keep, impl Drop_for_TempFile. + +#[allow(unused_imports)] +use super::*; + +impl VisionConfig { + /// `Vision.__init__`'s arguments. + pub fn args(&self) -> Vec { + let mut args = vec![ + "--mmproj".to_owned(), + self.mmproj.to_string_lossy().into_owned(), + "--model".to_owned(), + self.model.to_string_lossy().into_owned(), + ]; + if self.gpu { + args.push("--gpu".into()); + } + if let Some(threads) = self.threads.filter(|t| *t > 0) { + args.extend(["--threads".to_owned(), threads.to_string()]); + } + if let Some(max) = self.max_tokens.filter(|t| *t > 0) { + args.extend(["--max-tokens".to_owned(), max.to_string()]); + } + args + } + + /// `vision_env`: the environment overrides of the encoder process. + pub fn env(&self) -> Vec<(&'static str, String)> { + match self.cuda_device { + Some(device) => vec![ + ("CUDA_DEVICE_ORDER", "PCI_BUS_ID".to_owned()), + ("CUDA_VISIBLE_DEVICES", device.to_string()), + ], + None => Vec::new(), + } + } + + pub fn validate(&self) -> Result<(), String> { + for (name, path) in [ + ("exe", &self.exe), + ("mmproj", &self.mmproj), + ("model", &self.model), + ] { + if path.as_os_str().is_empty() { + return Err(format!("vision.{name} must not be empty")); + } + } + Ok(()) + } +} + +impl std::fmt::Display for VisionError { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match self { + Self::Invalid(message) | Self::Failed(message) => f.write_str(message), + } + } +} + +impl std::error::Error for VisionError {} + +impl Keep { + pub fn none() -> Self { + Self(None) + } +} + +impl PartialEq for Keep { + fn eq(&self, other: &Self) -> bool { + match (&self.0, &other.0) { + (None, None) => true, + (Some(a), Some(b)) => Arc::ptr_eq(a, b), + _ => false, + } + } +} + +impl Drop for TempFile { + fn drop(&mut self) { + let _ = std::fs::remove_file(&self.0); + } +} diff --git a/control-plane/src/worker.rs b/control-plane/src/worker.rs index c88032aa..ea85b7d0 100644 --- a/control-plane/src/worker.rs +++ b/control-plane/src/worker.rs @@ -27,34 +27,6 @@ pub enum GenerationResult { Finished, } -impl GenerationResult { - pub(crate) fn take(&mut self) -> Self { - std::mem::replace(self, Self::Finished) - } - - pub(crate) fn is_closed(&self) -> bool { - match self { - Self::Buffered(sender) => sender.is_closed(), - Self::Streaming(sender) => sender.is_closed(), - Self::Finished => true, - } - } - - pub(crate) async fn closed(&mut self) { - match self { - Self::Buffered(sender) => sender.closed().await, - Self::Streaming(sender) => sender.closed().await, - Self::Finished => {} - } - } - - pub(crate) async fn send_event(&self, event: Event) { - if let Self::Streaming(sender) = self { - let _ = sender.send(Ok(event)).await; - } - } -} - #[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)] #[serde(rename_all = "snake_case")] pub enum WorkerState { @@ -87,20 +59,6 @@ pub struct WorkerStatus { pub text_level_engine: bool, } -impl Default for WorkerStatus { - fn default() -> Self { - Self { - state: WorkerState::Unconfigured, - max_context: None, - known_max_context: None, - last_activity: None, - metrics: crate::metrics::GenerationMetrics::with_history(), - output_cap: None, - text_level_engine: false, - } - } -} - /// How to run the command before a reload. #[derive(Clone, Debug, PartialEq, Eq, serde::Deserialize)] #[serde(untagged)] @@ -131,24 +89,6 @@ pub struct WorkerConfig { pub vision: Option>, } -impl Default for WorkerConfig { - fn default() -> Self { - Self { - cuda_memory: None, - executable: OsString::new(), - args: Vec::new(), - startup_timeout: Duration::from_secs(600), - generation_timeout: None, - max_restarts: 0, - lazy: false, - stall_timeout: None, - before_load: None, - min_free_vram_mib: 0, - vision: None, - } - } -} - /// Why a load did not happen. #[derive(Clone, Debug, PartialEq, Eq)] pub enum LoadError { @@ -176,268 +116,12 @@ pub enum Control { }, } -/// Answer a reconfigure that reached a worker which cannot do it. -pub fn reconfigure_unavailable(reply: oneshot::Sender>, why: &str) { - let _ = reply.send(Err((503, why.to_owned()))); -} - -pub async fn run( - config: WorkerConfig, - status: Arc>, - shutdown: watch::Receiver, -) { - let (sender, receiver) = mpsc::channel(1); - run_with_requests(config, status, shutdown, receiver).await; - drop(sender); -} - -pub async fn run_with_requests( - config: WorkerConfig, - status: Arc>, - shutdown: watch::Receiver, - requests: mpsc::Receiver, -) { - // The sender stays alive for the duration: with no administrative channel, nothing is ever sent. - let (_idle, control) = mpsc::channel(1); - run_supervised(config, status, shutdown, requests, control).await; -} - enum Wake { Shutdown, Load, Command(Box), } -async fn fail_loads(waiting: &mut Vec, error: &LoadError) { - for reply in waiting.drain(..) { - let _ = reply.send(Err(error.clone())); - } -} - -/// Wait while the engine is unloaded for something that needs it. -async fn wait_unloaded( - shutdown: &mut watch::Receiver, - requests: &mut mpsc::Receiver, - control: &mut mpsc::Receiver, - waiting: &mut Vec, -) -> Wake { - let mut requests_closed = false; - let mut control_closed = false; - loop { - tokio::select! { - biased; - _ = shutdown.changed() => return Wake::Shutdown, - message = control.recv(), if !control_closed => match message { - Some(Control::Reconfigure { reply, .. }) => reconfigure_unavailable(reply, "the engine is not loaded"), - Some(Control::Load { reply }) => { - waiting.push(reply); - return Wake::Load; - } - 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) => return Wake::Command(Box::new(command)), - None => requests_closed = true, - }, - } - } -} - -/// The checks before an engine is started again (not the first start): the `before_load` command, -/// then the free-VRAM gate. A failing command is logged and the load goes on, as in the Original. -async fn reload_gate(config: &WorkerConfig) -> Result<(), LoadError> { - if let Some(before) = &config.before_load { - crate::elog!("before loading: {before:?}"); - let mut command = match before { - BeforeLoad::Shell(line) => { - let mut c = Command::new("sh"); - c.arg("-c").arg(line); - c - } - BeforeLoad::Argv(argv) if !argv.is_empty() => { - let mut c = Command::new(&argv[0]); - c.args(&argv[1..]); - c - } - BeforeLoad::Argv(_) => Command::new("true"), - }; - command.stdin(Stdio::null()).kill_on_drop(true); - match command.spawn() { - Ok(mut child) => match timeout(Duration::from_secs(120), child.wait()).await { - Ok(Ok(_)) => {} - Ok(Err(error)) => { - crate::elog!("the before_load command failed ({error}); loading anyway") - } - Err(_) => { - crate::elog!("the before_load command timed out; loading anyway"); - let _ = child.kill().await; - } - }, - Err(error) => crate::elog!("the before_load command failed ({error}); loading anyway"), - } - } - if config.min_free_vram_mib > 0 { - // Memory another process just gave back can take a moment. - let deadline = tokio::time::Instant::now() + Duration::from_secs(15); - let mut free = crate::cuda_memory::free_mib(config.cuda_memory.as_ref()).await; - while free.is_some_and(|f| f < config.min_free_vram_mib) - && tokio::time::Instant::now() < deadline - { - tokio::time::sleep(Duration::from_millis(500)).await; - free = crate::cuda_memory::free_mib(config.cuda_memory.as_ref()).await; - } - if let Some(free) = free.filter(|f| *f < config.min_free_vram_mib) { - return Err(LoadError::GpuBusy(format!( - "the GPU is in use by another program: {free} MiB of VRAM free, the model needs {} (min_free_vram_mib) - it stays unloaded until that is free", - config.min_free_vram_mib - ))); - } - } - Ok(()) -} - -pub async fn run_supervised( - config: WorkerConfig, - status: Arc>, - mut shutdown: watch::Receiver, - mut requests: mpsc::Receiver, - mut control: mpsc::Receiver, -) { - if config.max_restarts > 3 { - crate::elog!("worker max_restarts must be between 0 and 3"); - update(&status, WorkerState::Failed, None).await; - return; - } - // A lazy engine has not reported its context yet: `--max-context N` says what it will be. - if let Some(configured) = config - .args - .windows(2) - .find(|pair| pair[0] == "--max-context") - .and_then(|pair| pair[1].parse::().ok()) - .filter(|context| *context > 0) - { - status.write().await.known_max_context = Some(configured); - } - let mut waiting: Vec = Vec::new(); - let mut inbox: Option = None; - let mut unloaded = config.lazy; - let mut started_before = false; - let mut attempt: u32 = 0; - loop { - if unloaded { - update(&status, WorkerState::Unloaded, None).await; - match wait_unloaded(&mut shutdown, &mut requests, &mut control, &mut waiting).await { - Wake::Shutdown => { - update(&status, WorkerState::Stopping, None).await; - return; - } - Wake::Load => {} - Wake::Command(command) => inbox = Some(*command), - } - unloaded = false; - attempt = 0; - } - if (started_before || config.lazy) - && let Err(error) = reload_gate(&config).await - { - let message = match &error { - LoadError::GpuBusy(m) | LoadError::Failed(m) => m.clone(), - }; - crate::elog!("{message}"); - fail_loads(&mut waiting, &error).await; - if let Some(command) = inbox.take() { - send_failure(command.result, message).await; - } - unloaded = true; - continue; - } - // The image encoder first, as at a start: a GPU encoder takes its VRAM before the engine sizes its cache. - if let Some(vision) = &config.vision - && let Err(error) = vision.ensure_running().await - { - let message = error.to_string(); - crate::elog!("{message}"); - let error = LoadError::Failed(message.clone()); - fail_loads(&mut waiting, &error).await; - if let Some(command) = inbox.take() { - send_failure(command.result, message).await; - } - unloaded = true; - continue; - } - started_before = true; - match run_session( - &config, - &status, - &mut shutdown, - &mut requests, - &mut control, - &mut inbox, - &mut waiting, - ) - .await - { - SessionExit::Stopped => return, - SessionExit::StartupFailed => { - fail_loads( - &mut waiting, - &LoadError::Failed("the engine failed to start".into()), - ) - .await; - return; - } - SessionExit::Unloaded => { - unloaded = true; - continue; - } - SessionExit::RuntimeFailed if attempt == config.max_restarts => { - fail_loads(&mut waiting, &LoadError::Failed("the engine failed".into())).await; - return; - } - SessionExit::RuntimeFailed => {} - } - update(&status, WorkerState::Restarting, None).await; - let delay = Duration::from_secs(2 << attempt); - crate::elog!( - "Strata engine restart {}/{} in {} seconds", - attempt + 1, - config.max_restarts, - delay.as_secs() - ); - attempt += 1; - while let Ok(command) = requests.try_recv() { - send_failure( - command.result, - "worker failed; request was not replayed".to_owned(), - ) - .await; - } - let backoff = tokio::time::sleep(delay); - tokio::pin!(backoff); - let mut requests_closed = requests.is_closed() && requests.is_empty(); - loop { - tokio::select! { - biased; - _ = shutdown.changed() => { - update(&status, WorkerState::Stopping, None).await; - return; - } - _ = &mut backoff => break, - command = requests.recv(), if !requests_closed => { - match command { - Some(command) => send_failure(command.result, - "worker is restarting; request was not replayed".to_owned()).await, - None => requests_closed = true, - } - } - } - } - } -} - enum SessionExit { Stopped, StartupFailed, @@ -445,605 +129,6 @@ enum SessionExit { Unloaded, } -async fn run_session( - config: &WorkerConfig, - status: &RwLock, - shutdown: &mut watch::Receiver, - requests: &mut mpsc::Receiver, - control: &mut mpsc::Receiver, - inbox: &mut Option, - waiting: &mut Vec, -) -> SessionExit { - if *shutdown.borrow() { - update(status, WorkerState::Stopping, None).await; - return SessionExit::Stopped; - } - update(status, WorkerState::Starting, None).await; - let mut command = Command::new(&config.executable); - if let Some(selection) = &config.cuda_memory { - if let Err(error) = selection.recheck().await { - crate::elog!("GPU admission failed before worker spawn: {error}"); - update(status, WorkerState::Failed, None).await; - return SessionExit::StartupFailed; - } - command.env("CUDA_VISIBLE_DEVICES", &selection.uuid); - } - if *shutdown.borrow() { - update(status, WorkerState::Stopping, None).await; - return SessionExit::Stopped; - } - let mut child = match command - .arg("--serve") - .args(&config.args) - .stdin(Stdio::piped()) - .stdout(Stdio::piped()) - .stderr(Stdio::inherit()) - .kill_on_drop(true) - .spawn() - { - Ok(child) => child, - Err(error) => { - crate::elog!("failed to start Strata engine: {error}"); - update(status, WorkerState::Failed, None).await; - return SessionExit::StartupFailed; - } - }; - - // Keep stdin outside Child: Child::wait closes any stdin it still owns. - let mut stdin = child.stdin.take(); - let stdout = child.stdout.take().expect("piped engine stdout"); - let mut lines = BufReader::new(stdout).lines(); - let startup_deadline = tokio::time::sleep(config.startup_timeout); - tokio::pin!(startup_deadline); - let mut requests_closed = false; - let mut control_closed = false; - let max_context = loop { - let line = tokio::select! { - biased; - _ = shutdown.changed() => { - update(status, WorkerState::Stopping, None).await; - stop(&mut child, &mut stdin).await; - return SessionExit::Stopped; - } - _ = &mut startup_deadline => { - crate::elog!("Strata engine did not become ready before the startup timeout"); - stop(&mut child, &mut stdin).await; - update(status, WorkerState::Failed, None).await; - return SessionExit::StartupFailed; - } - message = control.recv(), if !control_closed => { - match message { - Some(Control::Reconfigure { reply, .. }) => reconfigure_unavailable(reply, "the engine is starting"), - // A load that arrives while the engine starts is answered at READY. - Some(Control::Load { reply }) => waiting.push(reply), - Some(Control::Unload { reply, .. }) => { - let _ = reply.send(leleka_serving_policy::idle::Outcome::Busy); - } - None => control_closed = true, - } - continue; - } - command = requests.recv(), if !requests_closed => { - match command { - Some(command) => send_failure(command.result, - "worker is starting; request was not replayed".to_owned()).await, - None => requests_closed = true, - } - continue; - } - line = lines.next_line() => line, - }; - match line { - Ok(Some(line)) if line.starts_with("READY") => { - if let Some(max_context) = parse_ready(&line) { - update(status, WorkerState::Ready, Some(max_context)).await; - status.write().await.last_activity = Some(tokio::time::Instant::now()); - for reply in waiting.drain(..) { - let _ = reply.send(Ok(())); - } - break max_context; - } - crate::elog!("Strata engine sent an invalid READY line"); - stop(&mut child, &mut stdin).await; - update(status, WorkerState::Failed, None).await; - return SessionExit::StartupFailed; - } - Ok(Some(_)) => {} - Ok(None) => { - crate::elog!("Strata engine exited before READY"); - terminate(&mut child, &mut stdin).await; - update(status, WorkerState::Failed, None).await; - return SessionExit::StartupFailed; - } - Err(error) => { - crate::elog!("failed to read Strata engine output: {error}"); - stop(&mut child, &mut stdin).await; - update(status, WorkerState::Failed, None).await; - return SessionExit::StartupFailed; - } - } - }; - - loop { - tokio::select! { - _ = shutdown.changed() => { - update(status, WorkerState::Stopping, None).await; - stop(&mut child, &mut stdin).await; - return SessionExit::Stopped; - }, - result = child.wait() => { - crate::elog!("Strata engine exited: {result:?}"); - update(status, WorkerState::Failed, None).await; - return SessionExit::RuntimeFailed; - }, - message = control.recv(), if !control_closed => { - match message { - Some(Control::Reconfigure { reply, .. }) => reconfigure_unavailable(reply, "this engine cannot be reconfigured at run time"), - Some(Control::Load { reply }) => { - let _ = reply.send(Ok(())); - } - Some(Control::Unload { idle_for, reply }) => { - let idle_s = status - .read() - .await - .last_activity - .map_or(f64::MAX, |at| at.elapsed().as_secs_f64()); - let outcome = leleka_serving_policy::idle::decide( - leleka_serving_policy::idle::Situation { - supported: true, - loaded: true, - busy: inbox.is_some() || !requests.is_empty(), - idle_s, - }, - idle_for.map(|d| d.as_secs_f64()), - ); - if outcome == leleka_serving_policy::idle::Outcome::Unloaded { - update(status, WorkerState::Unloaded, None).await; - stop(&mut child, &mut stdin).await; - if let Some(vision) = &config.vision { - vision.unload().await; - } - let _ = reply.send(outcome); - return SessionExit::Unloaded; - } - let _ = reply.send(outcome); - } - None => control_closed = true, - } - }, - command = async { - match inbox.take() { - Some(command) => Some(command), - None => requests.recv().await, - } - }, if !requests_closed => { - match command { - Some(mut command) => { - if command.result.is_closed() || command.queue.take().is_some_and(|ticket| !ticket.claim()) { - continue; - } - status.write().await.last_activity = Some(tokio::time::Instant::now()); - // Retain the command activity until protocol cleanup, - // including STOP/QUIT and failed-process termination. - let _activity = command.activity.take(); - // The encoder and the engine never use the GPU at the same time. - let _turn = match &config.vision { - Some(vision) => Some(vision.gate.clone().lock_owned().await), - None => None, - }; - tokio::select! { - (timed_out, result) = async { - let generation = generate(&mut stdin, &mut lines, &mut command, max_context, status, config.stall_timeout); - match config.generation_timeout { - Some(duration) => match timeout(duration, generation).await { - Ok(result) => (false, result), - Err(_) => (true, Err("generation exceeded configured execution deadline".to_owned())), - }, - None => (false, generation.await), - } - } => { - if let Err(error) = result { - crate::wlog!("Strata engine protocol failed: {error}"); - command.request.obs.error(&error); - command.request.obs.engine_restarted(); - command.request.obs.finalize(); - update(status, WorkerState::Failed, None).await; - terminate(&mut child, &mut stdin).await; - // A full streaming channel must not delay process cleanup - // or finite restart indefinitely. Closing it also signals - // failure to the response adapter once buffered tokens drain. - if timed_out || error.starts_with(STALL_PREFIX) { - let _ = timeout(Duration::from_secs(1), send_failure(command.result, error)).await; - } - return SessionExit::RuntimeFailed; - } - status.write().await.last_activity = Some(tokio::time::Instant::now()); - } - _ = shutdown.changed() => { - update(status, WorkerState::Stopping, None).await; - stop_active(&mut child, &mut stdin).await; - return SessionExit::Stopped; - } - } - } - None => requests_closed = true, - } - } - } - } -} - -/// Add up one pass's `DONE` counters (reasoning-budget passes report separately). -fn add_opt(total: Option, part: Option) -> Option { - match (total, part) { - (None, None) => None, - (a, b) => Some(a.unwrap_or(0).saturating_add(b.unwrap_or(0))), - } -} - -/// What the client sees after a budget wrap-up: one `DONE` for the whole request. -fn combine_done(first: &Done, passes: &[Done], generated: u64, finish: wire::Finish) -> Done { - let mut done = Done { - generated, - prompt_tokens: first.prompt_tokens, - prompt_ms: 0.0, - decode_ms: 0.0, - finish, - drafts_accepted: None, - drafts_offered: None, - // Only what the caller's own prompt reused: the tokens of the first pass's prefix, not the - // generated text the second pass re-reads from the engine's own cache. - reused: first.reused, - expert_hits: None, - expert_lookups: None, - }; - for pass in passes { - done.prompt_ms += pass.prompt_ms; - done.decode_ms += pass.decode_ms; - done.drafts_accepted = add_opt(done.drafts_accepted, pass.drafts_accepted); - done.drafts_offered = add_opt(done.drafts_offered, pass.drafts_offered); - done.expert_hits = add_opt(done.expert_hits, pass.expert_hits); - done.expert_lookups = add_opt(done.expert_lookups, pass.expert_lookups); - } - done -} - -async fn generate( - stdin: &mut Option, - lines: &mut tokio::io::Lines>, - command: &mut GenerationCommand, - max_context: usize, - status: &RwLock, - stall_timeout: Option, -) -> Result<(), String> { - if command.result.is_closed() { - return Ok(()); - } - let fits_context = usize::try_from(command.request.max_new) - .ok() - .and_then(|new| command.request.token_ids.len().checked_add(new)) - .and_then(|total| total.checked_add(8)) - .is_some_and(|total| total <= max_context); - if !fits_context { - send_failure( - command.result.take(), - "prompt, output budget, and 8-token margin exceed context".to_owned(), - ) - .await; - return Ok(()); - } - let request = match command.request.line() { - Ok(line) => line, - Err(error) => { - send_failure(command.result.take(), error.to_owned()).await; - return Ok(()); - } - }; - status.write().await.metrics.start(); - command.request.obs.engine_start(); - let pipe = stdin.as_mut().ok_or("engine stdin is closed")?; - pipe.write_all(request.as_bytes()) - .await - .map_err(|error| error.to_string())?; - pipe.flush().await.map_err(|error| error.to_string())?; - let mut events = Vec::new(); - let mut stopped = false; - let stop_deadline = tokio::time::sleep(STOP_DRAIN_TIMEOUT); - tokio::pin!(stop_deadline); - - // Reasoning budget (issue #123): the thinking is wrapped up at the budget and generation goes on. - let mut budget = command.request.reasoning.clone().map(|plan| { - ( - leleka_serving_policy::reasoning::BudgetTracker::new(plan.budget), - plan, - ) - }); - let budgeted = budget.is_some(); - let mut generated: u64 = 0; // tokens delivered to the client, wrap-up included - let mut segment: Vec = Vec::new(); // this pass's delivered tokens - let mut prompt: Vec = if budgeted { - command.request.token_ids.clone() - } else { - Vec::new() - }; - let mut wrap_pending = false; // a wrap-up STOP is in flight: tokens until its DONE are discarded - let mut passes: Vec = Vec::new(); - let mut first_pass = true; - - // The stall watchdog seen from outside: one poll a second over the engine's lines. - let started = tokio::time::Instant::now(); - let mut lines_read: u64 = 0; - let mut dog = stall_timeout.map(|limit| { - leleka_serving_policy::watchdog::StallWatchdog::new( - i64::try_from(limit.as_secs().max(1)).unwrap_or(i64::MAX), - 0, - leleka_serving_policy::watchdog::Counters { - beats: 0, - busy: true, - ticks: 0, - }, - ) - }); - let mut ticker = tokio::time::interval(Duration::from_secs(1)); - ticker.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Delay); - ticker.reset(); - - loop { - let line = tokio::select! { - biased; - _ = &mut stop_deadline, if stopped || wrap_pending => { - return Err("engine did not terminate generation within 20 seconds of STOP".to_owned()); - } - _ = command.result.closed(), if !stopped => { - if !wrap_pending { - pipe.write_all(b"STOP\n").await.map_err(|error| error.to_string())?; - pipe.flush().await.map_err(|error| error.to_string())?; - stop_deadline.as_mut().reset(tokio::time::Instant::now() + STOP_DRAIN_TIMEOUT); - } - stopped = true; - continue; - } - _ = ticker.tick(), if dog.is_some() => { - if let Some(dog) = dog.as_mut() - && let leleka_serving_policy::watchdog::Verdict::Stalled { quiet_ms, .. } = dog.poll( - u64::try_from(started.elapsed().as_millis()).unwrap_or(u64::MAX), - leleka_serving_policy::watchdog::Counters { beats: lines_read, busy: true, ticks: 0 }, - ) - { - return Err(format!( - "{STALL_PREFIX} for {} s during a request (stall watchdog)", - quiet_ms / 1000 - )); - } - continue; - } - line = lines.next_line() => line.map_err(|error| error.to_string())?, - } - .ok_or("engine exited before a terminal line")?; - lines_read = lines_read.wrapping_add(1); - match wire::parse_line(&line)? { - Some(Event::Error(message)) => { - status.write().await.metrics.fail(); - command.request.obs.error(&message); - command.request.obs.finalize(); - send_failure(command.result.take(), message).await; - return Ok(()); - } - Some(Event::Done(done)) => { - let disconnected = stopped || command.result.is_closed(); - if wrap_pending && !disconnected { - // The budget was reached: close the thinking and let the model answer. - wrap_pending = false; - passes.push(done); - let Some((_, plan)) = budget.take() else { - return Err("reasoning budget state lost".into()); - }; - let room = i64::from(command.request.max_new) - - i64::try_from(generated).unwrap_or(i64::MAX) - - i64::try_from(plan.wrap_up.len()).unwrap_or(i64::MAX); - if room < 1 { - // No room left to answer: "length", as without a budget. - let combined = - combine_done(&passes[0], &passes, generated, wire::Finish::Length); - return finish(command, events, combined, false, status).await; - } - crate::elog!( - "thinking budget reached ({} tokens): wrapping up the thinking", - plan.budget - ); - for id in &plan.wrap_up { - generated += 1; - deliver(command, &mut events, Event::Token(*id)).await; - } - prompt.extend_from_slice(&segment); - prompt.extend_from_slice(&plan.wrap_up); - segment.clear(); - let next = Generate { - token_ids: prompt.clone(), - max_new: u32::try_from( - i64::from(command.request.max_new) - - i64::try_from(generated).unwrap_or(i64::MAX), - ) - .unwrap_or(1), - reasoning: None, - ..command.request.clone() - }; - let next_line = next.line().map_err(str::to_owned)?; - pipe.write_all(next_line.as_bytes()) - .await - .map_err(|error| error.to_string())?; - pipe.flush().await.map_err(|error| error.to_string())?; - first_pass = false; - continue; - } - let done_out = if passes.is_empty() { - done - } else { - passes.push(done.clone()); - combine_done(&passes[0], &passes, generated, done.finish) - }; - return finish(command, events, done_out, disconnected, status).await; - } - Some(Event::PromptProgress { .. }) if !first_pass => {} - Some(_) if stopped || wrap_pending => {} - Some(event) => { - if let (Event::Token(id), Some((tracker, plan))) = (&event, budget.as_mut()) { - generated += 1; - segment.push(*id); - let verdict = if plan.stop_ids.contains(id) { - leleka_serving_policy::reasoning::Verdict::Continue - } else { - tracker.push(&(plan.token_bytes)(*id)) - }; - deliver(command, &mut events, event).await; - if verdict == leleka_serving_policy::reasoning::Verdict::WrapUp { - pipe.write_all(b"STOP\n") - .await - .map_err(|error| error.to_string())?; - pipe.flush().await.map_err(|error| error.to_string())?; - wrap_pending = true; - stop_deadline - .as_mut() - .reset(tokio::time::Instant::now() + STOP_DRAIN_TIMEOUT); - } - } else { - if matches!(event, Event::Token(_)) { - generated += 1; - } - deliver(command, &mut events, event).await; - } - } - None => {} - } - } -} - -/// Hand one event to the client side (buffered or streamed). -pub(crate) async fn deliver(command: &GenerationCommand, events: &mut Vec, event: Event) { - match &command.result { - GenerationResult::Buffered(_) => events.push(event), - GenerationResult::Streaming(_) => command.result.send_event(event).await, - GenerationResult::Finished => {} - } -} - -/// The terminal event: hand `done` to the client and record the generation. -pub(crate) async fn finish( - command: &mut GenerationCommand, - mut events: Vec, - done: Done, - disconnected: bool, - status: &RwLock, -) -> Result<(), String> { - // The per-request record (`request_log`, one line, no prompt or output text) is completed here and written after the client - // side has the terminal event, so a slow log sink never delays a response. - command.request.obs.done(&done, disconnected); - let finished_ms = unix_ms(); - let event = Event::Done(done.clone()); - match command.result.take() { - GenerationResult::Buffered(sender) => { - events.push(event); - let _ = sender.send(Ok(events)); - } - GenerationResult::Streaming(sender) => { - let _ = sender.send(Ok(event)).await; - } - GenerationResult::Finished => {} - } - // The lab scripts (`scripts/cp/live_report.py`, `scripts/e2e/analyze_session.py`) parse this exact line: kept under LELEKA_LOG_LEGACY=1. - if leleka_obs::settings().legacy { - leleka_obs::legacy_line(&format!( - "generation done: t_unix_ms={} finish={:?} prompt_tokens={} reused={} generated={} prompt_ms={:.1} decode_ms={:.1} disconnected={}", - finished_ms, - done.finish, - done.prompt_tokens, - done.reused.unwrap_or(0), - done.generated, - done.prompt_ms, - done.decode_ms, - disconnected - )); - } - status.write().await.metrics.finish(&done, disconnected); - command.request.obs.finalize(); - Ok(()) -} - -/// Wall-clock milliseconds for log lines that are joined with client-side timestamps. -pub(crate) fn unix_ms() -> u128 { - std::time::SystemTime::now() - .duration_since(std::time::UNIX_EPOCH) - .map_or(0, |d| d.as_millis()) -} - -pub(crate) async fn send_failure(result: GenerationResult, message: String) { - match result { - GenerationResult::Buffered(sender) => { - let _ = sender.send(Err(message)); - } - GenerationResult::Streaming(sender) => { - let _ = sender.send(Err(message)).await; - } - GenerationResult::Finished => {} - } -} - -fn parse_ready(line: &str) -> Option { - let mut fields = line.split_whitespace(); - if fields.next() != Some("READY") { - return None; - } - let context = fields.next()?.parse::().ok()?; - (context > 0).then_some(context) -} - -pub(crate) async fn update( - status: &RwLock, - state: WorkerState, - max_context: Option, -) { - let mut status = status.write().await; - if state != WorkerState::Ready { - status.metrics.fail(); - } - status.state = state; - status.max_context = max_context; - if max_context.is_some() { - status.known_max_context = max_context; - } -} - -async fn stop(child: &mut Child, stdin: &mut Option) { - if let Some(mut pipe) = stdin.take() { - let _ = pipe.write_all(b"QUIT\n").await; - let _ = pipe.flush().await; - } - if timeout(Duration::from_secs(20), child.wait()) - .await - .is_err() - { - let _ = child.start_kill(); - let _ = child.wait().await; - } -} - -async fn stop_active(child: &mut Child, stdin: &mut Option) { - if let Some(pipe) = stdin.as_mut() { - let _ = pipe.write_all(b"STOP\n").await; - let _ = pipe.flush().await; - } - stop(child, stdin).await; -} - -// Protocol alignment is lost: never reuse this process or add another graceful -// wait after an expired STOP deadline. Dropping the request receiver releases -// queued clients when the supervisor returns. -async fn terminate(child: &mut Child, stdin: &mut Option) { - stdin.take(); - let _ = child.start_kill(); - let _ = child.wait().await; -} - #[cfg(all(test, unix))] mod tests { use super::*; @@ -2168,3 +1253,19 @@ mod tests { let _ = timeout(Duration::from_secs(25), worker.task).await; } } + +mod impl_generationresult; +#[allow(unused_imports)] +pub use impl_generationresult::*; +mod run_supervised; +#[allow(unused_imports)] +pub use run_supervised::*; +mod run_session; +#[allow(unused_imports)] +pub use run_session::*; +mod combine_done; +#[allow(unused_imports)] +pub use combine_done::*; +mod finish; +#[allow(unused_imports)] +pub use finish::*; diff --git a/control-plane/src/worker/combine_done.rs b/control-plane/src/worker/combine_done.rs new file mode 100644 index 00000000..7d8e0a21 --- /dev/null +++ b/control-plane/src/worker/combine_done.rs @@ -0,0 +1,255 @@ +//! Moved out of the parent module by STRA-338: fn combine_done, fn generate, fn deliver. + +#[allow(unused_imports)] +use super::*; + +/// What the client sees after a budget wrap-up: one `DONE` for the whole request. +pub(super) fn combine_done( + first: &Done, + passes: &[Done], + generated: u64, + finish: wire::Finish, +) -> Done { + let mut done = Done { + generated, + prompt_tokens: first.prompt_tokens, + prompt_ms: 0.0, + decode_ms: 0.0, + finish, + drafts_accepted: None, + drafts_offered: None, + // Only what the caller's own prompt reused: the tokens of the first pass's prefix, not the + // generated text the second pass re-reads from the engine's own cache. + reused: first.reused, + expert_hits: None, + expert_lookups: None, + }; + for pass in passes { + done.prompt_ms += pass.prompt_ms; + done.decode_ms += pass.decode_ms; + done.drafts_accepted = add_opt(done.drafts_accepted, pass.drafts_accepted); + done.drafts_offered = add_opt(done.drafts_offered, pass.drafts_offered); + done.expert_hits = add_opt(done.expert_hits, pass.expert_hits); + done.expert_lookups = add_opt(done.expert_lookups, pass.expert_lookups); + } + done +} + +pub(super) async fn generate( + stdin: &mut Option, + lines: &mut tokio::io::Lines>, + command: &mut GenerationCommand, + max_context: usize, + status: &RwLock, + stall_timeout: Option, +) -> Result<(), String> { + if command.result.is_closed() { + return Ok(()); + } + let fits_context = usize::try_from(command.request.max_new) + .ok() + .and_then(|new| command.request.token_ids.len().checked_add(new)) + .and_then(|total| total.checked_add(8)) + .is_some_and(|total| total <= max_context); + if !fits_context { + send_failure( + command.result.take(), + "prompt, output budget, and 8-token margin exceed context".to_owned(), + ) + .await; + return Ok(()); + } + let request = match command.request.line() { + Ok(line) => line, + Err(error) => { + send_failure(command.result.take(), error.to_owned()).await; + return Ok(()); + } + }; + status.write().await.metrics.start(); + command.request.obs.engine_start(); + let pipe = stdin.as_mut().ok_or("engine stdin is closed")?; + pipe.write_all(request.as_bytes()) + .await + .map_err(|error| error.to_string())?; + pipe.flush().await.map_err(|error| error.to_string())?; + let mut events = Vec::new(); + let mut stopped = false; + let stop_deadline = tokio::time::sleep(STOP_DRAIN_TIMEOUT); + tokio::pin!(stop_deadline); + + // Reasoning budget (issue #123): the thinking is wrapped up at the budget and generation goes on. + let mut budget = command.request.reasoning.clone().map(|plan| { + ( + leleka_serving_policy::reasoning::BudgetTracker::new(plan.budget), + plan, + ) + }); + let budgeted = budget.is_some(); + let mut generated: u64 = 0; // tokens delivered to the client, wrap-up included + let mut segment: Vec = Vec::new(); // this pass's delivered tokens + let mut prompt: Vec = if budgeted { + command.request.token_ids.clone() + } else { + Vec::new() + }; + let mut wrap_pending = false; // a wrap-up STOP is in flight: tokens until its DONE are discarded + let mut passes: Vec = Vec::new(); + let mut first_pass = true; + + // The stall watchdog seen from outside: one poll a second over the engine's lines. + let started = tokio::time::Instant::now(); + let mut lines_read: u64 = 0; + let mut dog = stall_timeout.map(|limit| { + leleka_serving_policy::watchdog::StallWatchdog::new( + i64::try_from(limit.as_secs().max(1)).unwrap_or(i64::MAX), + 0, + leleka_serving_policy::watchdog::Counters { + beats: 0, + busy: true, + ticks: 0, + }, + ) + }); + let mut ticker = tokio::time::interval(Duration::from_secs(1)); + ticker.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Delay); + ticker.reset(); + + loop { + let line = tokio::select! { + biased; + _ = &mut stop_deadline, if stopped || wrap_pending => { + return Err("engine did not terminate generation within 20 seconds of STOP".to_owned()); + } + _ = command.result.closed(), if !stopped => { + if !wrap_pending { + pipe.write_all(b"STOP\n").await.map_err(|error| error.to_string())?; + pipe.flush().await.map_err(|error| error.to_string())?; + stop_deadline.as_mut().reset(tokio::time::Instant::now() + STOP_DRAIN_TIMEOUT); + } + stopped = true; + continue; + } + _ = ticker.tick(), if dog.is_some() => { + if let Some(dog) = dog.as_mut() + && let leleka_serving_policy::watchdog::Verdict::Stalled { quiet_ms, .. } = dog.poll( + u64::try_from(started.elapsed().as_millis()).unwrap_or(u64::MAX), + leleka_serving_policy::watchdog::Counters { beats: lines_read, busy: true, ticks: 0 }, + ) + { + return Err(format!( + "{STALL_PREFIX} for {} s during a request (stall watchdog)", + quiet_ms / 1000 + )); + } + continue; + } + line = lines.next_line() => line.map_err(|error| error.to_string())?, + } + .ok_or("engine exited before a terminal line")?; + lines_read = lines_read.wrapping_add(1); + match wire::parse_line(&line)? { + Some(Event::Error(message)) => { + status.write().await.metrics.fail(); + command.request.obs.error(&message); + command.request.obs.finalize(); + send_failure(command.result.take(), message).await; + return Ok(()); + } + Some(Event::Done(done)) => { + let disconnected = stopped || command.result.is_closed(); + if wrap_pending && !disconnected { + // The budget was reached: close the thinking and let the model answer. + wrap_pending = false; + passes.push(done); + let Some((_, plan)) = budget.take() else { + return Err("reasoning budget state lost".into()); + }; + let room = i64::from(command.request.max_new) + - i64::try_from(generated).unwrap_or(i64::MAX) + - i64::try_from(plan.wrap_up.len()).unwrap_or(i64::MAX); + if room < 1 { + // No room left to answer: "length", as without a budget. + let combined = + combine_done(&passes[0], &passes, generated, wire::Finish::Length); + return finish(command, events, combined, false, status).await; + } + crate::elog!( + "thinking budget reached ({} tokens): wrapping up the thinking", + plan.budget + ); + for id in &plan.wrap_up { + generated += 1; + deliver(command, &mut events, Event::Token(*id)).await; + } + prompt.extend_from_slice(&segment); + prompt.extend_from_slice(&plan.wrap_up); + segment.clear(); + let next = Generate { + token_ids: prompt.clone(), + max_new: u32::try_from( + i64::from(command.request.max_new) + - i64::try_from(generated).unwrap_or(i64::MAX), + ) + .unwrap_or(1), + reasoning: None, + ..command.request.clone() + }; + let next_line = next.line().map_err(str::to_owned)?; + pipe.write_all(next_line.as_bytes()) + .await + .map_err(|error| error.to_string())?; + pipe.flush().await.map_err(|error| error.to_string())?; + first_pass = false; + continue; + } + let done_out = if passes.is_empty() { + done + } else { + passes.push(done.clone()); + combine_done(&passes[0], &passes, generated, done.finish) + }; + return finish(command, events, done_out, disconnected, status).await; + } + Some(Event::PromptProgress { .. }) if !first_pass => {} + Some(_) if stopped || wrap_pending => {} + Some(event) => { + if let (Event::Token(id), Some((tracker, plan))) = (&event, budget.as_mut()) { + generated += 1; + segment.push(*id); + let verdict = if plan.stop_ids.contains(id) { + leleka_serving_policy::reasoning::Verdict::Continue + } else { + tracker.push(&(plan.token_bytes)(*id)) + }; + deliver(command, &mut events, event).await; + if verdict == leleka_serving_policy::reasoning::Verdict::WrapUp { + pipe.write_all(b"STOP\n") + .await + .map_err(|error| error.to_string())?; + pipe.flush().await.map_err(|error| error.to_string())?; + wrap_pending = true; + stop_deadline + .as_mut() + .reset(tokio::time::Instant::now() + STOP_DRAIN_TIMEOUT); + } + } else { + if matches!(event, Event::Token(_)) { + generated += 1; + } + deliver(command, &mut events, event).await; + } + } + None => {} + } + } +} + +/// Hand one event to the client side (buffered or streamed). +pub(crate) async fn deliver(command: &GenerationCommand, events: &mut Vec, event: Event) { + match &command.result { + GenerationResult::Buffered(_) => events.push(event), + GenerationResult::Streaming(_) => command.result.send_event(event).await, + GenerationResult::Finished => {} + } +} diff --git a/control-plane/src/worker/finish.rs b/control-plane/src/worker/finish.rs new file mode 100644 index 00000000..26df95aa --- /dev/null +++ b/control-plane/src/worker/finish.rs @@ -0,0 +1,121 @@ +//! Moved out of the parent module by STRA-338: fn finish, fn unix_ms, fn send_failure, fn parse_ready, fn update, fn stop .... + +#[allow(unused_imports)] +use super::*; + +/// The terminal event: hand `done` to the client and record the generation. +pub(crate) async fn finish( + command: &mut GenerationCommand, + mut events: Vec, + done: Done, + disconnected: bool, + status: &RwLock, +) -> Result<(), String> { + // The per-request record (`request_log`, one line, no prompt or output text) is completed here and written after the client + // side has the terminal event, so a slow log sink never delays a response. + command.request.obs.done(&done, disconnected); + let finished_ms = unix_ms(); + let event = Event::Done(done.clone()); + match command.result.take() { + GenerationResult::Buffered(sender) => { + events.push(event); + let _ = sender.send(Ok(events)); + } + GenerationResult::Streaming(sender) => { + let _ = sender.send(Ok(event)).await; + } + GenerationResult::Finished => {} + } + // The lab scripts (`scripts/cp/live_report.py`, `scripts/e2e/analyze_session.py`) parse this exact line: kept under LELEKA_LOG_LEGACY=1. + if leleka_obs::settings().legacy { + leleka_obs::legacy_line(&format!( + "generation done: t_unix_ms={} finish={:?} prompt_tokens={} reused={} generated={} prompt_ms={:.1} decode_ms={:.1} disconnected={}", + finished_ms, + done.finish, + done.prompt_tokens, + done.reused.unwrap_or(0), + done.generated, + done.prompt_ms, + done.decode_ms, + disconnected + )); + } + status.write().await.metrics.finish(&done, disconnected); + command.request.obs.finalize(); + Ok(()) +} + +/// Wall-clock milliseconds for log lines that are joined with client-side timestamps. +pub(crate) fn unix_ms() -> u128 { + std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .map_or(0, |d| d.as_millis()) +} + +pub(crate) async fn send_failure(result: GenerationResult, message: String) { + match result { + GenerationResult::Buffered(sender) => { + let _ = sender.send(Err(message)); + } + GenerationResult::Streaming(sender) => { + let _ = sender.send(Err(message)).await; + } + GenerationResult::Finished => {} + } +} + +pub(super) fn parse_ready(line: &str) -> Option { + let mut fields = line.split_whitespace(); + if fields.next() != Some("READY") { + return None; + } + let context = fields.next()?.parse::().ok()?; + (context > 0).then_some(context) +} + +pub(crate) async fn update( + status: &RwLock, + state: WorkerState, + max_context: Option, +) { + let mut status = status.write().await; + if state != WorkerState::Ready { + status.metrics.fail(); + } + status.state = state; + status.max_context = max_context; + if max_context.is_some() { + status.known_max_context = max_context; + } +} + +pub(super) async fn stop(child: &mut Child, stdin: &mut Option) { + if let Some(mut pipe) = stdin.take() { + let _ = pipe.write_all(b"QUIT\n").await; + let _ = pipe.flush().await; + } + if timeout(Duration::from_secs(20), child.wait()) + .await + .is_err() + { + let _ = child.start_kill(); + let _ = child.wait().await; + } +} + +pub(super) async fn stop_active(child: &mut Child, stdin: &mut Option) { + if let Some(pipe) = stdin.as_mut() { + let _ = pipe.write_all(b"STOP\n").await; + let _ = pipe.flush().await; + } + stop(child, stdin).await; +} + +// Protocol alignment is lost: never reuse this process or add another graceful +// wait after an expired STOP deadline. Dropping the request receiver releases +// queued clients when the supervisor returns. +pub(super) async fn terminate(child: &mut Child, stdin: &mut Option) { + stdin.take(); + let _ = child.start_kill(); + let _ = child.wait().await; +} diff --git a/control-plane/src/worker/impl_generationresult.rs b/control-plane/src/worker/impl_generationresult.rs new file mode 100644 index 00000000..e691a0f6 --- /dev/null +++ b/control-plane/src/worker/impl_generationresult.rs @@ -0,0 +1,181 @@ +//! Moved out of the parent module by STRA-338: impl GenerationResult, impl Default_for_WorkerStatus, impl Default_for_WorkerConfig, fn reconfigure_unavailable, fn run, fn run_with_requests .... + +#[allow(unused_imports)] +use super::*; + +impl GenerationResult { + pub(crate) fn take(&mut self) -> Self { + std::mem::replace(self, Self::Finished) + } + + pub(crate) fn is_closed(&self) -> bool { + match self { + Self::Buffered(sender) => sender.is_closed(), + Self::Streaming(sender) => sender.is_closed(), + Self::Finished => true, + } + } + + pub(crate) async fn closed(&mut self) { + match self { + Self::Buffered(sender) => sender.closed().await, + Self::Streaming(sender) => sender.closed().await, + Self::Finished => {} + } + } + + pub(crate) async fn send_event(&self, event: Event) { + if let Self::Streaming(sender) = self { + let _ = sender.send(Ok(event)).await; + } + } +} + +impl Default for WorkerStatus { + fn default() -> Self { + Self { + state: WorkerState::Unconfigured, + max_context: None, + known_max_context: None, + last_activity: None, + metrics: crate::metrics::GenerationMetrics::with_history(), + output_cap: None, + text_level_engine: false, + } + } +} + +impl Default for WorkerConfig { + fn default() -> Self { + Self { + cuda_memory: None, + executable: OsString::new(), + args: Vec::new(), + startup_timeout: Duration::from_secs(600), + generation_timeout: None, + max_restarts: 0, + lazy: false, + stall_timeout: None, + before_load: None, + min_free_vram_mib: 0, + vision: None, + } + } +} + +/// Answer a reconfigure that reached a worker which cannot do it. +pub fn reconfigure_unavailable(reply: oneshot::Sender>, why: &str) { + let _ = reply.send(Err((503, why.to_owned()))); +} + +pub async fn run( + config: WorkerConfig, + status: Arc>, + shutdown: watch::Receiver, +) { + let (sender, receiver) = mpsc::channel(1); + run_with_requests(config, status, shutdown, receiver).await; + drop(sender); +} + +pub async fn run_with_requests( + config: WorkerConfig, + status: Arc>, + shutdown: watch::Receiver, + requests: mpsc::Receiver, +) { + // The sender stays alive for the duration: with no administrative channel, nothing is ever sent. + let (_idle, control) = mpsc::channel(1); + run_supervised(config, status, shutdown, requests, control).await; +} + +pub(super) async fn fail_loads(waiting: &mut Vec, error: &LoadError) { + for reply in waiting.drain(..) { + let _ = reply.send(Err(error.clone())); + } +} + +/// Wait while the engine is unloaded for something that needs it. +pub(super) async fn wait_unloaded( + shutdown: &mut watch::Receiver, + requests: &mut mpsc::Receiver, + control: &mut mpsc::Receiver, + waiting: &mut Vec, +) -> Wake { + let mut requests_closed = false; + let mut control_closed = false; + loop { + tokio::select! { + biased; + _ = shutdown.changed() => return Wake::Shutdown, + message = control.recv(), if !control_closed => match message { + Some(Control::Reconfigure { reply, .. }) => reconfigure_unavailable(reply, "the engine is not loaded"), + Some(Control::Load { reply }) => { + waiting.push(reply); + return Wake::Load; + } + 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) => return Wake::Command(Box::new(command)), + None => requests_closed = true, + }, + } + } +} + +/// The checks before an engine is started again (not the first start): the `before_load` command, +/// then the free-VRAM gate. A failing command is logged and the load goes on, as in the Original. +pub(super) async fn reload_gate(config: &WorkerConfig) -> Result<(), LoadError> { + if let Some(before) = &config.before_load { + crate::elog!("before loading: {before:?}"); + let mut command = match before { + BeforeLoad::Shell(line) => { + let mut c = Command::new("sh"); + c.arg("-c").arg(line); + c + } + BeforeLoad::Argv(argv) if !argv.is_empty() => { + let mut c = Command::new(&argv[0]); + c.args(&argv[1..]); + c + } + BeforeLoad::Argv(_) => Command::new("true"), + }; + command.stdin(Stdio::null()).kill_on_drop(true); + match command.spawn() { + Ok(mut child) => match timeout(Duration::from_secs(120), child.wait()).await { + Ok(Ok(_)) => {} + Ok(Err(error)) => { + crate::elog!("the before_load command failed ({error}); loading anyway") + } + Err(_) => { + crate::elog!("the before_load command timed out; loading anyway"); + let _ = child.kill().await; + } + }, + Err(error) => crate::elog!("the before_load command failed ({error}); loading anyway"), + } + } + if config.min_free_vram_mib > 0 { + // Memory another process just gave back can take a moment. + let deadline = tokio::time::Instant::now() + Duration::from_secs(15); + let mut free = crate::cuda_memory::free_mib(config.cuda_memory.as_ref()).await; + while free.is_some_and(|f| f < config.min_free_vram_mib) + && tokio::time::Instant::now() < deadline + { + tokio::time::sleep(Duration::from_millis(500)).await; + free = crate::cuda_memory::free_mib(config.cuda_memory.as_ref()).await; + } + if let Some(free) = free.filter(|f| *f < config.min_free_vram_mib) { + return Err(LoadError::GpuBusy(format!( + "the GPU is in use by another program: {free} MiB of VRAM free, the model needs {} (min_free_vram_mib) - it stays unloaded until that is free", + config.min_free_vram_mib + ))); + } + } + Ok(()) +} diff --git a/control-plane/src/worker/run_session.rs b/control-plane/src/worker/run_session.rs new file mode 100644 index 00000000..9f6a8908 --- /dev/null +++ b/control-plane/src/worker/run_session.rs @@ -0,0 +1,240 @@ +//! Moved out of the parent module by STRA-338: fn run_session, fn add_opt. + +#[allow(unused_imports)] +use super::*; + +pub(super) async fn run_session( + config: &WorkerConfig, + status: &RwLock, + shutdown: &mut watch::Receiver, + requests: &mut mpsc::Receiver, + control: &mut mpsc::Receiver, + inbox: &mut Option, + waiting: &mut Vec, +) -> SessionExit { + if *shutdown.borrow() { + update(status, WorkerState::Stopping, None).await; + return SessionExit::Stopped; + } + update(status, WorkerState::Starting, None).await; + let mut command = Command::new(&config.executable); + if let Some(selection) = &config.cuda_memory { + if let Err(error) = selection.recheck().await { + crate::elog!("GPU admission failed before worker spawn: {error}"); + update(status, WorkerState::Failed, None).await; + return SessionExit::StartupFailed; + } + command.env("CUDA_VISIBLE_DEVICES", &selection.uuid); + } + if *shutdown.borrow() { + update(status, WorkerState::Stopping, None).await; + return SessionExit::Stopped; + } + let mut child = match command + .arg("--serve") + .args(&config.args) + .stdin(Stdio::piped()) + .stdout(Stdio::piped()) + .stderr(Stdio::inherit()) + .kill_on_drop(true) + .spawn() + { + Ok(child) => child, + Err(error) => { + crate::elog!("failed to start Strata engine: {error}"); + update(status, WorkerState::Failed, None).await; + return SessionExit::StartupFailed; + } + }; + + // Keep stdin outside Child: Child::wait closes any stdin it still owns. + let mut stdin = child.stdin.take(); + let stdout = child.stdout.take().expect("piped engine stdout"); + let mut lines = BufReader::new(stdout).lines(); + let startup_deadline = tokio::time::sleep(config.startup_timeout); + tokio::pin!(startup_deadline); + let mut requests_closed = false; + let mut control_closed = false; + let max_context = loop { + let line = tokio::select! { + biased; + _ = shutdown.changed() => { + update(status, WorkerState::Stopping, None).await; + stop(&mut child, &mut stdin).await; + return SessionExit::Stopped; + } + _ = &mut startup_deadline => { + crate::elog!("Strata engine did not become ready before the startup timeout"); + stop(&mut child, &mut stdin).await; + update(status, WorkerState::Failed, None).await; + return SessionExit::StartupFailed; + } + message = control.recv(), if !control_closed => { + match message { + Some(Control::Reconfigure { reply, .. }) => reconfigure_unavailable(reply, "the engine is starting"), + // A load that arrives while the engine starts is answered at READY. + Some(Control::Load { reply }) => waiting.push(reply), + Some(Control::Unload { reply, .. }) => { + let _ = reply.send(leleka_serving_policy::idle::Outcome::Busy); + } + None => control_closed = true, + } + continue; + } + command = requests.recv(), if !requests_closed => { + match command { + Some(command) => send_failure(command.result, + "worker is starting; request was not replayed".to_owned()).await, + None => requests_closed = true, + } + continue; + } + line = lines.next_line() => line, + }; + match line { + Ok(Some(line)) if line.starts_with("READY") => { + if let Some(max_context) = parse_ready(&line) { + update(status, WorkerState::Ready, Some(max_context)).await; + status.write().await.last_activity = Some(tokio::time::Instant::now()); + for reply in waiting.drain(..) { + let _ = reply.send(Ok(())); + } + break max_context; + } + crate::elog!("Strata engine sent an invalid READY line"); + stop(&mut child, &mut stdin).await; + update(status, WorkerState::Failed, None).await; + return SessionExit::StartupFailed; + } + Ok(Some(_)) => {} + Ok(None) => { + crate::elog!("Strata engine exited before READY"); + terminate(&mut child, &mut stdin).await; + update(status, WorkerState::Failed, None).await; + return SessionExit::StartupFailed; + } + Err(error) => { + crate::elog!("failed to read Strata engine output: {error}"); + stop(&mut child, &mut stdin).await; + update(status, WorkerState::Failed, None).await; + return SessionExit::StartupFailed; + } + } + }; + + loop { + tokio::select! { + _ = shutdown.changed() => { + update(status, WorkerState::Stopping, None).await; + stop(&mut child, &mut stdin).await; + return SessionExit::Stopped; + }, + result = child.wait() => { + crate::elog!("Strata engine exited: {result:?}"); + update(status, WorkerState::Failed, None).await; + return SessionExit::RuntimeFailed; + }, + message = control.recv(), if !control_closed => { + match message { + Some(Control::Reconfigure { reply, .. }) => reconfigure_unavailable(reply, "this engine cannot be reconfigured at run time"), + Some(Control::Load { reply }) => { + let _ = reply.send(Ok(())); + } + Some(Control::Unload { idle_for, reply }) => { + let idle_s = status + .read() + .await + .last_activity + .map_or(f64::MAX, |at| at.elapsed().as_secs_f64()); + let outcome = leleka_serving_policy::idle::decide( + leleka_serving_policy::idle::Situation { + supported: true, + loaded: true, + busy: inbox.is_some() || !requests.is_empty(), + idle_s, + }, + idle_for.map(|d| d.as_secs_f64()), + ); + if outcome == leleka_serving_policy::idle::Outcome::Unloaded { + update(status, WorkerState::Unloaded, None).await; + stop(&mut child, &mut stdin).await; + if let Some(vision) = &config.vision { + vision.unload().await; + } + let _ = reply.send(outcome); + return SessionExit::Unloaded; + } + let _ = reply.send(outcome); + } + None => control_closed = true, + } + }, + command = async { + match inbox.take() { + Some(command) => Some(command), + None => requests.recv().await, + } + }, if !requests_closed => { + match command { + Some(mut command) => { + if command.result.is_closed() || command.queue.take().is_some_and(|ticket| !ticket.claim()) { + continue; + } + status.write().await.last_activity = Some(tokio::time::Instant::now()); + // Retain the command activity until protocol cleanup, + // including STOP/QUIT and failed-process termination. + let _activity = command.activity.take(); + // The encoder and the engine never use the GPU at the same time. + let _turn = match &config.vision { + Some(vision) => Some(vision.gate.clone().lock_owned().await), + None => None, + }; + tokio::select! { + (timed_out, result) = async { + let generation = generate(&mut stdin, &mut lines, &mut command, max_context, status, config.stall_timeout); + match config.generation_timeout { + Some(duration) => match timeout(duration, generation).await { + Ok(result) => (false, result), + Err(_) => (true, Err("generation exceeded configured execution deadline".to_owned())), + }, + None => (false, generation.await), + } + } => { + if let Err(error) = result { + crate::wlog!("Strata engine protocol failed: {error}"); + command.request.obs.error(&error); + command.request.obs.engine_restarted(); + command.request.obs.finalize(); + update(status, WorkerState::Failed, None).await; + terminate(&mut child, &mut stdin).await; + // A full streaming channel must not delay process cleanup + // or finite restart indefinitely. Closing it also signals + // failure to the response adapter once buffered tokens drain. + if timed_out || error.starts_with(STALL_PREFIX) { + let _ = timeout(Duration::from_secs(1), send_failure(command.result, error)).await; + } + return SessionExit::RuntimeFailed; + } + status.write().await.last_activity = Some(tokio::time::Instant::now()); + } + _ = shutdown.changed() => { + update(status, WorkerState::Stopping, None).await; + stop_active(&mut child, &mut stdin).await; + return SessionExit::Stopped; + } + } + } + None => requests_closed = true, + } + } + } + } +} + +/// Add up one pass's `DONE` counters (reasoning-budget passes report separately). +pub(super) fn add_opt(total: Option, part: Option) -> Option { + match (total, part) { + (None, None) => None, + (a, b) => Some(a.unwrap_or(0).saturating_add(b.unwrap_or(0))), + } +} diff --git a/control-plane/src/worker/run_supervised.rs b/control-plane/src/worker/run_supervised.rs new file mode 100644 index 00000000..aa0a4f9c --- /dev/null +++ b/control-plane/src/worker/run_supervised.rs @@ -0,0 +1,143 @@ +//! Moved out of the parent module by STRA-338: fn run_supervised. + +#[allow(unused_imports)] +use super::*; + +pub async fn run_supervised( + config: WorkerConfig, + status: Arc>, + mut shutdown: watch::Receiver, + mut requests: mpsc::Receiver, + mut control: mpsc::Receiver, +) { + if config.max_restarts > 3 { + crate::elog!("worker max_restarts must be between 0 and 3"); + update(&status, WorkerState::Failed, None).await; + return; + } + // A lazy engine has not reported its context yet: `--max-context N` says what it will be. + if let Some(configured) = config + .args + .windows(2) + .find(|pair| pair[0] == "--max-context") + .and_then(|pair| pair[1].parse::().ok()) + .filter(|context| *context > 0) + { + status.write().await.known_max_context = Some(configured); + } + let mut waiting: Vec = Vec::new(); + let mut inbox: Option = None; + let mut unloaded = config.lazy; + let mut started_before = false; + let mut attempt: u32 = 0; + loop { + if unloaded { + update(&status, WorkerState::Unloaded, None).await; + match wait_unloaded(&mut shutdown, &mut requests, &mut control, &mut waiting).await { + Wake::Shutdown => { + update(&status, WorkerState::Stopping, None).await; + return; + } + Wake::Load => {} + Wake::Command(command) => inbox = Some(*command), + } + unloaded = false; + attempt = 0; + } + if (started_before || config.lazy) + && let Err(error) = reload_gate(&config).await + { + let message = match &error { + LoadError::GpuBusy(m) | LoadError::Failed(m) => m.clone(), + }; + crate::elog!("{message}"); + fail_loads(&mut waiting, &error).await; + if let Some(command) = inbox.take() { + send_failure(command.result, message).await; + } + unloaded = true; + continue; + } + // The image encoder first, as at a start: a GPU encoder takes its VRAM before the engine sizes its cache. + if let Some(vision) = &config.vision + && let Err(error) = vision.ensure_running().await + { + let message = error.to_string(); + crate::elog!("{message}"); + let error = LoadError::Failed(message.clone()); + fail_loads(&mut waiting, &error).await; + if let Some(command) = inbox.take() { + send_failure(command.result, message).await; + } + unloaded = true; + continue; + } + started_before = true; + match run_session( + &config, + &status, + &mut shutdown, + &mut requests, + &mut control, + &mut inbox, + &mut waiting, + ) + .await + { + SessionExit::Stopped => return, + SessionExit::StartupFailed => { + fail_loads( + &mut waiting, + &LoadError::Failed("the engine failed to start".into()), + ) + .await; + return; + } + SessionExit::Unloaded => { + unloaded = true; + continue; + } + SessionExit::RuntimeFailed if attempt == config.max_restarts => { + fail_loads(&mut waiting, &LoadError::Failed("the engine failed".into())).await; + return; + } + SessionExit::RuntimeFailed => {} + } + update(&status, WorkerState::Restarting, None).await; + let delay = Duration::from_secs(2 << attempt); + crate::elog!( + "Strata engine restart {}/{} in {} seconds", + attempt + 1, + config.max_restarts, + delay.as_secs() + ); + attempt += 1; + while let Ok(command) = requests.try_recv() { + send_failure( + command.result, + "worker failed; request was not replayed".to_owned(), + ) + .await; + } + let backoff = tokio::time::sleep(delay); + tokio::pin!(backoff); + let mut requests_closed = requests.is_closed() && requests.is_empty(); + loop { + tokio::select! { + biased; + _ = shutdown.changed() => { + update(&status, WorkerState::Stopping, None).await; + return; + } + _ = &mut backoff => break, + command = requests.recv(), if !requests_closed => { + match command { + Some(command) => send_failure(command.result, + "worker is restarting; request was not replayed".to_owned()).await, + None => requests_closed = true, + } + } + } + } + } +} diff --git a/crates/backend-api/src/scripted.rs b/crates/backend-api/src/scripted.rs index 2b03ec45..446d9542 100644 --- a/crates/backend-api/src/scripted.rs +++ b/crates/backend-api/src/scripted.rs @@ -67,49 +67,6 @@ pub struct Script { steps: Vec, } -impl Script { - pub fn new(steps: Vec) -> Self { - Self { steps } - } - - /// The deltas, then a `Stop` terminal with the given usage. - pub fn stop_with(chunks: &[&str], usage: Usage) -> Self { - Self::finishing(chunks, FinishReason::Stop, usage) - } - - /// The deltas, then a terminal with the given reason. - pub fn finishing(chunks: &[&str], reason: FinishReason, usage: Usage) -> Self { - let mut steps: Vec = chunks.iter().map(|c| Step::Text((*c).to_owned())).collect(); - steps.push(Step::Finish { reason, usage }); - Self { steps } - } - - /// The deltas, then the engine dies. - pub fn dying_after(chunks: &[&str]) -> Self { - let mut steps: Vec = chunks.iter().map(|c| Step::Text((*c).to_owned())).collect(); - steps.push(Step::DropWithoutTerminal); - Self { steps } - } - - /// The deltas, then a failed terminal. - pub fn failing_after(chunks: &[&str], code: ErrorCode, message: &str) -> Self { - let mut steps: Vec = chunks.iter().map(|c| Step::Text((*c).to_owned())).collect(); - steps.push(Step::Fail { - code, - message: message.to_owned(), - retryable: false, - }); - Self { steps } - } - - /// The deltas, then silence until the generation is cancelled. - pub fn hanging_after(chunks: &[&str]) -> Self { - let mut steps: Vec = chunks.iter().map(|c| Step::Text((*c).to_owned())).collect(); - steps.push(Step::AwaitCancel); - Self { steps } - } -} - type Responder = Box Script + Send>; struct Shared { @@ -151,403 +108,15 @@ pub struct ScriptedEngine { shared: Arc, } -impl ScriptedEngine { - /// An engine that is not loaded yet; `load` must be given exactly `descriptor`. - pub fn new(descriptor: ModelDescriptor) -> (Self, ScriptedHandle) { - let shared = Arc::new(Shared { - descriptor, - ready: AtomicBool::new(false), - epoch: AtomicU64::new(0), - kill: AtomicBool::new(false), - down: AtomicBool::new(false), - queue: Mutex::new(VecDeque::new()), - responder: Mutex::new(None), - requests: Mutex::new(Vec::new()), - cancels: Mutex::new(Vec::new()), - loads: Mutex::new(Vec::new()), - active: Mutex::new(None), - prefix_summary: Mutex::new(None), - memory_report: Mutex::new(None), - settings: Mutex::new(Vec::new()), - }); - ( - Self { - shared: shared.clone(), - }, - ScriptedHandle { shared }, - ) - } - - /// A valid descriptor for tests that do not care which model they name. - pub fn fixture_descriptor() -> ModelDescriptor { - ModelDescriptor { - family: "scripted_family".into(), - architecture: "scripted_arch".into(), - artifact_digest: format!("sha256:{}", "c".repeat(64)), - weight_format: "scripted:format".into(), - } - } -} - -impl ScriptedHandle { - /// The next generation plays this script (FIFO). - pub fn push(&self, script: Script) { - self.shared.queue.lock().unwrap().push_back(script); - } - - /// Every generation plays what `responder` returns for its request; the FIFO is used only - /// while no responder is installed. - pub fn respond_with( - &self, - responder: impl FnMut(&GenerationRequest) -> Script + Send + 'static, - ) { - *self.shared.responder.lock().unwrap() = Some(Box::new(responder)); - } - - /// Every request accepted so far, in order. - pub fn requests(&self) -> Vec { - self.shared.requests.lock().unwrap().clone() - } - - /// The ids passed to `Backend::cancel`, in order. - pub fn cancels(&self) -> Vec { - self.shared.cancels.lock().unwrap().clone() - } - - pub fn loads(&self) -> Vec<(ModelDescriptor, RuntimeConfig)> { - self.shared.loads.lock().unwrap().clone() - } - - /// The engine reports this prefix-cache summary (JSON) from now on; `None` = it has no such cache. - pub fn set_memory_report(&self, report: Option) { - *self.shared.memory_report.lock().unwrap() = report; - } - - pub fn set_prefix_summary(&self, summary: Option) { - *self.shared.prefix_summary.lock().unwrap() = summary; - } - - pub fn is_ready(&self) -> bool { - self.shared.ready.load(Ordering::Acquire) - } - - pub fn is_generating(&self) -> bool { - self.shared.active.lock().unwrap().is_some() - } - - /// The engine process dies: a running generation ends without a terminal event, the model is - /// no longer loaded and every handle issued before is stale. - pub fn restart_engine(&self) { - self.shared.kill.store(true, Ordering::Release); - self.shared.down.store(true, Ordering::Release); - self.shared.ready.store(false, Ordering::Release); - self.shared.epoch.fetch_add(1, Ordering::AcqRel); - } - - /// The engine process is back and has the model loaded again (a new handle, a new epoch). - pub fn reload_engine(&self) { - self.shared.kill.store(false, Ordering::Release); - self.shared.down.store(false, Ordering::Release); - self.shared.epoch.fetch_add(1, Ordering::AcqRel); - self.shared.ready.store(true, Ordering::Release); - } -} - -fn error(code: ErrorCode, message: &str, retryable: bool) -> BackendError { - BackendError { - code, - message: message.to_owned(), - retryable, - } -} - -fn handle_name(epoch: u64) -> String { - format!("scripted-handle-{epoch}") -} - -impl Backend for ScriptedEngine { - fn identity(&self) -> BackendIdentity { - BackendIdentity { - name: "scripted".into(), - implementation_version: "test".into(), - api_version: crate::BACKEND_API_VERSION, - } - } - - fn prefix_cache_summary(&self) -> Option { - self.shared.prefix_summary.lock().unwrap().clone() - } - - fn memory_report(&self) -> Option { - self.shared.memory_report.lock().unwrap().clone() - } - - /// Accepts any document that looks like a JSON object unless it names a member `"bad"` (refused as an invalid request) and echoes it. - fn reconfigure(&mut self, settings_json: &str) -> Result { - let invalid = |message: &str| BackendError { - code: ErrorCode::InvalidRequest, - message: message.into(), - retryable: false, - }; - let trimmed = settings_json.trim(); - if !(trimmed.starts_with('{') && trimmed.ends_with('}')) { - return Err(invalid("not an object")); - } - if trimmed.contains("\"bad\"") { - return Err(invalid("bad setting")); - } - self.shared - .settings - .lock() - .unwrap() - .push(trimmed.to_owned()); - Ok(trimmed.to_owned()) - } - - fn capabilities(&self) -> BackendCapabilities { - let d = &self.shared.descriptor; - BackendCapabilities { - supported_models: if self.shared.ready.load(Ordering::Acquire) { - vec![SupportedModelTuple { - family: d.family.clone(), - architecture: d.architecture.clone(), - weight_format: d.weight_format.clone(), - }] - } else { - Vec::new() - }, - max_concurrent_generations: 1, - supports_cancellation: true, - supports_tool_call_streaming: false, - } - } - - fn load( - &mut self, - model: ModelDescriptor, - config: RuntimeConfig, - ) -> Result { - self.shared - .loads - .lock() - .unwrap() - .push((model.clone(), config.clone())); - config.validate().map_err(|_| { - error( - ErrorCode::InvalidRequest, - "invalid load configuration", - false, - ) - })?; - if self.shared.down.load(Ordering::Acquire) { - return Err(error(ErrorCode::BackendUnavailable, "engine is down", true)); - } - if model != self.shared.descriptor { - return Err(error( - ErrorCode::UnsupportedModel, - "unsupported model", - false, - )); - } - self.shared.kill.store(false, Ordering::Release); - let epoch = self.shared.epoch.fetch_add(1, Ordering::AcqRel) + 1; - self.shared.ready.store(true, Ordering::Release); - Ok(LoadedModel { - handle: handle_name(epoch), - descriptor: model, - load_config_version: config.load_config_version, - effective_mode: config.inference_mode, - mode_identity_digest: format!("sha256:{}", "d".repeat(64)), - }) - } - - fn start_generation( - &mut self, - model: &LoadedModel, - request: GenerationRequest, - ) -> Result { - let shared = &self.shared; - if !shared.ready.load(Ordering::Acquire) { - return Err(error( - ErrorCode::BackendUnavailable, - "model is not loaded", - true, - )); - } - if model.handle != handle_name(shared.epoch.load(Ordering::Acquire)) { - return Err(error( - ErrorCode::BackendUnavailable, - "stale model handle", - true, - )); - } - if request.request_id.is_empty() || request.max_output_tokens == 0 { - return Err(error(ErrorCode::InvalidRequest, "invalid request", false)); - } - let cancel = Arc::new(AtomicBool::new(false)); - { - let mut active = shared.active.lock().unwrap(); - if active.is_some() { - return Err(error( - ErrorCode::ResourceExhausted, - "a generation is already running", - true, - )); - } - *active = Some(ActiveGeneration { - id: request.request_id.clone(), - cancel: cancel.clone(), - }); - } - shared.requests.lock().unwrap().push(request.clone()); - let script = { - let mut responder = shared.responder.lock().unwrap(); - match responder.as_mut() { - Some(responder) => responder(&request), - None => shared.queue.lock().unwrap().pop_front().unwrap_or_else(|| { - Script::new(vec![Step::Fail { - code: ErrorCode::Internal, - message: "no script queued".into(), - retryable: false, - }]) - }), - } - }; - let (sink, stream) = GenerationSink::channel(); - let shared = Arc::clone(&self.shared); - thread::spawn(move || play(&shared, &cancel, sink, script)); - Ok(stream) - } - - fn cancel(&mut self, request_id: &str) -> Result<(), BackendError> { - self.shared - .cancels - .lock() - .unwrap() - .push(request_id.to_owned()); - match self.shared.active.lock().unwrap().as_ref() { - Some(active) if active.id == request_id => { - active.cancel.store(true, Ordering::Release); - Ok(()) - } - _ => Err(error( - ErrorCode::InvalidRequest, - "generation is not active", - false, - )), - } - } - - fn unload(&mut self, model: LoadedModel) -> Result<(), BackendError> { - if model.handle != handle_name(self.shared.epoch.load(Ordering::Acquire)) { - return Err(error( - ErrorCode::InvalidRequest, - "stale model handle", - false, - )); - } - self.shared.ready.store(false, Ordering::Release); - Ok(()) - } -} - -/// Plays one script. The active slot is released before the terminal event is published, so a -/// caller that reacts to the terminal can start the next generation at once. -fn play(shared: &Shared, cancel: &AtomicBool, sink: GenerationSink, script: Script) { - let release = || { - *shared.active.lock().unwrap() = None; - }; - let killed = || shared.kill.load(Ordering::Acquire); - for step in script.steps { - if killed() { - release(); - return; // the sink drops without a terminal event - } - if cancel.load(Ordering::Acquire) || sink.is_closed() { - release(); - let _ = sink.cancel(); - return; - } - let sent = match step { - Step::Text(text) => sink.emit(GenerationEvent::TextDelta { text }), - Step::Usage(usage) => sink.emit(GenerationEvent::Usage(usage)), - Step::ToolCall { - index, - id, - name, - arguments_delta, - } => sink.emit(GenerationEvent::ToolCallDelta { - index, - id, - name, - arguments_delta, - }), - Step::Pause(duration) => { - let until = Instant::now() + duration; - while Instant::now() < until - && !cancel.load(Ordering::Acquire) - && !killed() - && !sink.is_closed() - { - thread::sleep(Duration::from_millis(2)); - } - Ok(()) - } - Step::Unresponsive(duration) => { - thread::sleep(duration); - Ok(()) - } - Step::AwaitCancel => { - while !cancel.load(Ordering::Acquire) && !killed() && !sink.is_closed() { - thread::sleep(Duration::from_millis(2)); - } - if killed() { - release(); - return; - } - release(); - let _ = sink.cancel(); - return; - } - Step::Finish { reason, usage } => { - release(); - let _ = sink.emit(GenerationEvent::Terminal(GenerationTerminal::Completed { - reason, - usage, - })); - return; - } - Step::Fail { - code, - message, - retryable, - } => { - release(); - let _ = sink.emit(GenerationEvent::Terminal(GenerationTerminal::Failed { - code, - message, - retryable, - })); - return; - } - Step::CancelledUnasked => { - release(); - let _ = sink.cancel(); - return; - } - Step::DropWithoutTerminal => { - release(); - return; - } - }; - if sent.is_err() { - release(); - return; - } - } - // A script that ends without a terminal step is an engine that died. - release(); -} - #[cfg(test)] mod tests; + +mod impl_script; +#[allow(unused_imports)] +pub use impl_script::*; +mod impl_backend_for_scriptedengine; +#[allow(unused_imports)] +pub use impl_backend_for_scriptedengine::*; +mod play; +#[allow(unused_imports)] +pub use play::*; diff --git a/crates/backend-api/src/scripted/impl_backend_for_scriptedengine.rs b/crates/backend-api/src/scripted/impl_backend_for_scriptedengine.rs new file mode 100644 index 00000000..8c936e75 --- /dev/null +++ b/crates/backend-api/src/scripted/impl_backend_for_scriptedengine.rs @@ -0,0 +1,190 @@ +//! Moved out of the parent module by STRA-338: impl Backend_for_ScriptedEngine. + +#[allow(unused_imports)] +use super::*; + +impl Backend for ScriptedEngine { + fn identity(&self) -> BackendIdentity { + BackendIdentity { + name: "scripted".into(), + implementation_version: "test".into(), + api_version: crate::BACKEND_API_VERSION, + } + } + + fn prefix_cache_summary(&self) -> Option { + self.shared.prefix_summary.lock().unwrap().clone() + } + + fn memory_report(&self) -> Option { + self.shared.memory_report.lock().unwrap().clone() + } + + /// Accepts any document that looks like a JSON object unless it names a member `"bad"` (refused as an invalid request) and echoes it. + fn reconfigure(&mut self, settings_json: &str) -> Result { + let invalid = |message: &str| BackendError { + code: ErrorCode::InvalidRequest, + message: message.into(), + retryable: false, + }; + let trimmed = settings_json.trim(); + if !(trimmed.starts_with('{') && trimmed.ends_with('}')) { + return Err(invalid("not an object")); + } + if trimmed.contains("\"bad\"") { + return Err(invalid("bad setting")); + } + self.shared + .settings + .lock() + .unwrap() + .push(trimmed.to_owned()); + Ok(trimmed.to_owned()) + } + + fn capabilities(&self) -> BackendCapabilities { + let d = &self.shared.descriptor; + BackendCapabilities { + supported_models: if self.shared.ready.load(Ordering::Acquire) { + vec![SupportedModelTuple { + family: d.family.clone(), + architecture: d.architecture.clone(), + weight_format: d.weight_format.clone(), + }] + } else { + Vec::new() + }, + max_concurrent_generations: 1, + supports_cancellation: true, + supports_tool_call_streaming: false, + } + } + + fn load( + &mut self, + model: ModelDescriptor, + config: RuntimeConfig, + ) -> Result { + self.shared + .loads + .lock() + .unwrap() + .push((model.clone(), config.clone())); + config.validate().map_err(|_| { + error( + ErrorCode::InvalidRequest, + "invalid load configuration", + false, + ) + })?; + if self.shared.down.load(Ordering::Acquire) { + return Err(error(ErrorCode::BackendUnavailable, "engine is down", true)); + } + if model != self.shared.descriptor { + return Err(error( + ErrorCode::UnsupportedModel, + "unsupported model", + false, + )); + } + self.shared.kill.store(false, Ordering::Release); + let epoch = self.shared.epoch.fetch_add(1, Ordering::AcqRel) + 1; + self.shared.ready.store(true, Ordering::Release); + Ok(LoadedModel { + handle: handle_name(epoch), + descriptor: model, + load_config_version: config.load_config_version, + effective_mode: config.inference_mode, + mode_identity_digest: format!("sha256:{}", "d".repeat(64)), + }) + } + + fn start_generation( + &mut self, + model: &LoadedModel, + request: GenerationRequest, + ) -> Result { + let shared = &self.shared; + if !shared.ready.load(Ordering::Acquire) { + return Err(error( + ErrorCode::BackendUnavailable, + "model is not loaded", + true, + )); + } + if model.handle != handle_name(shared.epoch.load(Ordering::Acquire)) { + return Err(error( + ErrorCode::BackendUnavailable, + "stale model handle", + true, + )); + } + if request.request_id.is_empty() || request.max_output_tokens == 0 { + return Err(error(ErrorCode::InvalidRequest, "invalid request", false)); + } + let cancel = Arc::new(AtomicBool::new(false)); + { + let mut active = shared.active.lock().unwrap(); + if active.is_some() { + return Err(error( + ErrorCode::ResourceExhausted, + "a generation is already running", + true, + )); + } + *active = Some(ActiveGeneration { + id: request.request_id.clone(), + cancel: cancel.clone(), + }); + } + shared.requests.lock().unwrap().push(request.clone()); + let script = { + let mut responder = shared.responder.lock().unwrap(); + match responder.as_mut() { + Some(responder) => responder(&request), + None => shared.queue.lock().unwrap().pop_front().unwrap_or_else(|| { + Script::new(vec![Step::Fail { + code: ErrorCode::Internal, + message: "no script queued".into(), + retryable: false, + }]) + }), + } + }; + let (sink, stream) = GenerationSink::channel(); + let shared = Arc::clone(&self.shared); + thread::spawn(move || play(&shared, &cancel, sink, script)); + Ok(stream) + } + + fn cancel(&mut self, request_id: &str) -> Result<(), BackendError> { + self.shared + .cancels + .lock() + .unwrap() + .push(request_id.to_owned()); + match self.shared.active.lock().unwrap().as_ref() { + Some(active) if active.id == request_id => { + active.cancel.store(true, Ordering::Release); + Ok(()) + } + _ => Err(error( + ErrorCode::InvalidRequest, + "generation is not active", + false, + )), + } + } + + fn unload(&mut self, model: LoadedModel) -> Result<(), BackendError> { + if model.handle != handle_name(self.shared.epoch.load(Ordering::Acquire)) { + return Err(error( + ErrorCode::InvalidRequest, + "stale model handle", + false, + )); + } + self.shared.ready.store(false, Ordering::Release); + Ok(()) + } +} diff --git a/crates/backend-api/src/scripted/impl_script.rs b/crates/backend-api/src/scripted/impl_script.rs new file mode 100644 index 00000000..fdc359af --- /dev/null +++ b/crates/backend-api/src/scripted/impl_script.rs @@ -0,0 +1,161 @@ +//! Moved out of the parent module by STRA-338: impl Script, impl ScriptedEngine, impl ScriptedHandle, fn error, fn handle_name. + +#[allow(unused_imports)] +use super::*; + +impl Script { + pub fn new(steps: Vec) -> Self { + Self { steps } + } + + /// The deltas, then a `Stop` terminal with the given usage. + pub fn stop_with(chunks: &[&str], usage: Usage) -> Self { + Self::finishing(chunks, FinishReason::Stop, usage) + } + + /// The deltas, then a terminal with the given reason. + pub fn finishing(chunks: &[&str], reason: FinishReason, usage: Usage) -> Self { + let mut steps: Vec = chunks.iter().map(|c| Step::Text((*c).to_owned())).collect(); + steps.push(Step::Finish { reason, usage }); + Self { steps } + } + + /// The deltas, then the engine dies. + pub fn dying_after(chunks: &[&str]) -> Self { + let mut steps: Vec = chunks.iter().map(|c| Step::Text((*c).to_owned())).collect(); + steps.push(Step::DropWithoutTerminal); + Self { steps } + } + + /// The deltas, then a failed terminal. + pub fn failing_after(chunks: &[&str], code: ErrorCode, message: &str) -> Self { + let mut steps: Vec = chunks.iter().map(|c| Step::Text((*c).to_owned())).collect(); + steps.push(Step::Fail { + code, + message: message.to_owned(), + retryable: false, + }); + Self { steps } + } + + /// The deltas, then silence until the generation is cancelled. + pub fn hanging_after(chunks: &[&str]) -> Self { + let mut steps: Vec = chunks.iter().map(|c| Step::Text((*c).to_owned())).collect(); + steps.push(Step::AwaitCancel); + Self { steps } + } +} + +impl ScriptedEngine { + /// An engine that is not loaded yet; `load` must be given exactly `descriptor`. + pub fn new(descriptor: ModelDescriptor) -> (Self, ScriptedHandle) { + let shared = Arc::new(Shared { + descriptor, + ready: AtomicBool::new(false), + epoch: AtomicU64::new(0), + kill: AtomicBool::new(false), + down: AtomicBool::new(false), + queue: Mutex::new(VecDeque::new()), + responder: Mutex::new(None), + requests: Mutex::new(Vec::new()), + cancels: Mutex::new(Vec::new()), + loads: Mutex::new(Vec::new()), + active: Mutex::new(None), + prefix_summary: Mutex::new(None), + memory_report: Mutex::new(None), + settings: Mutex::new(Vec::new()), + }); + ( + Self { + shared: shared.clone(), + }, + ScriptedHandle { shared }, + ) + } + + /// A valid descriptor for tests that do not care which model they name. + pub fn fixture_descriptor() -> ModelDescriptor { + ModelDescriptor { + family: "scripted_family".into(), + architecture: "scripted_arch".into(), + artifact_digest: format!("sha256:{}", "c".repeat(64)), + weight_format: "scripted:format".into(), + } + } +} + +impl ScriptedHandle { + /// The next generation plays this script (FIFO). + pub fn push(&self, script: Script) { + self.shared.queue.lock().unwrap().push_back(script); + } + + /// Every generation plays what `responder` returns for its request; the FIFO is used only + /// while no responder is installed. + pub fn respond_with( + &self, + responder: impl FnMut(&GenerationRequest) -> Script + Send + 'static, + ) { + *self.shared.responder.lock().unwrap() = Some(Box::new(responder)); + } + + /// Every request accepted so far, in order. + pub fn requests(&self) -> Vec { + self.shared.requests.lock().unwrap().clone() + } + + /// The ids passed to `Backend::cancel`, in order. + pub fn cancels(&self) -> Vec { + self.shared.cancels.lock().unwrap().clone() + } + + pub fn loads(&self) -> Vec<(ModelDescriptor, RuntimeConfig)> { + self.shared.loads.lock().unwrap().clone() + } + + /// The engine reports this prefix-cache summary (JSON) from now on; `None` = it has no such cache. + pub fn set_memory_report(&self, report: Option) { + *self.shared.memory_report.lock().unwrap() = report; + } + + pub fn set_prefix_summary(&self, summary: Option) { + *self.shared.prefix_summary.lock().unwrap() = summary; + } + + pub fn is_ready(&self) -> bool { + self.shared.ready.load(Ordering::Acquire) + } + + pub fn is_generating(&self) -> bool { + self.shared.active.lock().unwrap().is_some() + } + + /// The engine process dies: a running generation ends without a terminal event, the model is + /// no longer loaded and every handle issued before is stale. + pub fn restart_engine(&self) { + self.shared.kill.store(true, Ordering::Release); + self.shared.down.store(true, Ordering::Release); + self.shared.ready.store(false, Ordering::Release); + self.shared.epoch.fetch_add(1, Ordering::AcqRel); + } + + /// The engine process is back and has the model loaded again (a new handle, a new epoch). + pub fn reload_engine(&self) { + self.shared.kill.store(false, Ordering::Release); + self.shared.down.store(false, Ordering::Release); + self.shared.epoch.fetch_add(1, Ordering::AcqRel); + self.shared.ready.store(true, Ordering::Release); + } +} + +pub(super) fn error(code: ErrorCode, message: &str, retryable: bool) -> BackendError { + BackendError { + code, + message: message.to_owned(), + retryable, + } +} + +pub(super) fn handle_name(epoch: u64) -> String { + format!("scripted-handle-{epoch}") +} diff --git a/crates/backend-api/src/scripted/play.rs b/crates/backend-api/src/scripted/play.rs new file mode 100644 index 00000000..4801f5a5 --- /dev/null +++ b/crates/backend-api/src/scripted/play.rs @@ -0,0 +1,102 @@ +//! Moved out of the parent module by STRA-338: fn play. + +#[allow(unused_imports)] +use super::*; + +/// Plays one script. The active slot is released before the terminal event is published, so a +/// caller that reacts to the terminal can start the next generation at once. +pub(super) fn play(shared: &Shared, cancel: &AtomicBool, sink: GenerationSink, script: Script) { + let release = || { + *shared.active.lock().unwrap() = None; + }; + let killed = || shared.kill.load(Ordering::Acquire); + for step in script.steps { + if killed() { + release(); + return; // the sink drops without a terminal event + } + if cancel.load(Ordering::Acquire) || sink.is_closed() { + release(); + let _ = sink.cancel(); + return; + } + let sent = match step { + Step::Text(text) => sink.emit(GenerationEvent::TextDelta { text }), + Step::Usage(usage) => sink.emit(GenerationEvent::Usage(usage)), + Step::ToolCall { + index, + id, + name, + arguments_delta, + } => sink.emit(GenerationEvent::ToolCallDelta { + index, + id, + name, + arguments_delta, + }), + Step::Pause(duration) => { + let until = Instant::now() + duration; + while Instant::now() < until + && !cancel.load(Ordering::Acquire) + && !killed() + && !sink.is_closed() + { + thread::sleep(Duration::from_millis(2)); + } + Ok(()) + } + Step::Unresponsive(duration) => { + thread::sleep(duration); + Ok(()) + } + Step::AwaitCancel => { + while !cancel.load(Ordering::Acquire) && !killed() && !sink.is_closed() { + thread::sleep(Duration::from_millis(2)); + } + if killed() { + release(); + return; + } + release(); + let _ = sink.cancel(); + return; + } + Step::Finish { reason, usage } => { + release(); + let _ = sink.emit(GenerationEvent::Terminal(GenerationTerminal::Completed { + reason, + usage, + })); + return; + } + Step::Fail { + code, + message, + retryable, + } => { + release(); + let _ = sink.emit(GenerationEvent::Terminal(GenerationTerminal::Failed { + code, + message, + retryable, + })); + return; + } + Step::CancelledUnasked => { + release(); + let _ = sink.cancel(); + return; + } + Step::DropWithoutTerminal => { + release(); + return; + } + }; + if sent.is_err() { + release(); + return; + } + } + // A script that ends without a terminal step is an engine that died. + release(); +} diff --git a/crates/context/src/memory_plan.rs b/crates/context/src/memory_plan.rs index 1d1febff..1973043e 100644 --- a/crates/context/src/memory_plan.rs +++ b/crates/context/src/memory_plan.rs @@ -43,45 +43,6 @@ pub struct Geometry { pub ssm_conv_channels: u64, } -impl Default for Geometry { - fn default() -> Self { - Self { - n_layers: 48, - n_qsa_layers: 12, - n_kv_heads: 2, - head_dim: 256, - kv_group: 64, - qsa_block: 4, - indexer_q_heads: 4, - indexer_key_heads: 1, - indexer_key_dim: 128, - ssm_state_size: 128, - ssm_v_heads: 48, - ssm_d_conv: 4, - ssm_conv_channels: 10240, - } - } -} - -impl Geometry { - pub fn n_gdn_layers(&self) -> Result { - self.n_layers - .checked_sub(self.n_qsa_layers) - .ok_or(PlanError::Geometry("n_qsa_layers exceeds n_layers")) - } - - /// Rejects values that would divide by zero or underflow in the Original's integer arithmetic. - pub fn validate(&self) -> Result<(), PlanError> { - self.n_gdn_layers()?; - if self.kv_group == 0 || self.qsa_block == 0 || self.ssm_d_conv == 0 { - return Err(PlanError::Geometry( - "kv_group, qsa_block and ssm_d_conv must be non-zero", - )); - } - Ok(()) - } -} - /// Byte costs (plan.hpp `Costs`). #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub struct Costs { @@ -93,19 +54,6 @@ pub struct Costs { pub state_bytes: u64, } -impl Default for Costs { - fn default() -> Self { - Self { - expert_blob: 1_382_400, - dense_bytes: 0, - embd_bytes: 0, - mtp_bytes: 0, - workspace_bytes: 0, - state_bytes: 0, - } - } -} - #[derive(Clone, Debug, PartialEq, Eq)] pub enum PlanError { /// plan.hpp `DoesNotClose`; the payload is the Original's exact `what()` text. @@ -115,53 +63,8 @@ pub enum PlanError { Geometry(&'static str), } -impl fmt::Display for PlanError { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - match self { - Self::DoesNotClose(w) => f.write_str(w), - Self::Overflow => f.write_str("memory-plan arithmetic overflowed u64"), - Self::Geometry(w) => write!(f, "invalid geometry: {w}"), - } - } -} - -impl std::error::Error for PlanError {} - type R = Result; -fn mul(a: u64, b: u64) -> R { - a.checked_mul(b).ok_or(PlanError::Overflow) -} -fn add(a: u64, b: u64) -> R { - a.checked_add(b).ok_or(PlanError::Overflow) -} - -/// GDN recurrence + conv history, bytes per sequence (plan.hpp `state_bytes`). -pub fn state_bytes(g: &Geometry) -> R { - g.validate()?; - let recurrence = mul( - mul(mul(g.ssm_state_size, g.ssm_v_heads)?, g.ssm_state_size)?, - 4, - )?; - let conv = mul(mul(g.ssm_d_conv - 1, g.ssm_conv_channels)?, 4)?; - mul(g.n_gdn_layers()?, add(recurrence, conv)?) -} - -/// INT8 KV + indexer keys, bytes per token (plan.hpp `kv_bytes_per_token`), literal. -pub fn kv_bytes_per_token_int8(g: &Geometry) -> R { - g.validate()?; - let kv_elems = mul(mul(2, g.n_kv_heads)?, g.head_dim)?; - let kv_scales = mul(kv_elems / g.kv_group, 2)?; - let per_layer = add(kv_elems, kv_scales)?; - let idx_layer = mul(g.indexer_key_heads, g.indexer_key_dim)? / g.qsa_block; - mul(g.n_qsa_layers, add(per_layer, idx_layer)?) -} - -/// The VRAM budget the KV cache and the expert cache share (plan.hpp `vram_pool_bytes`). -pub const fn vram_pool_bytes() -> u64 { - 5_943_000_000 -} - // ---- KV formats ------------------------------------------------------------------------------ /// KV cache storage formats of the Original (`--kv`). `Int8Keyless` is the experimental @@ -176,31 +79,6 @@ pub enum KvFormat { Int8Keyless, } -impl KvFormat { - pub fn name(self) -> &'static str { - match self { - Self::Fp16 => "fp16", - Self::Int8 => "int8", - Self::Q4_0 => "q4_0", - Self::K8V4 => "k8v4", - Self::Int8Keyless => "int8-keyless", - } - } - /// `--kv` spellings of `generate.cpp` (`q4` is accepted as `q4_0`). The keyless mode has no `--kv` name. - pub fn parse_cli(s: &str) -> Option { - match s { - "fp16" => Some(Self::Fp16), - "int8" => Some(Self::Int8), - "q4_0" | "q4" => Some(Self::Q4_0), - "k8v4" => Some(Self::K8V4), - _ => None, - } - } - pub fn is_experimental(self) -> bool { - self == Self::Int8Keyless - } -} - /// `KV_Q8_GROUP` (kv_q8.hpp) and `QK4_0`/`sizeof(block_q4_0)` (kv_q4.hpp). pub const KV_Q8_GROUP: u64 = 64; pub const QK4_0: u64 = 32; @@ -215,87 +93,6 @@ pub struct KvShapes { pub page_size: u64, } -impl KvShapes { - pub fn real() -> Self { - Self { - n_head_kv: 2, - head_dim: 256, - page_size: 4, - } - } - pub fn from_geometry(g: &Geometry) -> Self { - Self { - n_head_kv: g.n_kv_heads, - head_dim: g.head_dim, - page_size: 4, - } - } - fn validate(&self, fmt: KvFormat) -> R<()> { - if self.page_size == 0 { - return Err(PlanError::Geometry("page_size must be non-zero")); - } - if fmt != KvFormat::Fp16 && !self.head_dim.is_multiple_of(KV_Q8_GROUP) { - return Err(PlanError::Geometry( - "quantised KV needs head_dim to be a multiple of 64", - )); - } - Ok(()) - } -} - -fn q8_bytes_per_cell(s: &KvShapes) -> R { - add( - mul(mul(s.n_head_kv, s.head_dim)?, 2)?, - mul(mul(s.n_head_kv, s.head_dim / KV_Q8_GROUP)?, 4)?, - ) -} -fn q4_bytes_per_head(head_dim: u64) -> R { - mul(head_dim / QK4_0, BLOCK_Q4_0_BYTES) -} - -/// Bytes per cell (one token, one QSA layer) of the K/V pool in `fmt`, without the pool's constant `+64`. -/// fp16: `n_head_kv * head_dim * 2 * 2`; INT8: kv_q8.hpp; Q4_0: kv_q4.hpp; K8V4: `layer.cpp` hybrid branch -/// (816 B/cell on the real shapes); keyless: INT8 / 2. -pub fn kv_cell_bytes(s: &KvShapes, fmt: KvFormat) -> R { - s.validate(fmt)?; - match fmt { - KvFormat::Fp16 => mul(mul(mul(s.n_head_kv, s.head_dim)?, 2)?, 2), - KvFormat::Int8 => q8_bytes_per_cell(s), - KvFormat::Q4_0 => mul(mul(s.n_head_kv, q4_bytes_per_head(s.head_dim)?)?, 2), - KvFormat::K8V4 => { - let rows = s.n_head_kv; - add( - add( - mul(rows, s.head_dim)?, - mul(mul(rows, s.head_dim / KV_Q8_GROUP)?, 2)?, - )?, - mul(rows, q4_bytes_per_head(s.head_dim)?)?, - ) - } - KvFormat::Int8Keyless => Ok(q8_bytes_per_cell(s)? / 2), - } -} - -/// `layer.cpp::kv_pool_bytes` for one QSA layer: `pages` pages of `page_size` cells, fully resident. -/// Includes the Original's `+64` slack for every format except fp16 (which has none). -pub fn kv_pool_bytes(s: &KvShapes, pages: u64, fmt: KvFormat) -> R { - let cells = mul(pages, s.page_size)?; - let body = mul(cells, kv_cell_bytes(s, fmt)?)?; - match fmt { - KvFormat::Fp16 => Ok(body), - _ => add(body, 64), - } -} - -/// KV + indexer-key bytes per token over all QSA layers for `fmt`, with plan.hpp's indexer term. -/// For [`KvFormat::Int8`] this equals [`kv_bytes_per_token_int8`] (tested). -pub fn kv_bytes_per_token(g: &Geometry, fmt: KvFormat) -> R { - g.validate()?; - let cell = kv_cell_bytes(&KvShapes::from_geometry(g), fmt)?; - let idx_layer = mul(g.indexer_key_heads, g.indexer_key_dim)? / g.qsa_block; - mul(g.n_qsa_layers, add(cell, idx_layer)?) -} - // ---- the plan -------------------------------------------------------------------------------- #[derive(Clone, Debug, PartialEq, Eq)] @@ -311,97 +108,6 @@ pub struct Plan { pub notes: Vec, } -fn does_not_close(msg: String) -> R { - Err(PlanError::DoesNotClose(msg)) -} - -/// plan.hpp `make_plan` with INT8 KV, literal. Identical to the `strata-plan` CLI for the same inputs. -pub fn make_plan(max_context: u64, g: &Geometry, c: &Costs, pool: u64) -> R { - plan_with_per_token(max_context, kv_bytes_per_token_int8(g)?, c, pool) -} - -/// EXTENSION: `make_plan` with another KV format's bytes per token. `Int8` reproduces [`make_plan`]. -pub fn make_plan_with_format( - max_context: u64, - g: &Geometry, - fmt: KvFormat, - c: &Costs, - pool: u64, -) -> R { - plan_with_per_token(max_context, kv_bytes_per_token(g, fmt)?, c, pool) -} - -fn plan_with_per_token(max_context: u64, per_token: u64, c: &Costs, pool: u64) -> R { - if c.expert_blob == 0 { - return Err(PlanError::Geometry("expert_blob must be non-zero")); - } - let kv_bytes = mul(per_token, max_context)?; - let dram_experts = add(c.dense_bytes, c.embd_bytes)?; - let fixed = add( - add(add(dram_experts, c.mtp_bytes)?, c.workspace_bytes)?, - c.state_bytes, - )?; - let need = add(kv_bytes, fixed)?; - if need > pool { - return does_not_close(format!( - "max-context {max_context} needs {need} B of the {pool} B VRAM pool; reduce --max-context" - )); - } - let cache_bytes = pool - need; - let cache_slots = cache_bytes / c.expert_blob; - let vram_used = pool - cache_bytes % c.expert_blob; - if cache_slots == 0 { - return does_not_close(format!( - "no room for even one expert cache slot at max-context {max_context}" - )); - } - Ok(Plan { - max_context, - kv_bytes, - state_bytes: c.state_bytes, - cache_bytes, - cache_slots, - vram_budget: pool, - vram_used, - dram_experts, - notes: Vec::new(), - }) -} - -/// The pool derivation of `plan_main.cpp`: free VRAM less the resident dense and embedding bytes, and a -/// derived 0 falls back to [`vram_pool_bytes`] (`pool ? pool : strata::plan::vram_pool_bytes()`). -/// `--pool B` in the CLI assigns `free_vram` and so goes through this too. -pub fn cli_pool(free_vram: u64, c: &Costs) -> R { - let resident = add(c.dense_bytes, c.embd_bytes)?; - let pool = free_vram.saturating_sub(resident); - Ok(if pool != 0 { pool } else { vram_pool_bytes() }) -} - -impl Plan { - /// plan.hpp `to_string`, byte for byte (`std::to_string(double)` is `%f`). - pub fn to_text(&self) -> String { - let gb = |b: u64| format!("{:.6}", b as f64 / 1e9); - let mut s = String::new(); - s += &format!("memory plan --max-context {}\n", self.max_context); - s += &format!(" KV + indexer keys {} GB\n", gb(self.kv_bytes)); - s += &format!( - " recurrent state {} GB (GDN recurrence + conv history, NOT evictable)\n", - gb(self.state_bytes) - ); - s += &format!( - " expert cache {} GB ({} slots of 1,382,400 B)\n", - gb(self.cache_bytes), - self.cache_slots - ); - s += &format!(" VRAM pool {} GB\n", gb(self.vram_budget)); - s += &format!(" expert arena (DRAM) {} GB\n", gb(self.dram_experts)); - for n in &self.notes { - s += &format!(" note: {n}\n"); - } - s - } -} - // ---- EXTENSION: advisory estimate of what the engine allocates --------------------------------- /// Hand-derived from `layer.cpp::qsa_state_bytes` for a fully resident state (no `--kv-resident` @@ -417,51 +123,12 @@ pub struct EngineResidentEstimate { pub total: u64, } -/// `slots` independent sequence states of `ctx_per_slot` cells each; one rope table per state when -/// `rope_table_per_slot` is `Some(n_rot)` (the table is shared across layers by `share_rope`). -pub fn engine_resident_estimate( - g: &Geometry, - fmt: KvFormat, - slots: u64, - ctx_per_slot: u64, - rope_n_rot: Option, -) -> R { - g.validate()?; - let s = KvShapes::from_geometry(g); - let pages = ctx_per_slot.div_ceil(s.page_size); - let layers = g.n_qsa_layers; - let kv_layer = kv_pool_bytes(&s, pages, fmt)?; - let pooled_rows = ctx_per_slot / g.qsa_block + 2; - let idx_layer = add( - add( - mul(mul(g.qsa_block - 1, g.indexer_key_dim)?, 4)?, - mul(g.indexer_key_dim, 4)?, - )?, - mul(mul(pooled_rows, g.indexer_key_dim)?, 4)?, - )?; - let per_slot_kv = mul(layers, kv_layer)?; - let per_slot_pt = mul(layers, mul(pages, 4)?)?; - let per_slot_idx = mul(layers, idx_layer)?; - let per_slot_rope = match rope_n_rot { - Some(n) => mul(mul(ctx_per_slot, n / 2)?, 8)?, - None => 0, - }; - let kv_pools = mul(slots, per_slot_kv)?; - let page_tables = mul(slots, per_slot_pt)?; - let indexer_stores = mul(slots, per_slot_idx)?; - let rope_tables = mul(slots, per_slot_rope)?; - let total = add( - add(add(kv_pools, page_tables)?, indexer_stores)?, - rope_tables, - )?; - Ok(EngineResidentEstimate { - kv_pools, - page_tables, - indexer_stores, - rope_tables, - total, - }) -} - #[cfg(test)] mod tests; + +mod impl_default_for_geometry; +#[allow(unused_imports)] +pub use impl_default_for_geometry::*; +mod plan_with_per_token; +#[allow(unused_imports)] +pub use plan_with_per_token::*; diff --git a/crates/context/src/memory_plan/impl_default_for_geometry.rs b/crates/context/src/memory_plan/impl_default_for_geometry.rs new file mode 100644 index 00000000..4b11738c --- /dev/null +++ b/crates/context/src/memory_plan/impl_default_for_geometry.rs @@ -0,0 +1,227 @@ +//! Moved out of the parent module by STRA-338: impl Default_for_Geometry, impl Geometry, impl Default_for_Costs, impl fmt_Display_for, impl std_error_Error, fn mul .... + +#[allow(unused_imports)] +use super::*; + +impl Default for Geometry { + fn default() -> Self { + Self { + n_layers: 48, + n_qsa_layers: 12, + n_kv_heads: 2, + head_dim: 256, + kv_group: 64, + qsa_block: 4, + indexer_q_heads: 4, + indexer_key_heads: 1, + indexer_key_dim: 128, + ssm_state_size: 128, + ssm_v_heads: 48, + ssm_d_conv: 4, + ssm_conv_channels: 10240, + } + } +} + +impl Geometry { + pub fn n_gdn_layers(&self) -> Result { + self.n_layers + .checked_sub(self.n_qsa_layers) + .ok_or(PlanError::Geometry("n_qsa_layers exceeds n_layers")) + } + + /// Rejects values that would divide by zero or underflow in the Original's integer arithmetic. + pub fn validate(&self) -> Result<(), PlanError> { + self.n_gdn_layers()?; + if self.kv_group == 0 || self.qsa_block == 0 || self.ssm_d_conv == 0 { + return Err(PlanError::Geometry( + "kv_group, qsa_block and ssm_d_conv must be non-zero", + )); + } + Ok(()) + } +} + +impl Default for Costs { + fn default() -> Self { + Self { + expert_blob: 1_382_400, + dense_bytes: 0, + embd_bytes: 0, + mtp_bytes: 0, + workspace_bytes: 0, + state_bytes: 0, + } + } +} + +impl fmt::Display for PlanError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Self::DoesNotClose(w) => f.write_str(w), + Self::Overflow => f.write_str("memory-plan arithmetic overflowed u64"), + Self::Geometry(w) => write!(f, "invalid geometry: {w}"), + } + } +} + +impl std::error::Error for PlanError {} + +pub(super) fn mul(a: u64, b: u64) -> R { + a.checked_mul(b).ok_or(PlanError::Overflow) +} +pub(super) fn add(a: u64, b: u64) -> R { + a.checked_add(b).ok_or(PlanError::Overflow) +} + +/// GDN recurrence + conv history, bytes per sequence (plan.hpp `state_bytes`). +pub fn state_bytes(g: &Geometry) -> R { + g.validate()?; + let recurrence = mul( + mul(mul(g.ssm_state_size, g.ssm_v_heads)?, g.ssm_state_size)?, + 4, + )?; + let conv = mul(mul(g.ssm_d_conv - 1, g.ssm_conv_channels)?, 4)?; + mul(g.n_gdn_layers()?, add(recurrence, conv)?) +} + +/// INT8 KV + indexer keys, bytes per token (plan.hpp `kv_bytes_per_token`), literal. +pub fn kv_bytes_per_token_int8(g: &Geometry) -> R { + g.validate()?; + let kv_elems = mul(mul(2, g.n_kv_heads)?, g.head_dim)?; + let kv_scales = mul(kv_elems / g.kv_group, 2)?; + let per_layer = add(kv_elems, kv_scales)?; + let idx_layer = mul(g.indexer_key_heads, g.indexer_key_dim)? / g.qsa_block; + mul(g.n_qsa_layers, add(per_layer, idx_layer)?) +} + +/// The VRAM budget the KV cache and the expert cache share (plan.hpp `vram_pool_bytes`). +pub const fn vram_pool_bytes() -> u64 { + 5_943_000_000 +} + +impl KvFormat { + pub fn name(self) -> &'static str { + match self { + Self::Fp16 => "fp16", + Self::Int8 => "int8", + Self::Q4_0 => "q4_0", + Self::K8V4 => "k8v4", + Self::Int8Keyless => "int8-keyless", + } + } + /// `--kv` spellings of `generate.cpp` (`q4` is accepted as `q4_0`). The keyless mode has no `--kv` name. + pub fn parse_cli(s: &str) -> Option { + match s { + "fp16" => Some(Self::Fp16), + "int8" => Some(Self::Int8), + "q4_0" | "q4" => Some(Self::Q4_0), + "k8v4" => Some(Self::K8V4), + _ => None, + } + } + pub fn is_experimental(self) -> bool { + self == Self::Int8Keyless + } +} + +impl KvShapes { + pub fn real() -> Self { + Self { + n_head_kv: 2, + head_dim: 256, + page_size: 4, + } + } + pub fn from_geometry(g: &Geometry) -> Self { + Self { + n_head_kv: g.n_kv_heads, + head_dim: g.head_dim, + page_size: 4, + } + } + pub(super) fn validate(&self, fmt: KvFormat) -> R<()> { + if self.page_size == 0 { + return Err(PlanError::Geometry("page_size must be non-zero")); + } + if fmt != KvFormat::Fp16 && !self.head_dim.is_multiple_of(KV_Q8_GROUP) { + return Err(PlanError::Geometry( + "quantised KV needs head_dim to be a multiple of 64", + )); + } + Ok(()) + } +} + +pub(super) fn q8_bytes_per_cell(s: &KvShapes) -> R { + add( + mul(mul(s.n_head_kv, s.head_dim)?, 2)?, + mul(mul(s.n_head_kv, s.head_dim / KV_Q8_GROUP)?, 4)?, + ) +} +pub(super) fn q4_bytes_per_head(head_dim: u64) -> R { + mul(head_dim / QK4_0, BLOCK_Q4_0_BYTES) +} + +/// Bytes per cell (one token, one QSA layer) of the K/V pool in `fmt`, without the pool's constant `+64`. +/// fp16: `n_head_kv * head_dim * 2 * 2`; INT8: kv_q8.hpp; Q4_0: kv_q4.hpp; K8V4: `layer.cpp` hybrid branch +/// (816 B/cell on the real shapes); keyless: INT8 / 2. +pub fn kv_cell_bytes(s: &KvShapes, fmt: KvFormat) -> R { + s.validate(fmt)?; + match fmt { + KvFormat::Fp16 => mul(mul(mul(s.n_head_kv, s.head_dim)?, 2)?, 2), + KvFormat::Int8 => q8_bytes_per_cell(s), + KvFormat::Q4_0 => mul(mul(s.n_head_kv, q4_bytes_per_head(s.head_dim)?)?, 2), + KvFormat::K8V4 => { + let rows = s.n_head_kv; + add( + add( + mul(rows, s.head_dim)?, + mul(mul(rows, s.head_dim / KV_Q8_GROUP)?, 2)?, + )?, + mul(rows, q4_bytes_per_head(s.head_dim)?)?, + ) + } + KvFormat::Int8Keyless => Ok(q8_bytes_per_cell(s)? / 2), + } +} + +/// `layer.cpp::kv_pool_bytes` for one QSA layer: `pages` pages of `page_size` cells, fully resident. +/// Includes the Original's `+64` slack for every format except fp16 (which has none). +pub fn kv_pool_bytes(s: &KvShapes, pages: u64, fmt: KvFormat) -> R { + let cells = mul(pages, s.page_size)?; + let body = mul(cells, kv_cell_bytes(s, fmt)?)?; + match fmt { + KvFormat::Fp16 => Ok(body), + _ => add(body, 64), + } +} + +/// KV + indexer-key bytes per token over all QSA layers for `fmt`, with plan.hpp's indexer term. +/// For [`KvFormat::Int8`] this equals [`kv_bytes_per_token_int8`] (tested). +pub fn kv_bytes_per_token(g: &Geometry, fmt: KvFormat) -> R { + g.validate()?; + let cell = kv_cell_bytes(&KvShapes::from_geometry(g), fmt)?; + let idx_layer = mul(g.indexer_key_heads, g.indexer_key_dim)? / g.qsa_block; + mul(g.n_qsa_layers, add(cell, idx_layer)?) +} + +pub(super) fn does_not_close(msg: String) -> R { + Err(PlanError::DoesNotClose(msg)) +} + +/// plan.hpp `make_plan` with INT8 KV, literal. Identical to the `strata-plan` CLI for the same inputs. +pub fn make_plan(max_context: u64, g: &Geometry, c: &Costs, pool: u64) -> R { + plan_with_per_token(max_context, kv_bytes_per_token_int8(g)?, c, pool) +} + +/// EXTENSION: `make_plan` with another KV format's bytes per token. `Int8` reproduces [`make_plan`]. +pub fn make_plan_with_format( + max_context: u64, + g: &Geometry, + fmt: KvFormat, + c: &Costs, + pool: u64, +) -> R { + plan_with_per_token(max_context, kv_bytes_per_token(g, fmt)?, c, pool) +} diff --git a/crates/context/src/memory_plan/plan_with_per_token.rs b/crates/context/src/memory_plan/plan_with_per_token.rs new file mode 100644 index 00000000..ae3eab16 --- /dev/null +++ b/crates/context/src/memory_plan/plan_with_per_token.rs @@ -0,0 +1,126 @@ +//! Moved out of the parent module by STRA-338: fn plan_with_per_token, fn cli_pool, impl Plan, fn engine_resident_estimate. + +#[allow(unused_imports)] +use super::*; + +pub(super) fn plan_with_per_token( + max_context: u64, + per_token: u64, + c: &Costs, + pool: u64, +) -> R { + if c.expert_blob == 0 { + return Err(PlanError::Geometry("expert_blob must be non-zero")); + } + let kv_bytes = mul(per_token, max_context)?; + let dram_experts = add(c.dense_bytes, c.embd_bytes)?; + let fixed = add( + add(add(dram_experts, c.mtp_bytes)?, c.workspace_bytes)?, + c.state_bytes, + )?; + let need = add(kv_bytes, fixed)?; + if need > pool { + return does_not_close(format!( + "max-context {max_context} needs {need} B of the {pool} B VRAM pool; reduce --max-context" + )); + } + let cache_bytes = pool - need; + let cache_slots = cache_bytes / c.expert_blob; + let vram_used = pool - cache_bytes % c.expert_blob; + if cache_slots == 0 { + return does_not_close(format!( + "no room for even one expert cache slot at max-context {max_context}" + )); + } + Ok(Plan { + max_context, + kv_bytes, + state_bytes: c.state_bytes, + cache_bytes, + cache_slots, + vram_budget: pool, + vram_used, + dram_experts, + notes: Vec::new(), + }) +} + +/// The pool derivation of `plan_main.cpp`: free VRAM less the resident dense and embedding bytes, and a +/// derived 0 falls back to [`vram_pool_bytes`] (`pool ? pool : strata::plan::vram_pool_bytes()`). +/// `--pool B` in the CLI assigns `free_vram` and so goes through this too. +pub fn cli_pool(free_vram: u64, c: &Costs) -> R { + let resident = add(c.dense_bytes, c.embd_bytes)?; + let pool = free_vram.saturating_sub(resident); + Ok(if pool != 0 { pool } else { vram_pool_bytes() }) +} + +impl Plan { + /// plan.hpp `to_string`, byte for byte (`std::to_string(double)` is `%f`). + pub fn to_text(&self) -> String { + let gb = |b: u64| format!("{:.6}", b as f64 / 1e9); + let mut s = String::new(); + s += &format!("memory plan --max-context {}\n", self.max_context); + s += &format!(" KV + indexer keys {} GB\n", gb(self.kv_bytes)); + s += &format!( + " recurrent state {} GB (GDN recurrence + conv history, NOT evictable)\n", + gb(self.state_bytes) + ); + s += &format!( + " expert cache {} GB ({} slots of 1,382,400 B)\n", + gb(self.cache_bytes), + self.cache_slots + ); + s += &format!(" VRAM pool {} GB\n", gb(self.vram_budget)); + s += &format!(" expert arena (DRAM) {} GB\n", gb(self.dram_experts)); + for n in &self.notes { + s += &format!(" note: {n}\n"); + } + s + } +} + +/// `slots` independent sequence states of `ctx_per_slot` cells each; one rope table per state when +/// `rope_table_per_slot` is `Some(n_rot)` (the table is shared across layers by `share_rope`). +pub fn engine_resident_estimate( + g: &Geometry, + fmt: KvFormat, + slots: u64, + ctx_per_slot: u64, + rope_n_rot: Option, +) -> R { + g.validate()?; + let s = KvShapes::from_geometry(g); + let pages = ctx_per_slot.div_ceil(s.page_size); + let layers = g.n_qsa_layers; + let kv_layer = kv_pool_bytes(&s, pages, fmt)?; + let pooled_rows = ctx_per_slot / g.qsa_block + 2; + let idx_layer = add( + add( + mul(mul(g.qsa_block - 1, g.indexer_key_dim)?, 4)?, + mul(g.indexer_key_dim, 4)?, + )?, + mul(mul(pooled_rows, g.indexer_key_dim)?, 4)?, + )?; + let per_slot_kv = mul(layers, kv_layer)?; + let per_slot_pt = mul(layers, mul(pages, 4)?)?; + let per_slot_idx = mul(layers, idx_layer)?; + let per_slot_rope = match rope_n_rot { + Some(n) => mul(mul(ctx_per_slot, n / 2)?, 8)?, + None => 0, + }; + let kv_pools = mul(slots, per_slot_kv)?; + let page_tables = mul(slots, per_slot_pt)?; + let indexer_stores = mul(slots, per_slot_idx)?; + let rope_tables = mul(slots, per_slot_rope)?; + let total = add( + add(add(kv_pools, page_tables)?, indexer_stores)?, + rope_tables, + )?; + Ok(EngineResidentEstimate { + kv_pools, + page_tables, + indexer_stores, + rope_tables, + total, + }) +} diff --git a/crates/context/src/rope_scaling.rs b/crates/context/src/rope_scaling.rs index 59c16001..6915a3f3 100644 --- a/crates/context/src/rope_scaling.rs +++ b/crates/context/src/rope_scaling.rs @@ -35,24 +35,6 @@ pub enum RopeScalingType { YaRN, } -impl RopeScalingType { - pub fn name(self) -> &'static str { - match self { - Self::None => "none", - Self::Linear => "linear", - Self::YaRN => "yarn", - } - } - pub fn parse(name: &str) -> Option { - match name { - "none" => Some(Self::None), - "linear" => Some(Self::Linear), - "yarn" => Some(Self::YaRN), - _ => None, - } - } -} - /// The float32 constants the analytic rotation kernels take. Defaults are the identity. #[derive(Clone, Copy, Debug, PartialEq)] pub struct RopeKernelArgs { @@ -63,18 +45,6 @@ pub struct RopeKernelArgs { pub attn_factor: f32, } -impl Default for RopeKernelArgs { - fn default() -> Self { - Self { - freq_scale: 1.0, - corr_low: 0.0, - corr_high: 0.0, - ext_factor: 0.0, - attn_factor: 1.0, - } - } -} - /// Why a resolved configuration is unusable. `reason()` is the Original's exact message. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum RopeScalingError { @@ -89,32 +59,6 @@ pub enum RopeScalingError { Mscale, } -impl RopeScalingError { - pub fn reason(self) -> &'static str { - match self { - Self::FreqBase => "the frequency base must be a finite value above 1", - Self::Factor => "the scaling factor must be a finite value >= 1", - Self::FreqScaleIn => "the frequency scale must be finite and positive (0 = 1/factor)", - Self::ResolvedFreqScale => { - "the resolved frequency scale must be a finite positive value" - } - Self::OrigCtx => "the original (trained) context must be finite and > 0", - Self::ExtFactor => "the YaRN ext factor must be finite and >= 0", - Self::AttnFactor => "the attention factor must be finite and > 0", - Self::Betas => "the YaRN betas must be finite and > 0", - Self::Mscale => "the resolved magnitude correction must be finite and > 0", - } - } -} - -impl fmt::Display for RopeScalingError { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - f.write_str(self.reason()) - } -} - -impl std::error::Error for RopeScalingError {} - /// The one rope configuration. `Default` is exactly today's engine: freq_scale 1, mscale 1, no correction. #[derive(Clone, Copy, Debug, PartialEq)] pub struct RopeScaling { @@ -135,146 +79,6 @@ pub struct RopeScaling { pub beta_slow: f64, } -impl Default for RopeScaling { - fn default() -> Self { - Self { - kind: RopeScalingType::None, - freq_base: DEFAULT_FREQ_BASE, - factor: 1.0, - freq_scale_in: 0.0, - orig_ctx: TRAINED_CONTEXT as f64, - ext_factor: 0.0, - attn_factor: 1.0, - beta_fast: 32.0, - beta_slow: 1.0, - } - } -} - -/// ggml `ggml_rope_yarn_corr_dim`, float64 as in the Original. -fn rope_yarn_corr_dim(n_dims: i32, n_ctx_orig: f64, n_rot: f64, base: f64) -> f64 { - f64::from(n_dims) * (n_ctx_orig / (n_rot * 2.0 * PI)).ln() / (2.0 * base.ln()) -} - -impl RopeScaling { - /// The angle shrink (ggml's `freq_scale`). - pub fn freq_scale(&self) -> f64 { - if self.kind == RopeScalingType::None { - return 1.0; - } - if self.freq_scale_in > 0.0 { - self.freq_scale_in - } else { - 1.0 / self.factor - } - } - - /// The magnitude correction; the log term rides on `ext_factor != 0`, not on the type. - pub fn mscale(&self) -> f64 { - if self.ext_factor == 0.0 { - return self.attn_factor; - } - self.attn_factor * (1.0 + 0.1 * (1.0 / self.freq_scale()).ln()) - } - - /// The correction window in PAIR indices, clamped to `[0, n_rot - 1]`. - pub fn corr_dims(&self, n_rot: i32) -> [f64; 2] { - let start = - rope_yarn_corr_dim(n_rot, self.orig_ctx, self.beta_fast, self.freq_base).floor(); - let end = rope_yarn_corr_dim(n_rot, self.orig_ctx, self.beta_slow, self.freq_base).ceil(); - let hi = f64::from(n_rot - 1); - [ - if start < 0.0 { 0.0 } else { start }, - if end > hi { hi } else { end }, - ] - } - - /// The analytic kernels' constants; `none` returns the identity whatever the other knobs hold. - pub fn kernel_args(&self, n_rot: i32) -> RopeKernelArgs { - if self.kind == RopeScalingType::None { - return RopeKernelArgs::default(); - } - let cd = self.corr_dims(n_rot); - RopeKernelArgs { - freq_scale: self.freq_scale() as f32, - corr_low: cd[0] as f32, - corr_high: cd[1] as f32, - ext_factor: self.ext_factor as f32, - attn_factor: self.attn_factor as f32, - } - } - - /// `rope_scaling_invalid`: the one validity rule. Every value is tested with `is_finite` first so a NaN - /// cannot slip through a range comparison. - pub fn validate(&self) -> Result<(), RopeScalingError> { - if !self.freq_base.is_finite() || self.freq_base <= 1.0 { - return Err(RopeScalingError::FreqBase); - } - if self.kind == RopeScalingType::None { - return Ok(()); - } - if !self.factor.is_finite() || self.factor < 1.0 { - return Err(RopeScalingError::Factor); - } - if !self.freq_scale_in.is_finite() || self.freq_scale_in < 0.0 { - return Err(RopeScalingError::FreqScaleIn); - } - let fs = self.freq_scale(); - if !fs.is_finite() || fs <= 0.0 { - return Err(RopeScalingError::ResolvedFreqScale); - } - if !self.orig_ctx.is_finite() || self.orig_ctx < 1.0 { - return Err(RopeScalingError::OrigCtx); - } - if !self.ext_factor.is_finite() || self.ext_factor < 0.0 { - return Err(RopeScalingError::ExtFactor); - } - if !self.attn_factor.is_finite() || self.attn_factor <= 0.0 { - return Err(RopeScalingError::AttnFactor); - } - if !self.beta_fast.is_finite() - || self.beta_fast <= 0.0 - || !self.beta_slow.is_finite() - || self.beta_slow <= 0.0 - { - return Err(RopeScalingError::Betas); - } - let ms = self.mscale(); - if !ms.is_finite() || ms <= 0.0 { - return Err(RopeScalingError::Mscale); - } - Ok(()) - } -} - -/// `rope_yarn_ramp`: 1 - clamp(y, 0, 1), float32, taking the PAIR index (ggml's `i0 / 2`). -pub fn rope_yarn_ramp(low: f32, high: f32, pair: i32) -> f32 { - let span = high - low; - let y = (pair as f32 - low) / if span > 0.001 { span } else { 0.001 }; - let clamped = y.clamp(0.0, 1.0); - 1.0 - clamped -} - -/// `rope_scaled_angle`: the analytic paths' float32 contract. Returns `(cos, sin)` with mscale folded in. -pub fn rope_scaled_angle( - theta_extrap: f32, - freq_scale: f32, - corr_low: f32, - corr_high: f32, - ext_factor: f32, - mscale_in: f32, - pair: i32, -) -> (f32, f32) { - let mut theta = freq_scale * theta_extrap; - let mut mscale = mscale_in; - if ext_factor != 0.0 { - let ramp_mix = rope_yarn_ramp(corr_low, corr_high, pair) * ext_factor; - theta = theta * (1.0 - ramp_mix) + theta_extrap * ramp_mix; - mscale *= 1.0 + 0.1 * (1.0 / freq_scale).ln(); - } - (theta.cos() * mscale, theta.sin() * mscale) -} - /// Why a table could not be built. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum RopeTableError { @@ -287,104 +91,6 @@ pub enum RopeTableError { BufferLength, } -impl fmt::Display for RopeTableError { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - match self { - Self::Config(e) => write!(f, "invalid rope scaling configuration: {e}"), - Self::NRot(n) => write!(f, "n_rot {n} must be even and non-zero"), - Self::TooManyPositions(n) => write!(f, "{n} positions exceed the table limits"), - Self::BufferLength => f.write_str("output buffer length does not match the row count"), - } - } -} - -impl std::error::Error for RopeTableError {} - -impl From for RopeTableError { - fn from(e: RopeScalingError) -> Self { - Self::Config(e) - } -} - -fn check_n_rot(n_rot: usize) -> Result<(), RopeTableError> { - if n_rot == 0 || !n_rot.is_multiple_of(2) || i32::try_from(n_rot).is_err() { - return Err(RopeTableError::NRot(n_rot)); - } - Ok(()) -} - -/// Bytes of the cos plus sin tables (the `with_rope` term in `qsa_state_bytes`). -pub fn rope_table_bytes(n_rot: usize, n_pos: usize) -> Option { - let half = (n_rot / 2) as u64; - (n_pos as u64).checked_mul(half)?.checked_mul(4 * 2) -} - -/// Fill rows `first_pos .. first_pos + rows` of the table into `cos_out` / `sin_out` -/// (`rows * n_rot / 2` entries each, row-major like `cos_tab[p * half + i]`). -/// -/// Row `p` depends only on `(n_rot, sc, p)`, so a table of any length is a prefix of any longer one. -/// `RopeScalingType::None` takes the Original's unscaled loop verbatim (no mscale multiply). -pub fn fill_rope_table( - n_rot: usize, - sc: &RopeScaling, - first_pos: usize, - cos_out: &mut [f32], - sin_out: &mut [f32], -) -> Result<(), RopeTableError> { - check_n_rot(n_rot)?; - sc.validate()?; - let half = n_rot / 2; - if cos_out.len() != sin_out.len() || !cos_out.len().is_multiple_of(half) { - return Err(RopeTableError::BufferLength); - } - let rows = cos_out.len() / half; - let end = first_pos - .checked_add(rows) - .ok_or(RopeTableError::TooManyPositions(rows))?; - if i32::try_from(end).is_err() { - return Err(RopeTableError::TooManyPositions(end)); - } - // inv[i] depends only on i: hoisting the pow out of the position loop yields the same value per entry. - let n_rot_f = n_rot as f64; - let inv: Vec = (0..half) - .map(|i| sc.freq_base.powf(-2.0 * (i as f64) / n_rot_f)) - .collect(); - if sc.kind == RopeScalingType::None { - for r in 0..rows { - let p = (first_pos + r) as f64; - for i in 0..half { - let ang = p * inv[i]; - cos_out[r * half + i] = ang.cos() as f32; - sin_out[r * half + i] = ang.sin() as f32; - } - } - return Ok(()); - } - let fs = sc.freq_scale(); - let ms = sc.mscale(); - let cd = sc.corr_dims(n_rot as i32); - let correct = sc.ext_factor != 0.0; - let (low, high) = (cd[0] as f32, cd[1] as f32); - // the ramp depends on the pair only - let ramp: Vec = (0..half) - .map(|i| f64::from(rope_yarn_ramp(low, high, i as i32)) * sc.ext_factor) - .collect(); - for r in 0..rows { - let p = (first_pos + r) as f64; - for i in 0..half { - let extrap = p * inv[i]; - let interp = fs * extrap; - let mut ang = interp; - if correct { - ang = interp * (1.0 - ramp[i]) + extrap * ramp[i]; - } - cos_out[r * half + i] = (ang.cos() * ms) as f32; - sin_out[r * half + i] = (ang.sin() * ms) as f32; - } - } - Ok(()) -} - /// A full `[n_pos][n_rot / 2]` cos/sin table, the layout `build_rope_table` fills and `session_init` uploads. #[derive(Clone, Debug, PartialEq)] pub struct RopeTable { @@ -394,39 +100,6 @@ pub struct RopeTable { pub sin: Vec, } -impl RopeTable { - pub fn half(&self) -> usize { - self.n_rot / 2 - } - pub fn row_cos(&self, pos: usize) -> &[f32] { - &self.cos[pos * self.half()..(pos + 1) * self.half()] - } - pub fn row_sin(&self, pos: usize) -> &[f32] { - &self.sin[pos * self.half()..(pos + 1) * self.half()] - } -} - -/// `build_rope_table(n_rot, scaling, n_pos, ...)`; `n_pos` up to 524288 (128 MiB for `n_rot` 64) and beyond. -pub fn build_rope_table( - n_rot: usize, - sc: &RopeScaling, - n_pos: usize, -) -> Result { - check_n_rot(n_rot)?; - let len = n_pos - .checked_mul(n_rot / 2) - .ok_or(RopeTableError::TooManyPositions(n_pos))?; - let mut cos = vec![0.0f32; len]; - let mut sin = vec![0.0f32; len]; - fill_rope_table(n_rot, sc, 0, &mut cos, &mut sin)?; - Ok(RopeTable { - n_rot, - n_pos, - cos, - sin, - }) -} - // ------------------------------------------------------------------------------------------------ // Knob resolution (generate.cpp): explicit flag over model-file keys over struct defaults. // ------------------------------------------------------------------------------------------------ @@ -447,22 +120,6 @@ pub struct RopeKnobs { pub yarn_beta_slow: f64, } -impl Default for RopeKnobs { - fn default() -> Self { - Self { - scaling: None, - rope_scale: 0.0, - rope_freq_base: 0.0, - rope_freq_scale: 0.0, - yarn_orig_ctx: 0.0, - yarn_ext_factor: -1.0, - yarn_attn_factor: 1.0, - yarn_beta_fast: 32.0, - yarn_beta_slow: 1.0, - } - } -} - /// The model file's rope keys (`qwen4exp.rope.*`); `0` / `None` = absent. The shipped artifact carries none. #[derive(Clone, Debug, Default, PartialEq)] pub struct ModelRopeKeys { @@ -488,30 +145,6 @@ pub enum RopeKnobError { Invalid(RopeScalingError), } -impl fmt::Display for RopeKnobError { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - match self { - Self::NotFinite => f.write_str("a rope scaling knob is not a finite number"), - Self::ScaleBelowOne => { - f.write_str("--rope-scale must be >= 1 (it extends the context, not shrinks it)") - } - Self::FreqBase => { - f.write_str("--rope-freq-base must be a base above 1 (0 = the model's)") - } - Self::Knob => f.write_str( - "invalid rope scaling knob (--yarn-ext-factor < 0 = auto, --yarn-orig-ctx 0 = default, the rest positive)", - ), - Self::ModelType(t) => write!( - f, - "model file carries rope.scaling.type '{t}' - none, linear or yarn only" - ), - Self::Invalid(e) => write!(f, "invalid rope scaling configuration: {e}"), - } - } -} - -impl std::error::Error for RopeKnobError {} - /// A resolved configuration and whether the `none` branch dropped explicit knobs /// (the Original prints "no rope scaling is active, so ... have no effect"). #[derive(Clone, Copy, Debug, PartialEq)] @@ -520,101 +153,6 @@ pub struct ResolvedRope { pub inert_knobs_ignored: bool, } -/// Port of the `generate.cpp` rope resolution: range checks, then precedence flag > model file > defaults, -/// the `none` reset, and the whole-config validity rule. -pub fn resolve_rope_scaling( - knobs: &RopeKnobs, - model: &ModelRopeKeys, -) -> Result { - let all = [ - knobs.rope_scale, - knobs.rope_freq_base, - knobs.rope_freq_scale, - knobs.yarn_orig_ctx, - knobs.yarn_ext_factor, - knobs.yarn_attn_factor, - knobs.yarn_beta_fast, - knobs.yarn_beta_slow, - ]; - if all.iter().any(|v| !v.is_finite()) { - return Err(RopeKnobError::NotFinite); - } - if knobs.rope_scale != 0.0 && knobs.rope_scale < 1.0 { - return Err(RopeKnobError::ScaleBelowOne); - } - if knobs.rope_freq_base != 0.0 && knobs.rope_freq_base <= 1.0 { - return Err(RopeKnobError::FreqBase); - } - if knobs.rope_freq_scale < 0.0 - || knobs.yarn_orig_ctx < 0.0 - || knobs.yarn_ext_factor < -1.0 - || knobs.yarn_attn_factor <= 0.0 - || knobs.yarn_beta_fast <= 0.0 - || knobs.yarn_beta_slow <= 0.0 - { - return Err(RopeKnobError::Knob); - } - - let mut cfg = RopeScaling::default(); - if let Some(kind) = knobs.scaling { - cfg.kind = kind; - } else if let Some(t) = model.scaling_type.as_deref().filter(|t| !t.is_empty()) { - match RopeScalingType::parse(t) { - Some(kind) => cfg.kind = kind, - None => return Err(RopeKnobError::ModelType(t.to_owned())), - } - } - if knobs.rope_scale > 0.0 { - cfg.factor = knobs.rope_scale; - } else if model.factor > 1.0 { - cfg.factor = model.factor; - } - if knobs.rope_freq_base > 0.0 { - cfg.freq_base = knobs.rope_freq_base; - } else if model.freq_base > 1.0 { - cfg.freq_base = model.freq_base; - } - if knobs.yarn_orig_ctx > 0.0 { - cfg.orig_ctx = knobs.yarn_orig_ctx; - } else if model.orig_ctx >= 1.0 { - cfg.orig_ctx = model.orig_ctx; - } - cfg.freq_scale_in = knobs.rope_freq_scale; - cfg.ext_factor = if knobs.yarn_ext_factor >= 0.0 { - knobs.yarn_ext_factor - } else if cfg.kind == RopeScalingType::YaRN { - 1.0 - } else { - 0.0 - }; - cfg.attn_factor = knobs.yarn_attn_factor; - cfg.beta_fast = knobs.yarn_beta_fast; - cfg.beta_slow = knobs.yarn_beta_slow; - - let mut inert = false; - if cfg.kind == RopeScalingType::None { - inert = knobs.rope_scale > 1.0 - || knobs.rope_freq_scale > 0.0 - || knobs.yarn_ext_factor > 0.0 - || knobs.yarn_attn_factor != 1.0; - let base = cfg.freq_base; - cfg = RopeScaling { - freq_base: base, - ..RopeScaling::default() - }; - } - cfg.validate().map_err(RopeKnobError::Invalid)?; - Ok(ResolvedRope { - scaling: cfg, - inert_knobs_ignored: inert, - }) -} - -/// `setup.py::derived_factor`: final context over the trained one, at least 1. -pub fn derived_factor(ctx: u64, trained: u64) -> f64 { - (ctx as f64 / trained as f64).max(1.0) -} - /// Why `setup.py::resolve_rope` refuses a combination. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum SetupRopeError { @@ -624,51 +162,15 @@ pub enum SetupRopeError { NoneBeyondTrained, } -impl fmt::Display for SetupRopeError { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - match self { - Self::ScaleWithoutMethod => f.write_str( - "--rope-scale needs --rope-scaling linear or yarn (the chosen context fits the trained range, so there is nothing to scale)", - ), - Self::NoneBeyondTrained => f.write_str( - "the context is past the model's trained range and --rope-scaling none keeps the stock angles there; pick yarn or linear, or lower the context", - ), - } - } -} - -impl std::error::Error for SetupRopeError {} - -/// `setup.py::resolve_rope(ctx, scaling, scale, trained)`: `(scaling, scale)` for the context actually served; -/// `None` means "no scaling flags" (the stock model). `scaling = None` is the omitted flag. -pub fn setup_resolve_rope( - ctx: u64, - scaling: Option, - scale: Option, - trained: u64, -) -> Result, SetupRopeError> { - let none_or_absent = matches!(scaling, None | Some(RopeScalingType::None)); - if ctx <= trained { - if scale.is_some() && none_or_absent { - return Err(SetupRopeError::ScaleWithoutMethod); - } - if none_or_absent { - return Ok(None); - } - let kind = scaling.unwrap_or(RopeScalingType::YaRN); - return Ok(Some(( - kind, - scale.unwrap_or_else(|| derived_factor(ctx, trained)), - ))); - } - if scaling == Some(RopeScalingType::None) { - return Err(SetupRopeError::NoneBeyondTrained); - } - Ok(Some(( - scaling.unwrap_or(RopeScalingType::YaRN), - scale.unwrap_or_else(|| derived_factor(ctx, trained)), - ))) -} - #[cfg(test)] mod tests; + +mod impl_ropescalingtype; +#[allow(unused_imports)] +pub use impl_ropescalingtype::*; +mod fill_rope_table; +#[allow(unused_imports)] +pub use fill_rope_table::*; +mod impl_fmt_display_for; +#[allow(unused_imports)] +pub use impl_fmt_display_for::*; diff --git a/crates/context/src/rope_scaling/fill_rope_table.rs b/crates/context/src/rope_scaling/fill_rope_table.rs new file mode 100644 index 00000000..348a0ceb --- /dev/null +++ b/crates/context/src/rope_scaling/fill_rope_table.rs @@ -0,0 +1,238 @@ +//! Moved out of the parent module by STRA-338: fn fill_rope_table, impl RopeTable, fn build_rope_table, impl Default_for_RopeKnobs, impl fmt_Display_for, impl std_error_Error .... + +#[allow(unused_imports)] +use super::*; + +/// Fill rows `first_pos .. first_pos + rows` of the table into `cos_out` / `sin_out` +/// (`rows * n_rot / 2` entries each, row-major like `cos_tab[p * half + i]`). +/// +/// Row `p` depends only on `(n_rot, sc, p)`, so a table of any length is a prefix of any longer one. +/// `RopeScalingType::None` takes the Original's unscaled loop verbatim (no mscale multiply). +pub fn fill_rope_table( + n_rot: usize, + sc: &RopeScaling, + first_pos: usize, + cos_out: &mut [f32], + sin_out: &mut [f32], +) -> Result<(), RopeTableError> { + check_n_rot(n_rot)?; + sc.validate()?; + let half = n_rot / 2; + if cos_out.len() != sin_out.len() || !cos_out.len().is_multiple_of(half) { + return Err(RopeTableError::BufferLength); + } + let rows = cos_out.len() / half; + let end = first_pos + .checked_add(rows) + .ok_or(RopeTableError::TooManyPositions(rows))?; + if i32::try_from(end).is_err() { + return Err(RopeTableError::TooManyPositions(end)); + } + // inv[i] depends only on i: hoisting the pow out of the position loop yields the same value per entry. + let n_rot_f = n_rot as f64; + let inv: Vec = (0..half) + .map(|i| sc.freq_base.powf(-2.0 * (i as f64) / n_rot_f)) + .collect(); + if sc.kind == RopeScalingType::None { + for r in 0..rows { + let p = (first_pos + r) as f64; + for i in 0..half { + let ang = p * inv[i]; + cos_out[r * half + i] = ang.cos() as f32; + sin_out[r * half + i] = ang.sin() as f32; + } + } + return Ok(()); + } + let fs = sc.freq_scale(); + let ms = sc.mscale(); + let cd = sc.corr_dims(n_rot as i32); + let correct = sc.ext_factor != 0.0; + let (low, high) = (cd[0] as f32, cd[1] as f32); + // the ramp depends on the pair only + let ramp: Vec = (0..half) + .map(|i| f64::from(rope_yarn_ramp(low, high, i as i32)) * sc.ext_factor) + .collect(); + for r in 0..rows { + let p = (first_pos + r) as f64; + for i in 0..half { + let extrap = p * inv[i]; + let interp = fs * extrap; + let mut ang = interp; + if correct { + ang = interp * (1.0 - ramp[i]) + extrap * ramp[i]; + } + cos_out[r * half + i] = (ang.cos() * ms) as f32; + sin_out[r * half + i] = (ang.sin() * ms) as f32; + } + } + Ok(()) +} + +impl RopeTable { + pub fn half(&self) -> usize { + self.n_rot / 2 + } + pub fn row_cos(&self, pos: usize) -> &[f32] { + &self.cos[pos * self.half()..(pos + 1) * self.half()] + } + pub fn row_sin(&self, pos: usize) -> &[f32] { + &self.sin[pos * self.half()..(pos + 1) * self.half()] + } +} + +/// `build_rope_table(n_rot, scaling, n_pos, ...)`; `n_pos` up to 524288 (128 MiB for `n_rot` 64) and beyond. +pub fn build_rope_table( + n_rot: usize, + sc: &RopeScaling, + n_pos: usize, +) -> Result { + check_n_rot(n_rot)?; + let len = n_pos + .checked_mul(n_rot / 2) + .ok_or(RopeTableError::TooManyPositions(n_pos))?; + let mut cos = vec![0.0f32; len]; + let mut sin = vec![0.0f32; len]; + fill_rope_table(n_rot, sc, 0, &mut cos, &mut sin)?; + Ok(RopeTable { + n_rot, + n_pos, + cos, + sin, + }) +} + +impl Default for RopeKnobs { + fn default() -> Self { + Self { + scaling: None, + rope_scale: 0.0, + rope_freq_base: 0.0, + rope_freq_scale: 0.0, + yarn_orig_ctx: 0.0, + yarn_ext_factor: -1.0, + yarn_attn_factor: 1.0, + yarn_beta_fast: 32.0, + yarn_beta_slow: 1.0, + } + } +} + +impl fmt::Display for RopeKnobError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Self::NotFinite => f.write_str("a rope scaling knob is not a finite number"), + Self::ScaleBelowOne => { + f.write_str("--rope-scale must be >= 1 (it extends the context, not shrinks it)") + } + Self::FreqBase => { + f.write_str("--rope-freq-base must be a base above 1 (0 = the model's)") + } + Self::Knob => f.write_str( + "invalid rope scaling knob (--yarn-ext-factor < 0 = auto, --yarn-orig-ctx 0 = default, the rest positive)", + ), + Self::ModelType(t) => write!( + f, + "model file carries rope.scaling.type '{t}' - none, linear or yarn only" + ), + Self::Invalid(e) => write!(f, "invalid rope scaling configuration: {e}"), + } + } +} + +impl std::error::Error for RopeKnobError {} + +/// Port of the `generate.cpp` rope resolution: range checks, then precedence flag > model file > defaults, +/// the `none` reset, and the whole-config validity rule. +pub fn resolve_rope_scaling( + knobs: &RopeKnobs, + model: &ModelRopeKeys, +) -> Result { + let all = [ + knobs.rope_scale, + knobs.rope_freq_base, + knobs.rope_freq_scale, + knobs.yarn_orig_ctx, + knobs.yarn_ext_factor, + knobs.yarn_attn_factor, + knobs.yarn_beta_fast, + knobs.yarn_beta_slow, + ]; + if all.iter().any(|v| !v.is_finite()) { + return Err(RopeKnobError::NotFinite); + } + if knobs.rope_scale != 0.0 && knobs.rope_scale < 1.0 { + return Err(RopeKnobError::ScaleBelowOne); + } + if knobs.rope_freq_base != 0.0 && knobs.rope_freq_base <= 1.0 { + return Err(RopeKnobError::FreqBase); + } + if knobs.rope_freq_scale < 0.0 + || knobs.yarn_orig_ctx < 0.0 + || knobs.yarn_ext_factor < -1.0 + || knobs.yarn_attn_factor <= 0.0 + || knobs.yarn_beta_fast <= 0.0 + || knobs.yarn_beta_slow <= 0.0 + { + return Err(RopeKnobError::Knob); + } + + let mut cfg = RopeScaling::default(); + if let Some(kind) = knobs.scaling { + cfg.kind = kind; + } else if let Some(t) = model.scaling_type.as_deref().filter(|t| !t.is_empty()) { + match RopeScalingType::parse(t) { + Some(kind) => cfg.kind = kind, + None => return Err(RopeKnobError::ModelType(t.to_owned())), + } + } + if knobs.rope_scale > 0.0 { + cfg.factor = knobs.rope_scale; + } else if model.factor > 1.0 { + cfg.factor = model.factor; + } + if knobs.rope_freq_base > 0.0 { + cfg.freq_base = knobs.rope_freq_base; + } else if model.freq_base > 1.0 { + cfg.freq_base = model.freq_base; + } + if knobs.yarn_orig_ctx > 0.0 { + cfg.orig_ctx = knobs.yarn_orig_ctx; + } else if model.orig_ctx >= 1.0 { + cfg.orig_ctx = model.orig_ctx; + } + cfg.freq_scale_in = knobs.rope_freq_scale; + cfg.ext_factor = if knobs.yarn_ext_factor >= 0.0 { + knobs.yarn_ext_factor + } else if cfg.kind == RopeScalingType::YaRN { + 1.0 + } else { + 0.0 + }; + cfg.attn_factor = knobs.yarn_attn_factor; + cfg.beta_fast = knobs.yarn_beta_fast; + cfg.beta_slow = knobs.yarn_beta_slow; + + let mut inert = false; + if cfg.kind == RopeScalingType::None { + inert = knobs.rope_scale > 1.0 + || knobs.rope_freq_scale > 0.0 + || knobs.yarn_ext_factor > 0.0 + || knobs.yarn_attn_factor != 1.0; + let base = cfg.freq_base; + cfg = RopeScaling { + freq_base: base, + ..RopeScaling::default() + }; + } + cfg.validate().map_err(RopeKnobError::Invalid)?; + Ok(ResolvedRope { + scaling: cfg, + inert_knobs_ignored: inert, + }) +} + +/// `setup.py::derived_factor`: final context over the trained one, at least 1. +pub fn derived_factor(ctx: u64, trained: u64) -> f64 { + (ctx as f64 / trained as f64).max(1.0) +} diff --git a/crates/context/src/rope_scaling/impl_fmt_display_for.rs b/crates/context/src/rope_scaling/impl_fmt_display_for.rs new file mode 100644 index 00000000..09ef6326 --- /dev/null +++ b/crates/context/src/rope_scaling/impl_fmt_display_for.rs @@ -0,0 +1,50 @@ +//! Moved out of the parent module by STRA-338: impl fmt_Display_for, impl std_error_Error, fn setup_resolve_rope. + +#[allow(unused_imports)] +use super::*; + +impl fmt::Display for SetupRopeError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Self::ScaleWithoutMethod => f.write_str( + "--rope-scale needs --rope-scaling linear or yarn (the chosen context fits the trained range, so there is nothing to scale)", + ), + Self::NoneBeyondTrained => f.write_str( + "the context is past the model's trained range and --rope-scaling none keeps the stock angles there; pick yarn or linear, or lower the context", + ), + } + } +} + +impl std::error::Error for SetupRopeError {} + +/// `setup.py::resolve_rope(ctx, scaling, scale, trained)`: `(scaling, scale)` for the context actually served; +/// `None` means "no scaling flags" (the stock model). `scaling = None` is the omitted flag. +pub fn setup_resolve_rope( + ctx: u64, + scaling: Option, + scale: Option, + trained: u64, +) -> Result, SetupRopeError> { + let none_or_absent = matches!(scaling, None | Some(RopeScalingType::None)); + if ctx <= trained { + if scale.is_some() && none_or_absent { + return Err(SetupRopeError::ScaleWithoutMethod); + } + if none_or_absent { + return Ok(None); + } + let kind = scaling.unwrap_or(RopeScalingType::YaRN); + return Ok(Some(( + kind, + scale.unwrap_or_else(|| derived_factor(ctx, trained)), + ))); + } + if scaling == Some(RopeScalingType::None) { + return Err(SetupRopeError::NoneBeyondTrained); + } + Ok(Some(( + scaling.unwrap_or(RopeScalingType::YaRN), + scale.unwrap_or_else(|| derived_factor(ctx, trained)), + ))) +} diff --git a/crates/context/src/rope_scaling/impl_ropescalingtype.rs b/crates/context/src/rope_scaling/impl_ropescalingtype.rs new file mode 100644 index 00000000..1e4ab068 --- /dev/null +++ b/crates/context/src/rope_scaling/impl_ropescalingtype.rs @@ -0,0 +1,232 @@ +//! Moved out of the parent module by STRA-338: impl RopeScalingType, impl Default_for_RopeKernelArgs, impl RopeScalingError, impl fmt_Display_for, impl std_error_Error, impl Default_for_RopeScaling .... + +#[allow(unused_imports)] +use super::*; + +impl RopeScalingType { + pub fn name(self) -> &'static str { + match self { + Self::None => "none", + Self::Linear => "linear", + Self::YaRN => "yarn", + } + } + pub fn parse(name: &str) -> Option { + match name { + "none" => Some(Self::None), + "linear" => Some(Self::Linear), + "yarn" => Some(Self::YaRN), + _ => None, + } + } +} + +impl Default for RopeKernelArgs { + fn default() -> Self { + Self { + freq_scale: 1.0, + corr_low: 0.0, + corr_high: 0.0, + ext_factor: 0.0, + attn_factor: 1.0, + } + } +} + +impl RopeScalingError { + pub fn reason(self) -> &'static str { + match self { + Self::FreqBase => "the frequency base must be a finite value above 1", + Self::Factor => "the scaling factor must be a finite value >= 1", + Self::FreqScaleIn => "the frequency scale must be finite and positive (0 = 1/factor)", + Self::ResolvedFreqScale => { + "the resolved frequency scale must be a finite positive value" + } + Self::OrigCtx => "the original (trained) context must be finite and > 0", + Self::ExtFactor => "the YaRN ext factor must be finite and >= 0", + Self::AttnFactor => "the attention factor must be finite and > 0", + Self::Betas => "the YaRN betas must be finite and > 0", + Self::Mscale => "the resolved magnitude correction must be finite and > 0", + } + } +} + +impl fmt::Display for RopeScalingError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str(self.reason()) + } +} + +impl std::error::Error for RopeScalingError {} + +impl Default for RopeScaling { + fn default() -> Self { + Self { + kind: RopeScalingType::None, + freq_base: DEFAULT_FREQ_BASE, + factor: 1.0, + freq_scale_in: 0.0, + orig_ctx: TRAINED_CONTEXT as f64, + ext_factor: 0.0, + attn_factor: 1.0, + beta_fast: 32.0, + beta_slow: 1.0, + } + } +} + +/// ggml `ggml_rope_yarn_corr_dim`, float64 as in the Original. +pub(super) fn rope_yarn_corr_dim(n_dims: i32, n_ctx_orig: f64, n_rot: f64, base: f64) -> f64 { + f64::from(n_dims) * (n_ctx_orig / (n_rot * 2.0 * PI)).ln() / (2.0 * base.ln()) +} + +impl RopeScaling { + /// The angle shrink (ggml's `freq_scale`). + pub fn freq_scale(&self) -> f64 { + if self.kind == RopeScalingType::None { + return 1.0; + } + if self.freq_scale_in > 0.0 { + self.freq_scale_in + } else { + 1.0 / self.factor + } + } + + /// The magnitude correction; the log term rides on `ext_factor != 0`, not on the type. + pub fn mscale(&self) -> f64 { + if self.ext_factor == 0.0 { + return self.attn_factor; + } + self.attn_factor * (1.0 + 0.1 * (1.0 / self.freq_scale()).ln()) + } + + /// The correction window in PAIR indices, clamped to `[0, n_rot - 1]`. + pub fn corr_dims(&self, n_rot: i32) -> [f64; 2] { + let start = + rope_yarn_corr_dim(n_rot, self.orig_ctx, self.beta_fast, self.freq_base).floor(); + let end = rope_yarn_corr_dim(n_rot, self.orig_ctx, self.beta_slow, self.freq_base).ceil(); + let hi = f64::from(n_rot - 1); + [ + if start < 0.0 { 0.0 } else { start }, + if end > hi { hi } else { end }, + ] + } + + /// The analytic kernels' constants; `none` returns the identity whatever the other knobs hold. + pub fn kernel_args(&self, n_rot: i32) -> RopeKernelArgs { + if self.kind == RopeScalingType::None { + return RopeKernelArgs::default(); + } + let cd = self.corr_dims(n_rot); + RopeKernelArgs { + freq_scale: self.freq_scale() as f32, + corr_low: cd[0] as f32, + corr_high: cd[1] as f32, + ext_factor: self.ext_factor as f32, + attn_factor: self.attn_factor as f32, + } + } + + /// `rope_scaling_invalid`: the one validity rule. Every value is tested with `is_finite` first so a NaN + /// cannot slip through a range comparison. + pub fn validate(&self) -> Result<(), RopeScalingError> { + if !self.freq_base.is_finite() || self.freq_base <= 1.0 { + return Err(RopeScalingError::FreqBase); + } + if self.kind == RopeScalingType::None { + return Ok(()); + } + if !self.factor.is_finite() || self.factor < 1.0 { + return Err(RopeScalingError::Factor); + } + if !self.freq_scale_in.is_finite() || self.freq_scale_in < 0.0 { + return Err(RopeScalingError::FreqScaleIn); + } + let fs = self.freq_scale(); + if !fs.is_finite() || fs <= 0.0 { + return Err(RopeScalingError::ResolvedFreqScale); + } + if !self.orig_ctx.is_finite() || self.orig_ctx < 1.0 { + return Err(RopeScalingError::OrigCtx); + } + if !self.ext_factor.is_finite() || self.ext_factor < 0.0 { + return Err(RopeScalingError::ExtFactor); + } + if !self.attn_factor.is_finite() || self.attn_factor <= 0.0 { + return Err(RopeScalingError::AttnFactor); + } + if !self.beta_fast.is_finite() + || self.beta_fast <= 0.0 + || !self.beta_slow.is_finite() + || self.beta_slow <= 0.0 + { + return Err(RopeScalingError::Betas); + } + let ms = self.mscale(); + if !ms.is_finite() || ms <= 0.0 { + return Err(RopeScalingError::Mscale); + } + Ok(()) + } +} + +/// `rope_yarn_ramp`: 1 - clamp(y, 0, 1), float32, taking the PAIR index (ggml's `i0 / 2`). +pub fn rope_yarn_ramp(low: f32, high: f32, pair: i32) -> f32 { + let span = high - low; + let y = (pair as f32 - low) / if span > 0.001 { span } else { 0.001 }; + let clamped = y.clamp(0.0, 1.0); + 1.0 - clamped +} + +/// `rope_scaled_angle`: the analytic paths' float32 contract. Returns `(cos, sin)` with mscale folded in. +pub fn rope_scaled_angle( + theta_extrap: f32, + freq_scale: f32, + corr_low: f32, + corr_high: f32, + ext_factor: f32, + mscale_in: f32, + pair: i32, +) -> (f32, f32) { + let mut theta = freq_scale * theta_extrap; + let mut mscale = mscale_in; + if ext_factor != 0.0 { + let ramp_mix = rope_yarn_ramp(corr_low, corr_high, pair) * ext_factor; + theta = theta * (1.0 - ramp_mix) + theta_extrap * ramp_mix; + mscale *= 1.0 + 0.1 * (1.0 / freq_scale).ln(); + } + (theta.cos() * mscale, theta.sin() * mscale) +} + +impl fmt::Display for RopeTableError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Self::Config(e) => write!(f, "invalid rope scaling configuration: {e}"), + Self::NRot(n) => write!(f, "n_rot {n} must be even and non-zero"), + Self::TooManyPositions(n) => write!(f, "{n} positions exceed the table limits"), + Self::BufferLength => f.write_str("output buffer length does not match the row count"), + } + } +} + +impl std::error::Error for RopeTableError {} + +impl From for RopeTableError { + fn from(e: RopeScalingError) -> Self { + Self::Config(e) + } +} + +pub(super) fn check_n_rot(n_rot: usize) -> Result<(), RopeTableError> { + if n_rot == 0 || !n_rot.is_multiple_of(2) || i32::try_from(n_rot).is_err() { + return Err(RopeTableError::NRot(n_rot)); + } + Ok(()) +} + +/// Bytes of the cos plus sin tables (the `with_rope` term in `qsa_state_bytes`). +pub fn rope_table_bytes(n_rot: usize, n_pos: usize) -> Option { + let half = (n_rot / 2) as u64; + (n_pos as u64).checked_mul(half)?.checked_mul(4 * 2) +} diff --git a/crates/experimental-ref/src/cvec.rs b/crates/experimental-ref/src/cvec.rs index 6628af54..fca9c4da 100644 --- a/crates/experimental-ref/src/cvec.rs +++ b/crates/experimental-ref/src/cvec.rs @@ -33,26 +33,6 @@ pub enum CvecError { BadTables, } -impl std::fmt::Display for CvecError { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - match self { - Self::Gguf(m) => write!(f, "{m}"), - Self::NotAControlVector(p) => { - write!(f, "{p}: not a control vector GGUF (general.architecture is not 'controlvector')") - } - Self::BadTensor { file, tensor, n_embd } => write!(f, "{file}: {tensor} must be {n_embd} f32"), - Self::NoDirections(p) => write!(f, "{p}: no direction. tensors"), - Self::NoSingleDirection(l) => write!(f, "--cvec-dir single:{l}: the vector has no direction for that layer"), - Self::NothingSteered { first, last } => { - write!(f, "the control vector has no direction in layers {first}..{last}") - } - Self::UnsupportedEmbd => f.write_str("control vector: unsupported n_embd"), - Self::BadTables => f.write_str("control vector: bad table sizes"), - } - } -} -impl std::error::Error for CvecError {} - // ------------------------------------------------------------------------------------------------ GGUF #[derive(Clone, Debug, PartialEq, Eq)] @@ -64,12 +44,6 @@ pub struct GgufTensor { pub data: std::ops::Range, } -impl GgufTensor { - pub fn elements(&self) -> u64 { - self.shape.iter().product() - } -} - #[derive(Clone, Debug, PartialEq, Eq)] pub struct GgufFile { pub architecture: Option, @@ -81,31 +55,6 @@ struct Cursor<'a> { b: &'a [u8], at: usize, } -impl Cursor<'_> { - fn need(&self, n: usize) -> Result<(), CvecError> { - if self.at.checked_add(n).is_none_or(|e| e > self.b.len()) { - return Err(CvecError::Gguf("GGUF: unexpected end of file in header".into())); - } - Ok(()) - } - fn take(&mut self, n: usize) -> Result<&[u8], CvecError> { - self.need(n)?; - let s = &self.b[self.at..self.at + n]; - self.at += n; - Ok(s) - } - fn u32(&mut self) -> Result { - Ok(u32::from_le_bytes(self.take(4)?.try_into().expect("4"))) - } - fn u64(&mut self) -> Result { - Ok(u64::from_le_bytes(self.take(8)?.try_into().expect("8"))) - } - fn string(&mut self) -> Result { - let n = self.u64()?; - let n = usize::try_from(n).map_err(|_| CvecError::Gguf("GGUF: unexpected end of file in header".into()))?; - Ok(String::from_utf8_lossy(self.take(n)?).into_owned()) - } -} enum Meta { Str(String), @@ -113,113 +62,6 @@ enum Meta { Other, } -fn read_value(c: &mut Cursor<'_>, t: u32, depth: u32) -> Result { - if depth > 2 { - return Err(CvecError::Gguf("GGUF: array nesting too deep".into())); - } - Ok(match t { - 0 | 1 | 7 => Meta::Uint(u64::from(c.take(1)?[0])), - 2 | 3 => Meta::Uint(u64::from(u16::from_le_bytes(c.take(2)?.try_into().expect("2")))), - 4 | 5 => Meta::Uint(u64::from(c.u32()?)), - 6 => { - c.take(4)?; - Meta::Other - } - 8 => Meta::Str(c.string()?), - 10 | 11 => Meta::Uint(c.u64()?), - 12 => { - c.take(8)?; - Meta::Other - } - 9 => { - let elem = c.u32()?; - let count = c.u64()?; - if count > (1 << 24) { - return Err(CvecError::Gguf("GGUF: implausible array length".into())); - } - for _ in 0..count { - read_value(c, elem, depth + 1)?; - } - Meta::Other - } - _ => return Err(CvecError::Gguf("GGUF: unknown metadata value type".into())), - }) -} - -/// Parse a GGUF v3 file's header (`GgufFile::parse` of `gguf_reader.hpp`), plus a check the Original lacks: -/// every tensor's data range must lie inside the file. -pub fn parse_gguf(bytes: &[u8]) -> Result { - let mut c = Cursor { b: bytes, at: 0 }; - if c.u32()? != 0x4655_4747 { - return Err(CvecError::Gguf("not a GGUF file (bad magic)".into())); - } - let version = c.u32()?; - if version != 3 { - return Err(CvecError::Gguf(format!("GGUF v{version}, this reader handles v3"))); - } - let n_tensors = c.u64()?; - let n_kv = c.u64()?; - let (mut architecture, mut model_hint, mut alignment) = (None, None, 32u64); - let mut seen_keys = std::collections::BTreeSet::new(); - for _ in 0..n_kv { - let key = c.string()?; - let t = c.u32()?; - let v = read_value(&mut c, t, 0)?; - if !seen_keys.insert(key.clone()) { - continue; // emplace keeps the first - } - match (key.as_str(), v) { - ("general.architecture", Meta::Str(s)) => architecture = Some(s), - ("general.architecture", _) => architecture = Some(String::new()), - ("controlvector.model_hint", Meta::Str(s)) => model_hint = Some(s), - ("controlvector.model_hint", _) => model_hint = Some(String::new()), - ("general.alignment", Meta::Uint(a)) if a != 0 => alignment = a, - _ => {} - } - } - let mut names = std::collections::BTreeSet::new(); - let mut infos = Vec::new(); - for _ in 0..n_tensors { - let name = c.string()?; - if !names.insert(name.clone()) { - return Err(CvecError::Gguf(format!("GGUF: duplicate tensor name '{name}'"))); - } - let nd = c.u32()?; - if nd == 0 || nd > 4 { - return Err(CvecError::Gguf(format!("GGUF: bad n_dims for {name}"))); - } - let mut shape = Vec::new(); - for _ in 0..nd { - shape.push(c.u64()?); - } - let ggml_type = c.u32()?; - let offset = c.u64()?; - infos.push((name, shape, ggml_type, offset)); - } - let data_start = (c.at as u64).div_ceil(alignment) * alignment; - if data_start > bytes.len() as u64 { - return Err(CvecError::Gguf("GGUF: data section starts past EOF".into())); - } - let mut tensors = Vec::new(); - for (name, shape, ggml_type, offset) in infos { - let elements = shape.iter().try_fold(1u64, |a, d| a.checked_mul(*d)); - // only F32 tensors are read; their extent is checked, others keep an empty range - let range = match (ggml_type, elements) { - (0, Some(n)) => { - let start = data_start.checked_add(offset); - let end = start.and_then(|s| n.checked_mul(4).and_then(|b| s.checked_add(b))); - match (start, end) { - (Some(s), Some(e)) if e <= bytes.len() as u64 => s as usize..e as usize, - _ => return Err(CvecError::Gguf(format!("GGUF: tensor {name} lies outside the file"))), - } - } - _ => 0..0, - }; - tensors.push(GgufTensor { name, shape, ggml_type, data: range }); - } - Ok(GgufFile { architecture, model_hint, tensors }) -} - // ---------------------------------------------------------------------------------------------- tables /// `--cvec-mode`: 0 project, 1 add (llama.cpp's default). @@ -239,12 +81,6 @@ pub struct CvecOptions { pub single: i64, } -impl Default for CvecOptions { - fn default() -> Self { - Self { first: -1, last: -1, mode: CvecMode::Add, single: -1 } - } -} - /// The tables `cvec_upload` takes plus the description the engine keeps (`Cvec`). #[derive(Clone, Debug, PartialEq)] pub struct CvecTables { @@ -262,215 +98,12 @@ pub struct CvecTables { pub summary: String, } -impl CvecTables { - /// `Cvec::covers`: layer `l`'s FFN write is followed by the vector (decided at load time). - pub fn covers(&self, l: i64) -> bool { - l >= self.first && l <= self.last && (l as usize) < self.steered.len() && l >= 0 && self.steered[l as usize] - } -} - -/// `load_control_vectors`: every file's `direction.` times its scale, summed (f32 multiply then add), then the -/// project/add tables. `files` are `(label, bytes, scale)`. A `direction.` with `l < 1` or `l >= n_layers` is -/// ignored (layer 0 has no vector; past the model is ignored, as in llama.cpp). -pub fn load_control_vectors( - files: &[(String, Vec, f32)], - n_layers: i64, - n_embd: i64, - hc: i64, - o: &CvecOptions, -) -> Result { - let (l_n, n) = (n_layers as usize, n_embd as usize); - let mut data = vec![0.0f32; l_n * n]; - let mut have = vec![false; l_n]; - for (label, bytes, scale) in files { - let f = parse_gguf(bytes)?; - if f.architecture.as_deref() != Some("controlvector") { - return Err(CvecError::NotAControlVector(label.clone())); - } - let mut found = 0; - for t in &f.tensors { - let Some(rest) = t.name.strip_prefix("direction.") else { continue }; - // std::strtol: an optional sign and leading digits, anything else stops the parse (0 if none) - let digits: String = rest.chars().take_while(|c| c.is_ascii_digit()).collect(); - let l: i64 = digits.parse().unwrap_or(0); - if l < 1 || l >= n_layers { - continue; - } - if t.ggml_type != 0 || t.elements() != n as u64 { - return Err(CvecError::BadTensor { file: label.clone(), tensor: t.name.clone(), n_embd }); - } - let src = &bytes[t.data.clone()]; - for j in 0..n { - let v = f32::from_le_bytes(src[j * 4..j * 4 + 4].try_into().expect("4")); - data[l as usize * n + j] += *scale * v; - } - have[l as usize] = true; - found += 1; - } - if found == 0 { - return Err(CvecError::NoDirections(label.clone())); - } - } - let first = if o.first <= 0 { 1 } else { o.first }; - let last = if o.last <= 0 || o.last >= n_layers { n_layers - 1 } else { o.last }; - let single = if o.mode == CvecMode::Project { o.single } else { -1 }; - if single >= 0 && (single >= n_layers || !have[single as usize]) { - return Err(CvecError::NoSingleDirection(single)); - } - let mut dir = vec![0.0f32; l_n * n]; - let mut s = vec![0.0f32; l_n]; - let mut steered = 0; - for l in first..=last { - let src = if single >= 0 { single } else { l }; - if src < 0 || src >= n_layers || !have[src as usize] { - continue; - } - let d = &data[src as usize * n..(src as usize + 1) * n]; - match o.mode { - CvecMode::Project => { - let mut nrm = 0.0f64; - for v in d { - nrm += f64::from(*v) * f64::from(*v); - } - let nrm = nrm.sqrt(); - if nrm <= 0.0 { - continue; - } - s[l as usize] = nrm as f32; - for j in 0..n { - dir[l as usize * n + j] = (f64::from(d[j]) / nrm) as f32; - } - } - CvecMode::Add => { - s[l as usize] = 1.0; - dir[l as usize * n..(l as usize + 1) * n].copy_from_slice(d); - } - } - steered += 1; - } - if steered == 0 { - return Err(CvecError::NothingSteered { first, last }); - } - check_tables(&dir, &s, n_embd)?; - let summary = format!( - "{}:{}-{}{}", - if o.mode == CvecMode::Project { "project" } else { "add" }, - first, - last, - if single >= 0 { format!(":single{single}") } else { String::new() } - ); - let steered_flags = s.iter().map(|v| *v != 0.0).collect(); - Ok(CvecTables { dir, s, mode: o.mode, first, last, n_embd, hc, steered: steered_flags, summary }) -} - -/// The admission of `cvec_upload`. -pub fn check_tables(dir: &[f32], s: &[f32], n_embd: i64) -> Result<(), CvecError> { - if n_embd < 1 || n_embd > (THREADS * MAXK) as i64 { - return Err(CvecError::UnsupportedEmbd); - } - if s.is_empty() || dir.len() != s.len() * n_embd as usize { - return Err(CvecError::BadTables); - } - Ok(()) -} - -// ---------------------------------------------------------------------------------------------- kernel - -/// The fused hyper-connection read's gate (`sigmoidf_`, `1 / (1 + __expf(-x))`). The device uses the fast -/// intrinsic; this is the libm result, so a pending write is exact only up to that intrinsic's error. -pub fn sigmoid(x: f32) -> f32 { - 1.0 / (1.0 + (-x).exp()) -} - -/// Butterfly sum over 32 lanes with `__shfl_xor_sync` offsets 16, 8, 4, 2, 1 (every lane ends with the same -/// value; lane 0's is returned). -pub fn warp_xor_sum(mut lanes: [f32; 32]) -> f32 { - let mut o = 16; - while o > 0 { - let prev = lanes; - for l in 0..32 { - lanes[l] = prev[l] + prev[l ^ o]; - } - o >>= 1; - } - lanes[0] -} - -/// One `cvec_apply` over a batch: `R` is `T` rows of `r_ld` floats, each holding `hc` streams of `n`. With -/// `write`, the pending FFN write `R += bo * 2 sigmoid(inj / hc)` is applied first (`bo` rows of `bo_ld`, -/// `inj` rows of `inj_ld`). Literal twin of `cvec_kernel`'s per-thread dataflow, including the reduction tree. -#[allow(clippy::too_many_arguments, clippy::needless_range_loop)] // thread/k indices mirror the CUDA text -pub fn apply( - r: &mut [f32], - tables: &CvecTables, - on: bool, - layer: usize, - t_count: usize, - r_ld: usize, - pending: Option<(&[f32], usize, &[f32], usize)>, -) { - let (n, hc) = (tables.n_embd as usize, tables.hc as usize); - let write = pending.is_some(); - let s = tables.s[layer]; - let steer = on && s != 0.0; - if !steer && !write { - return; - } - let v = &tables.dir[layer * n..(layer + 1) * n]; - for t in 0..t_count { - for c in 0..hc { - let base = t * r_ld + c * n; - let (w, b) = match pending { - Some((bo, bo_ld, inj, inj_ld)) => (2.0 * sigmoid(inj[t * inj_ld + c] / hc as f32), Some(&bo[t * bo_ld..][..n])), - None => (0.0, None), - }; - // per-thread registers - let mut x = vec![[0.0f32; MAXK]; THREADS]; - let mut dots = [0.0f32; THREADS]; - for tid in 0..THREADS { - let mut dot = 0.0f32; - for k in 0..MAXK { - let d = tid + k * THREADS; - if d < n { - let mut xv = r[base + d]; - if let Some(b) = b { - xv = b[d].mul_add(w, xv); - } - x[tid][k] = xv; - if steer && tables.mode == CvecMode::Project { - dot = xv.mul_add(v[d], dot); - } - } - } - dots[tid] = dot; - } - let mut dot = 0.0f32; - if steer && tables.mode == CvecMode::Project { - let mut part = [0.0f32; THREADS / 32]; - for (w_i, p) in part.iter_mut().enumerate() { - let mut lanes = [0.0f32; 32]; - lanes.copy_from_slice(&dots[w_i * 32..w_i * 32 + 32]); - *p = warp_xor_sum(lanes); - } - let mut lanes = [0.0f32; 32]; - lanes[..THREADS / 32].copy_from_slice(&part); - dot = warp_xor_sum(lanes) * s; // s (h . v) - } - for tid in 0..THREADS { - for k in 0..MAXK { - let d = tid + k * THREADS; - if d < n { - let mut xv = x[tid][k]; - if steer { - xv = if tables.mode == CvecMode::Project { (-dot).mul_add(v[d], xv) } else { xv + v[d] }; - } - r[base + d] = xv; - } - } - } - } - } -} - #[cfg(test)] mod tests; + +mod impl_std_fmt_display; +#[allow(unused_imports)] +pub use impl_std_fmt_display::*; +mod load_control_vectors; +#[allow(unused_imports)] +pub use load_control_vectors::*; diff --git a/crates/experimental-ref/src/cvec/impl_std_fmt_display.rs b/crates/experimental-ref/src/cvec/impl_std_fmt_display.rs new file mode 100644 index 00000000..3ea67e2a --- /dev/null +++ b/crates/experimental-ref/src/cvec/impl_std_fmt_display.rs @@ -0,0 +1,176 @@ +//! Moved out of the parent module by STRA-338: impl std_fmt_Display, impl std_error_Error, impl GgufTensor, impl Cursor, fn read_value, fn parse_gguf .... + +#[allow(unused_imports)] +use super::*; + + +impl std::fmt::Display for CvecError { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match self { + Self::Gguf(m) => write!(f, "{m}"), + Self::NotAControlVector(p) => { + write!(f, "{p}: not a control vector GGUF (general.architecture is not 'controlvector')") + } + Self::BadTensor { file, tensor, n_embd } => write!(f, "{file}: {tensor} must be {n_embd} f32"), + Self::NoDirections(p) => write!(f, "{p}: no direction. tensors"), + Self::NoSingleDirection(l) => write!(f, "--cvec-dir single:{l}: the vector has no direction for that layer"), + Self::NothingSteered { first, last } => { + write!(f, "the control vector has no direction in layers {first}..{last}") + } + Self::UnsupportedEmbd => f.write_str("control vector: unsupported n_embd"), + Self::BadTables => f.write_str("control vector: bad table sizes"), + } + } +} +impl std::error::Error for CvecError {} + +impl GgufTensor { + pub fn elements(&self) -> u64 { + self.shape.iter().product() + } +} +impl Cursor<'_> { + pub(super) fn need(&self, n: usize) -> Result<(), CvecError> { + if self.at.checked_add(n).is_none_or(|e| e > self.b.len()) { + return Err(CvecError::Gguf("GGUF: unexpected end of file in header".into())); + } + Ok(()) + } + pub(super) fn take(&mut self, n: usize) -> Result<&[u8], CvecError> { + self.need(n)?; + let s = &self.b[self.at..self.at + n]; + self.at += n; + Ok(s) + } + pub(super) fn u32(&mut self) -> Result { + Ok(u32::from_le_bytes(self.take(4)?.try_into().expect("4"))) + } + pub(super) fn u64(&mut self) -> Result { + Ok(u64::from_le_bytes(self.take(8)?.try_into().expect("8"))) + } + pub(super) fn string(&mut self) -> Result { + let n = self.u64()?; + let n = usize::try_from(n).map_err(|_| CvecError::Gguf("GGUF: unexpected end of file in header".into()))?; + Ok(String::from_utf8_lossy(self.take(n)?).into_owned()) + } +} + +pub(super) fn read_value(c: &mut Cursor<'_>, t: u32, depth: u32) -> Result { + if depth > 2 { + return Err(CvecError::Gguf("GGUF: array nesting too deep".into())); + } + Ok(match t { + 0 | 1 | 7 => Meta::Uint(u64::from(c.take(1)?[0])), + 2 | 3 => Meta::Uint(u64::from(u16::from_le_bytes(c.take(2)?.try_into().expect("2")))), + 4 | 5 => Meta::Uint(u64::from(c.u32()?)), + 6 => { + c.take(4)?; + Meta::Other + } + 8 => Meta::Str(c.string()?), + 10 | 11 => Meta::Uint(c.u64()?), + 12 => { + c.take(8)?; + Meta::Other + } + 9 => { + let elem = c.u32()?; + let count = c.u64()?; + if count > (1 << 24) { + return Err(CvecError::Gguf("GGUF: implausible array length".into())); + } + for _ in 0..count { + read_value(c, elem, depth + 1)?; + } + Meta::Other + } + _ => return Err(CvecError::Gguf("GGUF: unknown metadata value type".into())), + }) +} + +/// Parse a GGUF v3 file's header (`GgufFile::parse` of `gguf_reader.hpp`), plus a check the Original lacks: +/// every tensor's data range must lie inside the file. +pub fn parse_gguf(bytes: &[u8]) -> Result { + let mut c = Cursor { b: bytes, at: 0 }; + if c.u32()? != 0x4655_4747 { + return Err(CvecError::Gguf("not a GGUF file (bad magic)".into())); + } + let version = c.u32()?; + if version != 3 { + return Err(CvecError::Gguf(format!("GGUF v{version}, this reader handles v3"))); + } + let n_tensors = c.u64()?; + let n_kv = c.u64()?; + let (mut architecture, mut model_hint, mut alignment) = (None, None, 32u64); + let mut seen_keys = std::collections::BTreeSet::new(); + for _ in 0..n_kv { + let key = c.string()?; + let t = c.u32()?; + let v = read_value(&mut c, t, 0)?; + if !seen_keys.insert(key.clone()) { + continue; // emplace keeps the first + } + match (key.as_str(), v) { + ("general.architecture", Meta::Str(s)) => architecture = Some(s), + ("general.architecture", _) => architecture = Some(String::new()), + ("controlvector.model_hint", Meta::Str(s)) => model_hint = Some(s), + ("controlvector.model_hint", _) => model_hint = Some(String::new()), + ("general.alignment", Meta::Uint(a)) if a != 0 => alignment = a, + _ => {} + } + } + let mut names = std::collections::BTreeSet::new(); + let mut infos = Vec::new(); + for _ in 0..n_tensors { + let name = c.string()?; + if !names.insert(name.clone()) { + return Err(CvecError::Gguf(format!("GGUF: duplicate tensor name '{name}'"))); + } + let nd = c.u32()?; + if nd == 0 || nd > 4 { + return Err(CvecError::Gguf(format!("GGUF: bad n_dims for {name}"))); + } + let mut shape = Vec::new(); + for _ in 0..nd { + shape.push(c.u64()?); + } + let ggml_type = c.u32()?; + let offset = c.u64()?; + infos.push((name, shape, ggml_type, offset)); + } + let data_start = (c.at as u64).div_ceil(alignment) * alignment; + if data_start > bytes.len() as u64 { + return Err(CvecError::Gguf("GGUF: data section starts past EOF".into())); + } + let mut tensors = Vec::new(); + for (name, shape, ggml_type, offset) in infos { + let elements = shape.iter().try_fold(1u64, |a, d| a.checked_mul(*d)); + // only F32 tensors are read; their extent is checked, others keep an empty range + let range = match (ggml_type, elements) { + (0, Some(n)) => { + let start = data_start.checked_add(offset); + let end = start.and_then(|s| n.checked_mul(4).and_then(|b| s.checked_add(b))); + match (start, end) { + (Some(s), Some(e)) if e <= bytes.len() as u64 => s as usize..e as usize, + _ => return Err(CvecError::Gguf(format!("GGUF: tensor {name} lies outside the file"))), + } + } + _ => 0..0, + }; + tensors.push(GgufTensor { name, shape, ggml_type, data: range }); + } + Ok(GgufFile { architecture, model_hint, tensors }) +} + +impl Default for CvecOptions { + fn default() -> Self { + Self { first: -1, last: -1, mode: CvecMode::Add, single: -1 } + } +} + +impl CvecTables { + /// `Cvec::covers`: layer `l`'s FFN write is followed by the vector (decided at load time). + pub fn covers(&self, l: i64) -> bool { + l >= self.first && l <= self.last && (l as usize) < self.steered.len() && l >= 0 && self.steered[l as usize] + } +} diff --git a/crates/experimental-ref/src/cvec/load_control_vectors.rs b/crates/experimental-ref/src/cvec/load_control_vectors.rs new file mode 100644 index 00000000..8434e052 --- /dev/null +++ b/crates/experimental-ref/src/cvec/load_control_vectors.rs @@ -0,0 +1,208 @@ +//! Moved out of the parent module by STRA-338: fn load_control_vectors, fn check_tables, fn sigmoid, fn warp_xor_sum, fn apply. + +#[allow(unused_imports)] +use super::*; + + +/// `load_control_vectors`: every file's `direction.` times its scale, summed (f32 multiply then add), then the +/// project/add tables. `files` are `(label, bytes, scale)`. A `direction.` with `l < 1` or `l >= n_layers` is +/// ignored (layer 0 has no vector; past the model is ignored, as in llama.cpp). +pub fn load_control_vectors( + files: &[(String, Vec, f32)], + n_layers: i64, + n_embd: i64, + hc: i64, + o: &CvecOptions, +) -> Result { + let (l_n, n) = (n_layers as usize, n_embd as usize); + let mut data = vec![0.0f32; l_n * n]; + let mut have = vec![false; l_n]; + for (label, bytes, scale) in files { + let f = parse_gguf(bytes)?; + if f.architecture.as_deref() != Some("controlvector") { + return Err(CvecError::NotAControlVector(label.clone())); + } + let mut found = 0; + for t in &f.tensors { + let Some(rest) = t.name.strip_prefix("direction.") else { continue }; + // std::strtol: an optional sign and leading digits, anything else stops the parse (0 if none) + let digits: String = rest.chars().take_while(|c| c.is_ascii_digit()).collect(); + let l: i64 = digits.parse().unwrap_or(0); + if l < 1 || l >= n_layers { + continue; + } + if t.ggml_type != 0 || t.elements() != n as u64 { + return Err(CvecError::BadTensor { file: label.clone(), tensor: t.name.clone(), n_embd }); + } + let src = &bytes[t.data.clone()]; + for j in 0..n { + let v = f32::from_le_bytes(src[j * 4..j * 4 + 4].try_into().expect("4")); + data[l as usize * n + j] += *scale * v; + } + have[l as usize] = true; + found += 1; + } + if found == 0 { + return Err(CvecError::NoDirections(label.clone())); + } + } + let first = if o.first <= 0 { 1 } else { o.first }; + let last = if o.last <= 0 || o.last >= n_layers { n_layers - 1 } else { o.last }; + let single = if o.mode == CvecMode::Project { o.single } else { -1 }; + if single >= 0 && (single >= n_layers || !have[single as usize]) { + return Err(CvecError::NoSingleDirection(single)); + } + let mut dir = vec![0.0f32; l_n * n]; + let mut s = vec![0.0f32; l_n]; + let mut steered = 0; + for l in first..=last { + let src = if single >= 0 { single } else { l }; + if src < 0 || src >= n_layers || !have[src as usize] { + continue; + } + let d = &data[src as usize * n..(src as usize + 1) * n]; + match o.mode { + CvecMode::Project => { + let mut nrm = 0.0f64; + for v in d { + nrm += f64::from(*v) * f64::from(*v); + } + let nrm = nrm.sqrt(); + if nrm <= 0.0 { + continue; + } + s[l as usize] = nrm as f32; + for j in 0..n { + dir[l as usize * n + j] = (f64::from(d[j]) / nrm) as f32; + } + } + CvecMode::Add => { + s[l as usize] = 1.0; + dir[l as usize * n..(l as usize + 1) * n].copy_from_slice(d); + } + } + steered += 1; + } + if steered == 0 { + return Err(CvecError::NothingSteered { first, last }); + } + check_tables(&dir, &s, n_embd)?; + let summary = format!( + "{}:{}-{}{}", + if o.mode == CvecMode::Project { "project" } else { "add" }, + first, + last, + if single >= 0 { format!(":single{single}") } else { String::new() } + ); + let steered_flags = s.iter().map(|v| *v != 0.0).collect(); + Ok(CvecTables { dir, s, mode: o.mode, first, last, n_embd, hc, steered: steered_flags, summary }) +} + +/// The admission of `cvec_upload`. +pub fn check_tables(dir: &[f32], s: &[f32], n_embd: i64) -> Result<(), CvecError> { + if n_embd < 1 || n_embd > (THREADS * MAXK) as i64 { + return Err(CvecError::UnsupportedEmbd); + } + if s.is_empty() || dir.len() != s.len() * n_embd as usize { + return Err(CvecError::BadTables); + } + Ok(()) +} + +// ---------------------------------------------------------------------------------------------- kernel + +/// The fused hyper-connection read's gate (`sigmoidf_`, `1 / (1 + __expf(-x))`). The device uses the fast +/// intrinsic; this is the libm result, so a pending write is exact only up to that intrinsic's error. +pub fn sigmoid(x: f32) -> f32 { + 1.0 / (1.0 + (-x).exp()) +} + +/// Butterfly sum over 32 lanes with `__shfl_xor_sync` offsets 16, 8, 4, 2, 1 (every lane ends with the same +/// value; lane 0's is returned). +pub fn warp_xor_sum(mut lanes: [f32; 32]) -> f32 { + let mut o = 16; + while o > 0 { + let prev = lanes; + for l in 0..32 { + lanes[l] = prev[l] + prev[l ^ o]; + } + o >>= 1; + } + lanes[0] +} + +/// One `cvec_apply` over a batch: `R` is `T` rows of `r_ld` floats, each holding `hc` streams of `n`. With +/// `write`, the pending FFN write `R += bo * 2 sigmoid(inj / hc)` is applied first (`bo` rows of `bo_ld`, +/// `inj` rows of `inj_ld`). Literal twin of `cvec_kernel`'s per-thread dataflow, including the reduction tree. +#[allow(clippy::too_many_arguments, clippy::needless_range_loop)] // thread/k indices mirror the CUDA text +pub fn apply( + r: &mut [f32], + tables: &CvecTables, + on: bool, + layer: usize, + t_count: usize, + r_ld: usize, + pending: Option<(&[f32], usize, &[f32], usize)>, +) { + let (n, hc) = (tables.n_embd as usize, tables.hc as usize); + let write = pending.is_some(); + let s = tables.s[layer]; + let steer = on && s != 0.0; + if !steer && !write { + return; + } + let v = &tables.dir[layer * n..(layer + 1) * n]; + for t in 0..t_count { + for c in 0..hc { + let base = t * r_ld + c * n; + let (w, b) = match pending { + Some((bo, bo_ld, inj, inj_ld)) => (2.0 * sigmoid(inj[t * inj_ld + c] / hc as f32), Some(&bo[t * bo_ld..][..n])), + None => (0.0, None), + }; + // per-thread registers + let mut x = vec![[0.0f32; MAXK]; THREADS]; + let mut dots = [0.0f32; THREADS]; + for tid in 0..THREADS { + let mut dot = 0.0f32; + for k in 0..MAXK { + let d = tid + k * THREADS; + if d < n { + let mut xv = r[base + d]; + if let Some(b) = b { + xv = b[d].mul_add(w, xv); + } + x[tid][k] = xv; + if steer && tables.mode == CvecMode::Project { + dot = xv.mul_add(v[d], dot); + } + } + } + dots[tid] = dot; + } + let mut dot = 0.0f32; + if steer && tables.mode == CvecMode::Project { + let mut part = [0.0f32; THREADS / 32]; + for (w_i, p) in part.iter_mut().enumerate() { + let mut lanes = [0.0f32; 32]; + lanes.copy_from_slice(&dots[w_i * 32..w_i * 32 + 32]); + *p = warp_xor_sum(lanes); + } + let mut lanes = [0.0f32; 32]; + lanes[..THREADS / 32].copy_from_slice(&part); + dot = warp_xor_sum(lanes) * s; // s (h . v) + } + for tid in 0..THREADS { + for k in 0..MAXK { + let d = tid + k * THREADS; + if d < n { + let mut xv = x[tid][k]; + if steer { + xv = if tables.mode == CvecMode::Project { (-dot).mul_add(v[d], xv) } else { xv + v[d] }; + } + r[base + d] = xv; + } + } + } + } + } +} diff --git a/crates/experimental-ref/src/kv_stream.rs b/crates/experimental-ref/src/kv_stream.rs index 08649c3d..2d058939 100644 --- a/crates/experimental-ref/src/kv_stream.rs +++ b/crates/experimental-ref/src/kv_stream.rs @@ -29,11 +29,6 @@ pub const KV_RESIDENT_MIN: i64 = 20480; /// `qsa_step_bytes()`: four int32. pub const STEP_BYTES: u64 = 16; -/// `kv_stream_map_bytes`: five per-slot int arrays plus the control block. -pub const fn map_bytes(n_slots: u64) -> u64 { - n_slots * 4 * 5 + CTL_INTS as u64 * 4 -} - // ------------------------------------------------------------------------------------------ planner /// `QsaState::kv_mode`. @@ -62,75 +57,6 @@ pub struct PlanSwitches { pub main_off: bool, } -/// `kv_plan` of `layer.cpp`. `ring_cells < 0` forces a fully resident state, `> 0` is the drafter's ring. -pub fn kv_plan(s: &QsaShapes, max_cells: i64, ring_cells: i64, kv_resident: i64, sw: PlanSwitches) -> KvPlan { - let ps = s.page_size; - let pages = (max_cells + ps - 1) / ps; - let mut p = KvPlan { mode: StreamMode::Resident, pages, slots: pages, pooled_rows: max_cells / s.idx_block + 2 }; - if kv_resident <= 0 || ring_cells < 0 { - return p; - } - if if ring_cells > 0 { sw.ring_off } else { sw.main_off } { - return p; - } - if ring_cells > 0 { - let r = (ring_cells + ps - 1) / ps; - if r < pages { - p.mode = StreamMode::Ring; - p.slots = r; - p.pooled_rows = 2; // the drafter has no indexer - } - } else { - let r = (kv_resident.max(KV_RESIDENT_MIN) + ps - 1) / ps; - if r < pages { - p.mode = StreamMode::Streamed; - p.slots = r; - } - } - p -} - -fn align16(n: u64) -> u64 { - (n + 15) & !15 -} - -/// `qsa_state_bytes(g, max_cells, with_rope, ring_cells)` of one QSA layer for `format`. `ring` selects the -/// drafter's state (`ring_cells > 0`): K8V4 does not apply to it (the drafter is plain INT8), the other globals do. -pub fn qsa_state_bytes( - s: &QsaShapes, - format: KvFormat, - max_cells: i64, - with_rope: bool, - ring_cells: i64, - kv_resident: i64, - sw: PlanSwitches, -) -> u64 { - let p = kv_plan(s, max_cells, ring_cells, kv_resident, sw); - // g_kv_hybrid && ring_cells <= 0 selects the hybrid pool; a ring state under k8v4 is INT8 (mtp.cpp) - let pool_format = if format == KvFormat::K8V4 && ring_cells > 0 { KvFormat::Int8 } else { format }; - let mut n = kv_pool_bytes(pool_format, s, p.slots as u64) + 4 * 16; - n += p.pages as u64 * 4; // page_table - if p.mode == StreamMode::Streamed { - n += map_bytes(p.slots as u64) + 6 * 16; // the residency map - } - n += (s.idx_block as u64 - 1) * s.idx_dim as u64 * 4; // tail - n += s.idx_dim as u64 * 4; // dead - n += p.pooled_rows as u64 * s.idx_dim as u64 * 4; // pooled - n += 16; // block_pos - if with_rope { - n += max_cells as u64 * (s.n_rot as u64 / 2) * 4 * 2; // cos + sin tables - } - n += STEP_BYTES + 16; // counts and aligned attention status - n += s.n_head as u64 * 4; // pos_dev - align16(n) + 256 -} - -/// Pinned host bytes of one streamed or ring state's copy (`pages * kv_block_bytes + 4 * 256`). -pub fn host_copy_bytes(s: &QsaShapes, format: KvFormat, pages: i64) -> Option { - let sf = StreamFormat::of(format)?; - Some(pages as u64 * kv_block_bytes(s, sf) + 4 * 256) -} - #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum StreamError { /// Fewer slots than the resolve block: the sweep would take one slot twice (`kv_stream_resolve` guard). @@ -147,21 +73,6 @@ pub enum StreamError { NotStreamable, } -/// The host guards of `kv_stream_resolve`. -pub fn check_resolve(s: &QsaShapes, n_slots: i64, n_q: i64, cap: i64) -> Result<(), StreamError> { - if s.n_head_kv * s.page_size * (s.head_dim / crate::kv_q8::KV_Q8_GROUP as i64) * 2 % 16 != 0 { - return Err(StreamError::ScaleRunAlignment); - } - if n_slots < RT as i64 { - return Err(StreamError::TooFewSlots); - } - // n_slots "must hold the distinct blocks of one call (n_q x (cap / page_size + 2))" - if n_slots < n_q * (cap / s.page_size + 2) { - return Err(StreamError::CallTooLarge); - } - Ok(()) -} - // ------------------------------------------------------------------------------------ the resolver /// Order in which the device threads appended the missed blocks of phase 1. @@ -205,233 +116,12 @@ pub struct StreamMap { pub miss_slot: Vec, } -impl StreamMap { - /// `kv_stream_reset`: every block evicted, every slot free, counters zero. - pub fn new(n_blocks: usize, n_slots: usize) -> Self { - Self { - page_table: vec![-1; n_blocks], - slot_block: vec![-1; n_slots], - slot_stamp: vec![-1; n_slots], - slot_ref: vec![0; n_slots], - ctl: [0; CTL_INTS], - miss_block: vec![0; n_slots], - miss_slot: vec![0; n_slots], - } - } - - pub fn n_slots(&self) -> usize { - self.slot_block.len() - } - - pub fn reset(&mut self) { - *self = Self::new(self.page_table.len(), self.n_slots()); - } - - /// `kv_stream_counters` (the u64 counters sit at ctl[4..10]). - pub fn counters(&self) -> Counters { - let u = |i: usize| u64::from(self.ctl[i] as u32) | (u64::from(self.ctl[i + 1] as u32) << 32); - Counters { misses: u(4), lookups: u(6), calls: u(8), overflow: self.ctl[3] != 0 } - } - - fn add_u64(&mut self, i: usize, v: u64) { - let cur = u64::from(self.ctl[i] as u32) | (u64::from(self.ctl[i + 1] as u32) << 32); - let n = cur.wrapping_add(v); - self.ctl[i] = n as u32 as i32; - self.ctl[i + 1] = (n >> 32) as u32 as i32; - } - - /// One `resolve_kernel` call. `ids` is `[n_q][cap]` ascending cell ids, the width of query `q` is - /// `steps[q * 4 + 3]`. - pub fn resolve( - &mut self, - ids: &[i32], - steps: &[i32], - n_q: usize, - cap: usize, - page_size: i32, - order: &MissOrder, - ) -> Result { - let n = self.n_slots(); - if n < RT { - return Err(StreamError::TooFewSlots); - } - let epoch = self.ctl[0] + 1; - // 1. hits take this epoch and their reference bit; a missing block is claimed exactly once (-1 -> -2) - let mut lookups = 0usize; - let mut misses: Vec = Vec::new(); - for q in 0..n_q { - let width = steps[q * 4 + 3] as usize; - let qi = &ids[q * cap..q * cap + cap]; - for i in 0..width { - let b = qi[i] / page_size; - if i > 0 && qi[i - 1] / page_size == b { - continue; // ids are ascending: one lookup per block - } - lookups += 1; - let bu = usize::try_from(b).map_err(|_| StreamError::BlockOutOfRange)?; - let sl = *self.page_table.get(bu).ok_or(StreamError::BlockOutOfRange)?; - if sl >= 0 { - self.slot_stamp[sl as usize] = epoch; - self.slot_ref[sl as usize] = 1; - } else if sl == -1 { - self.page_table[bu] = -2; - misses.push(b); - } - } - } - if misses.len() > n { - return Err(StreamError::CallTooLarge); - } - if let MissOrder::Observed(o) = order { - let mut a = o.clone(); - let mut b = misses.clone(); - a.sort_unstable(); - b.sort_unstable(); - if a != b { - return Err(StreamError::BadMissOrder); - } - misses = o.clone(); - } - for (k, b) in misses.iter().enumerate() { - self.miss_block[k] = *b; - } - // 2. one victim per miss: a clock sweep from the hand. A slot this call uses (stamp == epoch) is never - // taken; a referenced one loses its bit as the hand passes it and is taken on the next pass. - let need = misses.len(); - let mut hand = self.ctl[1] as usize; - let mut got = 0usize; - let mut scanned = 0usize; - while got < need && scanned < 3 * n { - // the RT threads read the pre-iteration state, then write - let mut cand = [false; RT]; - let mut mine = [false; RT]; - for t in 0..RT { - let j = (hand + t) % n; - mine[t] = self.slot_stamp[j] == epoch; - cand[t] = !mine[t] && (self.slot_block[j] < 0 || self.slot_ref[j] == 0); - } - let want = need - got; - let mut rank = [0usize; RT]; - let mut total = 0usize; - for t in 0..RT { - rank[t] = total; - total += usize::from(cand[t]); - } - let mut cut = RT; - for t in 0..RT { - if cand[t] && rank[t] + 1 == want { - cut = t + 1; // the hand stops just past the last slot taken - } - } - for t in 0..RT { - let j = (hand + t) % n; - if cand[t] && rank[t] < want { - self.miss_slot[got + rank[t]] = j as i32; - self.slot_stamp[j] = epoch; // taken: a sweep that wraps around must not take it twice - } else if t < cut && !mine[t] { - self.slot_ref[j] = 0; - } - } - got += total.min(want); - hand = (hand + cut) % n; - scanned += RT; - } - // 3. re-point the table; the copy kernel fills the slots - let placed = got.min(need); - for k in 0..need { - let b = self.miss_block[k] as usize; - if k >= placed { - self.page_table[b] = -1; // overflow: never happens with a legal n_slots - continue; - } - let sl = self.miss_slot[k] as usize; - let old = self.slot_block[sl]; - if old >= 0 { - self.page_table[old as usize] = -1; - } - self.slot_block[sl] = b as i32; - self.slot_stamp[sl] = epoch; - self.slot_ref[sl] = 1; - self.page_table[b] = sl as i32; - } - self.ctl[0] = epoch; - self.ctl[1] = hand as i32; - self.ctl[2] = placed as i32; - if placed < need { - self.ctl[3] = 1; - } - self.add_u64(4, placed as u64); - self.add_u64(6, lookups as u64); - self.add_u64(8, 1); - Ok(ResolveReport { epoch, hand: hand as i32, misses: need, placed, lookups }) - } - - /// The map inverts itself: every resident block names a slot that names it back, and every occupied slot is - /// in the table (the invariant `kv_stream_parity.cpp` checks after every call). - pub fn is_consistent(&self) -> bool { - let n = self.n_slots() as i32; - for (b, &sl) in self.page_table.iter().enumerate() { - if sl < -1 || sl >= n || (sl >= 0 && self.slot_block[sl as usize] != b as i32) { - return false; - } - } - self.slot_block - .iter() - .enumerate() - .all(|(sl, &b)| b < 0 || self.page_table.get(b as usize) == Some(&(sl as i32))) - } - - pub fn resident_blocks(&self) -> usize { - self.page_table.iter().filter(|s| **s >= 0).count() - } - - /// `copy_kernel`: the first `ctl[2]` missed blocks are copied from the host copy into their slots, run by - /// run. `slots` is the VRAM pool bundle, `host` the identity-layout copy. - pub fn copy_missed(&self, slots: &mut PoolSet, host: &PoolSet, s: &QsaShapes, fmt: StreamFormat) { - let need = self.ctl[2] as usize; - for (name, len) in stream_runs(s, fmt) { - let len = len as usize; - let src = host.array(name).expect("host array"); - let dst = slots.array_mut(name).expect("slot array"); - for k in 0..need { - let (b, sl) = (self.miss_block[k] as usize, self.miss_slot[k] as usize); - dst[sl * len..(sl + 1) * len].copy_from_slice(&src[b * len..(b + 1) * len]); - } - } - } -} - -/// `kv_ring_table`: the static ring `block -> block % n_slots`. -pub fn ring_table(n_blocks: usize, n_slots: usize) -> Vec { - (0..n_blocks).map(|i| (i % n_slots) as i32).collect() -} - -/// `kv_ring_restore`: blocks `[b0, b1)` of the host copy into the ring slots `b % n_slots`, in runs up to the -/// ring's end (the Original issues one copy per run per array). -pub fn ring_restore(slots: &mut PoolSet, host: &PoolSet, s: &QsaShapes, fmt: StreamFormat, b0: usize, b1: usize, n_slots: usize) { - for (name, len) in stream_runs(s, fmt) { - let len = len as usize; - let src = host.array(name).expect("host array"); - let dst = slots.array_mut(name).expect("slot array"); - let mut b = b0; - while b < b1 { - let sl = b % n_slots; - let run = (b1 - b).min(n_slots - sl); - dst[sl * len..(sl + run) * len].copy_from_slice(&src[b * len..(b + run) * len]); - b += run; - } - } -} - -/// `kv_stage_from_host`: the first `n_blocks` blocks of the host copy into an identity-layout staging pool. -pub fn stage_from_host(stage: &mut PoolSet, host: &PoolSet, s: &QsaShapes, fmt: StreamFormat, n_blocks: usize) { - for (name, len) in stream_runs(s, fmt) { - let len = len as usize; - let src = host.array(name).expect("host array"); - let dst = stage.array_mut(name).expect("stage array"); - dst[..n_blocks * len].copy_from_slice(&src[..n_blocks * len]); - } -} - #[cfg(test)] mod tests; + +mod map_bytes; +#[allow(unused_imports)] +pub use map_bytes::*; +mod impl_streammap; +#[allow(unused_imports)] +pub use impl_streammap::*; diff --git a/crates/experimental-ref/src/kv_stream/impl_streammap.rs b/crates/experimental-ref/src/kv_stream/impl_streammap.rs new file mode 100644 index 00000000..55e57a5f --- /dev/null +++ b/crates/experimental-ref/src/kv_stream/impl_streammap.rs @@ -0,0 +1,233 @@ +//! Moved out of the parent module by STRA-338: impl StreamMap, fn ring_table, fn ring_restore, fn stage_from_host. + +#[allow(unused_imports)] +use super::*; + + +impl StreamMap { + /// `kv_stream_reset`: every block evicted, every slot free, counters zero. + pub fn new(n_blocks: usize, n_slots: usize) -> Self { + Self { + page_table: vec![-1; n_blocks], + slot_block: vec![-1; n_slots], + slot_stamp: vec![-1; n_slots], + slot_ref: vec![0; n_slots], + ctl: [0; CTL_INTS], + miss_block: vec![0; n_slots], + miss_slot: vec![0; n_slots], + } + } + + pub fn n_slots(&self) -> usize { + self.slot_block.len() + } + + pub fn reset(&mut self) { + *self = Self::new(self.page_table.len(), self.n_slots()); + } + + /// `kv_stream_counters` (the u64 counters sit at ctl[4..10]). + pub fn counters(&self) -> Counters { + let u = |i: usize| u64::from(self.ctl[i] as u32) | (u64::from(self.ctl[i + 1] as u32) << 32); + Counters { misses: u(4), lookups: u(6), calls: u(8), overflow: self.ctl[3] != 0 } + } + + pub(super) fn add_u64(&mut self, i: usize, v: u64) { + let cur = u64::from(self.ctl[i] as u32) | (u64::from(self.ctl[i + 1] as u32) << 32); + let n = cur.wrapping_add(v); + self.ctl[i] = n as u32 as i32; + self.ctl[i + 1] = (n >> 32) as u32 as i32; + } + + /// One `resolve_kernel` call. `ids` is `[n_q][cap]` ascending cell ids, the width of query `q` is + /// `steps[q * 4 + 3]`. + pub fn resolve( + &mut self, + ids: &[i32], + steps: &[i32], + n_q: usize, + cap: usize, + page_size: i32, + order: &MissOrder, + ) -> Result { + let n = self.n_slots(); + if n < RT { + return Err(StreamError::TooFewSlots); + } + let epoch = self.ctl[0] + 1; + // 1. hits take this epoch and their reference bit; a missing block is claimed exactly once (-1 -> -2) + let mut lookups = 0usize; + let mut misses: Vec = Vec::new(); + for q in 0..n_q { + let width = steps[q * 4 + 3] as usize; + let qi = &ids[q * cap..q * cap + cap]; + for i in 0..width { + let b = qi[i] / page_size; + if i > 0 && qi[i - 1] / page_size == b { + continue; // ids are ascending: one lookup per block + } + lookups += 1; + let bu = usize::try_from(b).map_err(|_| StreamError::BlockOutOfRange)?; + let sl = *self.page_table.get(bu).ok_or(StreamError::BlockOutOfRange)?; + if sl >= 0 { + self.slot_stamp[sl as usize] = epoch; + self.slot_ref[sl as usize] = 1; + } else if sl == -1 { + self.page_table[bu] = -2; + misses.push(b); + } + } + } + if misses.len() > n { + return Err(StreamError::CallTooLarge); + } + if let MissOrder::Observed(o) = order { + let mut a = o.clone(); + let mut b = misses.clone(); + a.sort_unstable(); + b.sort_unstable(); + if a != b { + return Err(StreamError::BadMissOrder); + } + misses = o.clone(); + } + for (k, b) in misses.iter().enumerate() { + self.miss_block[k] = *b; + } + // 2. one victim per miss: a clock sweep from the hand. A slot this call uses (stamp == epoch) is never + // taken; a referenced one loses its bit as the hand passes it and is taken on the next pass. + let need = misses.len(); + let mut hand = self.ctl[1] as usize; + let mut got = 0usize; + let mut scanned = 0usize; + while got < need && scanned < 3 * n { + // the RT threads read the pre-iteration state, then write + let mut cand = [false; RT]; + let mut mine = [false; RT]; + for t in 0..RT { + let j = (hand + t) % n; + mine[t] = self.slot_stamp[j] == epoch; + cand[t] = !mine[t] && (self.slot_block[j] < 0 || self.slot_ref[j] == 0); + } + let want = need - got; + let mut rank = [0usize; RT]; + let mut total = 0usize; + for t in 0..RT { + rank[t] = total; + total += usize::from(cand[t]); + } + let mut cut = RT; + for t in 0..RT { + if cand[t] && rank[t] + 1 == want { + cut = t + 1; // the hand stops just past the last slot taken + } + } + for t in 0..RT { + let j = (hand + t) % n; + if cand[t] && rank[t] < want { + self.miss_slot[got + rank[t]] = j as i32; + self.slot_stamp[j] = epoch; // taken: a sweep that wraps around must not take it twice + } else if t < cut && !mine[t] { + self.slot_ref[j] = 0; + } + } + got += total.min(want); + hand = (hand + cut) % n; + scanned += RT; + } + // 3. re-point the table; the copy kernel fills the slots + let placed = got.min(need); + for k in 0..need { + let b = self.miss_block[k] as usize; + if k >= placed { + self.page_table[b] = -1; // overflow: never happens with a legal n_slots + continue; + } + let sl = self.miss_slot[k] as usize; + let old = self.slot_block[sl]; + if old >= 0 { + self.page_table[old as usize] = -1; + } + self.slot_block[sl] = b as i32; + self.slot_stamp[sl] = epoch; + self.slot_ref[sl] = 1; + self.page_table[b] = sl as i32; + } + self.ctl[0] = epoch; + self.ctl[1] = hand as i32; + self.ctl[2] = placed as i32; + if placed < need { + self.ctl[3] = 1; + } + self.add_u64(4, placed as u64); + self.add_u64(6, lookups as u64); + self.add_u64(8, 1); + Ok(ResolveReport { epoch, hand: hand as i32, misses: need, placed, lookups }) + } + + /// The map inverts itself: every resident block names a slot that names it back, and every occupied slot is + /// in the table (the invariant `kv_stream_parity.cpp` checks after every call). + pub fn is_consistent(&self) -> bool { + let n = self.n_slots() as i32; + for (b, &sl) in self.page_table.iter().enumerate() { + if sl < -1 || sl >= n || (sl >= 0 && self.slot_block[sl as usize] != b as i32) { + return false; + } + } + self.slot_block + .iter() + .enumerate() + .all(|(sl, &b)| b < 0 || self.page_table.get(b as usize) == Some(&(sl as i32))) + } + + pub fn resident_blocks(&self) -> usize { + self.page_table.iter().filter(|s| **s >= 0).count() + } + + /// `copy_kernel`: the first `ctl[2]` missed blocks are copied from the host copy into their slots, run by + /// run. `slots` is the VRAM pool bundle, `host` the identity-layout copy. + pub fn copy_missed(&self, slots: &mut PoolSet, host: &PoolSet, s: &QsaShapes, fmt: StreamFormat) { + let need = self.ctl[2] as usize; + for (name, len) in stream_runs(s, fmt) { + let len = len as usize; + let src = host.array(name).expect("host array"); + let dst = slots.array_mut(name).expect("slot array"); + for k in 0..need { + let (b, sl) = (self.miss_block[k] as usize, self.miss_slot[k] as usize); + dst[sl * len..(sl + 1) * len].copy_from_slice(&src[b * len..(b + 1) * len]); + } + } + } +} + +/// `kv_ring_table`: the static ring `block -> block % n_slots`. +pub fn ring_table(n_blocks: usize, n_slots: usize) -> Vec { + (0..n_blocks).map(|i| (i % n_slots) as i32).collect() +} + +/// `kv_ring_restore`: blocks `[b0, b1)` of the host copy into the ring slots `b % n_slots`, in runs up to the +/// ring's end (the Original issues one copy per run per array). +pub fn ring_restore(slots: &mut PoolSet, host: &PoolSet, s: &QsaShapes, fmt: StreamFormat, b0: usize, b1: usize, n_slots: usize) { + for (name, len) in stream_runs(s, fmt) { + let len = len as usize; + let src = host.array(name).expect("host array"); + let dst = slots.array_mut(name).expect("slot array"); + let mut b = b0; + while b < b1 { + let sl = b % n_slots; + let run = (b1 - b).min(n_slots - sl); + dst[sl * len..(sl + run) * len].copy_from_slice(&src[b * len..(b + run) * len]); + b += run; + } + } +} + +/// `kv_stage_from_host`: the first `n_blocks` blocks of the host copy into an identity-layout staging pool. +pub fn stage_from_host(stage: &mut PoolSet, host: &PoolSet, s: &QsaShapes, fmt: StreamFormat, n_blocks: usize) { + for (name, len) in stream_runs(s, fmt) { + let len = len as usize; + let src = host.array(name).expect("host array"); + let dst = stage.array_mut(name).expect("stage array"); + dst[..n_blocks * len].copy_from_slice(&src[..n_blocks * len]); + } +} diff --git a/crates/experimental-ref/src/kv_stream/map_bytes.rs b/crates/experimental-ref/src/kv_stream/map_bytes.rs new file mode 100644 index 00000000..505e741f --- /dev/null +++ b/crates/experimental-ref/src/kv_stream/map_bytes.rs @@ -0,0 +1,94 @@ +//! Moved out of the parent module by STRA-338: fn map_bytes, fn kv_plan, fn align16, fn qsa_state_bytes, fn host_copy_bytes, fn check_resolve. + +#[allow(unused_imports)] +use super::*; + + +/// `kv_stream_map_bytes`: five per-slot int arrays plus the control block. +pub const fn map_bytes(n_slots: u64) -> u64 { + n_slots * 4 * 5 + CTL_INTS as u64 * 4 +} + +/// `kv_plan` of `layer.cpp`. `ring_cells < 0` forces a fully resident state, `> 0` is the drafter's ring. +pub fn kv_plan(s: &QsaShapes, max_cells: i64, ring_cells: i64, kv_resident: i64, sw: PlanSwitches) -> KvPlan { + let ps = s.page_size; + let pages = (max_cells + ps - 1) / ps; + let mut p = KvPlan { mode: StreamMode::Resident, pages, slots: pages, pooled_rows: max_cells / s.idx_block + 2 }; + if kv_resident <= 0 || ring_cells < 0 { + return p; + } + if if ring_cells > 0 { sw.ring_off } else { sw.main_off } { + return p; + } + if ring_cells > 0 { + let r = (ring_cells + ps - 1) / ps; + if r < pages { + p.mode = StreamMode::Ring; + p.slots = r; + p.pooled_rows = 2; // the drafter has no indexer + } + } else { + let r = (kv_resident.max(KV_RESIDENT_MIN) + ps - 1) / ps; + if r < pages { + p.mode = StreamMode::Streamed; + p.slots = r; + } + } + p +} + +pub(super) fn align16(n: u64) -> u64 { + (n + 15) & !15 +} + +/// `qsa_state_bytes(g, max_cells, with_rope, ring_cells)` of one QSA layer for `format`. `ring` selects the +/// drafter's state (`ring_cells > 0`): K8V4 does not apply to it (the drafter is plain INT8), the other globals do. +pub fn qsa_state_bytes( + s: &QsaShapes, + format: KvFormat, + max_cells: i64, + with_rope: bool, + ring_cells: i64, + kv_resident: i64, + sw: PlanSwitches, +) -> u64 { + let p = kv_plan(s, max_cells, ring_cells, kv_resident, sw); + // g_kv_hybrid && ring_cells <= 0 selects the hybrid pool; a ring state under k8v4 is INT8 (mtp.cpp) + let pool_format = if format == KvFormat::K8V4 && ring_cells > 0 { KvFormat::Int8 } else { format }; + let mut n = kv_pool_bytes(pool_format, s, p.slots as u64) + 4 * 16; + n += p.pages as u64 * 4; // page_table + if p.mode == StreamMode::Streamed { + n += map_bytes(p.slots as u64) + 6 * 16; // the residency map + } + n += (s.idx_block as u64 - 1) * s.idx_dim as u64 * 4; // tail + n += s.idx_dim as u64 * 4; // dead + n += p.pooled_rows as u64 * s.idx_dim as u64 * 4; // pooled + n += 16; // block_pos + if with_rope { + n += max_cells as u64 * (s.n_rot as u64 / 2) * 4 * 2; // cos + sin tables + } + n += STEP_BYTES + 16; // counts and aligned attention status + n += s.n_head as u64 * 4; // pos_dev + align16(n) + 256 +} + +/// Pinned host bytes of one streamed or ring state's copy (`pages * kv_block_bytes + 4 * 256`). +pub fn host_copy_bytes(s: &QsaShapes, format: KvFormat, pages: i64) -> Option { + let sf = StreamFormat::of(format)?; + Some(pages as u64 * kv_block_bytes(s, sf) + 4 * 256) +} + +/// The host guards of `kv_stream_resolve`. +pub fn check_resolve(s: &QsaShapes, n_slots: i64, n_q: i64, cap: i64) -> Result<(), StreamError> { + if s.n_head_kv * s.page_size * (s.head_dim / crate::kv_q8::KV_Q8_GROUP as i64) * 2 % 16 != 0 { + return Err(StreamError::ScaleRunAlignment); + } + if n_slots < RT as i64 { + return Err(StreamError::TooFewSlots); + } + // n_slots "must hold the distinct blocks of one call (n_q x (cap / page_size + 2))" + if n_slots < n_q * (cap / s.page_size + 2) { + return Err(StreamError::CallTooLarge); + } + Ok(()) +} diff --git a/crates/gateway-text/src/prompt.rs b/crates/gateway-text/src/prompt.rs index a8531a90..e93fd180 100644 --- a/crates/gateway-text/src/prompt.rs +++ b/crates/gateway-text/src/prompt.rs @@ -48,351 +48,6 @@ pub enum Json { Object(Vec<(String, Json)>), } -impl Json { - pub fn object(fields: [(&str, Json); N]) -> Self { - Self::Object(fields.into_iter().map(|(k, v)| (k.to_owned(), v)).collect()) - } - - pub fn str(value: &str) -> Self { - Self::String(value.to_owned()) - } - - pub fn get(&self, key: &str) -> Option<&Json> { - match self { - Self::Object(fields) => fields.iter().find(|(k, _)| k == key).map(|(_, v)| v), - _ => None, - } - } - - /// From a `serde_json::Value`: keys come out in the order the value holds them (insertion order with `preserve_order`, - /// which this crate declares; sorted otherwise). - pub fn from_value(value: &Plain) -> Self { - match value { - Plain::Null => Self::Null, - Plain::Bool(b) => Self::Bool(*b), - Plain::Number(n) => Self::Number(n.clone()), - Plain::String(s) => Self::String(s.clone()), - Plain::Array(items) => Self::Array(items.iter().map(Self::from_value).collect()), - Plain::Object(fields) => Self::Object( - fields - .iter() - .map(|(k, v)| (k.clone(), Self::from_value(v))) - .collect(), - ), - } - } - - /// Like [`Json::from_value`], but every object that has a `"type"` key is ordered the way JSON Schema is - /// conventionally written (see [`schema_order`]). It was written for a `serde_json::Value` that had sorted the client's - /// keys away; the value now keeps them, so this only differs from the client's order for a schema object that was not - /// written in that convention (none of the 281 schemas in the repository's fixtures: Codex, Claude Code and the tool - /// corpus). Objects without a `"type"` (`properties`, `definitions`) keep the client's order. - pub fn from_schema_value(value: &Plain) -> Self { - match value { - Plain::Array(items) => Self::Array(items.iter().map(Self::from_schema_value).collect()), - Plain::Object(fields) => { - let mut keys: Vec<&String> = fields.keys().collect(); - if fields.contains_key("type") { - keys.sort_by_key(|key| (schema_order(key), key.as_str())); - } - Self::Object( - keys.into_iter() - .map(|k| (k.clone(), Self::from_schema_value(&fields[k]))) - .collect(), - ) - } - other => Self::from_value(other), - } - } -} - -/// Position of a JSON Schema keyword in the conventional writing order. -pub fn schema_order(key: &str) -> u8 { - match key { - "type" => 0, - "properties" => 1, - "required" => 2, - "items" => 3, - "enum" => 4, - "description" => 5, - "additionalProperties" => 6, - _ => 7, - } -} - -impl Serialize for Json { - fn serialize(&self, serializer: S) -> Result { - match self { - Self::Null => serializer.serialize_unit(), - Self::Bool(b) => serializer.serialize_bool(*b), - Self::Number(n) => n.serialize(serializer), - Self::String(s) => serializer.serialize_str(s), - Self::Array(items) => { - let mut seq = serializer.serialize_seq(Some(items.len()))?; - for item in items { - seq.serialize_element(item)?; - } - seq.end() - } - Self::Object(fields) => { - let mut map = serializer.serialize_map(Some(fields.len()))?; - for (k, v) in fields { - map.serialize_entry(k, v)?; - } - map.end() - } - } - } -} - -impl<'de> Deserialize<'de> for Json { - fn deserialize>(deserializer: D) -> Result { - struct V; - impl<'de> Visitor<'de> for V { - type Value = Json; - - fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - f.write_str("any JSON value") - } - - fn visit_unit(self) -> Result { - Ok(Json::Null) - } - - fn visit_none(self) -> Result { - Ok(Json::Null) - } - - fn visit_some>(self, d: D) -> Result { - Json::deserialize(d) - } - - fn visit_bool(self, v: bool) -> Result { - Ok(Json::Bool(v)) - } - - fn visit_i64(self, v: i64) -> Result { - Ok(Json::Number(v.into())) - } - - fn visit_u64(self, v: u64) -> Result { - Ok(Json::Number(v.into())) - } - - fn visit_f64(self, v: f64) -> Result { - serde_json::Number::from_f64(v) - .map(Json::Number) - .ok_or_else(|| E::custom("non-finite number")) - } - - fn visit_str(self, v: &str) -> Result { - Ok(Json::String(v.to_owned())) - } - - fn visit_string(self, v: String) -> Result { - Ok(Json::String(v)) - } - - fn visit_seq>(self, mut seq: A) -> Result { - let mut items = Vec::new(); - while let Some(item) = seq.next_element()? { - items.push(item); - } - Ok(Json::Array(items)) - } - - fn visit_map>(self, mut map: A) -> Result { - let mut fields: Vec<(String, Json)> = Vec::new(); - while let Some((key, value)) = map.next_entry::()? { - // a repeated key keeps its first position and takes the last value, as a Python dict does - match fields.iter_mut().find(|(k, _)| *k == key) { - Some(slot) => slot.1 = value, - None => fields.push((key, value)), - } - } - Ok(Json::Object(fields)) - } - } - deserializer.deserialize_any(V) - } -} - -// --------------------------------------------------------------------------------------------------------------- -// Python-compatible filters - -/// `str.isspace()` for one character: Unicode White_Space plus the four separator controls U+001C-U+001F. -fn py_space(c: char) -> bool { - c.is_whitespace() || ('\u{1c}'..='\u{1f}').contains(&c) -} - -/// Jinja's `trim` filter is `str.strip(chars)`. -fn trim(value: Value, chars: Option) -> String { - let text = if value.is_undefined() { - String::new() - } else { - value.to_string() - }; - match chars { - None => text.trim_matches(py_space).to_owned(), - Some(set) => text.trim_matches(|c| set.contains(c)).to_owned(), - } -} - -/// Python's `repr(float)` as `json.dumps` writes it: shortest round-trip digits, exponent form outside 1e-4..1e16. -fn python_float(value: f64) -> String { - if value == 0.0 { - return if value.is_sign_negative() { - "-0.0" - } else { - "0.0" - } - .to_owned(); - } - let scientific = format!("{value:e}"); // shortest digits: "-1.2345e-5" - let (mantissa, exponent) = scientific.split_once('e').expect("exponent"); - let exponent: i32 = exponent.parse().expect("exponent digits"); - let (sign, digits) = match mantissa.strip_prefix('-') { - Some(rest) => ("-", rest), - None => ("", mantissa), - }; - let digits: String = digits.chars().filter(|c| *c != '.').collect(); - if (-4..16).contains(&exponent) { - if exponent >= 0 { - let point = exponent as usize + 1; - if digits.len() <= point { - format!("{sign}{digits}{}.0", "0".repeat(point - digits.len())) - } else { - format!("{sign}{}.{}", &digits[..point], &digits[point..]) - } - } else { - format!("{sign}0.{}{digits}", "0".repeat((-exponent - 1) as usize)) - } - } else { - let mut out = format!("{sign}{}", &digits[..1]); - if digits.len() > 1 { - out.push('.'); - out.push_str(&digits[1..]); - } - format!( - "{out}e{}{:02}", - if exponent < 0 { '-' } else { '+' }, - exponent.abs() - ) - } -} - -fn json_string(text: &str, ensure_ascii: bool, out: &mut String) { - out.push('"'); - for c in text.chars() { - match c { - '"' => out.push_str("\\\""), - '\\' => out.push_str("\\\\"), - '\n' => out.push_str("\\n"), - '\r' => out.push_str("\\r"), - '\t' => out.push_str("\\t"), - '\u{8}' => out.push_str("\\b"), - '\u{c}' => out.push_str("\\f"), - c if (c as u32) < 0x20 => out.push_str(&format!("\\u{:04x}", c as u32)), - c if ensure_ascii && !c.is_ascii() => { - let mut units = [0u16; 2]; - for unit in c.encode_utf16(&mut units) { - out.push_str(&format!("\\u{unit:04x}")); - } - } - c => out.push(c), - } - } - out.push('"'); -} - -fn write_json( - value: &Value, - sort_keys: bool, - ensure_ascii: bool, - out: &mut String, -) -> Result<(), Error> { - match value.kind() { - ValueKind::None => out.push_str("null"), - ValueKind::Bool => out.push_str(if value.is_true() { "true" } else { "false" }), - ValueKind::Number => { - if value.is_integer() { - out.push_str(&value.to_string()); - } else { - let float = f64::try_from(value.clone())?; - if !float.is_finite() { - out.push_str(if float.is_nan() { - "NaN" - } else if float > 0.0 { - "Infinity" - } else { - "-Infinity" - }); - } else { - out.push_str(&python_float(float)); - } - } - } - ValueKind::String => json_string(value.as_str().unwrap_or_default(), ensure_ascii, out), - ValueKind::Seq | ValueKind::Iterable => { - out.push('['); - for (at, item) in value.try_iter()?.enumerate() { - if at > 0 { - out.push_str(", "); - } - write_json(&item, sort_keys, ensure_ascii, out)?; - } - out.push(']'); - } - ValueKind::Map => { - let mut keys: Vec = value.try_iter()?.collect(); - if sort_keys { - keys.sort_by_key(|k| k.to_string()); - } - out.push('{'); - for (at, key) in keys.iter().enumerate() { - if at > 0 { - out.push_str(", "); - } - let Some(name) = key.as_str() else { - return Err(Error::new( - ErrorKind::InvalidOperation, - "tojson keys must be strings", - )); - }; - json_string(name, ensure_ascii, out); - out.push_str(": "); - write_json(&value.get_item(key)?, sort_keys, ensure_ascii, out)?; - } - out.push('}'); - } - other => { - return Err(Error::new( - ErrorKind::InvalidOperation, - format!("Object of type {other:?} is not JSON serializable"), - )); - } - } - Ok(()) -} - -/// The server's `tojson`: `json.dumps(x, ensure_ascii=False, indent=None, separators=None, sort_keys=False)`. -fn tojson(_state: &State, value: Value, kwargs: Kwargs) -> Result { - let ensure_ascii = kwargs.get::>("ensure_ascii")?.unwrap_or(false); - let sort_keys = kwargs.get::>("sort_keys")?.unwrap_or(false); - let indent: Option = kwargs.get("indent")?; - let separators: Option = kwargs.get("separators")?; - kwargs.assert_all_used()?; - if indent.is_some_and(|v| !v.is_none()) || separators.is_some_and(|v| !v.is_none()) { - return Err(Error::new( - ErrorKind::InvalidOperation, - "tojson with indent or separators is not supported by the native renderer", - )); - } - let mut out = String::new(); - write_json(&value, sort_keys, ensure_ascii, &mut out)?; - Ok(out) -} - // --------------------------------------------------------------------------------------------------------------- // the renderer @@ -406,150 +61,10 @@ pub struct ChatInput<'a> { pub kwargs: Vec<(&'a str, Json)>, } -/// `STRATA_KEEP_EMPTY_TURNS=1` renders completed empty assistant turns as before (`ChatTemplate.render`). -fn keep_empty_turns() -> bool { - std::env::var_os("STRATA_KEEP_EMPTY_TURNS").is_some_and(|v| v == "1") -} - -/// `serve/frontend.py` `_text_of`, as far as the emptiness test needs it: the text of a message's content, or the `TypeError` -/// Python raises for a content it cannot iterate (a number or a boolean). A string is itself, a list joins the `text` of its text -/// parts (type `text`, `input_text` or no type), an object is iterated by key (no part is a dict, so its text is empty). -fn content_text(content: Option<&Json>) -> Result { - match content { - None | Some(Json::Null) | Some(Json::Object(_)) => Ok(String::new()), - Some(Json::String(text)) => Ok(text.clone()), - Some(Json::Array(parts)) => { - let mut text = String::new(); - for part in parts { - let Json::Object(_) = part else { continue }; - let text_part = match part.get("type") { - None | Some(Json::Null) => true, - Some(Json::String(kind)) => kind == "text" || kind == "input_text", - Some(_) => false, - }; - if !text_part { - continue; - } - match part.get("text") { - None => {} - Some(Json::String(piece)) => text.push_str(piece), - Some(_) => { - return Err("TypeError: sequence item: expected str instance".into()); - } - } - } - Ok(text) - } - Some(_) => Err("TypeError: object is not iterable".into()), - } -} - -/// `serve/frontend.py` `_has_image`: a list content with an `image_url`, `input_image` or `image` part. -fn content_has_image(content: Option<&Json>) -> bool { - let Some(Json::Array(parts)) = content else { - return false; - }; - parts.iter().any(|part| { - matches!(part.get("type"), Some(Json::String(t)) if matches!(t.as_str(), "image_url" | "input_image" | "image")) - }) -} - -/// Python truthiness of a JSON value (`not m.get("tool_calls")`). -fn truthy(value: Option<&Json>) -> bool { - match value { - None | Some(Json::Null) | Some(Json::Bool(false)) => false, - Some(Json::Bool(true)) => true, - Some(Json::Number(n)) => n.as_f64().is_none_or(|f| f != 0.0), - Some(Json::String(s)) => !s.is_empty(), - Some(Json::Array(items)) => !items.is_empty(), - Some(Json::Object(fields)) => !fields.is_empty(), - } -} - -/// A completed empty assistant turn: an assistant message with no text (after `str.strip`), no picture and no tool calls. -/// A reasoning content does not keep it. -fn is_empty_assistant_turn(message: &Json) -> Result { - if !matches!(message.get("role"), Some(Json::String(role)) if role == "assistant") { - return Ok(false); - } - let content = message.get("content"); - Ok(content_text(content)?.trim_matches(py_space).is_empty() - && !content_has_image(content) - && !truthy(message.get("tool_calls"))) -} - -/// `ChatTemplate.render` (serve/frontend.py, Strata 0.1.50, #843): "Do not use completed empty assistant turns as examples -/// for the next reply. Keep the final message." The template sees the list without them; `STRATA_KEEP_EMPTY_TURNS=1` keeps them. -fn without_empty_assistant_turns(messages: &[Json]) -> Result, String> { - let mut kept = Vec::with_capacity(messages.len()); - for (index, message) in messages.iter().enumerate() { - if index + 1 == messages.len() || keep_empty_turns() || !is_empty_assistant_turn(message)? { - kept.push(message.clone()); - } - } - Ok(kept) -} - pub struct Renderer { env: Environment<'static>, } -impl Renderer { - /// A template configured like `ChatTemplate`: `trim_blocks`, `lstrip_blocks`, no autoescape, Python string - /// methods, `raise_exception`, `tojson`, `trim`. - pub fn new(source: &str) -> Result { - let mut env = Environment::new(); - env.set_trim_blocks(true); - env.set_lstrip_blocks(true); - env.set_keep_trailing_newline(false); - env.set_auto_escape_callback(|_| minijinja::AutoEscape::None); - env.set_unknown_method_callback(minijinja_contrib::pycompat::unknown_method_callback); - env.add_filter("tojson", tojson); - env.add_filter("trim", trim); - env.add_function( - "raise_exception", - |message: String| -> Result { - Err(Error::new(ErrorKind::InvalidOperation, message)) - }, - ); - env.add_template_owned("chat", source.to_owned()) - .map_err(|e| format!("chat template does not compile: {e:#}"))?; - Ok(Self { env }) - } - - pub fn render(&self, input: &ChatInput<'_>) -> Result { - let mut context: BTreeMap<&str, Value> = BTreeMap::new(); - let messages = without_empty_assistant_turns(input.messages)?; - context.insert("messages", Value::from_serialize(&messages)); - context.insert( - "tools", - input.tools.map_or(Value::from(()), Value::from_serialize), - ); - context.insert( - "add_generation_prompt", - Value::from(input.add_generation_prompt), - ); - for (name, value) in &input.kwargs { - context.insert(name, Value::from_serialize(value)); - } - self.env - .get_template("chat") - .and_then(|template| template.render(&context)) - .map_err(|error| { - error - .detail() - .map_or_else(|| error.to_string(), str::to_owned) - }) - } -} - -/// The compiled pinned template. -pub fn pinned() -> &'static Renderer { - static PINNED: OnceLock = OnceLock::new(); - PINNED - .get_or_init(|| Renderer::new(PINNED_TEMPLATE).expect("the pinned chat template compiles")) -} - // --------------------------------------------------------------------------------------------------------------- // typed entry points @@ -561,17 +76,6 @@ pub enum Role { Assistant, } -impl Role { - fn name(self) -> &'static str { - match self { - Self::System => "system", - Self::Developer => "developer", - Self::User => "user", - Self::Assistant => "assistant", - } - } -} - /// One item of a message that carries pictures (`serve/frontend.py` `_parts_of`): the template renders a text item /// as its text and an image item as `<|vision_start|><|image_pad|><|vision_end|>`, in order. #[derive(Clone, Debug, PartialEq, Eq)] @@ -590,32 +94,6 @@ pub struct Message<'a> { pub parts: Option<&'a [Part]>, } -impl<'a> Message<'a> { - /// A completed empty assistant turn (see [`without_empty_assistant_turns`]): no text after `str.strip`, no picture, and (the - /// typed messages carry none) no tool calls. - fn is_empty_assistant_turn(&self) -> bool { - if self.role != Role::Assistant { - return false; - } - match self.parts { - None => self.content.trim_matches(py_space).is_empty(), - Some(parts) => parts.iter().all(|part| match part { - Part::Text(text) => text.trim_matches(py_space).is_empty(), - Part::Image(_) => false, - }), - } - } - - pub fn text(role: Role, content: &'a str, reasoning: Option<&'a str>) -> Self { - Self { - role, - content, - reasoning, - parts: None, - } - } -} - #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] pub enum Effort { None, @@ -626,257 +104,23 @@ pub enum Effort { XHigh, } -impl Effort { - /// `serve/frontend.py::effort_kwargs`: the template's `enable_thinking` / `reasoning_effort`. - pub fn kwargs(self) -> Vec<(&'static str, Json)> { - match self { - Self::None => vec![("enable_thinking", Json::Bool(false))], - Self::Low => vec![("reasoning_effort", Json::str("low"))], - Self::Medium => vec![("reasoning_effort", Json::str("medium"))], - Self::High => vec![("reasoning_effort", Json::str("high"))], - Self::XHigh => vec![("reasoning_effort", Json::str("xhigh"))], - } - } -} - -pub fn render(messages: &[Message<'_>], effort: Effort) -> Result { - render_with_tools(messages, effort, &[]) -} - -/// Adapt a flat Responses function object to the `{"type": "function", "function": {...}}` form the template -/// prints. Field order is the template-conventional one; the parameter schema keeps [`Json::from_schema_value`] order. -pub fn chat_tool(tool: &Plain) -> Result { - let name = tool - .get("name") - .and_then(Plain::as_str) - .ok_or("tool needs a name")?; - let mut function = vec![("name".to_owned(), Json::str(name))]; - if let Some(description) = tool.get("description").and_then(Plain::as_str) { - function.push(("description".to_owned(), Json::str(description))); - } - if let Some(parameters) = tool.get("parameters") { - function.push(("parameters".to_owned(), Json::from_schema_value(parameters))); - } - if let Some(strict) = tool.get("strict") { - function.push(("strict".to_owned(), Json::from_schema_value(strict))); - } - Ok(Json::object([ - ("type", Json::str("function")), - ("function", Json::Object(function)), - ])) -} - -pub fn render_with_tools( - messages: &[Message<'_>], - effort: Effort, - tools: &[Plain], -) -> Result { - render_with_images(messages, effort, tools).map(|(prompt, _)| prompt) -} - -/// `STRATA_REFERENCE_RENDER=1` sends every prompt through the Jinja template (no native fast path). -fn reference_render() -> bool { - static ON: OnceLock = OnceLock::new(); - *ON.get_or_init(|| std::env::var_os("STRATA_REFERENCE_RENDER").is_some_and(|v| v == "1")) -} - -/// The prompt of a text-only conversation without running the Jinja template over the history. -/// -/// For the pinned template a message after the leading system/developer ones renders to text that depends on that message -/// alone, because `preserve_thinking` is never set (an assistant turn always keeps its `` block): -/// -/// ```text -/// user: <|im_start|>user\n{content|trim}<|im_end|>\n -/// assistant: <|im_start|>assistant\n\n{reasoning|trim}\n\n\n{content|trim}<|im_end|>\n -/// ``` -/// -/// and what comes before them (the tools, the reasoning instruction, the merged system text) depends only on the leading -/// system messages, the tools and the effort, so the template renders just that part, with the history left out. The -/// generation prompt is the template's own closing lines. The result is the template's output byte for byte -/// (`native_render_equals_the_template` renders thousands of random conversations both ways); pictures take the template. -fn render_native( - messages: &[Message<'_>], - effort: Effort, - tools: &[Json], -) -> Result { - let leading = messages - .iter() - .take_while(|message| matches!(message.role, Role::System | Role::Developer)) - .count(); - let object = |message: &Message<'_>| { - let mut fields = vec![ - ("role".to_owned(), Json::str(message.role.name())), - ("content".to_owned(), Json::str(message.content)), - ]; - if let Some(reasoning) = message.reasoning { - fields.push(("reasoning_content".to_owned(), Json::str(reasoning))); - } - Json::Object(fields) - }; - // The template refuses an empty message list, so a conversation without system messages gets a placeholder user turn whose - // exact output is cut off again. - const PLACEHOLDER: &str = "<|im_start|>user\n<|im_end|>\n"; - let head: Vec = if leading == 0 { - vec![Json::object([ - ("role", Json::str("user")), - ("content", Json::str("")), - ])] - } else { - messages[..leading].iter().map(object).collect() - }; - let mut prompt = pinned().render(&ChatInput { - messages: &head, - tools: (!tools.is_empty()).then_some(tools), - add_generation_prompt: false, - kwargs: effort.kwargs(), - })?; - if leading == 0 { - prompt = prompt - .strip_suffix(PLACEHOLDER) - .ok_or("the chat template changed its output for an empty user turn")? - .to_owned(); - } - let rest = &messages[leading..]; - prompt.reserve( - rest.iter() - .map(|m| m.content.len() + m.reasoning.map_or(0, str::len) + 64) - .sum::() - + 64, - ); - for message in rest { - let content = message.content.trim_matches(py_space); - match message.role { - Role::User => { - prompt.push_str("<|im_start|>user\n"); - prompt.push_str(content); - prompt.push_str("<|im_end|>\n"); - } - Role::Assistant => { - prompt.push_str("<|im_start|>assistant\n\n"); - prompt.push_str(message.reasoning.unwrap_or("").trim_matches(py_space)); - prompt.push_str("\n\n\n"); - prompt.push_str(content); - prompt.push_str("<|im_end|>\n"); - } - Role::System | Role::Developer => { - return Err("System message must be at the beginning.".into()); - } - } - } - prompt.push_str("<|im_start|>assistant\n"); - prompt.push_str(if matches!(effort, Effort::None) { - "\n\n\n\n" - } else { - "\n" - }); - Ok(prompt) -} - -/// The typed counterpart of [`without_empty_assistant_turns`]. -fn without_empty_turns<'a>(messages: &[Message<'a>]) -> Vec> { - messages - .iter() - .enumerate() - .filter(|(index, message)| { - index + 1 == messages.len() || keep_empty_turns() || !message.is_empty_assistant_turn() - }) - .map(|(_, message)| *message) - .collect() -} - -/// [`render_with_tools`] and the sources of the pictures the prompt contains, in prompt order (`images_of`). -pub fn render_with_images( - messages: &[Message<'_>], - effort: Effort, - tools: &[Plain], -) -> Result<(String, Vec), String> { - if messages.is_empty() { - return Err("prompt needs a message".into()); - } - // The template never sees a completed empty assistant turn (`without_empty_assistant_turns`); the checks below and the native - // renderer work on the same list. - let kept = without_empty_turns(messages); - let messages = kept.as_slice(); - let first_non_system = messages - .iter() - .position(|message| !matches!(message.role, Role::System | Role::Developer)) - .unwrap_or(messages.len()); - if first_non_system == messages.len() - || messages[first_non_system..] - .iter() - .any(|message| matches!(message.role, Role::System | Role::Developer)) - { - return Err("system and developer messages must be at the beginning".into()); - } - if messages - .last() - .is_none_or(|message| message.role != Role::User) - { - return Err("generation needs a final user message".into()); - } - if !reference_render() && messages.iter().all(|message| message.parts.is_none()) { - let tools = tools.iter().map(chat_tool).collect::, _>>()?; - return render_native(messages, effort, &tools).map(|prompt| (prompt, Vec::new())); - } - render_via_template(messages, effort, tools) -} - -/// The whole conversation through the Jinja template (the reference the native renderer is tested against). -fn render_via_template( - messages: &[Message<'_>], - effort: Effort, - tools: &[Plain], -) -> Result<(String, Vec), String> { - let chat: Vec = messages - .iter() - .map(|message| { - let content = match message.parts { - None => Json::str(message.content), - Some(parts) => Json::Array( - parts - .iter() - .map(|part| match part { - Part::Text(text) => Json::object([ - ("type", Json::str("text")), - ("text", Json::str(text)), - ]), - Part::Image(source) => Json::object([ - ("type", Json::str("image")), - ("source", Json::str(source)), - ]), - }) - .collect(), - ), - }; - let mut fields = vec![ - ("role".to_owned(), Json::str(message.role.name())), - ("content".to_owned(), content), - ]; - if let Some(reasoning) = message.reasoning { - fields.push(("reasoning_content".to_owned(), Json::str(reasoning))); - } - Json::Object(fields) - }) - .collect(); - let images = messages - .iter() - .flat_map(|message| message.parts.unwrap_or(&[])) - .filter_map(|part| match part { - Part::Image(source) => Some(source.clone()), - Part::Text(_) => None, - }) - .collect(); - let tools = tools.iter().map(chat_tool).collect::, _>>()?; - pinned() - .render(&ChatInput { - messages: &chat, - tools: (!tools.is_empty()).then_some(&tools), - add_generation_prompt: true, - kwargs: effort.kwargs(), - }) - .map(|prompt| (prompt, images)) -} - #[cfg(test)] #[path = "prompt/tests.rs"] mod tests; + +#[path = "prompt/impl_json.rs"] +mod impl_json; +#[allow(unused_imports)] +pub use impl_json::*; +#[path = "prompt/json_string.rs"] +mod json_string; +#[allow(unused_imports)] +pub use json_string::*; +#[path = "prompt/impl_renderer.rs"] +mod impl_renderer; +#[allow(unused_imports)] +pub use impl_renderer::*; +#[path = "prompt/without_empty_turns.rs"] +mod without_empty_turns; +#[allow(unused_imports)] +pub use without_empty_turns::*; diff --git a/crates/gateway-text/src/prompt/impl_json.rs b/crates/gateway-text/src/prompt/impl_json.rs new file mode 100644 index 00000000..b149659c --- /dev/null +++ b/crates/gateway-text/src/prompt/impl_json.rs @@ -0,0 +1,237 @@ +//! Moved out of the parent module by STRA-338: impl Json, fn schema_order, impl Serialize_for_Json, impl Deserialize_for_Json, fn py_space, fn trim .... + +#[allow(unused_imports)] +use super::*; + +impl Json { + pub fn object(fields: [(&str, Json); N]) -> Self { + Self::Object(fields.into_iter().map(|(k, v)| (k.to_owned(), v)).collect()) + } + + pub fn str(value: &str) -> Self { + Self::String(value.to_owned()) + } + + pub fn get(&self, key: &str) -> Option<&Json> { + match self { + Self::Object(fields) => fields.iter().find(|(k, _)| k == key).map(|(_, v)| v), + _ => None, + } + } + + /// From a `serde_json::Value`: keys come out in the order the value holds them (insertion order with `preserve_order`, + /// which this crate declares; sorted otherwise). + pub fn from_value(value: &Plain) -> Self { + match value { + Plain::Null => Self::Null, + Plain::Bool(b) => Self::Bool(*b), + Plain::Number(n) => Self::Number(n.clone()), + Plain::String(s) => Self::String(s.clone()), + Plain::Array(items) => Self::Array(items.iter().map(Self::from_value).collect()), + Plain::Object(fields) => Self::Object( + fields + .iter() + .map(|(k, v)| (k.clone(), Self::from_value(v))) + .collect(), + ), + } + } + + /// Like [`Json::from_value`], but every object that has a `"type"` key is ordered the way JSON Schema is + /// conventionally written (see [`schema_order`]). It was written for a `serde_json::Value` that had sorted the client's + /// keys away; the value now keeps them, so this only differs from the client's order for a schema object that was not + /// written in that convention (none of the 281 schemas in the repository's fixtures: Codex, Claude Code and the tool + /// corpus). Objects without a `"type"` (`properties`, `definitions`) keep the client's order. + pub fn from_schema_value(value: &Plain) -> Self { + match value { + Plain::Array(items) => Self::Array(items.iter().map(Self::from_schema_value).collect()), + Plain::Object(fields) => { + let mut keys: Vec<&String> = fields.keys().collect(); + if fields.contains_key("type") { + keys.sort_by_key(|key| (schema_order(key), key.as_str())); + } + Self::Object( + keys.into_iter() + .map(|k| (k.clone(), Self::from_schema_value(&fields[k]))) + .collect(), + ) + } + other => Self::from_value(other), + } + } +} + +/// Position of a JSON Schema keyword in the conventional writing order. +pub fn schema_order(key: &str) -> u8 { + match key { + "type" => 0, + "properties" => 1, + "required" => 2, + "items" => 3, + "enum" => 4, + "description" => 5, + "additionalProperties" => 6, + _ => 7, + } +} + +impl Serialize for Json { + fn serialize(&self, serializer: S) -> Result { + match self { + Self::Null => serializer.serialize_unit(), + Self::Bool(b) => serializer.serialize_bool(*b), + Self::Number(n) => n.serialize(serializer), + Self::String(s) => serializer.serialize_str(s), + Self::Array(items) => { + let mut seq = serializer.serialize_seq(Some(items.len()))?; + for item in items { + seq.serialize_element(item)?; + } + seq.end() + } + Self::Object(fields) => { + let mut map = serializer.serialize_map(Some(fields.len()))?; + for (k, v) in fields { + map.serialize_entry(k, v)?; + } + map.end() + } + } + } +} + +impl<'de> Deserialize<'de> for Json { + fn deserialize>(deserializer: D) -> Result { + struct V; + impl<'de> Visitor<'de> for V { + type Value = Json; + + fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str("any JSON value") + } + + fn visit_unit(self) -> Result { + Ok(Json::Null) + } + + fn visit_none(self) -> Result { + Ok(Json::Null) + } + + fn visit_some>(self, d: D) -> Result { + Json::deserialize(d) + } + + fn visit_bool(self, v: bool) -> Result { + Ok(Json::Bool(v)) + } + + fn visit_i64(self, v: i64) -> Result { + Ok(Json::Number(v.into())) + } + + fn visit_u64(self, v: u64) -> Result { + Ok(Json::Number(v.into())) + } + + fn visit_f64(self, v: f64) -> Result { + serde_json::Number::from_f64(v) + .map(Json::Number) + .ok_or_else(|| E::custom("non-finite number")) + } + + fn visit_str(self, v: &str) -> Result { + Ok(Json::String(v.to_owned())) + } + + fn visit_string(self, v: String) -> Result { + Ok(Json::String(v)) + } + + fn visit_seq>(self, mut seq: A) -> Result { + let mut items = Vec::new(); + while let Some(item) = seq.next_element()? { + items.push(item); + } + Ok(Json::Array(items)) + } + + fn visit_map>(self, mut map: A) -> Result { + let mut fields: Vec<(String, Json)> = Vec::new(); + while let Some((key, value)) = map.next_entry::()? { + // a repeated key keeps its first position and takes the last value, as a Python dict does + match fields.iter_mut().find(|(k, _)| *k == key) { + Some(slot) => slot.1 = value, + None => fields.push((key, value)), + } + } + Ok(Json::Object(fields)) + } + } + deserializer.deserialize_any(V) + } +} + +// --------------------------------------------------------------------------------------------------------------- +// Python-compatible filters + +/// `str.isspace()` for one character: Unicode White_Space plus the four separator controls U+001C-U+001F. +pub(super) fn py_space(c: char) -> bool { + c.is_whitespace() || ('\u{1c}'..='\u{1f}').contains(&c) +} + +/// Jinja's `trim` filter is `str.strip(chars)`. +pub(super) fn trim(value: Value, chars: Option) -> String { + let text = if value.is_undefined() { + String::new() + } else { + value.to_string() + }; + match chars { + None => text.trim_matches(py_space).to_owned(), + Some(set) => text.trim_matches(|c| set.contains(c)).to_owned(), + } +} + +/// Python's `repr(float)` as `json.dumps` writes it: shortest round-trip digits, exponent form outside 1e-4..1e16. +pub(super) fn python_float(value: f64) -> String { + if value == 0.0 { + return if value.is_sign_negative() { + "-0.0" + } else { + "0.0" + } + .to_owned(); + } + let scientific = format!("{value:e}"); // shortest digits: "-1.2345e-5" + let (mantissa, exponent) = scientific.split_once('e').expect("exponent"); + let exponent: i32 = exponent.parse().expect("exponent digits"); + let (sign, digits) = match mantissa.strip_prefix('-') { + Some(rest) => ("-", rest), + None => ("", mantissa), + }; + let digits: String = digits.chars().filter(|c| *c != '.').collect(); + if (-4..16).contains(&exponent) { + if exponent >= 0 { + let point = exponent as usize + 1; + if digits.len() <= point { + format!("{sign}{digits}{}.0", "0".repeat(point - digits.len())) + } else { + format!("{sign}{}.{}", &digits[..point], &digits[point..]) + } + } else { + format!("{sign}0.{}{digits}", "0".repeat((-exponent - 1) as usize)) + } + } else { + let mut out = format!("{sign}{}", &digits[..1]); + if digits.len() > 1 { + out.push('.'); + out.push_str(&digits[1..]); + } + format!( + "{out}e{}{:02}", + if exponent < 0 { '-' } else { '+' }, + exponent.abs() + ) + } +} diff --git a/crates/gateway-text/src/prompt/impl_renderer.rs b/crates/gateway-text/src/prompt/impl_renderer.rs new file mode 100644 index 00000000..2093fea9 --- /dev/null +++ b/crates/gateway-text/src/prompt/impl_renderer.rs @@ -0,0 +1,243 @@ +//! Moved out of the parent module by STRA-338: impl Renderer, fn pinned, impl Role, impl Message, impl Effort, fn render .... + +#[allow(unused_imports)] +use super::*; + +impl Renderer { + /// A template configured like `ChatTemplate`: `trim_blocks`, `lstrip_blocks`, no autoescape, Python string + /// methods, `raise_exception`, `tojson`, `trim`. + pub fn new(source: &str) -> Result { + let mut env = Environment::new(); + env.set_trim_blocks(true); + env.set_lstrip_blocks(true); + env.set_keep_trailing_newline(false); + env.set_auto_escape_callback(|_| minijinja::AutoEscape::None); + env.set_unknown_method_callback(minijinja_contrib::pycompat::unknown_method_callback); + env.add_filter("tojson", tojson); + env.add_filter("trim", trim); + env.add_function( + "raise_exception", + |message: String| -> Result { + Err(Error::new(ErrorKind::InvalidOperation, message)) + }, + ); + env.add_template_owned("chat", source.to_owned()) + .map_err(|e| format!("chat template does not compile: {e:#}"))?; + Ok(Self { env }) + } + + pub fn render(&self, input: &ChatInput<'_>) -> Result { + let mut context: BTreeMap<&str, Value> = BTreeMap::new(); + let messages = without_empty_assistant_turns(input.messages)?; + context.insert("messages", Value::from_serialize(&messages)); + context.insert( + "tools", + input.tools.map_or(Value::from(()), Value::from_serialize), + ); + context.insert( + "add_generation_prompt", + Value::from(input.add_generation_prompt), + ); + for (name, value) in &input.kwargs { + context.insert(name, Value::from_serialize(value)); + } + self.env + .get_template("chat") + .and_then(|template| template.render(&context)) + .map_err(|error| { + error + .detail() + .map_or_else(|| error.to_string(), str::to_owned) + }) + } +} + +/// The compiled pinned template. +pub fn pinned() -> &'static Renderer { + static PINNED: OnceLock = OnceLock::new(); + PINNED + .get_or_init(|| Renderer::new(PINNED_TEMPLATE).expect("the pinned chat template compiles")) +} + +impl Role { + pub(super) fn name(self) -> &'static str { + match self { + Self::System => "system", + Self::Developer => "developer", + Self::User => "user", + Self::Assistant => "assistant", + } + } +} + +impl<'a> Message<'a> { + /// A completed empty assistant turn (see [`without_empty_assistant_turns`]): no text after `str.strip`, no picture, and (the + /// typed messages carry none) no tool calls. + pub(super) fn is_empty_assistant_turn(&self) -> bool { + if self.role != Role::Assistant { + return false; + } + match self.parts { + None => self.content.trim_matches(py_space).is_empty(), + Some(parts) => parts.iter().all(|part| match part { + Part::Text(text) => text.trim_matches(py_space).is_empty(), + Part::Image(_) => false, + }), + } + } + + pub fn text(role: Role, content: &'a str, reasoning: Option<&'a str>) -> Self { + Self { + role, + content, + reasoning, + parts: None, + } + } +} + +impl Effort { + /// `serve/frontend.py::effort_kwargs`: the template's `enable_thinking` / `reasoning_effort`. + pub fn kwargs(self) -> Vec<(&'static str, Json)> { + match self { + Self::None => vec![("enable_thinking", Json::Bool(false))], + Self::Low => vec![("reasoning_effort", Json::str("low"))], + Self::Medium => vec![("reasoning_effort", Json::str("medium"))], + Self::High => vec![("reasoning_effort", Json::str("high"))], + Self::XHigh => vec![("reasoning_effort", Json::str("xhigh"))], + } + } +} + +pub fn render(messages: &[Message<'_>], effort: Effort) -> Result { + render_with_tools(messages, effort, &[]) +} + +/// Adapt a flat Responses function object to the `{"type": "function", "function": {...}}` form the template +/// prints. Field order is the template-conventional one; the parameter schema keeps [`Json::from_schema_value`] order. +pub fn chat_tool(tool: &Plain) -> Result { + let name = tool + .get("name") + .and_then(Plain::as_str) + .ok_or("tool needs a name")?; + let mut function = vec![("name".to_owned(), Json::str(name))]; + if let Some(description) = tool.get("description").and_then(Plain::as_str) { + function.push(("description".to_owned(), Json::str(description))); + } + if let Some(parameters) = tool.get("parameters") { + function.push(("parameters".to_owned(), Json::from_schema_value(parameters))); + } + if let Some(strict) = tool.get("strict") { + function.push(("strict".to_owned(), Json::from_schema_value(strict))); + } + Ok(Json::object([ + ("type", Json::str("function")), + ("function", Json::Object(function)), + ])) +} + +pub fn render_with_tools( + messages: &[Message<'_>], + effort: Effort, + tools: &[Plain], +) -> Result { + render_with_images(messages, effort, tools).map(|(prompt, _)| prompt) +} + +/// `STRATA_REFERENCE_RENDER=1` sends every prompt through the Jinja template (no native fast path). +pub(super) fn reference_render() -> bool { + static ON: OnceLock = OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("STRATA_REFERENCE_RENDER").is_some_and(|v| v == "1")) +} + +/// The prompt of a text-only conversation without running the Jinja template over the history. +/// +/// For the pinned template a message after the leading system/developer ones renders to text that depends on that message +/// alone, because `preserve_thinking` is never set (an assistant turn always keeps its `` block): +/// +/// ```text +/// user: <|im_start|>user\n{content|trim}<|im_end|>\n +/// assistant: <|im_start|>assistant\n\n{reasoning|trim}\n\n\n{content|trim}<|im_end|>\n +/// ``` +/// +/// and what comes before them (the tools, the reasoning instruction, the merged system text) depends only on the leading +/// system messages, the tools and the effort, so the template renders just that part, with the history left out. The +/// generation prompt is the template's own closing lines. The result is the template's output byte for byte +/// (`native_render_equals_the_template` renders thousands of random conversations both ways); pictures take the template. +pub(super) fn render_native( + messages: &[Message<'_>], + effort: Effort, + tools: &[Json], +) -> Result { + let leading = messages + .iter() + .take_while(|message| matches!(message.role, Role::System | Role::Developer)) + .count(); + let object = |message: &Message<'_>| { + let mut fields = vec![ + ("role".to_owned(), Json::str(message.role.name())), + ("content".to_owned(), Json::str(message.content)), + ]; + if let Some(reasoning) = message.reasoning { + fields.push(("reasoning_content".to_owned(), Json::str(reasoning))); + } + Json::Object(fields) + }; + // The template refuses an empty message list, so a conversation without system messages gets a placeholder user turn whose + // exact output is cut off again. + const PLACEHOLDER: &str = "<|im_start|>user\n<|im_end|>\n"; + let head: Vec = if leading == 0 { + vec![Json::object([ + ("role", Json::str("user")), + ("content", Json::str("")), + ])] + } else { + messages[..leading].iter().map(object).collect() + }; + let mut prompt = pinned().render(&ChatInput { + messages: &head, + tools: (!tools.is_empty()).then_some(tools), + add_generation_prompt: false, + kwargs: effort.kwargs(), + })?; + if leading == 0 { + prompt = prompt + .strip_suffix(PLACEHOLDER) + .ok_or("the chat template changed its output for an empty user turn")? + .to_owned(); + } + let rest = &messages[leading..]; + prompt.reserve( + rest.iter() + .map(|m| m.content.len() + m.reasoning.map_or(0, str::len) + 64) + .sum::() + + 64, + ); + for message in rest { + let content = message.content.trim_matches(py_space); + match message.role { + Role::User => { + prompt.push_str("<|im_start|>user\n"); + prompt.push_str(content); + prompt.push_str("<|im_end|>\n"); + } + Role::Assistant => { + prompt.push_str("<|im_start|>assistant\n\n"); + prompt.push_str(message.reasoning.unwrap_or("").trim_matches(py_space)); + prompt.push_str("\n\n\n"); + prompt.push_str(content); + prompt.push_str("<|im_end|>\n"); + } + Role::System | Role::Developer => { + return Err("System message must be at the beginning.".into()); + } + } + } + prompt.push_str("<|im_start|>assistant\n"); + prompt.push_str(if matches!(effort, Effort::None) { + "\n\n\n\n" + } else { + "\n" + }); + Ok(prompt) +} diff --git a/crates/gateway-text/src/prompt/json_string.rs b/crates/gateway-text/src/prompt/json_string.rs new file mode 100644 index 00000000..9e085085 --- /dev/null +++ b/crates/gateway-text/src/prompt/json_string.rs @@ -0,0 +1,200 @@ +//! Moved out of the parent module by STRA-338: fn json_string, fn write_json, fn tojson, fn keep_empty_turns, fn content_text, fn content_has_image .... + +#[allow(unused_imports)] +use super::*; + +pub(super) fn json_string(text: &str, ensure_ascii: bool, out: &mut String) { + out.push('"'); + for c in text.chars() { + match c { + '"' => out.push_str("\\\""), + '\\' => out.push_str("\\\\"), + '\n' => out.push_str("\\n"), + '\r' => out.push_str("\\r"), + '\t' => out.push_str("\\t"), + '\u{8}' => out.push_str("\\b"), + '\u{c}' => out.push_str("\\f"), + c if (c as u32) < 0x20 => out.push_str(&format!("\\u{:04x}", c as u32)), + c if ensure_ascii && !c.is_ascii() => { + let mut units = [0u16; 2]; + for unit in c.encode_utf16(&mut units) { + out.push_str(&format!("\\u{unit:04x}")); + } + } + c => out.push(c), + } + } + out.push('"'); +} + +pub(super) fn write_json( + value: &Value, + sort_keys: bool, + ensure_ascii: bool, + out: &mut String, +) -> Result<(), Error> { + match value.kind() { + ValueKind::None => out.push_str("null"), + ValueKind::Bool => out.push_str(if value.is_true() { "true" } else { "false" }), + ValueKind::Number => { + if value.is_integer() { + out.push_str(&value.to_string()); + } else { + let float = f64::try_from(value.clone())?; + if !float.is_finite() { + out.push_str(if float.is_nan() { + "NaN" + } else if float > 0.0 { + "Infinity" + } else { + "-Infinity" + }); + } else { + out.push_str(&python_float(float)); + } + } + } + ValueKind::String => json_string(value.as_str().unwrap_or_default(), ensure_ascii, out), + ValueKind::Seq | ValueKind::Iterable => { + out.push('['); + for (at, item) in value.try_iter()?.enumerate() { + if at > 0 { + out.push_str(", "); + } + write_json(&item, sort_keys, ensure_ascii, out)?; + } + out.push(']'); + } + ValueKind::Map => { + let mut keys: Vec = value.try_iter()?.collect(); + if sort_keys { + keys.sort_by_key(|k| k.to_string()); + } + out.push('{'); + for (at, key) in keys.iter().enumerate() { + if at > 0 { + out.push_str(", "); + } + let Some(name) = key.as_str() else { + return Err(Error::new( + ErrorKind::InvalidOperation, + "tojson keys must be strings", + )); + }; + json_string(name, ensure_ascii, out); + out.push_str(": "); + write_json(&value.get_item(key)?, sort_keys, ensure_ascii, out)?; + } + out.push('}'); + } + other => { + return Err(Error::new( + ErrorKind::InvalidOperation, + format!("Object of type {other:?} is not JSON serializable"), + )); + } + } + Ok(()) +} + +/// The server's `tojson`: `json.dumps(x, ensure_ascii=False, indent=None, separators=None, sort_keys=False)`. +pub(super) fn tojson(_state: &State, value: Value, kwargs: Kwargs) -> Result { + let ensure_ascii = kwargs.get::>("ensure_ascii")?.unwrap_or(false); + let sort_keys = kwargs.get::>("sort_keys")?.unwrap_or(false); + let indent: Option = kwargs.get("indent")?; + let separators: Option = kwargs.get("separators")?; + kwargs.assert_all_used()?; + if indent.is_some_and(|v| !v.is_none()) || separators.is_some_and(|v| !v.is_none()) { + return Err(Error::new( + ErrorKind::InvalidOperation, + "tojson with indent or separators is not supported by the native renderer", + )); + } + let mut out = String::new(); + write_json(&value, sort_keys, ensure_ascii, &mut out)?; + Ok(out) +} + +/// `STRATA_KEEP_EMPTY_TURNS=1` renders completed empty assistant turns as before (`ChatTemplate.render`). +pub(super) fn keep_empty_turns() -> bool { + std::env::var_os("STRATA_KEEP_EMPTY_TURNS").is_some_and(|v| v == "1") +} + +/// `serve/frontend.py` `_text_of`, as far as the emptiness test needs it: the text of a message's content, or the `TypeError` +/// Python raises for a content it cannot iterate (a number or a boolean). A string is itself, a list joins the `text` of its text +/// parts (type `text`, `input_text` or no type), an object is iterated by key (no part is a dict, so its text is empty). +pub(super) fn content_text(content: Option<&Json>) -> Result { + match content { + None | Some(Json::Null) | Some(Json::Object(_)) => Ok(String::new()), + Some(Json::String(text)) => Ok(text.clone()), + Some(Json::Array(parts)) => { + let mut text = String::new(); + for part in parts { + let Json::Object(_) = part else { continue }; + let text_part = match part.get("type") { + None | Some(Json::Null) => true, + Some(Json::String(kind)) => kind == "text" || kind == "input_text", + Some(_) => false, + }; + if !text_part { + continue; + } + match part.get("text") { + None => {} + Some(Json::String(piece)) => text.push_str(piece), + Some(_) => { + return Err("TypeError: sequence item: expected str instance".into()); + } + } + } + Ok(text) + } + Some(_) => Err("TypeError: object is not iterable".into()), + } +} + +/// `serve/frontend.py` `_has_image`: a list content with an `image_url`, `input_image` or `image` part. +pub(super) fn content_has_image(content: Option<&Json>) -> bool { + let Some(Json::Array(parts)) = content else { + return false; + }; + parts.iter().any(|part| { + matches!(part.get("type"), Some(Json::String(t)) if matches!(t.as_str(), "image_url" | "input_image" | "image")) + }) +} + +/// Python truthiness of a JSON value (`not m.get("tool_calls")`). +pub(super) fn truthy(value: Option<&Json>) -> bool { + match value { + None | Some(Json::Null) | Some(Json::Bool(false)) => false, + Some(Json::Bool(true)) => true, + Some(Json::Number(n)) => n.as_f64().is_none_or(|f| f != 0.0), + Some(Json::String(s)) => !s.is_empty(), + Some(Json::Array(items)) => !items.is_empty(), + Some(Json::Object(fields)) => !fields.is_empty(), + } +} + +/// A completed empty assistant turn: an assistant message with no text (after `str.strip`), no picture and no tool calls. +/// A reasoning content does not keep it. +pub(super) fn is_empty_assistant_turn(message: &Json) -> Result { + if !matches!(message.get("role"), Some(Json::String(role)) if role == "assistant") { + return Ok(false); + } + let content = message.get("content"); + Ok(content_text(content)?.trim_matches(py_space).is_empty() + && !content_has_image(content) + && !truthy(message.get("tool_calls"))) +} + +/// `ChatTemplate.render` (serve/frontend.py, Strata 0.1.50, #843): "Do not use completed empty assistant turns as examples +/// for the next reply. Keep the final message." The template sees the list without them; `STRATA_KEEP_EMPTY_TURNS=1` keeps them. +pub(super) fn without_empty_assistant_turns(messages: &[Json]) -> Result, String> { + let mut kept = Vec::with_capacity(messages.len()); + for (index, message) in messages.iter().enumerate() { + if index + 1 == messages.len() || keep_empty_turns() || !is_empty_assistant_turn(message)? { + kept.push(message.clone()); + } + } + Ok(kept) +} diff --git a/crates/gateway-text/src/prompt/without_empty_turns.rs b/crates/gateway-text/src/prompt/without_empty_turns.rs new file mode 100644 index 00000000..270b580c --- /dev/null +++ b/crates/gateway-text/src/prompt/without_empty_turns.rs @@ -0,0 +1,109 @@ +//! Moved out of the parent module by STRA-338: fn without_empty_turns, fn render_with_images, fn render_via_template. + +#[allow(unused_imports)] +use super::*; + +/// The typed counterpart of [`without_empty_assistant_turns`]. +pub(super) fn without_empty_turns<'a>(messages: &[Message<'a>]) -> Vec> { + messages + .iter() + .enumerate() + .filter(|(index, message)| { + index + 1 == messages.len() || keep_empty_turns() || !message.is_empty_assistant_turn() + }) + .map(|(_, message)| *message) + .collect() +} + +/// [`render_with_tools`] and the sources of the pictures the prompt contains, in prompt order (`images_of`). +pub fn render_with_images( + messages: &[Message<'_>], + effort: Effort, + tools: &[Plain], +) -> Result<(String, Vec), String> { + if messages.is_empty() { + return Err("prompt needs a message".into()); + } + // The template never sees a completed empty assistant turn (`without_empty_assistant_turns`); the checks below and the native + // renderer work on the same list. + let kept = without_empty_turns(messages); + let messages = kept.as_slice(); + let first_non_system = messages + .iter() + .position(|message| !matches!(message.role, Role::System | Role::Developer)) + .unwrap_or(messages.len()); + if first_non_system == messages.len() + || messages[first_non_system..] + .iter() + .any(|message| matches!(message.role, Role::System | Role::Developer)) + { + return Err("system and developer messages must be at the beginning".into()); + } + if messages + .last() + .is_none_or(|message| message.role != Role::User) + { + return Err("generation needs a final user message".into()); + } + if !reference_render() && messages.iter().all(|message| message.parts.is_none()) { + let tools = tools.iter().map(chat_tool).collect::, _>>()?; + return render_native(messages, effort, &tools).map(|prompt| (prompt, Vec::new())); + } + render_via_template(messages, effort, tools) +} + +/// The whole conversation through the Jinja template (the reference the native renderer is tested against). +pub(super) fn render_via_template( + messages: &[Message<'_>], + effort: Effort, + tools: &[Plain], +) -> Result<(String, Vec), String> { + let chat: Vec = messages + .iter() + .map(|message| { + let content = match message.parts { + None => Json::str(message.content), + Some(parts) => Json::Array( + parts + .iter() + .map(|part| match part { + Part::Text(text) => Json::object([ + ("type", Json::str("text")), + ("text", Json::str(text)), + ]), + Part::Image(source) => Json::object([ + ("type", Json::str("image")), + ("source", Json::str(source)), + ]), + }) + .collect(), + ), + }; + let mut fields = vec![ + ("role".to_owned(), Json::str(message.role.name())), + ("content".to_owned(), content), + ]; + if let Some(reasoning) = message.reasoning { + fields.push(("reasoning_content".to_owned(), Json::str(reasoning))); + } + Json::Object(fields) + }) + .collect(); + let images = messages + .iter() + .flat_map(|message| message.parts.unwrap_or(&[])) + .filter_map(|part| match part { + Part::Image(source) => Some(source.clone()), + Part::Text(_) => None, + }) + .collect(); + let tools = tools.iter().map(chat_tool).collect::, _>>()?; + pinned() + .render(&ChatInput { + messages: &chat, + tools: (!tools.is_empty()).then_some(&tools), + add_generation_prompt: true, + kwargs: effort.kwargs(), + }) + .map(|prompt| (prompt, images)) +} diff --git a/crates/gateway-text/src/tool_output.rs b/crates/gateway-text/src/tool_output.rs index 22089d8e..f1412ac5 100644 --- a/crates/gateway-text/src/tool_output.rs +++ b/crates/gateway-text/src/tool_output.rs @@ -41,28 +41,6 @@ pub struct Notes { pub recovered_forms: usize, } -impl Notes { - pub fn is_empty(&self) -> bool { - *self == Notes::default() - } - - fn absorb(&mut self, other: &Notes) { - self.closers_supplied += other.closers_supplied; - self.repaired_arguments += other.repaired_arguments; - self.recovered_forms += other.recovered_forms; - } -} - -impl std::fmt::Display for Notes { - fn fmt(&self, out: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - write!( - out, - "closers supplied: {}, arguments repaired: {}, drifted forms recovered: {}", - self.closers_supplied, self.repaired_arguments, self.recovered_forms - ) - } -} - pub struct Parsed { pub segments: Vec, pub notes: Notes, @@ -77,49 +55,6 @@ struct CodeState { line: String, } -impl CodeState { - fn feed(&mut self, text: &str) { - let mut parts = text.split('\n'); - if let Some(first) = parts.next() { - self.line.push_str(first); - } - for part in parts { - let line = std::mem::take(&mut self.line); - self.close_line(&line); - self.line.push_str(part); - } - } - - fn close_line(&mut self, line: &str) { - let start = line.trim_start(); - if let Some(mark) = self.fence { - if start.starts_with(&mark.to_string().repeat(3)) { - self.fence = None; - } - } else if (start.starts_with("```") || start.starts_with("~~~")) - && !start[3..].contains(&start[..3]) - { - self.fence = start.chars().next(); - } else if start.is_empty() { - self.ticks = 0; - } else { - self.ticks += line.matches('`').count(); - } - } - - /// Whether the next character starts a line outside a code fence and outside inline code. - fn at_opener(&self) -> bool { - self.fence.is_none() && self.line.trim().is_empty() && self.ticks.is_multiple_of(2) - } -} - -/// Whether the next character, after `before`, starts a line outside a code fence and outside inline code. -fn stands_outside_code(before: &str) -> bool { - let mut state = CodeState::default(); - state.feed(before); - state.at_opener() -} - pub struct Incremental<'a> { tools: &'a [Value], options: Options, @@ -136,301 +71,6 @@ pub struct Incremental<'a> { code: CodeState, } -impl<'a> Incremental<'a> { - pub fn new(tools: &'a [Value]) -> Self { - Self::with_options(tools, Options::default()) - } - - pub fn with_options(tools: &'a [Value], options: Options) -> Self { - Self { - tools, - options, - notes: Notes::default(), - buffer: String::new(), - in_call: false, - bare: false, - after_call: false, - tried: 0, - code: CodeState::default(), - } - } - - /// What was accepted although the template form was not followed, so far. - pub fn notes(&self) -> &Notes { - &self.notes - } - - fn track(&mut self, text: &str) { - if self.options.recovery { - self.code.feed(text); - } - } - - /// Start the call whose opener (`marker` bytes long) is at `at`: the text before it is emitted. - fn begin(&mut self, out: &mut Vec, at: usize, marker: usize, bare: bool) { - let raw = self.buffer[..at].to_owned(); - let prefix = raw.trim_end_matches('\n'); - if !prefix.is_empty() { - out.push(Segment::Text(prefix.to_owned())); - } - self.track(&raw); - self.buffer.drain(..at + marker); - self.tried = 0; - self.in_call = true; - self.bare = bare; - } - - /// A wrapped call that is whole in the buffer: its calls, how much of the buffer they used, what was accepted beyond the form. - fn complete_wrapped(&mut self) -> Option<(Vec, usize, Notes)> { - let mut search = self.tried; - while let Some(relative) = self.buffer[search..].find("") { - let end = search + relative + "".len(); - let mut found = Notes::default(); - // A `` left out is not accepted while streaming: the `` found may be text inside a value, and - // only the end of the generation can tell (see `finish_after`). - if let Ok((calls, used)) = read_wrapped( - &self.buffer[..end], - self.tools, - self.options, - false, - &mut found, - ) { - return Some((calls, used, found)); - } - search = end; - } - self.tried = search; - None - } - - /// The same for a call with no ``: it ends at its ``, and a `` after it is dropped. - fn complete_bare(&mut self) -> Option<(Vec, usize, Notes)> { - let mut search = self.tried; - while let Some(relative) = self.buffer[search..].find("") { - let end = search + relative + "".len(); - let mut found = Notes::default(); - if let Ok((call, _, _)) = parse_call( - &self.buffer[..end], - self.tools, - self.options, - false, - true, - &mut found, - ) { - let after = &self.buffer[end..]; - let rest = after.trim_start(); - let used = if rest.starts_with("") { - end + (after.len() - rest.len()) + "".len() - } else if rest.is_empty() || "".starts_with(rest) { - return None; // the stray closer may still be arriving - } else { - end - }; - return Some((vec![call], used, found)); - } - search = end; - } - self.tried = search; - None - } - - pub fn feed(&mut self, delta: &str) -> Result, String> { - self.buffer.push_str(delta); - let mut out = Vec::new(); - loop { - if self.after_call && !self.in_call { - let kept = self.buffer.trim_start_matches('\n').len(); - let dropped = self.buffer.len() - kept; - if dropped > 0 { - let text = self.buffer[..dropped].to_owned(); - self.track(&text); - self.buffer.drain(..dropped); - } - if !self.buffer.is_empty() { - self.after_call = false; - } - } - if self.in_call { - if self.buffer.len() > 16 * 1024 * 1024 { - return Err("tool call exceeds the 16 MiB streaming buffer".into()); - } - let found = if self.bare { - self.complete_bare() - } else { - self.complete_wrapped() - }; - let Some((calls, used, found)) = found else { - break; - }; - out.extend(calls); - self.notes.absorb(&found); - self.buffer.drain(..used); - self.tried = 0; - self.in_call = false; - self.bare = false; - self.after_call = true; - continue; - } - let wrapped = self.buffer.find(""); - let bare = if self.options.recovery { - find_bare(&self.buffer, &self.code, self.tools) - } else { - Bare::None - }; - match (wrapped, bare) { - (wrapped, Bare::Found(at)) if wrapped.is_none_or(|w| at < w) => { - self.begin(&mut out, at, 0, true) - } - (Some(at), _) => self.begin(&mut out, at, "".len(), false), - (None, bare) => { - let mut safe = match bare { - Bare::Pending(at) => at, - _ => self.buffer.len() - held_tag_prefix(&self.buffer, ""), - }; - while safe > 0 && self.buffer.as_bytes()[safe - 1] == b'\n' { - safe -= 1; - } - if safe > 0 { - let text = self.buffer[..safe].to_owned(); - self.track(&text); - out.push(Segment::Text(text)); - self.buffer.drain(..safe); - } - break; - } - } - } - Ok(out) - } - - /// End of the generation, which stopped at the token limit or was otherwise not a natural stop. - pub fn finish(&mut self) -> Result, String> { - self.finish_after(false) - } - - /// End of the generation. With `natural_stop` a call whose text ends on `` is whole. - pub fn finish_after(&mut self, natural_stop: bool) -> Result, String> { - if self.in_call { - let text = if self.bare { - self.buffer.clone() - } else { - format!("{}", self.buffer) - }; - let options = Options { - natural_stop, - ..self.options - }; - return match parse_text(&text, self.tools, options, self.code.clone()) { - Ok(parsed) => { - self.in_call = false; - self.bare = false; - self.buffer.clear(); - self.notes.absorb(&parsed.notes); - Ok(parsed.segments) - } - Err(_) => Err("generation ended inside a tool call".into()), - }; - } - if self.after_call || self.buffer.is_empty() { - Ok(Vec::new()) - } else { - Ok(vec![Segment::Text(std::mem::take(&mut self.buffer))]) - } - } -} - -fn held_tag_prefix(text: &str, tag: &str) -> usize { - (1..tag.len()) - .rev() - .find(|&len| text.ends_with(&tag[..len])) - .unwrap_or(0) -} - -pub fn parse_complete(text: &str, tools: &[Value]) -> Result, String> { - Ok(parse_with(text, tools, Options::default())?.segments) -} - -/// The whole text of a generation as text and calls, with what was accepted beyond the strict template form. -pub fn parse_with(text: &str, tools: &[Value], options: Options) -> Result { - parse_text(text, tools, options, CodeState::default()) -} - -fn parse_text( - mut text: &str, - tools: &[Value], - options: Options, - mut code: CodeState, -) -> Result { - let mut segments = Vec::new(); - let mut notes = Notes::default(); - loop { - let wrapped = text.find(""); - let bare = if options.recovery { - find_bare(text, &code, tools) - } else { - Bare::None - }; - let (start, is_bare) = match (wrapped, bare) { - (wrapped, Bare::Found(at)) if wrapped.is_none_or(|w| at < w) => (at, true), - (Some(at), _) => (at, false), - _ => break, - }; - let raw = &text[..start]; - let prefix = raw.trim_end_matches('\n'); - if !prefix.is_empty() { - segments.push(Segment::Text(prefix.to_owned())); - } - if options.recovery { - code.feed(raw); - } - let body = &text[start + if is_bare { 0 } else { "".len() }..]; - let (calls, used) = if is_bare { - let (call, used, _) = parse_call(body, tools, options, true, true, &mut notes)?; - notes.recovered_forms += 1; - (vec![call], used) - } else { - read_wrapped(body, tools, options, true, &mut notes)? - }; - segments.extend(calls); - let rest = &body[used..]; - text = rest.trim_start_matches('\n'); - if options.recovery { - code.feed(&rest[..rest.len() - text.len()]); - } - } - if !text.is_empty() { - segments.push(Segment::Text(text.to_owned())); - } - Ok(Parsed { segments, notes }) -} - -/// A generation that stopped by itself without ever closing its reasoning (``) and ended on tool calls: the offset -/// where the calls start. The calls count only when every one of them is a whole call of a declared tool, they are the last -/// thing in the text (whitespace aside), and the first one stands at the start of a line outside a code fence and outside -/// inline code, so a call the reasoning only quotes is not one. -pub fn calls_at_end(text: &str, tools: &[Value], options: Options) -> Option { - let options = Options { - natural_stop: true, - ..options - }; - let mut from = 0; - while let Some(relative) = text[from..].find("") { - let at = from + relative; - if stands_outside_code(&text[..at]) - && let Ok(parsed) = parse_with(&text[at..], tools, options) - && !parsed.segments.is_empty() - && parsed - .segments - .iter() - .all(|segment| matches!(segment, Segment::Call { .. })) - { - return Some(at); - } - from = at + 1; - } - None -} - /// A call without `` (`Options::recovery`): where `` of a declared tool starts a line outside code. enum Bare { None, @@ -440,296 +80,6 @@ enum Bare { Pending(usize), } -fn find_bare(text: &str, code: &CodeState, tools: &[Value]) -> Bare { - let starts_line = |at: usize| { - let mut state = code.clone(); - state.feed(&text[..at]); - state.at_opener() - }; - let mut from = 0; - while let Some(relative) = text[from..].find(" bool { - !name.is_empty() && !name.contains(|c: char| c == '<' || c == '>' || c.is_whitespace()) -} - -/// The calls of a wrapped body (the text after ``) up to and including its ``, and how much it used. With -/// `Options::recovery` the body may be a JSON call, and may hold several calls. -fn read_wrapped( - text: &str, - tools: &[Value], - options: Options, - closes_call: bool, - notes: &mut Notes, -) -> Result<(Vec, usize), String> { - if options.recovery - && let Some((call, used)) = json_call(text, tools) - { - notes.recovered_forms += 1; - return Ok((vec![call], used)); - } - let mut calls = Vec::new(); - let mut at = 0; - loop { - let (call, used, more) = - parse_call(&text[at..], tools, options, closes_call, false, notes)?; - calls.push(call); - at += used; - if !more { - return Ok((calls, at)); - } - notes.recovered_forms += 1; // a second call in the same wrapper - } -} - -/// `{"name": NAME, "arguments": {...}}` (or `"parameters"`, or the arguments as a JSON string) of a declared tool inside the -/// wrapper, up to its ``; also inside a Markdown fence. -fn json_call(text: &str, tools: &[Value]) -> Option<(Segment, usize)> { - let body = text.trim_start(); - if !(body.starts_with('{') || body.starts_with("```")) { - return None; - } - let end = text.find("")?; - let mut object = text[text.len() - body.len()..end].trim(); - if let Some(fenced) = object.strip_prefix("```") { - let after = fenced.trim_start_matches([' ', '\t']); - let after = if after - .get(..4) - .is_some_and(|tag| tag.eq_ignore_ascii_case("json")) - { - &after[4..] - } else { - after - }; - let after = after.trim_start_matches([' ', '\t']); - let after = after.strip_prefix('\r').unwrap_or(after); - object = after.strip_prefix('\n')?.trim(); - object = object.strip_suffix("```").unwrap_or(object).trim(); - } - let value: Value = serde_json::from_str(object).ok()?; - let name = value.get("name")?.as_str()?; - if !is_declared(name, tools) { - return None; - } - let arguments = match value.get("arguments").or_else(|| value.get("parameters")) { - None | Some(Value::Null) => json!({}), - Some(Value::String(text)) => serde_json::from_str::(text).ok()?, - Some(other) => other.clone(), - }; - arguments.is_object().then(|| { - ( - Segment::Call { - name: name.to_owned(), - arguments, - }, - end + "".len(), - ) - }) -} - -/// The opener of a call at the start of `text`: its tool name and how much of `text` it used. -fn read_opener<'t>( - text: &'t str, - tools: &[Value], - options: Options, -) -> Result<(&'t str, usize), String> { - let start = text.len() - text.trim_start().len(); - let rest = &text[start..]; - if let Some(after) = rest.strip_prefix("') - .ok_or("tool call function name is incomplete")?; - return Ok((&after[..end], start + "".to_owned()) -} - -/// A drifted opener of a declared tool (`Options::recovery`): `` where `` belongs, or the -/// envelope with a token off: `<=NAME>`, ``, ``, ``. -fn drifted_opener<'t>(rest: &'t str, tools: &[Value]) -> Option<(&'t str, usize)> { - if let Some(after) = rest.strip_prefix("')?; - let name = &after[..end]; - return is_declared(name, tools).then_some((name, "')?; - let mut head = inner[..end].trim_start(); - if let Some(after) = head.strip_prefix("function") - && let Some(after) = after.trim_start().strip_prefix(['=', ':']) - { - head = after.trim_start(); - } else if let Some(after) = head.strip_prefix('=') { - head = after.trim_start(); - } - let name = head.trim_end(); - let valid = !name.is_empty() - && name - .chars() - .all(|c| c.is_ascii_alphanumeric() || matches!(c, '_' | '.' | '-')); - (valid && is_declared(name, tools)).then_some((name, 1 + end + 1)) -} - -/// Whether `tail` (after a call's ``) opens another call in the same wrapper (`Options::recovery`). -fn starts_batched_call(tail: &str, tools: &[Value]) -> bool { - tail.starts_with("") { - offset += "".len(); - offset += after.len() - after.trim_start().len(); - let tail = &text[offset..]; - if tail.starts_with("") { - offset += "".len(); - } else if bare { - // no wrapper: the call ends here - } else if options.recovery && starts_batched_call(tail, tools) { - more = true; - } else if starts_next_call(tail) || (options.natural_stop && tail.is_empty()) { - // The wrapper's closer was left out and the next call's opener, or the end of a generation that stopped by - // itself, shows that the call is whole. - found.closers_supplied += 1; - } else { - return Err("tool call is missing ".to_owned()); - } - break; - } - let after = rest - .strip_prefix("').ok_or("tool parameter name is incomplete")?; - let parameter = &after[..end]; - if parameter.is_empty() { - return Err("tool parameter name is empty".to_owned()); - } - offset += "".len(); - if call_closed { - // `` and then ``: the `` was left out. - offset += text[offset..].len() - text[offset..].trim_start().len(); - offset += "".len(); - found.closers_supplied += 1; - break; - } - } - notes.absorb(&found); - if let Some(shell) = &patch_shell { - let (name, arguments) = shell.rewrite(&arguments); - return Ok((Segment::Call { name, arguments }, offset, more)); - } - Ok(( - Segment::Call { - name: name.to_owned(), - arguments: Value::Object(arguments), - }, - offset, - more, - )) -} - -/// Whether `tail` starts the next call: `` and then ``. -fn starts_next_call(tail: &str) -> bool { - let Some(rest) = tail.strip_prefix("") else { - return false; - }; - let Some(rest) = rest.trim_start().strip_prefix("') else { - return false; - }; - is_tool_name(rest[..end].trim()) -} - /// How to run a shell command through the shell tool the agent declared. struct PatchShell { tool: String, @@ -738,62 +88,6 @@ struct PatchShell { argv: bool, } -/// The shell tool of a Codex-style agent: `exec_command {cmd}`, `shell_command {command}` or `shell {command: [..]}`. -fn patch_shell(tools: &[Value]) -> Option { - let property = |tool: &Value, name: &str| { - tool.get("parameters")? - .get("properties")? - .get(name) - .and_then(|p| p.get("type")) - .cloned() - }; - for (tool_name, argument, argv) in [ - ("exec_command", "cmd", false), - ("shell_command", "command", false), - ("shell", "command", true), - ] { - let Some(tool) = tools - .iter() - .find(|tool| tool.get("name").and_then(Value::as_str) == Some(tool_name)) - else { - continue; - }; - if let Some(kind) = property(tool, argument) { - let is_array = kind == "array"; - if is_array == argv { - return Some(PatchShell { - tool: tool_name.to_owned(), - argument, - argv, - }); - } - } - } - None -} - -impl PatchShell { - /// The patch text is the parameter that holds `*** Begin Patch` (else the first one); the call becomes the heredoc form. - fn rewrite(&self, arguments: &Map) -> (String, Value) { - let patch = arguments - .values() - .filter_map(Value::as_str) - .find(|text| text.contains("*** Begin Patch")) - .or_else(|| arguments.values().find_map(Value::as_str)) - .unwrap_or(""); - let script = format!( - "apply_patch <<'PATCH'\n{}\nPATCH", - patch.trim_end_matches('\n') - ); - let value = if self.argv { - json!(["bash", "-lc", script]) - } else { - Value::String(script) - }; - (self.tool.clone(), json!({ self.argument: value })) - } -} - /// Which JSON types a parameter's declared `type` allows. #[derive(Clone, Copy)] struct Kinds { @@ -802,311 +96,12 @@ struct Kinds { object: bool, } -impl Kinds { - fn of(declared: Option<&Value>) -> Self { - let has = |wanted: &str| match declared { - Some(Value::String(kind)) => kind == wanted, - Some(Value::Array(kinds)) => kinds.iter().any(|kind| kind == wanted), - _ => false, - }; - Self { - string: has("string"), - array: has("array"), - object: has("object"), - } - } - - /// An array or object parameter that cannot be a string, so a damaged value is not simply text. - fn structured(self) -> bool { - !self.string && (self.array || self.object) - } - - fn fits(self, value: &Value) -> bool { - (self.array && value.is_array()) || (self.object && value.is_object()) - } -} - -/// `lossy`: also repair what needs a guess (`Options::recovery`). -fn parameter_value(raw: &str, declared: Option<&Value>, lossy: bool, found: &mut Notes) -> Value { - let text = || Value::String(raw.to_owned()); - if declared.is_some_and(|kind| kind == "string") { - return text(); - } - let kinds = Kinds::of(declared); - let parsed = match serde_json::from_str::(raw) { - Ok(parsed) => parsed, - Err(_) => { - // A slightly damaged array or object (a trailing comma, single quotes, Python's True/None) is read as written. - if kinds.structured() - && let Some(value) = repair_json(raw, lossy).filter(|value| kinds.fits(value)) - { - found.repaired_arguments += 1; - return value; - } - text() - } - }; - if kinds.structured() - && let Value::String(inner) = &parsed - && matches!(inner.trim_start().chars().next(), Some('[' | '{')) - { - // An array or object written as a JSON string of itself. - let value = serde_json::from_str::(inner) - .ok() - .or_else(|| repair_json(inner, lossy)); - if let Some(value) = value.filter(|value| kinds.fits(value)) { - found.repaired_arguments += 1; - return value; - } - } - if let Some(types) = declared.and_then(Value::as_array) - && types.iter().any(|kind| kind == "string") - { - // Qwen's string parameters are raw text, not JSON string literals. - // A union may opt into another JSON type, but must not turn a nullable - // string such as 123 into an undeclared number (or strip its quotes). - let declared_non_string = types.iter().any(|kind| match kind.as_str() { - Some("null") => parsed.is_null(), - Some("boolean") => parsed.is_boolean(), - Some("number") => parsed.is_number(), - Some("integer") => parsed.as_f64().is_some_and(|n| n.fract() == 0.0), - Some("object") => parsed.is_object(), - Some("array") => parsed.is_array(), - _ => false, - }); - if !declared_non_string { - return text(); - } - } - parsed -} - -/// A reader for the mechanical slips a model makes inside an array or object argument: a trailing or doubled comma, single -/// quotes, Python's `True`/`False`/`None`, and extra closing brackets at the end. It is only asked about text that is not valid -/// JSON. It never guesses a value and never drops or invents one: a string cut short, an unknown word, a bare string where a -/// member belongs, a missing colon: anything else is not repaired. With `lossy` (`Options::recovery`) it also closes brackets -/// left open at the end of the text and drops a bare string where an object member belongs. -fn repair_json(raw: &str, lossy: bool) -> Option { - let text = raw.trim(); - if !text.starts_with(['[', '{']) || text.len() > 1 << 20 { - return None; - } - let mut reader = Lenient { - chars: text.chars().collect(), - at: 0, - lossy, - }; - let value = reader.value(0).ok()?; - let rest: String = reader.chars[reader.at.min(reader.chars.len())..] - .iter() - .collect(); - rest.trim_matches(|c: char| "]}) \t\r\n".contains(c)) - .is_empty() - .then_some(value) -} - struct Lenient { chars: Vec, at: usize, lossy: bool, } -impl Lenient { - fn peek(&mut self) -> Option { - while self - .chars - .get(self.at) - .is_some_and(|c| matches!(c, ' ' | '\t' | '\r' | '\n')) - { - self.at += 1; - } - self.chars.get(self.at).copied() - } - - fn string(&mut self) -> Result { - let quote = self.chars[self.at]; - self.at += 1; - let mut out = String::new(); - while let Some(&c) = self.chars.get(self.at) { - self.at += 1; - if c == quote { - return Ok(out); - } - if c != '\\' { - out.push(c); - continue; - } - let escape = *self.chars.get(self.at).ok_or(())?; - self.at += 1; - out.push(match escape { - '"' | '\'' | '\\' | '/' => escape, - 'b' => '\u{8}', - 'f' => '\u{c}', - 'n' => '\n', - 'r' => '\r', - 't' => '\t', - 'u' => { - let mut unit = self.hex4()?; - if (0xd800..0xdc00).contains(&unit) { - // a surrogate pair: 😀 - if self.chars.get(self.at) != Some(&'\\') - || self.chars.get(self.at + 1) != Some(&'u') - { - return Err(()); - } - self.at += 2; - let low = self.hex4()?; - if !(0xdc00..0xe000).contains(&low) { - return Err(()); - } - unit = 0x10000 + ((unit - 0xd800) << 10) + (low - 0xdc00); - } - char::from_u32(unit).ok_or(())? - } - _ => return Err(()), - }); - } - Err(()) - } - - fn hex4(&mut self) -> Result { - let digits: String = self - .chars - .get(self.at..self.at + 4) - .ok_or(())? - .iter() - .collect(); - self.at += 4; - u32::from_str_radix(&digits, 16).map_err(|_| ()) - } - - fn value(&mut self, depth: usize) -> Result { - if depth > 64 { - return Err(()); - } - match self.peek().ok_or(())? { - '{' => self.object(depth + 1), - '[' => self.array(depth + 1), - '"' | '\'' => self.string().map(Value::String), - _ => { - let start = self.at; - while self - .chars - .get(self.at) - .is_some_and(|c| !c.is_whitespace() && !matches!(c, ',' | ']' | '}' | ':')) - { - self.at += 1; - } - let word: String = self.chars[start..self.at].iter().collect(); - match word.as_str() { - "true" | "True" => Ok(Value::Bool(true)), - "false" | "False" => Ok(Value::Bool(false)), - "null" | "None" => Ok(Value::Null), - _ => serde_json::from_str::(&word) - .ok() - .filter(Value::is_number) - .ok_or(()), - } - } - } - } - - fn object(&mut self, depth: usize) -> Result { - self.at += 1; - let mut members = Map::new(); - loop { - match self.peek() { - Some('}') => { - self.at += 1; - return Ok(Value::Object(members)); - } - None if self.lossy => return Ok(Value::Object(members)), - Some(',') => { - self.at += 1; - continue; - } - Some('"' | '\'') => {} - _ => return Err(()), - } - let key = self.string()?; - match self.peek() { - Some(':') => { - self.at += 1; - let value = self.value(depth)?; - members.insert(key, value); - } - // a bare string where a member belongs is dropped - Some(',' | '}') | None if self.lossy => {} - _ => return Err(()), - } - } - } - - fn array(&mut self, depth: usize) -> Result { - self.at += 1; - let mut items = Vec::new(); - loop { - match self.peek() { - Some(']') => { - self.at += 1; - return Ok(Value::Array(items)); - } - None if self.lossy => return Ok(Value::Array(items)), - None => return Err(()), - Some(',') => { - self.at += 1; - continue; - } - Some(_) => {} - } - items.push(self.value(depth)?); - match self.peek() { - Some(',' | ']') => {} - None if self.lossy => {} - _ => return Err(()), - } - } - } -} - -/// Where a parameter value in `text` (which starts at the value) ends, and whether the call's `` was left out. -/// The value ends at the first `` that is followed, after whitespace, by the next ``. The same text inside a value (a file that documents the call format) is part of the value, and so is a close -/// that belongs to a call the value itself quotes (upstream #4078): a `` counts only when the quoted openers -/// (`` followed by ``) before it are no more than the `` closers before -/// it. (A value that reopens its own parameter, `` of the same name, still ends at the first close: -/// it is indistinguishable from a parameter written twice, which is refused as `duplicate tool parameter`, not merged.) -/// Only when no such close exists, and `closes_call` is set, a `` followed by `` ends the value and the -/// call (the `` was left out). -fn find_parameter_end(text: &str, closes_call: bool) -> Option<(usize, bool)> { - scan_parameter_end(text, false) - .map(|at| (at, false)) - .or_else(|| { - closes_call - .then(|| scan_parameter_end(text, true).map(|at| (at, true))) - .flatten() - }) -} - -fn scan_parameter_end(text: &str, call_close: bool) -> Option { - let mut balance = QuoteBalance::new(text); - let mut search = 0; - while let Some(relative) = text[search..].find("") { - let at = search + relative; - if balance.opened_before(at) <= balance.closed_before(at) { - let after = text[at + "".len()..].trim_start(); - if after.starts_with("") - || (call_close && after.starts_with("")) - { - return Some(at); - } - } - search = at + 1; - } - None -} - /// Counts, for increasing positions, the calls a value quotes: openers `` that are followed by `` (a bare `` closers. Both cursors only move /// forward, so walking every `` candidate of a value costs one pass over it. @@ -1118,67 +113,24 @@ struct QuoteBalance<'a> { closers: usize, } -impl<'a> QuoteBalance<'a> { - fn new(text: &'a str) -> Self { - Self { - text, - opener_at: 0, - openers: 0, - closer_at: 0, - closers: 0, - } - } - - /// The end of a quoted opener that starts at `start` (` Option { - let rest = &self.text[start + "' || c.is_whitespace())?; - if name == 0 || !rest[name..].starts_with('>') { - return None; - } - let after = &rest[name + 1..]; - let follower = after.trim_start(); - let skipped = after.len() - follower.len(); - let token = if follower.starts_with("") { - "".len() - } else { - return None; - }; - Some(start + " usize { - while let Some(relative) = self.text[self.opener_at..].find(" { - self.openers += 1; - self.opener_at = end; - } - Some(_) => break, - None if start + " at => break, - None => self.opener_at = start + 1, - } - } - self.openers - } - - /// `` closers that end at or before `at`. - fn closed_before(&mut self, at: usize) -> usize { - while let Some(relative) = self.text[self.closer_at..].find("") { - let end = self.closer_at + relative + "".len(); - if end > at { - break; - } - self.closers += 1; - self.closer_at = end; - } - self.closers - } -} - #[cfg(test)] mod tests; + +mod impl_notes; +#[allow(unused_imports)] +pub use impl_notes::*; +mod impl_incremental; +#[allow(unused_imports)] +pub use impl_incremental::*; +mod parse_text; +#[allow(unused_imports)] +pub use parse_text::*; +mod starts_batched_call; +#[allow(unused_imports)] +pub use starts_batched_call::*; +mod parameter_value; +#[allow(unused_imports)] +pub use parameter_value::*; +mod find_parameter_end; +#[allow(unused_imports)] +pub use find_parameter_end::*; diff --git a/crates/gateway-text/src/tool_output/find_parameter_end.rs b/crates/gateway-text/src/tool_output/find_parameter_end.rs new file mode 100644 index 00000000..e80493bd --- /dev/null +++ b/crates/gateway-text/src/tool_output/find_parameter_end.rs @@ -0,0 +1,104 @@ +//! Moved out of the parent module by STRA-338: fn find_parameter_end, fn scan_parameter_end, impl QuoteBalance. + +#[allow(unused_imports)] +use super::*; + +/// Where a parameter value in `text` (which starts at the value) ends, and whether the call's `` was left out. +/// The value ends at the first `` that is followed, after whitespace, by the next ``. The same text inside a value (a file that documents the call format) is part of the value, and so is a close +/// that belongs to a call the value itself quotes (upstream #4078): a `` counts only when the quoted openers +/// (`` followed by ``) before it are no more than the `` closers before +/// it. (A value that reopens its own parameter, `` of the same name, still ends at the first close: +/// it is indistinguishable from a parameter written twice, which is refused as `duplicate tool parameter`, not merged.) +/// Only when no such close exists, and `closes_call` is set, a `` followed by `` ends the value and the +/// call (the `` was left out). +pub(super) fn find_parameter_end(text: &str, closes_call: bool) -> Option<(usize, bool)> { + scan_parameter_end(text, false) + .map(|at| (at, false)) + .or_else(|| { + closes_call + .then(|| scan_parameter_end(text, true).map(|at| (at, true))) + .flatten() + }) +} + +pub(super) fn scan_parameter_end(text: &str, call_close: bool) -> Option { + let mut balance = QuoteBalance::new(text); + let mut search = 0; + while let Some(relative) = text[search..].find("") { + let at = search + relative; + if balance.opened_before(at) <= balance.closed_before(at) { + let after = text[at + "".len()..].trim_start(); + if after.starts_with("") + || (call_close && after.starts_with("")) + { + return Some(at); + } + } + search = at + 1; + } + None +} + +impl<'a> QuoteBalance<'a> { + pub(super) fn new(text: &'a str) -> Self { + Self { + text, + opener_at: 0, + openers: 0, + closer_at: 0, + closers: 0, + } + } + + /// The end of a quoted opener that starts at `start` (` Option { + let rest = &self.text[start + "' || c.is_whitespace())?; + if name == 0 || !rest[name..].starts_with('>') { + return None; + } + let after = &rest[name + 1..]; + let follower = after.trim_start(); + let skipped = after.len() - follower.len(); + let token = if follower.starts_with("") { + "".len() + } else { + return None; + }; + Some(start + " usize { + while let Some(relative) = self.text[self.opener_at..].find(" { + self.openers += 1; + self.opener_at = end; + } + Some(_) => break, + None if start + " at => break, + None => self.opener_at = start + 1, + } + } + self.openers + } + + /// `` closers that end at or before `at`. + pub(super) fn closed_before(&mut self, at: usize) -> usize { + while let Some(relative) = self.text[self.closer_at..].find("") { + let end = self.closer_at + relative + "".len(); + if end > at { + break; + } + self.closers += 1; + self.closer_at = end; + } + self.closers + } +} diff --git a/crates/gateway-text/src/tool_output/impl_incremental.rs b/crates/gateway-text/src/tool_output/impl_incremental.rs new file mode 100644 index 00000000..d9cc8a07 --- /dev/null +++ b/crates/gateway-text/src/tool_output/impl_incremental.rs @@ -0,0 +1,223 @@ +//! Moved out of the parent module by STRA-338: impl Incremental, fn held_tag_prefix, fn parse_complete, fn parse_with. + +#[allow(unused_imports)] +use super::*; + +impl<'a> Incremental<'a> { + pub fn new(tools: &'a [Value]) -> Self { + Self::with_options(tools, Options::default()) + } + + pub fn with_options(tools: &'a [Value], options: Options) -> Self { + Self { + tools, + options, + notes: Notes::default(), + buffer: String::new(), + in_call: false, + bare: false, + after_call: false, + tried: 0, + code: CodeState::default(), + } + } + + /// What was accepted although the template form was not followed, so far. + pub fn notes(&self) -> &Notes { + &self.notes + } + + pub(super) fn track(&mut self, text: &str) { + if self.options.recovery { + self.code.feed(text); + } + } + + /// Start the call whose opener (`marker` bytes long) is at `at`: the text before it is emitted. + pub(super) fn begin(&mut self, out: &mut Vec, at: usize, marker: usize, bare: bool) { + let raw = self.buffer[..at].to_owned(); + let prefix = raw.trim_end_matches('\n'); + if !prefix.is_empty() { + out.push(Segment::Text(prefix.to_owned())); + } + self.track(&raw); + self.buffer.drain(..at + marker); + self.tried = 0; + self.in_call = true; + self.bare = bare; + } + + /// A wrapped call that is whole in the buffer: its calls, how much of the buffer they used, what was accepted beyond the form. + pub(super) fn complete_wrapped(&mut self) -> Option<(Vec, usize, Notes)> { + let mut search = self.tried; + while let Some(relative) = self.buffer[search..].find("") { + let end = search + relative + "".len(); + let mut found = Notes::default(); + // A `` left out is not accepted while streaming: the `` found may be text inside a value, and + // only the end of the generation can tell (see `finish_after`). + if let Ok((calls, used)) = read_wrapped( + &self.buffer[..end], + self.tools, + self.options, + false, + &mut found, + ) { + return Some((calls, used, found)); + } + search = end; + } + self.tried = search; + None + } + + /// The same for a call with no ``: it ends at its ``, and a `` after it is dropped. + pub(super) fn complete_bare(&mut self) -> Option<(Vec, usize, Notes)> { + let mut search = self.tried; + while let Some(relative) = self.buffer[search..].find("") { + let end = search + relative + "".len(); + let mut found = Notes::default(); + if let Ok((call, _, _)) = parse_call( + &self.buffer[..end], + self.tools, + self.options, + false, + true, + &mut found, + ) { + let after = &self.buffer[end..]; + let rest = after.trim_start(); + let used = if rest.starts_with("") { + end + (after.len() - rest.len()) + "".len() + } else if rest.is_empty() || "".starts_with(rest) { + return None; // the stray closer may still be arriving + } else { + end + }; + return Some((vec![call], used, found)); + } + search = end; + } + self.tried = search; + None + } + + pub fn feed(&mut self, delta: &str) -> Result, String> { + self.buffer.push_str(delta); + let mut out = Vec::new(); + loop { + if self.after_call && !self.in_call { + let kept = self.buffer.trim_start_matches('\n').len(); + let dropped = self.buffer.len() - kept; + if dropped > 0 { + let text = self.buffer[..dropped].to_owned(); + self.track(&text); + self.buffer.drain(..dropped); + } + if !self.buffer.is_empty() { + self.after_call = false; + } + } + if self.in_call { + if self.buffer.len() > 16 * 1024 * 1024 { + return Err("tool call exceeds the 16 MiB streaming buffer".into()); + } + let found = if self.bare { + self.complete_bare() + } else { + self.complete_wrapped() + }; + let Some((calls, used, found)) = found else { + break; + }; + out.extend(calls); + self.notes.absorb(&found); + self.buffer.drain(..used); + self.tried = 0; + self.in_call = false; + self.bare = false; + self.after_call = true; + continue; + } + let wrapped = self.buffer.find(""); + let bare = if self.options.recovery { + find_bare(&self.buffer, &self.code, self.tools) + } else { + Bare::None + }; + match (wrapped, bare) { + (wrapped, Bare::Found(at)) if wrapped.is_none_or(|w| at < w) => { + self.begin(&mut out, at, 0, true) + } + (Some(at), _) => self.begin(&mut out, at, "".len(), false), + (None, bare) => { + let mut safe = match bare { + Bare::Pending(at) => at, + _ => self.buffer.len() - held_tag_prefix(&self.buffer, ""), + }; + while safe > 0 && self.buffer.as_bytes()[safe - 1] == b'\n' { + safe -= 1; + } + if safe > 0 { + let text = self.buffer[..safe].to_owned(); + self.track(&text); + out.push(Segment::Text(text)); + self.buffer.drain(..safe); + } + break; + } + } + } + Ok(out) + } + + /// End of the generation, which stopped at the token limit or was otherwise not a natural stop. + pub fn finish(&mut self) -> Result, String> { + self.finish_after(false) + } + + /// End of the generation. With `natural_stop` a call whose text ends on `` is whole. + pub fn finish_after(&mut self, natural_stop: bool) -> Result, String> { + if self.in_call { + let text = if self.bare { + self.buffer.clone() + } else { + format!("{}", self.buffer) + }; + let options = Options { + natural_stop, + ..self.options + }; + return match parse_text(&text, self.tools, options, self.code.clone()) { + Ok(parsed) => { + self.in_call = false; + self.bare = false; + self.buffer.clear(); + self.notes.absorb(&parsed.notes); + Ok(parsed.segments) + } + Err(_) => Err("generation ended inside a tool call".into()), + }; + } + if self.after_call || self.buffer.is_empty() { + Ok(Vec::new()) + } else { + Ok(vec![Segment::Text(std::mem::take(&mut self.buffer))]) + } + } +} + +pub(super) fn held_tag_prefix(text: &str, tag: &str) -> usize { + (1..tag.len()) + .rev() + .find(|&len| text.ends_with(&tag[..len])) + .unwrap_or(0) +} + +pub fn parse_complete(text: &str, tools: &[Value]) -> Result, String> { + Ok(parse_with(text, tools, Options::default())?.segments) +} + +/// The whole text of a generation as text and calls, with what was accepted beyond the strict template form. +pub fn parse_with(text: &str, tools: &[Value], options: Options) -> Result { + parse_text(text, tools, options, CodeState::default()) +} diff --git a/crates/gateway-text/src/tool_output/impl_notes.rs b/crates/gateway-text/src/tool_output/impl_notes.rs new file mode 100644 index 00000000..4b9c5b0f --- /dev/null +++ b/crates/gateway-text/src/tool_output/impl_notes.rs @@ -0,0 +1,69 @@ +//! Moved out of the parent module by STRA-338: impl Notes, impl std_fmt_Display, impl CodeState, fn stands_outside_code. + +#[allow(unused_imports)] +use super::*; + +impl Notes { + pub fn is_empty(&self) -> bool { + *self == Notes::default() + } + + pub(super) fn absorb(&mut self, other: &Notes) { + self.closers_supplied += other.closers_supplied; + self.repaired_arguments += other.repaired_arguments; + self.recovered_forms += other.recovered_forms; + } +} + +impl std::fmt::Display for Notes { + fn fmt(&self, out: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + write!( + out, + "closers supplied: {}, arguments repaired: {}, drifted forms recovered: {}", + self.closers_supplied, self.repaired_arguments, self.recovered_forms + ) + } +} + +impl CodeState { + pub(super) fn feed(&mut self, text: &str) { + let mut parts = text.split('\n'); + if let Some(first) = parts.next() { + self.line.push_str(first); + } + for part in parts { + let line = std::mem::take(&mut self.line); + self.close_line(&line); + self.line.push_str(part); + } + } + + pub(super) fn close_line(&mut self, line: &str) { + let start = line.trim_start(); + if let Some(mark) = self.fence { + if start.starts_with(&mark.to_string().repeat(3)) { + self.fence = None; + } + } else if (start.starts_with("```") || start.starts_with("~~~")) + && !start[3..].contains(&start[..3]) + { + self.fence = start.chars().next(); + } else if start.is_empty() { + self.ticks = 0; + } else { + self.ticks += line.matches('`').count(); + } + } + + /// Whether the next character starts a line outside a code fence and outside inline code. + pub(super) fn at_opener(&self) -> bool { + self.fence.is_none() && self.line.trim().is_empty() && self.ticks.is_multiple_of(2) + } +} + +/// Whether the next character, after `before`, starts a line outside a code fence and outside inline code. +pub(super) fn stands_outside_code(before: &str) -> bool { + let mut state = CodeState::default(); + state.feed(before); + state.at_opener() +} diff --git a/crates/gateway-text/src/tool_output/parameter_value.rs b/crates/gateway-text/src/tool_output/parameter_value.rs new file mode 100644 index 00000000..bb5916e5 --- /dev/null +++ b/crates/gateway-text/src/tool_output/parameter_value.rs @@ -0,0 +1,246 @@ +//! Moved out of the parent module by STRA-338: fn parameter_value, fn repair_json, impl Lenient. + +#[allow(unused_imports)] +use super::*; + +/// `lossy`: also repair what needs a guess (`Options::recovery`). +pub(super) fn parameter_value( + raw: &str, + declared: Option<&Value>, + lossy: bool, + found: &mut Notes, +) -> Value { + let text = || Value::String(raw.to_owned()); + if declared.is_some_and(|kind| kind == "string") { + return text(); + } + let kinds = Kinds::of(declared); + let parsed = match serde_json::from_str::(raw) { + Ok(parsed) => parsed, + Err(_) => { + // A slightly damaged array or object (a trailing comma, single quotes, Python's True/None) is read as written. + if kinds.structured() + && let Some(value) = repair_json(raw, lossy).filter(|value| kinds.fits(value)) + { + found.repaired_arguments += 1; + return value; + } + text() + } + }; + if kinds.structured() + && let Value::String(inner) = &parsed + && matches!(inner.trim_start().chars().next(), Some('[' | '{')) + { + // An array or object written as a JSON string of itself. + let value = serde_json::from_str::(inner) + .ok() + .or_else(|| repair_json(inner, lossy)); + if let Some(value) = value.filter(|value| kinds.fits(value)) { + found.repaired_arguments += 1; + return value; + } + } + if let Some(types) = declared.and_then(Value::as_array) + && types.iter().any(|kind| kind == "string") + { + // Qwen's string parameters are raw text, not JSON string literals. + // A union may opt into another JSON type, but must not turn a nullable + // string such as 123 into an undeclared number (or strip its quotes). + let declared_non_string = types.iter().any(|kind| match kind.as_str() { + Some("null") => parsed.is_null(), + Some("boolean") => parsed.is_boolean(), + Some("number") => parsed.is_number(), + Some("integer") => parsed.as_f64().is_some_and(|n| n.fract() == 0.0), + Some("object") => parsed.is_object(), + Some("array") => parsed.is_array(), + _ => false, + }); + if !declared_non_string { + return text(); + } + } + parsed +} + +/// A reader for the mechanical slips a model makes inside an array or object argument: a trailing or doubled comma, single +/// quotes, Python's `True`/`False`/`None`, and extra closing brackets at the end. It is only asked about text that is not valid +/// JSON. It never guesses a value and never drops or invents one: a string cut short, an unknown word, a bare string where a +/// member belongs, a missing colon: anything else is not repaired. With `lossy` (`Options::recovery`) it also closes brackets +/// left open at the end of the text and drops a bare string where an object member belongs. +pub(super) fn repair_json(raw: &str, lossy: bool) -> Option { + let text = raw.trim(); + if !text.starts_with(['[', '{']) || text.len() > 1 << 20 { + return None; + } + let mut reader = Lenient { + chars: text.chars().collect(), + at: 0, + lossy, + }; + let value = reader.value(0).ok()?; + let rest: String = reader.chars[reader.at.min(reader.chars.len())..] + .iter() + .collect(); + rest.trim_matches(|c: char| "]}) \t\r\n".contains(c)) + .is_empty() + .then_some(value) +} + +impl Lenient { + pub(super) fn peek(&mut self) -> Option { + while self + .chars + .get(self.at) + .is_some_and(|c| matches!(c, ' ' | '\t' | '\r' | '\n')) + { + self.at += 1; + } + self.chars.get(self.at).copied() + } + + pub(super) fn string(&mut self) -> Result { + let quote = self.chars[self.at]; + self.at += 1; + let mut out = String::new(); + while let Some(&c) = self.chars.get(self.at) { + self.at += 1; + if c == quote { + return Ok(out); + } + if c != '\\' { + out.push(c); + continue; + } + let escape = *self.chars.get(self.at).ok_or(())?; + self.at += 1; + out.push(match escape { + '"' | '\'' | '\\' | '/' => escape, + 'b' => '\u{8}', + 'f' => '\u{c}', + 'n' => '\n', + 'r' => '\r', + 't' => '\t', + 'u' => { + let mut unit = self.hex4()?; + if (0xd800..0xdc00).contains(&unit) { + // a surrogate pair: 😀 + if self.chars.get(self.at) != Some(&'\\') + || self.chars.get(self.at + 1) != Some(&'u') + { + return Err(()); + } + self.at += 2; + let low = self.hex4()?; + if !(0xdc00..0xe000).contains(&low) { + return Err(()); + } + unit = 0x10000 + ((unit - 0xd800) << 10) + (low - 0xdc00); + } + char::from_u32(unit).ok_or(())? + } + _ => return Err(()), + }); + } + Err(()) + } + + pub(super) fn hex4(&mut self) -> Result { + let digits: String = self + .chars + .get(self.at..self.at + 4) + .ok_or(())? + .iter() + .collect(); + self.at += 4; + u32::from_str_radix(&digits, 16).map_err(|_| ()) + } + + pub(super) fn value(&mut self, depth: usize) -> Result { + if depth > 64 { + return Err(()); + } + match self.peek().ok_or(())? { + '{' => self.object(depth + 1), + '[' => self.array(depth + 1), + '"' | '\'' => self.string().map(Value::String), + _ => { + let start = self.at; + while self + .chars + .get(self.at) + .is_some_and(|c| !c.is_whitespace() && !matches!(c, ',' | ']' | '}' | ':')) + { + self.at += 1; + } + let word: String = self.chars[start..self.at].iter().collect(); + match word.as_str() { + "true" | "True" => Ok(Value::Bool(true)), + "false" | "False" => Ok(Value::Bool(false)), + "null" | "None" => Ok(Value::Null), + _ => serde_json::from_str::(&word) + .ok() + .filter(Value::is_number) + .ok_or(()), + } + } + } + } + + pub(super) fn object(&mut self, depth: usize) -> Result { + self.at += 1; + let mut members = Map::new(); + loop { + match self.peek() { + Some('}') => { + self.at += 1; + return Ok(Value::Object(members)); + } + None if self.lossy => return Ok(Value::Object(members)), + Some(',') => { + self.at += 1; + continue; + } + Some('"' | '\'') => {} + _ => return Err(()), + } + let key = self.string()?; + match self.peek() { + Some(':') => { + self.at += 1; + let value = self.value(depth)?; + members.insert(key, value); + } + // a bare string where a member belongs is dropped + Some(',' | '}') | None if self.lossy => {} + _ => return Err(()), + } + } + } + + pub(super) fn array(&mut self, depth: usize) -> Result { + self.at += 1; + let mut items = Vec::new(); + loop { + match self.peek() { + Some(']') => { + self.at += 1; + return Ok(Value::Array(items)); + } + None if self.lossy => return Ok(Value::Array(items)), + None => return Err(()), + Some(',') => { + self.at += 1; + continue; + } + Some(_) => {} + } + items.push(self.value(depth)?); + match self.peek() { + Some(',' | ']') => {} + None if self.lossy => {} + _ => return Err(()), + } + } + } +} diff --git a/crates/gateway-text/src/tool_output/parse_text.rs b/crates/gateway-text/src/tool_output/parse_text.rs new file mode 100644 index 00000000..9a8d55fe --- /dev/null +++ b/crates/gateway-text/src/tool_output/parse_text.rs @@ -0,0 +1,243 @@ +//! Moved out of the parent module by STRA-338: fn parse_text, fn calls_at_end, fn find_bare, fn is_declared, fn is_tool_name, fn read_wrapped .... + +#[allow(unused_imports)] +use super::*; + +pub(super) fn parse_text( + mut text: &str, + tools: &[Value], + options: Options, + mut code: CodeState, +) -> Result { + let mut segments = Vec::new(); + let mut notes = Notes::default(); + loop { + let wrapped = text.find(""); + let bare = if options.recovery { + find_bare(text, &code, tools) + } else { + Bare::None + }; + let (start, is_bare) = match (wrapped, bare) { + (wrapped, Bare::Found(at)) if wrapped.is_none_or(|w| at < w) => (at, true), + (Some(at), _) => (at, false), + _ => break, + }; + let raw = &text[..start]; + let prefix = raw.trim_end_matches('\n'); + if !prefix.is_empty() { + segments.push(Segment::Text(prefix.to_owned())); + } + if options.recovery { + code.feed(raw); + } + let body = &text[start + if is_bare { 0 } else { "".len() }..]; + let (calls, used) = if is_bare { + let (call, used, _) = parse_call(body, tools, options, true, true, &mut notes)?; + notes.recovered_forms += 1; + (vec![call], used) + } else { + read_wrapped(body, tools, options, true, &mut notes)? + }; + segments.extend(calls); + let rest = &body[used..]; + text = rest.trim_start_matches('\n'); + if options.recovery { + code.feed(&rest[..rest.len() - text.len()]); + } + } + if !text.is_empty() { + segments.push(Segment::Text(text.to_owned())); + } + Ok(Parsed { segments, notes }) +} + +/// A generation that stopped by itself without ever closing its reasoning (``) and ended on tool calls: the offset +/// where the calls start. The calls count only when every one of them is a whole call of a declared tool, they are the last +/// thing in the text (whitespace aside), and the first one stands at the start of a line outside a code fence and outside +/// inline code, so a call the reasoning only quotes is not one. +pub fn calls_at_end(text: &str, tools: &[Value], options: Options) -> Option { + let options = Options { + natural_stop: true, + ..options + }; + let mut from = 0; + while let Some(relative) = text[from..].find("") { + let at = from + relative; + if stands_outside_code(&text[..at]) + && let Ok(parsed) = parse_with(&text[at..], tools, options) + && !parsed.segments.is_empty() + && parsed + .segments + .iter() + .all(|segment| matches!(segment, Segment::Call { .. })) + { + return Some(at); + } + from = at + 1; + } + None +} + +pub(super) fn find_bare(text: &str, code: &CodeState, tools: &[Value]) -> Bare { + let starts_line = |at: usize| { + let mut state = code.clone(); + state.feed(&text[..at]); + state.at_opener() + }; + let mut from = 0; + while let Some(relative) = text[from..].find(" bool { + !name.is_empty() && !name.contains(|c: char| c == '<' || c == '>' || c.is_whitespace()) +} + +/// The calls of a wrapped body (the text after ``) up to and including its ``, and how much it used. With +/// `Options::recovery` the body may be a JSON call, and may hold several calls. +pub(super) fn read_wrapped( + text: &str, + tools: &[Value], + options: Options, + closes_call: bool, + notes: &mut Notes, +) -> Result<(Vec, usize), String> { + if options.recovery + && let Some((call, used)) = json_call(text, tools) + { + notes.recovered_forms += 1; + return Ok((vec![call], used)); + } + let mut calls = Vec::new(); + let mut at = 0; + loop { + let (call, used, more) = + parse_call(&text[at..], tools, options, closes_call, false, notes)?; + calls.push(call); + at += used; + if !more { + return Ok((calls, at)); + } + notes.recovered_forms += 1; // a second call in the same wrapper + } +} + +/// `{"name": NAME, "arguments": {...}}` (or `"parameters"`, or the arguments as a JSON string) of a declared tool inside the +/// wrapper, up to its ``; also inside a Markdown fence. +pub(super) fn json_call(text: &str, tools: &[Value]) -> Option<(Segment, usize)> { + let body = text.trim_start(); + if !(body.starts_with('{') || body.starts_with("```")) { + return None; + } + let end = text.find("")?; + let mut object = text[text.len() - body.len()..end].trim(); + if let Some(fenced) = object.strip_prefix("```") { + let after = fenced.trim_start_matches([' ', '\t']); + let after = if after + .get(..4) + .is_some_and(|tag| tag.eq_ignore_ascii_case("json")) + { + &after[4..] + } else { + after + }; + let after = after.trim_start_matches([' ', '\t']); + let after = after.strip_prefix('\r').unwrap_or(after); + object = after.strip_prefix('\n')?.trim(); + object = object.strip_suffix("```").unwrap_or(object).trim(); + } + let value: Value = serde_json::from_str(object).ok()?; + let name = value.get("name")?.as_str()?; + if !is_declared(name, tools) { + return None; + } + let arguments = match value.get("arguments").or_else(|| value.get("parameters")) { + None | Some(Value::Null) => json!({}), + Some(Value::String(text)) => serde_json::from_str::(text).ok()?, + Some(other) => other.clone(), + }; + arguments.is_object().then(|| { + ( + Segment::Call { + name: name.to_owned(), + arguments, + }, + end + "".len(), + ) + }) +} + +/// The opener of a call at the start of `text`: its tool name and how much of `text` it used. +pub(super) fn read_opener<'t>( + text: &'t str, + tools: &[Value], + options: Options, +) -> Result<(&'t str, usize), String> { + let start = text.len() - text.trim_start().len(); + let rest = &text[start..]; + if let Some(after) = rest.strip_prefix("') + .ok_or("tool call function name is incomplete")?; + return Ok((&after[..end], start + "".to_owned()) +} + +/// A drifted opener of a declared tool (`Options::recovery`): `` where `` belongs, or the +/// envelope with a token off: `<=NAME>`, ``, ``, ``. +pub(super) fn drifted_opener<'t>(rest: &'t str, tools: &[Value]) -> Option<(&'t str, usize)> { + if let Some(after) = rest.strip_prefix("')?; + let name = &after[..end]; + return is_declared(name, tools).then_some((name, "')?; + let mut head = inner[..end].trim_start(); + if let Some(after) = head.strip_prefix("function") + && let Some(after) = after.trim_start().strip_prefix(['=', ':']) + { + head = after.trim_start(); + } else if let Some(after) = head.strip_prefix('=') { + head = after.trim_start(); + } + let name = head.trim_end(); + let valid = !name.is_empty() + && name + .chars() + .all(|c| c.is_ascii_alphanumeric() || matches!(c, '_' | '.' | '-')); + (valid && is_declared(name, tools)).then_some((name, 1 + end + 1)) +} diff --git a/crates/gateway-text/src/tool_output/starts_batched_call.rs b/crates/gateway-text/src/tool_output/starts_batched_call.rs new file mode 100644 index 00000000..934781e5 --- /dev/null +++ b/crates/gateway-text/src/tool_output/starts_batched_call.rs @@ -0,0 +1,211 @@ +//! Moved out of the parent module by STRA-338: fn starts_batched_call, fn parse_call, fn starts_next_call, fn patch_shell, impl PatchShell, impl Kinds. + +#[allow(unused_imports)] +use super::*; + +/// Whether `tail` (after a call's ``) opens another call in the same wrapper (`Options::recovery`). +pub(super) fn starts_batched_call(tail: &str, tools: &[Value]) -> bool { + tail.starts_with("") { + offset += "".len(); + offset += after.len() - after.trim_start().len(); + let tail = &text[offset..]; + if tail.starts_with("") { + offset += "".len(); + } else if bare { + // no wrapper: the call ends here + } else if options.recovery && starts_batched_call(tail, tools) { + more = true; + } else if starts_next_call(tail) || (options.natural_stop && tail.is_empty()) { + // The wrapper's closer was left out and the next call's opener, or the end of a generation that stopped by + // itself, shows that the call is whole. + found.closers_supplied += 1; + } else { + return Err("tool call is missing ".to_owned()); + } + break; + } + let after = rest + .strip_prefix("').ok_or("tool parameter name is incomplete")?; + let parameter = &after[..end]; + if parameter.is_empty() { + return Err("tool parameter name is empty".to_owned()); + } + offset += "".len(); + if call_closed { + // `` and then ``: the `` was left out. + offset += text[offset..].len() - text[offset..].trim_start().len(); + offset += "".len(); + found.closers_supplied += 1; + break; + } + } + notes.absorb(&found); + if let Some(shell) = &patch_shell { + let (name, arguments) = shell.rewrite(&arguments); + return Ok((Segment::Call { name, arguments }, offset, more)); + } + Ok(( + Segment::Call { + name: name.to_owned(), + arguments: Value::Object(arguments), + }, + offset, + more, + )) +} + +/// Whether `tail` starts the next call: `` and then ``. +pub(super) fn starts_next_call(tail: &str) -> bool { + let Some(rest) = tail.strip_prefix("") else { + return false; + }; + let Some(rest) = rest.trim_start().strip_prefix("') else { + return false; + }; + is_tool_name(rest[..end].trim()) +} + +/// The shell tool of a Codex-style agent: `exec_command {cmd}`, `shell_command {command}` or `shell {command: [..]}`. +pub(super) fn patch_shell(tools: &[Value]) -> Option { + let property = |tool: &Value, name: &str| { + tool.get("parameters")? + .get("properties")? + .get(name) + .and_then(|p| p.get("type")) + .cloned() + }; + for (tool_name, argument, argv) in [ + ("exec_command", "cmd", false), + ("shell_command", "command", false), + ("shell", "command", true), + ] { + let Some(tool) = tools + .iter() + .find(|tool| tool.get("name").and_then(Value::as_str) == Some(tool_name)) + else { + continue; + }; + if let Some(kind) = property(tool, argument) { + let is_array = kind == "array"; + if is_array == argv { + return Some(PatchShell { + tool: tool_name.to_owned(), + argument, + argv, + }); + } + } + } + None +} + +impl PatchShell { + /// The patch text is the parameter that holds `*** Begin Patch` (else the first one); the call becomes the heredoc form. + pub(super) fn rewrite(&self, arguments: &Map) -> (String, Value) { + let patch = arguments + .values() + .filter_map(Value::as_str) + .find(|text| text.contains("*** Begin Patch")) + .or_else(|| arguments.values().find_map(Value::as_str)) + .unwrap_or(""); + let script = format!( + "apply_patch <<'PATCH'\n{}\nPATCH", + patch.trim_end_matches('\n') + ); + let value = if self.argv { + json!(["bash", "-lc", script]) + } else { + Value::String(script) + }; + (self.tool.clone(), json!({ self.argument: value })) + } +} + +impl Kinds { + pub(super) fn of(declared: Option<&Value>) -> Self { + let has = |wanted: &str| match declared { + Some(Value::String(kind)) => kind == wanted, + Some(Value::Array(kinds)) => kinds.iter().any(|kind| kind == wanted), + _ => false, + }; + Self { + string: has("string"), + array: has("array"), + object: has("object"), + } + } + + /// An array or object parameter that cannot be a string, so a damaged value is not simply text. + pub(super) fn structured(self) -> bool { + !self.string && (self.array || self.object) + } + + pub(super) fn fits(self, value: &Value) -> bool { + (self.array && value.is_array()) || (self.object && value.is_object()) + } +} diff --git a/crates/harmony/src/render.rs b/crates/harmony/src/render.rs index 0b9220d9..7cabfa90 100644 --- a/crates/harmony/src/render.rs +++ b/crates/harmony/src/render.rs @@ -22,105 +22,6 @@ pub struct RenderOptions { pub sentinel_markers: bool, } -impl RenderOptions { - pub fn new(current_date: impl Into) -> Self { - Self { - current_date: current_date.into(), - omit_date: false, - reasoning_effort: "medium".into(), - model_identity: None, - add_generation_prompt: true, - sentinel_markers: false, - } - } -} - -fn err(what: impl Into) -> HarmonyError { - HarmonyError::InvalidConversation(what.into()) -} - -// ---- Jinja value semantics used by the template ---- - -/// Jinja truthiness of an optional JSON value. -fn truthy(v: Option<&Value>) -> bool { - match v { - None | Some(Value::Null) => false, - Some(Value::Bool(b)) => *b, - Some(Value::Number(n)) => n.as_f64().is_some_and(|f| f != 0.0), - Some(Value::String(s)) => !s.is_empty(), - Some(Value::Array(a)) => !a.is_empty(), - Some(Value::Object(o)) => !o.is_empty(), - } -} - -/// `json.dumps`-style output as minja's `tojson` writes it: ", " and ": " separators, keys in -/// insertion order, non-ASCII characters kept as they are. -pub(crate) fn to_json(v: &Value) -> String { - let mut out = String::new(); - write_json(v, &mut out); - out -} - -fn write_json_string(s: &str, out: &mut String) { - out.push('"'); - for c in s.chars() { - match c { - '"' => out.push_str("\\\""), - '\\' => out.push_str("\\\\"), - '\n' => out.push_str("\\n"), - '\r' => out.push_str("\\r"), - '\t' => out.push_str("\\t"), - '\u{8}' => out.push_str("\\b"), - '\u{c}' => out.push_str("\\f"), - c if (c as u32) < 0x20 => out.push_str(&format!("\\u{:04x}", c as u32)), - c => out.push(c), - } - } - out.push('"'); -} - -fn write_json(v: &Value, out: &mut String) { - match v { - Value::Null => out.push_str("null"), - Value::Bool(b) => out.push_str(if *b { "true" } else { "false" }), - Value::Number(n) => out.push_str(&n.to_string()), - Value::String(s) => write_json_string(s, out), - Value::Array(a) => { - out.push('['); - for (i, item) in a.iter().enumerate() { - if i > 0 { - out.push_str(", "); - } - write_json(item, out); - } - out.push(']'); - } - Value::Object(o) => { - out.push('{'); - for (i, (k, item)) in o.iter().enumerate() { - if i > 0 { - out.push_str(", "); - } - write_json_string(k, out); - out.push_str(": "); - write_json(item, out); - } - out.push('}'); - } - } -} - -/// A JSON value as Jinja's string concatenation would take it (only strings concatenate). -fn as_concat_str(v: &Value, what: &str) -> Result { - match v { - Value::String(s) => Ok(s.clone()), - other => Err(err(format!( - "{what} must be a string to be joined into the prompt, found {}", - to_json(other) - ))), - } -} - // ---- tool definitions ---- /// Indent the template writes before the type of a property inside an object type. @@ -128,191 +29,6 @@ const NESTED_INDENT: &str = " "; /// Indent before a oneOf variant's default comment (the template's, on its expression line). const ONE_OF_DEFAULT_INDENT: &str = " "; -fn render_type(spec: &Value) -> Result { - let get = |k: &str| spec.get(k); - let ty = get("type"); - let mut out = String::new(); - if ty.and_then(Value::as_str) == Some("array") { - let items = get("items"); - if truthy(items) { - let items = items.expect("truthy"); - match items.get("type").and_then(Value::as_str) { - Some("string") => out.push_str("string[]"), - Some("number") | Some("integer") => out.push_str("number[]"), - Some("boolean") => out.push_str("boolean[]"), - _ => { - let inner = render_type(items)?; - if inner == "object | object" || inner.chars().count() > 50 { - out.push_str("any[]"); - } else { - out.push_str(&inner); - out.push_str("[]"); - } - } - } - } else { - out.push_str("any[]"); - } - if truthy(get("nullable")) { - out.push_str(" | null"); - } - return Ok(out); - } - if let Some(Value::Array(types)) = ty - && !types.is_empty() - { - // a list of types such as ["string", "null"] - let names: Vec = types - .iter() - .map(|t| as_concat_str(t, "a type name")) - .collect::>()?; - return Ok(if names.len() > 1 { - names.join(" | ") - } else { - names[0].clone() - }); - } - if truthy(get("oneOf")) { - // The template tests for object variants with a `set` inside a loop, which does not leak out of - // the loop in Jinja, so its "any" shortcut never applies: every alternative is rendered. - let variants = get("oneOf") - .and_then(Value::as_array) - .cloned() - .unwrap_or_default(); - for (i, variant) in variants.iter().enumerate() { - out.push_str(&render_type(variant)?); - if truthy(variant.get("description")) { - out.push_str("// "); - out.push_str(&as_concat_str(&variant["description"], "a description")?); - } - if let Some(default) = variant.get("default") { - out.push_str(ONE_OF_DEFAULT_INDENT); - out.push_str("// default: "); - out.push_str(&to_json(default)); - } - if i + 1 < variants.len() { - out.push_str(" | \n"); - } - } - return Ok(out); - } - match ty.and_then(Value::as_str) { - Some("string") => { - let en = get("enum"); - if truthy(en) { - let names: Vec = en - .and_then(Value::as_array) - .map(|a| { - a.iter() - .map(|v| as_concat_str(v, "an enum value")) - .collect() - }) - .unwrap_or_else(|| Ok(Vec::new()))?; - out.push('"'); - out.push_str(&names.join("\" | \"")); - out.push('"'); - } else { - out.push_str("string"); - if truthy(get("nullable")) { - out.push_str(" | null"); - } - } - } - Some("number") | Some("integer") => out.push_str("number"), - Some("boolean") => out.push_str("boolean"), - Some("object") => { - let props = get("properties"); - if truthy(props) { - let props: &Map = props - .and_then(Value::as_object) - .ok_or_else(|| err("properties must be an object"))?; - let required = required_names(spec)?; - out.push_str("{\n"); - let last = props.len() - 1; - for (i, (name, prop)) in props.iter().enumerate() { - out.push_str(name); - if !required.contains(name) { - out.push('?'); - } - out.push_str(": "); - out.push('\n'); - out.push_str(NESTED_INDENT); - out.push_str(&render_type(prop)?); - if i != last { - out.push_str(", "); - } - } - out.push('}'); - } else { - out.push_str("object"); - } - } - _ => out.push_str("any"), - } - Ok(out) -} - -fn required_names(spec: &Value) -> Result, HarmonyError> { - match spec.get("required") { - Some(Value::Array(a)) => a - .iter() - .map(|v| as_concat_str(v, "a required name")) - .collect(), - _ => Ok(Vec::new()), - } -} - -fn render_namespace(name: &str, tools: &[Tool]) -> Result { - let mut out = format!("## {name}\n\nnamespace {name} {{\n\n"); - for tool in tools { - if let Some(description) = &tool.description { - out.push_str(&format!("// {description}\n")); - } - out.push_str(&format!("type {} = ", tool.name)); - let props = tool.parameters.get("properties"); - if truthy(Some(&tool.parameters)) && truthy(props) { - let props = props - .and_then(Value::as_object) - .ok_or_else(|| err("tool parameters: properties must be an object"))?; - let required = required_names(&tool.parameters)?; - out.push_str("(_: {\n"); - let last = props.len() - 1; - for (i, (param, spec)) in props.iter().enumerate() { - if truthy(spec.get("description")) { - out.push_str(&format!( - "// {}\n", - as_concat_str(&spec["description"], "a description")? - )); - } - out.push_str(param); - if !required.contains(param) { - out.push('?'); - } - out.push_str(": "); - out.push_str(&render_type(spec)?); - if let Some(default) = spec.get("default") { - if truthy(spec.get("enum")) { - out.push_str(", // default: "); - out.push_str(&as_concat_str(default, "a default")?); - } else if truthy(spec.get("oneOf")) { - out.push_str("// default: "); - out.push_str(&as_concat_str(default, "a default")?); - } else { - out.push_str(", // default: "); - out.push_str(&to_json(default)); - } - } - out.push_str(if i != last { ",\n" } else { "\n" }); - } - out.push_str("}) => any;\n\n"); - } else { - out.push_str("() => any;\n\n"); - } - } - out.push_str(&format!("}} // namespace {name}")); - Ok(out) -} - // ---- the conversation ---- /// The private-use characters that stand for the format's special tokens in sentinel mode, in the order @@ -336,176 +52,9 @@ struct Out { sentinel: bool, } -impl Out { - fn new(sentinel: bool) -> Self { - Self { - s: String::new(), - sentinel, - } - } - - fn lit(&mut self, template: &str) { - if self.sentinel { - let mut mapped = template.to_owned(); - for (character, marker) in SENTINELS { - mapped = mapped.replace(marker, &character.to_string()); - } - self.s.push_str(&mapped); - } else { - self.s.push_str(template); - } - } - - fn text(&mut self, caller_text: &str) { - if self.sentinel { - self.s.extend(caller_text.chars().map(|c| { - if SENTINELS.iter().any(|(s, _)| *s == c) { - '\u{FFFD}' - } else { - c - } - })); - } else { - self.s.push_str(caller_text); - } - } -} -/// Render `messages` and `tools` as the gpt-oss prompt. -pub fn render( - messages: &[Message], - tools: &[Tool], - options: &RenderOptions, -) -> Result { - let mut out = Out::new(options.sentinel_markers); - out.lit("<|start|>system<|message|>"); - out.text( - options - .model_identity - .as_deref() - .unwrap_or("You are ChatGPT, a large language model trained by OpenAI."), - ); - out.lit("\nKnowledge cutoff: 2024-06\n"); - if options.omit_date { - out.lit("\n"); - } else { - out.text(&format!("Current date: {}\n\n", options.current_date)); - } - out.text(&format!("Reasoning: {}\n\n", options.reasoning_effort)); - out.lit("# Valid channels: analysis, commentary, final. Channel must be included for every message."); - if !tools.is_empty() { - out.lit("\nCalls to these tools must go to the commentary channel: 'functions'."); - } - out.lit("<|end|>"); - - // the first system or developer message carries the developer instructions - let (developer, rest) = match messages.first() { - Some(m) if matches!(m.role, Role::Developer | Role::System) => { - (m.content.clone().unwrap_or_default(), &messages[1..]) - } - _ => (String::new(), messages), - }; - if !developer.is_empty() || !tools.is_empty() { - out.lit("<|start|>developer<|message|>"); - if !developer.is_empty() { - out.lit("# Instructions\n\n"); - out.text(&developer); - } - if !tools.is_empty() { - out.lit("\n\n# Tools\n\n"); - out.text(&render_namespace("functions", tools)?); - } - out.lit("<|end|>"); - } - - let mut last_tool_call: Option = None; - for (index, message) in rest.iter().enumerate() { - let is_last = index + 1 == rest.len(); - match message.role { - Role::Assistant => { - if let Some(call) = message.tool_calls.first() { - let content = message.content.as_deref().filter(|c| !c.is_empty()); - let thinking = message.thinking.as_deref().filter(|c| !c.is_empty()); - match (content, thinking) { - (Some(_), Some(_)) => { - return Err(err( - "an assistant message with tool calls cannot have both content and thinking", - )); - } - (Some(text), None) | (None, Some(text)) => { - out.lit("<|start|>assistant<|channel|>analysis<|message|>"); - out.text(text); - out.lit("<|end|>"); - } - (None, None) => {} - } - out.lit("<|start|>assistant to=functions."); - out.text(&call.name); - out.lit("<|channel|>commentary "); - out.text(call.content_type.as_deref().unwrap_or("json")); - out.lit("<|message|>"); - out.text(&to_json(&call.arguments)); - out.lit("<|call|>"); - last_tool_call = Some(call.name.clone()); - } else { - let content = message - .content - .as_deref() - .ok_or_else(|| err("an assistant message needs content"))?; - if let Some(thinking) = &message.thinking - && (thinking.contains("<|channel|>analysis<|message|>") - || thinking.contains("<|channel|>final<|message|>")) - { - return Err(err("thinking must not contain channel markers")); - } - if is_last && !options.add_generation_prompt { - if let Some(thinking) = &message.thinking { - out.lit("<|start|>assistant<|channel|>analysis<|message|>"); - out.text(thinking); - out.lit("<|end|>"); - } - out.lit("<|start|>assistant<|channel|>final<|message|>"); - out.text(content); - out.lit("<|return|>"); - } else { - out.lit("<|start|>assistant<|channel|>final<|message|>"); - out.text(content); - out.lit("<|end|>"); - last_tool_call = None; - } - } - } - Role::Tool => { - let Some(name) = &last_tool_call else { - return Err(err( - "a tool message needs an earlier assistant message with a tool call", - )); - }; - let content = message - .content - .as_deref() - .ok_or_else(|| err("a tool message needs content"))?; - out.lit("<|start|>functions."); - out.text(name); - out.lit(" to=assistant<|channel|>commentary<|message|>"); - out.text(&to_json(&Value::String(content.to_owned()))); - out.lit("<|end|>"); - } - Role::User => { - out.lit("<|start|>user<|message|>"); - out.text( - message - .content - .as_deref() - .ok_or_else(|| err("a user message needs content"))?, - ); - out.lit("<|end|>"); - } - // later system or developer messages are not rendered, as in the template - Role::System | Role::Developer => {} - } - } - if options.add_generation_prompt { - out.lit("<|start|>assistant"); - } - Ok(out.s) -} +mod impl_renderoptions; +#[allow(unused_imports)] +pub use impl_renderoptions::*; +mod render_namespace; +#[allow(unused_imports)] +pub use render_namespace::*; diff --git a/crates/harmony/src/render/impl_renderoptions.rs b/crates/harmony/src/render/impl_renderoptions.rs new file mode 100644 index 00000000..cea6f0dd --- /dev/null +++ b/crates/harmony/src/render/impl_renderoptions.rs @@ -0,0 +1,238 @@ +//! Moved out of the parent module by STRA-338: impl RenderOptions, fn err, fn truthy, fn to_json, fn write_json_string, fn write_json .... + +#[allow(unused_imports)] +use super::*; + + +impl RenderOptions { + pub fn new(current_date: impl Into) -> Self { + Self { + current_date: current_date.into(), + omit_date: false, + reasoning_effort: "medium".into(), + model_identity: None, + add_generation_prompt: true, + sentinel_markers: false, + } + } +} + +pub(super) fn err(what: impl Into) -> HarmonyError { + HarmonyError::InvalidConversation(what.into()) +} + +// ---- Jinja value semantics used by the template ---- + +/// Jinja truthiness of an optional JSON value. +pub(super) fn truthy(v: Option<&Value>) -> bool { + match v { + None | Some(Value::Null) => false, + Some(Value::Bool(b)) => *b, + Some(Value::Number(n)) => n.as_f64().is_some_and(|f| f != 0.0), + Some(Value::String(s)) => !s.is_empty(), + Some(Value::Array(a)) => !a.is_empty(), + Some(Value::Object(o)) => !o.is_empty(), + } +} + +/// `json.dumps`-style output as minja's `tojson` writes it: ", " and ": " separators, keys in +/// insertion order, non-ASCII characters kept as they are. +pub(crate) fn to_json(v: &Value) -> String { + let mut out = String::new(); + write_json(v, &mut out); + out +} + +pub(super) fn write_json_string(s: &str, out: &mut String) { + out.push('"'); + for c in s.chars() { + match c { + '"' => out.push_str("\\\""), + '\\' => out.push_str("\\\\"), + '\n' => out.push_str("\\n"), + '\r' => out.push_str("\\r"), + '\t' => out.push_str("\\t"), + '\u{8}' => out.push_str("\\b"), + '\u{c}' => out.push_str("\\f"), + c if (c as u32) < 0x20 => out.push_str(&format!("\\u{:04x}", c as u32)), + c => out.push(c), + } + } + out.push('"'); +} + +pub(super) fn write_json(v: &Value, out: &mut String) { + match v { + Value::Null => out.push_str("null"), + Value::Bool(b) => out.push_str(if *b { "true" } else { "false" }), + Value::Number(n) => out.push_str(&n.to_string()), + Value::String(s) => write_json_string(s, out), + Value::Array(a) => { + out.push('['); + for (i, item) in a.iter().enumerate() { + if i > 0 { + out.push_str(", "); + } + write_json(item, out); + } + out.push(']'); + } + Value::Object(o) => { + out.push('{'); + for (i, (k, item)) in o.iter().enumerate() { + if i > 0 { + out.push_str(", "); + } + write_json_string(k, out); + out.push_str(": "); + write_json(item, out); + } + out.push('}'); + } + } +} + +/// A JSON value as Jinja's string concatenation would take it (only strings concatenate). +pub(super) fn as_concat_str(v: &Value, what: &str) -> Result { + match v { + Value::String(s) => Ok(s.clone()), + other => Err(err(format!( + "{what} must be a string to be joined into the prompt, found {}", + to_json(other) + ))), + } +} + +pub(super) fn render_type(spec: &Value) -> Result { + let get = |k: &str| spec.get(k); + let ty = get("type"); + let mut out = String::new(); + if ty.and_then(Value::as_str) == Some("array") { + let items = get("items"); + if truthy(items) { + let items = items.expect("truthy"); + match items.get("type").and_then(Value::as_str) { + Some("string") => out.push_str("string[]"), + Some("number") | Some("integer") => out.push_str("number[]"), + Some("boolean") => out.push_str("boolean[]"), + _ => { + let inner = render_type(items)?; + if inner == "object | object" || inner.chars().count() > 50 { + out.push_str("any[]"); + } else { + out.push_str(&inner); + out.push_str("[]"); + } + } + } + } else { + out.push_str("any[]"); + } + if truthy(get("nullable")) { + out.push_str(" | null"); + } + return Ok(out); + } + if let Some(Value::Array(types)) = ty + && !types.is_empty() + { + // a list of types such as ["string", "null"] + let names: Vec = types + .iter() + .map(|t| as_concat_str(t, "a type name")) + .collect::>()?; + return Ok(if names.len() > 1 { + names.join(" | ") + } else { + names[0].clone() + }); + } + if truthy(get("oneOf")) { + // The template tests for object variants with a `set` inside a loop, which does not leak out of + // the loop in Jinja, so its "any" shortcut never applies: every alternative is rendered. + let variants = get("oneOf") + .and_then(Value::as_array) + .cloned() + .unwrap_or_default(); + for (i, variant) in variants.iter().enumerate() { + out.push_str(&render_type(variant)?); + if truthy(variant.get("description")) { + out.push_str("// "); + out.push_str(&as_concat_str(&variant["description"], "a description")?); + } + if let Some(default) = variant.get("default") { + out.push_str(ONE_OF_DEFAULT_INDENT); + out.push_str("// default: "); + out.push_str(&to_json(default)); + } + if i + 1 < variants.len() { + out.push_str(" | \n"); + } + } + return Ok(out); + } + match ty.and_then(Value::as_str) { + Some("string") => { + let en = get("enum"); + if truthy(en) { + let names: Vec = en + .and_then(Value::as_array) + .map(|a| { + a.iter() + .map(|v| as_concat_str(v, "an enum value")) + .collect() + }) + .unwrap_or_else(|| Ok(Vec::new()))?; + out.push('"'); + out.push_str(&names.join("\" | \"")); + out.push('"'); + } else { + out.push_str("string"); + if truthy(get("nullable")) { + out.push_str(" | null"); + } + } + } + Some("number") | Some("integer") => out.push_str("number"), + Some("boolean") => out.push_str("boolean"), + Some("object") => { + let props = get("properties"); + if truthy(props) { + let props: &Map = props + .and_then(Value::as_object) + .ok_or_else(|| err("properties must be an object"))?; + let required = required_names(spec)?; + out.push_str("{\n"); + let last = props.len() - 1; + for (i, (name, prop)) in props.iter().enumerate() { + out.push_str(name); + if !required.contains(name) { + out.push('?'); + } + out.push_str(": "); + out.push('\n'); + out.push_str(NESTED_INDENT); + out.push_str(&render_type(prop)?); + if i != last { + out.push_str(", "); + } + } + out.push('}'); + } else { + out.push_str("object"); + } + } + _ => out.push_str("any"), + } + Ok(out) +} + +pub(super) fn required_names(spec: &Value) -> Result, HarmonyError> { + match spec.get("required") { + Some(Value::Array(a)) => a + .iter() + .map(|v| as_concat_str(v, "a required name")) + .collect(), + _ => Ok(Vec::new()), + } +} diff --git a/crates/harmony/src/render/render_namespace.rs b/crates/harmony/src/render/render_namespace.rs new file mode 100644 index 00000000..8be57a6d --- /dev/null +++ b/crates/harmony/src/render/render_namespace.rs @@ -0,0 +1,230 @@ +//! Moved out of the parent module by STRA-338: fn render_namespace, impl Out, fn render. + +#[allow(unused_imports)] +use super::*; + + +pub(super) fn render_namespace(name: &str, tools: &[Tool]) -> Result { + let mut out = format!("## {name}\n\nnamespace {name} {{\n\n"); + for tool in tools { + if let Some(description) = &tool.description { + out.push_str(&format!("// {description}\n")); + } + out.push_str(&format!("type {} = ", tool.name)); + let props = tool.parameters.get("properties"); + if truthy(Some(&tool.parameters)) && truthy(props) { + let props = props + .and_then(Value::as_object) + .ok_or_else(|| err("tool parameters: properties must be an object"))?; + let required = required_names(&tool.parameters)?; + out.push_str("(_: {\n"); + let last = props.len() - 1; + for (i, (param, spec)) in props.iter().enumerate() { + if truthy(spec.get("description")) { + out.push_str(&format!( + "// {}\n", + as_concat_str(&spec["description"], "a description")? + )); + } + out.push_str(param); + if !required.contains(param) { + out.push('?'); + } + out.push_str(": "); + out.push_str(&render_type(spec)?); + if let Some(default) = spec.get("default") { + if truthy(spec.get("enum")) { + out.push_str(", // default: "); + out.push_str(&as_concat_str(default, "a default")?); + } else if truthy(spec.get("oneOf")) { + out.push_str("// default: "); + out.push_str(&as_concat_str(default, "a default")?); + } else { + out.push_str(", // default: "); + out.push_str(&to_json(default)); + } + } + out.push_str(if i != last { ",\n" } else { "\n" }); + } + out.push_str("}) => any;\n\n"); + } else { + out.push_str("() => any;\n\n"); + } + } + out.push_str(&format!("}} // namespace {name}")); + Ok(out) +} + +impl Out { + pub(super) fn new(sentinel: bool) -> Self { + Self { + s: String::new(), + sentinel, + } + } + + pub(super) fn lit(&mut self, template: &str) { + if self.sentinel { + let mut mapped = template.to_owned(); + for (character, marker) in SENTINELS { + mapped = mapped.replace(marker, &character.to_string()); + } + self.s.push_str(&mapped); + } else { + self.s.push_str(template); + } + } + + pub(super) fn text(&mut self, caller_text: &str) { + if self.sentinel { + self.s.extend(caller_text.chars().map(|c| { + if SENTINELS.iter().any(|(s, _)| *s == c) { + '\u{FFFD}' + } else { + c + } + })); + } else { + self.s.push_str(caller_text); + } + } +} +/// Render `messages` and `tools` as the gpt-oss prompt. +pub fn render( + messages: &[Message], + tools: &[Tool], + options: &RenderOptions, +) -> Result { + let mut out = Out::new(options.sentinel_markers); + out.lit("<|start|>system<|message|>"); + out.text( + options + .model_identity + .as_deref() + .unwrap_or("You are ChatGPT, a large language model trained by OpenAI."), + ); + out.lit("\nKnowledge cutoff: 2024-06\n"); + if options.omit_date { + out.lit("\n"); + } else { + out.text(&format!("Current date: {}\n\n", options.current_date)); + } + out.text(&format!("Reasoning: {}\n\n", options.reasoning_effort)); + out.lit("# Valid channels: analysis, commentary, final. Channel must be included for every message."); + if !tools.is_empty() { + out.lit("\nCalls to these tools must go to the commentary channel: 'functions'."); + } + out.lit("<|end|>"); + + // the first system or developer message carries the developer instructions + let (developer, rest) = match messages.first() { + Some(m) if matches!(m.role, Role::Developer | Role::System) => { + (m.content.clone().unwrap_or_default(), &messages[1..]) + } + _ => (String::new(), messages), + }; + if !developer.is_empty() || !tools.is_empty() { + out.lit("<|start|>developer<|message|>"); + if !developer.is_empty() { + out.lit("# Instructions\n\n"); + out.text(&developer); + } + if !tools.is_empty() { + out.lit("\n\n# Tools\n\n"); + out.text(&render_namespace("functions", tools)?); + } + out.lit("<|end|>"); + } + + let mut last_tool_call: Option = None; + for (index, message) in rest.iter().enumerate() { + let is_last = index + 1 == rest.len(); + match message.role { + Role::Assistant => { + if let Some(call) = message.tool_calls.first() { + let content = message.content.as_deref().filter(|c| !c.is_empty()); + let thinking = message.thinking.as_deref().filter(|c| !c.is_empty()); + match (content, thinking) { + (Some(_), Some(_)) => { + return Err(err( + "an assistant message with tool calls cannot have both content and thinking", + )); + } + (Some(text), None) | (None, Some(text)) => { + out.lit("<|start|>assistant<|channel|>analysis<|message|>"); + out.text(text); + out.lit("<|end|>"); + } + (None, None) => {} + } + out.lit("<|start|>assistant to=functions."); + out.text(&call.name); + out.lit("<|channel|>commentary "); + out.text(call.content_type.as_deref().unwrap_or("json")); + out.lit("<|message|>"); + out.text(&to_json(&call.arguments)); + out.lit("<|call|>"); + last_tool_call = Some(call.name.clone()); + } else { + let content = message + .content + .as_deref() + .ok_or_else(|| err("an assistant message needs content"))?; + if let Some(thinking) = &message.thinking + && (thinking.contains("<|channel|>analysis<|message|>") + || thinking.contains("<|channel|>final<|message|>")) + { + return Err(err("thinking must not contain channel markers")); + } + if is_last && !options.add_generation_prompt { + if let Some(thinking) = &message.thinking { + out.lit("<|start|>assistant<|channel|>analysis<|message|>"); + out.text(thinking); + out.lit("<|end|>"); + } + out.lit("<|start|>assistant<|channel|>final<|message|>"); + out.text(content); + out.lit("<|return|>"); + } else { + out.lit("<|start|>assistant<|channel|>final<|message|>"); + out.text(content); + out.lit("<|end|>"); + last_tool_call = None; + } + } + } + Role::Tool => { + let Some(name) = &last_tool_call else { + return Err(err( + "a tool message needs an earlier assistant message with a tool call", + )); + }; + let content = message + .content + .as_deref() + .ok_or_else(|| err("a tool message needs content"))?; + out.lit("<|start|>functions."); + out.text(name); + out.lit(" to=assistant<|channel|>commentary<|message|>"); + out.text(&to_json(&Value::String(content.to_owned()))); + out.lit("<|end|>"); + } + Role::User => { + out.lit("<|start|>user<|message|>"); + out.text( + message + .content + .as_deref() + .ok_or_else(|| err("a user message needs content"))?, + ); + out.lit("<|end|>"); + } + // later system or developer messages are not rendered, as in the template + Role::System | Role::Developer => {} + } + } + if options.add_generation_prompt { + out.lit("<|start|>assistant"); + } + Ok(out.s) +} diff --git a/crates/igpu/src/shaders.rs b/crates/igpu/src/shaders.rs index 5fa28100..2695c9fc 100644 --- a/crates/igpu/src/shaders.rs +++ b/crates/igpu/src/shaders.rs @@ -12,189 +12,6 @@ use crate::WeightKind; pub const TILE_M: u32 = 4; pub const TILE_N: u32 = 4; -/// `C[m][n] = sum over blocks of f32(sum of int8 products) * act_scale * weight_scale`. -/// -/// Bindings: 0 dims `{m, n, nb, pad}`; 1 weight quant words; 2 weight scale words; 3 activation quant -/// words (8 per 32-element block); 4 activation scales (f32 per block); 5 output (f32, `[m][n]`). -/// Q8_0 weights: 8 int8 words per block, scales as half floats, two per word. MXFP4 weights: 4 nibble -/// words per block (byte `j` holds element `j` low and element `j + 16` high, as in ggml), scales as E8M0 -/// bytes, four per word. -pub fn gemm(kind: WeightKind, tm: u32, tn: u32, moe: bool) -> String { - // Blocks of the shared dimension staged per barrier pair. Two measured 20% faster for MXFP4 (the weight - // decode and the barriers amortize over more dot products); for Q8_0 it halved the speed (probably - // register pressure), so Q8_0 keeps one. - let nbk: u32 = match kind { - WeightKind::Mxfp4 => 2, - WeightKind::Q8_0 => 1, - }; - let bm = 8 * tm; - let bn = 8 * tn; - let mut declare_acc = String::new(); - let mut declare_sum = String::new(); - let mut operands = String::new(); - let mut multiply = String::new(); - let mut scale = String::new(); - let mut store = String::new(); - for i in 0..tm { - for j in 0..tn { - declare_acc += &format!(" var acc_{i}_{j} = 0.0;\n"); - declare_sum += &format!(" var s_{i}_{j} = 0;\n"); - multiply += &format!(" s_{i}_{j} += dot4I8Packed(a{i}, b{j});\n"); - scale += &format!(" acc_{i}_{j} += f32(s_{i}_{j}) * (sa{i} * sw{j});\n"); - store += &format!( - " {{ let r = row0 + ty * {tm}u + {i}u; let cc = col0 + tx * {tn}u + {j}u; if (r < rows_valid && cc < dims.n) {{ var v = acc_{i}_{j}; if ((dims.flags & 1u) != 0u) {{ v += bias[wbase + cc]; }} if ((dims.flags & 2u) != 0u) {{ v += c[(out_base + r) * dims.n + cc]; }} c[(out_base + r) * dims.n + cc] = v; }} }}\n" - ); - } - } - for i in 0..tm { - operands += - &format!(" let a{i} = tile_a[(sub * 8u + kk) * BM + {i}u * 8u + ty];\n"); - } - for j in 0..tn { - operands += - &format!(" let b{j} = tile_b[(sub * 8u + kk) * BN + {j}u * 8u + tx];\n"); - } - let mut scales = String::new(); - for i in 0..tm { - scales += &format!(" let sa{i} = sa_tile[sub * BM + ty * {tm}u + {i}u];\n"); - } - for j in 0..tn { - scales += &format!(" let sw{j} = sw_tile[sub * BN + tx * {tn}u + {j}u];\n"); - } - let loads_a = bm * 8 / 64; - let loads_b = bn * 8 / 64; - let (weight_word, weight_scale) = match kind { - WeightKind::Q8_0 => ( - // eight int8 words per block, read as they are - "wq[(wbase + col0 + r) * dims.nb * 8u + kb * 8u + w]".to_owned(), - // half float: two scales per word - "let s = (wbase + col0 + r) * dims.nb + kb; let word = ws[s / 2u]; let pair = unpack2x16float(word); sw_tile[sub * BN + r] = select(pair.x, pair.y, (s & 1u) == 1u);".to_owned(), - ), - WeightKind::Mxfp4 => ( - // output word w: elements 4w..4w+3; words 0..3 take the low nibbles of nibble word w, words - // 4..7 the high nibbles of nibble word w - 4 - "decode_mxfp4(wq[((wbase + col0 + r) * dims.nb + kb) * 4u + (w & 3u)], w >= 4u)".to_owned(), - "let s = (wbase + col0 + r) * dims.nb + kb; let e = (ws[s / 4u] >> (8u * (s & 3u))) & 255u; sw_tile[sub * BN + r] = bitcast(select(0x00200000u << e, (e - 1u) << 23u, e >= 2u));".to_owned(), - ), - }; - // Plain products tile the activation rows by workgroup row. The grouped (mixture-of-experts) variant - // takes its tile from a table: the expert, the first compact row and the row count; the weight rows - // start at `expert * n`, the activation row of compact row `i` is `rowmap[i]` (or `i` itself when - // flag 4 is clear), and the output is the compact `[entries][n]` array. - let (extra_bindings, setup, a_row) = if moe { - ( - "@group(0) @binding(7) var tiles: array;\n@group(0) @binding(8) var rowmap: array;", - " let tile_at = wid.y * 4u;\n let expert = tiles[tile_at];\n let start = tiles[tile_at + 1u];\n let rows_valid = tiles[tile_at + 2u];\n let row0 = 0u;\n let wbase = expert * dims.n;\n let out_base = start;", - "select(start + r, rowmap[start + r], (dims.flags & 4u) != 0u)", - ) - } else { - ( - "", - " let row0 = wid.y * BM;\n let rows_valid = dims.m;\n let wbase = 0u;\n let out_base = 0u;", - "(row0 + r)", - ) - }; - format!( - r#" -requires packed_4x8_integer_dot_product; - -struct Dims {{ m: u32, n: u32, nb: u32, flags: u32 }} // flags: 1 adds bias[n], 2 adds the existing output -@group(0) @binding(0) var dims: Dims; -@group(0) @binding(1) var wq: array; -@group(0) @binding(2) var ws: array; -@group(0) @binding(3) var aq: array; -@group(0) @binding(4) var asc: array; -@group(0) @binding(5) var c: array; -@group(0) @binding(6) var bias: array; -{extra_bindings} - -const BM: u32 = {bm}u; -const BN: u32 = {bn}u; -const NBK: u32 = {nbk}u; - -var tile_a: array; // NBK blocks -var tile_b: array; -var sa_tile: array; -var sw_tile: array; - -// the MXFP4 value table (twice the E2M1 value) as magnitudes packed one per nibble: 0 1 2 3 4 6 8 12 -fn mxfp4_magnitude(nibble: u32) -> i32 {{ - return i32((0xC8643210u >> (4u * (nibble & 7u))) & 15u); -}} - -// four nibbles (taken from the low or the high half of each byte of `word`) as four packed int8 values -fn decode_mxfp4(word: u32, high: bool) -> u32 {{ - var out = 0u; - for (var t = 0u; t < 4u; t++) {{ - let byte = (word >> (8u * t)) & 255u; - let nibble = select(byte & 15u, byte >> 4u, high); - let magnitude = mxfp4_magnitude(nibble); - let value = select(magnitude, -magnitude, nibble >= 8u); - out |= (u32(value) & 255u) << (8u * t); - }} - return out; -}} - -@compute @workgroup_size(8, 8) -fn main(@builtin(local_invocation_id) lid: vec3, - @builtin(workgroup_id) wid: vec3) {{ - let tx = lid.x; - let ty = lid.y; - let flat = ty * 8u + tx; -{setup} - let col0 = wid.x * BN; -{declare_acc} - for (var kb0 = 0u; kb0 < dims.nb; kb0 += NBK) {{ - for (var sub = 0u; sub < NBK; sub++) {{ - let kb = kb0 + sub; - let live = kb < dims.nb; - for (var i = 0u; i < {loads_a}u; i++) {{ - let idx = flat + i * 64u; - let r = idx / 8u; - let w = idx % 8u; - var v = 0u; - if (live && row0 + r < rows_valid) {{ v = aq[{a_row} * dims.nb * 8u + kb * 8u + w]; }} - tile_a[(sub * 8u + w) * BM + (r % {tm}u) * 8u + r / {tm}u] = v; - }} - for (var i = 0u; i < {loads_b}u; i++) {{ - let idx = flat + i * 64u; - let r = idx / 8u; - let w = idx % 8u; - var v = 0u; - if (live && col0 + r < dims.n) {{ v = {weight_word}; }} - tile_b[(sub * 8u + w) * BN + (r % {tn}u) * 8u + r / {tn}u] = v; - }} - if (flat < BM) {{ - var v = 0.0; - if (live && row0 + flat < rows_valid) {{ let r = flat; v = asc[{a_row} * dims.nb + kb]; }} - sa_tile[sub * BM + flat] = v; - }} - if (flat < BN) {{ - let r = flat; - sw_tile[sub * BN + r] = 0.0; - if (live && col0 + r < dims.n) {{ {weight_scale} }} - }} - }} - workgroupBarrier(); - for (var sub = 0u; sub < NBK; sub++) {{ -{declare_sum} for (var kk = 0u; kk < 8u; kk++) {{ -{operands}{multiply} }} -{scales}{scale} }} - workgroupBarrier(); - }} -{store}}} -"#, - nbk = nbk, - ta = bm * 8 * nbk, - tb = bn * 8 * nbk, - sam = bm * nbk, - swn = bn * nbk, - extra_bindings = extra_bindings, - setup = setup, - a_row = a_row, - ) -} - /// RMSNorm of `m` rows of `e` floats followed by Q8_0 quantization of the result. /// /// Bindings: 0 params `{m, e, nb, eps}`; 1 input `x` (`[m][e]`); 2 norm weights (`[e]`); 3 normalized rows @@ -618,7 +435,6 @@ fn f16_round(x: f32) -> f32 { } "#; -/// A kernel source with the shared helper functions in front. -pub fn with_helpers(source: &str) -> String { - format!("{F16_ROUND}{source}") -} +mod gemm; +#[allow(unused_imports)] +pub use gemm::*; diff --git a/crates/igpu/src/shaders/gemm.rs b/crates/igpu/src/shaders/gemm.rs new file mode 100644 index 00000000..0ead0ab7 --- /dev/null +++ b/crates/igpu/src/shaders/gemm.rs @@ -0,0 +1,193 @@ +//! Moved out of the parent module by STRA-338: fn gemm, fn with_helpers. + +#[allow(unused_imports)] +use super::*; + + +/// `C[m][n] = sum over blocks of f32(sum of int8 products) * act_scale * weight_scale`. +/// +/// Bindings: 0 dims `{m, n, nb, pad}`; 1 weight quant words; 2 weight scale words; 3 activation quant +/// words (8 per 32-element block); 4 activation scales (f32 per block); 5 output (f32, `[m][n]`). +/// Q8_0 weights: 8 int8 words per block, scales as half floats, two per word. MXFP4 weights: 4 nibble +/// words per block (byte `j` holds element `j` low and element `j + 16` high, as in ggml), scales as E8M0 +/// bytes, four per word. +pub fn gemm(kind: WeightKind, tm: u32, tn: u32, moe: bool) -> String { + // Blocks of the shared dimension staged per barrier pair. Two measured 20% faster for MXFP4 (the weight + // decode and the barriers amortize over more dot products); for Q8_0 it halved the speed (probably + // register pressure), so Q8_0 keeps one. + let nbk: u32 = match kind { + WeightKind::Mxfp4 => 2, + WeightKind::Q8_0 => 1, + }; + let bm = 8 * tm; + let bn = 8 * tn; + let mut declare_acc = String::new(); + let mut declare_sum = String::new(); + let mut operands = String::new(); + let mut multiply = String::new(); + let mut scale = String::new(); + let mut store = String::new(); + for i in 0..tm { + for j in 0..tn { + declare_acc += &format!(" var acc_{i}_{j} = 0.0;\n"); + declare_sum += &format!(" var s_{i}_{j} = 0;\n"); + multiply += &format!(" s_{i}_{j} += dot4I8Packed(a{i}, b{j});\n"); + scale += &format!(" acc_{i}_{j} += f32(s_{i}_{j}) * (sa{i} * sw{j});\n"); + store += &format!( + " {{ let r = row0 + ty * {tm}u + {i}u; let cc = col0 + tx * {tn}u + {j}u; if (r < rows_valid && cc < dims.n) {{ var v = acc_{i}_{j}; if ((dims.flags & 1u) != 0u) {{ v += bias[wbase + cc]; }} if ((dims.flags & 2u) != 0u) {{ v += c[(out_base + r) * dims.n + cc]; }} c[(out_base + r) * dims.n + cc] = v; }} }}\n" + ); + } + } + for i in 0..tm { + operands += + &format!(" let a{i} = tile_a[(sub * 8u + kk) * BM + {i}u * 8u + ty];\n"); + } + for j in 0..tn { + operands += + &format!(" let b{j} = tile_b[(sub * 8u + kk) * BN + {j}u * 8u + tx];\n"); + } + let mut scales = String::new(); + for i in 0..tm { + scales += &format!(" let sa{i} = sa_tile[sub * BM + ty * {tm}u + {i}u];\n"); + } + for j in 0..tn { + scales += &format!(" let sw{j} = sw_tile[sub * BN + tx * {tn}u + {j}u];\n"); + } + let loads_a = bm * 8 / 64; + let loads_b = bn * 8 / 64; + let (weight_word, weight_scale) = match kind { + WeightKind::Q8_0 => ( + // eight int8 words per block, read as they are + "wq[(wbase + col0 + r) * dims.nb * 8u + kb * 8u + w]".to_owned(), + // half float: two scales per word + "let s = (wbase + col0 + r) * dims.nb + kb; let word = ws[s / 2u]; let pair = unpack2x16float(word); sw_tile[sub * BN + r] = select(pair.x, pair.y, (s & 1u) == 1u);".to_owned(), + ), + WeightKind::Mxfp4 => ( + // output word w: elements 4w..4w+3; words 0..3 take the low nibbles of nibble word w, words + // 4..7 the high nibbles of nibble word w - 4 + "decode_mxfp4(wq[((wbase + col0 + r) * dims.nb + kb) * 4u + (w & 3u)], w >= 4u)".to_owned(), + "let s = (wbase + col0 + r) * dims.nb + kb; let e = (ws[s / 4u] >> (8u * (s & 3u))) & 255u; sw_tile[sub * BN + r] = bitcast(select(0x00200000u << e, (e - 1u) << 23u, e >= 2u));".to_owned(), + ), + }; + // Plain products tile the activation rows by workgroup row. The grouped (mixture-of-experts) variant + // takes its tile from a table: the expert, the first compact row and the row count; the weight rows + // start at `expert * n`, the activation row of compact row `i` is `rowmap[i]` (or `i` itself when + // flag 4 is clear), and the output is the compact `[entries][n]` array. + let (extra_bindings, setup, a_row) = if moe { + ( + "@group(0) @binding(7) var tiles: array;\n@group(0) @binding(8) var rowmap: array;", + " let tile_at = wid.y * 4u;\n let expert = tiles[tile_at];\n let start = tiles[tile_at + 1u];\n let rows_valid = tiles[tile_at + 2u];\n let row0 = 0u;\n let wbase = expert * dims.n;\n let out_base = start;", + "select(start + r, rowmap[start + r], (dims.flags & 4u) != 0u)", + ) + } else { + ( + "", + " let row0 = wid.y * BM;\n let rows_valid = dims.m;\n let wbase = 0u;\n let out_base = 0u;", + "(row0 + r)", + ) + }; + format!( + r#" +requires packed_4x8_integer_dot_product; + +struct Dims {{ m: u32, n: u32, nb: u32, flags: u32 }} // flags: 1 adds bias[n], 2 adds the existing output +@group(0) @binding(0) var dims: Dims; +@group(0) @binding(1) var wq: array; +@group(0) @binding(2) var ws: array; +@group(0) @binding(3) var aq: array; +@group(0) @binding(4) var asc: array; +@group(0) @binding(5) var c: array; +@group(0) @binding(6) var bias: array; +{extra_bindings} + +const BM: u32 = {bm}u; +const BN: u32 = {bn}u; +const NBK: u32 = {nbk}u; + +var tile_a: array; // NBK blocks +var tile_b: array; +var sa_tile: array; +var sw_tile: array; + +// the MXFP4 value table (twice the E2M1 value) as magnitudes packed one per nibble: 0 1 2 3 4 6 8 12 +fn mxfp4_magnitude(nibble: u32) -> i32 {{ + return i32((0xC8643210u >> (4u * (nibble & 7u))) & 15u); +}} + +// four nibbles (taken from the low or the high half of each byte of `word`) as four packed int8 values +fn decode_mxfp4(word: u32, high: bool) -> u32 {{ + var out = 0u; + for (var t = 0u; t < 4u; t++) {{ + let byte = (word >> (8u * t)) & 255u; + let nibble = select(byte & 15u, byte >> 4u, high); + let magnitude = mxfp4_magnitude(nibble); + let value = select(magnitude, -magnitude, nibble >= 8u); + out |= (u32(value) & 255u) << (8u * t); + }} + return out; +}} + +@compute @workgroup_size(8, 8) +fn main(@builtin(local_invocation_id) lid: vec3, + @builtin(workgroup_id) wid: vec3) {{ + let tx = lid.x; + let ty = lid.y; + let flat = ty * 8u + tx; +{setup} + let col0 = wid.x * BN; +{declare_acc} + for (var kb0 = 0u; kb0 < dims.nb; kb0 += NBK) {{ + for (var sub = 0u; sub < NBK; sub++) {{ + let kb = kb0 + sub; + let live = kb < dims.nb; + for (var i = 0u; i < {loads_a}u; i++) {{ + let idx = flat + i * 64u; + let r = idx / 8u; + let w = idx % 8u; + var v = 0u; + if (live && row0 + r < rows_valid) {{ v = aq[{a_row} * dims.nb * 8u + kb * 8u + w]; }} + tile_a[(sub * 8u + w) * BM + (r % {tm}u) * 8u + r / {tm}u] = v; + }} + for (var i = 0u; i < {loads_b}u; i++) {{ + let idx = flat + i * 64u; + let r = idx / 8u; + let w = idx % 8u; + var v = 0u; + if (live && col0 + r < dims.n) {{ v = {weight_word}; }} + tile_b[(sub * 8u + w) * BN + (r % {tn}u) * 8u + r / {tn}u] = v; + }} + if (flat < BM) {{ + var v = 0.0; + if (live && row0 + flat < rows_valid) {{ let r = flat; v = asc[{a_row} * dims.nb + kb]; }} + sa_tile[sub * BM + flat] = v; + }} + if (flat < BN) {{ + let r = flat; + sw_tile[sub * BN + r] = 0.0; + if (live && col0 + r < dims.n) {{ {weight_scale} }} + }} + }} + workgroupBarrier(); + for (var sub = 0u; sub < NBK; sub++) {{ +{declare_sum} for (var kk = 0u; kk < 8u; kk++) {{ +{operands}{multiply} }} +{scales}{scale} }} + workgroupBarrier(); + }} +{store}}} +"#, + nbk = nbk, + ta = bm * 8 * nbk, + tb = bn * 8 * nbk, + sam = bm * nbk, + swn = bn * nbk, + extra_bindings = extra_bindings, + setup = setup, + a_row = a_row, + ) +} + +/// A kernel source with the shared helper functions in front. +pub fn with_helpers(source: &str) -> String { + format!("{F16_ROUND}{source}") +} diff --git a/crates/leleka-memory/src/governor.rs b/crates/leleka-memory/src/governor.rs index 86edc665..54221107 100644 --- a/crates/leleka-memory/src/governor.rs +++ b/crates/leleka-memory/src/governor.rs @@ -40,83 +40,6 @@ pub struct GovernorConfig { pub log: bool, } -impl GovernorConfig { - pub fn new(policy: Policy) -> Self { - Self { policy, sample_interval_ms: 1000, lock_mode: LockMode::Try, heal: true, heal_bytes_per_tick: GIB, residency_every_ms: 30_000, log: true } - } - - /// Defaults for the host, then the `LELEKA_MEMORY_*` overrides. An unparsable override is an error naming the variable - /// (a typo must not silently keep the default of a safety setting). - pub fn from_env(mem_total: u64, laptop: bool, env: &dyn Fn(&str) -> Option) -> Result { - let mut cfg = Self::new(Policy::for_host(mem_total, laptop)); - let number = |name: &str| -> Result, String> { - match env(name) { - None => Ok(None), - Some(v) => v.trim().parse::().map(Some).map_err(|_| format!("{name}={v:?} is not a number")), - } - }; - if let Some(v) = number("LELEKA_MEMORY_SOFT_FLOOR_MIB")? { - cfg.policy.soft_floor = v.saturating_mul(MIB); - } - if let Some(v) = number("LELEKA_MEMORY_HARD_FLOOR_MIB")? { - cfg.policy.hard_floor = v.saturating_mul(MIB); - } - if let Some(v) = number("LELEKA_MEMORY_RESERVE_MIB")? { - cfg.policy.reserve = v.saturating_mul(MIB); - } - if let Some(v) = number("LELEKA_MEMORY_HYSTERESIS_MIB")? { - cfg.policy.hysteresis = v.saturating_mul(MIB); - } - if let Some(v) = number("LELEKA_MEMORY_CACHE_SHARE_PERCENT")? { - if v == 0 || v > 100 { - return Err(format!("LELEKA_MEMORY_CACHE_SHARE_PERCENT={v} must be 1..=100")); - } - cfg.policy.cache_share_percent = v; - } - if let Some(v) = number("LELEKA_MEMORY_SWAPOUT_PAGES_PER_S")? { - cfg.policy.swapout_pages_per_s_shed = v; - } - let float = |name: &str| -> Result, String> { - match env(name) { - None => Ok(None), - Some(v) => v.trim().parse::().ok().filter(|f| f.is_finite() && *f >= 0.0).map(Some).ok_or_else(|| format!("{name}={v:?} is not a non-negative number")), - } - }; - if let Some(v) = number("LELEKA_MEMORY_PSI_GUARD_MIB")? { - cfg.policy.psi_guard_available = v.saturating_mul(MIB); - } - if let Some(v) = float("LELEKA_MEMORY_PSI_SOME_SHED")? { - cfg.policy.psi_some_shed = v; - } - if let Some(v) = float("LELEKA_MEMORY_PSI_FULL_REJECT")? { - cfg.policy.psi_full_reject = v; - } - if let Some(v) = number("LELEKA_MEMORY_ENFORCE")? { - cfg.policy.enforce = v != 0; - } - if let Some(v) = number("LELEKA_MEMORY_SAMPLE_MS")? { - cfg.sample_interval_ms = v.clamp(50, 60_000); - } - if let Some(v) = number("LELEKA_MEMORY_HEAL")? { - cfg.heal = v != 0; - } - if let Some(v) = number("LELEKA_MEMORY_RESIDENCY_S")? { - cfg.residency_every_ms = v.saturating_mul(1000).max(1000); - } - if let Some(v) = env("LELEKA_MEMORY_LOCK") { - cfg.lock_mode = LockMode::parse(v.trim()).ok_or_else(|| format!("LELEKA_MEMORY_LOCK={v:?} must be off, try or require"))?; - } - if cfg.policy.hard_floor >= cfg.policy.soft_floor { - return Err(format!( - "hard floor {} MiB must be below the soft floor {} MiB (LELEKA_MEMORY_HARD_FLOOR_MIB / SOFT_FLOOR_MIB)", - cfg.policy.hard_floor >> 20, - cfg.policy.soft_floor >> 20 - )); - } - Ok(cfg) - } -} - /// What a request needs from the governor. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub struct RequestShape { @@ -242,763 +165,21 @@ pub struct Governor { static GLOBAL: OnceLock = OnceLock::new(); static PUBLISHED: Mutex> = Mutex::new(None); -/// The last report the sampler published (JSON text), for the status surface. -pub fn published_report() -> Option { - PUBLISHED.lock().unwrap_or_else(|p| p.into_inner()).clone() -} - -fn lock(m: &Mutex) -> MutexGuard<'_, T> { - m.lock().unwrap_or_else(|p| p.into_inner()) -} - -impl Governor { - pub fn new(cfg: GovernorConfig, src: Arc) -> Self { - let policy0 = cfg.policy; - let monitor = Monitor::new(policy0); - Self { - inner: Arc::new(Inner { - cfg, - src, - epoch: Instant::now(), - plan: Mutex::new(None), - monitor: Mutex::new(monitor), - policy: Mutex::new(policy0), - level: AtomicU8::new(Level::Normal as u8), - reason: Mutex::new("startup".into()), - available: AtomicU64::new(NONE), - sampled_at_ms: AtomicU64::new(0), - prefix_planned: AtomicU64::new(0), - prefix_target: AtomicU64::new(NONE), - prefix_used: AtomicU64::new(0), - last_shed_ms: AtomicU64::new(0), - last_trim_ms: AtomicU64::new(NONE), - last_trim_log_ms: AtomicU64::new(0), - trims: AtomicU64::new(0), - since_ms: AtomicU64::new(0), - transitions: Mutex::new(VecDeque::new()), - counters: Counters::default(), - ledger: Ledger::new(), - vram: Mutex::new(None), - post_load: Mutex::new(None), - #[cfg(all(target_os = "linux", target_pointer_width = "64"))] - guarded: Mutex::new(None), - stop: AtomicBool::new(false), - }), - } - } - - /// A governor over the real `/proc`. - pub fn real(cfg: GovernorConfig) -> Self { - Self::new(cfg, Arc::new(RealProc)) - } - - /// Make this the process-wide governor (the first install wins; later ones are returned unchanged). - pub fn install(self) -> &'static Governor { - GLOBAL.get_or_init(|| self) - } - pub fn global() -> Option<&'static Governor> { - GLOBAL.get() - } - - /// Replace the pressure floors at run time (diagnostics and the shed tests: move the thresholds next to the memory - /// the host has now, so the whole shed path runs without ever approaching the real limit). `hard < soft` is required. - pub fn set_floors(&self, soft_floor: u64, hard_floor: u64) -> Result<(), String> { - if hard_floor >= soft_floor { - return Err(format!("hard floor {hard_floor} must be below the soft floor {soft_floor}")); - } - let mut policy = lock(&self.inner.policy); - policy.soft_floor = soft_floor; - policy.hard_floor = hard_floor; - lock(&self.inner.monitor).set_policy(*policy); - drop(policy); - self.log(&format!("floors set to soft {} MiB / hard {} MiB", soft_floor >> 20, hard_floor >> 20)); - Ok(()) - } - - pub fn config(&self) -> &GovernorConfig { - &self.inner.cfg - } - pub fn policy(&self) -> Policy { - *lock(&self.inner.policy) - } - pub fn inventory(&self) -> &'static Inventory { - Inventory::global() - } - pub fn ledger(&self) -> &Ledger { - &self.inner.ledger - } - pub fn source(&self) -> &(dyn ProcSource + Send + Sync) { - &*self.inner.src - } - pub fn probe(&self) -> HostFacts { - HostFacts::probe(&*self.inner.src) - } - pub fn census(&self) -> Census { - Census::take(&*self.inner.src) - } - fn now_ms(&self) -> u64 { - self.inner.epoch.elapsed().as_millis() as u64 - } - pub fn log(&self, text: &str) { - if self.inner.cfg.log { - // Structured and rate limited like every other line; the lab scripts' bare form under LELEKA_LOG_LEGACY=1. - if leleka_obs::settings().legacy { - leleka_obs::legacy_line(&format!("leleka-memory: {text}")); - } else { - leleka_obs::emit_msg(leleka_obs::Level::Info, "memory", "leleka-memory:governor", text); - } - } - } - - // ---- plan ------------------------------------------------------------------------------------------------- - - /// Plan the budget (or refuse), log the plan, register the expected size of every fixed item in the inventory and keep - /// the plan for the report. - pub fn startup(&self, input: &crate::plan::PlanInput) -> Result { - let plan = match crate::plan::plan(input) { - Ok(plan) => plan, - Err(refusal) => { - self.log(&format!("REFUSING TO START: {refusal}")); - return Err(refusal); - } - }; - let inv = self.inventory(); - for item in &plan.fixed { - inv.set( - crate::inventory::Entry::new("planned", &item.name, item.space, crate::inventory::When::Startup, &item.formula) - .expected(item.bytes) - .swappable(false), - ); - } - self.log(&format!( - "budget: available {} - fixed {} - memfd to create {} = {} after the fixed footprint; floors soft {} / hard {}; elastic {}: resident complement {}, prefix cache {}, conversation checkpoints {} ({}){}", - plan.available_before.map_or("unknown".into(), gib), - gib(plan.fixed_bytes), - gib(plan.kar_to_create), - plan.available_after_fixed.map_or("unknown".into(), gib), - gib(plan.soft_floor), - gib(plan.hard_floor), - gib(plan.elastic), - gib(plan.resident_complement_bytes), - gib(plan.prefix_bytes), - plan.conversation_checkpoints, - gib(plan.conversation_bytes), - if plan.blind { "; BLIND: no memory telemetry, caches off" } else { "" } - )); - for note in &plan.notes { - self.log(&format!("note: {note}")); - } - self.set_plan(plan.clone()); - Ok(plan) - } - - /// The device check once the device is visible (`cuMemGetInfo`): refuse or note, and keep the numbers for the report. - pub fn check_vram(&self, vram: crate::plan::VramFacts, budget: u64, fixed_estimate: Option) -> Result<(), Refusal> { - match crate::plan::check_vram(&self.policy(), vram, budget, fixed_estimate) { - Ok((plan, note)) => { - if let Some(note) = note { - self.log(&format!("note: {note}")); - } - *lock(&self.inner.vram) = Some(plan); - Ok(()) - } - Err(refusal) => { - self.log(&format!("REFUSING TO START: {refusal}")); - Err(refusal) - } - } - } - - /// Compare the plan's prediction with what the host really has after the stack opened, log the error when it matters and keep it for the - /// report (`plan_check`). Returns `actual - predicted` in bytes (negative: the footprint was bigger than planned). - pub fn note_post_load(&self, actual_available: Option) -> Option { - let predicted = lock(&self.inner.plan).as_ref().and_then(|p| p.available_after_fixed)?; - let actual = actual_available?; - *lock(&self.inner.post_load) = Some((predicted, actual)); - let error = i128::from(actual) - i128::from(predicted); - let error = i64::try_from(error).unwrap_or(if error < 0 { i64::MIN } else { i64::MAX }); - if error.unsigned_abs() > 512 * MIB { - self.log(&format!( - "WARNING: the startup plan predicted {} available after the fixed footprint, the host has {} after the stack opened ({:+} MiB): the footprint constants are off, caches are sized from the measured value", - gib(predicted), - gib(actual), - error >> 20 - )); - } - Some(error) - } - - pub fn set_plan(&self, plan: Plan) { - self.inner.prefix_planned.store(plan.prefix_bytes, Ordering::Release); - *lock(&self.inner.plan) = Some(plan); - } - pub fn plan(&self) -> Option { - lock(&self.inner.plan).clone() - } - /// The prefix budget decided at stack open (after the fixed items are resident); the shed target is relative to it. - pub fn set_prefix_budget(&self, bytes: u64) { - self.inner.prefix_planned.store(bytes, Ordering::Release); - } - - // ---- level ------------------------------------------------------------------------------------------------ - - pub fn level(&self) -> Level { - Level::from_u8(self.inner.level.load(Ordering::Acquire)) - } - - /// The caller's own sample when the sampler thread has not delivered one for five intervals (it died, or was never started): - /// a stuck `reject` must not outlive the thread that would have lifted it, so the owner thread drives the monitor itself. - fn ensure_fresh(&self) { - let interval = self.inner.cfg.sample_interval_ms.max(50); - let now = self.now_ms(); - let last = self.inner.sampled_at_ms.load(Ordering::Acquire); - if now.saturating_sub(last) > interval.saturating_mul(5) && self.inner.counters.samples.load(Ordering::Relaxed) > 0 { - self.sample_at(now); - } - } - /// A fresh reading of the effective available memory (one probe of a dozen small files). - pub fn available_now(&self) -> Option { - self.probe().effective_available() - } - /// The last sampled value (at most one sample interval old); `None` before the first sample or when unknown. - pub fn available_cached(&self) -> Option { - match self.inner.available.load(Ordering::Acquire) { - NONE => None, - v => Some(v), - } - } - - /// Take a sample now and apply it. Returns the transition, if any. - pub fn sample_now(&self) -> Option { - self.sample_at(self.now_ms()) - } - - pub fn sample_at(&self, at_ms: u64) -> Option { - let facts = self.relieve_working_set(self.probe()); - let sample = Sample { - at_ms, - available: facts.effective_available(), - psi: facts.psi, - events: facts.cgroup.as_ref().and_then(|c| c.events), - pswpout: facts.pswpout, - }; - self.inner.counters.samples.fetch_add(1, Ordering::Relaxed); - self.inner.available.store(sample.available.unwrap_or(NONE), Ordering::Release); - self.inner.sampled_at_ms.store(at_ms, Ordering::Release); - let transition = lock(&self.inner.monitor).update(&sample); - if let Some(t) = &transition { - self.inner.level.store(t.to as u8, Ordering::Release); - self.inner.since_ms.store(at_ms, Ordering::Release); - *lock(&self.inner.reason) = t.reason.0.clone(); - self.inner.counters.level_changes.fetch_add(1, Ordering::Relaxed); - let mut q = lock(&self.inner.transitions); - if q.len() >= 32 { - q.pop_front(); - } - q.push_back(TransitionRecord { at_ms, from: t.from, to: t.to, reason: t.reason.0.clone() }); - drop(q); - self.log(&format!("memory pressure {} -> {}: {}", t.from.as_str(), t.to.as_str(), t.reason.0)); - } - transition - } - - // ---- admission and shedding ------------------------------------------------------------------------------- - - /// May this request start? Context first (a request that can never fit is a 400, not a retry), then the pressure level, - /// then whether its own transient memory would take the host below the hard floor. - pub fn admit(&self, shape: &RequestShape) -> Admission { - let c = &self.inner.counters; - let needed = shape.prompt_tokens.saturating_add(shape.max_new_tokens).saturating_add(8); - if needed > shape.max_context { - c.rejected_context.fetch_add(1, Ordering::Relaxed); - return Admission::Refuse(Refuse { - status: 400, - code: "context_length_exceeded", - message: format!( - "the request needs {needed} tokens (prompt {} + up to {} new + 8) but the pinned K/V image holds {} tokens", - shape.prompt_tokens, shape.max_new_tokens, shape.max_context - ), - retry_after_secs: 0, - }); - } - self.ensure_fresh(); - let level = self.level(); - let retry = lock(&self.inner.monitor).retry_after_secs().max(1); - if level == Level::Reject { - c.rejected_pressure.fetch_add(1, Ordering::Relaxed); - return Admission::Refuse(Refuse { - status: 503, - code: "memory_pressure", - message: format!("host memory is under pressure ({}); retry shortly", lock(&self.inner.reason)), - retry_after_secs: retry, - }); - } - // the transient of one request (checkpoint / node state / import staging) must not take the host below the hard floor - let transient = self.policy().reserve / 4; - if let Some(available) = self.available_now() - && available.saturating_sub(transient) < self.policy().hard_floor { - c.rejected_pressure.fetch_add(1, Ordering::Relaxed); - return Admission::Refuse(Refuse { - status: 503, - code: "memory_pressure", - message: format!( - "{} available is within {} of the hard floor {}; retry shortly", - gib(available), - gib(transient), - gib(self.policy().hard_floor) - ), - retry_after_secs: retry, - }); - } - c.admitted.fetch_add(1, Ordering::Relaxed); - Admission::Admit - } - - /// Windows keeps touched mapped pages in the working set, where they count as used. When the host reads below the soft floor, hand them back to - /// the standby list (at most every 250 ms) and read the host again, so that a dip caused only by trimmable mapped pages never reaches the monitor: - /// a shed evicts prefix-cache blocks, and live runs showed it firing every few seconds at the floor (laptop 256k session, 2026-10-26: 113 blocks - /// evicted, the fourth turn re-read 223k tokens in 32 minutes). - fn relieve_working_set(&self, facts: HostFacts) -> HostFacts { - self.relieve_working_set_below(facts, self.policy().soft_floor) - } - - /// The available memory after handing the engine's trimmable working-set pages back, for a cache owner that needs `needed` bytes of it - /// (a prefix-cache checkpoint must leave the admit floor free: a reading of 8.9 GiB against a floor of 9.2 GiB refused a 0.2 GiB checkpoint - /// that the very next trim would have admitted, because the periodic trim only runs below the soft floor). At most one trim per 250 ms. - pub fn available_after_relief(&self, needed: u64) -> Option { - let facts = self.probe(); - self.relieve_working_set_below(facts, needed).effective_available() - } - - fn relieve_working_set_below(&self, facts: HostFacts, threshold: u64) -> HostFacts { - if !cfg!(windows) { - return facts; - } - // A/B inside one engine (bring-up): no trim while the file named by LELEKA_NO_TRIM_FILE exists - static NO_TRIM_FILE: OnceLock> = OnceLock::new(); - if NO_TRIM_FILE.get_or_init(|| std::env::var_os("LELEKA_NO_TRIM_FILE").map(std::path::PathBuf::from)).as_ref().is_some_and(|f| f.exists()) { - return facts; - } - let Some(available) = facts.effective_available() else { return facts }; - if available >= threshold { - return facts; - } - let now = self.now_ms(); - let last = self.inner.last_trim_ms.load(Ordering::Acquire); - if last != NONE && now.saturating_sub(last) < WORKING_SET_TRIM_EVERY.as_millis() as u64 { - return facts; - } - self.inner.last_trim_ms.store(now, Ordering::Release); - if !crate::winproc::trim_working_set() { - return facts; - } - let after = self.probe(); - let trims = self.inner.trims.fetch_add(1, Ordering::Relaxed) + 1; - if trims == 1 || now.saturating_sub(self.inner.last_trim_log_ms.load(Ordering::Relaxed)) >= 10_000 { - self.inner.last_trim_log_ms.store(now, Ordering::Relaxed); - self.log(&format!( - "working set trimmed (#{trims}): available {} -> {} MiB", - available >> 20, - after.effective_available().unwrap_or(0) >> 20 - )); - } - after - } - - /// What the cache owners must do at this level. The prefix target steps down by a quarter per second while shedding. - pub fn directive(&self, prefix_used: u64) -> ShedDirective { - self.ensure_fresh(); - let level = self.level(); - let planned = self.inner.prefix_planned.load(Ordering::Acquire); - self.inner.prefix_used.store(prefix_used, Ordering::Release); - match level { - Level::Normal => { - self.inner.prefix_target.store(NONE, Ordering::Release); - ShedDirective { level, prefix_budget: None, drop_conversation: false } - } - Level::Shed => { - let now = self.now_ms(); - let last = self.inner.last_shed_ms.load(Ordering::Acquire); - let current = self.inner.prefix_target.load(Ordering::Acquire); - let target = if current == NONE || now.saturating_sub(last) >= 1000 { - let base = if current == NONE { prefix_used.min(planned) } else { current.min(prefix_used) }; - let next = base / 4 * 3; - self.inner.prefix_target.store(next, Ordering::Release); - self.inner.last_shed_ms.store(now, Ordering::Release); - self.inner.counters.shed_steps.fetch_add(1, Ordering::Relaxed); - next - } else { - current - }; - ShedDirective { level, prefix_budget: Some(target), drop_conversation: true } - } - Level::Reject => { - self.inner.prefix_target.store(0, Ordering::Release); - ShedDirective { level, prefix_budget: Some(0), drop_conversation: true } - } - } - } - - pub fn note_prefix_used(&self, bytes: u64) { - self.inner.prefix_used.store(bytes, Ordering::Release); - } - pub fn note_evicted(&self, bytes: u64) { - self.inner.counters.evicted_bytes.fetch_add(bytes, Ordering::Relaxed); - } - - // ---- the sealed memfd --------------------------------------------------------------------------------------- - - /// Map the sealed archive, lock it when the limits allow, and keep the mapping for the residency guard. - #[cfg(all(target_os = "linux", target_pointer_width = "64"))] - pub fn guard_archive(&self, fd: std::os::fd::BorrowedFd<'_>, len: u64) -> Result { - self.guard_archive_extents(fd, len, None) - } - - /// [`Self::guard_archive`] for a sparse memfd: `extents` are the `(offset, len)` ranges that hold data, everything else of the - /// `len`-byte descriptor is a hole. Only the extents are locked and healed (locking or populating a hole allocates zero - /// pages for it, which would turn the sparse copy back into the full archive), the lock limit is judged against their - /// size, and the report says so. `None` is the whole archive. - #[cfg(all(target_os = "linux", target_pointer_width = "64"))] - pub fn guard_archive_extents(&self, fd: std::os::fd::BorrowedFd<'_>, len: u64, extents: Option<&[crate::lock::Span]>) -> Result { - let started = Instant::now(); - let facts = self.probe(); - let mode = self.inner.cfg.lock_mode; - if let Some(spans) = extents - && let Err(why) = crate::lock::check_spans(spans, len) - { - return Err(Refusal { code: "memlock", message: format!("the sparse archive extents are invalid: {why}"), numbers: vec![("archive".to_owned(), len)], advice: vec![] }); - } - // the bytes that are resident and have to be locked - let resident = extents.map_or(len, crate::lock::spans_bytes); - let extent_bytes = extents.map(crate::lock::spans_bytes); - let decision = plan_lock(mode, resident, facts.memlock, &facts.status); - // Map a private READ-ONLY reopen of the descriptor, never the descriptor itself: a write-sealed memfd refuses a shared - // mapping that could become writable (EPERM on kernels up to 5.15 when the description is read-write), and a read-only - // description can never become writable, so the mapping is allowed everywhere and is immutable by construction. - let readonly = { - use std::os::fd::AsRawFd; - std::fs::OpenOptions::new().read(true).open(format!("/proc/self/fd/{}", fd.as_raw_fd())) - }; - let mapped = match &readonly { - Ok(file) => { - use std::os::fd::AsFd as _; - crate::lock::FdMapping::map_readonly(file.as_fd(), usize::try_from(len).unwrap_or(usize::MAX)) - } - Err(e) => Err(std::io::Error::new(e.kind(), format!("cannot reopen the descriptor read-only: {e}"))), - }; - let mut mapping = match mapped { - Ok(m) => m, - Err(e) => { - let report = LockReport { - mode, - decision, - outcome: LockOutcome::NotAttempted { why: format!("mmap of the archive failed: {e}") }, - mapping_bytes: 0, - extent_bytes, - memlock_soft: facts.memlock.map(|m| m.0), - memlock_hard: facts.memlock.map(|m| m.1), - millis: started.elapsed().as_secs_f64() * 1e3, - }; - self.log(&format!("WARNING: cannot map the sealed KAR memfd for the residency guard: {e}")); - if mode == LockMode::Require { - return Err(Refusal { code: "memlock", message: format!("mmap of the archive failed: {e}"), numbers: vec![], advice: vec![] }); - } - return Ok(report); - } - }; - let outcome = match &decision { - LockDecision::Off => LockOutcome::NotAttempted { why: "LELEKA_MEMORY_LOCK=off".into() }, - LockDecision::Insufficient { need, soft, hard, advice } => { - let why = format!( - "RLIMIT_MEMLOCK soft {} MiB / hard {} MiB cannot cover {} MiB", - soft >> 20, - if *hard == u64::MAX { "unlimited".into() } else { (hard >> 20).to_string() }, - need >> 20 - ); - self.log(&format!("WARNING: the sealed KAR memfd ({}) stays swappable: {why}. To keep it resident: {}", gib(resident), advice.join(" | "))); - LockOutcome::NotAttempted { why } - } - LockDecision::Attempt { raise_soft_to } => { - if let Some(to) = raise_soft_to - && let Err(e) = crate::lock::raise_memlock_soft(*to) { - self.log(&format!("WARNING: could not raise the soft RLIMIT_MEMLOCK to {} MiB: {e}", to >> 20)); - } - let policy = self.policy(); - let swapped = self.mapping_swapped(&mapping).unwrap_or(0); - let src = self.inner.src.clone(); - let allow = |n: u64| { - // a swapped-out chunk is read back into RAM: keep the hard floor + reserve - let need = if swapped > 0 { n } else { 0 }; - HostFacts::probe(&*src).effective_available().is_none_or(|a| a.saturating_sub(need) >= policy.hard_floor + policy.reserve) - }; - let outcome = match extents { - Some(spans) => mapping.lock_ranges(spans, GIB, allow), - None => mapping.lock(GIB, allow), - }; - match &outcome { - LockOutcome::Locked { bytes } => self.log(&format!("sealed KAR memfd locked in RAM: {} (mlock, never swapped)", gib(*bytes))), - LockOutcome::Partial { locked, why, .. } => self.log(&format!("WARNING: sealed KAR memfd lock stopped at {} of {}: {why}", gib(*locked), gib(len))), - LockOutcome::NotAttempted { why } => self.log(&format!("sealed KAR memfd lock not attempted: {why}")), - } - outcome - } - }; - let report = LockReport { - mode, - decision: decision.clone(), - outcome: outcome.clone(), - mapping_bytes: len, - extent_bytes, - memlock_soft: facts.memlock.map(|m| m.0), - memlock_hard: facts.memlock.map(|m| m.1), - millis: started.elapsed().as_secs_f64() * 1e3, - }; - if mode == LockMode::Require && !matches!(outcome, LockOutcome::Locked { .. }) { - let (numbers, advice) = match &decision { - LockDecision::Insufficient { need, soft, hard, advice } => ( - vec![("needed to lock".to_owned(), *need), ("RLIMIT_MEMLOCK soft".to_owned(), *soft), ("RLIMIT_MEMLOCK hard".to_owned(), *hard)], - advice.clone(), - ), - _ => (vec![("archive".to_owned(), resident)], vec![]), - }; - return Err(Refusal { code: "memlock", message: format!("LELEKA_MEMORY_LOCK=require but the sealed KAR memfd could not be locked ({outcome:?})"), numbers, advice }); - } - *lock(&self.inner.guarded) = Some(Guarded { mapping, report: report.clone(), extents: extents.map(<[_]>::to_vec), cursor: 0, last_swapped: 0, warned_swapped: 0, last_check: None, last: None }); - Ok(report) - } - - #[cfg(all(target_os = "linux", target_pointer_width = "64"))] - fn mapping_swapped(&self, mapping: &crate::lock::FdMapping) -> Option { - let text = self.inner.src.read("/proc/self/smaps").ok()?; - residency_from_smaps(&text, mapping.start(), mapping.len()).map(|r| r.swapped_bytes) - } - - /// Read the swap state of the archive mapping; warn when pages are swapped; pull them back when allowed. - /// Returns the swapped bytes found (0 when no mapping is guarded). - #[cfg(all(target_os = "linux", target_pointer_width = "64"))] - pub fn residency_tick(&self) -> u64 { - let policy = self.policy(); - let mut slot = lock(&self.inner.guarded); - let Some(g) = slot.as_mut() else { return 0 }; - let started = Instant::now(); - let Some(text) = self.inner.src.read("/proc/self/smaps").ok() else { return 0 }; - let Some(r) = residency_from_smaps(&text, g.mapping.start(), g.mapping.len()) else { return 0 }; - let read_ms = started.elapsed().as_secs_f64() * 1e3; - g.last = Some(r); - g.last_check = Some(Instant::now()); - g.last_swapped = r.swapped_bytes; - if r.swapped_bytes >= 64 * MIB && r.swapped_bytes.abs_diff(g.warned_swapped) >= 64 * MIB { - g.warned_swapped = r.swapped_bytes; - self.log(&format!( - "WARNING: {} MiB of the sealed KAR memfd are swapped out ({} of {} resident, locked {} MiB; smaps read {read_ms:.0} ms): PLE reads fault from swap until they are pulled back{}", - r.swapped_bytes >> 20, - gib(r.rss_bytes), - gib(r.mapping_bytes), - r.locked_bytes >> 20, - if self.inner.cfg.heal { "; healing" } else { "" } - )); - } else if r.swapped_bytes < 64 * MIB { - g.warned_swapped = 0; - } - if self.inner.cfg.heal && r.swapped_bytes >= 16 * MIB && self.level() == Level::Normal { - let budget = self.inner.cfg.heal_bytes_per_tick.min(r.swapped_bytes.max(GIB)); - let ok = HostFacts::probe(&*self.inner.src) - .effective_available() - .is_some_and(|a| a.saturating_sub(budget.min(r.swapped_bytes)) >= policy.soft_floor + policy.reserve); - if ok { - let mut done = 0; - match g.extents.clone() { - // a sparse archive: walk the concatenation of the extents, never a hole - Some(spans) => { - let total = crate::lock::spans_bytes(&spans); - while done < budget && done < total { - if g.cursor >= total { - g.cursor = 0; - } - let want = (256 * MIB).min(budget - done); - let Some((offset, piece)) = crate::lock::compact_piece(&spans, g.cursor, want) else { break }; - // whole pages; the last page of the last extent may be partial and is rounded up by the kernel - let n = if g.cursor + piece == total || piece < 4096 { piece } else { piece / 4096 * 4096 }; - if g.mapping.populate(offset, n).is_err() { - break; - } - g.cursor += n; - done += n; - } - } - None => { - let total = g.mapping.len(); - while done < budget && done < total { - if g.cursor >= total { - g.cursor = 0; - } - let n = (256 * MIB).min(total - g.cursor).min(budget - done) / 4096 * 4096; - if n == 0 { - break; - } - if g.mapping.populate(g.cursor, n).is_err() { - break; - } - g.cursor += n; - done += n; - } - } - } - self.inner.counters.heal_bytes.fetch_add(done, Ordering::Relaxed); - self.inner.counters.heal_runs.fetch_add(1, Ordering::Relaxed); - } - } - r.swapped_bytes - } - - #[cfg(not(all(target_os = "linux", target_pointer_width = "64")))] - pub fn residency_tick(&self) -> u64 { - 0 - } - - // ---- report ----------------------------------------------------------------------------------------------- - - pub fn report(&self) -> serde_json::Value { - let facts = self.probe(); - let monitor = lock(&self.inner.monitor); - let policy = self.policy(); - let level = self.level(); - let c = &self.inner.counters; - let planned = self.inner.prefix_planned.load(Ordering::Acquire); - let target = self.inner.prefix_target.load(Ordering::Acquire); - #[cfg(all(target_os = "linux", target_pointer_width = "64"))] - let archive = lock(&self.inner.guarded).as_ref().map(|g| json!({"lock": g.report, "residency": g.last, "heal": {"cursor": g.cursor}})); - #[cfg(not(all(target_os = "linux", target_pointer_width = "64")))] - let archive: Option = None; - json!({ - "version": 1, - "uptime_ms": self.now_ms(), - "gate": { - "level": level.as_str(), - "since_ms": self.inner.since_ms.load(Ordering::Acquire), - "reason": &*lock(&self.inner.reason), - "retry_after_secs": if level == Level::Normal { 0 } else { monitor.retry_after_secs() }, - "available_bytes": self.available_cached(), - "soft_floor_bytes": policy.soft_floor, - "hard_floor_bytes": policy.hard_floor, - }, - "policy": policy, - "config": {"sample_interval_ms": self.inner.cfg.sample_interval_ms, "lock_mode": self.inner.cfg.lock_mode, "heal": self.inner.cfg.heal}, - "plan": self.plan(), - "host": { - "mem_total": facts.meminfo.mem_total, - "mem_available": facts.meminfo.mem_available, - "effective_available": facts.effective_available(), - "swap_total": facts.meminfo.swap_total, - "swap_free": facts.meminfo.swap_free, - "shmem": facts.meminfo.shmem, - "mlocked": facts.meminfo.mlocked, - "cgroup": facts.cgroup, - "psi": facts.psi, - "memlock": facts.memlock, - "wsl": facts.wsl, - "kernel": facts.kernel, - }, - "process": { - "rss": facts.status.vm_rss, "swap": facts.status.vm_swap, "pinned": facts.status.vm_pin, "locked": facts.status.vm_lck, - "threads": facts.status.threads, "fds": facts.open_fds, - }, - "observed": monitor.observed, - "caches": { - "prefix": {"planned_bytes": planned, "shed_target_bytes": if target == NONE { serde_json::Value::Null } else { json!(target) }, "used_bytes": self.inner.prefix_used.load(Ordering::Acquire)}, - }, - "counters": { - "admitted": c.admitted.load(Ordering::Relaxed), - "rejected_memory_pressure": c.rejected_pressure.load(Ordering::Relaxed), - "rejected_context": c.rejected_context.load(Ordering::Relaxed), - "shed_steps": c.shed_steps.load(Ordering::Relaxed), - "evicted_bytes": c.evicted_bytes.load(Ordering::Relaxed), - "samples": c.samples.load(Ordering::Relaxed), - "level_changes": c.level_changes.load(Ordering::Relaxed), - "heal_bytes": c.heal_bytes.load(Ordering::Relaxed), - "heal_runs": c.heal_runs.load(Ordering::Relaxed), - }, - "archive": archive, - "inventory": self.inventory().to_json(), - "ledger": self.inner.ledger.to_json(), - "vram": &*lock(&self.inner.vram), - "plan_check": lock(&self.inner.post_load).map(|(p, a)| json!({"predicted_available_after_fixed": p, "actual_available_after_open": a, "error_bytes": i128::from(a) - i128::from(p)})), - "transitions": &*lock(&self.inner.transitions), - }) - } - - /// Render the report into the cell [`published_report`] reads. - pub fn publish(&self) { - if let Ok(text) = serde_json::to_string(&self.report()) { - *PUBLISHED.lock().unwrap_or_else(|p| p.into_inner()) = Some(text); - } - } - - // ---- sampler ----------------------------------------------------------------------------------------------- - - /// Start the sampler thread (pressure level and report, every interval) and the residency-guard thread (the smaps read of - /// the memfd mapping costs up to a second for 55 GB, which must not delay a pressure sample). Both stop when the guard is - /// dropped. - pub fn spawn_sampler(&self) -> SamplerGuard { - fn nap(inner: &Inner, total: Duration) { - let mut slept = Duration::ZERO; - while slept < total && !inner.stop.load(Ordering::Acquire) { - let step = Duration::from_millis(50).min(total - slept); - std::thread::sleep(step); - slept += step; - } - } - self.inner.stop.store(false, Ordering::Release); - let me = self.clone(); - let sampler = std::thread::Builder::new() - .name("leleka-memory".into()) - .spawn(move || { - let interval = Duration::from_millis(me.inner.cfg.sample_interval_ms); - while !me.inner.stop.load(Ordering::Acquire) { - // a panic in one round (a malformed /proc read, a poisoned state) must not end the thread that lifts a pressure level - let round = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { - me.sample_now(); - me.publish(); - })); - if round.is_err() { - me.log("WARNING: the memory sampler round panicked; continuing"); - } - nap(&me.inner, interval); - } - }) - .ok(); - let me = self.clone(); - let guard = std::thread::Builder::new() - .name("leleka-memory-guard".into()) - .spawn(move || { - let every = Duration::from_millis(me.inner.cfg.residency_every_ms); - while !me.inner.stop.load(Ordering::Acquire) { - let round = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| me.residency_tick())); - if round.is_err() { - me.log("WARNING: the memfd residency round panicked; continuing"); - } - nap(&me.inner, every); - } - }) - .ok(); - SamplerGuard { inner: self.inner.clone(), handles: sampler.into_iter().chain(guard).collect() } - } -} - /// Stops the sampler thread when dropped. pub struct SamplerGuard { inner: Arc, handles: Vec>, } -impl Drop for SamplerGuard { - fn drop(&mut self) { - self.inner.stop.store(true, Ordering::Release); - for h in self.handles.drain(..) { - let _ = h.join(); - } - } -} - #[cfg(test)] mod tests; + +mod impl_governorconfig; +#[allow(unused_imports)] +pub use impl_governorconfig::*; +mod impl_governor; +#[allow(unused_imports)] +pub use impl_governor::*; +mod impl_drop_for_samplerguard; +#[allow(unused_imports)] +pub use impl_drop_for_samplerguard::*; diff --git a/crates/leleka-memory/src/governor/impl_drop_for_samplerguard.rs b/crates/leleka-memory/src/governor/impl_drop_for_samplerguard.rs new file mode 100644 index 00000000..1b557815 --- /dev/null +++ b/crates/leleka-memory/src/governor/impl_drop_for_samplerguard.rs @@ -0,0 +1,14 @@ +//! Moved out of the parent module by STRA-338: impl Drop_for_SamplerGuard. + +#[allow(unused_imports)] +use super::*; + + +impl Drop for SamplerGuard { + fn drop(&mut self) { + self.inner.stop.store(true, Ordering::Release); + for h in self.handles.drain(..) { + let _ = h.join(); + } + } +} diff --git a/crates/leleka-memory/src/governor/impl_governor.rs b/crates/leleka-memory/src/governor/impl_governor.rs new file mode 100644 index 00000000..a277946d --- /dev/null +++ b/crates/leleka-memory/src/governor/impl_governor.rs @@ -0,0 +1,739 @@ +//! Moved out of the parent module by STRA-338: impl Governor. + +#[allow(unused_imports)] +use super::*; + + +impl Governor { + pub fn new(cfg: GovernorConfig, src: Arc) -> Self { + let policy0 = cfg.policy; + let monitor = Monitor::new(policy0); + Self { + inner: Arc::new(Inner { + cfg, + src, + epoch: Instant::now(), + plan: Mutex::new(None), + monitor: Mutex::new(monitor), + policy: Mutex::new(policy0), + level: AtomicU8::new(Level::Normal as u8), + reason: Mutex::new("startup".into()), + available: AtomicU64::new(NONE), + sampled_at_ms: AtomicU64::new(0), + prefix_planned: AtomicU64::new(0), + prefix_target: AtomicU64::new(NONE), + prefix_used: AtomicU64::new(0), + last_shed_ms: AtomicU64::new(0), + last_trim_ms: AtomicU64::new(NONE), + last_trim_log_ms: AtomicU64::new(0), + trims: AtomicU64::new(0), + since_ms: AtomicU64::new(0), + transitions: Mutex::new(VecDeque::new()), + counters: Counters::default(), + ledger: Ledger::new(), + vram: Mutex::new(None), + post_load: Mutex::new(None), + #[cfg(all(target_os = "linux", target_pointer_width = "64"))] + guarded: Mutex::new(None), + stop: AtomicBool::new(false), + }), + } + } + + /// A governor over the real `/proc`. + pub fn real(cfg: GovernorConfig) -> Self { + Self::new(cfg, Arc::new(RealProc)) + } + + /// Make this the process-wide governor (the first install wins; later ones are returned unchanged). + pub fn install(self) -> &'static Governor { + GLOBAL.get_or_init(|| self) + } + pub fn global() -> Option<&'static Governor> { + GLOBAL.get() + } + + /// Replace the pressure floors at run time (diagnostics and the shed tests: move the thresholds next to the memory + /// the host has now, so the whole shed path runs without ever approaching the real limit). `hard < soft` is required. + pub fn set_floors(&self, soft_floor: u64, hard_floor: u64) -> Result<(), String> { + if hard_floor >= soft_floor { + return Err(format!("hard floor {hard_floor} must be below the soft floor {soft_floor}")); + } + let mut policy = lock(&self.inner.policy); + policy.soft_floor = soft_floor; + policy.hard_floor = hard_floor; + lock(&self.inner.monitor).set_policy(*policy); + drop(policy); + self.log(&format!("floors set to soft {} MiB / hard {} MiB", soft_floor >> 20, hard_floor >> 20)); + Ok(()) + } + + pub fn config(&self) -> &GovernorConfig { + &self.inner.cfg + } + pub fn policy(&self) -> Policy { + *lock(&self.inner.policy) + } + pub fn inventory(&self) -> &'static Inventory { + Inventory::global() + } + pub fn ledger(&self) -> &Ledger { + &self.inner.ledger + } + pub fn source(&self) -> &(dyn ProcSource + Send + Sync) { + &*self.inner.src + } + pub fn probe(&self) -> HostFacts { + HostFacts::probe(&*self.inner.src) + } + pub fn census(&self) -> Census { + Census::take(&*self.inner.src) + } + pub(super) fn now_ms(&self) -> u64 { + self.inner.epoch.elapsed().as_millis() as u64 + } + pub fn log(&self, text: &str) { + if self.inner.cfg.log { + // Structured and rate limited like every other line; the lab scripts' bare form under LELEKA_LOG_LEGACY=1. + if leleka_obs::settings().legacy { + leleka_obs::legacy_line(&format!("leleka-memory: {text}")); + } else { + leleka_obs::emit_msg(leleka_obs::Level::Info, "memory", "leleka-memory:governor", text); + } + } + } + + // ---- plan ------------------------------------------------------------------------------------------------- + + /// Plan the budget (or refuse), log the plan, register the expected size of every fixed item in the inventory and keep + /// the plan for the report. + pub fn startup(&self, input: &crate::plan::PlanInput) -> Result { + let plan = match crate::plan::plan(input) { + Ok(plan) => plan, + Err(refusal) => { + self.log(&format!("REFUSING TO START: {refusal}")); + return Err(refusal); + } + }; + let inv = self.inventory(); + for item in &plan.fixed { + inv.set( + crate::inventory::Entry::new("planned", &item.name, item.space, crate::inventory::When::Startup, &item.formula) + .expected(item.bytes) + .swappable(false), + ); + } + self.log(&format!( + "budget: available {} - fixed {} - memfd to create {} = {} after the fixed footprint; floors soft {} / hard {}; elastic {}: resident complement {}, prefix cache {}, conversation checkpoints {} ({}){}", + plan.available_before.map_or("unknown".into(), gib), + gib(plan.fixed_bytes), + gib(plan.kar_to_create), + plan.available_after_fixed.map_or("unknown".into(), gib), + gib(plan.soft_floor), + gib(plan.hard_floor), + gib(plan.elastic), + gib(plan.resident_complement_bytes), + gib(plan.prefix_bytes), + plan.conversation_checkpoints, + gib(plan.conversation_bytes), + if plan.blind { "; BLIND: no memory telemetry, caches off" } else { "" } + )); + for note in &plan.notes { + self.log(&format!("note: {note}")); + } + self.set_plan(plan.clone()); + Ok(plan) + } + + /// The device check once the device is visible (`cuMemGetInfo`): refuse or note, and keep the numbers for the report. + pub fn check_vram(&self, vram: crate::plan::VramFacts, budget: u64, fixed_estimate: Option) -> Result<(), Refusal> { + match crate::plan::check_vram(&self.policy(), vram, budget, fixed_estimate) { + Ok((plan, note)) => { + if let Some(note) = note { + self.log(&format!("note: {note}")); + } + *lock(&self.inner.vram) = Some(plan); + Ok(()) + } + Err(refusal) => { + self.log(&format!("REFUSING TO START: {refusal}")); + Err(refusal) + } + } + } + + /// Compare the plan's prediction with what the host really has after the stack opened, log the error when it matters and keep it for the + /// report (`plan_check`). Returns `actual - predicted` in bytes (negative: the footprint was bigger than planned). + pub fn note_post_load(&self, actual_available: Option) -> Option { + let predicted = lock(&self.inner.plan).as_ref().and_then(|p| p.available_after_fixed)?; + let actual = actual_available?; + *lock(&self.inner.post_load) = Some((predicted, actual)); + let error = i128::from(actual) - i128::from(predicted); + let error = i64::try_from(error).unwrap_or(if error < 0 { i64::MIN } else { i64::MAX }); + if error.unsigned_abs() > 512 * MIB { + self.log(&format!( + "WARNING: the startup plan predicted {} available after the fixed footprint, the host has {} after the stack opened ({:+} MiB): the footprint constants are off, caches are sized from the measured value", + gib(predicted), + gib(actual), + error >> 20 + )); + } + Some(error) + } + + pub fn set_plan(&self, plan: Plan) { + self.inner.prefix_planned.store(plan.prefix_bytes, Ordering::Release); + *lock(&self.inner.plan) = Some(plan); + } + pub fn plan(&self) -> Option { + lock(&self.inner.plan).clone() + } + /// The prefix budget decided at stack open (after the fixed items are resident); the shed target is relative to it. + pub fn set_prefix_budget(&self, bytes: u64) { + self.inner.prefix_planned.store(bytes, Ordering::Release); + } + + // ---- level ------------------------------------------------------------------------------------------------ + + pub fn level(&self) -> Level { + Level::from_u8(self.inner.level.load(Ordering::Acquire)) + } + + /// The caller's own sample when the sampler thread has not delivered one for five intervals (it died, or was never started): + /// a stuck `reject` must not outlive the thread that would have lifted it, so the owner thread drives the monitor itself. + pub(super) fn ensure_fresh(&self) { + let interval = self.inner.cfg.sample_interval_ms.max(50); + let now = self.now_ms(); + let last = self.inner.sampled_at_ms.load(Ordering::Acquire); + if now.saturating_sub(last) > interval.saturating_mul(5) && self.inner.counters.samples.load(Ordering::Relaxed) > 0 { + self.sample_at(now); + } + } + /// A fresh reading of the effective available memory (one probe of a dozen small files). + pub fn available_now(&self) -> Option { + self.probe().effective_available() + } + /// The last sampled value (at most one sample interval old); `None` before the first sample or when unknown. + pub fn available_cached(&self) -> Option { + match self.inner.available.load(Ordering::Acquire) { + NONE => None, + v => Some(v), + } + } + + /// Take a sample now and apply it. Returns the transition, if any. + pub fn sample_now(&self) -> Option { + self.sample_at(self.now_ms()) + } + + pub fn sample_at(&self, at_ms: u64) -> Option { + let facts = self.relieve_working_set(self.probe()); + let sample = Sample { + at_ms, + available: facts.effective_available(), + psi: facts.psi, + events: facts.cgroup.as_ref().and_then(|c| c.events), + pswpout: facts.pswpout, + }; + self.inner.counters.samples.fetch_add(1, Ordering::Relaxed); + self.inner.available.store(sample.available.unwrap_or(NONE), Ordering::Release); + self.inner.sampled_at_ms.store(at_ms, Ordering::Release); + let transition = lock(&self.inner.monitor).update(&sample); + if let Some(t) = &transition { + self.inner.level.store(t.to as u8, Ordering::Release); + self.inner.since_ms.store(at_ms, Ordering::Release); + *lock(&self.inner.reason) = t.reason.0.clone(); + self.inner.counters.level_changes.fetch_add(1, Ordering::Relaxed); + let mut q = lock(&self.inner.transitions); + if q.len() >= 32 { + q.pop_front(); + } + q.push_back(TransitionRecord { at_ms, from: t.from, to: t.to, reason: t.reason.0.clone() }); + drop(q); + self.log(&format!("memory pressure {} -> {}: {}", t.from.as_str(), t.to.as_str(), t.reason.0)); + } + transition + } + + // ---- admission and shedding ------------------------------------------------------------------------------- + + /// May this request start? Context first (a request that can never fit is a 400, not a retry), then the pressure level, + /// then whether its own transient memory would take the host below the hard floor. + pub fn admit(&self, shape: &RequestShape) -> Admission { + let c = &self.inner.counters; + let needed = shape.prompt_tokens.saturating_add(shape.max_new_tokens).saturating_add(8); + if needed > shape.max_context { + c.rejected_context.fetch_add(1, Ordering::Relaxed); + return Admission::Refuse(Refuse { + status: 400, + code: "context_length_exceeded", + message: format!( + "the request needs {needed} tokens (prompt {} + up to {} new + 8) but the pinned K/V image holds {} tokens", + shape.prompt_tokens, shape.max_new_tokens, shape.max_context + ), + retry_after_secs: 0, + }); + } + self.ensure_fresh(); + let level = self.level(); + let retry = lock(&self.inner.monitor).retry_after_secs().max(1); + if level == Level::Reject { + c.rejected_pressure.fetch_add(1, Ordering::Relaxed); + return Admission::Refuse(Refuse { + status: 503, + code: "memory_pressure", + message: format!("host memory is under pressure ({}); retry shortly", lock(&self.inner.reason)), + retry_after_secs: retry, + }); + } + // the transient of one request (checkpoint / node state / import staging) must not take the host below the hard floor + let transient = self.policy().reserve / 4; + if let Some(available) = self.available_now() + && available.saturating_sub(transient) < self.policy().hard_floor { + c.rejected_pressure.fetch_add(1, Ordering::Relaxed); + return Admission::Refuse(Refuse { + status: 503, + code: "memory_pressure", + message: format!( + "{} available is within {} of the hard floor {}; retry shortly", + gib(available), + gib(transient), + gib(self.policy().hard_floor) + ), + retry_after_secs: retry, + }); + } + c.admitted.fetch_add(1, Ordering::Relaxed); + Admission::Admit + } + + /// Windows keeps touched mapped pages in the working set, where they count as used. When the host reads below the soft floor, hand them back to + /// the standby list (at most every 250 ms) and read the host again, so that a dip caused only by trimmable mapped pages never reaches the monitor: + /// a shed evicts prefix-cache blocks, and live runs showed it firing every few seconds at the floor (laptop 256k session, 2026-10-26: 113 blocks + /// evicted, the fourth turn re-read 223k tokens in 32 minutes). + pub(super) fn relieve_working_set(&self, facts: HostFacts) -> HostFacts { + self.relieve_working_set_below(facts, self.policy().soft_floor) + } + + /// The available memory after handing the engine's trimmable working-set pages back, for a cache owner that needs `needed` bytes of it + /// (a prefix-cache checkpoint must leave the admit floor free: a reading of 8.9 GiB against a floor of 9.2 GiB refused a 0.2 GiB checkpoint + /// that the very next trim would have admitted, because the periodic trim only runs below the soft floor). At most one trim per 250 ms. + pub fn available_after_relief(&self, needed: u64) -> Option { + let facts = self.probe(); + self.relieve_working_set_below(facts, needed).effective_available() + } + + pub(super) fn relieve_working_set_below(&self, facts: HostFacts, threshold: u64) -> HostFacts { + if !cfg!(windows) { + return facts; + } + // A/B inside one engine (bring-up): no trim while the file named by LELEKA_NO_TRIM_FILE exists + static NO_TRIM_FILE: OnceLock> = OnceLock::new(); + if NO_TRIM_FILE.get_or_init(|| std::env::var_os("LELEKA_NO_TRIM_FILE").map(std::path::PathBuf::from)).as_ref().is_some_and(|f| f.exists()) { + return facts; + } + let Some(available) = facts.effective_available() else { return facts }; + if available >= threshold { + return facts; + } + let now = self.now_ms(); + let last = self.inner.last_trim_ms.load(Ordering::Acquire); + if last != NONE && now.saturating_sub(last) < WORKING_SET_TRIM_EVERY.as_millis() as u64 { + return facts; + } + self.inner.last_trim_ms.store(now, Ordering::Release); + if !crate::winproc::trim_working_set() { + return facts; + } + let after = self.probe(); + let trims = self.inner.trims.fetch_add(1, Ordering::Relaxed) + 1; + if trims == 1 || now.saturating_sub(self.inner.last_trim_log_ms.load(Ordering::Relaxed)) >= 10_000 { + self.inner.last_trim_log_ms.store(now, Ordering::Relaxed); + self.log(&format!( + "working set trimmed (#{trims}): available {} -> {} MiB", + available >> 20, + after.effective_available().unwrap_or(0) >> 20 + )); + } + after + } + + /// What the cache owners must do at this level. The prefix target steps down by a quarter per second while shedding. + pub fn directive(&self, prefix_used: u64) -> ShedDirective { + self.ensure_fresh(); + let level = self.level(); + let planned = self.inner.prefix_planned.load(Ordering::Acquire); + self.inner.prefix_used.store(prefix_used, Ordering::Release); + match level { + Level::Normal => { + self.inner.prefix_target.store(NONE, Ordering::Release); + ShedDirective { level, prefix_budget: None, drop_conversation: false } + } + Level::Shed => { + let now = self.now_ms(); + let last = self.inner.last_shed_ms.load(Ordering::Acquire); + let current = self.inner.prefix_target.load(Ordering::Acquire); + let target = if current == NONE || now.saturating_sub(last) >= 1000 { + let base = if current == NONE { prefix_used.min(planned) } else { current.min(prefix_used) }; + let next = base / 4 * 3; + self.inner.prefix_target.store(next, Ordering::Release); + self.inner.last_shed_ms.store(now, Ordering::Release); + self.inner.counters.shed_steps.fetch_add(1, Ordering::Relaxed); + next + } else { + current + }; + ShedDirective { level, prefix_budget: Some(target), drop_conversation: true } + } + Level::Reject => { + self.inner.prefix_target.store(0, Ordering::Release); + ShedDirective { level, prefix_budget: Some(0), drop_conversation: true } + } + } + } + + pub fn note_prefix_used(&self, bytes: u64) { + self.inner.prefix_used.store(bytes, Ordering::Release); + } + pub fn note_evicted(&self, bytes: u64) { + self.inner.counters.evicted_bytes.fetch_add(bytes, Ordering::Relaxed); + } + + // ---- the sealed memfd --------------------------------------------------------------------------------------- + + /// Map the sealed archive, lock it when the limits allow, and keep the mapping for the residency guard. + #[cfg(all(target_os = "linux", target_pointer_width = "64"))] + pub fn guard_archive(&self, fd: std::os::fd::BorrowedFd<'_>, len: u64) -> Result { + self.guard_archive_extents(fd, len, None) + } + + /// [`Self::guard_archive`] for a sparse memfd: `extents` are the `(offset, len)` ranges that hold data, everything else of the + /// `len`-byte descriptor is a hole. Only the extents are locked and healed (locking or populating a hole allocates zero + /// pages for it, which would turn the sparse copy back into the full archive), the lock limit is judged against their + /// size, and the report says so. `None` is the whole archive. + #[cfg(all(target_os = "linux", target_pointer_width = "64"))] + pub fn guard_archive_extents(&self, fd: std::os::fd::BorrowedFd<'_>, len: u64, extents: Option<&[crate::lock::Span]>) -> Result { + let started = Instant::now(); + let facts = self.probe(); + let mode = self.inner.cfg.lock_mode; + if let Some(spans) = extents + && let Err(why) = crate::lock::check_spans(spans, len) + { + return Err(Refusal { code: "memlock", message: format!("the sparse archive extents are invalid: {why}"), numbers: vec![("archive".to_owned(), len)], advice: vec![] }); + } + // the bytes that are resident and have to be locked + let resident = extents.map_or(len, crate::lock::spans_bytes); + let extent_bytes = extents.map(crate::lock::spans_bytes); + let decision = plan_lock(mode, resident, facts.memlock, &facts.status); + // Map a private READ-ONLY reopen of the descriptor, never the descriptor itself: a write-sealed memfd refuses a shared + // mapping that could become writable (EPERM on kernels up to 5.15 when the description is read-write), and a read-only + // description can never become writable, so the mapping is allowed everywhere and is immutable by construction. + let readonly = { + use std::os::fd::AsRawFd; + std::fs::OpenOptions::new().read(true).open(format!("/proc/self/fd/{}", fd.as_raw_fd())) + }; + let mapped = match &readonly { + Ok(file) => { + use std::os::fd::AsFd as _; + crate::lock::FdMapping::map_readonly(file.as_fd(), usize::try_from(len).unwrap_or(usize::MAX)) + } + Err(e) => Err(std::io::Error::new(e.kind(), format!("cannot reopen the descriptor read-only: {e}"))), + }; + let mut mapping = match mapped { + Ok(m) => m, + Err(e) => { + let report = LockReport { + mode, + decision, + outcome: LockOutcome::NotAttempted { why: format!("mmap of the archive failed: {e}") }, + mapping_bytes: 0, + extent_bytes, + memlock_soft: facts.memlock.map(|m| m.0), + memlock_hard: facts.memlock.map(|m| m.1), + millis: started.elapsed().as_secs_f64() * 1e3, + }; + self.log(&format!("WARNING: cannot map the sealed KAR memfd for the residency guard: {e}")); + if mode == LockMode::Require { + return Err(Refusal { code: "memlock", message: format!("mmap of the archive failed: {e}"), numbers: vec![], advice: vec![] }); + } + return Ok(report); + } + }; + let outcome = match &decision { + LockDecision::Off => LockOutcome::NotAttempted { why: "LELEKA_MEMORY_LOCK=off".into() }, + LockDecision::Insufficient { need, soft, hard, advice } => { + let why = format!( + "RLIMIT_MEMLOCK soft {} MiB / hard {} MiB cannot cover {} MiB", + soft >> 20, + if *hard == u64::MAX { "unlimited".into() } else { (hard >> 20).to_string() }, + need >> 20 + ); + self.log(&format!("WARNING: the sealed KAR memfd ({}) stays swappable: {why}. To keep it resident: {}", gib(resident), advice.join(" | "))); + LockOutcome::NotAttempted { why } + } + LockDecision::Attempt { raise_soft_to } => { + if let Some(to) = raise_soft_to + && let Err(e) = crate::lock::raise_memlock_soft(*to) { + self.log(&format!("WARNING: could not raise the soft RLIMIT_MEMLOCK to {} MiB: {e}", to >> 20)); + } + let policy = self.policy(); + let swapped = self.mapping_swapped(&mapping).unwrap_or(0); + let src = self.inner.src.clone(); + let allow = |n: u64| { + // a swapped-out chunk is read back into RAM: keep the hard floor + reserve + let need = if swapped > 0 { n } else { 0 }; + HostFacts::probe(&*src).effective_available().is_none_or(|a| a.saturating_sub(need) >= policy.hard_floor + policy.reserve) + }; + let outcome = match extents { + Some(spans) => mapping.lock_ranges(spans, GIB, allow), + None => mapping.lock(GIB, allow), + }; + match &outcome { + LockOutcome::Locked { bytes } => self.log(&format!("sealed KAR memfd locked in RAM: {} (mlock, never swapped)", gib(*bytes))), + LockOutcome::Partial { locked, why, .. } => self.log(&format!("WARNING: sealed KAR memfd lock stopped at {} of {}: {why}", gib(*locked), gib(len))), + LockOutcome::NotAttempted { why } => self.log(&format!("sealed KAR memfd lock not attempted: {why}")), + } + outcome + } + }; + let report = LockReport { + mode, + decision: decision.clone(), + outcome: outcome.clone(), + mapping_bytes: len, + extent_bytes, + memlock_soft: facts.memlock.map(|m| m.0), + memlock_hard: facts.memlock.map(|m| m.1), + millis: started.elapsed().as_secs_f64() * 1e3, + }; + if mode == LockMode::Require && !matches!(outcome, LockOutcome::Locked { .. }) { + let (numbers, advice) = match &decision { + LockDecision::Insufficient { need, soft, hard, advice } => ( + vec![("needed to lock".to_owned(), *need), ("RLIMIT_MEMLOCK soft".to_owned(), *soft), ("RLIMIT_MEMLOCK hard".to_owned(), *hard)], + advice.clone(), + ), + _ => (vec![("archive".to_owned(), resident)], vec![]), + }; + return Err(Refusal { code: "memlock", message: format!("LELEKA_MEMORY_LOCK=require but the sealed KAR memfd could not be locked ({outcome:?})"), numbers, advice }); + } + *lock(&self.inner.guarded) = Some(Guarded { mapping, report: report.clone(), extents: extents.map(<[_]>::to_vec), cursor: 0, last_swapped: 0, warned_swapped: 0, last_check: None, last: None }); + Ok(report) + } + + #[cfg(all(target_os = "linux", target_pointer_width = "64"))] + pub(super) fn mapping_swapped(&self, mapping: &crate::lock::FdMapping) -> Option { + let text = self.inner.src.read("/proc/self/smaps").ok()?; + residency_from_smaps(&text, mapping.start(), mapping.len()).map(|r| r.swapped_bytes) + } + + /// Read the swap state of the archive mapping; warn when pages are swapped; pull them back when allowed. + /// Returns the swapped bytes found (0 when no mapping is guarded). + #[cfg(all(target_os = "linux", target_pointer_width = "64"))] + pub fn residency_tick(&self) -> u64 { + let policy = self.policy(); + let mut slot = lock(&self.inner.guarded); + let Some(g) = slot.as_mut() else { return 0 }; + let started = Instant::now(); + let Some(text) = self.inner.src.read("/proc/self/smaps").ok() else { return 0 }; + let Some(r) = residency_from_smaps(&text, g.mapping.start(), g.mapping.len()) else { return 0 }; + let read_ms = started.elapsed().as_secs_f64() * 1e3; + g.last = Some(r); + g.last_check = Some(Instant::now()); + g.last_swapped = r.swapped_bytes; + if r.swapped_bytes >= 64 * MIB && r.swapped_bytes.abs_diff(g.warned_swapped) >= 64 * MIB { + g.warned_swapped = r.swapped_bytes; + self.log(&format!( + "WARNING: {} MiB of the sealed KAR memfd are swapped out ({} of {} resident, locked {} MiB; smaps read {read_ms:.0} ms): PLE reads fault from swap until they are pulled back{}", + r.swapped_bytes >> 20, + gib(r.rss_bytes), + gib(r.mapping_bytes), + r.locked_bytes >> 20, + if self.inner.cfg.heal { "; healing" } else { "" } + )); + } else if r.swapped_bytes < 64 * MIB { + g.warned_swapped = 0; + } + if self.inner.cfg.heal && r.swapped_bytes >= 16 * MIB && self.level() == Level::Normal { + let budget = self.inner.cfg.heal_bytes_per_tick.min(r.swapped_bytes.max(GIB)); + let ok = HostFacts::probe(&*self.inner.src) + .effective_available() + .is_some_and(|a| a.saturating_sub(budget.min(r.swapped_bytes)) >= policy.soft_floor + policy.reserve); + if ok { + let mut done = 0; + match g.extents.clone() { + // a sparse archive: walk the concatenation of the extents, never a hole + Some(spans) => { + let total = crate::lock::spans_bytes(&spans); + while done < budget && done < total { + if g.cursor >= total { + g.cursor = 0; + } + let want = (256 * MIB).min(budget - done); + let Some((offset, piece)) = crate::lock::compact_piece(&spans, g.cursor, want) else { break }; + // whole pages; the last page of the last extent may be partial and is rounded up by the kernel + let n = if g.cursor + piece == total || piece < 4096 { piece } else { piece / 4096 * 4096 }; + if g.mapping.populate(offset, n).is_err() { + break; + } + g.cursor += n; + done += n; + } + } + None => { + let total = g.mapping.len(); + while done < budget && done < total { + if g.cursor >= total { + g.cursor = 0; + } + let n = (256 * MIB).min(total - g.cursor).min(budget - done) / 4096 * 4096; + if n == 0 { + break; + } + if g.mapping.populate(g.cursor, n).is_err() { + break; + } + g.cursor += n; + done += n; + } + } + } + self.inner.counters.heal_bytes.fetch_add(done, Ordering::Relaxed); + self.inner.counters.heal_runs.fetch_add(1, Ordering::Relaxed); + } + } + r.swapped_bytes + } + + #[cfg(not(all(target_os = "linux", target_pointer_width = "64")))] + pub fn residency_tick(&self) -> u64 { + 0 + } + + // ---- report ----------------------------------------------------------------------------------------------- + + pub fn report(&self) -> serde_json::Value { + let facts = self.probe(); + let monitor = lock(&self.inner.monitor); + let policy = self.policy(); + let level = self.level(); + let c = &self.inner.counters; + let planned = self.inner.prefix_planned.load(Ordering::Acquire); + let target = self.inner.prefix_target.load(Ordering::Acquire); + #[cfg(all(target_os = "linux", target_pointer_width = "64"))] + let archive = lock(&self.inner.guarded).as_ref().map(|g| json!({"lock": g.report, "residency": g.last, "heal": {"cursor": g.cursor}})); + #[cfg(not(all(target_os = "linux", target_pointer_width = "64")))] + let archive: Option = None; + json!({ + "version": 1, + "uptime_ms": self.now_ms(), + "gate": { + "level": level.as_str(), + "since_ms": self.inner.since_ms.load(Ordering::Acquire), + "reason": &*lock(&self.inner.reason), + "retry_after_secs": if level == Level::Normal { 0 } else { monitor.retry_after_secs() }, + "available_bytes": self.available_cached(), + "soft_floor_bytes": policy.soft_floor, + "hard_floor_bytes": policy.hard_floor, + }, + "policy": policy, + "config": {"sample_interval_ms": self.inner.cfg.sample_interval_ms, "lock_mode": self.inner.cfg.lock_mode, "heal": self.inner.cfg.heal}, + "plan": self.plan(), + "host": { + "mem_total": facts.meminfo.mem_total, + "mem_available": facts.meminfo.mem_available, + "effective_available": facts.effective_available(), + "swap_total": facts.meminfo.swap_total, + "swap_free": facts.meminfo.swap_free, + "shmem": facts.meminfo.shmem, + "mlocked": facts.meminfo.mlocked, + "cgroup": facts.cgroup, + "psi": facts.psi, + "memlock": facts.memlock, + "wsl": facts.wsl, + "kernel": facts.kernel, + }, + "process": { + "rss": facts.status.vm_rss, "swap": facts.status.vm_swap, "pinned": facts.status.vm_pin, "locked": facts.status.vm_lck, + "threads": facts.status.threads, "fds": facts.open_fds, + }, + "observed": monitor.observed, + "caches": { + "prefix": {"planned_bytes": planned, "shed_target_bytes": if target == NONE { serde_json::Value::Null } else { json!(target) }, "used_bytes": self.inner.prefix_used.load(Ordering::Acquire)}, + }, + "counters": { + "admitted": c.admitted.load(Ordering::Relaxed), + "rejected_memory_pressure": c.rejected_pressure.load(Ordering::Relaxed), + "rejected_context": c.rejected_context.load(Ordering::Relaxed), + "shed_steps": c.shed_steps.load(Ordering::Relaxed), + "evicted_bytes": c.evicted_bytes.load(Ordering::Relaxed), + "samples": c.samples.load(Ordering::Relaxed), + "level_changes": c.level_changes.load(Ordering::Relaxed), + "heal_bytes": c.heal_bytes.load(Ordering::Relaxed), + "heal_runs": c.heal_runs.load(Ordering::Relaxed), + }, + "archive": archive, + "inventory": self.inventory().to_json(), + "ledger": self.inner.ledger.to_json(), + "vram": &*lock(&self.inner.vram), + "plan_check": lock(&self.inner.post_load).map(|(p, a)| json!({"predicted_available_after_fixed": p, "actual_available_after_open": a, "error_bytes": i128::from(a) - i128::from(p)})), + "transitions": &*lock(&self.inner.transitions), + }) + } + + /// Render the report into the cell [`published_report`] reads. + pub fn publish(&self) { + if let Ok(text) = serde_json::to_string(&self.report()) { + *PUBLISHED.lock().unwrap_or_else(|p| p.into_inner()) = Some(text); + } + } + + // ---- sampler ----------------------------------------------------------------------------------------------- + + /// Start the sampler thread (pressure level and report, every interval) and the residency-guard thread (the smaps read of + /// the memfd mapping costs up to a second for 55 GB, which must not delay a pressure sample). Both stop when the guard is + /// dropped. + pub fn spawn_sampler(&self) -> SamplerGuard { + fn nap(inner: &Inner, total: Duration) { + let mut slept = Duration::ZERO; + while slept < total && !inner.stop.load(Ordering::Acquire) { + let step = Duration::from_millis(50).min(total - slept); + std::thread::sleep(step); + slept += step; + } + } + self.inner.stop.store(false, Ordering::Release); + let me = self.clone(); + let sampler = std::thread::Builder::new() + .name("leleka-memory".into()) + .spawn(move || { + let interval = Duration::from_millis(me.inner.cfg.sample_interval_ms); + while !me.inner.stop.load(Ordering::Acquire) { + // a panic in one round (a malformed /proc read, a poisoned state) must not end the thread that lifts a pressure level + let round = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { + me.sample_now(); + me.publish(); + })); + if round.is_err() { + me.log("WARNING: the memory sampler round panicked; continuing"); + } + nap(&me.inner, interval); + } + }) + .ok(); + let me = self.clone(); + let guard = std::thread::Builder::new() + .name("leleka-memory-guard".into()) + .spawn(move || { + let every = Duration::from_millis(me.inner.cfg.residency_every_ms); + while !me.inner.stop.load(Ordering::Acquire) { + let round = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| me.residency_tick())); + if round.is_err() { + me.log("WARNING: the memfd residency round panicked; continuing"); + } + nap(&me.inner, every); + } + }) + .ok(); + SamplerGuard { inner: self.inner.clone(), handles: sampler.into_iter().chain(guard).collect() } + } +} diff --git a/crates/leleka-memory/src/governor/impl_governorconfig.rs b/crates/leleka-memory/src/governor/impl_governorconfig.rs new file mode 100644 index 00000000..2862ab45 --- /dev/null +++ b/crates/leleka-memory/src/governor/impl_governorconfig.rs @@ -0,0 +1,91 @@ +//! Moved out of the parent module by STRA-338: impl GovernorConfig, fn published_report, fn lock. + +#[allow(unused_imports)] +use super::*; + + +impl GovernorConfig { + pub fn new(policy: Policy) -> Self { + Self { policy, sample_interval_ms: 1000, lock_mode: LockMode::Try, heal: true, heal_bytes_per_tick: GIB, residency_every_ms: 30_000, log: true } + } + + /// Defaults for the host, then the `LELEKA_MEMORY_*` overrides. An unparsable override is an error naming the variable + /// (a typo must not silently keep the default of a safety setting). + pub fn from_env(mem_total: u64, laptop: bool, env: &dyn Fn(&str) -> Option) -> Result { + let mut cfg = Self::new(Policy::for_host(mem_total, laptop)); + let number = |name: &str| -> Result, String> { + match env(name) { + None => Ok(None), + Some(v) => v.trim().parse::().map(Some).map_err(|_| format!("{name}={v:?} is not a number")), + } + }; + if let Some(v) = number("LELEKA_MEMORY_SOFT_FLOOR_MIB")? { + cfg.policy.soft_floor = v.saturating_mul(MIB); + } + if let Some(v) = number("LELEKA_MEMORY_HARD_FLOOR_MIB")? { + cfg.policy.hard_floor = v.saturating_mul(MIB); + } + if let Some(v) = number("LELEKA_MEMORY_RESERVE_MIB")? { + cfg.policy.reserve = v.saturating_mul(MIB); + } + if let Some(v) = number("LELEKA_MEMORY_HYSTERESIS_MIB")? { + cfg.policy.hysteresis = v.saturating_mul(MIB); + } + if let Some(v) = number("LELEKA_MEMORY_CACHE_SHARE_PERCENT")? { + if v == 0 || v > 100 { + return Err(format!("LELEKA_MEMORY_CACHE_SHARE_PERCENT={v} must be 1..=100")); + } + cfg.policy.cache_share_percent = v; + } + if let Some(v) = number("LELEKA_MEMORY_SWAPOUT_PAGES_PER_S")? { + cfg.policy.swapout_pages_per_s_shed = v; + } + let float = |name: &str| -> Result, String> { + match env(name) { + None => Ok(None), + Some(v) => v.trim().parse::().ok().filter(|f| f.is_finite() && *f >= 0.0).map(Some).ok_or_else(|| format!("{name}={v:?} is not a non-negative number")), + } + }; + if let Some(v) = number("LELEKA_MEMORY_PSI_GUARD_MIB")? { + cfg.policy.psi_guard_available = v.saturating_mul(MIB); + } + if let Some(v) = float("LELEKA_MEMORY_PSI_SOME_SHED")? { + cfg.policy.psi_some_shed = v; + } + if let Some(v) = float("LELEKA_MEMORY_PSI_FULL_REJECT")? { + cfg.policy.psi_full_reject = v; + } + if let Some(v) = number("LELEKA_MEMORY_ENFORCE")? { + cfg.policy.enforce = v != 0; + } + if let Some(v) = number("LELEKA_MEMORY_SAMPLE_MS")? { + cfg.sample_interval_ms = v.clamp(50, 60_000); + } + if let Some(v) = number("LELEKA_MEMORY_HEAL")? { + cfg.heal = v != 0; + } + if let Some(v) = number("LELEKA_MEMORY_RESIDENCY_S")? { + cfg.residency_every_ms = v.saturating_mul(1000).max(1000); + } + if let Some(v) = env("LELEKA_MEMORY_LOCK") { + cfg.lock_mode = LockMode::parse(v.trim()).ok_or_else(|| format!("LELEKA_MEMORY_LOCK={v:?} must be off, try or require"))?; + } + if cfg.policy.hard_floor >= cfg.policy.soft_floor { + return Err(format!( + "hard floor {} MiB must be below the soft floor {} MiB (LELEKA_MEMORY_HARD_FLOOR_MIB / SOFT_FLOOR_MIB)", + cfg.policy.hard_floor >> 20, + cfg.policy.soft_floor >> 20 + )); + } + Ok(cfg) + } +} + +/// The last report the sampler published (JSON text), for the status surface. +pub fn published_report() -> Option { + PUBLISHED.lock().unwrap_or_else(|p| p.into_inner()).clone() +} + +pub(super) fn lock(m: &Mutex) -> MutexGuard<'_, T> { + m.lock().unwrap_or_else(|p| p.into_inner()) +} diff --git a/crates/leleka-memory/src/lock.rs b/crates/leleka-memory/src/lock.rs index 90bc8a4b..d91c98a3 100644 --- a/crates/leleka-memory/src/lock.rs +++ b/crates/leleka-memory/src/lock.rs @@ -31,17 +31,6 @@ pub enum LockMode { Require, } -impl LockMode { - pub fn parse(text: &str) -> Option { - match text { - "off" | "0" => Some(Self::Off), - "try" | "auto" => Some(Self::Try), - "require" | "on" | "1" => Some(Self::Require), - _ => None, - } - } -} - /// What to do about locking, decided from the numbers alone. #[derive(Clone, Debug, PartialEq, Eq, Serialize)] #[serde(tag = "decision", rename_all = "snake_case")] @@ -54,33 +43,6 @@ pub enum LockDecision { Insufficient { need: u64, soft: u64, hard: u64, advice: Vec }, } -/// Pure: can `len` bytes be locked given `RLIMIT_MEMLOCK` (`soft`, `hard`), what is already locked and the capabilities? -pub fn plan_lock(mode: LockMode, len: u64, memlock: Option<(u64, u64)>, status: &ProcStatus) -> LockDecision { - if mode == LockMode::Off { - return LockDecision::Off; - } - if status.cap_eff.is_some_and(|c| c & CAP_IPC_LOCK_BIT != 0) { - return LockDecision::Attempt { raise_soft_to: None }; - } - let already = status.vm_lck.unwrap_or(0); - let need = len.saturating_add(already); - match memlock { - Some((soft, _)) if soft >= need => LockDecision::Attempt { raise_soft_to: None }, - Some((_, hard)) if hard >= need => LockDecision::Attempt { raise_soft_to: Some(need) }, - Some((soft, hard)) => LockDecision::Insufficient { - need, - soft, - hard, - advice: vec![ - format!("raise RLIMIT_MEMLOCK to at least {} MiB: systemd `LimitMEMLOCK=infinity` in the service unit (the leleka unit sets it), or `ulimit -l unlimited` / /etc/security/limits.conf `memlock` for the user", need >> 20), - "or grant the binary CAP_IPC_LOCK (`setcap cap_ipc_lock+ep` / systemd `AmbientCapabilities=CAP_IPC_LOCK`)".into(), - "without the lock the guard still detects swapped pages and pulls them back (MADV_POPULATE_READ); lower vm.swappiness and `MemoryLow=` on the service cgroup also keep the memfd out of swap".into(), - ], - }, - None => LockDecision::Attempt { raise_soft_to: None }, - } -} - /// How a lock attempt ended. #[derive(Clone, Debug, PartialEq, Eq, Serialize)] #[serde(tag = "outcome", rename_all = "snake_case")] @@ -91,16 +53,6 @@ pub enum LockOutcome { NotAttempted { why: String }, } -impl LockOutcome { - pub fn locked_bytes(&self) -> u64 { - match self { - LockOutcome::Locked { bytes } => *bytes, - LockOutcome::Partial { locked, .. } => *locked, - LockOutcome::NotAttempted { .. } => 0, - } - } -} - /// The swap state of the mapping. #[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize)] pub struct Residency { @@ -113,51 +65,9 @@ pub struct Residency { pub locked_bytes: u64, } -/// Find the mapping that starts at `start` in `smaps` text and report its swap. -pub fn residency_from_smaps(smaps: &str, start: u64, len: u64) -> Option { - procfs::parse_smaps(smaps) - .into_iter() - .find(|e| e.start == start && e.end - e.start >= len) - .map(|e| Residency { mapping_bytes: e.end - e.start, swapped_bytes: e.swap, rss_bytes: e.rss, locked_bytes: e.locked }) -} - /// A byte range `(offset, len)` of the archive mapping. pub type Span = (u64, u64); -/// Total bytes of a list of spans. -pub fn spans_bytes(spans: &[Span]) -> u64 { - spans.iter().map(|s| s.1).sum() -} - -/// Are the spans usable for `mlock` / `madvise` on a mapping of `len` bytes: page-aligned starts, non-empty, sorted, disjoint, inside? -pub fn check_spans(spans: &[Span], len: u64) -> Result<(), String> { - let mut previous_end = 0u64; - for (i, (offset, n)) in spans.iter().enumerate() { - let end = offset.checked_add(*n).ok_or_else(|| format!("span {i} overflows"))?; - if !offset.is_multiple_of(PAGE) || *n == 0 || end > len || *offset < previous_end { - return Err(format!("span {i} ({offset}+{n}) is unaligned, empty, out of order or outside the mapping of {len} bytes")); - } - previous_end = end; - } - Ok(()) -} - -/// The piece of the spans at position `pos` of their concatenation ("compact space"): `(offset in the mapping, bytes)`, at most -/// `max` bytes and never across the end of a span. `None` when `pos` is past the last byte (or `max` is 0). A sparse archive -/// is walked with this so that nothing is ever asked of a hole. -pub fn compact_piece(spans: &[Span], pos: u64, max: u64) -> Option<(u64, u64)> { - let mut start = 0u64; - for (offset, n) in spans { - if pos < start + n { - let inside = pos - start; - let piece = (n - inside).min(max); - return (piece > 0).then_some((offset + inside, piece)); - } - start += n; - } - None -} - #[cfg(all(target_os = "linux", target_pointer_width = "64"))] pub use sys::{FdMapping, raise_memlock_soft}; @@ -516,3 +426,7 @@ mod sys { #[cfg(test)] mod tests; + +mod impl_lockmode; +#[allow(unused_imports)] +pub use impl_lockmode::*; diff --git a/crates/leleka-memory/src/lock/impl_lockmode.rs b/crates/leleka-memory/src/lock/impl_lockmode.rs new file mode 100644 index 00000000..22c148b0 --- /dev/null +++ b/crates/leleka-memory/src/lock/impl_lockmode.rs @@ -0,0 +1,95 @@ +//! Moved out of the parent module by STRA-338: impl LockMode, fn plan_lock, impl LockOutcome, fn residency_from_smaps, fn spans_bytes, fn check_spans .... + +#[allow(unused_imports)] +use super::*; + + +impl LockMode { + pub fn parse(text: &str) -> Option { + match text { + "off" | "0" => Some(Self::Off), + "try" | "auto" => Some(Self::Try), + "require" | "on" | "1" => Some(Self::Require), + _ => None, + } + } +} + +/// Pure: can `len` bytes be locked given `RLIMIT_MEMLOCK` (`soft`, `hard`), what is already locked and the capabilities? +pub fn plan_lock(mode: LockMode, len: u64, memlock: Option<(u64, u64)>, status: &ProcStatus) -> LockDecision { + if mode == LockMode::Off { + return LockDecision::Off; + } + if status.cap_eff.is_some_and(|c| c & CAP_IPC_LOCK_BIT != 0) { + return LockDecision::Attempt { raise_soft_to: None }; + } + let already = status.vm_lck.unwrap_or(0); + let need = len.saturating_add(already); + match memlock { + Some((soft, _)) if soft >= need => LockDecision::Attempt { raise_soft_to: None }, + Some((_, hard)) if hard >= need => LockDecision::Attempt { raise_soft_to: Some(need) }, + Some((soft, hard)) => LockDecision::Insufficient { + need, + soft, + hard, + advice: vec![ + format!("raise RLIMIT_MEMLOCK to at least {} MiB: systemd `LimitMEMLOCK=infinity` in the service unit (the leleka unit sets it), or `ulimit -l unlimited` / /etc/security/limits.conf `memlock` for the user", need >> 20), + "or grant the binary CAP_IPC_LOCK (`setcap cap_ipc_lock+ep` / systemd `AmbientCapabilities=CAP_IPC_LOCK`)".into(), + "without the lock the guard still detects swapped pages and pulls them back (MADV_POPULATE_READ); lower vm.swappiness and `MemoryLow=` on the service cgroup also keep the memfd out of swap".into(), + ], + }, + None => LockDecision::Attempt { raise_soft_to: None }, + } +} + +impl LockOutcome { + pub fn locked_bytes(&self) -> u64 { + match self { + LockOutcome::Locked { bytes } => *bytes, + LockOutcome::Partial { locked, .. } => *locked, + LockOutcome::NotAttempted { .. } => 0, + } + } +} + +/// Find the mapping that starts at `start` in `smaps` text and report its swap. +pub fn residency_from_smaps(smaps: &str, start: u64, len: u64) -> Option { + procfs::parse_smaps(smaps) + .into_iter() + .find(|e| e.start == start && e.end - e.start >= len) + .map(|e| Residency { mapping_bytes: e.end - e.start, swapped_bytes: e.swap, rss_bytes: e.rss, locked_bytes: e.locked }) +} + +/// Total bytes of a list of spans. +pub fn spans_bytes(spans: &[Span]) -> u64 { + spans.iter().map(|s| s.1).sum() +} + +/// Are the spans usable for `mlock` / `madvise` on a mapping of `len` bytes: page-aligned starts, non-empty, sorted, disjoint, inside? +pub fn check_spans(spans: &[Span], len: u64) -> Result<(), String> { + let mut previous_end = 0u64; + for (i, (offset, n)) in spans.iter().enumerate() { + let end = offset.checked_add(*n).ok_or_else(|| format!("span {i} overflows"))?; + if !offset.is_multiple_of(PAGE) || *n == 0 || end > len || *offset < previous_end { + return Err(format!("span {i} ({offset}+{n}) is unaligned, empty, out of order or outside the mapping of {len} bytes")); + } + previous_end = end; + } + Ok(()) +} + +/// The piece of the spans at position `pos` of their concatenation ("compact space"): `(offset in the mapping, bytes)`, at most +/// `max` bytes and never across the end of a span. `None` when `pos` is past the last byte (or `max` is 0). A sparse archive +/// is walked with this so that nothing is ever asked of a hole. +pub fn compact_piece(spans: &[Span], pos: u64, max: u64) -> Option<(u64, u64)> { + let mut start = 0u64; + for (offset, n) in spans { + if pos < start + n { + let inside = pos - start; + let piece = (n - inside).min(max); + return (piece > 0).then_some((offset + inside, piece)); + } + start += n; + } + None +} diff --git a/crates/leleka-memory/src/plan.rs b/crates/leleka-memory/src/plan.rs index 27460f20..1cb81ccb 100644 --- a/crates/leleka-memory/src/plan.rs +++ b/crates/leleka-memory/src/plan.rs @@ -55,32 +55,6 @@ pub struct Policy { pub enforce: bool, } -impl Policy { - /// Below this much available memory a cache stops admitting new entries (before anything has to be shed): `soft_floor + reserve`. - pub fn admit_floor(&self) -> u64 { - self.soft_floor.saturating_add(self.reserve) - } - /// 4 GiB soft / 2 GiB hard floors (more on very large hosts), 75% of the elastic memory to an auto cache. - pub fn for_host(mem_total: u64, laptop: bool) -> Self { - Self { - soft_floor: (4 * GIB).max(mem_total / 32 / MIB * MIB), - hard_floor: (2 * GIB).max(mem_total / 64 / MIB * MIB), - // 2 GiB: the first long request and the cache's own overhead grew the process by ~1 GiB beyond the plan in the real Codex CRM session (job 945) - reserve: 2 * GIB, - hysteresis: GIB, - cache_share_percent: 75, - prefix_cap: if laptop { 24 * GIB } else { 96 * GIB }, - min_useful_cache: GIB, - psi_guard_available: 3 * (4 * GIB).max(mem_total / 32 / MIB * MIB), - psi_some_shed: 20.0, - psi_full_reject: 5.0, - swapout_pages_per_s_shed: 25_000, - vram_headroom: 512 * MIB, - enforce: true, - } - } -} - /// What the operator asked of a cache. #[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)] #[serde(rename_all = "snake_case")] @@ -111,12 +85,6 @@ pub struct FixedItem { pub formula: String, } -impl FixedItem { - pub fn new(name: &str, bytes: u64, space: Space, formula: &str) -> Self { - Self { name: name.to_owned(), bytes, space, formula: formula.to_owned() } - } -} - #[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)] pub struct VramFacts { pub free: u64, @@ -182,227 +150,12 @@ pub struct Refusal { pub advice: Vec, } -impl std::fmt::Display for Refusal { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - write!(f, "memory budget refused ({}): {}", self.code, self.message)?; - for (name, bytes) in &self.numbers { - write!(f, "; {name} = {}", gib(*bytes))?; - } - for a in &self.advice { - write!(f, "; change: {a}")?; - } - Ok(()) - } -} - -impl std::error::Error for Refusal {} - -pub fn gib(bytes: u64) -> String { - format!("{:.2} GiB", bytes as f64 / GIB as f64) -} - -/// The device check, run when the device is first visible: refuses when a measured fixed footprint does not fit in the free -/// VRAM, otherwise only notes a free VRAM below the declared budget. The note (if any) is returned. -pub fn check_vram(policy: &Policy, vram: VramFacts, budget: u64, fixed_estimate: Option) -> Result<(VramPlan, Option), Refusal> { - let plan = VramPlan { free: vram.free, total: vram.total, budget, headroom: policy.vram_headroom }; - if let Some(estimate) = fixed_estimate - && plan.free < estimate.saturating_add(plan.headroom) && policy.enforce { - return Err(Refusal { - code: "vram", - message: format!("the device footprint does not fit: {} free of {} total", gib(plan.free), gib(plan.total)), - numbers: vec![ - ("vram free".into(), plan.free), - ("vram fixed footprint".into(), estimate), - ("vram headroom".into(), plan.headroom), - ], - advice: vec![ - "stop the other GPU processes (nvidia-smi)".into(), - "lower --gpu-budget / the expert slots / --kv-resident".into(), - ], - }); - } - let note = (plan.free < plan.budget).then(|| { - format!( - "VRAM free {} is below the declared --gpu-budget {}: the stack may run out of device memory while it opens", - gib(plan.free), - gib(plan.budget) - ) - }); - Ok((plan, note)) -} - -/// The budget. Pure: no file system, no clock. -pub fn plan(input: &PlanInput) -> Result { - let policy = input.policy; - let mut notes: Vec = Vec::new(); - let fixed_bytes: u64 = input.fixed.iter().filter(|i| i.space.is_host()).map(|i| i.bytes).sum(); - let kar_to_create = match input.kar { - KarForm::MemfdToCreate { bytes } => bytes, - KarForm::MemfdInherited { .. } | KarForm::File { .. } => 0, - }; - let vram = match input.vram { - Some(v) => { - let (plan, note) = check_vram(&policy, v, input.vram_budget, input.vram_fixed_estimate)?; - notes.extend(note); - Some(plan) - } - None => None, - }; - let Some(available) = input.host.effective_available() else { - notes.push("host memory telemetry is unavailable (MemAvailable): caches are off and the monitor sheds (fail closed)".into()); - return Ok(Plan { - available_before: None, - kar_to_create, - fixed_bytes, - fixed: input.fixed.clone(), - available_after_fixed: None, - elastic: 0, - resident_complement_bytes: 0, - prefix_bytes: 0, - conversation_checkpoints: 0, - conversation_bytes: 0, - soft_floor: policy.soft_floor, - hard_floor: policy.hard_floor, - policy, - blind: true, - vram, - notes, - }); - }; - let needs = fixed_bytes.saturating_add(kar_to_create); - let required_after = policy.soft_floor.saturating_add(policy.reserve); - let after = available.checked_sub(needs); - if after.is_none_or(|r| r < required_after) { - let mut advice = vec![ - "free host memory (stop other processes; `free -g` and the MemAvailable line of /proc/meminfo)".into(), - "use `--expert-source mapped` (read-only mappings of shard 0) instead of the ~50 GB resident copy".into(), - "use `--kar-archive-file` (read-only file) instead of a sealed memfd on small hosts".into(), - "lower --context-tokens (the pinned K/V image is sized by the serving context)".into(), - ]; - if input.host.wsl { - advice.push(wsl_advice().into()); - } - if input.host.cgroup.as_ref().is_some_and(|c| c.limit.is_some()) { - advice.push("raise the cgroup limit (memory.max / systemd MemoryMax=) of the service".into()); - } - let mut numbers = vec![ - ("available".to_owned(), available), - ("fixed host footprint".to_owned(), fixed_bytes), - ]; - if kar_to_create > 0 { - numbers.push(("sealed KAR memfd to create".to_owned(), kar_to_create)); - } - numbers.push(("soft floor + reserve".to_owned(), required_after)); - numbers.push(("short by".to_owned(), required_after.saturating_add(needs).saturating_sub(available))); - let refusal = Refusal { - code: "host_ram", - message: format!( - "the fixed host footprint ({}) leaves {} of {} available, below the {} the runtime needs to stay out of swap and the OOM killer", - gib(needs), - after.map_or("nothing".to_owned(), gib), - gib(available), - gib(required_after) - ), - numbers, - advice, - }; - if policy.enforce { - return Err(refusal); - } - notes.push(format!("ENFORCEMENT OFF: {refusal}")); - } - let after = after.unwrap_or(0); - let mut elastic = after.saturating_sub(required_after); - - // 1. the resident complement (explicit, pinned at open) - let mut complement = 0; - if let Some(wish) = input.resident_complement { - complement = wish.min(elastic); - if complement < wish { - notes.push(format!("resident complement clamped from {} to {} (elastic memory)", gib(wish), gib(complement))); - } - elastic -= complement; - } - // 2. the prefix cache, or the conversation checkpoints it replaces - let (mut prefix_bytes, mut checkpoints, mut conversation_bytes) = (0, 0, 0); - match input.prefix { - CacheWish::Off => { - let each = input.checkpoint_bytes.max(1); - checkpoints = input.conversation_checkpoints.min(elastic / each); - if checkpoints < input.conversation_checkpoints { - notes.push(format!( - "conversation checkpoints reduced from {} to {checkpoints} ({} each, elastic memory {})", - input.conversation_checkpoints, - gib(input.checkpoint_bytes), - gib(elastic) - )); - } - conversation_bytes = checkpoints * input.checkpoint_bytes; - } - CacheWish::Auto => { - let share = (u128::from(elastic) * u128::from(policy.cache_share_percent.min(100)) / 100) as u64; - let bytes = share.min(policy.prefix_cap) / MIB * MIB; - if bytes < policy.min_useful_cache { - notes.push(format!( - "prefix cache off: auto budget {} is below the useful minimum {}", - gib(bytes), - gib(policy.min_useful_cache) - )); - } else { - prefix_bytes = bytes; - } - } - CacheWish::Bytes(wish) => { - prefix_bytes = wish.min(elastic) / MIB * MIB; - if prefix_bytes < wish { - notes.push(format!( - "prefix cache clamped from {} to {} (elastic memory {}); lower --prefix-cache-mib or free memory", - gib(wish), - gib(prefix_bytes), - gib(elastic) - )); - } - } - } - Ok(Plan { - available_before: Some(available), - kar_to_create, - fixed_bytes, - fixed: input.fixed.clone(), - available_after_fixed: Some(after), - elastic: elastic + complement, - resident_complement_bytes: complement, - prefix_bytes, - conversation_checkpoints: checkpoints, - conversation_bytes, - soft_floor: policy.soft_floor, - hard_floor: policy.hard_floor, - policy, - blind: false, - vram, - notes, - }) -} - -/// The `auto` prefix budget recomputed from the memory available when the stack opens (after the expert bank and the -/// other fixed items are really resident): the same rule as [`plan`] with `fixed = 0`. -pub fn auto_prefix_budget(available: Option, policy: &Policy, complement_pinned: u64) -> u64 { - let Some(available) = available else { return 0 }; - let required = policy.soft_floor.saturating_add(policy.reserve); - let elastic = available.saturating_sub(required).saturating_sub(complement_pinned.min(available)); - let share = (u128::from(elastic) * u128::from(policy.cache_share_percent.min(100)) / 100) as u64; - let bytes = share.min(policy.prefix_cap) / MIB * MIB; - if bytes < policy.min_useful_cache { 0 } else { bytes } -} - -/// An explicit `--prefix-cache-mib N` at stack open: the wish, clamped to what the host has now, **never above the wish**. -/// Unlike [`auto_prefix_budget`] the result does not depend on how much memory is free beyond the wish: freeing RAM -/// elsewhere (a smaller archive copy, a smaller expert bank) cannot make the store bigger than the operator's number. -/// Returns the granted bytes and the elastic memory it was clamped against. -pub fn explicit_prefix_budget(wish: u64, available: Option, policy: &Policy, complement_pending: u64) -> (u64, u64) { - let elastic = available.map_or(0, |a| a.saturating_sub(policy.soft_floor + policy.reserve).saturating_sub(complement_pending)); - (wish.min(elastic) / MIB * MIB, elastic) -} - #[cfg(test)] mod tests; + +mod impl_policy; +#[allow(unused_imports)] +pub use impl_policy::*; +mod auto_prefix_budget; +#[allow(unused_imports)] +pub use auto_prefix_budget::*; diff --git a/crates/leleka-memory/src/plan/auto_prefix_budget.rs b/crates/leleka-memory/src/plan/auto_prefix_budget.rs new file mode 100644 index 00000000..27b92f6b --- /dev/null +++ b/crates/leleka-memory/src/plan/auto_prefix_budget.rs @@ -0,0 +1,25 @@ +//! Moved out of the parent module by STRA-338: fn auto_prefix_budget, fn explicit_prefix_budget. + +#[allow(unused_imports)] +use super::*; + + +/// The `auto` prefix budget recomputed from the memory available when the stack opens (after the expert bank and the +/// other fixed items are really resident): the same rule as [`plan`] with `fixed = 0`. +pub fn auto_prefix_budget(available: Option, policy: &Policy, complement_pinned: u64) -> u64 { + let Some(available) = available else { return 0 }; + let required = policy.soft_floor.saturating_add(policy.reserve); + let elastic = available.saturating_sub(required).saturating_sub(complement_pinned.min(available)); + let share = (u128::from(elastic) * u128::from(policy.cache_share_percent.min(100)) / 100) as u64; + let bytes = share.min(policy.prefix_cap) / MIB * MIB; + if bytes < policy.min_useful_cache { 0 } else { bytes } +} + +/// An explicit `--prefix-cache-mib N` at stack open: the wish, clamped to what the host has now, **never above the wish**. +/// Unlike [`auto_prefix_budget`] the result does not depend on how much memory is free beyond the wish: freeing RAM +/// elsewhere (a smaller archive copy, a smaller expert bank) cannot make the store bigger than the operator's number. +/// Returns the granted bytes and the elastic memory it was clamped against. +pub fn explicit_prefix_budget(wish: u64, available: Option, policy: &Policy, complement_pending: u64) -> (u64, u64) { + let elastic = available.map_or(0, |a| a.saturating_sub(policy.soft_floor + policy.reserve).saturating_sub(complement_pending)); + (wish.min(elastic) / MIB * MIB, elastic) +} diff --git a/crates/leleka-memory/src/plan/impl_policy.rs b/crates/leleka-memory/src/plan/impl_policy.rs new file mode 100644 index 00000000..f2fff205 --- /dev/null +++ b/crates/leleka-memory/src/plan/impl_policy.rs @@ -0,0 +1,239 @@ +//! Moved out of the parent module by STRA-338: impl Policy, impl FixedItem, impl std_fmt_Display, impl std_error_Error, fn gib, fn check_vram .... + +#[allow(unused_imports)] +use super::*; + + +impl Policy { + /// Below this much available memory a cache stops admitting new entries (before anything has to be shed): `soft_floor + reserve`. + pub fn admit_floor(&self) -> u64 { + self.soft_floor.saturating_add(self.reserve) + } + /// 4 GiB soft / 2 GiB hard floors (more on very large hosts), 75% of the elastic memory to an auto cache. + pub fn for_host(mem_total: u64, laptop: bool) -> Self { + Self { + soft_floor: (4 * GIB).max(mem_total / 32 / MIB * MIB), + hard_floor: (2 * GIB).max(mem_total / 64 / MIB * MIB), + // 2 GiB: the first long request and the cache's own overhead grew the process by ~1 GiB beyond the plan in the real Codex CRM session (job 945) + reserve: 2 * GIB, + hysteresis: GIB, + cache_share_percent: 75, + prefix_cap: if laptop { 24 * GIB } else { 96 * GIB }, + min_useful_cache: GIB, + psi_guard_available: 3 * (4 * GIB).max(mem_total / 32 / MIB * MIB), + psi_some_shed: 20.0, + psi_full_reject: 5.0, + swapout_pages_per_s_shed: 25_000, + vram_headroom: 512 * MIB, + enforce: true, + } + } +} + +impl FixedItem { + pub fn new(name: &str, bytes: u64, space: Space, formula: &str) -> Self { + Self { name: name.to_owned(), bytes, space, formula: formula.to_owned() } + } +} + +impl std::fmt::Display for Refusal { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + write!(f, "memory budget refused ({}): {}", self.code, self.message)?; + for (name, bytes) in &self.numbers { + write!(f, "; {name} = {}", gib(*bytes))?; + } + for a in &self.advice { + write!(f, "; change: {a}")?; + } + Ok(()) + } +} + +impl std::error::Error for Refusal {} + +pub fn gib(bytes: u64) -> String { + format!("{:.2} GiB", bytes as f64 / GIB as f64) +} + +/// The device check, run when the device is first visible: refuses when a measured fixed footprint does not fit in the free +/// VRAM, otherwise only notes a free VRAM below the declared budget. The note (if any) is returned. +pub fn check_vram(policy: &Policy, vram: VramFacts, budget: u64, fixed_estimate: Option) -> Result<(VramPlan, Option), Refusal> { + let plan = VramPlan { free: vram.free, total: vram.total, budget, headroom: policy.vram_headroom }; + if let Some(estimate) = fixed_estimate + && plan.free < estimate.saturating_add(plan.headroom) && policy.enforce { + return Err(Refusal { + code: "vram", + message: format!("the device footprint does not fit: {} free of {} total", gib(plan.free), gib(plan.total)), + numbers: vec![ + ("vram free".into(), plan.free), + ("vram fixed footprint".into(), estimate), + ("vram headroom".into(), plan.headroom), + ], + advice: vec![ + "stop the other GPU processes (nvidia-smi)".into(), + "lower --gpu-budget / the expert slots / --kv-resident".into(), + ], + }); + } + let note = (plan.free < plan.budget).then(|| { + format!( + "VRAM free {} is below the declared --gpu-budget {}: the stack may run out of device memory while it opens", + gib(plan.free), + gib(plan.budget) + ) + }); + Ok((plan, note)) +} + +/// The budget. Pure: no file system, no clock. +pub fn plan(input: &PlanInput) -> Result { + let policy = input.policy; + let mut notes: Vec = Vec::new(); + let fixed_bytes: u64 = input.fixed.iter().filter(|i| i.space.is_host()).map(|i| i.bytes).sum(); + let kar_to_create = match input.kar { + KarForm::MemfdToCreate { bytes } => bytes, + KarForm::MemfdInherited { .. } | KarForm::File { .. } => 0, + }; + let vram = match input.vram { + Some(v) => { + let (plan, note) = check_vram(&policy, v, input.vram_budget, input.vram_fixed_estimate)?; + notes.extend(note); + Some(plan) + } + None => None, + }; + let Some(available) = input.host.effective_available() else { + notes.push("host memory telemetry is unavailable (MemAvailable): caches are off and the monitor sheds (fail closed)".into()); + return Ok(Plan { + available_before: None, + kar_to_create, + fixed_bytes, + fixed: input.fixed.clone(), + available_after_fixed: None, + elastic: 0, + resident_complement_bytes: 0, + prefix_bytes: 0, + conversation_checkpoints: 0, + conversation_bytes: 0, + soft_floor: policy.soft_floor, + hard_floor: policy.hard_floor, + policy, + blind: true, + vram, + notes, + }); + }; + let needs = fixed_bytes.saturating_add(kar_to_create); + let required_after = policy.soft_floor.saturating_add(policy.reserve); + let after = available.checked_sub(needs); + if after.is_none_or(|r| r < required_after) { + let mut advice = vec![ + "free host memory (stop other processes; `free -g` and the MemAvailable line of /proc/meminfo)".into(), + "use `--expert-source mapped` (read-only mappings of shard 0) instead of the ~50 GB resident copy".into(), + "use `--kar-archive-file` (read-only file) instead of a sealed memfd on small hosts".into(), + "lower --context-tokens (the pinned K/V image is sized by the serving context)".into(), + ]; + if input.host.wsl { + advice.push(wsl_advice().into()); + } + if input.host.cgroup.as_ref().is_some_and(|c| c.limit.is_some()) { + advice.push("raise the cgroup limit (memory.max / systemd MemoryMax=) of the service".into()); + } + let mut numbers = vec![ + ("available".to_owned(), available), + ("fixed host footprint".to_owned(), fixed_bytes), + ]; + if kar_to_create > 0 { + numbers.push(("sealed KAR memfd to create".to_owned(), kar_to_create)); + } + numbers.push(("soft floor + reserve".to_owned(), required_after)); + numbers.push(("short by".to_owned(), required_after.saturating_add(needs).saturating_sub(available))); + let refusal = Refusal { + code: "host_ram", + message: format!( + "the fixed host footprint ({}) leaves {} of {} available, below the {} the runtime needs to stay out of swap and the OOM killer", + gib(needs), + after.map_or("nothing".to_owned(), gib), + gib(available), + gib(required_after) + ), + numbers, + advice, + }; + if policy.enforce { + return Err(refusal); + } + notes.push(format!("ENFORCEMENT OFF: {refusal}")); + } + let after = after.unwrap_or(0); + let mut elastic = after.saturating_sub(required_after); + + // 1. the resident complement (explicit, pinned at open) + let mut complement = 0; + if let Some(wish) = input.resident_complement { + complement = wish.min(elastic); + if complement < wish { + notes.push(format!("resident complement clamped from {} to {} (elastic memory)", gib(wish), gib(complement))); + } + elastic -= complement; + } + // 2. the prefix cache, or the conversation checkpoints it replaces + let (mut prefix_bytes, mut checkpoints, mut conversation_bytes) = (0, 0, 0); + match input.prefix { + CacheWish::Off => { + let each = input.checkpoint_bytes.max(1); + checkpoints = input.conversation_checkpoints.min(elastic / each); + if checkpoints < input.conversation_checkpoints { + notes.push(format!( + "conversation checkpoints reduced from {} to {checkpoints} ({} each, elastic memory {})", + input.conversation_checkpoints, + gib(input.checkpoint_bytes), + gib(elastic) + )); + } + conversation_bytes = checkpoints * input.checkpoint_bytes; + } + CacheWish::Auto => { + let share = (u128::from(elastic) * u128::from(policy.cache_share_percent.min(100)) / 100) as u64; + let bytes = share.min(policy.prefix_cap) / MIB * MIB; + if bytes < policy.min_useful_cache { + notes.push(format!( + "prefix cache off: auto budget {} is below the useful minimum {}", + gib(bytes), + gib(policy.min_useful_cache) + )); + } else { + prefix_bytes = bytes; + } + } + CacheWish::Bytes(wish) => { + prefix_bytes = wish.min(elastic) / MIB * MIB; + if prefix_bytes < wish { + notes.push(format!( + "prefix cache clamped from {} to {} (elastic memory {}); lower --prefix-cache-mib or free memory", + gib(wish), + gib(prefix_bytes), + gib(elastic) + )); + } + } + } + Ok(Plan { + available_before: Some(available), + kar_to_create, + fixed_bytes, + fixed: input.fixed.clone(), + available_after_fixed: Some(after), + elastic: elastic + complement, + resident_complement_bytes: complement, + prefix_bytes, + conversation_checkpoints: checkpoints, + conversation_bytes, + soft_floor: policy.soft_floor, + hard_floor: policy.hard_floor, + policy, + blind: false, + vram, + notes, + }) +} diff --git a/crates/leleka-memory/src/telemetry.rs b/crates/leleka-memory/src/telemetry.rs index 341d6f68..8ccd64c6 100644 --- a/crates/leleka-memory/src/telemetry.rs +++ b/crates/leleka-memory/src/telemetry.rs @@ -128,152 +128,6 @@ static STATE: Mutex> = Mutex::new(None); static PUBLISHED: Mutex> = Mutex::new(None); static SETTINGS: Mutex> = Mutex::new(None); -fn lock(m: &Mutex) -> MutexGuard<'_, T> { - m.lock().unwrap_or_else(|p| p.into_inner()) -} - -fn with_state(f: impl FnOnce(&mut State)) { - f(lock(&STATE).get_or_insert_with(State::default)); -} - -/// The last document the sampler published (JSON text). -pub fn published_telemetry() -> Option { - lock(&PUBLISHED).clone() -} - -/// The settings the engine runs with now (context, prefill chunk, caches, workers...): rendered as `settings` in the document. -pub fn set_settings(settings: serde_json::Value) { - *lock(&SETTINGS) = Some(settings); -} - -/// The context window the engine serves (tokens); constant until a reconfigure. -pub fn set_context_max(tokens: u64) { - with_state(|s| s.context_max = tokens); -} - -/// A request entered the engine with `prompt_tokens` in its prompt (the cache hit is known when it finishes; the figures of the last finished request stay until then). -pub fn request_started(prompt_tokens: u64) { - with_state(|s| { - s.phase = Phase::Prefill; - s.started = Some(Instant::now()); - s.first_token = None; - s.produced_now = 0; - s.prompt_now = prompt_tokens; - s.context_live = prompt_tokens; - }); -} - -/// Tokens were delivered: the first delivery ends the prefill phase. -pub fn tokens_delivered(count: u64) { - with_state(|s| { - if s.first_token.is_none() { - s.first_token = Some(Instant::now()); - s.phase = Phase::Decode; - } - s.produced_now += count; - s.context_live += count; - }); -} - -/// The NaN guard retried a window whose logits or stage outputs were not finite from the round's checkpoint, and the retry was good. -/// `what` names it for the operator (position, rows, attempt, the error class); the last one is kept in the document. -pub fn nan_guard_healed(what: &str) { - with_state(|s| { - s.nan_healed += 1; - s.nan_last = Some(format!("healed: {what}")); - }); -} - -/// The NaN guard gave up on a non-finite window (no retry left, or the checkpoint could not be restored): the request fails as before. -pub fn nan_guard_unhealed(what: &str) { - with_state(|s| { - s.nan_unhealed += 1; - s.nan_last = Some(format!("unhealed: {what}")); - }); -} - -/// A request ended without numbers worth folding in (cancelled or failed): the engine is idle again. -pub fn request_aborted() { - with_state(|s| { - s.phase = Phase::Idle; - s.started = None; - s.first_token = None; - }); -} - -/// A request finished (any outcome that produced numbers): fold it into the lifetime figures. -pub fn request_finished(prompt_tokens: u64, reused_tokens: u64, produced: u64, prompt_ms: f64, decode_ms: f64) { - with_state(|s| { - s.phase = Phase::Idle; - s.started = None; - s.first_token = None; - s.requests += 1; - s.prompt_tokens += prompt_tokens; - s.reused_tokens += reused_tokens; - s.produced_tokens += produced; - if reused_tokens > 0 { - s.cache_hit_requests += 1; - } - s.last_prompt_tokens = prompt_tokens; - s.last_reused_tokens = reused_tokens; - s.last_produced_for_spec = produced; - s.last_prefill_ms = prompt_ms; - s.last_decode_ms = decode_ms; - s.context_live = prompt_tokens + produced; - let prefilled = prompt_tokens.saturating_sub(reused_tokens); - if prefilled > 0 && prompt_ms > 0.0 { - let rate = prefilled as f64 * 1e3 / prompt_ms; - s.prefill_tokens += prefilled; - s.prefill_ms += prompt_ms; - s.last_prefill_tok_s = Some(rate); - s.prefill_ema = Some(ema(s.prefill_ema, rate)); - } - if produced > 0 && decode_ms > 0.0 { - let rate = produced as f64 * 1e3 / decode_ms; - s.decode_tokens += produced; - s.decode_ms += decode_ms; - s.last_decode_tok_s = Some(rate); - s.decode_ema = Some(ema(s.decode_ema, rate)); - } - }); -} - -/// The engine's own account of the request that just finished: its id, the rounds the speculative loop ran and the -/// expert tier's counters (lifetime of the stack). Call after [`request_finished`]. -pub fn request_detail(request_id: &str, rounds: u64, tier: Option) { - with_state(|s| { - let produced = s.last_produced_for_spec; - s.spec_rounds += rounds; - s.spec_tokens += produced; - s.last_request = Some(LastRequest { - request_id: request_id.chars().take(64).collect(), - prompt_tokens: s.last_prompt_tokens, - reused_tokens: s.last_reused_tokens, - produced_tokens: produced, - rounds, - tokens_per_round: (rounds > 0).then(|| (produced as f64 / rounds as f64 * 100.0).round() / 100.0), - prefill_ms: s.last_prefill_ms, - decode_ms: s.last_decode_ms, - }); - if tier.is_some() { - s.expert_tier = tier; - } - }); -} - -/// The share (percent, one decimal) of expert entries served from VRAM / over PCIe / by the CPU in one request: the counters are -/// the stack's lifetime, so it is the difference to the previous request (or all of them after a reload, when they went back). -pub fn tier_shares(previous: Option<&TierCounters>, now: &TierCounters) -> (f64, f64, f64) { - let base = previous.filter(|p| now.vram_entries >= p.vram_entries && now.pcie_entries >= p.pcie_entries && now.cpu_entries >= p.cpu_entries); - let (v, p, c) = match base { - Some(b) => (now.vram_entries - b.vram_entries, now.pcie_entries - b.pcie_entries, now.cpu_entries - b.cpu_entries), - None => (now.vram_entries, now.pcie_entries, now.cpu_entries), - }; - let all = (v + p + c).max(1) as f64; - let pct = |n: u64| (n as f64 * 1e3 / all).round() / 10.0; - (pct(v), pct(p), pct(c)) -} - /// What the engine says about one finished request in its own log line. pub struct RequestLine<'a> { pub request_id: &'a str, @@ -288,38 +142,6 @@ pub struct RequestLine<'a> { pub shares: Option<(f64, f64, f64)>, } -/// The fields of the engine's one structured line per request (`engine.log`), keyed by the id the API gave the request so that -/// `leleka logs --request ID` joins it with the API's record. Pure, so its content and size are testable. -pub fn request_line_fields<'a>(r: &RequestLine<'a>) -> Vec> { - use leleka_obs::V; - let fresh = r.input_tokens.saturating_sub(r.reused_tokens); - let rate = |tokens: u64, ms: f64| (tokens > 0 && ms > 0.0).then(|| (tokens as f64 * 1e4 / ms).round() / 10.0); - let mut fields: Vec> = vec![ - ("rid", V::Str(r.request_id)), - ("ptok", r.input_tokens.into()), - ("ctok", r.reused_tokens.into()), - ("otok", r.output_tokens.into()), - ("rounds", r.rounds.into()), - ("tok_per_round", (r.rounds > 0).then(|| (r.produced as f64 * 100.0 / r.rounds as f64).round() / 100.0).into()), - ("pf_ms", V::Float((r.prefill_ms * 10.0).round() / 10.0)), - ("dec_ms", V::Float((r.decode_ms * 10.0).round() / 10.0)), - ("pf_tps", rate(fresh, r.prefill_ms).into()), - ("dec_tps", rate(r.output_tokens, r.decode_ms).into()), - ]; - if let Some((vram, pcie, cpu)) = r.shares { - fields.extend([("tier_vram_pct", V::Float(vram)), ("tier_pcie_pct", V::Float(pcie)), ("tier_cpu_pct", V::Float(cpu))]); - } - fields -} - -fn ema(previous: Option, value: f64) -> f64 { - previous.map_or(value, |p| p + EMA_ALPHA * (value - p)) -} - -fn round1(value: f64) -> f64 { - (value * 10.0).round() / 10.0 -} - /// Process and system CPU time read at one instant. #[derive(Clone, Copy, Debug, Default, PartialEq)] pub struct CpuReading { @@ -330,48 +152,6 @@ pub struct CpuReading { pub system_total: u64, } -/// `/proc/self/stat`: utime and stime are fields 14 and 15 (counted after the parenthesised command name). -pub fn parse_self_stat_ticks(text: &str) -> Option { - let rest = text.rsplit_once(')')?.1; - let fields: Vec<&str> = rest.split_ascii_whitespace().collect(); - // after ")" the fields start at 3 (state); utime is 14, stime 15 - let utime: u64 = fields.get(11)?.parse().ok()?; - let stime: u64 = fields.get(12)?.parse().ok()?; - Some(utime + stime) -} - -/// `/proc/stat` first line: (busy, total) ticks over all CPUs. -pub fn parse_stat_cpu(text: &str) -> Option<(u64, u64)> { - let line = text.lines().next()?; - let mut parts = line.split_ascii_whitespace(); - if parts.next()? != "cpu" { - return None; - } - let values: Vec = parts.filter_map(|v| v.parse().ok()).collect(); - if values.len() < 4 { - return None; - } - let idle = values[3] + values.get(4).copied().unwrap_or(0); - let total: u64 = values.iter().take(8).sum(); - Some((total.saturating_sub(idle), total)) -} - -pub fn read_cpu(src: &dyn ProcSource) -> Option { - let process_ticks = parse_self_stat_ticks(&src.read("/proc/self/stat").ok()?)?; - let (system_busy, system_total) = parse_stat_cpu(&src.read("/proc/stat").ok()?)?; - Some(CpuReading { process_ticks, system_busy, system_total }) -} - -/// Cores worth of CPU this process used between two readings, and the whole system's busy percentage. -pub fn cpu_usage(before: &CpuReading, after: &CpuReading, wall: Duration) -> (f64, f64) { - let seconds = wall.as_secs_f64().max(1e-6); - let process = after.process_ticks.saturating_sub(before.process_ticks) as f64 / USER_HZ / seconds; - let total = after.system_total.saturating_sub(before.system_total); - let busy = after.system_busy.saturating_sub(before.system_busy); - let system = if total == 0 { 0.0 } else { 100.0 * busy as f64 / total as f64 }; - (process, system) -} - #[derive(Debug, Serialize)] struct Ram { total_mib: u64, @@ -470,14 +250,6 @@ struct Document { settings: Option, } -fn ratio(part: u64, whole: u64) -> Option { - (whole > 0).then(|| (part as f64 / whole as f64 * 1e4).round() / 1e4) -} - -fn lifetime_rate(tokens: u64, ms: f64) -> Option { - (ms > 0.0).then(|| round1(tokens as f64 * 1e3 / ms)) -} - /// Everything the sampler measured this tick. pub struct Measured { pub now_ms: u64, @@ -489,142 +261,16 @@ pub struct Measured { pub cpu: Option<(f64, f64)>, } -fn render(state: &State, measured: &Measured) -> String { - let mib = |bytes: Option| bytes.map_or(0, |b| b >> 20); - let ram = measured.meminfo.mem_total.map(|total| Ram { - total_mib: total >> 20, - available_mib: mib(measured.meminfo.mem_available), - process_rss_mib: mib(measured.status.vm_rss), - process_pinned_mib: mib(measured.status.vm_pin), - swap_used_mib: measured.meminfo.swap_total.unwrap_or(0).saturating_sub(measured.meminfo.swap_free.unwrap_or(0)) >> 20, - }); - let live_rate = match (state.phase, state.first_token) { - (Phase::Decode, Some(first)) if state.produced_now > 1 => { - let secs = first.elapsed().as_secs_f64(); - (secs > 0.05).then(|| round1(state.produced_now as f64 / secs)) - } - _ => None, - }; - let document = Document { - version: 1, - ts_ms: measured.now_ms, - uptime_s: measured.uptime_s, - phase: state.phase, - request: state.started.filter(|_| state.phase != Phase::Idle).map(|started| LiveRequest { - prompt_tokens: state.prompt_now, - generated_tokens: state.produced_now, - elapsed_s: (started.elapsed().as_secs_f64() * 10.0).round() / 10.0, - }), - gpu: measured.gpu.clone(), - ram, - cpu: measured.cpu.map(|(process, system)| Cpu { - cores: measured.cores, - process_busy_cores: round1(process), - system_busy_pct: round1(system), - }), - throughput: Rates { - prefill_tok_s_last: state.last_prefill_tok_s.map(round1), - prefill_tok_s_avg: state.prefill_ema.map(round1), - prefill_tok_s_lifetime: lifetime_rate(state.prefill_tokens, state.prefill_ms), - decode_tok_s_last: state.last_decode_tok_s.map(round1), - decode_tok_s_avg: state.decode_ema.map(round1), - decode_tok_s_lifetime: lifetime_rate(state.decode_tokens, state.decode_ms), - decode_tok_s_live: live_rate, - }, - cache: Cache { - requests: state.requests, - hit_requests: state.cache_hit_requests, - hit_ratio: ratio(state.cache_hit_requests, state.requests), - prompt_tokens: state.prompt_tokens, - reused_tokens: state.reused_tokens, - token_hit_ratio: ratio(state.reused_tokens, state.prompt_tokens), - last_prompt_tokens: state.last_prompt_tokens, - last_reused_tokens: state.last_reused_tokens, - }, - context: Context { - live_tokens: state.context_live, - max_tokens: state.context_max, - used_pct: ratio(state.context_live, state.context_max).map(|r| (r * 1e4).round() / 1e2), - }, - nan_guard: NanGuard { healed_windows: state.nan_healed, unhealed_windows: state.nan_unhealed, last: state.nan_last.clone() }, - spec: Spec { - rounds: state.spec_rounds, - tokens: state.spec_tokens, - tokens_per_round: (state.spec_rounds > 0).then(|| (state.spec_tokens as f64 / state.spec_rounds as f64 * 100.0).round() / 100.0), - }, - expert_tier: state.expert_tier.map(|counters| Tier { - counters, - vram_ratio: ratio(counters.vram_entries, counters.vram_entries + counters.pcie_entries + counters.cpu_entries), - }), - last_request: state.last_request.clone(), - settings: lock(&SETTINGS).clone(), - }; - serde_json::to_string(&document).unwrap_or_default() -} - -/// Render the current document from the recorded state and one measurement (public for tests and for a one-shot read). -pub fn render_now(measured: &Measured) -> String { - let guard = lock(&STATE); - match guard.as_ref() { - Some(state) => render(state, measured), - None => render(&State::default(), measured), - } -} - pub struct Sampler { stop: Arc, } -impl Sampler { - pub fn stop(&self) { - self.stop.store(true, Ordering::Release); - } -} - -impl Drop for Sampler { - fn drop(&mut self) { - self.stop(); - } -} - -/// Start the once-a-second sampler over the real `/proc`. `gpu_probe` reads the device (NVML); `None` reports no GPU block. -pub fn start(gpu_probe: Option, period: Duration) -> Sampler { - let stop = Arc::new(AtomicBool::new(false)); - let flag = stop.clone(); - let spawned = std::thread::Builder::new().name("leleka-telemetry".into()).spawn(move || { - let src = RealProc; - let began = Instant::now(); - let cores = std::thread::available_parallelism().map_or(0, |n| n.get() as u32); - let mut previous = read_cpu(&src).map(|reading| (reading, Instant::now())); - while !flag.load(Ordering::Acquire) { - std::thread::sleep(period); - let now = Instant::now(); - let reading = read_cpu(&src); - let cpu = match (&previous, &reading) { - (Some((before, at)), Some(after)) => Some(cpu_usage(before, after, now.duration_since(*at))), - _ => None, - }; - if let Some(reading) = reading { - previous = Some((reading, now)); - } - let measured = Measured { - now_ms: SystemTime::now().duration_since(UNIX_EPOCH).map_or(0, |d| d.as_millis() as u64), - uptime_s: began.elapsed().as_secs(), - gpu: gpu_probe.as_ref().and_then(|probe| probe()), - meminfo: procfs::parse_meminfo(&src.read("/proc/meminfo").unwrap_or_default()), - status: procfs::parse_status(&src.read("/proc/self/status").unwrap_or_default()), - cores, - cpu, - }; - let text = render_now(&measured); - *lock(&PUBLISHED) = Some(text); - } - }); - if spawned.is_err() { - stop.store(true, Ordering::Release); - } - Sampler { stop } -} - #[cfg(test)] mod tests; + +mod lock; +#[allow(unused_imports)] +pub use lock::*; +mod render; +#[allow(unused_imports)] +pub use render::*; diff --git a/crates/leleka-memory/src/telemetry/lock.rs b/crates/leleka-memory/src/telemetry/lock.rs new file mode 100644 index 00000000..dc2a2f41 --- /dev/null +++ b/crates/leleka-memory/src/telemetry/lock.rs @@ -0,0 +1,233 @@ +//! Moved out of the parent module by STRA-338: fn lock, fn with_state, fn published_telemetry, fn set_settings, fn set_context_max, fn request_started .... + +#[allow(unused_imports)] +use super::*; + + +pub(super) fn lock(m: &Mutex) -> MutexGuard<'_, T> { + m.lock().unwrap_or_else(|p| p.into_inner()) +} + +pub(super) fn with_state(f: impl FnOnce(&mut State)) { + f(lock(&STATE).get_or_insert_with(State::default)); +} + +/// The last document the sampler published (JSON text). +pub fn published_telemetry() -> Option { + lock(&PUBLISHED).clone() +} + +/// The settings the engine runs with now (context, prefill chunk, caches, workers...): rendered as `settings` in the document. +pub fn set_settings(settings: serde_json::Value) { + *lock(&SETTINGS) = Some(settings); +} + +/// The context window the engine serves (tokens); constant until a reconfigure. +pub fn set_context_max(tokens: u64) { + with_state(|s| s.context_max = tokens); +} + +/// A request entered the engine with `prompt_tokens` in its prompt (the cache hit is known when it finishes; the figures of the last finished request stay until then). +pub fn request_started(prompt_tokens: u64) { + with_state(|s| { + s.phase = Phase::Prefill; + s.started = Some(Instant::now()); + s.first_token = None; + s.produced_now = 0; + s.prompt_now = prompt_tokens; + s.context_live = prompt_tokens; + }); +} + +/// Tokens were delivered: the first delivery ends the prefill phase. +pub fn tokens_delivered(count: u64) { + with_state(|s| { + if s.first_token.is_none() { + s.first_token = Some(Instant::now()); + s.phase = Phase::Decode; + } + s.produced_now += count; + s.context_live += count; + }); +} + +/// The NaN guard retried a window whose logits or stage outputs were not finite from the round's checkpoint, and the retry was good. +/// `what` names it for the operator (position, rows, attempt, the error class); the last one is kept in the document. +pub fn nan_guard_healed(what: &str) { + with_state(|s| { + s.nan_healed += 1; + s.nan_last = Some(format!("healed: {what}")); + }); +} + +/// The NaN guard gave up on a non-finite window (no retry left, or the checkpoint could not be restored): the request fails as before. +pub fn nan_guard_unhealed(what: &str) { + with_state(|s| { + s.nan_unhealed += 1; + s.nan_last = Some(format!("unhealed: {what}")); + }); +} + +/// A request ended without numbers worth folding in (cancelled or failed): the engine is idle again. +pub fn request_aborted() { + with_state(|s| { + s.phase = Phase::Idle; + s.started = None; + s.first_token = None; + }); +} + +/// A request finished (any outcome that produced numbers): fold it into the lifetime figures. +pub fn request_finished(prompt_tokens: u64, reused_tokens: u64, produced: u64, prompt_ms: f64, decode_ms: f64) { + with_state(|s| { + s.phase = Phase::Idle; + s.started = None; + s.first_token = None; + s.requests += 1; + s.prompt_tokens += prompt_tokens; + s.reused_tokens += reused_tokens; + s.produced_tokens += produced; + if reused_tokens > 0 { + s.cache_hit_requests += 1; + } + s.last_prompt_tokens = prompt_tokens; + s.last_reused_tokens = reused_tokens; + s.last_produced_for_spec = produced; + s.last_prefill_ms = prompt_ms; + s.last_decode_ms = decode_ms; + s.context_live = prompt_tokens + produced; + let prefilled = prompt_tokens.saturating_sub(reused_tokens); + if prefilled > 0 && prompt_ms > 0.0 { + let rate = prefilled as f64 * 1e3 / prompt_ms; + s.prefill_tokens += prefilled; + s.prefill_ms += prompt_ms; + s.last_prefill_tok_s = Some(rate); + s.prefill_ema = Some(ema(s.prefill_ema, rate)); + } + if produced > 0 && decode_ms > 0.0 { + let rate = produced as f64 * 1e3 / decode_ms; + s.decode_tokens += produced; + s.decode_ms += decode_ms; + s.last_decode_tok_s = Some(rate); + s.decode_ema = Some(ema(s.decode_ema, rate)); + } + }); +} + +/// The engine's own account of the request that just finished: its id, the rounds the speculative loop ran and the +/// expert tier's counters (lifetime of the stack). Call after [`request_finished`]. +pub fn request_detail(request_id: &str, rounds: u64, tier: Option) { + with_state(|s| { + let produced = s.last_produced_for_spec; + s.spec_rounds += rounds; + s.spec_tokens += produced; + s.last_request = Some(LastRequest { + request_id: request_id.chars().take(64).collect(), + prompt_tokens: s.last_prompt_tokens, + reused_tokens: s.last_reused_tokens, + produced_tokens: produced, + rounds, + tokens_per_round: (rounds > 0).then(|| (produced as f64 / rounds as f64 * 100.0).round() / 100.0), + prefill_ms: s.last_prefill_ms, + decode_ms: s.last_decode_ms, + }); + if tier.is_some() { + s.expert_tier = tier; + } + }); +} + +/// The share (percent, one decimal) of expert entries served from VRAM / over PCIe / by the CPU in one request: the counters are +/// the stack's lifetime, so it is the difference to the previous request (or all of them after a reload, when they went back). +pub fn tier_shares(previous: Option<&TierCounters>, now: &TierCounters) -> (f64, f64, f64) { + let base = previous.filter(|p| now.vram_entries >= p.vram_entries && now.pcie_entries >= p.pcie_entries && now.cpu_entries >= p.cpu_entries); + let (v, p, c) = match base { + Some(b) => (now.vram_entries - b.vram_entries, now.pcie_entries - b.pcie_entries, now.cpu_entries - b.cpu_entries), + None => (now.vram_entries, now.pcie_entries, now.cpu_entries), + }; + let all = (v + p + c).max(1) as f64; + let pct = |n: u64| (n as f64 * 1e3 / all).round() / 10.0; + (pct(v), pct(p), pct(c)) +} + +/// The fields of the engine's one structured line per request (`engine.log`), keyed by the id the API gave the request so that +/// `leleka logs --request ID` joins it with the API's record. Pure, so its content and size are testable. +pub fn request_line_fields<'a>(r: &RequestLine<'a>) -> Vec> { + use leleka_obs::V; + let fresh = r.input_tokens.saturating_sub(r.reused_tokens); + let rate = |tokens: u64, ms: f64| (tokens > 0 && ms > 0.0).then(|| (tokens as f64 * 1e4 / ms).round() / 10.0); + let mut fields: Vec> = vec![ + ("rid", V::Str(r.request_id)), + ("ptok", r.input_tokens.into()), + ("ctok", r.reused_tokens.into()), + ("otok", r.output_tokens.into()), + ("rounds", r.rounds.into()), + ("tok_per_round", (r.rounds > 0).then(|| (r.produced as f64 * 100.0 / r.rounds as f64).round() / 100.0).into()), + ("pf_ms", V::Float((r.prefill_ms * 10.0).round() / 10.0)), + ("dec_ms", V::Float((r.decode_ms * 10.0).round() / 10.0)), + ("pf_tps", rate(fresh, r.prefill_ms).into()), + ("dec_tps", rate(r.output_tokens, r.decode_ms).into()), + ]; + if let Some((vram, pcie, cpu)) = r.shares { + fields.extend([("tier_vram_pct", V::Float(vram)), ("tier_pcie_pct", V::Float(pcie)), ("tier_cpu_pct", V::Float(cpu))]); + } + fields +} + +pub(super) fn ema(previous: Option, value: f64) -> f64 { + previous.map_or(value, |p| p + EMA_ALPHA * (value - p)) +} + +pub(super) fn round1(value: f64) -> f64 { + (value * 10.0).round() / 10.0 +} + +/// `/proc/self/stat`: utime and stime are fields 14 and 15 (counted after the parenthesised command name). +pub fn parse_self_stat_ticks(text: &str) -> Option { + let rest = text.rsplit_once(')')?.1; + let fields: Vec<&str> = rest.split_ascii_whitespace().collect(); + // after ")" the fields start at 3 (state); utime is 14, stime 15 + let utime: u64 = fields.get(11)?.parse().ok()?; + let stime: u64 = fields.get(12)?.parse().ok()?; + Some(utime + stime) +} + +/// `/proc/stat` first line: (busy, total) ticks over all CPUs. +pub fn parse_stat_cpu(text: &str) -> Option<(u64, u64)> { + let line = text.lines().next()?; + let mut parts = line.split_ascii_whitespace(); + if parts.next()? != "cpu" { + return None; + } + let values: Vec = parts.filter_map(|v| v.parse().ok()).collect(); + if values.len() < 4 { + return None; + } + let idle = values[3] + values.get(4).copied().unwrap_or(0); + let total: u64 = values.iter().take(8).sum(); + Some((total.saturating_sub(idle), total)) +} + +pub fn read_cpu(src: &dyn ProcSource) -> Option { + let process_ticks = parse_self_stat_ticks(&src.read("/proc/self/stat").ok()?)?; + let (system_busy, system_total) = parse_stat_cpu(&src.read("/proc/stat").ok()?)?; + Some(CpuReading { process_ticks, system_busy, system_total }) +} + +/// Cores worth of CPU this process used between two readings, and the whole system's busy percentage. +pub fn cpu_usage(before: &CpuReading, after: &CpuReading, wall: Duration) -> (f64, f64) { + let seconds = wall.as_secs_f64().max(1e-6); + let process = after.process_ticks.saturating_sub(before.process_ticks) as f64 / USER_HZ / seconds; + let total = after.system_total.saturating_sub(before.system_total); + let busy = after.system_busy.saturating_sub(before.system_busy); + let system = if total == 0 { 0.0 } else { 100.0 * busy as f64 / total as f64 }; + (process, system) +} + +pub(super) fn ratio(part: u64, whole: u64) -> Option { + (whole > 0).then(|| (part as f64 / whole as f64 * 1e4).round() / 1e4) +} + +pub(super) fn lifetime_rate(tokens: u64, ms: f64) -> Option { + (ms > 0.0).then(|| round1(tokens as f64 * 1e3 / ms)) +} diff --git a/crates/leleka-memory/src/telemetry/render.rs b/crates/leleka-memory/src/telemetry/render.rs new file mode 100644 index 00000000..2ee901a9 --- /dev/null +++ b/crates/leleka-memory/src/telemetry/render.rs @@ -0,0 +1,138 @@ +//! Moved out of the parent module by STRA-338: fn render, fn render_now, impl Sampler, impl Drop_for_Sampler, fn start. + +#[allow(unused_imports)] +use super::*; + + +pub(super) fn render(state: &State, measured: &Measured) -> String { + let mib = |bytes: Option| bytes.map_or(0, |b| b >> 20); + let ram = measured.meminfo.mem_total.map(|total| Ram { + total_mib: total >> 20, + available_mib: mib(measured.meminfo.mem_available), + process_rss_mib: mib(measured.status.vm_rss), + process_pinned_mib: mib(measured.status.vm_pin), + swap_used_mib: measured.meminfo.swap_total.unwrap_or(0).saturating_sub(measured.meminfo.swap_free.unwrap_or(0)) >> 20, + }); + let live_rate = match (state.phase, state.first_token) { + (Phase::Decode, Some(first)) if state.produced_now > 1 => { + let secs = first.elapsed().as_secs_f64(); + (secs > 0.05).then(|| round1(state.produced_now as f64 / secs)) + } + _ => None, + }; + let document = Document { + version: 1, + ts_ms: measured.now_ms, + uptime_s: measured.uptime_s, + phase: state.phase, + request: state.started.filter(|_| state.phase != Phase::Idle).map(|started| LiveRequest { + prompt_tokens: state.prompt_now, + generated_tokens: state.produced_now, + elapsed_s: (started.elapsed().as_secs_f64() * 10.0).round() / 10.0, + }), + gpu: measured.gpu.clone(), + ram, + cpu: measured.cpu.map(|(process, system)| Cpu { + cores: measured.cores, + process_busy_cores: round1(process), + system_busy_pct: round1(system), + }), + throughput: Rates { + prefill_tok_s_last: state.last_prefill_tok_s.map(round1), + prefill_tok_s_avg: state.prefill_ema.map(round1), + prefill_tok_s_lifetime: lifetime_rate(state.prefill_tokens, state.prefill_ms), + decode_tok_s_last: state.last_decode_tok_s.map(round1), + decode_tok_s_avg: state.decode_ema.map(round1), + decode_tok_s_lifetime: lifetime_rate(state.decode_tokens, state.decode_ms), + decode_tok_s_live: live_rate, + }, + cache: Cache { + requests: state.requests, + hit_requests: state.cache_hit_requests, + hit_ratio: ratio(state.cache_hit_requests, state.requests), + prompt_tokens: state.prompt_tokens, + reused_tokens: state.reused_tokens, + token_hit_ratio: ratio(state.reused_tokens, state.prompt_tokens), + last_prompt_tokens: state.last_prompt_tokens, + last_reused_tokens: state.last_reused_tokens, + }, + context: Context { + live_tokens: state.context_live, + max_tokens: state.context_max, + used_pct: ratio(state.context_live, state.context_max).map(|r| (r * 1e4).round() / 1e2), + }, + nan_guard: NanGuard { healed_windows: state.nan_healed, unhealed_windows: state.nan_unhealed, last: state.nan_last.clone() }, + spec: Spec { + rounds: state.spec_rounds, + tokens: state.spec_tokens, + tokens_per_round: (state.spec_rounds > 0).then(|| (state.spec_tokens as f64 / state.spec_rounds as f64 * 100.0).round() / 100.0), + }, + expert_tier: state.expert_tier.map(|counters| Tier { + counters, + vram_ratio: ratio(counters.vram_entries, counters.vram_entries + counters.pcie_entries + counters.cpu_entries), + }), + last_request: state.last_request.clone(), + settings: lock(&SETTINGS).clone(), + }; + serde_json::to_string(&document).unwrap_or_default() +} + +/// Render the current document from the recorded state and one measurement (public for tests and for a one-shot read). +pub fn render_now(measured: &Measured) -> String { + let guard = lock(&STATE); + match guard.as_ref() { + Some(state) => render(state, measured), + None => render(&State::default(), measured), + } +} + +impl Sampler { + pub fn stop(&self) { + self.stop.store(true, Ordering::Release); + } +} + +impl Drop for Sampler { + fn drop(&mut self) { + self.stop(); + } +} + +/// Start the once-a-second sampler over the real `/proc`. `gpu_probe` reads the device (NVML); `None` reports no GPU block. +pub fn start(gpu_probe: Option, period: Duration) -> Sampler { + let stop = Arc::new(AtomicBool::new(false)); + let flag = stop.clone(); + let spawned = std::thread::Builder::new().name("leleka-telemetry".into()).spawn(move || { + let src = RealProc; + let began = Instant::now(); + let cores = std::thread::available_parallelism().map_or(0, |n| n.get() as u32); + let mut previous = read_cpu(&src).map(|reading| (reading, Instant::now())); + while !flag.load(Ordering::Acquire) { + std::thread::sleep(period); + let now = Instant::now(); + let reading = read_cpu(&src); + let cpu = match (&previous, &reading) { + (Some((before, at)), Some(after)) => Some(cpu_usage(before, after, now.duration_since(*at))), + _ => None, + }; + if let Some(reading) = reading { + previous = Some((reading, now)); + } + let measured = Measured { + now_ms: SystemTime::now().duration_since(UNIX_EPOCH).map_or(0, |d| d.as_millis() as u64), + uptime_s: began.elapsed().as_secs(), + gpu: gpu_probe.as_ref().and_then(|probe| probe()), + meminfo: procfs::parse_meminfo(&src.read("/proc/meminfo").unwrap_or_default()), + status: procfs::parse_status(&src.read("/proc/self/status").unwrap_or_default()), + cores, + cpu, + }; + let text = render_now(&measured); + *lock(&PUBLISHED) = Some(text); + } + }); + if spawned.is_err() { + stop.store(true, Ordering::Release); + } + Sampler { stop } +} diff --git a/crates/libc-shim/src/cuda_trace.rs b/crates/libc-shim/src/cuda_trace.rs index 82a568d7..97d0fe21 100644 --- a/crates/libc-shim/src/cuda_trace.rs +++ b/crates/libc-shim/src/cuda_trace.rs @@ -27,11 +27,6 @@ use windows_sys::Win32::System::LibraryLoader::{GetModuleHandleA, GetProcAddress const RING: usize = 16384; const NOT_READY: c_int = 600; -fn enabled() -> bool { - static ON: OnceLock = OnceLock::new(); - *ON.get_or_init(|| std::env::var_os("LELEKA_BRINGUP_TRACE").is_some()) -} - #[derive(Clone, Copy)] struct Entry { seq: u64, @@ -62,26 +57,6 @@ struct State { streams: Vec, } -fn state() -> &'static Mutex { - static S: OnceLock> = OnceLock::new(); - S.get_or_init(|| { - Mutex::new(State { - ring: vec![None; RING], - next: 1, - names: HashMap::new(), - stream_ok: HashMap::new(), - ctx_ok: 0, - capturing: HashMap::new(), - failures: 0, - streams: Vec::new(), - }) - }) -} - -fn lock() -> std::sync::MutexGuard<'static, State> { - state().lock().unwrap_or_else(|e| e.into_inner()) -} - const SLOTS: usize = 24; static REAL: [AtomicUsize; SLOTS] = [const { AtomicUsize::new(0) }; SLOTS]; static LAUNCHES: AtomicU64 = AtomicU64::new(0); @@ -96,181 +71,6 @@ static CALLBACKS: AtomicBool = AtomicBool::new(false); const STREAM_SLOTS: usize = 16; static DONE: [AtomicU64; STREAM_SLOTS] = [const { AtomicU64::new(0) }; STREAM_SLOTS]; -unsafe extern "C" fn done_callback(argument: *mut c_void) { - let value = argument as usize as u64; - DONE[(value >> 56) as usize % STREAM_SLOTS].fetch_max(value & ((1 << 56) - 1), Ordering::Relaxed); -} - -/// Queue the completion callback of operation `seq` on `stream`. -fn queue_callback(stream: usize, seq: u64) { - if !CALLBACKS.load(Ordering::Relaxed) { - return; - } - type HostFunc = unsafe extern "C" fn(usize, usize, usize) -> c_int; - static F: OnceLock = OnceLock::new(); - let address = *F.get_or_init(|| { - // SAFETY: valid module handle and NUL-terminated symbol name. - unsafe { GetProcAddress(nvcuda() as _, c"cuLaunchHostFunc".as_ptr().cast()).map_or(0, |f| f as usize) } - }); - if address == 0 { - return; - } - let index = { - let mut s = lock(); - match s.streams.iter().position(|&x| x == stream) { - Some(i) => i, - None if s.streams.len() < STREAM_SLOTS => { - s.streams.push(stream); - s.streams.len() - 1 - } - None => return, - } - }; - // SAFETY: the address is the driver's cuLaunchHostFunc; the callback only stores to an atomic. - let real: HostFunc = unsafe { std::mem::transmute(address) }; - let _ = unsafe { real(stream, done_callback as *const () as usize, ((index as u64) << 56 | seq) as usize) }; -} - -/// Switch the per-launch synchronization on or off. It is only ever on when `LELEKA_BRINGUP_TRACE` and -/// `LELEKA_CUDA_TRACE_SYNC` are both set, and the runtime turns it on only around the prompt (prefill) forward: the -/// decode windows launch polling kernels that a per-launch synchronization would deadlock, exactly like -/// `CUDA_LAUNCH_BLOCKING`. Returns whether it is now on. -pub fn set_sync(on: bool) -> bool { - static ALLOWED: OnceLock = OnceLock::new(); - static CALLBACK_ALLOWED: OnceLock = OnceLock::new(); - let allowed = *ALLOWED.get_or_init(|| enabled() && std::env::var_os("LELEKA_CUDA_TRACE_SYNC").is_some()); - let callbacks = *CALLBACK_ALLOWED.get_or_init(|| enabled() && std::env::var_os("LELEKA_CUDA_TRACE_CALLBACKS").is_some()); - SYNC.store(on && allowed, Ordering::Relaxed); - CALLBACKS.store(on && callbacks, Ordering::Relaxed); - on && (allowed || callbacks) -} - -fn real_stream_synchronize() -> Option c_int> { - static F: OnceLock = OnceLock::new(); - let address = *F.get_or_init(|| { - let slot = REAL[1].load(Ordering::Relaxed); - if slot != 0 { - return slot; - } - // SAFETY: valid module handle and NUL-terminated symbol name. - unsafe { GetProcAddress(nvcuda() as _, c"cuStreamSynchronize".as_ptr().cast()).map_or(0, |f| f as usize) } - }); - // SAFETY: the address is the driver's cuStreamSynchronize. - (address != 0).then(|| unsafe { std::mem::transmute:: c_int>(address) }) -} - -fn nvcuda() -> *mut c_void { - // SAFETY: NUL-terminated literal; GetModuleHandleA does not take a reference. - unsafe { GetModuleHandleA(c"nvcuda.dll".as_ptr().cast()) as *mut c_void } -} - -fn error_text(code: c_int) -> String { - type Get = unsafe extern "C" fn(c_int, *mut *const c_char) -> c_int; - let module = nvcuda(); - let lookup = |name: &CStr| -> Option { - // SAFETY: valid module handle and symbol name; the symbol has this exact signature in the driver. - unsafe { GetProcAddress(module as _, name.as_ptr().cast()).map(|f| std::mem::transmute::<_, Get>(f)) } - }; - let text = |f: Option| -> String { - let Some(f) = f else { return "?".into() }; - let mut p: *const c_char = std::ptr::null(); - // SAFETY: out pointer is valid; on success the driver returns a static NUL-terminated string. - if unsafe { f(code, &mut p) } == 0 && !p.is_null() { - unsafe { CStr::from_ptr(p) }.to_string_lossy().into_owned() - } else { - "?".into() - } - }; - format!("{} ({})", text(lookup(c"cuGetErrorName")), text(lookup(c"cuGetErrorString"))) -} - -fn describe(state: &State, e: &Entry) -> String { - let c = if e.captured { " [capture]" } else { "" }; - match e.kind { - "kernel" => format!( - "#{} kernel {} grid {}x{}x{} block {}x{}x{} smem {} stream {:#x}{}", - e.seq, - state.names.get(&e.a).map(String::as_str).unwrap_or("?"), - e.grid[0], e.grid[1], e.grid[2], e.block[0], e.block[1], e.block[2], e.smem, e.stream, c - ), - "graph" => format!("#{} graph-launch exec {:#x} stream {:#x}", e.seq, e.a, e.stream), - "batch-async" => format!("#{} batch-async copies {} dsts {:#x} srcs {:#x} stream {:#x}{}", e.seq, e.n, e.a, e.b, e.stream, c), - "set" => format!("#{} memset dst {:#x} value {:#x} bytes {} stream {:#x}{}", e.seq, e.a, e.b & 0xff, e.n, e.stream, c), - k => format!("#{} {} dst {:#x} src {:#x} bytes {} stream {:#x}{}", e.seq, k, e.a, e.b, e.n, e.stream, c), - } -} - -fn push(e: Entry) -> u64 { - let mut s = lock(); - let seq = s.next; - s.next += 1; - let captured = s.capturing.get(&e.stream).copied().unwrap_or(false); - s.ring[(seq as usize) % RING] = Some(Entry { seq, captured, ..e }); - seq -} - -fn blank(kind: &'static str) -> Entry { - Entry { seq: 0, kind, a: 0, b: 0, n: 0, grid: [0; 3], block: [0; 3], smem: 0, stream: 0, captured: false } -} - -/// A non-zero return (`stream` is the stream the failing call synchronizes or was issued on, 0 if unknown). -fn failed(op: &str, code: c_int, stream: Option) { - let text = error_text(code); - let mut s = lock(); - s.failures += 1; - if s.failures > 40 { - return; - } - eprintln!("CUDA-TRACE failure: {op} returned {code} {text}"); - if REPORTED.swap(true, Ordering::Relaxed) { - return; - } - if CALLBACKS.load(Ordering::Relaxed) || DONE.iter().any(|d| d.load(Ordering::Relaxed) != 0) { - for (index, st) in s.streams.clone().into_iter().enumerate() { - let done = DONE[index].load(Ordering::Relaxed); - let next = (done + 1..s.next).find_map(|q| s.ring[(q as usize) % RING].filter(|e| e.seq == q && e.stream == st)); - eprintln!("CUDA-TRACE stream {st:#x}: last completed operation #{done}, the next one queued on it (the fault is at or after it): {}", - next.map_or_else(|| "none".to_string(), |e| describe(&s, &e))); - } - } - let newest = s.next.saturating_sub(1); - let from = match stream { - Some(st) => s.stream_ok.get(&st).copied().unwrap_or(0).max(s.ctx_ok), - None => s.ctx_ok, - }; - let oldest = newest.saturating_sub(RING as u64 - 1).max(1); - let begin = (from + 1).max(oldest); - let pending = newest.saturating_sub(from); - eprintln!( - "CUDA-TRACE launches so far {} (graph launches {}), operations queued since the last successful synchronization of this stream: {}{}", - LAUNCHES.load(Ordering::Relaxed), - GRAPH_LAUNCHES.load(Ordering::Relaxed), - pending, - if begin > from + 1 { " (older ones fell out of the ring)" } else { "" } - ); - let list: Vec = (begin..=newest).filter_map(|q| s.ring[(q as usize) % RING].filter(|e| e.seq == q)).collect(); - let head = 40usize; - let tail = 40usize; - for (i, e) in list.iter().enumerate() { - if i < head || i + tail >= list.len() { - eprintln!("CUDA-TRACE {}", describe(&s, e)); - } else if i == head { - eprintln!("CUDA-TRACE ... {} more ...", list.len() - head - tail); - } - } -} - -fn synced(stream: Option) { - let mut s = lock(); - let newest = s.next.saturating_sub(1); - match stream { - Some(st) => { - s.stream_ok.insert(st, newest); - } - None => s.ctx_ok = newest, - } -} - macro_rules! plain { ($fname:ident, $slot:expr, $op:literal, $stream:expr, $on_ok:expr, ($($a:ident),*)) => { unsafe extern "C" fn $fname($($a: usize),*) -> c_int { @@ -289,8 +89,6 @@ macro_rules! plain { }; } -fn nothing(_: Option) {} - plain!(w_ctx_sync, 0, "cuCtxSynchronize", None, |_s: Option| synced(None), ()); plain!(w_stream_sync, 1, "cuStreamSynchronize", Some(a0), |s| synced(s), (a0)); plain!(w_event_sync, 2, "cuEventSynchronize", None, nothing, (a0)); @@ -332,118 +130,12 @@ copy!(w_set, 15, "cuMemsetD8_v2", "set", 0, true, (a0, a1, a2), a0, a1, a2); // (driver 617.42 on the RTX 3080 laptop faults on it from page-locked memory, docs/windows.md "PCIe tier on the laptop") copy!(w_batch_async, 21, "cuMemcpyBatchAsync_v2", "batch-async", a7, false, (a0, a1, a2, a3, a4, a5, a6, a7), a0, a1, a3); -unsafe extern "C" fn w_graph_launch(a0: usize, a1: usize) -> c_int { - // SAFETY: slot 16 holds cuGraphLaunch. - let real: unsafe extern "C" fn(usize, usize) -> c_int = unsafe { std::mem::transmute(REAL[16].load(Ordering::Relaxed)) }; - GRAPH_LAUNCHES.fetch_add(1, Ordering::Relaxed); - push(Entry { a: a0, stream: a1, ..blank("graph") }); - let code = unsafe { real(a0, a1) }; - if code != 0 { - failed("cuGraphLaunch", code, Some(a1)); - } - code -} - -#[allow(clippy::too_many_arguments)] -unsafe extern "C" fn w_launch(f: usize, gx: usize, gy: usize, gz: usize, bx: usize, by: usize, bz: usize, smem: usize, stream: usize, params: usize, extra: usize) -> c_int { - type Launch = unsafe extern "C" fn(usize, usize, usize, usize, usize, usize, usize, usize, usize, usize, usize) -> c_int; - // SAFETY: slot 17 holds cuLaunchKernel. - let real: Launch = unsafe { std::mem::transmute(REAL[17].load(Ordering::Relaxed)) }; - LAUNCHES.fetch_add(1, Ordering::Relaxed); - let u = |v: usize| v as u32; - let seq = push(Entry { a: f, grid: [u(gx), u(gy), u(gz)], block: [u(bx), u(by), u(bz)], smem: u(smem), stream, ..blank("kernel") }); - let code = unsafe { real(f, gx, gy, gz, bx, by, bz, smem, stream, params, extra) }; - if code == 0 { - queue_callback(stream, seq); - } - if code != 0 { - let name = lock().names.get(&f).cloned().unwrap_or_default(); - failed(&format!("cuLaunchKernel({name})"), code, Some(stream)); - } else if SYNC.load(Ordering::Relaxed) - && let Some(sync) = real_stream_synchronize() - { - // SAFETY: the stream handle is the caller's own (0 is the legacy stream). - let after = unsafe { sync(stream) }; - if after == 0 { - synced(Some(stream)); - } else { - let name = lock().names.get(&f).cloned().unwrap_or_default(); - failed(&format!("cuStreamSynchronize right after cuLaunchKernel({name})"), after, Some(stream)); - } - } - code -} - -unsafe extern "C" fn w_get_function(out: usize, module: usize, name: usize) -> c_int { - // SAFETY: slot 18 holds cuModuleGetFunction. - let real: unsafe extern "C" fn(usize, usize, usize) -> c_int = unsafe { std::mem::transmute(REAL[18].load(Ordering::Relaxed)) }; - let code = unsafe { real(out, module, name) }; - if code == 0 && out != 0 && name != 0 { - // SAFETY: on success the driver wrote the handle; `name` is the caller's NUL-terminated string. - let (function, text) = unsafe { (*(out as *const usize), CStr::from_ptr(name as *const c_char).to_string_lossy().into_owned()) }; - lock().names.insert(function, text); - } else if code != 0 { - failed("cuModuleGetFunction", code, None); - } - code -} - -unsafe extern "C" fn w_begin_capture(a0: usize, a1: usize) -> c_int { - // SAFETY: slot 19 holds cuStreamBeginCapture_v2. - let real: unsafe extern "C" fn(usize, usize) -> c_int = unsafe { std::mem::transmute(REAL[19].load(Ordering::Relaxed)) }; - let code = unsafe { real(a0, a1) }; - if code == 0 { - lock().capturing.insert(a0, true); - } else { - failed("cuStreamBeginCapture_v2", code, Some(a0)); - } - code -} - -unsafe extern "C" fn w_end_capture(a0: usize, a1: usize) -> c_int { - // SAFETY: slot 20 holds cuStreamEndCapture. - let real: unsafe extern "C" fn(usize, usize) -> c_int = unsafe { std::mem::transmute(REAL[20].load(Ordering::Relaxed)) }; - let code = unsafe { real(a0, a1) }; - lock().capturing.insert(a0, false); - if code != 0 { - failed("cuStreamEndCapture", code, Some(a0)); - } - code -} - -/// `dlsym` hook: the wrapper for `symbol` when tracing is on and `handle` is the driver, otherwise `real`. -pub(crate) fn interpose(handle: *mut c_void, symbol: &CStr, real: *mut c_void) -> *mut c_void { - if !enabled() || real.is_null() || handle != nvcuda() { - return real; - } - let (slot, wrapper): (usize, usize) = match symbol.to_bytes() { - b"cuCtxSynchronize" => (0, w_ctx_sync as *const () as usize), - b"cuStreamSynchronize" => (1, w_stream_sync as *const () as usize), - b"cuEventSynchronize" => (2, w_event_sync as *const () as usize), - b"cuEventQuery" => (3, w_event_query as *const () as usize), - b"cuStreamQuery" => (4, w_stream_query as *const () as usize), - b"cuEventRecord" => (5, w_event_record as *const () as usize), - b"cuStreamWaitEvent" => (6, w_stream_wait_event as *const () as usize), - b"cuLaunchHostFunc" => (7, w_host_func as *const () as usize), - b"cuMemcpyHtoDAsync_v2" => (8, w_h2d_async as *const () as usize), - b"cuMemcpyDtoHAsync_v2" => (9, w_d2h_async as *const () as usize), - b"cuMemcpyAsync" => (10, w_copy_async as *const () as usize), - b"cuMemsetD8Async" => (11, w_set_async as *const () as usize), - b"cuMemcpyHtoD_v2" => (12, w_h2d as *const () as usize), - b"cuMemcpyDtoH_v2" => (13, w_d2h as *const () as usize), - b"cuMemcpyDtoD_v2" => (14, w_d2d as *const () as usize), - b"cuMemsetD8_v2" => (15, w_set as *const () as usize), - b"cuMemcpyBatchAsync_v2" => (21, w_batch_async as *const () as usize), - b"cuGraphLaunch" => (16, w_graph_launch as *const () as usize), - b"cuLaunchKernel" => (17, w_launch as *const () as usize), - b"cuModuleGetFunction" => (18, w_get_function as *const () as usize), - b"cuStreamBeginCapture_v2" => (19, w_begin_capture as *const () as usize), - b"cuStreamEndCapture" => (20, w_end_capture as *const () as usize), - _ => return real, - }; - REAL[slot].store(real as usize, Ordering::Relaxed); - wrapper as *mut c_void -} - #[cfg(test)] mod tests; + +mod enabled; +#[allow(unused_imports)] +pub use enabled::*; +mod w_launch; +#[allow(unused_imports)] +pub use w_launch::*; diff --git a/crates/libc-shim/src/cuda_trace/enabled.rs b/crates/libc-shim/src/cuda_trace/enabled.rs new file mode 100644 index 00000000..bcce91bc --- /dev/null +++ b/crates/libc-shim/src/cuda_trace/enabled.rs @@ -0,0 +1,219 @@ +//! Moved out of the parent module by STRA-338: fn enabled, fn state, fn lock, fn done_callback, fn queue_callback, fn set_sync .... + +#[allow(unused_imports)] +use super::*; + + +pub(super) fn enabled() -> bool { + static ON: OnceLock = OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("LELEKA_BRINGUP_TRACE").is_some()) +} + +pub(super) fn state() -> &'static Mutex { + static S: OnceLock> = OnceLock::new(); + S.get_or_init(|| { + Mutex::new(State { + ring: vec![None; RING], + next: 1, + names: HashMap::new(), + stream_ok: HashMap::new(), + ctx_ok: 0, + capturing: HashMap::new(), + failures: 0, + streams: Vec::new(), + }) + }) +} + +pub(super) fn lock() -> std::sync::MutexGuard<'static, State> { + state().lock().unwrap_or_else(|e| e.into_inner()) +} + +pub(super) unsafe extern "C" fn done_callback(argument: *mut c_void) { + let value = argument as usize as u64; + DONE[(value >> 56) as usize % STREAM_SLOTS].fetch_max(value & ((1 << 56) - 1), Ordering::Relaxed); +} + +/// Queue the completion callback of operation `seq` on `stream`. +pub(super) fn queue_callback(stream: usize, seq: u64) { + if !CALLBACKS.load(Ordering::Relaxed) { + return; + } + type HostFunc = unsafe extern "C" fn(usize, usize, usize) -> c_int; + static F: OnceLock = OnceLock::new(); + let address = *F.get_or_init(|| { + // SAFETY: valid module handle and NUL-terminated symbol name. + unsafe { GetProcAddress(nvcuda() as _, c"cuLaunchHostFunc".as_ptr().cast()).map_or(0, |f| f as usize) } + }); + if address == 0 { + return; + } + let index = { + let mut s = lock(); + match s.streams.iter().position(|&x| x == stream) { + Some(i) => i, + None if s.streams.len() < STREAM_SLOTS => { + s.streams.push(stream); + s.streams.len() - 1 + } + None => return, + } + }; + // SAFETY: the address is the driver's cuLaunchHostFunc; the callback only stores to an atomic. + let real: HostFunc = unsafe { std::mem::transmute(address) }; + let _ = unsafe { real(stream, done_callback as *const () as usize, ((index as u64) << 56 | seq) as usize) }; +} + +/// Switch the per-launch synchronization on or off. It is only ever on when `LELEKA_BRINGUP_TRACE` and +/// `LELEKA_CUDA_TRACE_SYNC` are both set, and the runtime turns it on only around the prompt (prefill) forward: the +/// decode windows launch polling kernels that a per-launch synchronization would deadlock, exactly like +/// `CUDA_LAUNCH_BLOCKING`. Returns whether it is now on. +pub fn set_sync(on: bool) -> bool { + static ALLOWED: OnceLock = OnceLock::new(); + static CALLBACK_ALLOWED: OnceLock = OnceLock::new(); + let allowed = *ALLOWED.get_or_init(|| enabled() && std::env::var_os("LELEKA_CUDA_TRACE_SYNC").is_some()); + let callbacks = *CALLBACK_ALLOWED.get_or_init(|| enabled() && std::env::var_os("LELEKA_CUDA_TRACE_CALLBACKS").is_some()); + SYNC.store(on && allowed, Ordering::Relaxed); + CALLBACKS.store(on && callbacks, Ordering::Relaxed); + on && (allowed || callbacks) +} + +pub(super) fn real_stream_synchronize() -> Option c_int> { + static F: OnceLock = OnceLock::new(); + let address = *F.get_or_init(|| { + let slot = REAL[1].load(Ordering::Relaxed); + if slot != 0 { + return slot; + } + // SAFETY: valid module handle and NUL-terminated symbol name. + unsafe { GetProcAddress(nvcuda() as _, c"cuStreamSynchronize".as_ptr().cast()).map_or(0, |f| f as usize) } + }); + // SAFETY: the address is the driver's cuStreamSynchronize. + (address != 0).then(|| unsafe { std::mem::transmute:: c_int>(address) }) +} + +pub(super) fn nvcuda() -> *mut c_void { + // SAFETY: NUL-terminated literal; GetModuleHandleA does not take a reference. + unsafe { GetModuleHandleA(c"nvcuda.dll".as_ptr().cast()) as *mut c_void } +} + +pub(super) fn error_text(code: c_int) -> String { + type Get = unsafe extern "C" fn(c_int, *mut *const c_char) -> c_int; + let module = nvcuda(); + let lookup = |name: &CStr| -> Option { + // SAFETY: valid module handle and symbol name; the symbol has this exact signature in the driver. + unsafe { GetProcAddress(module as _, name.as_ptr().cast()).map(|f| std::mem::transmute::<_, Get>(f)) } + }; + let text = |f: Option| -> String { + let Some(f) = f else { return "?".into() }; + let mut p: *const c_char = std::ptr::null(); + // SAFETY: out pointer is valid; on success the driver returns a static NUL-terminated string. + if unsafe { f(code, &mut p) } == 0 && !p.is_null() { + unsafe { CStr::from_ptr(p) }.to_string_lossy().into_owned() + } else { + "?".into() + } + }; + format!("{} ({})", text(lookup(c"cuGetErrorName")), text(lookup(c"cuGetErrorString"))) +} + +pub(super) fn describe(state: &State, e: &Entry) -> String { + let c = if e.captured { " [capture]" } else { "" }; + match e.kind { + "kernel" => format!( + "#{} kernel {} grid {}x{}x{} block {}x{}x{} smem {} stream {:#x}{}", + e.seq, + state.names.get(&e.a).map(String::as_str).unwrap_or("?"), + e.grid[0], e.grid[1], e.grid[2], e.block[0], e.block[1], e.block[2], e.smem, e.stream, c + ), + "graph" => format!("#{} graph-launch exec {:#x} stream {:#x}", e.seq, e.a, e.stream), + "batch-async" => format!("#{} batch-async copies {} dsts {:#x} srcs {:#x} stream {:#x}{}", e.seq, e.n, e.a, e.b, e.stream, c), + "set" => format!("#{} memset dst {:#x} value {:#x} bytes {} stream {:#x}{}", e.seq, e.a, e.b & 0xff, e.n, e.stream, c), + k => format!("#{} {} dst {:#x} src {:#x} bytes {} stream {:#x}{}", e.seq, k, e.a, e.b, e.n, e.stream, c), + } +} + +pub(super) fn push(e: Entry) -> u64 { + let mut s = lock(); + let seq = s.next; + s.next += 1; + let captured = s.capturing.get(&e.stream).copied().unwrap_or(false); + s.ring[(seq as usize) % RING] = Some(Entry { seq, captured, ..e }); + seq +} + +pub(super) fn blank(kind: &'static str) -> Entry { + Entry { seq: 0, kind, a: 0, b: 0, n: 0, grid: [0; 3], block: [0; 3], smem: 0, stream: 0, captured: false } +} + +/// A non-zero return (`stream` is the stream the failing call synchronizes or was issued on, 0 if unknown). +pub(super) fn failed(op: &str, code: c_int, stream: Option) { + let text = error_text(code); + let mut s = lock(); + s.failures += 1; + if s.failures > 40 { + return; + } + eprintln!("CUDA-TRACE failure: {op} returned {code} {text}"); + if REPORTED.swap(true, Ordering::Relaxed) { + return; + } + if CALLBACKS.load(Ordering::Relaxed) || DONE.iter().any(|d| d.load(Ordering::Relaxed) != 0) { + for (index, st) in s.streams.clone().into_iter().enumerate() { + let done = DONE[index].load(Ordering::Relaxed); + let next = (done + 1..s.next).find_map(|q| s.ring[(q as usize) % RING].filter(|e| e.seq == q && e.stream == st)); + eprintln!("CUDA-TRACE stream {st:#x}: last completed operation #{done}, the next one queued on it (the fault is at or after it): {}", + next.map_or_else(|| "none".to_string(), |e| describe(&s, &e))); + } + } + let newest = s.next.saturating_sub(1); + let from = match stream { + Some(st) => s.stream_ok.get(&st).copied().unwrap_or(0).max(s.ctx_ok), + None => s.ctx_ok, + }; + let oldest = newest.saturating_sub(RING as u64 - 1).max(1); + let begin = (from + 1).max(oldest); + let pending = newest.saturating_sub(from); + eprintln!( + "CUDA-TRACE launches so far {} (graph launches {}), operations queued since the last successful synchronization of this stream: {}{}", + LAUNCHES.load(Ordering::Relaxed), + GRAPH_LAUNCHES.load(Ordering::Relaxed), + pending, + if begin > from + 1 { " (older ones fell out of the ring)" } else { "" } + ); + let list: Vec = (begin..=newest).filter_map(|q| s.ring[(q as usize) % RING].filter(|e| e.seq == q)).collect(); + let head = 40usize; + let tail = 40usize; + for (i, e) in list.iter().enumerate() { + if i < head || i + tail >= list.len() { + eprintln!("CUDA-TRACE {}", describe(&s, e)); + } else if i == head { + eprintln!("CUDA-TRACE ... {} more ...", list.len() - head - tail); + } + } +} + +pub(super) fn synced(stream: Option) { + let mut s = lock(); + let newest = s.next.saturating_sub(1); + match stream { + Some(st) => { + s.stream_ok.insert(st, newest); + } + None => s.ctx_ok = newest, + } +} + +pub(super) fn nothing(_: Option) {} + +pub(super) unsafe extern "C" fn w_graph_launch(a0: usize, a1: usize) -> c_int { + // SAFETY: slot 16 holds cuGraphLaunch. + let real: unsafe extern "C" fn(usize, usize) -> c_int = unsafe { std::mem::transmute(REAL[16].load(Ordering::Relaxed)) }; + GRAPH_LAUNCHES.fetch_add(1, Ordering::Relaxed); + push(Entry { a: a0, stream: a1, ..blank("graph") }); + let code = unsafe { real(a0, a1) }; + if code != 0 { + failed("cuGraphLaunch", code, Some(a1)); + } + code +} diff --git a/crates/libc-shim/src/cuda_trace/w_launch.rs b/crates/libc-shim/src/cuda_trace/w_launch.rs new file mode 100644 index 00000000..b4833ab6 --- /dev/null +++ b/crates/libc-shim/src/cuda_trace/w_launch.rs @@ -0,0 +1,106 @@ +//! Moved out of the parent module by STRA-338: fn w_launch, fn w_get_function, fn w_begin_capture, fn w_end_capture, fn interpose. + +#[allow(unused_imports)] +use super::*; + + +#[allow(clippy::too_many_arguments)] +pub(super) unsafe extern "C" fn w_launch(f: usize, gx: usize, gy: usize, gz: usize, bx: usize, by: usize, bz: usize, smem: usize, stream: usize, params: usize, extra: usize) -> c_int { + type Launch = unsafe extern "C" fn(usize, usize, usize, usize, usize, usize, usize, usize, usize, usize, usize) -> c_int; + // SAFETY: slot 17 holds cuLaunchKernel. + let real: Launch = unsafe { std::mem::transmute(REAL[17].load(Ordering::Relaxed)) }; + LAUNCHES.fetch_add(1, Ordering::Relaxed); + let u = |v: usize| v as u32; + let seq = push(Entry { a: f, grid: [u(gx), u(gy), u(gz)], block: [u(bx), u(by), u(bz)], smem: u(smem), stream, ..blank("kernel") }); + let code = unsafe { real(f, gx, gy, gz, bx, by, bz, smem, stream, params, extra) }; + if code == 0 { + queue_callback(stream, seq); + } + if code != 0 { + let name = lock().names.get(&f).cloned().unwrap_or_default(); + failed(&format!("cuLaunchKernel({name})"), code, Some(stream)); + } else if SYNC.load(Ordering::Relaxed) + && let Some(sync) = real_stream_synchronize() + { + // SAFETY: the stream handle is the caller's own (0 is the legacy stream). + let after = unsafe { sync(stream) }; + if after == 0 { + synced(Some(stream)); + } else { + let name = lock().names.get(&f).cloned().unwrap_or_default(); + failed(&format!("cuStreamSynchronize right after cuLaunchKernel({name})"), after, Some(stream)); + } + } + code +} + +pub(super) unsafe extern "C" fn w_get_function(out: usize, module: usize, name: usize) -> c_int { + // SAFETY: slot 18 holds cuModuleGetFunction. + let real: unsafe extern "C" fn(usize, usize, usize) -> c_int = unsafe { std::mem::transmute(REAL[18].load(Ordering::Relaxed)) }; + let code = unsafe { real(out, module, name) }; + if code == 0 && out != 0 && name != 0 { + // SAFETY: on success the driver wrote the handle; `name` is the caller's NUL-terminated string. + let (function, text) = unsafe { (*(out as *const usize), CStr::from_ptr(name as *const c_char).to_string_lossy().into_owned()) }; + lock().names.insert(function, text); + } else if code != 0 { + failed("cuModuleGetFunction", code, None); + } + code +} + +pub(super) unsafe extern "C" fn w_begin_capture(a0: usize, a1: usize) -> c_int { + // SAFETY: slot 19 holds cuStreamBeginCapture_v2. + let real: unsafe extern "C" fn(usize, usize) -> c_int = unsafe { std::mem::transmute(REAL[19].load(Ordering::Relaxed)) }; + let code = unsafe { real(a0, a1) }; + if code == 0 { + lock().capturing.insert(a0, true); + } else { + failed("cuStreamBeginCapture_v2", code, Some(a0)); + } + code +} + +pub(super) unsafe extern "C" fn w_end_capture(a0: usize, a1: usize) -> c_int { + // SAFETY: slot 20 holds cuStreamEndCapture. + let real: unsafe extern "C" fn(usize, usize) -> c_int = unsafe { std::mem::transmute(REAL[20].load(Ordering::Relaxed)) }; + let code = unsafe { real(a0, a1) }; + lock().capturing.insert(a0, false); + if code != 0 { + failed("cuStreamEndCapture", code, Some(a0)); + } + code +} + +/// `dlsym` hook: the wrapper for `symbol` when tracing is on and `handle` is the driver, otherwise `real`. +pub(crate) fn interpose(handle: *mut c_void, symbol: &CStr, real: *mut c_void) -> *mut c_void { + if !enabled() || real.is_null() || handle != nvcuda() { + return real; + } + let (slot, wrapper): (usize, usize) = match symbol.to_bytes() { + b"cuCtxSynchronize" => (0, w_ctx_sync as *const () as usize), + b"cuStreamSynchronize" => (1, w_stream_sync as *const () as usize), + b"cuEventSynchronize" => (2, w_event_sync as *const () as usize), + b"cuEventQuery" => (3, w_event_query as *const () as usize), + b"cuStreamQuery" => (4, w_stream_query as *const () as usize), + b"cuEventRecord" => (5, w_event_record as *const () as usize), + b"cuStreamWaitEvent" => (6, w_stream_wait_event as *const () as usize), + b"cuLaunchHostFunc" => (7, w_host_func as *const () as usize), + b"cuMemcpyHtoDAsync_v2" => (8, w_h2d_async as *const () as usize), + b"cuMemcpyDtoHAsync_v2" => (9, w_d2h_async as *const () as usize), + b"cuMemcpyAsync" => (10, w_copy_async as *const () as usize), + b"cuMemsetD8Async" => (11, w_set_async as *const () as usize), + b"cuMemcpyHtoD_v2" => (12, w_h2d as *const () as usize), + b"cuMemcpyDtoH_v2" => (13, w_d2h as *const () as usize), + b"cuMemcpyDtoD_v2" => (14, w_d2d as *const () as usize), + b"cuMemsetD8_v2" => (15, w_set as *const () as usize), + b"cuMemcpyBatchAsync_v2" => (21, w_batch_async as *const () as usize), + b"cuGraphLaunch" => (16, w_graph_launch as *const () as usize), + b"cuLaunchKernel" => (17, w_launch as *const () as usize), + b"cuModuleGetFunction" => (18, w_get_function as *const () as usize), + b"cuStreamBeginCapture_v2" => (19, w_begin_capture as *const () as usize), + b"cuStreamEndCapture" => (20, w_end_capture as *const () as usize), + _ => return real, + }; + REAL[slot].store(real as usize, Ordering::Relaxed); + wrapper as *mut c_void +} diff --git a/crates/model-format/src/bulk_read.rs b/crates/model-format/src/bulk_read.rs index 2874c966..247a80ac 100644 --- a/crates/model-format/src/bulk_read.rs +++ b/crates/model-format/src/bulk_read.rs @@ -43,16 +43,6 @@ pub enum Strategy { Plain, } -impl Strategy { - pub fn as_str(self) -> &'static str { - match self { - Strategy::Direct => "direct", - Strategy::Advise => "advise", - Strategy::Plain => "plain", - } - } -} - #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub struct Plan { pub strategy: Strategy, @@ -64,46 +54,6 @@ pub struct Plan { pub ahead: u64, } -impl Plan { - /// The defaults, then the environment (`LELEKA_LOAD_READ=direct|advise|plain`, `LELEKA_LOAD_THREADS=N`, - /// `LELEKA_LOAD_CHUNK_MIB=N`, `LELEKA_LOAD_AHEAD_MIB=N`): the switches that let one binary be measured in each form. - pub fn from_env() -> Plan { - Plan::with_overrides(Plan::default(), |name| std::env::var(name).ok()) - } - - pub fn with_overrides(mut plan: Plan, var: impl Fn(&str) -> Option) -> Plan { - if let Some(text) = var("LELEKA_LOAD_READ") { - plan.strategy = match text.trim() { - "direct" => Strategy::Direct, - "advise" => Strategy::Advise, - "plain" => Strategy::Plain, - _ => plan.strategy, - }; - } - if let Some(n) = var("LELEKA_LOAD_THREADS").and_then(|t| t.trim().parse::().ok()) { - plan.threads = n.clamp(1, 128); - } - if let Some(n) = var("LELEKA_LOAD_CHUNK_MIB").and_then(|t| t.trim().parse::().ok()) { - plan.chunk = (n.clamp(1, 256)) << 20; - } - if let Some(n) = var("LELEKA_LOAD_AHEAD_MIB").and_then(|t| t.trim().parse::().ok()) { - plan.ahead = n.clamp(1, 8192) << 20; - } - plan - } -} - -impl Default for Plan { - fn default() -> Self { - Plan { - strategy: Strategy::Direct, - threads: 32, - chunk: 8 << 20, - ahead: 1 << 30, - } - } -} - #[derive(Clone, Copy, Debug)] pub struct Report { /// The strategy that actually ran (`Direct` becomes `Advise` where `O_DIRECT` is refused). @@ -112,12 +62,6 @@ pub struct Report { pub elapsed: Duration, } -impl Report { - pub fn mb_per_s(&self) -> f64 { - self.bytes as f64 / self.elapsed.as_secs_f64().max(1e-9) / 1e6 - } -} - /// A byte buffer whose start is 4 KiB-aligned, without `unsafe`. struct Aligned { raw: Vec, @@ -125,76 +69,6 @@ struct Aligned { len: usize, } -impl Aligned { - fn new(len: usize) -> io::Result { - let mut raw = Vec::new(); - raw.try_reserve_exact(len + ALIGN) - .map_err(|_| io::Error::new(io::ErrorKind::OutOfMemory, "read buffer"))?; - raw.resize(len + ALIGN, 0); - let start = (ALIGN - raw.as_ptr() as usize % ALIGN) % ALIGN; - Ok(Aligned { raw, start, len }) - } - fn bytes(&mut self) -> &mut [u8] { - &mut self.raw[self.start..self.start + self.len] - } -} - -/// Reopen the open file (the same inode, no pathname lookup) with `O_DIRECT`. -#[cfg(target_os = "linux")] -fn open_direct(file: &File) -> io::Result { - use std::os::{fd::AsRawFd, unix::fs::OpenOptionsExt}; - std::fs::OpenOptions::new() - .read(true) - .custom_flags(libc::O_DIRECT) - .open(format!("/proc/self/fd/{}", file.as_raw_fd())) -} - -#[cfg(not(target_os = "linux"))] -fn open_direct(_file: &File) -> io::Result { - Err(io::Error::new(io::ErrorKind::Unsupported, "O_DIRECT")) -} - -#[cfg(unix)] -fn read_at(file: &File, buffer: &mut [u8], offset: u64) -> io::Result { - use std::os::unix::fs::FileExt; - file.read_at(buffer, offset) -} - -#[cfg(windows)] -fn read_at(file: &File, buffer: &mut [u8], offset: u64) -> io::Result { - use std::os::windows::fs::FileExt; - file.seek_read(buffer, offset) -} - -/// Fill `buffer` from `offset`; `Ok(n)` with `n < buffer.len()` only at the end of the file. -fn read_full(file: &File, buffer: &mut [u8], offset: u64) -> io::Result { - let mut done = 0; - while done < buffer.len() { - match read_at(file, &mut buffer[done..], offset + done as u64) { - Ok(0) => break, - Ok(n) => done += n, - Err(error) if error.kind() == io::ErrorKind::Interrupted => {} - Err(error) => return Err(error), - } - } - Ok(done) -} - -#[cfg(target_os = "linux")] -fn advise(file: &File, offset: u64, len: u64, advice: rustix::fs::Advice) { - if let Some(len) = std::num::NonZeroU64::new(len) { - let _ = rustix::fs::fadvise(file, offset, Some(len), advice); - } -} - -/// Drop the clean page-cache pages of `file[offset .. offset + len]` (best effort; never `drop_caches`). -pub fn evict(file: &File, offset: u64, len: u64) { - #[cfg(target_os = "linux")] - advise(file, offset, len, rustix::fs::Advice::DontNeed); - #[cfg(not(target_os = "linux"))] - let _ = (file, offset, len); -} - struct Shared<'a, F> { file: &'a File, direct: Option, @@ -210,208 +84,12 @@ struct Shared<'a, F> { sink: &'a F, } -impl io::Result<()> + Sync> Shared<'_, F> { - fn failed(&self) -> bool { - self.failure.lock().is_ok_and(|f| f.is_some()) - } - - fn fail(&self, error: io::Error) { - if let Ok(mut slot) = self.failure.lock() { - slot.get_or_insert(error); - } - } - - fn worker(&self, buffer: &mut Aligned) { - let chunks = self.len.div_ceil(self.chunk); - loop { - if self.failed() { - return; - } - let index = self.next.fetch_add(1, Ordering::Relaxed); - if index >= chunks { - return; - } - let offset = self.start + index * self.chunk; - let count = (self.len - index * self.chunk).min(self.chunk) as usize; - if let Err(error) = self.read_block(buffer, offset, count) { - self.fail(error); - return; - } - } - } - - fn read_block(&self, buffer: &mut Aligned, offset: u64, count: usize) -> io::Result<()> { - match (&self.direct, self.strategy) { - (Some(direct), Strategy::Direct) => { - let aligned = offset - offset % ALIGN as u64; - let lead = (offset - aligned) as usize; - let want = (lead + count).next_multiple_of(ALIGN); - let got = read_full(direct, &mut buffer.bytes()[..want], aligned)?; - if got < lead + count { - return Err(io::Error::new( - io::ErrorKind::UnexpectedEof, - "the file ended before the span did", - )); - } - (self.sink)(offset, &buffer.bytes()[lead..lead + count]) - } - _ => { - if self.strategy == Strategy::Advise { - self.keep_ahead(offset + count as u64); - } - let got = read_full(self.file, &mut buffer.bytes()[..count], offset)?; - if got < count { - return Err(io::Error::new( - io::ErrorKind::UnexpectedEof, - "the file ended before the span did", - )); - } - (self.sink)(offset, &buffer.bytes()[..count])?; - evict(self.file, offset, count as u64); - Ok(()) - } - } - } - - /// Make sure `WILLNEED` covers `ahead` bytes beyond `until` (each byte is advised once). - fn keep_ahead(&self, until: u64) { - let target = (until + self.ahead) - .min(self.file_len) - .min(self.start + self.len); - let mut done = self.advised_to.load(Ordering::Relaxed).max(self.start); - while done < target { - match self.advised_to.compare_exchange( - done, - target, - Ordering::Relaxed, - Ordering::Relaxed, - ) { - Ok(_) => { - #[cfg(target_os = "linux")] - advise(self.file, done, target - done, rustix::fs::Advice::WillNeed); - return; - } - Err(now) => done = now.max(self.start), - } - } - } -} - -/// Read `file[start .. start + len]` in blocks on several threads and hand each block to `sink(absolute_offset, bytes)`. -/// Blocks arrive in no particular order, from different threads; each covers a distinct range of at most `plan.chunk` -/// bytes. The first error stops the others and is returned. -pub fn for_each_chunk( - file: &File, - start: u64, - len: u64, - plan: Plan, - sink: F, -) -> io::Result -where - F: Fn(u64, &[u8]) -> io::Result<()> + Sync, -{ - let began = Instant::now(); - let file_len = file.metadata()?.len(); - if start.checked_add(len).is_none_or(|end| end > file_len) { - return Err(io::Error::new( - io::ErrorKind::UnexpectedEof, - "the span is beyond the end of the file", - )); - } - let chunk = (plan.chunk.max(ALIGN) / ALIGN * ALIGN) as u64; - let mut strategy = plan.strategy; - let mut direct = None; - if strategy == Strategy::Direct { - match open_direct(file) { - Ok(handle) => direct = Some(handle), - Err(_) => strategy = Strategy::Advise, - } - } - if len == 0 { - return Ok(Report { - strategy, - bytes: 0, - elapsed: began.elapsed(), - }); - } - // The block that reaches the file's last bytes may be shorter than its aligned length: `read_full` stops at the end. - let threads = plan.threads.clamp(1, len.div_ceil(chunk) as usize); - let buffer_len = chunk as usize + 2 * ALIGN; - let mut buffers = Vec::with_capacity(threads); - for _ in 0..threads { - buffers.push(Aligned::new(buffer_len)?); - } - let mut shared = Shared { - file, - direct, - strategy, - start, - len, - file_len, - chunk, - ahead: plan.ahead, - next: AtomicU64::new(0), - advised_to: AtomicU64::new(start), - failure: Mutex::new(None), - sink: &sink, - }; - if strategy == Strategy::Advise { - // The first window before any reader asks. - shared.keep_ahead(start); - } - // A direct handle that the file system accepted at open but refuses at read (EINVAL): retry the first block - // once with the buffered strategy instead of failing the whole load. - if let (Some(direct), Strategy::Direct) = (&shared.direct, shared.strategy) { - let mut probe = Aligned::new(ALIGN)?; - let aligned = start - start % ALIGN as u64; - if read_full(direct, probe.bytes(), aligned).is_err() { - shared.direct = None; - shared.strategy = Strategy::Advise; - shared.keep_ahead(start); - } - } - let used = shared.strategy; - thread::scope(|scope| { - let shared = &shared; - for buffer in buffers.iter_mut() { - scope.spawn(move || shared.worker(buffer)); - } - }); - if let Some(error) = shared.failure.into_inner().ok().flatten() { - return Err(error); - } - if used != Strategy::Direct { - evict(file, start, len); - } - Ok(Report { - strategy: used, - bytes: len, - elapsed: began.elapsed(), - }) -} - -/// Fill `dest` with `file[start .. start + dest.len()]`. -pub fn read_into(file: &File, start: u64, dest: &mut [u8], plan: Plan) -> io::Result { - let chunk = plan.chunk.max(ALIGN) / ALIGN * ALIGN; - let len = dest.len() as u64; - let pieces: Vec> = dest.chunks_mut(chunk).map(Mutex::new).collect(); - let plan = Plan { chunk, ..plan }; - for_each_chunk(file, start, len, plan, |offset, bytes| { - let index = ((offset - start) / chunk as u64) as usize; - let mut piece = pieces - .get(index) - .ok_or_else(|| io::Error::other("block outside the destination"))? - .lock() - .map_err(|_| io::Error::other("destination lock poisoned"))?; - if piece.len() != bytes.len() { - return Err(io::Error::other( - "block length differs from the destination piece", - )); - } - piece.copy_from_slice(bytes); - Ok(()) - }) -} - #[cfg(test)] mod tests; + +mod impl_strategy; +#[allow(unused_imports)] +pub use impl_strategy::*; +mod for_each_chunk; +#[allow(unused_imports)] +pub use for_each_chunk::*; diff --git a/crates/model-format/src/bulk_read/for_each_chunk.rs b/crates/model-format/src/bulk_read/for_each_chunk.rs new file mode 100644 index 00000000..ee0d8c9f --- /dev/null +++ b/crates/model-format/src/bulk_read/for_each_chunk.rs @@ -0,0 +1,121 @@ +//! Moved out of the parent module by STRA-338: fn for_each_chunk, fn read_into. + +#[allow(unused_imports)] +use super::*; + + +/// Read `file[start .. start + len]` in blocks on several threads and hand each block to `sink(absolute_offset, bytes)`. +/// Blocks arrive in no particular order, from different threads; each covers a distinct range of at most `plan.chunk` +/// bytes. The first error stops the others and is returned. +pub fn for_each_chunk( + file: &File, + start: u64, + len: u64, + plan: Plan, + sink: F, +) -> io::Result +where + F: Fn(u64, &[u8]) -> io::Result<()> + Sync, +{ + let began = Instant::now(); + let file_len = file.metadata()?.len(); + if start.checked_add(len).is_none_or(|end| end > file_len) { + return Err(io::Error::new( + io::ErrorKind::UnexpectedEof, + "the span is beyond the end of the file", + )); + } + let chunk = (plan.chunk.max(ALIGN) / ALIGN * ALIGN) as u64; + let mut strategy = plan.strategy; + let mut direct = None; + if strategy == Strategy::Direct { + match open_direct(file) { + Ok(handle) => direct = Some(handle), + Err(_) => strategy = Strategy::Advise, + } + } + if len == 0 { + return Ok(Report { + strategy, + bytes: 0, + elapsed: began.elapsed(), + }); + } + // The block that reaches the file's last bytes may be shorter than its aligned length: `read_full` stops at the end. + let threads = plan.threads.clamp(1, len.div_ceil(chunk) as usize); + let buffer_len = chunk as usize + 2 * ALIGN; + let mut buffers = Vec::with_capacity(threads); + for _ in 0..threads { + buffers.push(Aligned::new(buffer_len)?); + } + let mut shared = Shared { + file, + direct, + strategy, + start, + len, + file_len, + chunk, + ahead: plan.ahead, + next: AtomicU64::new(0), + advised_to: AtomicU64::new(start), + failure: Mutex::new(None), + sink: &sink, + }; + if strategy == Strategy::Advise { + // The first window before any reader asks. + shared.keep_ahead(start); + } + // A direct handle that the file system accepted at open but refuses at read (EINVAL): retry the first block + // once with the buffered strategy instead of failing the whole load. + if let (Some(direct), Strategy::Direct) = (&shared.direct, shared.strategy) { + let mut probe = Aligned::new(ALIGN)?; + let aligned = start - start % ALIGN as u64; + if read_full(direct, probe.bytes(), aligned).is_err() { + shared.direct = None; + shared.strategy = Strategy::Advise; + shared.keep_ahead(start); + } + } + let used = shared.strategy; + thread::scope(|scope| { + let shared = &shared; + for buffer in buffers.iter_mut() { + scope.spawn(move || shared.worker(buffer)); + } + }); + if let Some(error) = shared.failure.into_inner().ok().flatten() { + return Err(error); + } + if used != Strategy::Direct { + evict(file, start, len); + } + Ok(Report { + strategy: used, + bytes: len, + elapsed: began.elapsed(), + }) +} + +/// Fill `dest` with `file[start .. start + dest.len()]`. +pub fn read_into(file: &File, start: u64, dest: &mut [u8], plan: Plan) -> io::Result { + let chunk = plan.chunk.max(ALIGN) / ALIGN * ALIGN; + let len = dest.len() as u64; + let pieces: Vec> = dest.chunks_mut(chunk).map(Mutex::new).collect(); + let plan = Plan { chunk, ..plan }; + for_each_chunk(file, start, len, plan, |offset, bytes| { + let index = ((offset - start) / chunk as u64) as usize; + let mut piece = pieces + .get(index) + .ok_or_else(|| io::Error::other("block outside the destination"))? + .lock() + .map_err(|_| io::Error::other("destination lock poisoned"))?; + if piece.len() != bytes.len() { + return Err(io::Error::other( + "block length differs from the destination piece", + )); + } + piece.copy_from_slice(bytes); + Ok(()) + }) +} diff --git a/crates/model-format/src/bulk_read/impl_strategy.rs b/crates/model-format/src/bulk_read/impl_strategy.rs new file mode 100644 index 00000000..8e443f66 --- /dev/null +++ b/crates/model-format/src/bulk_read/impl_strategy.rs @@ -0,0 +1,218 @@ +//! Moved out of the parent module by STRA-338: impl Strategy, impl Plan, impl Default_for_Plan, impl Report, impl Aligned, fn open_direct .... + +#[allow(unused_imports)] +use super::*; + + +impl Strategy { + pub fn as_str(self) -> &'static str { + match self { + Strategy::Direct => "direct", + Strategy::Advise => "advise", + Strategy::Plain => "plain", + } + } +} + +impl Plan { + /// The defaults, then the environment (`LELEKA_LOAD_READ=direct|advise|plain`, `LELEKA_LOAD_THREADS=N`, + /// `LELEKA_LOAD_CHUNK_MIB=N`, `LELEKA_LOAD_AHEAD_MIB=N`): the switches that let one binary be measured in each form. + pub fn from_env() -> Plan { + Plan::with_overrides(Plan::default(), |name| std::env::var(name).ok()) + } + + pub fn with_overrides(mut plan: Plan, var: impl Fn(&str) -> Option) -> Plan { + if let Some(text) = var("LELEKA_LOAD_READ") { + plan.strategy = match text.trim() { + "direct" => Strategy::Direct, + "advise" => Strategy::Advise, + "plain" => Strategy::Plain, + _ => plan.strategy, + }; + } + if let Some(n) = var("LELEKA_LOAD_THREADS").and_then(|t| t.trim().parse::().ok()) { + plan.threads = n.clamp(1, 128); + } + if let Some(n) = var("LELEKA_LOAD_CHUNK_MIB").and_then(|t| t.trim().parse::().ok()) { + plan.chunk = (n.clamp(1, 256)) << 20; + } + if let Some(n) = var("LELEKA_LOAD_AHEAD_MIB").and_then(|t| t.trim().parse::().ok()) { + plan.ahead = n.clamp(1, 8192) << 20; + } + plan + } +} + +impl Default for Plan { + fn default() -> Self { + Plan { + strategy: Strategy::Direct, + threads: 32, + chunk: 8 << 20, + ahead: 1 << 30, + } + } +} + +impl Report { + pub fn mb_per_s(&self) -> f64 { + self.bytes as f64 / self.elapsed.as_secs_f64().max(1e-9) / 1e6 + } +} + +impl Aligned { + pub(super) fn new(len: usize) -> io::Result { + let mut raw = Vec::new(); + raw.try_reserve_exact(len + ALIGN) + .map_err(|_| io::Error::new(io::ErrorKind::OutOfMemory, "read buffer"))?; + raw.resize(len + ALIGN, 0); + let start = (ALIGN - raw.as_ptr() as usize % ALIGN) % ALIGN; + Ok(Aligned { raw, start, len }) + } + pub(super) fn bytes(&mut self) -> &mut [u8] { + &mut self.raw[self.start..self.start + self.len] + } +} + +/// Reopen the open file (the same inode, no pathname lookup) with `O_DIRECT`. +#[cfg(target_os = "linux")] +pub(super) fn open_direct(file: &File) -> io::Result { + use std::os::{fd::AsRawFd, unix::fs::OpenOptionsExt}; + std::fs::OpenOptions::new() + .read(true) + .custom_flags(libc::O_DIRECT) + .open(format!("/proc/self/fd/{}", file.as_raw_fd())) +} + +#[cfg(not(target_os = "linux"))] +pub(super) fn open_direct(_file: &File) -> io::Result { + Err(io::Error::new(io::ErrorKind::Unsupported, "O_DIRECT")) +} + +#[cfg(unix)] +pub(super) fn read_at(file: &File, buffer: &mut [u8], offset: u64) -> io::Result { + use std::os::unix::fs::FileExt; + file.read_at(buffer, offset) +} + +#[cfg(windows)] +pub(super) fn read_at(file: &File, buffer: &mut [u8], offset: u64) -> io::Result { + use std::os::windows::fs::FileExt; + file.seek_read(buffer, offset) +} + +/// Fill `buffer` from `offset`; `Ok(n)` with `n < buffer.len()` only at the end of the file. +pub(super) fn read_full(file: &File, buffer: &mut [u8], offset: u64) -> io::Result { + let mut done = 0; + while done < buffer.len() { + match read_at(file, &mut buffer[done..], offset + done as u64) { + Ok(0) => break, + Ok(n) => done += n, + Err(error) if error.kind() == io::ErrorKind::Interrupted => {} + Err(error) => return Err(error), + } + } + Ok(done) +} + +#[cfg(target_os = "linux")] +pub(super) fn advise(file: &File, offset: u64, len: u64, advice: rustix::fs::Advice) { + if let Some(len) = std::num::NonZeroU64::new(len) { + let _ = rustix::fs::fadvise(file, offset, Some(len), advice); + } +} + +/// Drop the clean page-cache pages of `file[offset .. offset + len]` (best effort; never `drop_caches`). +pub fn evict(file: &File, offset: u64, len: u64) { + #[cfg(target_os = "linux")] + advise(file, offset, len, rustix::fs::Advice::DontNeed); + #[cfg(not(target_os = "linux"))] + let _ = (file, offset, len); +} + +impl io::Result<()> + Sync> Shared<'_, F> { + pub(super) fn failed(&self) -> bool { + self.failure.lock().is_ok_and(|f| f.is_some()) + } + + pub(super) fn fail(&self, error: io::Error) { + if let Ok(mut slot) = self.failure.lock() { + slot.get_or_insert(error); + } + } + + pub(super) fn worker(&self, buffer: &mut Aligned) { + let chunks = self.len.div_ceil(self.chunk); + loop { + if self.failed() { + return; + } + let index = self.next.fetch_add(1, Ordering::Relaxed); + if index >= chunks { + return; + } + let offset = self.start + index * self.chunk; + let count = (self.len - index * self.chunk).min(self.chunk) as usize; + if let Err(error) = self.read_block(buffer, offset, count) { + self.fail(error); + return; + } + } + } + + pub(super) fn read_block(&self, buffer: &mut Aligned, offset: u64, count: usize) -> io::Result<()> { + match (&self.direct, self.strategy) { + (Some(direct), Strategy::Direct) => { + let aligned = offset - offset % ALIGN as u64; + let lead = (offset - aligned) as usize; + let want = (lead + count).next_multiple_of(ALIGN); + let got = read_full(direct, &mut buffer.bytes()[..want], aligned)?; + if got < lead + count { + return Err(io::Error::new( + io::ErrorKind::UnexpectedEof, + "the file ended before the span did", + )); + } + (self.sink)(offset, &buffer.bytes()[lead..lead + count]) + } + _ => { + if self.strategy == Strategy::Advise { + self.keep_ahead(offset + count as u64); + } + let got = read_full(self.file, &mut buffer.bytes()[..count], offset)?; + if got < count { + return Err(io::Error::new( + io::ErrorKind::UnexpectedEof, + "the file ended before the span did", + )); + } + (self.sink)(offset, &buffer.bytes()[..count])?; + evict(self.file, offset, count as u64); + Ok(()) + } + } + } + + /// Make sure `WILLNEED` covers `ahead` bytes beyond `until` (each byte is advised once). + pub(super) fn keep_ahead(&self, until: u64) { + let target = (until + self.ahead) + .min(self.file_len) + .min(self.start + self.len); + let mut done = self.advised_to.load(Ordering::Relaxed).max(self.start); + while done < target { + match self.advised_to.compare_exchange( + done, + target, + Ordering::Relaxed, + Ordering::Relaxed, + ) { + Ok(_) => { + #[cfg(target_os = "linux")] + advise(self.file, done, target - done, rustix::fs::Advice::WillNeed); + return; + } + Err(now) => done = now.max(self.start), + } + } + } +} diff --git a/crates/model-format/src/gguf.rs b/crates/model-format/src/gguf.rs index 624305eb..9a5a2c3e 100644 --- a/crates/model-format/src/gguf.rs +++ b/crates/model-format/src/gguf.rs @@ -98,34 +98,6 @@ thread_local! { static STREAM_BUFFER_TEST_OVERRIDE: std::cell::Cell> = const { std::cell::Cell::new(None) }; } - -// Production always uses `STREAM_BUFFER_BYTES`. Tests may shrink the span -// stream buffer on their own thread to exercise multi-chunk behaviour with -// small fixtures (see `with_test_stream_buffer`). -#[cfg(test)] -fn stream_buffer_bytes() -> usize { - STREAM_BUFFER_TEST_OVERRIDE.with(|cell| cell.get().unwrap_or(STREAM_BUFFER_BYTES)) -} - -#[cfg(not(test))] -const fn stream_buffer_bytes() -> usize { - STREAM_BUFFER_BYTES -} - -/// Test seam: run `body` with `stream_tensor` buffering spans in `bytes`-sized -/// chunks (1..=16 MiB) on this thread only; restored even on panic. -#[cfg(test)] -pub(crate) fn with_test_stream_buffer(bytes: usize, body: impl FnOnce() -> T) -> T { - assert!(bytes > 0 && bytes <= STREAM_BUFFER_BYTES); - struct Restore(Option); - impl Drop for Restore { - fn drop(&mut self) { - STREAM_BUFFER_TEST_OVERRIDE.with(|cell| cell.set(self.0)); - } - } - let _restore = Restore(STREAM_BUFFER_TEST_OVERRIDE.with(|cell| cell.replace(Some(bytes)))); - body() -} const FLASH_NEXT_PROFILE_KEYS: &[&str] = &[ "qwen4exp.block_count", "qwen4exp.embedding_length", @@ -174,1122 +146,12 @@ const QWEN4EXP_BINDING_KEYS: &[&str] = &[ "qwen4exp.ple.layer_multipliers", ]; -impl VerifiedGgufFile { - /// Verify `sha256:<64 hex digits>` and strictly index the same opened file. - /// The opened file's contents must remain stable until this handle is dropped. - pub fn open(path: &Path, expected_digest: &str) -> Result { - let expected = parse_artifact_digest(expected_digest)?; - // Refuse an ordinary nonregular path before opening it (notably FIFOs). - // The opened-file check below is authoritative for the accepted source. - if !std::fs::metadata(path)?.is_file() { - return Err("GGUF source must be a regular file".into()); - } - let mut file = File::open(path)?; - let metadata = file.metadata()?; - if !metadata.is_file() { - return Err("GGUF source must be a regular file".into()); - } - let size = metadata.len(); - let identity = crate::verify_stamp::FileIdentity::of(&metadata); - let stamps = crate::verify_stamp::global(); - // A stamp skips the hash only for this very file in this very state, keyed by the pinned digest. - let trusted = matches!((stamps, identity.as_ref()), (Some(s), Some(id)) if s.trusts("gguf", &expected, id)); - let actual: [u8; 32] = if trusted { - expected - } else { - sha256_pipelined(&file, size)? - }; - if actual != expected { - return Err("GGUF artifact SHA256 mismatch".into()); - } - if file.metadata()?.len() != size { - return Err("GGUF source size changed during verification".into()); - } - if !trusted - && let (Some(stamps), Some(before)) = (stamps, identity) - && crate::verify_stamp::FileIdentity::of(&file.metadata()?) == Some(before) - { - // Only a file that did not change while it was hashed can vouch for itself next time. - let _ = stamps.record("gguf", &expected, &before); - } - let index = read_index_file(&mut file, size, true)?; - if file.metadata()?.len() != size { - return Err("GGUF source size changed during indexing".into()); - } - Ok(Self { - file, - index, - artifact_sha256: actual, - resident_source_id: None, - }) - } - - pub fn index(&self) -> &TensorIndex { - &self.index - } - - /// A duplicate of the retained descriptor (same open file, not a path - /// reopen) for positional reads. `pread` neither uses nor moves the shared - /// cursor. The indexed size is observed first, as for every stream. - pub fn duplicate_descriptor(&self) -> Result { - self.check_size()?; - Ok(self.file.try_clone()?) - } - - /// Digest verified when opening, not a promise of later source immutability. - pub fn artifact_sha256(&self) -> [u8; 32] { - self.artifact_sha256 - } - - /// Parse the bounded model/tokenizer metadata through the already verified - /// descriptor. The path is never reopened and the indexed file size is - /// checked on both sides of the snapshot. - #[cfg(test)] - pub(crate) fn metadata_snapshot(&mut self) -> Result { - self.check_size()?; - let snapshot = read_metadata_snapshot( - &mut self.file, - self.index.summary.file_size, - Some(QWEN4EXP_BINDING_KEYS), - true, - )?; - self.check_size()?; - Ok(snapshot) - } - - /// Parse only split metadata for the model binder's early admission phase. - /// Profile and tokenizer fields are skipped so their errors cannot precede - /// rejection of an invalid shard split. - pub(crate) fn split_snapshot(&mut self) -> Result { - self.check_size()?; - let snapshot = read_split_metadata_snapshot(&mut self.file, self.index.summary.file_size)?; - self.check_size()?; - Ok(snapshot) - } - - /// Parse only Qwen profile fields, deferring tokenizer work so the model - /// binder can preserve profile-before-tokenizer error precedence. - pub(crate) fn profile_snapshot(&mut self) -> Result { - self.check_size()?; - let snapshot = read_metadata_snapshot( - &mut self.file, - self.index.summary.file_size, - Some(QWEN4EXP_BINDING_KEYS), - false, - )?; - self.check_size()?; - Ok(snapshot) - } - - pub(crate) fn tokenizer_snapshot(&mut self) -> Result> { - self.check_size()?; - let snapshot = - read_metadata_snapshot(&mut self.file, self.index.summary.file_size, None, true)?; - self.check_size()?; - Ok(snapshot.tokenizer) - } - - /// Stream an exact byte range within an indexed tensor through a buffer of - /// at most 16 MiB. The consumer may return an I/O error to abort the stream. - /// No pathname is reopened; all range checks precede the first callback. - pub fn stream_tensor( - &mut self, - tensor_number: usize, - offset: u64, - bytes: u64, - consume: impl FnMut(&[u8]) -> std::io::Result<()>, - ) -> Result<()> { - let tensor = self - .index - .tensors - .get(tensor_number) - .ok_or("GGUF tensor index is out of bounds")?; - if tensor.bytes == 0 - || offset - .checked_add(bytes) - .is_none_or(|end| end > tensor.bytes) - { - return Err("GGUF tensor byte range is out of bounds".into()); - } - let absolute = self - .index - .summary - .data_start - .checked_add(tensor.offset) - .and_then(|start| start.checked_add(offset)) - .ok_or("GGUF tensor offset overflow")?; - if absolute - .checked_add(bytes) - .is_none_or(|end| end > self.index.summary.file_size) - { - return Err("GGUF tensor exceeds indexed file".into()); - } - self.check_size()?; - // Cached descriptor validation admits an empty span. Preserve both - // same-FD size checks without moving the retained reader's cursor. - if bytes != 0 { - stream_file_span(&mut self.file, absolute, bytes, consume)?; - } - self.check_size() - } - - /// Closed owned-span transport. The caller has fallibly allocated and - /// initialized this exact final owner; no stream scratch or append copy. - /// Same opened FD, indexed bounds and original pre/post size observations. - pub(crate) fn read_tensor_owned( - &mut self, - tensor_number: usize, - offset: u64, - mut bytes: Box<[u8]>, - ) -> Result> { - self.read_tensor_into(tensor_number, offset, &mut bytes)?; - Ok(bytes) - } - /// `read_tensor_owned` into caller-owned storage (the huge-page bank buffers of `huge_pages`): the same - /// FD, indexed bounds and pre/post size observations; every byte of `bytes` is written on success. - pub(crate) fn read_tensor_into( - &mut self, - tensor_number: usize, - offset: u64, - bytes: &mut [u8], - ) -> Result<()> { - let length = u64::try_from(bytes.len())?; - let tensor = self - .index - .tensors - .get(tensor_number) - .ok_or("GGUF tensor index is out of bounds")?; - if tensor.bytes == 0 - || offset - .checked_add(length) - .is_none_or(|end| end > tensor.bytes) - { - return Err("GGUF tensor byte range is out of bounds".into()); - } - let absolute = self - .index - .summary - .data_start - .checked_add(tensor.offset) - .and_then(|start| start.checked_add(offset)) - .ok_or("GGUF tensor offset overflow")?; - if absolute - .checked_add(length) - .is_none_or(|end| end > self.index.summary.file_size) - { - return Err("GGUF tensor exceeds indexed file".into()); - } - self.check_size()?; - // Original empty stream does not seek or invoke a consumer. - if length != 0 { - read_file_span_into(&mut self.file, absolute, bytes)?; - } - self.check_size()?; - Ok(()) - } - - /// Hash the complete indexed tensor without allocating its full payload. - pub fn tensor_sha256(&mut self, tensor_number: usize) -> Result<[u8; 32]> { - let bytes = self - .index - .tensors - .get(tensor_number) - .ok_or("GGUF tensor index is out of bounds")? - .bytes; - let mut digest = Sha256::new(); - self.stream_tensor(tensor_number, 0, bytes, |chunk| { - digest.update(chunk); - Ok(()) - })?; - Ok(digest.finalize().into()) - } - - fn check_size(&self) -> Result<()> { - if self.file.metadata()?.len() != self.index.summary.file_size { - return Err("GGUF source size changed after verification".into()); - } - Ok(()) - } -} - -fn parse_artifact_digest(value: &str) -> Result<[u8; 32]> { - let hex = value - .strip_prefix("sha256:") - .ok_or("invalid GGUF artifact digest")?; - if hex.len() != 64 || !hex.bytes().all(|byte| byte.is_ascii_hexdigit()) { - return Err("invalid GGUF artifact digest".into()); - } - let mut digest = [0u8; 32]; - for (index, byte) in digest.iter_mut().enumerate() { - *byte = u8::from_str_radix(&hex[index * 2..index * 2 + 2], 16)?; - } - Ok(digest) -} - -/// SHA-256 of the first `size` bytes, hashing while a reader thread keeps the next chunks coming. -fn sha256_pipelined(file: &File, size: u64) -> Result<[u8; 32]> { - crate::readahead::with_read_ahead(file, 0, size, 1, |mut receivers| -> Result<[u8; 32]> { - let receiver = receivers.remove(0); - let mut digest = Sha256::new(); - let mut total = 0u64; - for item in receiver { - let chunk = item?; - digest.update(&chunk[..]); - total += chunk.len() as u64; - } - if total != size { - return Err("GGUF source ended early during verification".into()); - } - Ok(digest.finalize().into()) - }) -} - -fn stream_file_span( - file: &mut File, - absolute: u64, - bytes: u64, - mut consume: impl FnMut(&[u8]) -> std::io::Result<()>, -) -> Result<()> { - file.seek(SeekFrom::Start(absolute))?; - let length = bytes.min(stream_buffer_bytes() as u64) as usize; - let mut buffer = Vec::new(); - buffer.try_reserve_exact(length)?; - buffer.resize(length, 0); - let mut remaining = bytes; - while remaining > 0 { - let count = remaining.min(buffer.len() as u64) as usize; - file.read_exact(&mut buffer[..count])?; - consume(&buffer[..count])?; - remaining -= count as u64; - } - Ok(()) -} - -// The owner is already initialized and exclusively held. Reads preserve the -// original seek followed by <=16MiB read_exact request order, including tails. -#[cfg_attr(not(test), allow(dead_code))] -fn read_file_span_owned(file: &mut File, absolute: u64, mut bytes: Box<[u8]>) -> Result> { - read_file_span_into(file, absolute, &mut bytes)?; - Ok(bytes) -} -fn read_file_span_into(file: &mut File, absolute: u64, bytes: &mut [u8]) -> Result<()> { - // A large span (a routed-expert tensor of hundreds of MB) is read in big blocks on several threads, so the - // device sees a deep queue; the bytes and the failure modes are the same (`bulk_read`). Positional reads leave the - // cursor alone, and every caller seeks before it reads. `LELEKA_LOAD_READ=legacy` keeps the sequential loop below. - #[cfg(target_os = "linux")] - if bytes.len() as u64 >= crate::bulk_read::MIN_PARALLEL_BYTES - && std::env::var("LELEKA_LOAD_READ").as_deref() != Ok("legacy") - { - crate::bulk_read::read_into(file, absolute, bytes, crate::bulk_read::Plan::from_env())?; - return Ok(()); - } - file.seek(SeekFrom::Start(absolute))?; - for chunk in bytes.chunks_mut(STREAM_BUFFER_BYTES) { - file.read_exact(chunk)?; - } - Ok(()) -} - -/// Metadata admission for the specialised engine, before expensive preparation. -/// Mirrors artifact/gguf_reader.hpp::Qwen4ExpGuard; this does not inspect tensor values. -pub fn check_flash_next_profile(path: &Path) -> Result<()> { - let mut file = File::open(path)?; - let size = file.metadata()?.len(); - read_index_file(&mut file, size, false)?; - let snapshot = read_metadata_snapshot(&mut file, size, Some(FLASH_NEXT_PROFILE_KEYS), false)?; - validate_flash_next_profile(&snapshot) -} - -fn validate_flash_next_profile(snapshot: &MetadataSnapshot) -> Result<()> { - if snapshot.architecture.as_deref() != Some("qwen4exp") { - return Err("runtime_profile requires general.architecture=qwen4exp".into()); - } - let required = [ - ("qwen4exp.block_count", Some(48)), - ("qwen4exp.embedding_length", Some(2560)), - ("qwen4exp.attention.head_count", Some(24)), - ("qwen4exp.attention.head_count_kv", Some(2)), - ("qwen4exp.expert_count", None), - ("qwen4exp.expert_used_count", None), - ]; - let mut values = BTreeMap::new(); - for (key, expected) in required { - let value = match snapshot.values.get(key) { - Some(MetadataValue::Unsigned(value)) => u32::try_from(*value).map_err(|_| { - format!("runtime_profile: {key} must be a nonnegative 32-bit integer") - })?, - Some(MetadataValue::Signed(value)) => u32::try_from(*value).map_err(|_| { - format!("runtime_profile: {key} must be a nonnegative 32-bit integer") - })?, - None => return Err(format!("runtime_profile: missing {key}").into()), - _ => return Err(format!("runtime_profile: {key} must be an integer").into()), - }; - values.insert(key, value); - if value == 0 || value > i32::MAX as u32 { - return Err(format!("runtime_profile: {key} must be in 1..2147483647").into()); - } - if let Some(expected) = expected - && value != expected - { - return Err(format!("runtime_profile: {key}={value}, expected {expected}").into()); - } - } - if values["qwen4exp.expert_used_count"] > values["qwen4exp.expert_count"] { - return Err( - "runtime_profile: qwen4exp.expert_used_count exceeds qwen4exp.expert_count".into(), - ); - } - Ok(()) -} - -/// Every metadata key/value of a GGUF file, in file order, bounded like the other readers (1M entries, 1 MiB -/// strings, 1M-element arrays, 512 MiB of array text). Duplicate keys and nested arrays are refused, and so is a -/// string that is not valid UTF-8 (`tools/gguf_reader.py` replaces bad bytes instead). Tensor payloads are never read. -pub fn metadata_entries(path: &Path) -> Result> { - let mut file = File::open(path)?; - let size = file.metadata()?.len(); - read_index_file(&mut file, size, false)?; - file.seek(SeekFrom::Start(0))?; - let mut cursor = Cursor::new(&mut file, size); - cursor.skip(16)?; // magic, version, tensor count - let count = cursor.u64()?; - if count > 1_000_000 { - return Err("unreasonable GGUF header count".into()); - } - let mut seen = HashSet::new(); - let mut entries = Vec::new(); - for _ in 0..count { - let key = cursor.string()?; - if !seen.insert(key.clone()) { - return Err(format!("duplicate GGUF metadata key: {key}").into()); - } - let kind = cursor.u32()?; - entries.push((key, cursor.metadata_value(kind)?)); - } - Ok(entries) -} - -/// Read only tokenizer fields after the complete GGUF header has passed inspection. -pub fn tokenizer_metadata(path: &Path) -> Result { - let mut file = File::open(path)?; - let size = file.metadata()?.len(); - read_index_file(&mut file, size, false)?; - validate_tokenizer_metadata( - read_metadata_snapshot(&mut file, size, None, true)? - .tokenizer - .ok_or("GGUF is missing required tokenizer metadata")?, - ) -} - -fn read_metadata_snapshot( - file: &mut File, - size: u64, - qwen_keys: Option<&[&str]>, - parse_tokenizer: bool, -) -> Result { - read_metadata_snapshot_with_architecture(file, size, qwen_keys, parse_tokenizer, true) -} - -fn read_split_metadata_snapshot(file: &mut File, size: u64) -> Result { - read_metadata_snapshot_with_architecture(file, size, None, false, false) -} - -fn read_metadata_snapshot_with_architecture( - file: &mut File, - size: u64, - qwen_keys: Option<&[&str]>, - parse_tokenizer: bool, - parse_architecture: bool, -) -> Result { - file.seek(SeekFrom::Start(0))?; - let mut cursor = Cursor::new(file, size); - cursor.skip(16)?; // magic, version, tensor count - let count = cursor.u64()?; - if count > 1_000_000 { - return Err("unreasonable GGUF header count".into()); - } - let mut architecture = None; - let mut split_no = None; - let mut split_count = None; - let mut split_tensors_count = None; - let mut model = None; - let mut pre = None; - let mut tokens = None; - let mut merges = None; - let mut token_types = None; - let mut special_ids = BTreeMap::new(); - let mut chat_template = None; - let mut values = BTreeMap::new(); - let mut seen = HashSet::new(); - for _ in 0..count { - let key = cursor.string()?; - if !seen.insert(key.clone()) { - return Err(format!("duplicate GGUF metadata key: {key}").into()); - } - let kind = cursor.u32()?; - match key.as_str() { - "general.architecture" if parse_architecture && kind == 8 => { - architecture = Some(cursor.string()?) - } - "split.no" if kind == 2 => split_no = Some(u64::from(cursor.u16()?)), - "split.count" if kind == 2 => split_count = Some(u64::from(cursor.u16()?)), - "split.tensors.count" if kind == 5 => { - split_tensors_count = Some(u64::from(cursor.u32()?)) - } - "split.no" | "split.count" | "split.tensors.count" => { - return Err("GGUF split metadata has an invalid integer type".into()); - } - "tokenizer.ggml.model" if parse_tokenizer && kind == 8 => { - model = Some(cursor.string()?) - } - "tokenizer.ggml.pre" if parse_tokenizer && kind == 8 => pre = Some(cursor.string()?), - "tokenizer.ggml.tokens" if parse_tokenizer => tokens = Some(cursor.string_array(kind)?), - "tokenizer.ggml.merges" if parse_tokenizer => merges = Some(cursor.string_array(kind)?), - "tokenizer.ggml.token_type" if parse_tokenizer => { - token_types = Some(cursor.integer_array(kind)?) - } - "tokenizer.chat_template" if parse_tokenizer && kind == 8 => { - chat_template = Some(cursor.string()?) - } - _ if parse_tokenizer - && key.starts_with("tokenizer.ggml.") - && key.ends_with("_token_id") => - { - special_ids.insert(key, cursor.integer(kind)?); - } - _ if qwen_keys.is_some_and(|keys| keys.contains(&key.as_str())) => { - values.insert(key, cursor.metadata_value(kind)?); - } - _ => cursor.skip_value(kind)?, - } - } - let tokenizer = match (model, tokens, merges, chat_template) { - (Some(model), Some(tokens), Some(merges), Some(chat_template)) => Some(TokenizerMetadata { - model, - pre: pre.unwrap_or_else(|| "qwen35".to_owned()), - tokens, - merges, - token_types, - special_ids, - chat_template, - }), - _ => None, - }; - Ok(MetadataSnapshot { - architecture, - split_no, - split_count, - split_tensors_count, - values, - tokenizer, - }) -} - -pub(crate) fn validate_tokenizer_metadata( - tokenizer: TokenizerMetadata, -) -> Result { - let TokenizerMetadata { - model, - pre, - tokens, - merges, - token_types, - special_ids, - chat_template, - } = tokenizer; - if model != "gpt2" || pre != "qwen35" { - return Err("only the qwen35 byte-level BPE tokenizer is supported".into()); - } - if tokens.is_empty() || chat_template.is_empty() { - return Err("GGUF tokenizer has an empty vocabulary or chat template".into()); - } - if token_types - .as_ref() - .is_some_and(|types| types.len() != tokens.len()) - { - return Err("token_type length differs from vocabulary length".into()); - } - let vocab: HashSet<&str> = tokens.iter().map(String::as_str).collect(); - if vocab.len() != tokens.len() { - return Err("GGUF tokenizer has duplicate vocabulary entries".into()); - } - let mut seen_merges = HashSet::new(); - for merge in &merges { - let Some((left, right)) = merge.split_once(' ') else { - return Err("GGUF BPE merge is not a pair".into()); - }; - if left.is_empty() - || right.is_empty() - || right.contains(' ') - || !vocab.contains(left) - || !vocab.contains(right) - || !seen_merges.insert(merge) - { - return Err("GGUF BPE merge is invalid or duplicated".into()); - } - } - for &id in special_ids.values() { - if id as usize >= tokens.len() { - return Err("special token ID exceeds vocabulary".into()); - } - } - Ok(TokenizerMetadata { - model, - pre, - tokens, - merges, - token_types, - special_ids, - chat_template, - }) -} - -pub fn inspect(path: &Path) -> Result { - Ok(read_index(path, false)?.summary) -} - -/// Locate each supported tensor payload without reading the tensor into RAM. -/// Types and byte lengths follow the pinned Strata GGUF reader geometry. -pub fn tensor_index(path: &Path) -> Result { - read_index(path, true) -} - -/// Hash one indexed tensor with a fixed-size buffer. The caller must keep the -/// verified source file stable between indexing and reading. -pub fn tensor_sha256(path: &Path, index: &TensorIndex, tensor_number: usize) -> Result<[u8; 32]> { - let tensor = index - .tensors - .get(tensor_number) - .ok_or("GGUF tensor index is out of bounds")?; - if tensor.bytes == 0 { - return Err("GGUF tensor index lacks verified byte geometry".into()); - } - let absolute = index - .summary - .data_start - .checked_add(tensor.offset) - .ok_or("GGUF tensor offset overflow")?; - if absolute - .checked_add(tensor.bytes) - .is_none_or(|end| end > index.summary.file_size) - { - return Err("GGUF tensor exceeds indexed file".into()); - } - let mut file = File::open(path)?; - if file.metadata()?.len() != index.summary.file_size { - return Err("GGUF source size changed after indexing".into()); - } - file.seek(SeekFrom::Start(absolute))?; - let mut digest = Sha256::new(); - let mut buffer = vec![0u8; 1024 * 1024]; - let mut remaining = tensor.bytes; - while remaining > 0 { - let count = remaining.min(buffer.len() as u64) as usize; - file.read_exact(&mut buffer[..count])?; - digest.update(&buffer[..count]); - remaining -= count as u64; - } - Ok(digest.finalize().into()) -} - -fn read_index(path: &Path, strict: bool) -> Result { - let mut file = File::open(path)?; - let size = file.metadata()?.len(); - read_index_file(&mut file, size, strict) -} - -fn read_index_file(file: &mut File, size: u64, strict: bool) -> Result { - file.seek(SeekFrom::Start(0))?; - let mut cursor = Cursor::new(file, size); - if cursor.take(4)? != b"GGUF" { - return Err("not a GGUF file".into()); - } - if cursor.u32()? != 3 { - return Err("only GGUF v3 is supported".into()); - } - let tensors = cursor.u64()?; - let metadata = cursor.u64()?; - if tensors > 1_000_000 || metadata > 1_000_000 { - return Err("unreasonable GGUF header count".into()); - } - let mut architecture = None; - let mut split_no = None; - let mut split_count = None; - let mut split_tensors_count = None; - let mut alignment = 32u64; - let mut keys = HashSet::new(); - for _ in 0..metadata { - let key = cursor.string()?; - if !keys.insert(key.clone()) { - return Err(format!("duplicate GGUF metadata key: {key}").into()); - } - let kind = cursor.u32()?; - match (key.as_str(), kind) { - ("general.architecture", 8) => architecture = Some(cursor.string()?), - ("general.alignment", 4) => alignment = u64::from(cursor.u32()?), - ("general.alignment", _) => { - // tools/gguf_reader.py accepts any integer width; llama.cpp and the C++ engine read a uint32. - // Silently keeping the default would place the data section at the wrong byte. - return Err("general.alignment must be a uint32".into()); - } - ("split.no", 2) => split_no = Some(u64::from(cursor.u16()?)), - ("split.count", 2) => split_count = Some(u64::from(cursor.u16()?)), - ("split.tensors.count", 5) => { - let count = cursor.u32()?; - if count > i32::MAX as u32 { - return Err("negative GGUF split tensor count".into()); - } - split_tensors_count = Some(u64::from(count)); - } - ("split.no" | "split.count" | "split.tensors.count", _) => { - return Err("GGUF split metadata has an invalid integer type".into()); - } - _ => cursor.skip_value(kind)?, - } - } - if !alignment.is_power_of_two() || alignment > 4096 { - return Err("invalid GGUF alignment".into()); - } - let mut types = BTreeMap::new(); - let mut names = HashSet::new(); - let mut tensor_index = Vec::with_capacity(tensors as usize); - for _ in 0..tensors { - let name = cursor.string()?; - if !names.insert(name.clone()) { - return Err("duplicate GGUF tensor name".into()); - } - let dimensions = cursor.u32()?; - if !(1..=8).contains(&dimensions) { - return Err("invalid GGUF tensor dimensions".into()); - } - let mut shape = Vec::with_capacity(dimensions as usize); - for _ in 0..dimensions { - let dim = cursor.u64()?; - if dim == 0 { - return Err("zero GGUF tensor dimension".into()); - } - shape.push(dim); - } - let kind = cursor.u32()?; - let offset = cursor.u64()?; - *types.entry(kind).or_insert(0) += 1; - tensor_index.push(TensorInfo { - name, - dimensions: shape, - kind, - offset, - bytes: 0, - }); - } - let header_end = cursor.position()?; - let data_start = header_end - .checked_add(alignment - 1) - .ok_or("GGUF header offset overflow")? - / alignment - * alignment; - if data_start > size { - return Err("GGUF data section is truncated".into()); - } - for tensor in &tensor_index { - if tensor.offset % alignment != 0 - || data_start - .checked_add(tensor.offset) - .is_none_or(|start| start >= size) - { - return Err("GGUF tensor offset is out of bounds or unaligned".into()); - } - } - if strict { - let mut positions = (0..tensor_index.len()).collect::>(); - if positions.is_empty() { - return Err("GGUF has no tensors to index".into()); - } - positions.sort_unstable_by_key(|&index| tensor_index[index].offset); - if tensor_index[positions[0]].offset != 0 { - return Err("GGUF first tensor does not start at data offset zero".into()); - } - for (at, &index) in positions.iter().enumerate() { - let tensor = &tensor_index[index]; - let (block_elements, block_bytes) = block_geometry(tensor.kind) - .ok_or_else(|| format!("unsupported GGUF tensor type {}", tensor.kind))?; - let elements = tensor - .dimensions - .iter() - .try_fold(1u64, |product, dim| product.checked_mul(*dim)) - .ok_or("GGUF tensor element count overflow")?; - if tensor.dimensions[0] % block_elements != 0 { - return Err(format!("{}: tensor row is not block aligned", tensor.name).into()); - } - let bytes = elements - .checked_div(block_elements) - .and_then(|blocks| blocks.checked_mul(block_bytes)) - .ok_or("GGUF tensor byte count overflow")?; - let end = tensor - .offset - .checked_add(bytes) - .ok_or("GGUF tensor end overflow")?; - let next = positions - .get(at + 1) - .map(|&next| tensor_index[next].offset) - .unwrap_or(size - data_start); - if end > next || next - end >= alignment { - return Err(format!( - "{}: tensor bytes overlap or have an invalid gap", - tensor.name - ) - .into()); - } - tensor_index[index].bytes = bytes; - } - } - if let (Some(no), Some(count)) = (split_no, split_count) - && (count == 0 || no >= count) - { - return Err("invalid GGUF split metadata".into()); - } - let summary = Summary { - tensors, - metadata, - architecture, - split_no, - split_count, - split_tensors_count, - data_start, - file_size: size, - types, - }; - Ok(TensorIndex { - summary, - tensors: tensor_index, - }) -} - -pub fn block_geometry(kind: u32) -> Option<(u64, u64)> { - // Mirrors engine/strata/include/strata/artifact/gguf_reader.hpp at the - // upstream commit recorded in docs/upstream.md, plus the kinds - // engine/strata/tools/gguf_reader.py BLOCK_GEOMETRY knows beyond it (Q8_K 15, - // IQ1_S 19, F64 28, MXFP4 39, NVFP4 40). Geometry is only a byte count: a - // consumer that cannot decode a kind still refuses it at use. Differential: - // control-plane/tests/gguf_header_differential.rs. - Some(match kind { - 0 => (1, 4), - 1 | 30 => (1, 2), - 2 => (32, 18), - 3 => (32, 20), - 6 => (32, 22), - 7 => (32, 24), - 8 => (32, 34), - 9 => (32, 36), - 10 => (256, 84), - 11 | 21 => (256, 110), - 12 => (256, 144), - 13 => (256, 176), - 14 => (256, 210), - 15 => (256, 292), - 16 => (256, 66), - 17 => (256, 74), - 18 => (256, 98), - 19 => (256, 50), - 20 => (32, 18), - 22 => (256, 82), - 23 => (256, 136), - 24 => (1, 1), - 28 => (1, 8), - 29 => (256, 56), - 39 => (32, 17), - 40 => (64, 36), - 42 => (64, 18), - // APR trellis types (gguf_reader.hpp 143 to 146, gguf_reader.py BLOCK_GEOMETRY): 128 values per block, - // PTQ1_0 28 bytes, TQ2_T 34, TQK6 26, TQK7 30 - 143 => (128, 28), - 144 => (128, 34), - 145 => (128, 26), - 146 => (128, 30), - _ => return None, - }) -} - struct Cursor { file: BufReader, size: u64, position: u64, } -impl Cursor { - // Both parser entrypoints have already sought the same descriptor to zero. - fn new(file: R, size: u64) -> Self { - Self { - file: BufReader::with_capacity(STREAM_BUFFER_BYTES, file), - size, - position: 0, - } - } - - #[cfg(test)] - fn with_test_capacity(file: R, size: u64, capacity: usize) -> Self { - assert!(capacity > 0 && capacity <= STREAM_BUFFER_BYTES); - Self { - file: BufReader::with_capacity(capacity, file), - size, - position: 0, - } - } - - fn position(&mut self) -> Result { - Ok(self.position) - } - - fn skip(&mut self, bytes: u64) -> Result<()> { - let end = self - .position()? - .checked_add(bytes) - .ok_or("GGUF offset overflow")?; - if end > self.size { - return Err("truncated GGUF header".into()); - } - if bytes <= self.file.buffer().len() as u64 { - self.file.consume(bytes as usize); - } else { - self.file.seek(SeekFrom::Start(end))?; - } - self.position = end; - Ok(()) - } - - fn take(&mut self, size: usize) -> Result> { - let end = self - .position()? - .checked_add(size as u64) - .filter(|end| *end <= self.size) - .ok_or("truncated GGUF header")?; - let mut data = Vec::new(); - data.try_reserve_exact(size)?; - data.resize(size, 0); - self.file.read_exact(&mut data)?; - self.position = end; - Ok(data) - } - - fn u16(&mut self) -> Result { - let bytes = self.take(2)?; - Ok(u16::from_le_bytes([bytes[0], bytes[1]])) - } - - fn u8(&mut self) -> Result { - Ok(self.take(1)?[0]) - } - - fn u32(&mut self) -> Result { - let bytes = self.take(4)?; - Ok(u32::from_le_bytes([bytes[0], bytes[1], bytes[2], bytes[3]])) - } - - fn u64(&mut self) -> Result { - let bytes = self.take(8)?; - Ok(u64::from_le_bytes([ - bytes[0], bytes[1], bytes[2], bytes[3], bytes[4], bytes[5], bytes[6], bytes[7], - ])) - } - - fn string(&mut self) -> Result { - let size = self.u64()?; - if size > 1_048_576 { - return Err("GGUF header string is too large".into()); - } - Ok(String::from_utf8(self.take(size as usize)?)?) - } - - fn string_array(&mut self, kind: u32) -> Result> { - if kind != 9 || self.u32()? != 8 { - return Err("expected a GGUF string array".into()); - } - let count = self.u64()?; - if count > 1_000_000 { - return Err("unreasonable GGUF tokenizer array count".into()); - } - let mut total = 0u64; - let mut values = Vec::with_capacity(count as usize); - for _ in 0..count { - let value = self.string()?; - total = total - .checked_add(value.len() as u64) - .ok_or("GGUF tokenizer array size overflow")?; - if total > 512 * 1024 * 1024 { - return Err("GGUF tokenizer array exceeds 512 MiB".into()); - } - values.push(value); - } - Ok(values) - } - - fn integer_array(&mut self, kind: u32) -> Result> { - if kind != 9 { - return Err("expected a GGUF integer array".into()); - } - let element = self.u32()?; - let count = self.u64()?; - if count > 1_000_000 { - return Err("unreasonable GGUF tokenizer array count".into()); - } - let mut values = Vec::with_capacity(count as usize); - for _ in 0..count { - values.push(self.integer(element)?); - } - Ok(values) - } - - fn integer(&mut self, kind: u32) -> Result { - match kind { - 0 | 7 => Ok(u32::from(self.u8()?)), - 1 => u32::try_from(self.u8()? as i8).map_err(Into::into), - 2 => Ok(u32::from(self.u16()?)), - 3 => u32::try_from(self.u16()? as i16).map_err(Into::into), - 4 => self.u32(), - 5 => u32::try_from(self.u32()? as i32).map_err(Into::into), - 10 => u32::try_from(self.u64()?).map_err(Into::into), - 11 => u32::try_from(self.u64()? as i64).map_err(Into::into), - _ => Err(format!("GGUF metadata type {kind} is not an integer").into()), - } - } - - fn metadata_value(&mut self, kind: u32) -> Result { - Ok(match kind { - 0 => MetadataValue::Unsigned(u64::from(self.u8()?)), - 7 => MetadataValue::Boolean(self.u8()? != 0), - 1 => MetadataValue::Signed(i64::from(self.u8()? as i8)), - 2 => MetadataValue::Unsigned(u64::from(self.u16()?)), - 3 => MetadataValue::Signed(i64::from(self.u16()? as i16)), - 4 => MetadataValue::Unsigned(u64::from(self.u32()?)), - 5 => MetadataValue::Signed(i64::from(self.u32()? as i32)), - 6 => MetadataValue::Float(f64::from(f32::from_bits(self.u32()?))), - 8 => MetadataValue::Text(self.string()?), - 9 => self.metadata_array()?, - 10 => MetadataValue::Unsigned(self.u64()?), - 11 => MetadataValue::Signed(self.u64()? as i64), - 12 => MetadataValue::Float(f64::from_bits(self.u64()?)), - _ => return Err(format!("unknown GGUF metadata type {kind}").into()), - }) - } - - fn metadata_array(&mut self) -> Result { - let element = self.u32()?; - let count = self.u64()?; - if count > 1_000_000 { - return Err("unreasonable GGUF metadata array count".into()); - } - let capacity = count as usize; - match element { - 7 => { - let mut values = Vec::with_capacity(capacity); - for _ in 0..count { - values.push(self.u8()? != 0); - } - Ok(MetadataValue::BooleanArray(values)) - } - 0 | 2 | 4 | 10 => { - let mut values = Vec::with_capacity(capacity); - for _ in 0..count { - values.push(match element { - 0 => u64::from(self.u8()?), - 2 => u64::from(self.u16()?), - 4 => u64::from(self.u32()?), - 10 => self.u64()?, - _ => unreachable!(), - }); - } - Ok(MetadataValue::UnsignedArray(values)) - } - 1 | 3 | 5 | 11 => { - let mut values = Vec::with_capacity(capacity); - for _ in 0..count { - values.push(match element { - 1 => i64::from(self.u8()? as i8), - 3 => i64::from(self.u16()? as i16), - 5 => i64::from(self.u32()? as i32), - 11 => self.u64()? as i64, - _ => unreachable!(), - }); - } - Ok(MetadataValue::SignedArray(values)) - } - 6 | 12 => { - let mut values = Vec::with_capacity(capacity); - for _ in 0..count { - values.push(if element == 6 { - f64::from(f32::from_bits(self.u32()?)) - } else { - f64::from_bits(self.u64()?) - }); - } - Ok(MetadataValue::FloatArray(values)) - } - 8 => { - let mut total = 0u64; - let mut values = Vec::with_capacity(capacity); - for _ in 0..count { - let value = self.string()?; - total = total - .checked_add(value.len() as u64) - .ok_or("GGUF metadata array size overflow")?; - if total > 512 * 1024 * 1024 { - return Err("GGUF metadata string array exceeds 512 MiB".into()); - } - values.push(value); - } - Ok(MetadataValue::TextArray(values)) - } - 9 => Err("nested GGUF arrays are unsupported".into()), - _ => Err(format!("invalid GGUF metadata array element type {element}").into()), - } - } - - fn skip_value(&mut self, kind: u32) -> Result<()> { - match kind { - 0 | 1 | 7 => self.skip(1), - 2 | 3 => self.skip(2), - 4..=6 => self.skip(4), - 8 => { - let size = self.u64()?; - self.skip(size) - } - 9 => { - let element = self.u32()?; - let count = self.u64()?; - match element { - 8 => { - if count > 10_000_000 { - return Err("unreasonable GGUF string array count".into()); - } - for _ in 0..count { - let size = self.u64()?; - self.skip(size)?; - } - Ok(()) - } - 9 => Err("nested GGUF arrays are unsupported".into()), - _ => self.skip( - count - .checked_mul(value_width(element)?) - .ok_or("GGUF array size overflow")?, - ), - } - } - 10..=12 => self.skip(8), - _ => Err(format!("unknown GGUF metadata type {kind}").into()), - } - } -} - -fn value_width(kind: u32) -> Result { - match kind { - 0 | 1 | 7 => Ok(1), - 2 | 3 => Ok(2), - 4..=6 => Ok(4), - 10..=12 => Ok(8), - _ => Err(format!("invalid GGUF array element type {kind}").into()), - } -} - #[cfg(test)] mod tests { use super::*; @@ -2191,76 +1053,6 @@ mod tests { pub(crate) struct GgufSourceFence<'source> { source: &'source mut VerifiedGgufFile, } -impl GgufSourceFence<'_> { - pub(crate) fn validate_tensor(&self, tensor_number: usize) -> Result<()> { - self.source.validate_empty_tensor_span(tensor_number) - } - pub(crate) fn stream_tensor( - &mut self, - tensor_number: usize, - offset: u64, - bytes: u64, - consume: impl FnMut(&[u8]) -> std::io::Result<()>, - ) -> Result<()> { - // Real misses preserve the original full range and before/after source - // checks, cursor behavior, read errors and bounded stream buffer. - self.source - .stream_tensor(tensor_number, offset, bytes, consume) - } - pub(crate) fn read_tensor_owned( - &mut self, - tensor_number: usize, - offset: u64, - bytes: Box<[u8]>, - ) -> Result> { - self.source.read_tensor_owned(tensor_number, offset, bytes) - } - pub(crate) fn finish(self) -> Result<()> { - self.source.check_size() - } -} -impl VerifiedGgufFile { - /// Recheck the same descriptor admission performed by an empty stream - /// without borrowing the retained reader mutably. This preserves the - /// geometry and both same-FD size observations while leaving its cursor - /// untouched for an immutable source lease. - pub(crate) fn validate_empty_tensor_source(&self, tensor_number: usize) -> Result<()> { - self.validate_empty_tensor_span(tensor_number)?; - self.check_size()?; - self.check_size() - } - - fn validate_empty_tensor_span(&self, tensor_number: usize) -> Result<()> { - let tensor = self - .index - .tensors - .get(tensor_number) - .ok_or("GGUF tensor index is out of bounds")?; - if tensor.bytes == 0 { - return Err("GGUF tensor byte range is out of bounds".into()); - } - let absolute = self - .index - .summary - .data_start - .checked_add(tensor.offset) - .ok_or("GGUF tensor offset overflow")?; - if absolute > self.index.summary.file_size { - return Err("GGUF tensor exceeds indexed file".into()); - } - Ok(()) - } - pub(crate) fn begin_source_fence( - &mut self, - tensor_number: usize, - ) -> Result> { - // Exactly the original first empty-span geometry precedes the first - // size observation. No seek, read, allocation or cursor mutation. - self.validate_empty_tensor_span(tensor_number)?; - self.check_size()?; - Ok(GgufSourceFence { source: self }) - } -} #[cfg(test)] #[path = "gguf_owned_read_test.rs"] @@ -2283,3 +1075,25 @@ pub use expert_file_source::ExpertFileOwner; #[path = "gguf_native_head.rs"] mod native_head_model; pub use native_head_model::{NativeHeadGgufModel, NativeHeadTensor}; + +mod stream_buffer_bytes; +#[allow(unused_imports)] +pub use stream_buffer_bytes::*; +mod impl_verifiedgguffile; +#[allow(unused_imports)] +pub use impl_verifiedgguffile::*; +mod parse_artifact_digest; +#[allow(unused_imports)] +pub use parse_artifact_digest::*; +mod read_metadata_snapshot_with_architecture; +#[allow(unused_imports)] +pub use read_metadata_snapshot_with_architecture::*; +mod read_index_file; +#[allow(unused_imports)] +pub use read_index_file::*; +mod impl_cursor; +#[allow(unused_imports)] +pub use impl_cursor::*; +mod value_width; +#[allow(unused_imports)] +pub use value_width::*; diff --git a/crates/model-format/src/gguf/impl_cursor.rs b/crates/model-format/src/gguf/impl_cursor.rs new file mode 100644 index 00000000..640afc07 --- /dev/null +++ b/crates/model-format/src/gguf/impl_cursor.rs @@ -0,0 +1,270 @@ +//! Moved out of the parent module by STRA-338: impl Cursor. + +#[allow(unused_imports)] +use super::*; + + +impl Cursor { + // Both parser entrypoints have already sought the same descriptor to zero. + pub(super) fn new(file: R, size: u64) -> Self { + Self { + file: BufReader::with_capacity(STREAM_BUFFER_BYTES, file), + size, + position: 0, + } + } + + #[cfg(test)] + pub(super) fn with_test_capacity(file: R, size: u64, capacity: usize) -> Self { + assert!(capacity > 0 && capacity <= STREAM_BUFFER_BYTES); + Self { + file: BufReader::with_capacity(capacity, file), + size, + position: 0, + } + } + + pub(super) fn position(&mut self) -> Result { + Ok(self.position) + } + + pub(super) fn skip(&mut self, bytes: u64) -> Result<()> { + let end = self + .position()? + .checked_add(bytes) + .ok_or("GGUF offset overflow")?; + if end > self.size { + return Err("truncated GGUF header".into()); + } + if bytes <= self.file.buffer().len() as u64 { + self.file.consume(bytes as usize); + } else { + self.file.seek(SeekFrom::Start(end))?; + } + self.position = end; + Ok(()) + } + + pub(super) fn take(&mut self, size: usize) -> Result> { + let end = self + .position()? + .checked_add(size as u64) + .filter(|end| *end <= self.size) + .ok_or("truncated GGUF header")?; + let mut data = Vec::new(); + data.try_reserve_exact(size)?; + data.resize(size, 0); + self.file.read_exact(&mut data)?; + self.position = end; + Ok(data) + } + + pub(super) fn u16(&mut self) -> Result { + let bytes = self.take(2)?; + Ok(u16::from_le_bytes([bytes[0], bytes[1]])) + } + + pub(super) fn u8(&mut self) -> Result { + Ok(self.take(1)?[0]) + } + + pub(super) fn u32(&mut self) -> Result { + let bytes = self.take(4)?; + Ok(u32::from_le_bytes([bytes[0], bytes[1], bytes[2], bytes[3]])) + } + + pub(super) fn u64(&mut self) -> Result { + let bytes = self.take(8)?; + Ok(u64::from_le_bytes([ + bytes[0], bytes[1], bytes[2], bytes[3], bytes[4], bytes[5], bytes[6], bytes[7], + ])) + } + + pub(super) fn string(&mut self) -> Result { + let size = self.u64()?; + if size > 1_048_576 { + return Err("GGUF header string is too large".into()); + } + Ok(String::from_utf8(self.take(size as usize)?)?) + } + + pub(super) fn string_array(&mut self, kind: u32) -> Result> { + if kind != 9 || self.u32()? != 8 { + return Err("expected a GGUF string array".into()); + } + let count = self.u64()?; + if count > 1_000_000 { + return Err("unreasonable GGUF tokenizer array count".into()); + } + let mut total = 0u64; + let mut values = Vec::with_capacity(count as usize); + for _ in 0..count { + let value = self.string()?; + total = total + .checked_add(value.len() as u64) + .ok_or("GGUF tokenizer array size overflow")?; + if total > 512 * 1024 * 1024 { + return Err("GGUF tokenizer array exceeds 512 MiB".into()); + } + values.push(value); + } + Ok(values) + } + + pub(super) fn integer_array(&mut self, kind: u32) -> Result> { + if kind != 9 { + return Err("expected a GGUF integer array".into()); + } + let element = self.u32()?; + let count = self.u64()?; + if count > 1_000_000 { + return Err("unreasonable GGUF tokenizer array count".into()); + } + let mut values = Vec::with_capacity(count as usize); + for _ in 0..count { + values.push(self.integer(element)?); + } + Ok(values) + } + + pub(super) fn integer(&mut self, kind: u32) -> Result { + match kind { + 0 | 7 => Ok(u32::from(self.u8()?)), + 1 => u32::try_from(self.u8()? as i8).map_err(Into::into), + 2 => Ok(u32::from(self.u16()?)), + 3 => u32::try_from(self.u16()? as i16).map_err(Into::into), + 4 => self.u32(), + 5 => u32::try_from(self.u32()? as i32).map_err(Into::into), + 10 => u32::try_from(self.u64()?).map_err(Into::into), + 11 => u32::try_from(self.u64()? as i64).map_err(Into::into), + _ => Err(format!("GGUF metadata type {kind} is not an integer").into()), + } + } + + pub(super) fn metadata_value(&mut self, kind: u32) -> Result { + Ok(match kind { + 0 => MetadataValue::Unsigned(u64::from(self.u8()?)), + 7 => MetadataValue::Boolean(self.u8()? != 0), + 1 => MetadataValue::Signed(i64::from(self.u8()? as i8)), + 2 => MetadataValue::Unsigned(u64::from(self.u16()?)), + 3 => MetadataValue::Signed(i64::from(self.u16()? as i16)), + 4 => MetadataValue::Unsigned(u64::from(self.u32()?)), + 5 => MetadataValue::Signed(i64::from(self.u32()? as i32)), + 6 => MetadataValue::Float(f64::from(f32::from_bits(self.u32()?))), + 8 => MetadataValue::Text(self.string()?), + 9 => self.metadata_array()?, + 10 => MetadataValue::Unsigned(self.u64()?), + 11 => MetadataValue::Signed(self.u64()? as i64), + 12 => MetadataValue::Float(f64::from_bits(self.u64()?)), + _ => return Err(format!("unknown GGUF metadata type {kind}").into()), + }) + } + + pub(super) fn metadata_array(&mut self) -> Result { + let element = self.u32()?; + let count = self.u64()?; + if count > 1_000_000 { + return Err("unreasonable GGUF metadata array count".into()); + } + let capacity = count as usize; + match element { + 7 => { + let mut values = Vec::with_capacity(capacity); + for _ in 0..count { + values.push(self.u8()? != 0); + } + Ok(MetadataValue::BooleanArray(values)) + } + 0 | 2 | 4 | 10 => { + let mut values = Vec::with_capacity(capacity); + for _ in 0..count { + values.push(match element { + 0 => u64::from(self.u8()?), + 2 => u64::from(self.u16()?), + 4 => u64::from(self.u32()?), + 10 => self.u64()?, + _ => unreachable!(), + }); + } + Ok(MetadataValue::UnsignedArray(values)) + } + 1 | 3 | 5 | 11 => { + let mut values = Vec::with_capacity(capacity); + for _ in 0..count { + values.push(match element { + 1 => i64::from(self.u8()? as i8), + 3 => i64::from(self.u16()? as i16), + 5 => i64::from(self.u32()? as i32), + 11 => self.u64()? as i64, + _ => unreachable!(), + }); + } + Ok(MetadataValue::SignedArray(values)) + } + 6 | 12 => { + let mut values = Vec::with_capacity(capacity); + for _ in 0..count { + values.push(if element == 6 { + f64::from(f32::from_bits(self.u32()?)) + } else { + f64::from_bits(self.u64()?) + }); + } + Ok(MetadataValue::FloatArray(values)) + } + 8 => { + let mut total = 0u64; + let mut values = Vec::with_capacity(capacity); + for _ in 0..count { + let value = self.string()?; + total = total + .checked_add(value.len() as u64) + .ok_or("GGUF metadata array size overflow")?; + if total > 512 * 1024 * 1024 { + return Err("GGUF metadata string array exceeds 512 MiB".into()); + } + values.push(value); + } + Ok(MetadataValue::TextArray(values)) + } + 9 => Err("nested GGUF arrays are unsupported".into()), + _ => Err(format!("invalid GGUF metadata array element type {element}").into()), + } + } + + pub(super) fn skip_value(&mut self, kind: u32) -> Result<()> { + match kind { + 0 | 1 | 7 => self.skip(1), + 2 | 3 => self.skip(2), + 4..=6 => self.skip(4), + 8 => { + let size = self.u64()?; + self.skip(size) + } + 9 => { + let element = self.u32()?; + let count = self.u64()?; + match element { + 8 => { + if count > 10_000_000 { + return Err("unreasonable GGUF string array count".into()); + } + for _ in 0..count { + let size = self.u64()?; + self.skip(size)?; + } + Ok(()) + } + 9 => Err("nested GGUF arrays are unsupported".into()), + _ => self.skip( + count + .checked_mul(value_width(element)?) + .ok_or("GGUF array size overflow")?, + ), + } + } + 10..=12 => self.skip(8), + _ => Err(format!("unknown GGUF metadata type {kind}").into()), + } + } +} diff --git a/crates/model-format/src/gguf/impl_verifiedgguffile.rs b/crates/model-format/src/gguf/impl_verifiedgguffile.rs new file mode 100644 index 00000000..633e2d24 --- /dev/null +++ b/crates/model-format/src/gguf/impl_verifiedgguffile.rs @@ -0,0 +1,243 @@ +//! Moved out of the parent module by STRA-338: impl VerifiedGgufFile. + +#[allow(unused_imports)] +use super::*; + + +impl VerifiedGgufFile { + /// Verify `sha256:<64 hex digits>` and strictly index the same opened file. + /// The opened file's contents must remain stable until this handle is dropped. + pub fn open(path: &Path, expected_digest: &str) -> Result { + let expected = parse_artifact_digest(expected_digest)?; + // Refuse an ordinary nonregular path before opening it (notably FIFOs). + // The opened-file check below is authoritative for the accepted source. + if !std::fs::metadata(path)?.is_file() { + return Err("GGUF source must be a regular file".into()); + } + let mut file = File::open(path)?; + let metadata = file.metadata()?; + if !metadata.is_file() { + return Err("GGUF source must be a regular file".into()); + } + let size = metadata.len(); + let identity = crate::verify_stamp::FileIdentity::of(&metadata); + let stamps = crate::verify_stamp::global(); + // A stamp skips the hash only for this very file in this very state, keyed by the pinned digest. + let trusted = matches!((stamps, identity.as_ref()), (Some(s), Some(id)) if s.trusts("gguf", &expected, id)); + let actual: [u8; 32] = if trusted { + expected + } else { + sha256_pipelined(&file, size)? + }; + if actual != expected { + return Err("GGUF artifact SHA256 mismatch".into()); + } + if file.metadata()?.len() != size { + return Err("GGUF source size changed during verification".into()); + } + if !trusted + && let (Some(stamps), Some(before)) = (stamps, identity) + && crate::verify_stamp::FileIdentity::of(&file.metadata()?) == Some(before) + { + // Only a file that did not change while it was hashed can vouch for itself next time. + let _ = stamps.record("gguf", &expected, &before); + } + let index = read_index_file(&mut file, size, true)?; + if file.metadata()?.len() != size { + return Err("GGUF source size changed during indexing".into()); + } + Ok(Self { + file, + index, + artifact_sha256: actual, + resident_source_id: None, + }) + } + + pub fn index(&self) -> &TensorIndex { + &self.index + } + + /// A duplicate of the retained descriptor (same open file, not a path + /// reopen) for positional reads. `pread` neither uses nor moves the shared + /// cursor. The indexed size is observed first, as for every stream. + pub fn duplicate_descriptor(&self) -> Result { + self.check_size()?; + Ok(self.file.try_clone()?) + } + + /// Digest verified when opening, not a promise of later source immutability. + pub fn artifact_sha256(&self) -> [u8; 32] { + self.artifact_sha256 + } + + /// Parse the bounded model/tokenizer metadata through the already verified + /// descriptor. The path is never reopened and the indexed file size is + /// checked on both sides of the snapshot. + #[cfg(test)] + pub(crate) fn metadata_snapshot(&mut self) -> Result { + self.check_size()?; + let snapshot = read_metadata_snapshot( + &mut self.file, + self.index.summary.file_size, + Some(QWEN4EXP_BINDING_KEYS), + true, + )?; + self.check_size()?; + Ok(snapshot) + } + + /// Parse only split metadata for the model binder's early admission phase. + /// Profile and tokenizer fields are skipped so their errors cannot precede + /// rejection of an invalid shard split. + pub(crate) fn split_snapshot(&mut self) -> Result { + self.check_size()?; + let snapshot = read_split_metadata_snapshot(&mut self.file, self.index.summary.file_size)?; + self.check_size()?; + Ok(snapshot) + } + + /// Parse only Qwen profile fields, deferring tokenizer work so the model + /// binder can preserve profile-before-tokenizer error precedence. + pub(crate) fn profile_snapshot(&mut self) -> Result { + self.check_size()?; + let snapshot = read_metadata_snapshot( + &mut self.file, + self.index.summary.file_size, + Some(QWEN4EXP_BINDING_KEYS), + false, + )?; + self.check_size()?; + Ok(snapshot) + } + + pub(crate) fn tokenizer_snapshot(&mut self) -> Result> { + self.check_size()?; + let snapshot = + read_metadata_snapshot(&mut self.file, self.index.summary.file_size, None, true)?; + self.check_size()?; + Ok(snapshot.tokenizer) + } + + /// Stream an exact byte range within an indexed tensor through a buffer of + /// at most 16 MiB. The consumer may return an I/O error to abort the stream. + /// No pathname is reopened; all range checks precede the first callback. + pub fn stream_tensor( + &mut self, + tensor_number: usize, + offset: u64, + bytes: u64, + consume: impl FnMut(&[u8]) -> std::io::Result<()>, + ) -> Result<()> { + let tensor = self + .index + .tensors + .get(tensor_number) + .ok_or("GGUF tensor index is out of bounds")?; + if tensor.bytes == 0 + || offset + .checked_add(bytes) + .is_none_or(|end| end > tensor.bytes) + { + return Err("GGUF tensor byte range is out of bounds".into()); + } + let absolute = self + .index + .summary + .data_start + .checked_add(tensor.offset) + .and_then(|start| start.checked_add(offset)) + .ok_or("GGUF tensor offset overflow")?; + if absolute + .checked_add(bytes) + .is_none_or(|end| end > self.index.summary.file_size) + { + return Err("GGUF tensor exceeds indexed file".into()); + } + self.check_size()?; + // Cached descriptor validation admits an empty span. Preserve both + // same-FD size checks without moving the retained reader's cursor. + if bytes != 0 { + stream_file_span(&mut self.file, absolute, bytes, consume)?; + } + self.check_size() + } + + /// Closed owned-span transport. The caller has fallibly allocated and + /// initialized this exact final owner; no stream scratch or append copy. + /// Same opened FD, indexed bounds and original pre/post size observations. + pub(crate) fn read_tensor_owned( + &mut self, + tensor_number: usize, + offset: u64, + mut bytes: Box<[u8]>, + ) -> Result> { + self.read_tensor_into(tensor_number, offset, &mut bytes)?; + Ok(bytes) + } + /// `read_tensor_owned` into caller-owned storage (the huge-page bank buffers of `huge_pages`): the same + /// FD, indexed bounds and pre/post size observations; every byte of `bytes` is written on success. + pub(crate) fn read_tensor_into( + &mut self, + tensor_number: usize, + offset: u64, + bytes: &mut [u8], + ) -> Result<()> { + let length = u64::try_from(bytes.len())?; + let tensor = self + .index + .tensors + .get(tensor_number) + .ok_or("GGUF tensor index is out of bounds")?; + if tensor.bytes == 0 + || offset + .checked_add(length) + .is_none_or(|end| end > tensor.bytes) + { + return Err("GGUF tensor byte range is out of bounds".into()); + } + let absolute = self + .index + .summary + .data_start + .checked_add(tensor.offset) + .and_then(|start| start.checked_add(offset)) + .ok_or("GGUF tensor offset overflow")?; + if absolute + .checked_add(length) + .is_none_or(|end| end > self.index.summary.file_size) + { + return Err("GGUF tensor exceeds indexed file".into()); + } + self.check_size()?; + // Original empty stream does not seek or invoke a consumer. + if length != 0 { + read_file_span_into(&mut self.file, absolute, bytes)?; + } + self.check_size()?; + Ok(()) + } + + /// Hash the complete indexed tensor without allocating its full payload. + pub fn tensor_sha256(&mut self, tensor_number: usize) -> Result<[u8; 32]> { + let bytes = self + .index + .tensors + .get(tensor_number) + .ok_or("GGUF tensor index is out of bounds")? + .bytes; + let mut digest = Sha256::new(); + self.stream_tensor(tensor_number, 0, bytes, |chunk| { + digest.update(chunk); + Ok(()) + })?; + Ok(digest.finalize().into()) + } + + pub(super) fn check_size(&self) -> Result<()> { + if self.file.metadata()?.len() != self.index.summary.file_size { + return Err("GGUF source size changed after verification".into()); + } + Ok(()) + } +} diff --git a/crates/model-format/src/gguf/parse_artifact_digest.rs b/crates/model-format/src/gguf/parse_artifact_digest.rs new file mode 100644 index 00000000..9105fa42 --- /dev/null +++ b/crates/model-format/src/gguf/parse_artifact_digest.rs @@ -0,0 +1,187 @@ +//! Moved out of the parent module by STRA-338: fn parse_artifact_digest, fn sha256_pipelined, fn stream_file_span, fn read_file_span_owned, fn read_file_span_into, fn check_flash_next_profile .... + +#[allow(unused_imports)] +use super::*; + + +pub(super) fn parse_artifact_digest(value: &str) -> Result<[u8; 32]> { + let hex = value + .strip_prefix("sha256:") + .ok_or("invalid GGUF artifact digest")?; + if hex.len() != 64 || !hex.bytes().all(|byte| byte.is_ascii_hexdigit()) { + return Err("invalid GGUF artifact digest".into()); + } + let mut digest = [0u8; 32]; + for (index, byte) in digest.iter_mut().enumerate() { + *byte = u8::from_str_radix(&hex[index * 2..index * 2 + 2], 16)?; + } + Ok(digest) +} + +/// SHA-256 of the first `size` bytes, hashing while a reader thread keeps the next chunks coming. +pub(super) fn sha256_pipelined(file: &File, size: u64) -> Result<[u8; 32]> { + crate::readahead::with_read_ahead(file, 0, size, 1, |mut receivers| -> Result<[u8; 32]> { + let receiver = receivers.remove(0); + let mut digest = Sha256::new(); + let mut total = 0u64; + for item in receiver { + let chunk = item?; + digest.update(&chunk[..]); + total += chunk.len() as u64; + } + if total != size { + return Err("GGUF source ended early during verification".into()); + } + Ok(digest.finalize().into()) + }) +} + +pub(super) fn stream_file_span( + file: &mut File, + absolute: u64, + bytes: u64, + mut consume: impl FnMut(&[u8]) -> std::io::Result<()>, +) -> Result<()> { + file.seek(SeekFrom::Start(absolute))?; + let length = bytes.min(stream_buffer_bytes() as u64) as usize; + let mut buffer = Vec::new(); + buffer.try_reserve_exact(length)?; + buffer.resize(length, 0); + let mut remaining = bytes; + while remaining > 0 { + let count = remaining.min(buffer.len() as u64) as usize; + file.read_exact(&mut buffer[..count])?; + consume(&buffer[..count])?; + remaining -= count as u64; + } + Ok(()) +} + +// The owner is already initialized and exclusively held. Reads preserve the +// original seek followed by <=16MiB read_exact request order, including tails. +#[cfg_attr(not(test), allow(dead_code))] +pub(super) fn read_file_span_owned(file: &mut File, absolute: u64, mut bytes: Box<[u8]>) -> Result> { + read_file_span_into(file, absolute, &mut bytes)?; + Ok(bytes) +} +pub(super) fn read_file_span_into(file: &mut File, absolute: u64, bytes: &mut [u8]) -> Result<()> { + // A large span (a routed-expert tensor of hundreds of MB) is read in big blocks on several threads, so the + // device sees a deep queue; the bytes and the failure modes are the same (`bulk_read`). Positional reads leave the + // cursor alone, and every caller seeks before it reads. `LELEKA_LOAD_READ=legacy` keeps the sequential loop below. + #[cfg(target_os = "linux")] + if bytes.len() as u64 >= crate::bulk_read::MIN_PARALLEL_BYTES + && std::env::var("LELEKA_LOAD_READ").as_deref() != Ok("legacy") + { + crate::bulk_read::read_into(file, absolute, bytes, crate::bulk_read::Plan::from_env())?; + return Ok(()); + } + file.seek(SeekFrom::Start(absolute))?; + for chunk in bytes.chunks_mut(STREAM_BUFFER_BYTES) { + file.read_exact(chunk)?; + } + Ok(()) +} + +/// Metadata admission for the specialised engine, before expensive preparation. +/// Mirrors artifact/gguf_reader.hpp::Qwen4ExpGuard; this does not inspect tensor values. +pub fn check_flash_next_profile(path: &Path) -> Result<()> { + let mut file = File::open(path)?; + let size = file.metadata()?.len(); + read_index_file(&mut file, size, false)?; + let snapshot = read_metadata_snapshot(&mut file, size, Some(FLASH_NEXT_PROFILE_KEYS), false)?; + validate_flash_next_profile(&snapshot) +} + +pub(super) fn validate_flash_next_profile(snapshot: &MetadataSnapshot) -> Result<()> { + if snapshot.architecture.as_deref() != Some("qwen4exp") { + return Err("runtime_profile requires general.architecture=qwen4exp".into()); + } + let required = [ + ("qwen4exp.block_count", Some(48)), + ("qwen4exp.embedding_length", Some(2560)), + ("qwen4exp.attention.head_count", Some(24)), + ("qwen4exp.attention.head_count_kv", Some(2)), + ("qwen4exp.expert_count", None), + ("qwen4exp.expert_used_count", None), + ]; + let mut values = BTreeMap::new(); + for (key, expected) in required { + let value = match snapshot.values.get(key) { + Some(MetadataValue::Unsigned(value)) => u32::try_from(*value).map_err(|_| { + format!("runtime_profile: {key} must be a nonnegative 32-bit integer") + })?, + Some(MetadataValue::Signed(value)) => u32::try_from(*value).map_err(|_| { + format!("runtime_profile: {key} must be a nonnegative 32-bit integer") + })?, + None => return Err(format!("runtime_profile: missing {key}").into()), + _ => return Err(format!("runtime_profile: {key} must be an integer").into()), + }; + values.insert(key, value); + if value == 0 || value > i32::MAX as u32 { + return Err(format!("runtime_profile: {key} must be in 1..2147483647").into()); + } + if let Some(expected) = expected + && value != expected + { + return Err(format!("runtime_profile: {key}={value}, expected {expected}").into()); + } + } + if values["qwen4exp.expert_used_count"] > values["qwen4exp.expert_count"] { + return Err( + "runtime_profile: qwen4exp.expert_used_count exceeds qwen4exp.expert_count".into(), + ); + } + Ok(()) +} + +/// Every metadata key/value of a GGUF file, in file order, bounded like the other readers (1M entries, 1 MiB +/// strings, 1M-element arrays, 512 MiB of array text). Duplicate keys and nested arrays are refused, and so is a +/// string that is not valid UTF-8 (`tools/gguf_reader.py` replaces bad bytes instead). Tensor payloads are never read. +pub fn metadata_entries(path: &Path) -> Result> { + let mut file = File::open(path)?; + let size = file.metadata()?.len(); + read_index_file(&mut file, size, false)?; + file.seek(SeekFrom::Start(0))?; + let mut cursor = Cursor::new(&mut file, size); + cursor.skip(16)?; // magic, version, tensor count + let count = cursor.u64()?; + if count > 1_000_000 { + return Err("unreasonable GGUF header count".into()); + } + let mut seen = HashSet::new(); + let mut entries = Vec::new(); + for _ in 0..count { + let key = cursor.string()?; + if !seen.insert(key.clone()) { + return Err(format!("duplicate GGUF metadata key: {key}").into()); + } + let kind = cursor.u32()?; + entries.push((key, cursor.metadata_value(kind)?)); + } + Ok(entries) +} + +/// Read only tokenizer fields after the complete GGUF header has passed inspection. +pub fn tokenizer_metadata(path: &Path) -> Result { + let mut file = File::open(path)?; + let size = file.metadata()?.len(); + read_index_file(&mut file, size, false)?; + validate_tokenizer_metadata( + read_metadata_snapshot(&mut file, size, None, true)? + .tokenizer + .ok_or("GGUF is missing required tokenizer metadata")?, + ) +} + +pub(super) fn read_metadata_snapshot( + file: &mut File, + size: u64, + qwen_keys: Option<&[&str]>, + parse_tokenizer: bool, +) -> Result { + read_metadata_snapshot_with_architecture(file, size, qwen_keys, parse_tokenizer, true) +} + +pub(super) fn read_split_metadata_snapshot(file: &mut File, size: u64) -> Result { + read_metadata_snapshot_with_architecture(file, size, None, false, false) +} diff --git a/crates/model-format/src/gguf/read_index_file.rs b/crates/model-format/src/gguf/read_index_file.rs new file mode 100644 index 00000000..b5b22b92 --- /dev/null +++ b/crates/model-format/src/gguf/read_index_file.rs @@ -0,0 +1,216 @@ +//! Moved out of the parent module by STRA-338: fn read_index_file, fn block_geometry. + +#[allow(unused_imports)] +use super::*; + + +pub(super) fn read_index_file(file: &mut File, size: u64, strict: bool) -> Result { + file.seek(SeekFrom::Start(0))?; + let mut cursor = Cursor::new(file, size); + if cursor.take(4)? != b"GGUF" { + return Err("not a GGUF file".into()); + } + if cursor.u32()? != 3 { + return Err("only GGUF v3 is supported".into()); + } + let tensors = cursor.u64()?; + let metadata = cursor.u64()?; + if tensors > 1_000_000 || metadata > 1_000_000 { + return Err("unreasonable GGUF header count".into()); + } + let mut architecture = None; + let mut split_no = None; + let mut split_count = None; + let mut split_tensors_count = None; + let mut alignment = 32u64; + let mut keys = HashSet::new(); + for _ in 0..metadata { + let key = cursor.string()?; + if !keys.insert(key.clone()) { + return Err(format!("duplicate GGUF metadata key: {key}").into()); + } + let kind = cursor.u32()?; + match (key.as_str(), kind) { + ("general.architecture", 8) => architecture = Some(cursor.string()?), + ("general.alignment", 4) => alignment = u64::from(cursor.u32()?), + ("general.alignment", _) => { + // tools/gguf_reader.py accepts any integer width; llama.cpp and the C++ engine read a uint32. + // Silently keeping the default would place the data section at the wrong byte. + return Err("general.alignment must be a uint32".into()); + } + ("split.no", 2) => split_no = Some(u64::from(cursor.u16()?)), + ("split.count", 2) => split_count = Some(u64::from(cursor.u16()?)), + ("split.tensors.count", 5) => { + let count = cursor.u32()?; + if count > i32::MAX as u32 { + return Err("negative GGUF split tensor count".into()); + } + split_tensors_count = Some(u64::from(count)); + } + ("split.no" | "split.count" | "split.tensors.count", _) => { + return Err("GGUF split metadata has an invalid integer type".into()); + } + _ => cursor.skip_value(kind)?, + } + } + if !alignment.is_power_of_two() || alignment > 4096 { + return Err("invalid GGUF alignment".into()); + } + let mut types = BTreeMap::new(); + let mut names = HashSet::new(); + let mut tensor_index = Vec::with_capacity(tensors as usize); + for _ in 0..tensors { + let name = cursor.string()?; + if !names.insert(name.clone()) { + return Err("duplicate GGUF tensor name".into()); + } + let dimensions = cursor.u32()?; + if !(1..=8).contains(&dimensions) { + return Err("invalid GGUF tensor dimensions".into()); + } + let mut shape = Vec::with_capacity(dimensions as usize); + for _ in 0..dimensions { + let dim = cursor.u64()?; + if dim == 0 { + return Err("zero GGUF tensor dimension".into()); + } + shape.push(dim); + } + let kind = cursor.u32()?; + let offset = cursor.u64()?; + *types.entry(kind).or_insert(0) += 1; + tensor_index.push(TensorInfo { + name, + dimensions: shape, + kind, + offset, + bytes: 0, + }); + } + let header_end = cursor.position()?; + let data_start = header_end + .checked_add(alignment - 1) + .ok_or("GGUF header offset overflow")? + / alignment + * alignment; + if data_start > size { + return Err("GGUF data section is truncated".into()); + } + for tensor in &tensor_index { + if tensor.offset % alignment != 0 + || data_start + .checked_add(tensor.offset) + .is_none_or(|start| start >= size) + { + return Err("GGUF tensor offset is out of bounds or unaligned".into()); + } + } + if strict { + let mut positions = (0..tensor_index.len()).collect::>(); + if positions.is_empty() { + return Err("GGUF has no tensors to index".into()); + } + positions.sort_unstable_by_key(|&index| tensor_index[index].offset); + if tensor_index[positions[0]].offset != 0 { + return Err("GGUF first tensor does not start at data offset zero".into()); + } + for (at, &index) in positions.iter().enumerate() { + let tensor = &tensor_index[index]; + let (block_elements, block_bytes) = block_geometry(tensor.kind) + .ok_or_else(|| format!("unsupported GGUF tensor type {}", tensor.kind))?; + let elements = tensor + .dimensions + .iter() + .try_fold(1u64, |product, dim| product.checked_mul(*dim)) + .ok_or("GGUF tensor element count overflow")?; + if tensor.dimensions[0] % block_elements != 0 { + return Err(format!("{}: tensor row is not block aligned", tensor.name).into()); + } + let bytes = elements + .checked_div(block_elements) + .and_then(|blocks| blocks.checked_mul(block_bytes)) + .ok_or("GGUF tensor byte count overflow")?; + let end = tensor + .offset + .checked_add(bytes) + .ok_or("GGUF tensor end overflow")?; + let next = positions + .get(at + 1) + .map(|&next| tensor_index[next].offset) + .unwrap_or(size - data_start); + if end > next || next - end >= alignment { + return Err(format!( + "{}: tensor bytes overlap or have an invalid gap", + tensor.name + ) + .into()); + } + tensor_index[index].bytes = bytes; + } + } + if let (Some(no), Some(count)) = (split_no, split_count) + && (count == 0 || no >= count) + { + return Err("invalid GGUF split metadata".into()); + } + let summary = Summary { + tensors, + metadata, + architecture, + split_no, + split_count, + split_tensors_count, + data_start, + file_size: size, + types, + }; + Ok(TensorIndex { + summary, + tensors: tensor_index, + }) +} + +pub fn block_geometry(kind: u32) -> Option<(u64, u64)> { + // Mirrors engine/strata/include/strata/artifact/gguf_reader.hpp at the + // upstream commit recorded in docs/upstream.md, plus the kinds + // engine/strata/tools/gguf_reader.py BLOCK_GEOMETRY knows beyond it (Q8_K 15, + // IQ1_S 19, F64 28, MXFP4 39, NVFP4 40). Geometry is only a byte count: a + // consumer that cannot decode a kind still refuses it at use. Differential: + // control-plane/tests/gguf_header_differential.rs. + Some(match kind { + 0 => (1, 4), + 1 | 30 => (1, 2), + 2 => (32, 18), + 3 => (32, 20), + 6 => (32, 22), + 7 => (32, 24), + 8 => (32, 34), + 9 => (32, 36), + 10 => (256, 84), + 11 | 21 => (256, 110), + 12 => (256, 144), + 13 => (256, 176), + 14 => (256, 210), + 15 => (256, 292), + 16 => (256, 66), + 17 => (256, 74), + 18 => (256, 98), + 19 => (256, 50), + 20 => (32, 18), + 22 => (256, 82), + 23 => (256, 136), + 24 => (1, 1), + 28 => (1, 8), + 29 => (256, 56), + 39 => (32, 17), + 40 => (64, 36), + 42 => (64, 18), + // APR trellis types (gguf_reader.hpp 143 to 146, gguf_reader.py BLOCK_GEOMETRY): 128 values per block, + // PTQ1_0 28 bytes, TQ2_T 34, TQK6 26, TQK7 30 + 143 => (128, 28), + 144 => (128, 34), + 145 => (128, 26), + 146 => (128, 30), + _ => return None, + }) +} diff --git a/crates/model-format/src/gguf/read_metadata_snapshot_with_architecture.rs b/crates/model-format/src/gguf/read_metadata_snapshot_with_architecture.rs new file mode 100644 index 00000000..58b65b9e --- /dev/null +++ b/crates/model-format/src/gguf/read_metadata_snapshot_with_architecture.rs @@ -0,0 +1,209 @@ +//! Moved out of the parent module by STRA-338: fn read_metadata_snapshot_with_architecture, fn validate_tokenizer_metadata, fn inspect, fn tensor_index, fn tensor_sha256, fn read_index. + +#[allow(unused_imports)] +use super::*; + + +pub(super) fn read_metadata_snapshot_with_architecture( + file: &mut File, + size: u64, + qwen_keys: Option<&[&str]>, + parse_tokenizer: bool, + parse_architecture: bool, +) -> Result { + file.seek(SeekFrom::Start(0))?; + let mut cursor = Cursor::new(file, size); + cursor.skip(16)?; // magic, version, tensor count + let count = cursor.u64()?; + if count > 1_000_000 { + return Err("unreasonable GGUF header count".into()); + } + let mut architecture = None; + let mut split_no = None; + let mut split_count = None; + let mut split_tensors_count = None; + let mut model = None; + let mut pre = None; + let mut tokens = None; + let mut merges = None; + let mut token_types = None; + let mut special_ids = BTreeMap::new(); + let mut chat_template = None; + let mut values = BTreeMap::new(); + let mut seen = HashSet::new(); + for _ in 0..count { + let key = cursor.string()?; + if !seen.insert(key.clone()) { + return Err(format!("duplicate GGUF metadata key: {key}").into()); + } + let kind = cursor.u32()?; + match key.as_str() { + "general.architecture" if parse_architecture && kind == 8 => { + architecture = Some(cursor.string()?) + } + "split.no" if kind == 2 => split_no = Some(u64::from(cursor.u16()?)), + "split.count" if kind == 2 => split_count = Some(u64::from(cursor.u16()?)), + "split.tensors.count" if kind == 5 => { + split_tensors_count = Some(u64::from(cursor.u32()?)) + } + "split.no" | "split.count" | "split.tensors.count" => { + return Err("GGUF split metadata has an invalid integer type".into()); + } + "tokenizer.ggml.model" if parse_tokenizer && kind == 8 => { + model = Some(cursor.string()?) + } + "tokenizer.ggml.pre" if parse_tokenizer && kind == 8 => pre = Some(cursor.string()?), + "tokenizer.ggml.tokens" if parse_tokenizer => tokens = Some(cursor.string_array(kind)?), + "tokenizer.ggml.merges" if parse_tokenizer => merges = Some(cursor.string_array(kind)?), + "tokenizer.ggml.token_type" if parse_tokenizer => { + token_types = Some(cursor.integer_array(kind)?) + } + "tokenizer.chat_template" if parse_tokenizer && kind == 8 => { + chat_template = Some(cursor.string()?) + } + _ if parse_tokenizer + && key.starts_with("tokenizer.ggml.") + && key.ends_with("_token_id") => + { + special_ids.insert(key, cursor.integer(kind)?); + } + _ if qwen_keys.is_some_and(|keys| keys.contains(&key.as_str())) => { + values.insert(key, cursor.metadata_value(kind)?); + } + _ => cursor.skip_value(kind)?, + } + } + let tokenizer = match (model, tokens, merges, chat_template) { + (Some(model), Some(tokens), Some(merges), Some(chat_template)) => Some(TokenizerMetadata { + model, + pre: pre.unwrap_or_else(|| "qwen35".to_owned()), + tokens, + merges, + token_types, + special_ids, + chat_template, + }), + _ => None, + }; + Ok(MetadataSnapshot { + architecture, + split_no, + split_count, + split_tensors_count, + values, + tokenizer, + }) +} + +pub(crate) fn validate_tokenizer_metadata( + tokenizer: TokenizerMetadata, +) -> Result { + let TokenizerMetadata { + model, + pre, + tokens, + merges, + token_types, + special_ids, + chat_template, + } = tokenizer; + if model != "gpt2" || pre != "qwen35" { + return Err("only the qwen35 byte-level BPE tokenizer is supported".into()); + } + if tokens.is_empty() || chat_template.is_empty() { + return Err("GGUF tokenizer has an empty vocabulary or chat template".into()); + } + if token_types + .as_ref() + .is_some_and(|types| types.len() != tokens.len()) + { + return Err("token_type length differs from vocabulary length".into()); + } + let vocab: HashSet<&str> = tokens.iter().map(String::as_str).collect(); + if vocab.len() != tokens.len() { + return Err("GGUF tokenizer has duplicate vocabulary entries".into()); + } + let mut seen_merges = HashSet::new(); + for merge in &merges { + let Some((left, right)) = merge.split_once(' ') else { + return Err("GGUF BPE merge is not a pair".into()); + }; + if left.is_empty() + || right.is_empty() + || right.contains(' ') + || !vocab.contains(left) + || !vocab.contains(right) + || !seen_merges.insert(merge) + { + return Err("GGUF BPE merge is invalid or duplicated".into()); + } + } + for &id in special_ids.values() { + if id as usize >= tokens.len() { + return Err("special token ID exceeds vocabulary".into()); + } + } + Ok(TokenizerMetadata { + model, + pre, + tokens, + merges, + token_types, + special_ids, + chat_template, + }) +} + +pub fn inspect(path: &Path) -> Result { + Ok(read_index(path, false)?.summary) +} + +/// Locate each supported tensor payload without reading the tensor into RAM. +/// Types and byte lengths follow the pinned Strata GGUF reader geometry. +pub fn tensor_index(path: &Path) -> Result { + read_index(path, true) +} + +/// Hash one indexed tensor with a fixed-size buffer. The caller must keep the +/// verified source file stable between indexing and reading. +pub fn tensor_sha256(path: &Path, index: &TensorIndex, tensor_number: usize) -> Result<[u8; 32]> { + let tensor = index + .tensors + .get(tensor_number) + .ok_or("GGUF tensor index is out of bounds")?; + if tensor.bytes == 0 { + return Err("GGUF tensor index lacks verified byte geometry".into()); + } + let absolute = index + .summary + .data_start + .checked_add(tensor.offset) + .ok_or("GGUF tensor offset overflow")?; + if absolute + .checked_add(tensor.bytes) + .is_none_or(|end| end > index.summary.file_size) + { + return Err("GGUF tensor exceeds indexed file".into()); + } + let mut file = File::open(path)?; + if file.metadata()?.len() != index.summary.file_size { + return Err("GGUF source size changed after indexing".into()); + } + file.seek(SeekFrom::Start(absolute))?; + let mut digest = Sha256::new(); + let mut buffer = vec![0u8; 1024 * 1024]; + let mut remaining = tensor.bytes; + while remaining > 0 { + let count = remaining.min(buffer.len() as u64) as usize; + file.read_exact(&mut buffer[..count])?; + digest.update(&buffer[..count]); + remaining -= count as u64; + } + Ok(digest.finalize().into()) +} + +pub(super) fn read_index(path: &Path, strict: bool) -> Result { + let mut file = File::open(path)?; + let size = file.metadata()?.len(); + read_index_file(&mut file, size, strict) +} diff --git a/crates/model-format/src/gguf/stream_buffer_bytes.rs b/crates/model-format/src/gguf/stream_buffer_bytes.rs new file mode 100644 index 00000000..99bb6530 --- /dev/null +++ b/crates/model-format/src/gguf/stream_buffer_bytes.rs @@ -0,0 +1,33 @@ +//! Moved out of the parent module by STRA-338: fn stream_buffer_bytes, fn stream_buffer_bytes, fn with_test_stream_buffer. + +#[allow(unused_imports)] +use super::*; + + +// Production always uses `STREAM_BUFFER_BYTES`. Tests may shrink the span +// stream buffer on their own thread to exercise multi-chunk behaviour with +// small fixtures (see `with_test_stream_buffer`). +#[cfg(test)] +pub(super) fn stream_buffer_bytes() -> usize { + STREAM_BUFFER_TEST_OVERRIDE.with(|cell| cell.get().unwrap_or(STREAM_BUFFER_BYTES)) +} + +#[cfg(not(test))] +pub(super) const fn stream_buffer_bytes() -> usize { + STREAM_BUFFER_BYTES +} + +/// Test seam: run `body` with `stream_tensor` buffering spans in `bytes`-sized +/// chunks (1..=16 MiB) on this thread only; restored even on panic. +#[cfg(test)] +pub(crate) fn with_test_stream_buffer(bytes: usize, body: impl FnOnce() -> T) -> T { + assert!(bytes > 0 && bytes <= STREAM_BUFFER_BYTES); + struct Restore(Option); + impl Drop for Restore { + fn drop(&mut self) { + STREAM_BUFFER_TEST_OVERRIDE.with(|cell| cell.set(self.0)); + } + } + let _restore = Restore(STREAM_BUFFER_TEST_OVERRIDE.with(|cell| cell.replace(Some(bytes)))); + body() +} diff --git a/crates/model-format/src/gguf/value_width.rs b/crates/model-format/src/gguf/value_width.rs new file mode 100644 index 00000000..e52c7c17 --- /dev/null +++ b/crates/model-format/src/gguf/value_width.rs @@ -0,0 +1,85 @@ +//! Moved out of the parent module by STRA-338: fn value_width, impl GgufSourceFence, impl VerifiedGgufFile. + +#[allow(unused_imports)] +use super::*; + + +pub(super) fn value_width(kind: u32) -> Result { + match kind { + 0 | 1 | 7 => Ok(1), + 2 | 3 => Ok(2), + 4..=6 => Ok(4), + 10..=12 => Ok(8), + _ => Err(format!("invalid GGUF array element type {kind}").into()), + } +} +impl GgufSourceFence<'_> { + pub(crate) fn validate_tensor(&self, tensor_number: usize) -> Result<()> { + self.source.validate_empty_tensor_span(tensor_number) + } + pub(crate) fn stream_tensor( + &mut self, + tensor_number: usize, + offset: u64, + bytes: u64, + consume: impl FnMut(&[u8]) -> std::io::Result<()>, + ) -> Result<()> { + // Real misses preserve the original full range and before/after source + // checks, cursor behavior, read errors and bounded stream buffer. + self.source + .stream_tensor(tensor_number, offset, bytes, consume) + } + pub(crate) fn read_tensor_owned( + &mut self, + tensor_number: usize, + offset: u64, + bytes: Box<[u8]>, + ) -> Result> { + self.source.read_tensor_owned(tensor_number, offset, bytes) + } + pub(crate) fn finish(self) -> Result<()> { + self.source.check_size() + } +} +impl VerifiedGgufFile { + /// Recheck the same descriptor admission performed by an empty stream + /// without borrowing the retained reader mutably. This preserves the + /// geometry and both same-FD size observations while leaving its cursor + /// untouched for an immutable source lease. + pub(crate) fn validate_empty_tensor_source(&self, tensor_number: usize) -> Result<()> { + self.validate_empty_tensor_span(tensor_number)?; + self.check_size()?; + self.check_size() + } + + pub(super) fn validate_empty_tensor_span(&self, tensor_number: usize) -> Result<()> { + let tensor = self + .index + .tensors + .get(tensor_number) + .ok_or("GGUF tensor index is out of bounds")?; + if tensor.bytes == 0 { + return Err("GGUF tensor byte range is out of bounds".into()); + } + let absolute = self + .index + .summary + .data_start + .checked_add(tensor.offset) + .ok_or("GGUF tensor offset overflow")?; + if absolute > self.index.summary.file_size { + return Err("GGUF tensor exceeds indexed file".into()); + } + Ok(()) + } + pub(crate) fn begin_source_fence( + &mut self, + tensor_number: usize, + ) -> Result> { + // Exactly the original first empty-span geometry precedes the first + // size observation. No seek, read, allocation or cursor mutation. + self.validate_empty_tensor_span(tensor_number)?; + self.check_size()?; + Ok(GgufSourceFence { source: self }) + } +} diff --git a/crates/model-format/src/gguf_resident.rs b/crates/model-format/src/gguf_resident.rs index 3831fb67..f9a7e254 100644 --- a/crates/model-format/src/gguf_resident.rs +++ b/crates/model-format/src/gguf_resident.rs @@ -12,18 +12,6 @@ pub(crate) enum ResidentLoadError { Budget, Source(Box), } -fn next_source_id() -> Result { - let mut current = NEXT_SOURCE_ID.load(Ordering::Relaxed); - loop { - let next = current - .checked_add(1) - .ok_or("resident source identity exhausted")?; - match NEXT_SOURCE_ID.compare_exchange(current, next, Ordering::Relaxed, Ordering::Relaxed) { - Ok(_) => return Ok(current), - Err(actual) => current = actual, - } - } -} pub(crate) struct ResidentTensor { source: u64, @@ -31,19 +19,6 @@ pub(crate) struct ResidentTensor { bytes: ResidentStorage, charged_bytes: usize, } -impl ResidentTensor { - pub(crate) fn charged_bytes(&self) -> usize { - self.charged_bytes - } - pub(crate) fn len(&self) -> usize { - self.bytes.len() - } - /// True when the bytes are the verified file's own pages (the Original's `--mmap-experts` GGUF-in-place - /// source), false for an owned RAM copy. - pub(crate) fn file_mapped(&self) -> bool { - matches!(self.bytes, ResidentStorage::Mapped(_)) - } -} /// Where a retained tensor's bytes live: an owned copy in RAM (the resident source), or a read-only shared /// mapping of the verified GGUF file itself (the low-RAM source: the OS file cache holds what is used and @@ -55,25 +30,6 @@ enum ResidentStorage { #[cfg(target_os = "linux")] Huge(crate::huge_pages::HugeBuffer), } -impl ResidentStorage { - fn as_slice(&self) -> &[u8] { - match self { - Self::Owned(bytes) => bytes, - Self::Mapped(span) => span.as_slice(), - #[cfg(target_os = "linux")] - Self::Huge(buffer) => buffer.as_slice(), - } - } - fn len(&self) -> usize { - self.as_slice().len() - } -} -impl std::ops::Deref for ResidentStorage { - type Target = [u8]; - fn deref(&self) -> &[u8] { - self.as_slice() - } -} /// A `PROT_READ`/`MAP_SHARED` mapping of one tensor's exact byte range of a verified file (rounded out to /// pages for the kernel, never exposed beyond the tensor). Unmapped on drop. @@ -83,350 +39,11 @@ pub(crate) struct FileSpan { start: usize, len: usize, } -impl FileSpan { - #[allow(unsafe_code)] - fn as_slice(&self) -> &[u8] { - // SAFETY: `base..base+map_len` is a live read-only mapping owned by `self`; `start + len <= map_len` - // was checked at construction. The source file's stability is the `VerifiedGgufFile` contract (its - // contents must not change while the handle and anything retained from it are alive). - unsafe { std::slice::from_raw_parts(self.base.cast::().add(self.start), self.len) } - } -} -impl Drop for FileSpan { - #[allow(unsafe_code)] - fn drop(&mut self) { - #[cfg(target_os = "linux")] - // SAFETY: exact base/length returned by mmap; no borrow of the slice outlives `self`. - unsafe { - let _ = rustix::mm::munmap(self.base, self.map_len); - } - #[cfg(windows)] - // SAFETY: exact view base returned by `map_file_readonly`; no borrow of the slice outlives `self`. - unsafe { - let _ = leleka_libc_shim::unmap_file(self.base); - } - } -} - -impl VerifiedGgufFile { - /// Constructor is source-owned: arbitrary caller bytes cannot become a bank. - pub(crate) fn load_resident_tensor( - &mut self, - tensor_number: usize, - capacity_ceiling: usize, - ) -> std::result::Result { - let tensor = self.index.tensors.get(tensor_number).ok_or_else(|| { - ResidentLoadError::Source("GGUF tensor index is out of bounds".into()) - })?; - let length = - usize::try_from(tensor.bytes).map_err(|e| ResidentLoadError::Source(e.into()))?; - if length == 0 { - return Err(ResidentLoadError::Source("resident tensor is empty".into())); - } - if length > capacity_ceiling { - return Err(ResidentLoadError::Budget); - } - // Existing descriptor/source-size admission precedes allocation. - self.stream_tensor(tensor_number, 0, 0, |_| Ok(())) - .map_err(ResidentLoadError::Source)?; - #[cfg(target_os = "linux")] - if crate::huge_pages::mode() != crate::huge_pages::Mode::Off { - // The same bytes in a huge-page mapping instead of the heap; refusals map as for the heap copy. - let mut buffer = crate::huge_pages::HugeBuffer::allocate(length).map_err(|_| ResidentLoadError::Allocation)?; - let charged_bytes = buffer.charged_len(); - if charged_bytes > capacity_ceiling { - return Err(ResidentLoadError::Budget); - } - self.read_tensor_into(tensor_number, 0, buffer.as_mut_slice()) - .map_err(ResidentLoadError::Source)?; - let source = match self.resident_source_id { - Some(source) => source, - None => { - let source = next_source_id().map_err(ResidentLoadError::Source)?; - self.resident_source_id = Some(source); - source - } - }; - return Ok(ResidentTensor { - source, - tensor_number, - bytes: ResidentStorage::Huge(buffer), - charged_bytes, - }); - } - let mut bytes = Vec::new(); - bytes - .try_reserve_exact(length) - .map_err(|_| ResidentLoadError::Allocation)?; - let charged_bytes = bytes.capacity(); - if charged_bytes > capacity_ceiling { - return Err(ResidentLoadError::Budget); - } - bytes.resize(length, 0); - let bytes = self - .read_tensor_owned(tensor_number, 0, bytes.into_boxed_slice()) - .map_err(ResidentLoadError::Source)?; - // The immutable real source owns this identity; no default allocation. - let source = match self.resident_source_id { - Some(source) => source, - None => { - let source = next_source_id().map_err(ResidentLoadError::Source)?; - self.resident_source_id = Some(source); - source - } - }; - Ok(ResidentTensor { - source, - tensor_number, - bytes: ResidentStorage::Owned(bytes), - charged_bytes, - }) - } - /// The Original's `--mmap-experts` with the GGUF in place (`FileExpertSource::set_gguf`): the tensor's - /// bytes are a read-only shared mapping of this verified file instead of a copy, so no RAM is committed - /// for them; the OS file cache keeps what is read. Same descriptor, same indexed bounds and size checks - /// as `load_resident_tensor`. `charged_bytes` is the mapped length (address space, not RAM). - #[cfg(any(target_os = "linux", windows))] - #[allow(unsafe_code)] - pub(crate) fn map_resident_tensor( - &mut self, - tensor_number: usize, - ) -> std::result::Result { - let (tensor_offset, tensor_bytes) = { - let tensor = self.index.tensors.get(tensor_number).ok_or_else(|| { - ResidentLoadError::Source("GGUF tensor index is out of bounds".into()) - })?; - (tensor.offset, tensor.bytes) - }; - let length = - usize::try_from(tensor_bytes).map_err(|e| ResidentLoadError::Source(e.into()))?; - if length == 0 { - return Err(ResidentLoadError::Source("resident tensor is empty".into())); - } - self.stream_tensor(tensor_number, 0, 0, |_| Ok(())) - .map_err(ResidentLoadError::Source)?; - let absolute = self - .index - .summary - .data_start - .checked_add(tensor_offset) - .ok_or_else(|| ResidentLoadError::Source("GGUF tensor offset overflow".into()))?; - if absolute - .checked_add(tensor_bytes) - .is_none_or(|end| end > self.index.summary.file_size) - { - return Err(ResidentLoadError::Source("GGUF tensor exceeds indexed file".into())); - } - #[cfg(target_os = "linux")] - let page = rustix::param::page_size() as u64; - #[cfg(windows)] - let page = leleka_libc_shim::allocation_granularity(); - let map_offset = absolute & !(page - 1); - let start = usize::try_from(absolute - map_offset) - .map_err(|e| ResidentLoadError::Source(e.into()))?; - let map_len = start - .checked_add(length) - .ok_or_else(|| ResidentLoadError::Source("mapping length overflow".into()))?; - self.check_size().map_err(ResidentLoadError::Source)?; - // SAFETY: a fresh read-only shared mapping of the retained verified descriptor at a page-aligned - // offset inside the indexed file; the kernel picks the address. No existing memory is replaced. - #[cfg(target_os = "linux")] - let base = unsafe { - rustix::mm::mmap( - std::ptr::null_mut(), - map_len, - rustix::mm::ProtFlags::READ, - rustix::mm::MapFlags::SHARED, - &self.file, - map_offset, - ) - } - .map_err(|e| ResidentLoadError::Source(Box::new(std::io::Error::from(e))))?; - // Windows: CreateFileMapping + MapViewOfFile(FILE_MAP_READ) of the retained verified handle; the view offset is - // a multiple of the 64 KiB allocation granularity (`page` above), the same layout as the Linux mapping. - #[cfg(windows)] - let base = { - use std::os::windows::io::AsRawHandle; - // SAFETY: a fresh read-only view of the retained verified handle at a granularity-aligned offset inside the indexed file. - let view = unsafe { leleka_libc_shim::map_file_readonly(self.file.as_raw_handle().cast(), map_offset, map_len) }; - if view.is_null() { - return Err(ResidentLoadError::Source(Box::new(std::io::Error::last_os_error()))); - } - view - }; - let span = FileSpan { base, map_len, start, len: length }; - self.check_size().map_err(ResidentLoadError::Source)?; - let source = match self.resident_source_id { - Some(source) => source, - None => { - let source = next_source_id().map_err(ResidentLoadError::Source)?; - self.resident_source_id = Some(source); - source - } - }; - Ok(ResidentTensor { - source, - tensor_number, - bytes: ResidentStorage::Mapped(span), - charged_bytes: length, - }) - } - /// Copies a real source-owned bank span, with unchanged indexed bounds and - /// same-FD pre/post size checks. A hit intentionally does not seek/read FD. - pub(crate) fn copy_resident_tensor( - &self, - resident: &ResidentTensor, - offset: u64, - mut output: Box<[u8]>, - ) -> Result> { - if self.resident_source_id != Some(resident.source) { - return Err("resident tensor source identity mismatch".into()); - } - let tensor = self - .index - .tensors - .get(resident.tensor_number) - .ok_or("GGUF tensor index is out of bounds")?; - let length = u64::try_from(output.len())?; - if tensor.bytes == 0 - || resident.bytes.len() as u64 != tensor.bytes - || offset - .checked_add(length) - .is_none_or(|end| end > tensor.bytes) - { - return Err("GGUF tensor byte range is out of bounds".into()); - } - let absolute = self - .index - .summary - .data_start - .checked_add(tensor.offset) - .and_then(|start| start.checked_add(offset)) - .ok_or("GGUF tensor offset overflow")?; - if absolute - .checked_add(length) - .is_none_or(|end| end > self.index.summary.file_size) - { - return Err("GGUF tensor exceeds indexed file".into()); - } - let first = usize::try_from(offset)?; - let end = first - .checked_add(output.len()) - .ok_or("resident tensor offset overflow")?; - let selected = resident - .bytes - .as_slice() - .get(first..end) - .ok_or("resident tensor extent")?; - self.check_size()?; - output.copy_from_slice(selected); - self.check_size()?; - Ok(output) - } -} -impl GgufSourceFence<'_> { - pub(crate) fn copy_resident_tensor( - &self, - tensor: &ResidentTensor, - offset: u64, - output: Box<[u8]>, - ) -> Result> { - self.source.copy_resident_tensor(tensor, offset, output) - } -} #[cfg(test)] #[path = "gguf_resident_sdet.rs"] mod sdet; -impl VerifiedGgufFile { - pub(crate) fn capture_source_identity(&mut self) -> Result { - self.check_size()?; - if let Some(source) = self.resident_source_id { - return Ok(source); - } - let source = next_source_id()?; - self.resident_source_id = Some(source); - Ok(source) - } - pub(crate) fn admit_captured_tensor( - &mut self, - source: u64, - tensor_number: usize, - bytes: Box<[u8]>, - charged_bytes: usize, - ) -> Result { - if self.resident_source_id != Some(source) - || self - .index - .tensors - .get(tensor_number) - .is_none_or(|tensor| tensor.bytes != bytes.len() as u64 || tensor.bytes == 0) - || charged_bytes < bytes.len() - { - return Err("GGUF resident source identity mismatch".into()); - } - self.stream_tensor(tensor_number, 0, 0, |_| Ok(()))?; - Ok(ResidentTensor { - source, - tensor_number, - bytes: ResidentStorage::Owned(bytes), - charged_bytes, - }) - } -} - -impl VerifiedGgufFile { - pub(crate) fn validate_capture_identity(&self, source: u64) -> Result<()> { - if self.resident_source_id != Some(source) { - return Err("GGUF resident source identity mismatch".into()); - } - self.check_size() - } -} - -// Retains the initialized Box itself; Rc payload is only the small owner. -impl ResidentTensor { - pub(crate) fn into_retained(self) -> std::rc::Rc { - std::rc::Rc::new(self) - } - pub(crate) fn retained_bytes(&self) -> &[u8] { - self.bytes.as_slice() - } - pub(crate) const fn retention_metadata_bytes() -> usize { - std::mem::size_of::() + 2 * std::mem::size_of::() - } -} -impl VerifiedGgufFile { - pub(crate) fn validate_retained_tensor(&self, resident: &ResidentTensor) -> Result<()> { - if self.resident_source_id != Some(resident.source) { - return Err("resident tensor source identity mismatch".into()); - } - let tensor = self - .index - .tensors - .get(resident.tensor_number) - .ok_or("GGUF tensor index is out of bounds")?; - if tensor.bytes == 0 - || resident.bytes.len() as u64 != tensor.bytes - || resident.charged_bytes < resident.bytes.len() - { - return Err("resident tensor extent".into()); - } - let end = self - .index - .summary - .data_start - .checked_add(tensor.offset) - .and_then(|start| start.checked_add(tensor.bytes)) - .ok_or("GGUF tensor offset overflow")?; - if end > self.index.summary.file_size { - return Err("GGUF tensor exceeds indexed file".into()); - } - self.check_size() - } -} - #[cfg(test)] mod retained_lease_test { use super::*; @@ -611,3 +228,16 @@ mod retained_lease_test { std::fs::remove_file(path).unwrap(); } } + +#[path = "gguf_resident/next_source_id.rs"] +mod next_source_id; +#[allow(unused_imports)] +pub use next_source_id::*; +#[path = "gguf_resident/impl_verifiedgguffile.rs"] +mod impl_verifiedgguffile; +#[allow(unused_imports)] +pub use impl_verifiedgguffile::*; +#[path = "gguf_resident/impl_verifiedgguffile_2.rs"] +mod impl_verifiedgguffile_2; +#[allow(unused_imports)] +pub use impl_verifiedgguffile_2::*; diff --git a/crates/model-format/src/gguf_resident/impl_verifiedgguffile.rs b/crates/model-format/src/gguf_resident/impl_verifiedgguffile.rs new file mode 100644 index 00000000..9f4e2504 --- /dev/null +++ b/crates/model-format/src/gguf_resident/impl_verifiedgguffile.rs @@ -0,0 +1,232 @@ +//! Moved out of the parent module by STRA-338: impl VerifiedGgufFile, impl GgufSourceFence. + +#[allow(unused_imports)] +use super::*; + + +impl VerifiedGgufFile { + /// Constructor is source-owned: arbitrary caller bytes cannot become a bank. + pub(crate) fn load_resident_tensor( + &mut self, + tensor_number: usize, + capacity_ceiling: usize, + ) -> std::result::Result { + let tensor = self.index.tensors.get(tensor_number).ok_or_else(|| { + ResidentLoadError::Source("GGUF tensor index is out of bounds".into()) + })?; + let length = + usize::try_from(tensor.bytes).map_err(|e| ResidentLoadError::Source(e.into()))?; + if length == 0 { + return Err(ResidentLoadError::Source("resident tensor is empty".into())); + } + if length > capacity_ceiling { + return Err(ResidentLoadError::Budget); + } + // Existing descriptor/source-size admission precedes allocation. + self.stream_tensor(tensor_number, 0, 0, |_| Ok(())) + .map_err(ResidentLoadError::Source)?; + #[cfg(target_os = "linux")] + if crate::huge_pages::mode() != crate::huge_pages::Mode::Off { + // The same bytes in a huge-page mapping instead of the heap; refusals map as for the heap copy. + let mut buffer = crate::huge_pages::HugeBuffer::allocate(length).map_err(|_| ResidentLoadError::Allocation)?; + let charged_bytes = buffer.charged_len(); + if charged_bytes > capacity_ceiling { + return Err(ResidentLoadError::Budget); + } + self.read_tensor_into(tensor_number, 0, buffer.as_mut_slice()) + .map_err(ResidentLoadError::Source)?; + let source = match self.resident_source_id { + Some(source) => source, + None => { + let source = next_source_id().map_err(ResidentLoadError::Source)?; + self.resident_source_id = Some(source); + source + } + }; + return Ok(ResidentTensor { + source, + tensor_number, + bytes: ResidentStorage::Huge(buffer), + charged_bytes, + }); + } + let mut bytes = Vec::new(); + bytes + .try_reserve_exact(length) + .map_err(|_| ResidentLoadError::Allocation)?; + let charged_bytes = bytes.capacity(); + if charged_bytes > capacity_ceiling { + return Err(ResidentLoadError::Budget); + } + bytes.resize(length, 0); + let bytes = self + .read_tensor_owned(tensor_number, 0, bytes.into_boxed_slice()) + .map_err(ResidentLoadError::Source)?; + // The immutable real source owns this identity; no default allocation. + let source = match self.resident_source_id { + Some(source) => source, + None => { + let source = next_source_id().map_err(ResidentLoadError::Source)?; + self.resident_source_id = Some(source); + source + } + }; + Ok(ResidentTensor { + source, + tensor_number, + bytes: ResidentStorage::Owned(bytes), + charged_bytes, + }) + } + /// The Original's `--mmap-experts` with the GGUF in place (`FileExpertSource::set_gguf`): the tensor's + /// bytes are a read-only shared mapping of this verified file instead of a copy, so no RAM is committed + /// for them; the OS file cache keeps what is read. Same descriptor, same indexed bounds and size checks + /// as `load_resident_tensor`. `charged_bytes` is the mapped length (address space, not RAM). + #[cfg(any(target_os = "linux", windows))] + #[allow(unsafe_code)] + pub(crate) fn map_resident_tensor( + &mut self, + tensor_number: usize, + ) -> std::result::Result { + let (tensor_offset, tensor_bytes) = { + let tensor = self.index.tensors.get(tensor_number).ok_or_else(|| { + ResidentLoadError::Source("GGUF tensor index is out of bounds".into()) + })?; + (tensor.offset, tensor.bytes) + }; + let length = + usize::try_from(tensor_bytes).map_err(|e| ResidentLoadError::Source(e.into()))?; + if length == 0 { + return Err(ResidentLoadError::Source("resident tensor is empty".into())); + } + self.stream_tensor(tensor_number, 0, 0, |_| Ok(())) + .map_err(ResidentLoadError::Source)?; + let absolute = self + .index + .summary + .data_start + .checked_add(tensor_offset) + .ok_or_else(|| ResidentLoadError::Source("GGUF tensor offset overflow".into()))?; + if absolute + .checked_add(tensor_bytes) + .is_none_or(|end| end > self.index.summary.file_size) + { + return Err(ResidentLoadError::Source("GGUF tensor exceeds indexed file".into())); + } + #[cfg(target_os = "linux")] + let page = rustix::param::page_size() as u64; + #[cfg(windows)] + let page = leleka_libc_shim::allocation_granularity(); + let map_offset = absolute & !(page - 1); + let start = usize::try_from(absolute - map_offset) + .map_err(|e| ResidentLoadError::Source(e.into()))?; + let map_len = start + .checked_add(length) + .ok_or_else(|| ResidentLoadError::Source("mapping length overflow".into()))?; + self.check_size().map_err(ResidentLoadError::Source)?; + // SAFETY: a fresh read-only shared mapping of the retained verified descriptor at a page-aligned + // offset inside the indexed file; the kernel picks the address. No existing memory is replaced. + #[cfg(target_os = "linux")] + let base = unsafe { + rustix::mm::mmap( + std::ptr::null_mut(), + map_len, + rustix::mm::ProtFlags::READ, + rustix::mm::MapFlags::SHARED, + &self.file, + map_offset, + ) + } + .map_err(|e| ResidentLoadError::Source(Box::new(std::io::Error::from(e))))?; + // Windows: CreateFileMapping + MapViewOfFile(FILE_MAP_READ) of the retained verified handle; the view offset is + // a multiple of the 64 KiB allocation granularity (`page` above), the same layout as the Linux mapping. + #[cfg(windows)] + let base = { + use std::os::windows::io::AsRawHandle; + // SAFETY: a fresh read-only view of the retained verified handle at a granularity-aligned offset inside the indexed file. + let view = unsafe { leleka_libc_shim::map_file_readonly(self.file.as_raw_handle().cast(), map_offset, map_len) }; + if view.is_null() { + return Err(ResidentLoadError::Source(Box::new(std::io::Error::last_os_error()))); + } + view + }; + let span = FileSpan { base, map_len, start, len: length }; + self.check_size().map_err(ResidentLoadError::Source)?; + let source = match self.resident_source_id { + Some(source) => source, + None => { + let source = next_source_id().map_err(ResidentLoadError::Source)?; + self.resident_source_id = Some(source); + source + } + }; + Ok(ResidentTensor { + source, + tensor_number, + bytes: ResidentStorage::Mapped(span), + charged_bytes: length, + }) + } + /// Copies a real source-owned bank span, with unchanged indexed bounds and + /// same-FD pre/post size checks. A hit intentionally does not seek/read FD. + pub(crate) fn copy_resident_tensor( + &self, + resident: &ResidentTensor, + offset: u64, + mut output: Box<[u8]>, + ) -> Result> { + if self.resident_source_id != Some(resident.source) { + return Err("resident tensor source identity mismatch".into()); + } + let tensor = self + .index + .tensors + .get(resident.tensor_number) + .ok_or("GGUF tensor index is out of bounds")?; + let length = u64::try_from(output.len())?; + if tensor.bytes == 0 + || resident.bytes.len() as u64 != tensor.bytes + || offset + .checked_add(length) + .is_none_or(|end| end > tensor.bytes) + { + return Err("GGUF tensor byte range is out of bounds".into()); + } + let absolute = self + .index + .summary + .data_start + .checked_add(tensor.offset) + .and_then(|start| start.checked_add(offset)) + .ok_or("GGUF tensor offset overflow")?; + if absolute + .checked_add(length) + .is_none_or(|end| end > self.index.summary.file_size) + { + return Err("GGUF tensor exceeds indexed file".into()); + } + let first = usize::try_from(offset)?; + let end = first + .checked_add(output.len()) + .ok_or("resident tensor offset overflow")?; + let selected = resident + .bytes + .as_slice() + .get(first..end) + .ok_or("resident tensor extent")?; + self.check_size()?; + output.copy_from_slice(selected); + self.check_size()?; + Ok(output) + } +} +impl GgufSourceFence<'_> { + pub(crate) fn copy_resident_tensor( + &self, + tensor: &ResidentTensor, + offset: u64, + output: Box<[u8]>, + ) -> Result> { + self.source.copy_resident_tensor(tensor, offset, output) + } +} diff --git a/crates/model-format/src/gguf_resident/impl_verifiedgguffile_2.rs b/crates/model-format/src/gguf_resident/impl_verifiedgguffile_2.rs new file mode 100644 index 00000000..d221fdb0 --- /dev/null +++ b/crates/model-format/src/gguf_resident/impl_verifiedgguffile_2.rs @@ -0,0 +1,93 @@ +//! Moved out of the parent module by STRA-338: impl VerifiedGgufFile, impl VerifiedGgufFile, impl ResidentTensor, impl VerifiedGgufFile. + +#[allow(unused_imports)] +use super::*; + + +impl VerifiedGgufFile { + pub(crate) fn capture_source_identity(&mut self) -> Result { + self.check_size()?; + if let Some(source) = self.resident_source_id { + return Ok(source); + } + let source = next_source_id()?; + self.resident_source_id = Some(source); + Ok(source) + } + pub(crate) fn admit_captured_tensor( + &mut self, + source: u64, + tensor_number: usize, + bytes: Box<[u8]>, + charged_bytes: usize, + ) -> Result { + if self.resident_source_id != Some(source) + || self + .index + .tensors + .get(tensor_number) + .is_none_or(|tensor| tensor.bytes != bytes.len() as u64 || tensor.bytes == 0) + || charged_bytes < bytes.len() + { + return Err("GGUF resident source identity mismatch".into()); + } + self.stream_tensor(tensor_number, 0, 0, |_| Ok(()))?; + Ok(ResidentTensor { + source, + tensor_number, + bytes: ResidentStorage::Owned(bytes), + charged_bytes, + }) + } +} + +impl VerifiedGgufFile { + pub(crate) fn validate_capture_identity(&self, source: u64) -> Result<()> { + if self.resident_source_id != Some(source) { + return Err("GGUF resident source identity mismatch".into()); + } + self.check_size() + } +} + +// Retains the initialized Box itself; Rc payload is only the small owner. +impl ResidentTensor { + pub(crate) fn into_retained(self) -> std::rc::Rc { + std::rc::Rc::new(self) + } + pub(crate) fn retained_bytes(&self) -> &[u8] { + self.bytes.as_slice() + } + pub(crate) const fn retention_metadata_bytes() -> usize { + std::mem::size_of::() + 2 * std::mem::size_of::() + } +} +impl VerifiedGgufFile { + pub(crate) fn validate_retained_tensor(&self, resident: &ResidentTensor) -> Result<()> { + if self.resident_source_id != Some(resident.source) { + return Err("resident tensor source identity mismatch".into()); + } + let tensor = self + .index + .tensors + .get(resident.tensor_number) + .ok_or("GGUF tensor index is out of bounds")?; + if tensor.bytes == 0 + || resident.bytes.len() as u64 != tensor.bytes + || resident.charged_bytes < resident.bytes.len() + { + return Err("resident tensor extent".into()); + } + let end = self + .index + .summary + .data_start + .checked_add(tensor.offset) + .and_then(|start| start.checked_add(tensor.bytes)) + .ok_or("GGUF tensor offset overflow")?; + if end > self.index.summary.file_size { + return Err("GGUF tensor exceeds indexed file".into()); + } + self.check_size() + } +} diff --git a/crates/model-format/src/gguf_resident/next_source_id.rs b/crates/model-format/src/gguf_resident/next_source_id.rs new file mode 100644 index 00000000..f93b1696 --- /dev/null +++ b/crates/model-format/src/gguf_resident/next_source_id.rs @@ -0,0 +1,73 @@ +//! Moved out of the parent module by STRA-338: fn next_source_id, impl ResidentTensor, impl ResidentStorage, impl std_ops_Deref, impl FileSpan, impl Drop_for_FileSpan. + +#[allow(unused_imports)] +use super::*; + +pub(super) fn next_source_id() -> Result { + let mut current = NEXT_SOURCE_ID.load(Ordering::Relaxed); + loop { + let next = current + .checked_add(1) + .ok_or("resident source identity exhausted")?; + match NEXT_SOURCE_ID.compare_exchange(current, next, Ordering::Relaxed, Ordering::Relaxed) { + Ok(_) => return Ok(current), + Err(actual) => current = actual, + } + } +} +impl ResidentTensor { + pub(crate) fn charged_bytes(&self) -> usize { + self.charged_bytes + } + pub(crate) fn len(&self) -> usize { + self.bytes.len() + } + /// True when the bytes are the verified file's own pages (the Original's `--mmap-experts` GGUF-in-place + /// source), false for an owned RAM copy. + pub(crate) fn file_mapped(&self) -> bool { + matches!(self.bytes, ResidentStorage::Mapped(_)) + } +} +impl ResidentStorage { + pub(super) fn as_slice(&self) -> &[u8] { + match self { + Self::Owned(bytes) => bytes, + Self::Mapped(span) => span.as_slice(), + #[cfg(target_os = "linux")] + Self::Huge(buffer) => buffer.as_slice(), + } + } + pub(super) fn len(&self) -> usize { + self.as_slice().len() + } +} +impl std::ops::Deref for ResidentStorage { + type Target = [u8]; + fn deref(&self) -> &[u8] { + self.as_slice() + } +} +impl FileSpan { + #[allow(unsafe_code)] + pub(super) fn as_slice(&self) -> &[u8] { + // SAFETY: `base..base+map_len` is a live read-only mapping owned by `self`; `start + len <= map_len` + // was checked at construction. The source file's stability is the `VerifiedGgufFile` contract (its + // contents must not change while the handle and anything retained from it are alive). + unsafe { std::slice::from_raw_parts(self.base.cast::().add(self.start), self.len) } + } +} +impl Drop for FileSpan { + #[allow(unsafe_code)] + fn drop(&mut self) { + #[cfg(target_os = "linux")] + // SAFETY: exact base/length returned by mmap; no borrow of the slice outlives `self`. + unsafe { + let _ = rustix::mm::munmap(self.base, self.map_len); + } + #[cfg(windows)] + // SAFETY: exact view base returned by `map_file_readonly`; no borrow of the slice outlives `self`. + unsafe { + let _ = leleka_libc_shim::unmap_file(self.base); + } + } +} diff --git a/crates/model-format/src/kar.rs b/crates/model-format/src/kar.rs index 074c6635..37b8d321 100644 --- a/crates/model-format/src/kar.rs +++ b/crates/model-format/src/kar.rs @@ -19,121 +19,6 @@ pub enum KarError { Allocation, Io(std::io::Error), } -impl std::fmt::Display for KarError { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - match self { - Self::Format(s) | Self::Range(s) | Self::Integrity(s) | Self::Profile(s) => { - f.write_str(s) - } - Self::Allocation => f.write_str("KAR allocation failed"), - Self::Io(e) => e.fmt(f), - } - } -} -impl std::error::Error for KarError { - fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { - if let Self::Io(e) = self { - Some(e) - } else { - None - } - } -} -fn typed(error: String) -> KarError { - if error == "KAR allocation failed" { - return KarError::Allocation; - } - if error.contains("payload CRC-32 mismatch") { - return KarError::Integrity("KAR payload CRC-32 mismatch"); - } - match error.as_str() { - "CPU KAR decoder requires 1..=1,000,000 values within tensor bounds" => { - KarError::Format("CPU KAR decoder requires 1..=1,000,000 values within tensor bounds") - } - "KAR accounted_bpw does not match archive size" => { - KarError::Format("KAR accounted_bpw does not match archive size") - } - "KAR aggregate metadata mismatch" => KarError::Format("KAR aggregate metadata mismatch"), - "KAR archive length mismatch" => KarError::Format("KAR archive length mismatch"), - "KAR book offset overflow" => KarError::Format("KAR book offset overflow"), - "KAR books offset overflow" => KarError::Format("KAR books offset overflow"), - "KAR coded bit count overflow" => KarError::Format("KAR coded bit count overflow"), - "KAR decode base overflow" => KarError::Format("KAR decode base overflow"), - "KAR decode padded size overflow" => KarError::Format("KAR decode padded size overflow"), - "KAR decode range exceeds padded tensor" => { - KarError::Format("KAR decode range exceeds padded tensor") - } - "KAR decode range overflow" => KarError::Format("KAR decode range overflow"), - "KAR directory digest mismatch" => KarError::Format("KAR directory digest mismatch"), - "KAR directory length overflow" => KarError::Format("KAR directory length overflow"), - "KAR directory overflow" => KarError::Format("KAR directory overflow"), - "KAR group is zero" => KarError::Format("KAR group is zero"), - "KAR header CRC-32 mismatch" => KarError::Format("KAR header CRC-32 mismatch"), - "KAR metadata exceeds bounded inspector limits" => { - KarError::Format("KAR metadata exceeds bounded inspector limits") - } - "KAR model element count overflow" => KarError::Format("KAR model element count overflow"), - "KAR name offset overflow" => KarError::Format("KAR name offset overflow"), - "KAR padded count overflow" => KarError::Format("KAR padded count overflow"), - "KAR padded tensor count mismatch" => KarError::Format("KAR padded tensor count mismatch"), - "KAR plane offset overflow" => KarError::Format("KAR plane offset overflow"), - "KAR plane size overflow" => KarError::Format("KAR plane size overflow"), - "KAR plane stride overflow" => KarError::Format("KAR plane stride overflow"), - "KAR planes offset overflow" => KarError::Format("KAR planes offset overflow"), - "KAR raw byte count overflow" => KarError::Format("KAR raw byte count overflow"), - "KAR raw offset overflow" => KarError::Format("KAR raw offset overflow"), - "KAR raw tensor section is too small" => { - KarError::Format("KAR raw tensor section is too small") - } - "KAR raw tensor size overflow" => KarError::Format("KAR raw tensor size overflow"), - "KAR scale byte count overflow" => KarError::Format("KAR scale byte count overflow"), - "KAR scale count overflow" => KarError::Format("KAR scale count overflow"), - "KAR scale offset overflow" => KarError::Format("KAR scale offset overflow"), - "KAR source identity differs from verified manifest shards" => { - KarError::Format("KAR source identity differs from verified manifest shards") - } - "KAR string table overflow" => KarError::Format("KAR string table overflow"), - "KAR tensor bit count overflow" => KarError::Format("KAR tensor bit count overflow"), - "KAR tensor element count mismatch" => { - KarError::Format("KAR tensor element count mismatch") - } - "KAR tensor is too large" => KarError::Format("KAR tensor is too large"), - "KAR tensor name is not UTF-8" => KarError::Format("KAR tensor name is not UTF-8"), - "KAR tensor section overflow" => KarError::Format("KAR tensor section overflow"), - "KAR tensor sections are not contiguous or bounded" => { - KarError::Format("KAR tensor sections are not contiguous or bounded") - } - "KAR tensor shape overflow" => KarError::Format("KAR tensor shape overflow"), - "KARCHIV2" => KarError::Format("KARCHIV2"), - "duplicate KAR tensor name" => KarError::Format("duplicate KAR tensor name"), - "invalid KAR byte order or record size" => { - KarError::Format("invalid KAR byte order or record size") - } - "invalid KAR flags, digest algorithm, or element counts" => { - KarError::Format("invalid KAR flags, digest algorithm, or element counts") - } - "invalid KAR metadata offsets or alignment" => { - KarError::Format("invalid KAR metadata offsets or alignment") - } - "invalid KAR nested tensor parameters" => { - KarError::Format("invalid KAR nested tensor parameters") - } - "invalid KAR nested tensor section layout" => { - KarError::Format("invalid KAR nested tensor section layout") - } - "invalid KAR raw tensor metadata" => KarError::Format("invalid KAR raw tensor metadata"), - "invalid KAR tensor name bounds" => KarError::Format("invalid KAR tensor name bounds"), - "invalid KAR unused dimension" => KarError::Format("invalid KAR unused dimension"), - "source manifest contains an invalid file name" => { - KarError::Format("source manifest contains an invalid file name") - } - "unsupported KAR archive magic or version" => { - KarError::Format("unsupported KAR archive magic or version") - } - "unsupported KAR tensor layout" => KarError::Format("unsupported KAR tensor layout"), - _ => KarError::Io(std::io::Error::other(error)), - } -} const HEADER_BYTES: usize = 256; const RECORD_BYTES: usize = 192; const MAX_TENSORS: usize = 100_000; @@ -168,49 +53,6 @@ pub struct KarTensorSource { pub plane_stride_bytes: u32, } -impl KarTensorSource { - /// The bytes libkar::kar_reserve stages for this record at the requested - /// level. RAW records have no precision dial and always stage in full. - pub fn gpu_resident_bytes(&self, level: u8) -> Result { - if self.storage_class == 1 { - return Ok(self.section_bytes); - } - if !(1..=8).contains(&level) || level < self.planes_min || level > self.planes_max { - return Err(KarError::Profile("KAR level is outside its supported dial")); - } - self.planes_offset - .checked_sub(self.section_offset) - .and_then(|prefix| { - prefix.checked_add(u64::from(level) * u64::from(self.plane_stride_bytes)) - }) - .filter(|bytes| *bytes <= self.section_bytes) - .ok_or(KarError::Range("invalid KAR GPU prefix size")) - } - - pub fn gpu_decode_bytes(&self) -> Result { - self.n_elements - .checked_mul(4) - .ok_or(KarError::Range("KAR F32 decode size overflow")) - } - - /// One-row output size for a geometrically addressable NESTED table. - /// Whether the model can consume only selected rows is a separate question. - pub fn gpu_one_row_decode_bytes(&self) -> Option { - let row_len = *self.dimensions.first()?; - if self.storage_class == 0 - && self.dimensions.len() >= 2 - && row_len.is_multiple_of(32) - && row_len <= u32::MAX as u64 - && self.n_elements > row_len - && self.n_elements.is_multiple_of(row_len) - { - row_len.checked_mul(4) - } else { - None - } - } -} - type ScalarDecoder = fn(&[u16], &[u16], &[&[u32]], u16, usize, &mut [f32]) -> Result<(), String>; pub struct KarInspection { summary: KarSummary, @@ -225,223 +67,6 @@ pub struct KarInspection { pub struct KarImmutableSource { inspection: KarInspection, } -impl KarInspection { - pub fn inspect(file: File) -> Result { - let Parsed { - summary, - file, - sections, - sources, - directory, - payload_offset, - metadata_bytes, - } = inspect_file(file).map_err(typed)?; - Ok(Self { - summary, - file, - sections, - sources, - directory, - payload_offset, - metadata_bytes, - }) - } - pub fn summary(&self) -> &KarSummary { - &self.summary - } - pub fn tensor_sources(&self) -> &[KarTensorSource] { - &self.sources - } - pub fn verify_payloads(&mut self) -> Result<(), KarError> { - let mut buffer = Vec::new(); - buffer - .try_reserve_exact(8 * 1024 * 1024) - .map_err(|_| KarError::Allocation)?; - buffer.resize(8 * 1024 * 1024, 0); - for section in &self.sections { - self.file - .seek(SeekFrom::Start(section.offset)) - .map_err(KarError::Io)?; - let mut remaining = section.bytes; - let mut crc = !0u32; - while remaining > 0 { - let n = remaining.min(buffer.len() as u64) as usize; - self.file - .read_exact(&mut buffer[..n]) - .map_err(KarError::Io)?; - crc = crc32_step(crc, &buffer[..n]); - remaining -= n as u64; - } - if !crc != section.crc32 { - return Err(KarError::Integrity("KAR payload CRC-32 mismatch")); - } - } - Ok(()) - } - fn verify_integrity(&mut self, bytes: u64, pin: &[u8; 32]) -> Result<(), KarError> { - verify_integrity_pipelined(&self.file, &self.sections, bytes, pin) - } - pub fn decode_range( - &mut self, - name: &str, - level: u8, - start: usize, - count: usize, - decoder: ScalarDecoder, - ) -> Result, KarError> { - let index = self - .sources - .iter() - .position(|s| s.name == name) - .ok_or(KarError::Range("KAR tensor not found"))?; - let record: [u8; RECORD_BYTES] = self.directory - [index * RECORD_BYTES..(index + 1) * RECORD_BYTES] - .try_into() - .expect("validated directory"); - decode_record_range(&mut self.file, &record, level, start, count, decoder).map_err(typed) - } - /// Trusted-owner contract, not an OS/stat check: the caller establishes that - /// the retained inode has been immutable since inspection and remains so - /// for the entire binding lifetime. A read-only descriptor alone is insufficient. - pub fn into_owner_controlled(self) -> KarImmutableSource { - KarImmutableSource { inspection: self } - } -} -fn decode_record_range( - file: &mut File, - record: &[u8; RECORD_BYTES], - level: u8, - start: usize, - count: usize, - decoder: ScalarDecoder, -) -> Result, String> { - let elements = usize::try_from(u64_at(record, 48)).map_err(|_| "KAR tensor is too large")?; - let end = start - .checked_add(count) - .ok_or("KAR decode range overflow")?; - if count == 0 || count > 1_000_000 || end > elements { - return Err("CPU KAR decoder requires 1..=1,000,000 values within tensor bounds".into()); - } - if record[7] == 1 { - if record[41] != 0 { - return Err("CPU quality oracle only supports RAW F32 tensors".into()); - } - let offset = u64_at(record, 112) - .checked_add( - (start as u64) - .checked_mul(4) - .ok_or("KAR raw offset overflow")?, - ) - .ok_or("KAR raw offset overflow")?; - let bytes = read_region( - file, - offset, - count.checked_mul(4).ok_or("KAR raw byte count overflow")?, - )?; - return Ok(bytes - .as_chunks::<4>() - .0 - .iter() - .map(|word| f32::from_le_bytes(*word)) - .collect()); - } - let stored = record[42]; - if level == 0 || level > stored { - return Err(format!("KAR tensor stores 1..={stored} levels")); - } - let group = u16_at(record, 46); - let group_size = usize::from(group); - if group_size == 0 { - return Err("KAR group is zero".into()); - } - let padded = usize::try_from(u64_at(record, 56)).map_err(|_| "KAR tensor is too large")?; - let base_group = start / group_size; - let end_group = end.div_ceil(group_size); - let base_element = base_group - .checked_mul(group_size) - .ok_or("KAR decode base overflow")?; - let local_padded = (end_group - base_group) - .checked_mul(group_size) - .ok_or("KAR decode padded size overflow")?; - if base_element - .checked_add(local_padded) - .is_none_or(|end| end > padded) - { - return Err("KAR decode range exceeds padded tensor".into()); - } - let scale_bytes = read_region( - file, - u64_at(record, 64) - .checked_add( - (base_group as u64) - .checked_mul(2) - .ok_or("KAR scale offset overflow")?, - ) - .ok_or("KAR scale offset overflow")?, - (end_group - base_group) - .checked_mul(2) - .ok_or("KAR scale byte count overflow")?, - )?; - let scales = scale_bytes - .as_chunks::<2>() - .0 - .iter() - .map(|pair| u16::from_le_bytes([pair[0], pair[1]])) - .collect::>(); - let book_offset = u64_at(record, 80) - .checked_add((1u64 << (u32::from(level) + 1)) - 4) - .ok_or("KAR book offset overflow")?; - let book_bytes = read_region(file, book_offset, (1usize << level) * 2)?; - let book = book_bytes - .as_chunks::<2>() - .0 - .iter() - .map(|pair| u16::from_le_bytes([pair[0], pair[1]])) - .collect::>(); - let plane_stride = u64::from(u32_at(record, 104)); - let plane_bytes = local_padded / 32 * 4; - let plane_base = u64::try_from( - (base_element / 32) - .checked_mul(4) - .ok_or("KAR plane offset overflow")?, - ) - .map_err(|_| "KAR plane offset overflow")?; - let mut planes = Vec::with_capacity(usize::from(level)); - for plane in 0..u64::from(level) { - let offset = u64_at(record, 96) - .checked_add( - plane - .checked_mul(plane_stride) - .ok_or("KAR plane offset overflow")?, - ) - .and_then(|offset| offset.checked_add(plane_base)) - .ok_or("KAR plane offset overflow")?; - let bytes = read_region(file, offset, plane_bytes)?; - planes.push( - bytes - .as_chunks::<4>() - .0 - .iter() - .map(|word| u32::from_le_bytes([word[0], word[1], word[2], word[3]])) - .collect::>(), - ); - } - let plane_refs = planes.iter().map(Vec::as_slice).collect::>(); - let mut output = Vec::new(); - output - .try_reserve_exact(count) - .map_err(|_| "KAR allocation failed")?; - output.resize(count, 0.0); - decoder( - &scales, - &book, - &plane_refs, - group, - start - base_element, - &mut output, - )?; - Ok(output) -} struct Section { offset: u64, @@ -459,316 +84,6 @@ struct Parsed { /// Header + name table + directory: everything `inspect` reads of the file. metadata_bytes: u64, } -fn inspect_file(mut file: File) -> Result { - let file_bytes = file.metadata().map_err(|error| error.to_string())?.len(); - let header = read_region(&mut file, 0, HEADER_BYTES)?; - if &header[0..8] != b"KARCHIV2" || u32_at(&header, 8) != 2 { - return Err("unsupported KAR archive magic or version".into()); - } - if u32_at(&header, 12) != 0x04030201 - || u32_at(&header, 16) != HEADER_BYTES as u32 - || u32_at(&header, 20) != RECORD_BYTES as u32 - { - return Err("invalid KAR byte order or record size".into()); - } - if crc32(&header[..192]) != u32_at(&header, 192) { - return Err("KAR header CRC-32 mismatch".into()); - } - let directory_offset = u64_at(&header, 24); - let tensor_count = u32_at(&header, 32); - let string_offset = u64_at(&header, 40); - let string_bytes = u64_at(&header, 48); - let payload_offset = u64_at(&header, 56); - let archive_bytes = u64_at(&header, 64); - let total_elements = u64_at(&header, 72); - let payload_bits = u64_at(&header, 80); - let source_total_elements = u64_at(&header, 88); - let source_bytes = u64_at(&header, 120); - let accounted_bpw = f64::from_le_bytes(header[96..104].try_into().unwrap()); - let mut source_digest = [0; 32]; - source_digest.copy_from_slice(&header[128..160]); - if archive_bytes != file_bytes || archive_bytes < HEADER_BYTES as u64 { - return Err("KAR archive length mismatch".into()); - } - if tensor_count == 0 || tensor_count as usize > MAX_TENSORS || string_bytes > MAX_NAMES as u64 { - return Err("KAR metadata exceeds bounded inspector limits".into()); - } - if u32_at(&header, 36) != 0 - || header[106] != 1 - || total_elements == 0 - || total_elements > source_total_elements - || source_bytes == 0 - { - return Err("invalid KAR flags, digest algorithm, or element counts".into()); - } - let expected_bpw = archive_bytes as f64 * 8.0 / total_elements as f64; - if !accounted_bpw.is_finite() - || ((accounted_bpw - expected_bpw) / expected_bpw).abs() > 2f64.powi(-40) - { - return Err("KAR accounted_bpw does not match archive size".into()); - } - let directory_bytes = (tensor_count as u64) - .checked_mul(RECORD_BYTES as u64) - .ok_or("KAR directory length overflow")?; - let directory_end = directory_offset - .checked_add(directory_bytes) - .ok_or("KAR directory overflow")?; - let string_end = string_offset - .checked_add(string_bytes) - .ok_or("KAR string table overflow")?; - if !directory_offset.is_multiple_of(64) - || !string_offset.is_multiple_of(64) - || !payload_offset.is_multiple_of(256) - || directory_offset < HEADER_BYTES as u64 - || directory_end > string_offset - || string_end > payload_offset - || payload_offset > archive_bytes - { - return Err("invalid KAR metadata offsets or alignment".into()); - } - let names = read_region(&mut file, string_offset, string_bytes as usize)?; - let directory = read_region(&mut file, directory_offset, directory_bytes as usize)?; - let mut digest = Sha256::new(); - digest.update(&names); - digest.update(&directory); - if digest.finalize().as_slice() != &header[160..192] { - return Err("KAR directory digest mismatch".into()); - } - - let mut seen_names = HashSet::new(); - seen_names - .try_reserve(tensor_count as usize) - .map_err(|_| "KAR allocation failed")?; - let mut elements_sum = 0u64; - let mut bits_sum = 0u64; - let mut previous_end = payload_offset; - let mut min_planes = u8::MAX; - let mut max_planes = 0u8; - let mut sections = Vec::new(); - sections - .try_reserve_exact(tensor_count as usize) - .map_err(|_| "KAR allocation failed")?; - let mut sources = Vec::new(); - sources - .try_reserve_exact(tensor_count as usize) - .map_err(|_| "KAR allocation failed")?; - let (records, remainder) = directory.as_chunks::(); - debug_assert!(remainder.is_empty()); - for record in records { - let name_start = u32_at(record, 0) as usize; - let name_len = u16_at(record, 4) as usize; - let name_end = name_start - .checked_add(name_len) - .ok_or("KAR name offset overflow")?; - if name_end >= names.len() || names[name_end] != 0 { - return Err("invalid KAR tensor name bounds".into()); - } - let name = std::str::from_utf8(&names[name_start..name_end]) - .map_err(|_| "KAR tensor name is not UTF-8")?; - if !seen_names.insert(name) { - return Err("duplicate KAR tensor name".into()); - } - let n_dims = record[6] as usize; - let storage = record[7]; - if !(1..=4).contains(&n_dims) || storage > 1 || record[40] != 0 || record[41] > 2 { - return Err("unsupported KAR tensor layout".into()); - } - let dims = (0..4) - .map(|index| u64_at(record, 8 + index * 8)) - .collect::>(); - if dims[n_dims..].iter().any(|dim| *dim != 1) { - return Err("invalid KAR unused dimension".into()); - } - let product = dims[..n_dims] - .iter() - .try_fold(1u64, |acc, dim| acc.checked_mul(*dim)) - .ok_or("KAR tensor shape overflow")?; - let n_elements = u64_at(record, 48); - if product != n_elements || n_elements == 0 { - return Err("KAR tensor element count mismatch".into()); - } - elements_sum = elements_sum - .checked_add(n_elements) - .ok_or("KAR model element count overflow")?; - let mut source_digest = [0u8; 32]; - source_digest.copy_from_slice(&record[128..160]); - sources.push(KarTensorSource { - name: name.to_owned(), - dimensions: dims[..n_dims].to_vec(), - dtype: record[41], - digest: source_digest, - offset: u64_at(record, 160), - section_bytes: u64_at(record, 120), - storage_class: storage, - n_elements, - planes_min: record[43], - planes_max: record[44], - section_offset: u64_at(record, 112), - planes_offset: u64_at(record, 96), - plane_stride_bytes: u32_at(record, 104), - }); - let section_offset = u64_at(record, 112); - let section_bytes = u64_at(record, 120); - let section_end = section_offset - .checked_add(section_bytes) - .ok_or("KAR tensor section overflow")?; - if section_offset != previous_end - || !section_offset.is_multiple_of(256) - || section_end > archive_bytes - { - return Err("KAR tensor sections are not contiguous or bounded".into()); - } - previous_end = section_end; - sections.push(Section { - offset: section_offset, - bytes: section_bytes, - crc32: u32_at(record, 108), - }); - if storage == 0 { - let group = u16_at(record, 46) as u64; - let planes = record[42]; - let n_padded = u64_at(record, 56); - if group == 0 - || group > 1024 - || !group.is_multiple_of(32) - || !(1..=16).contains(&planes) - || record[43] == 0 - || record[43] > record[44] - || record[44] > planes - || record[45] > 1 - { - return Err("invalid KAR nested tensor parameters".into()); - } - let rounded = n_elements - .div_ceil(group) - .checked_mul(group) - .ok_or("KAR padded count overflow")?; - if n_padded != rounded { - return Err("KAR padded tensor count mismatch".into()); - } - let scales_offset = u64_at(record, 64); - let scales_bytes = u64_at(record, 72); - let books_offset = u64_at(record, 80); - let books_bytes = u64_at(record, 88); - let planes_offset = u64_at(record, 96); - let stride = u32_at(record, 104) as u64; - let expected_scales = (n_padded / group) - .checked_mul(2) - .ok_or("KAR scale count overflow")?; - let expected_books = (1u64 << (planes as u32 + 2)) - 4; - let plane_words_bytes = (n_padded / 32) - .checked_mul(4) - .ok_or("KAR plane size overflow")?; - let expected_stride = - round_up(plane_words_bytes, 16).ok_or("KAR plane stride overflow")?; - let books_start = scales_offset - .checked_add(scales_bytes) - .and_then(|value| round_up(value, 16)) - .ok_or("KAR books offset overflow")?; - let planes_start = books_offset - .checked_add(books_bytes) - .and_then(|value| round_up(value, 16)) - .ok_or("KAR planes offset overflow")?; - if scales_offset != section_offset - || scales_bytes != expected_scales - || books_offset != books_start - || books_bytes != expected_books - || planes_offset != planes_start - || stride != expected_stride - || planes_offset - .checked_add(planes as u64 * stride) - .is_none_or(|end| end > section_end) - { - return Err("invalid KAR nested tensor section layout".into()); - } - let tensor_bits = (planes as u64) - .checked_mul(n_padded) - .and_then(|bits| { - (n_padded / group) - .checked_mul(16) - .and_then(|scale_bits| bits.checked_add(scale_bits)) - }) - .ok_or("KAR tensor bit count overflow")?; - bits_sum = bits_sum - .checked_add(tensor_bits) - .ok_or("KAR coded bit count overflow")?; - min_planes = min_planes.min(record[43]); - max_planes = max_planes.max(record[44]); - } else { - if record[42..48].iter().any(|value| *value != 0) - || u64_at(record, 56) != n_elements - || record[64..104].iter().any(|value| *value != 0) - || u32_at(record, 104) != 0 - { - return Err("invalid KAR raw tensor metadata".into()); - } - let width = if record[41] == 0 { 4 } else { 2 }; - if section_bytes - < n_elements - .checked_mul(width) - .ok_or("KAR raw tensor size overflow")? - { - return Err("KAR raw tensor section is too small".into()); - } - } - } - if previous_end != archive_bytes - || elements_sum != total_elements - || bits_sum != payload_bits - || header[104] != if min_planes == u8::MAX { 0 } else { min_planes } - || header[105] != max_planes - { - return Err("KAR aggregate metadata mismatch".into()); - } - let summary = KarSummary { - archive_bytes, - tensor_count, - total_elements, - source_total_elements, - accounted_bpw, - source_digest, - source_bytes, - max_planes, - }; - Ok(Parsed { - summary, - file, - sections, - sources, - directory, - payload_offset, - metadata_bytes: HEADER_BYTES as u64 + string_bytes + directory_bytes, - }) -} - -fn read_region(file: &mut File, offset: u64, length: usize) -> Result, String> { - file.seek(SeekFrom::Start(offset)) - .map_err(|error| error.to_string())?; - let mut bytes = Vec::new(); - bytes - .try_reserve_exact(length) - .map_err(|_| "KAR allocation failed")?; - bytes.resize(length, 0); - file.read_exact(&mut bytes) - .map_err(|error| error.to_string())?; - Ok(bytes) -} - -fn u16_at(bytes: &[u8], offset: usize) -> u16 { - u16::from_le_bytes(bytes[offset..offset + 2].try_into().unwrap()) -} - -fn u32_at(bytes: &[u8], offset: usize) -> u32 { - u32::from_le_bytes(bytes[offset..offset + 4].try_into().unwrap()) -} - -fn u64_at(bytes: &[u8], offset: usize) -> u64 { - u64::from_le_bytes(bytes[offset..offset + 8].try_into().unwrap()) -} - -pub fn crc32(bytes: &[u8]) -> u32 { - !crc32_step(!0u32, bytes) -} const CRC32_TABLE: [u32; 256] = { let mut table = [0; 256]; @@ -802,176 +117,6 @@ const CRC32_SLICES: [[u32; 256]; 7] = { } tables }; -pub fn crc32_step(mut crc: u32, bytes: &[u8]) -> u32 { - let (blocks, tail) = bytes.as_chunks::<8>(); - for block in blocks { - let first = u32::from_le_bytes([block[0], block[1], block[2], block[3]]) ^ crc; - crc = CRC32_SLICES[6][(first & 255) as usize] - ^ CRC32_SLICES[5][((first >> 8) & 255) as usize] - ^ CRC32_SLICES[4][((first >> 16) & 255) as usize] - ^ CRC32_SLICES[3][(first >> 24) as usize] - ^ CRC32_SLICES[2][usize::from(block[4])] - ^ CRC32_SLICES[1][usize::from(block[5])] - ^ CRC32_SLICES[0][usize::from(block[6])] - ^ CRC32_TABLE[usize::from(block[7])]; - } - // Preserve the original scalar transition for all remaining zero to seven bytes. - for &byte in tail { - crc = (crc >> 8) ^ CRC32_TABLE[((crc ^ u32::from(byte)) & 255) as usize]; - } - crc -} - -/// Inspect has already admitted contiguous sections. Recheck their bounds here -/// before consuming bytes, including in the small streaming regression seam. -fn integrity_sections(sections: &[Section], bytes: u64) -> Result<(), KarError> { - let mut end = sections.first().map_or(bytes, |s| s.offset); - for section in sections { - if section.offset != end || section.bytes == 0 { - return Err(KarError::Range("KAR integrity section bounds")); - } - end = end - .checked_add(section.bytes) - .filter(|end| *end <= bytes) - .ok_or(KarError::Range("KAR integrity section bounds"))?; - } - if sections.is_empty() || end != bytes { - return Err(KarError::Range("KAR integrity section bounds")); - } - Ok(()) -} - -/// The production form of [`verify_integrity_stream`]: one reader thread keeps chunks coming, SHA-256 of the -/// whole archive runs on the calling thread and the per-section CRC-32 on a second one, so the pass costs the -/// slower of the two instead of the read plus both. Same verdicts, same precedence: a SHA mismatch (or a short -/// archive) is reported before a CRC failure, and a CRC failure never shortcuts the full hash. -fn verify_integrity_pipelined( - file: &File, - sections: &[Section], - bytes: u64, - pin: &[u8; 32], -) -> Result<(), KarError> { - integrity_sections(sections, bytes)?; - let (digest, total, crc) = crate::readahead::with_read_ahead(file, 0, bytes, 2, |mut receivers| { - let crc_rx = receivers.pop().expect("two receivers"); - let sha_rx = receivers.pop().expect("two receivers"); - std::thread::scope(|scope| { - let crc_thread = scope.spawn(move || -> std::io::Result<(bool, usize)> { - let (mut index, mut total, mut crc, mut failed) = (0usize, 0u64, !0u32, false); - for item in crc_rx { - let chunk = item?; - let end = total + chunk.len() as u64; - while let Some(section) = sections.get(index) { - if section.offset >= end { - break; - } - let section_end = section.offset + section.bytes; // Checked by integrity_sections. - let start = total.max(section.offset); - let stop = end.min(section_end); - crc = crc32_step(crc, &chunk[(start - total) as usize..(stop - total) as usize]); - if stop != section_end { - break; - } - failed |= !crc != section.crc32; - crc = !0u32; - index += 1; - } - total = end; - } - Ok((failed, index)) - }); - let mut digest = Sha256::new(); - let mut total = 0u64; - let mut read_error = None; - for item in sha_rx { - match item { - Ok(chunk) => { - digest.update(&chunk[..]); - total += chunk.len() as u64; - } - Err(error) => { - read_error = Some(error); - break; - } - } - } - let crc = crc_thread.join().expect("the CRC thread does not panic"); - match read_error { - Some(error) => Err(KarError::Io(error)), - None => crc.map(|c| (digest, total, c)).map_err(KarError::Io), - } - }) - })?; - let (crc_failed, index) = crc; - if total != bytes || digest.finalize().as_slice() != pin { - return Err(KarError::Integrity("KAR full archive SHA-256 mismatch")); - } - if crc_failed || index != sections.len() { - return Err(KarError::Integrity("KAR payload CRC-32 mismatch")); - } - Ok(()) -} - -/// The reference scan (kept for the tests that pin its verdicts; production uses the pipelined form above). -#[cfg_attr(not(test), allow(dead_code))] -fn verify_integrity_stream( - file: &mut impl Read, - sections: &[Section], - bytes: u64, - pin: &[u8; 32], - buffer: &mut [u8], -) -> Result<(), KarError> { - integrity_sections(sections, bytes)?; - if buffer.is_empty() { - return Err(KarError::Range("KAR integrity buffer is empty")); - } - let mut digest = Sha256::new(); - let mut total = 0u64; - let mut index = 0; - let mut crc = !0u32; - let mut crc_failed = false; - loop { - let n = file.read(buffer).map_err(KarError::Io)?; - if n == 0 { - break; - } - let end = total - .checked_add(n as u64) - .ok_or(KarError::Range("KAR hash length overflow"))?; - digest.update(&buffer[..n]); // Metadata and padding belong to the SHA too. - while let Some(section) = sections.get(index) { - if section.offset >= end { - break; - } - let section_end = section.offset + section.bytes; // Checked above. - let start = total.max(section.offset); - let stop = end.min(section_end); - crc = crc32_step( - crc, - &buffer[(start - total) as usize..(stop - total) as usize], - ); - if stop != section_end { - break; - } - crc_failed |= !crc != section.crc32; - crc = !0u32; - index += 1; - } - total = end; - } - // A CRC failure never shortcuts the full hash or changes SHA-first precedence. - if total != bytes || digest.finalize().as_slice() != pin { - return Err(KarError::Integrity("KAR full archive SHA-256 mismatch")); - } - if crc_failed || index != sections.len() { - return Err(KarError::Integrity("KAR payload CRC-32 mismatch")); - } - Ok(()) -} - -fn round_up(value: u64, alignment: u64) -> Option { - value.div_ceil(alignment).checked_mul(alignment) -} /// Values from a trusted, pinned provenance manifest, not an archive header. pub struct KarPlePartProvenance { @@ -994,73 +139,11 @@ pub struct KarPleProfile { spec: KarPleProfileSpec, } const PLE_ROWS: u64 = 320_001_536; -impl KarPleProfile { - /// Bounds validation does not authenticate the manifest's origin. Only the - /// admitted model-binding loader may supply its trusted pinned expectations. - pub fn new(spec: KarPleProfileSpec) -> Result { - Self::with_total_rows(spec, PLE_ROWS) - } - /// `new` for a table of `total_rows` rows: the pinned table has `PLE_ROWS`; tests build miniature archives. - fn with_total_rows(spec: KarPleProfileSpec, total_rows: u64) -> Result { - if spec.archive_bytes < 256 - || spec.virtual_f32_bytes == 0 - || spec.parts.is_empty() - || spec.parts.len() > 65535 - || spec.archive_sha256 == [0; 32] - || spec.provenance_sha256 == [0; 32] - || spec.virtual_f32_sha256 == [0; 32] - || spec.native_shard_sha256.contains(&[0; 32]) - { - return Err(KarError::Profile("invalid KAR PLE profile")); - } - let mut next = 0u64; - let mut names = HashSet::new(); - names - .try_reserve(spec.parts.len()) - .map_err(|_| KarError::Allocation)?; - for p in &spec.parts { - if p.name.is_empty() - || p.name.len() > 1024 - || p.name.bytes().any(|b| b < 32 || b == 127) - || !names.insert(p.name.as_str()) - || p.row_base != next - || p.row_count == 0 - || p.derived_f32_sha256 == [0; 32] - { - return Err(KarError::Profile("invalid KAR PLE partition provenance")); - } - next = next - .checked_add(p.row_count) - .filter(|n| *n <= total_rows) - .ok_or(KarError::Range("KAR PLE row count overflow"))?; - p.row_count - .checked_mul(640) - .and_then(|n| p.derived_f32_offset.checked_add(n)) - .filter(|n| *n <= spec.virtual_f32_bytes) - .ok_or(KarError::Range("KAR PLE virtual source range"))?; - } - if next != total_rows { - return Err(KarError::Profile("KAR PLE table extent mismatch")); - } - Ok(Self { spec }) - } - pub fn native_shard_sha256(&self) -> &[[u8; 32]; 2] { - &self.spec.native_shard_sha256 - } -} #[derive(Clone, Copy)] pub struct KarPleRowPacket { payload: [u8; 50], partition: u16, } -impl KarPleRowPacket { - pub fn payload(&self) -> &[u8; 50] { - &self.payload - } - pub fn partition(&self) -> u16 { - self.partition - } -} #[derive(Clone)] struct VerifiedPart { row_base: u64, @@ -1069,16 +152,6 @@ struct VerifiedPart { planes: u64, stride: u64, } -#[cfg(unix)] -fn is_unlinked(file: &File) -> bool { - use std::os::unix::fs::MetadataExt; - file.metadata().is_ok_and(|m| m.is_file() && m.nlink() == 0) -} - -#[cfg(not(unix))] -fn is_unlinked(_file: &File) -> bool { - false -} /// How the content of the archive was vouched for when it was opened. #[derive(Clone, Copy, Debug, Eq, PartialEq)] @@ -1092,16 +165,6 @@ pub enum KarTrust { /// A sparse memfd (`verify_sparse`): the bytes of its extents matched the pinned digest of the extents; the rest is a hole. SparseExtents, } -impl KarTrust { - pub fn as_str(self) -> &'static str { - match self { - KarTrust::FullPass => "full-pass", - KarTrust::Stamp => "stamp", - KarTrust::AttestedMemfd => "attested-memfd", - KarTrust::SparseExtents => "sparse-extents", - } - } -} /// What opening the archive read from it (not what a request reads later): the figures behind the startup log line. #[derive(Clone, Copy, Debug, Eq, PartialEq)] @@ -1114,11 +177,6 @@ pub struct KarStartupRead { /// Bytes hashed by the verification: the whole archive for `FullPass`, the extents for `SparseExtents`, otherwise 0. pub hashed_bytes: u64, } -impl KarStartupRead { - pub fn total_bytes(&self) -> u64 { - self.metadata_bytes + self.book_bytes + self.hashed_bytes - } -} pub struct VerifiedKarPleArtifact { reader: KarInspection, @@ -1137,268 +195,9 @@ pub struct VerifiedKarPleArtifact { /// file after verification refuses the read instead of serving bytes nobody checked. See `identity_recheck_enabled`. identity: Option, } -impl VerifiedKarPleArtifact { - pub fn verify(source: KarImmutableSource, profile: KarPleProfile) -> Result { - Self::verify_with(source, profile, None) - } - /// `verify` for a sealed memfd that holds only the bytes the serve path reads (holes elsewhere, same file offsets and - /// length): the full-archive SHA-256 and the payload CRCs cannot be computed, so the pinned `extents_sha256` - /// ([`digest_extents_with`] over `serve_extents`, measured once from the archive that matched its full pin) stands - /// in for them, and the directory digest in the header (checked by `inspect`, inside the extents) covers the rest. - /// Fails closed: a wrong digest, a read range outside the extents or a changed length is an error. - pub fn verify_sparse(source: KarImmutableSource, profile: KarPleProfile, extents_sha256: &[u8; 32]) -> Result { - Self::verify_with(source, profile, Some(extents_sha256)) - } - fn verify_with(source: KarImmutableSource, profile: KarPleProfile, sparse_pin: Option<&[u8; 32]>) -> Result { - let mut reader = source.inspection; - if reader.file.metadata().map_err(KarError::Io)?.len() != profile.spec.archive_bytes - || reader.summary.archive_bytes != profile.spec.archive_bytes - || reader.summary.source_bytes != profile.spec.virtual_f32_bytes - || reader.summary.source_digest != profile.spec.virtual_f32_sha256 - { - return Err(KarError::Integrity( - "KAR archive/provenance identity mismatch", - )); - } - // A stamp for exactly this file in exactly this state (see verify_stamp.rs) stands in for the full - // SHA-256 + CRC pass; a sealed memfd has no stable identity and always takes the full pass. - let identity = reader - .file - .metadata() - .ok() - .and_then(|m| crate::verify_stamp::FileIdentity::of(&m)); - let stamps = crate::verify_stamp::global(); - // An unlinked sealed memfd: only if the parent attested the copy (see `set_attested_archive`). - let attested_memfd = identity.is_none() && crate::verify_stamp::attested_archive() && is_unlinked(&reader.file); - let stamped = matches!((stamps, identity.as_ref()), (Some(s), Some(id)) if s.trusts("kar", &profile.spec.archive_sha256, id)); - let trusted = attested_memfd || stamped; - let trust = if sparse_pin.is_some() { - KarTrust::SparseExtents - } else if attested_memfd { - KarTrust::AttestedMemfd - } else if stamped { - KarTrust::Stamp - } else { - KarTrust::FullPass - }; - // A sparse copy never takes a stamp or an attestation: those speak for the whole archive, which it does not hold. - if sparse_pin.is_none() && !trusted { - reader.verify_integrity(profile.spec.archive_bytes, &profile.spec.archive_sha256)?; - if let (Some(stamps), Some(before)) = (stamps, identity) - && reader - .file - .metadata() - .ok() - .and_then(|m| crate::verify_stamp::FileIdentity::of(&m)) - == Some(before) - { - let _ = stamps.record("kar", &profile.spec.archive_sha256, &before); - } - } - let mut parts = Vec::new(); - let mut books = Vec::new(); - let mut book_at_list = Vec::new(); - parts - .try_reserve_exact(profile.spec.parts.len()) - .map_err(|_| KarError::Allocation)?; - books - .try_reserve_exact(profile.spec.parts.len()) - .map_err(|_| KarError::Allocation)?; - for p in &profile.spec.parts { - let index = reader - .sources - .iter() - .position(|s| s.name == p.name) - .ok_or(KarError::Profile("KAR PLE partition missing"))?; - let s = &reader.sources[index]; - let record = &reader.directory[index * 192..(index + 1) * 192]; - if s.dimensions != [160, p.row_count] - || s.dtype != 0 - || s.storage_class != 0 - || record[45] != 0 - || u16_at(record, 46) != 32 - || s.planes_min > 2 - || s.planes_max < 2 - || s.digest != p.derived_f32_sha256 - || s.offset != p.derived_f32_offset - { - return Err(KarError::Profile( - "KAR PLE partition/source mapping mismatch", - )); - } - let scales = u64_at(record, 64); - let planes = s.planes_offset; - let stride = u64::from(s.plane_stride_bytes); - let book_at = u64_at(record, 80) - .checked_add(4) - .ok_or(KarError::Range("KAR PLE book overflow"))?; - let bytes = read_region(&mut reader.file, book_at, 8).map_err(typed)?; - let book = std::array::from_fn(|i| u16_at(&bytes, i * 2)); - if book.iter().any(|b| b & 0x7c00 == 0x7c00) { - return Err(KarError::Profile("KAR PLE nonfinite book")); - } - parts.push(VerifiedPart { - row_base: p.row_base, - row_count: p.row_count, - scales, - planes, - stride, - }); - books.push(book); - book_at_list.push(book_at); - } - let serve_extents = normalize_extents( - &extents::exact_reads(reader.payload_offset, &parts, &book_at_list)?, - profile.spec.archive_bytes, - )?; - if let Some(pin) = sparse_pin { - // Every byte a row read can touch lies inside the extents (a row read is bounded by its partition), so no - // read can land in a hole; then the bytes of the extents must be the pinned ones. - for part in &parts { - for read in part.reads()? { - if !extents_cover(&serve_extents, read.offset, read.len) { - return Err(KarError::Range("KAR PLE read outside the sparse extents")); - } - } - } - let digest = digest_extents(&reader.file, &serve_extents, |_| {})?; - if &digest != pin { - return Err(KarError::Integrity("KAR sparse extents SHA-256 mismatch")); - } - } - let after = reader.file.metadata().map_err(KarError::Io)?; - if after.len() != profile.spec.archive_bytes { - return Err(KarError::Integrity("KAR archive length changed")); - } - // An ordinary file must be in the very state that was verified (or stamped) at the start of this call. - if identity.is_some() && crate::verify_stamp::FileIdentity::of(&after) != identity { - return Err(KarError::Integrity("KAR archive file changed while it was verified")); - } - let startup = KarStartupRead { - trust, - metadata_bytes: reader.metadata_bytes, - book_bytes: 8 * parts.len() as u64, - hashed_bytes: if sparse_pin.is_some() { - extents_bytes(&serve_extents) - } else if trusted { - 0 - } else { - profile.spec.archive_bytes - }, - }; - Ok(Self { - reader, - profile, - parts, - books, - handles: std::sync::OnceLock::new(), - serve_extents, - sparse: sparse_pin.is_some(), - startup, - identity: if identity_recheck_enabled() { identity } else { None }, - }) - } - /// The ranges of the archive the serve path reads (page-aligned, sorted, merged). - pub fn serve_extents(&self) -> &[Extent] { - &self.serve_extents - } - /// Verified as a sparse copy (by the digest of its extents, not the whole archive). - pub fn is_sparse(&self) -> bool { - self.sparse - } - /// What opening this archive read from it, for the startup log (`KarStartupRead`). - pub fn startup_read(&self) -> KarStartupRead { - self.startup - } - /// True when row reads compare the open file with its verified state (an ordinary file, not a memfd). - pub fn rechecks_file_identity(&self) -> bool { - self.identity.is_some() - } - pub fn archive_sha256(&self) -> &[u8; 32] { - &self.profile.spec.archive_sha256 - } - pub fn archive_bytes(&self) -> u64 { - self.profile.spec.archive_bytes - } - /// Digest of the trusted provenance manifest; never the archive/source digest. - pub fn profile_sha256(&self) -> &[u8; 32] { - &self.profile.spec.provenance_sha256 - } - pub fn native_shard_sha256(&self) -> &[[u8; 32]; 2] { - &self.profile.spec.native_shard_sha256 - } - pub fn row_count(&self) -> u64 { - PLE_ROWS - } - pub fn partition_books(&self) -> &[[u16; 4]] { - &self.books - } - pub fn read_rows(&mut self, rows: &[u64; 16]) -> Result<[KarPleRowPacket; 16], KarError> { - if rows.iter().any(|r| *r >= PLE_ROWS) { - return Err(KarError::Range("KAR PLE row outside table")); - } - // 16 rows are 48 random reads of a cold file: eight threads on handles of their own, two rows each. A file the page cache - // holds answers each read in about a microsecond, and eight thread starts and joins then cost more than the reads - // (about 0.1 ms per token of a decode window); `warm_probe` reads the first row on this thread, times it, and reads the - // other fifteen here too when it was served from memory. - let packets = read_rows_parallel(self.row_handles(), &self.parts, self.archive_bytes(), self.identity.as_ref(), rows, 8, 2, true)?; - let mut out = [KarPleRowPacket { - payload: [0; 50], - partition: 0, - }; 16]; - out.copy_from_slice(&packets); - Ok(out) - } - /// Handles with a file object of their own (so reads through two of them can be in flight at once). - fn row_handles(&self) -> &[File] { - self.handles - .get_or_init(|| independent_handles(&self.reader.file, ROW_HANDLES)) - } - /// `read_rows` over any number of rows: the same three region reads per row, the same bounds and non-finite - /// scale refusals, but positional (`pread`, no seek) and split over a few threads, because the batched prefill - /// reads every row of a chunk the cache does not hold at once (tens of thousands on a cold chunk). - pub fn read_rows_batch(&self, rows: &[u64]) -> Result, KarError> { - read_rows_parallel(self.row_handles(), &self.parts, self.archive_bytes(), self.identity.as_ref(), rows, 32, 512, false) - } - /// An owned reader of the same rows (handles of its own and a copy of the partition table) that another thread - /// can use while this artifact is busy: the prefill reads the rows of the next chunk ahead. - pub fn row_reader(&self) -> Result { - Ok(KarPleRowReader { - files: independent_handles(&self.reader.file, ROW_HANDLES), - parts: self.parts.clone(), - archive_bytes: self.archive_bytes(), - identity: self.identity, - }) - } -} /// Handles a row read spreads its threads over. On Windows each has a file object of its own (a synchronous handle serializes the /// requests made through it, whatever the number of threads: 100,000 random reads of a cold chunk took 10 s that way). const ROW_HANDLES: usize = 16; -/// `n` handles on `file` that can serve reads at the same time; the file itself when no more can be had. -fn independent_handles(file: &File, n: usize) -> Vec { - let mut out = Vec::with_capacity(n); - for _ in 0..n { - match reopen_independent(file) { - Ok(f) => out.push(f), - Err(_) => break, - } - } - if out.is_empty() { - if let Ok(f) = file.try_clone() { - out.push(f); - } - } - out -} -#[cfg(windows)] -fn reopen_independent(file: &File) -> std::io::Result { - leleka_libc_shim::reopen_file_read(file) -} -#[cfg(not(windows))] -fn reopen_independent(file: &File) -> std::io::Result { - // positional reads of one descriptor do not queue behind each other - file.try_clone() -} /// Rows of the PLE table read through an owned handle of the archive (`VerifiedKarPleArtifact::row_reader`): the same /// bytes, bounds and refusals as `read_rows_batch`, usable from a thread of its own. pub struct KarPleRowReader { @@ -1407,193 +206,12 @@ pub struct KarPleRowReader { archive_bytes: u64, identity: Option, } -impl KarPleRowReader { - /// `max_threads` positional-read threads at most (one per 512 rows). - pub fn read_rows(&self, rows: &[u64], max_threads: usize) -> Result, KarError> { - read_rows_parallel(&self.files, &self.parts, self.archive_bytes, self.identity.as_ref(), rows, max_threads, 512, false) - } -} /// A row read (three positional reads) that a warm file serves in this many nanoseconds or less takes the single-thread path. /// Memory-served reads of 10-20 bytes take about 1 us each; a read that waits for a device takes tens of microseconds or more. const WARM_ROW_NS: u128 = 20_000; /// After a cold verdict the next calls read in parallel without probing (a cold file would pay the probe's latency each time). const COLD_SKIP_CALLS: u32 = 256; static COLD_SKIP: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0); -#[allow(clippy::too_many_arguments)] -fn read_rows_parallel( - files: &[File], - parts: &[VerifiedPart], - archive_bytes: u64, - identity: Option<&crate::verify_stamp::FileIdentity>, - rows: &[u64], - max_threads: usize, - min_rows_per_thread: usize, - warm_probe: bool, -) -> Result, KarError> { - let Some(first) = files.first() else { - return Err(KarError::Io(std::io::ErrorKind::NotFound.into())); - }; - if rows.iter().any(|r| *r >= PLE_ROWS) { - return Err(KarError::Range("KAR PLE row outside table")); - } - check_archive_state(first, archive_bytes, identity)?; - let mut packets = Vec::new(); - packets - .try_reserve_exact(rows.len()) - .map_err(|_| KarError::Allocation)?; - packets.resize( - rows.len(), - KarPleRowPacket { - payload: [0; 50], - partition: 0, - }, - ); - // positional reads of a file that is not in the page cache are latency-bound: many in flight - let workers = (rows.len() / min_rows_per_thread.max(1)).clamp(1, max_threads.max(1)); - if warm_probe && workers > 1 { - use std::sync::atomic::Ordering; - if COLD_SKIP.load(Ordering::Relaxed) > 0 { - COLD_SKIP.fetch_sub(1, Ordering::Relaxed); - } else { - let started = std::time::Instant::now(); - read_rows_chunk(first, parts, &rows[..1], &mut packets[..1])?; - if started.elapsed().as_nanos() <= WARM_ROW_NS { - read_rows_chunk(first, parts, &rows[1..], &mut packets[1..])?; - return Ok(packets); - } - COLD_SKIP.store(COLD_SKIP_CALLS, Ordering::Relaxed); - } - } - if workers == 1 { - read_rows_chunk(first, parts, rows, &mut packets)?; - } else { - let per = rows.len().div_ceil(workers); - let results: Vec> = std::thread::scope(|scope| { - let handles: Vec<_> = rows - .chunks(per) - .zip(packets.chunks_mut(per)) - .enumerate() - .map(|(i, (rows, out))| { - let file = &files[i % files.len()]; - scope.spawn(move || read_rows_chunk(file, parts, rows, out)) - }) - .collect(); - handles - .into_iter() - .map(|h| { - h.join() - .unwrap_or(Err(KarError::Format("KAR PLE reader thread panicked"))) - }) - .collect() - }); - for r in results { - r?; - } - } - Ok(packets) -} -/// The per-read guard of the archive: the pinned length, and for an ordinary file the state it had when it was verified. One `fstat` (the -/// length check always did one); a different size, modification time or change time (any write, `touch`, `chmod`, rename or hard link made -/// after verification) is refused rather than served. -fn check_archive_state( - file: &File, - archive_bytes: u64, - identity: Option<&crate::verify_stamp::FileIdentity>, -) -> Result<(), KarError> { - let meta = file.metadata().map_err(KarError::Io)?; - if meta.len() != archive_bytes { - return Err(KarError::Integrity("KAR archive length changed")); - } - if let Some(expected) = identity - && crate::verify_stamp::FileIdentity::of(&meta).as_ref() != Some(expected) - { - return Err(KarError::Integrity("KAR archive file changed since it was verified")); - } - Ok(()) -} - -/// `LELEKA_KAR_IDENTITY_RECHECK=off` (or `0`) turns the per-read comparison with the verified file state off (a file system that does not -/// keep `ctime` stable, for example). Read once; the default is on. -fn identity_recheck_enabled() -> bool { - static ENABLED: std::sync::OnceLock = std::sync::OnceLock::new(); - *ENABLED.get_or_init(|| { - !matches!( - std::env::var("LELEKA_KAR_IDENTITY_RECHECK").as_deref().map(str::trim), - Ok("off" | "0" | "no" | "false") - ) - }) -} - -fn read_rows_chunk( - file: &File, - parts: &[VerifiedPart], - rows: &[u64], - out: &mut [KarPleRowPacket], -) -> Result<(), KarError> { - for (row, packet) in rows.iter().zip(out) { - let index = parts - .partition_point(|p| p.row_base <= *row) - .checked_sub(1) - .ok_or(KarError::Range("KAR PLE partition range"))?; - let p = &parts[index]; - let local = row - p.row_base; - if local >= p.row_count { - return Err(KarError::Range("KAR PLE local row range")); - } - let scale = p - .scales - .checked_add( - local - .checked_mul(10) - .ok_or(KarError::Range("KAR PLE scale overflow"))?, - ) - .ok_or(KarError::Range("KAR PLE scale overflow"))?; - read_at(file, scale, &mut packet.payload[..10])?; - for plane in 0..2usize { - let at = p - .planes - .checked_add( - (plane as u64) - .checked_mul(p.stride) - .ok_or(KarError::Range("KAR PLE plane overflow"))?, - ) - .and_then(|at| local.checked_mul(20).and_then(|n| at.checked_add(n))) - .ok_or(KarError::Range("KAR PLE plane overflow"))?; - read_at(file, at, &mut packet.payload[10 + plane * 20..30 + plane * 20])?; - } - if packet.payload[..10] - .as_chunks::<2>() - .0 - .iter() - .any(|b| u16::from_le_bytes(*b) & 0x7c00 == 0x7c00) - { - return Err(KarError::Profile("KAR PLE nonfinite scale")); - } - packet.partition = - u16::try_from(index).map_err(|_| KarError::Range("KAR PLE partition index"))?; - } - Ok(()) -} -#[cfg(unix)] -fn read_at(file: &File, offset: u64, buffer: &mut [u8]) -> Result<(), KarError> { - use std::os::unix::fs::FileExt; - file.read_exact_at(buffer, offset).map_err(KarError::Io) -} -#[cfg(not(unix))] -fn read_at(file: &File, offset: u64, buffer: &mut [u8]) -> Result<(), KarError> { - use std::os::windows::fs::FileExt; - let mut done = 0; - while done < buffer.len() { - let n = file - .seek_read(&mut buffer[done..], offset + done as u64) - .map_err(KarError::Io)?; - if n == 0 { - return Err(KarError::Io(std::io::ErrorKind::UnexpectedEof.into())); - } - done += n; - } - Ok(()) -} #[path = "kar_nested.rs"] mod nested; @@ -1749,3 +367,25 @@ mod row_read_tests { assert_eq!((KarTrust::AttestedMemfd.as_str(), KarTrust::FullPass.as_str()), ("attested-memfd", "full-pass")); } } + +mod impl_std_fmt_display; +#[allow(unused_imports)] +pub use impl_std_fmt_display::*; +mod decode_record_range; +#[allow(unused_imports)] +pub use decode_record_range::*; +mod inspect_file; +#[allow(unused_imports)] +pub use inspect_file::*; +mod read_region; +#[allow(unused_imports)] +pub use read_region::*; +mod impl_karpleprofile; +#[allow(unused_imports)] +pub use impl_karpleprofile::*; +mod impl_verifiedkarpleartifact; +#[allow(unused_imports)] +pub use impl_verifiedkarpleartifact::*; +mod independent_handles; +#[allow(unused_imports)] +pub use independent_handles::*; diff --git a/crates/model-format/src/kar/decode_record_range.rs b/crates/model-format/src/kar/decode_record_range.rs new file mode 100644 index 00000000..5caced3e --- /dev/null +++ b/crates/model-format/src/kar/decode_record_range.rs @@ -0,0 +1,140 @@ +//! Moved out of the parent module by STRA-338: fn decode_record_range. + +#[allow(unused_imports)] +use super::*; + +pub(super) fn decode_record_range( + file: &mut File, + record: &[u8; RECORD_BYTES], + level: u8, + start: usize, + count: usize, + decoder: ScalarDecoder, +) -> Result, String> { + let elements = usize::try_from(u64_at(record, 48)).map_err(|_| "KAR tensor is too large")?; + let end = start + .checked_add(count) + .ok_or("KAR decode range overflow")?; + if count == 0 || count > 1_000_000 || end > elements { + return Err("CPU KAR decoder requires 1..=1,000,000 values within tensor bounds".into()); + } + if record[7] == 1 { + if record[41] != 0 { + return Err("CPU quality oracle only supports RAW F32 tensors".into()); + } + let offset = u64_at(record, 112) + .checked_add( + (start as u64) + .checked_mul(4) + .ok_or("KAR raw offset overflow")?, + ) + .ok_or("KAR raw offset overflow")?; + let bytes = read_region( + file, + offset, + count.checked_mul(4).ok_or("KAR raw byte count overflow")?, + )?; + return Ok(bytes + .as_chunks::<4>() + .0 + .iter() + .map(|word| f32::from_le_bytes(*word)) + .collect()); + } + let stored = record[42]; + if level == 0 || level > stored { + return Err(format!("KAR tensor stores 1..={stored} levels")); + } + let group = u16_at(record, 46); + let group_size = usize::from(group); + if group_size == 0 { + return Err("KAR group is zero".into()); + } + let padded = usize::try_from(u64_at(record, 56)).map_err(|_| "KAR tensor is too large")?; + let base_group = start / group_size; + let end_group = end.div_ceil(group_size); + let base_element = base_group + .checked_mul(group_size) + .ok_or("KAR decode base overflow")?; + let local_padded = (end_group - base_group) + .checked_mul(group_size) + .ok_or("KAR decode padded size overflow")?; + if base_element + .checked_add(local_padded) + .is_none_or(|end| end > padded) + { + return Err("KAR decode range exceeds padded tensor".into()); + } + let scale_bytes = read_region( + file, + u64_at(record, 64) + .checked_add( + (base_group as u64) + .checked_mul(2) + .ok_or("KAR scale offset overflow")?, + ) + .ok_or("KAR scale offset overflow")?, + (end_group - base_group) + .checked_mul(2) + .ok_or("KAR scale byte count overflow")?, + )?; + let scales = scale_bytes + .as_chunks::<2>() + .0 + .iter() + .map(|pair| u16::from_le_bytes([pair[0], pair[1]])) + .collect::>(); + let book_offset = u64_at(record, 80) + .checked_add((1u64 << (u32::from(level) + 1)) - 4) + .ok_or("KAR book offset overflow")?; + let book_bytes = read_region(file, book_offset, (1usize << level) * 2)?; + let book = book_bytes + .as_chunks::<2>() + .0 + .iter() + .map(|pair| u16::from_le_bytes([pair[0], pair[1]])) + .collect::>(); + let plane_stride = u64::from(u32_at(record, 104)); + let plane_bytes = local_padded / 32 * 4; + let plane_base = u64::try_from( + (base_element / 32) + .checked_mul(4) + .ok_or("KAR plane offset overflow")?, + ) + .map_err(|_| "KAR plane offset overflow")?; + let mut planes = Vec::with_capacity(usize::from(level)); + for plane in 0..u64::from(level) { + let offset = u64_at(record, 96) + .checked_add( + plane + .checked_mul(plane_stride) + .ok_or("KAR plane offset overflow")?, + ) + .and_then(|offset| offset.checked_add(plane_base)) + .ok_or("KAR plane offset overflow")?; + let bytes = read_region(file, offset, plane_bytes)?; + planes.push( + bytes + .as_chunks::<4>() + .0 + .iter() + .map(|word| u32::from_le_bytes([word[0], word[1], word[2], word[3]])) + .collect::>(), + ); + } + let plane_refs = planes.iter().map(Vec::as_slice).collect::>(); + let mut output = Vec::new(); + output + .try_reserve_exact(count) + .map_err(|_| "KAR allocation failed")?; + output.resize(count, 0.0); + decoder( + &scales, + &book, + &plane_refs, + group, + start - base_element, + &mut output, + )?; + Ok(output) +} diff --git a/crates/model-format/src/kar/impl_karpleprofile.rs b/crates/model-format/src/kar/impl_karpleprofile.rs new file mode 100644 index 00000000..6be0d027 --- /dev/null +++ b/crates/model-format/src/kar/impl_karpleprofile.rs @@ -0,0 +1,92 @@ +//! Moved out of the parent module by STRA-338: impl KarPleProfile, impl KarPleRowPacket, fn is_unlinked, fn is_unlinked, impl KarTrust, impl KarStartupRead. + +#[allow(unused_imports)] +use super::*; + +impl KarPleProfile { + /// Bounds validation does not authenticate the manifest's origin. Only the + /// admitted model-binding loader may supply its trusted pinned expectations. + pub fn new(spec: KarPleProfileSpec) -> Result { + Self::with_total_rows(spec, PLE_ROWS) + } + /// `new` for a table of `total_rows` rows: the pinned table has `PLE_ROWS`; tests build miniature archives. + pub(super) fn with_total_rows(spec: KarPleProfileSpec, total_rows: u64) -> Result { + if spec.archive_bytes < 256 + || spec.virtual_f32_bytes == 0 + || spec.parts.is_empty() + || spec.parts.len() > 65535 + || spec.archive_sha256 == [0; 32] + || spec.provenance_sha256 == [0; 32] + || spec.virtual_f32_sha256 == [0; 32] + || spec.native_shard_sha256.contains(&[0; 32]) + { + return Err(KarError::Profile("invalid KAR PLE profile")); + } + let mut next = 0u64; + let mut names = HashSet::new(); + names + .try_reserve(spec.parts.len()) + .map_err(|_| KarError::Allocation)?; + for p in &spec.parts { + if p.name.is_empty() + || p.name.len() > 1024 + || p.name.bytes().any(|b| b < 32 || b == 127) + || !names.insert(p.name.as_str()) + || p.row_base != next + || p.row_count == 0 + || p.derived_f32_sha256 == [0; 32] + { + return Err(KarError::Profile("invalid KAR PLE partition provenance")); + } + next = next + .checked_add(p.row_count) + .filter(|n| *n <= total_rows) + .ok_or(KarError::Range("KAR PLE row count overflow"))?; + p.row_count + .checked_mul(640) + .and_then(|n| p.derived_f32_offset.checked_add(n)) + .filter(|n| *n <= spec.virtual_f32_bytes) + .ok_or(KarError::Range("KAR PLE virtual source range"))?; + } + if next != total_rows { + return Err(KarError::Profile("KAR PLE table extent mismatch")); + } + Ok(Self { spec }) + } + pub fn native_shard_sha256(&self) -> &[[u8; 32]; 2] { + &self.spec.native_shard_sha256 + } +} +impl KarPleRowPacket { + pub fn payload(&self) -> &[u8; 50] { + &self.payload + } + pub fn partition(&self) -> u16 { + self.partition + } +} +#[cfg(unix)] +pub(super) fn is_unlinked(file: &File) -> bool { + use std::os::unix::fs::MetadataExt; + file.metadata().is_ok_and(|m| m.is_file() && m.nlink() == 0) +} + +#[cfg(not(unix))] +pub(super) fn is_unlinked(_file: &File) -> bool { + false +} +impl KarTrust { + pub fn as_str(self) -> &'static str { + match self { + KarTrust::FullPass => "full-pass", + KarTrust::Stamp => "stamp", + KarTrust::AttestedMemfd => "attested-memfd", + KarTrust::SparseExtents => "sparse-extents", + } + } +} +impl KarStartupRead { + pub fn total_bytes(&self) -> u64 { + self.metadata_bytes + self.book_bytes + self.hashed_bytes + } +} diff --git a/crates/model-format/src/kar/impl_std_fmt_display.rs b/crates/model-format/src/kar/impl_std_fmt_display.rs new file mode 100644 index 00000000..dab51582 --- /dev/null +++ b/crates/model-format/src/kar/impl_std_fmt_display.rs @@ -0,0 +1,245 @@ +//! Moved out of the parent module by STRA-338: impl std_fmt_Display, impl std_error_Error, fn typed, impl KarTensorSource, impl KarInspection. + +#[allow(unused_imports)] +use super::*; + +impl std::fmt::Display for KarError { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match self { + Self::Format(s) | Self::Range(s) | Self::Integrity(s) | Self::Profile(s) => { + f.write_str(s) + } + Self::Allocation => f.write_str("KAR allocation failed"), + Self::Io(e) => e.fmt(f), + } + } +} +impl std::error::Error for KarError { + fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { + if let Self::Io(e) = self { + Some(e) + } else { + None + } + } +} +pub(super) fn typed(error: String) -> KarError { + if error == "KAR allocation failed" { + return KarError::Allocation; + } + if error.contains("payload CRC-32 mismatch") { + return KarError::Integrity("KAR payload CRC-32 mismatch"); + } + match error.as_str() { + "CPU KAR decoder requires 1..=1,000,000 values within tensor bounds" => { + KarError::Format("CPU KAR decoder requires 1..=1,000,000 values within tensor bounds") + } + "KAR accounted_bpw does not match archive size" => { + KarError::Format("KAR accounted_bpw does not match archive size") + } + "KAR aggregate metadata mismatch" => KarError::Format("KAR aggregate metadata mismatch"), + "KAR archive length mismatch" => KarError::Format("KAR archive length mismatch"), + "KAR book offset overflow" => KarError::Format("KAR book offset overflow"), + "KAR books offset overflow" => KarError::Format("KAR books offset overflow"), + "KAR coded bit count overflow" => KarError::Format("KAR coded bit count overflow"), + "KAR decode base overflow" => KarError::Format("KAR decode base overflow"), + "KAR decode padded size overflow" => KarError::Format("KAR decode padded size overflow"), + "KAR decode range exceeds padded tensor" => { + KarError::Format("KAR decode range exceeds padded tensor") + } + "KAR decode range overflow" => KarError::Format("KAR decode range overflow"), + "KAR directory digest mismatch" => KarError::Format("KAR directory digest mismatch"), + "KAR directory length overflow" => KarError::Format("KAR directory length overflow"), + "KAR directory overflow" => KarError::Format("KAR directory overflow"), + "KAR group is zero" => KarError::Format("KAR group is zero"), + "KAR header CRC-32 mismatch" => KarError::Format("KAR header CRC-32 mismatch"), + "KAR metadata exceeds bounded inspector limits" => { + KarError::Format("KAR metadata exceeds bounded inspector limits") + } + "KAR model element count overflow" => KarError::Format("KAR model element count overflow"), + "KAR name offset overflow" => KarError::Format("KAR name offset overflow"), + "KAR padded count overflow" => KarError::Format("KAR padded count overflow"), + "KAR padded tensor count mismatch" => KarError::Format("KAR padded tensor count mismatch"), + "KAR plane offset overflow" => KarError::Format("KAR plane offset overflow"), + "KAR plane size overflow" => KarError::Format("KAR plane size overflow"), + "KAR plane stride overflow" => KarError::Format("KAR plane stride overflow"), + "KAR planes offset overflow" => KarError::Format("KAR planes offset overflow"), + "KAR raw byte count overflow" => KarError::Format("KAR raw byte count overflow"), + "KAR raw offset overflow" => KarError::Format("KAR raw offset overflow"), + "KAR raw tensor section is too small" => { + KarError::Format("KAR raw tensor section is too small") + } + "KAR raw tensor size overflow" => KarError::Format("KAR raw tensor size overflow"), + "KAR scale byte count overflow" => KarError::Format("KAR scale byte count overflow"), + "KAR scale count overflow" => KarError::Format("KAR scale count overflow"), + "KAR scale offset overflow" => KarError::Format("KAR scale offset overflow"), + "KAR source identity differs from verified manifest shards" => { + KarError::Format("KAR source identity differs from verified manifest shards") + } + "KAR string table overflow" => KarError::Format("KAR string table overflow"), + "KAR tensor bit count overflow" => KarError::Format("KAR tensor bit count overflow"), + "KAR tensor element count mismatch" => { + KarError::Format("KAR tensor element count mismatch") + } + "KAR tensor is too large" => KarError::Format("KAR tensor is too large"), + "KAR tensor name is not UTF-8" => KarError::Format("KAR tensor name is not UTF-8"), + "KAR tensor section overflow" => KarError::Format("KAR tensor section overflow"), + "KAR tensor sections are not contiguous or bounded" => { + KarError::Format("KAR tensor sections are not contiguous or bounded") + } + "KAR tensor shape overflow" => KarError::Format("KAR tensor shape overflow"), + "KARCHIV2" => KarError::Format("KARCHIV2"), + "duplicate KAR tensor name" => KarError::Format("duplicate KAR tensor name"), + "invalid KAR byte order or record size" => { + KarError::Format("invalid KAR byte order or record size") + } + "invalid KAR flags, digest algorithm, or element counts" => { + KarError::Format("invalid KAR flags, digest algorithm, or element counts") + } + "invalid KAR metadata offsets or alignment" => { + KarError::Format("invalid KAR metadata offsets or alignment") + } + "invalid KAR nested tensor parameters" => { + KarError::Format("invalid KAR nested tensor parameters") + } + "invalid KAR nested tensor section layout" => { + KarError::Format("invalid KAR nested tensor section layout") + } + "invalid KAR raw tensor metadata" => KarError::Format("invalid KAR raw tensor metadata"), + "invalid KAR tensor name bounds" => KarError::Format("invalid KAR tensor name bounds"), + "invalid KAR unused dimension" => KarError::Format("invalid KAR unused dimension"), + "source manifest contains an invalid file name" => { + KarError::Format("source manifest contains an invalid file name") + } + "unsupported KAR archive magic or version" => { + KarError::Format("unsupported KAR archive magic or version") + } + "unsupported KAR tensor layout" => KarError::Format("unsupported KAR tensor layout"), + _ => KarError::Io(std::io::Error::other(error)), + } +} + +impl KarTensorSource { + /// The bytes libkar::kar_reserve stages for this record at the requested + /// level. RAW records have no precision dial and always stage in full. + pub fn gpu_resident_bytes(&self, level: u8) -> Result { + if self.storage_class == 1 { + return Ok(self.section_bytes); + } + if !(1..=8).contains(&level) || level < self.planes_min || level > self.planes_max { + return Err(KarError::Profile("KAR level is outside its supported dial")); + } + self.planes_offset + .checked_sub(self.section_offset) + .and_then(|prefix| { + prefix.checked_add(u64::from(level) * u64::from(self.plane_stride_bytes)) + }) + .filter(|bytes| *bytes <= self.section_bytes) + .ok_or(KarError::Range("invalid KAR GPU prefix size")) + } + + pub fn gpu_decode_bytes(&self) -> Result { + self.n_elements + .checked_mul(4) + .ok_or(KarError::Range("KAR F32 decode size overflow")) + } + + /// One-row output size for a geometrically addressable NESTED table. + /// Whether the model can consume only selected rows is a separate question. + pub fn gpu_one_row_decode_bytes(&self) -> Option { + let row_len = *self.dimensions.first()?; + if self.storage_class == 0 + && self.dimensions.len() >= 2 + && row_len.is_multiple_of(32) + && row_len <= u32::MAX as u64 + && self.n_elements > row_len + && self.n_elements.is_multiple_of(row_len) + { + row_len.checked_mul(4) + } else { + None + } + } +} +impl KarInspection { + pub fn inspect(file: File) -> Result { + let Parsed { + summary, + file, + sections, + sources, + directory, + payload_offset, + metadata_bytes, + } = inspect_file(file).map_err(typed)?; + Ok(Self { + summary, + file, + sections, + sources, + directory, + payload_offset, + metadata_bytes, + }) + } + pub fn summary(&self) -> &KarSummary { + &self.summary + } + pub fn tensor_sources(&self) -> &[KarTensorSource] { + &self.sources + } + pub fn verify_payloads(&mut self) -> Result<(), KarError> { + let mut buffer = Vec::new(); + buffer + .try_reserve_exact(8 * 1024 * 1024) + .map_err(|_| KarError::Allocation)?; + buffer.resize(8 * 1024 * 1024, 0); + for section in &self.sections { + self.file + .seek(SeekFrom::Start(section.offset)) + .map_err(KarError::Io)?; + let mut remaining = section.bytes; + let mut crc = !0u32; + while remaining > 0 { + let n = remaining.min(buffer.len() as u64) as usize; + self.file + .read_exact(&mut buffer[..n]) + .map_err(KarError::Io)?; + crc = crc32_step(crc, &buffer[..n]); + remaining -= n as u64; + } + if !crc != section.crc32 { + return Err(KarError::Integrity("KAR payload CRC-32 mismatch")); + } + } + Ok(()) + } + pub(super) fn verify_integrity(&mut self, bytes: u64, pin: &[u8; 32]) -> Result<(), KarError> { + verify_integrity_pipelined(&self.file, &self.sections, bytes, pin) + } + pub fn decode_range( + &mut self, + name: &str, + level: u8, + start: usize, + count: usize, + decoder: ScalarDecoder, + ) -> Result, KarError> { + let index = self + .sources + .iter() + .position(|s| s.name == name) + .ok_or(KarError::Range("KAR tensor not found"))?; + let record: [u8; RECORD_BYTES] = self.directory + [index * RECORD_BYTES..(index + 1) * RECORD_BYTES] + .try_into() + .expect("validated directory"); + decode_record_range(&mut self.file, &record, level, start, count, decoder).map_err(typed) + } + /// Trusted-owner contract, not an OS/stat check: the caller establishes that + /// the retained inode has been immutable since inspection and remains so + /// for the entire binding lifetime. A read-only descriptor alone is insufficient. + pub fn into_owner_controlled(self) -> KarImmutableSource { + KarImmutableSource { inspection: self } + } +} diff --git a/crates/model-format/src/kar/impl_verifiedkarpleartifact.rs b/crates/model-format/src/kar/impl_verifiedkarpleartifact.rs new file mode 100644 index 00000000..c5292fe6 --- /dev/null +++ b/crates/model-format/src/kar/impl_verifiedkarpleartifact.rs @@ -0,0 +1,239 @@ +//! Moved out of the parent module by STRA-338: impl VerifiedKarPleArtifact. + +#[allow(unused_imports)] +use super::*; + +impl VerifiedKarPleArtifact { + pub fn verify(source: KarImmutableSource, profile: KarPleProfile) -> Result { + Self::verify_with(source, profile, None) + } + /// `verify` for a sealed memfd that holds only the bytes the serve path reads (holes elsewhere, same file offsets and + /// length): the full-archive SHA-256 and the payload CRCs cannot be computed, so the pinned `extents_sha256` + /// ([`digest_extents_with`] over `serve_extents`, measured once from the archive that matched its full pin) stands + /// in for them, and the directory digest in the header (checked by `inspect`, inside the extents) covers the rest. + /// Fails closed: a wrong digest, a read range outside the extents or a changed length is an error. + pub fn verify_sparse(source: KarImmutableSource, profile: KarPleProfile, extents_sha256: &[u8; 32]) -> Result { + Self::verify_with(source, profile, Some(extents_sha256)) + } + pub(super) fn verify_with(source: KarImmutableSource, profile: KarPleProfile, sparse_pin: Option<&[u8; 32]>) -> Result { + let mut reader = source.inspection; + if reader.file.metadata().map_err(KarError::Io)?.len() != profile.spec.archive_bytes + || reader.summary.archive_bytes != profile.spec.archive_bytes + || reader.summary.source_bytes != profile.spec.virtual_f32_bytes + || reader.summary.source_digest != profile.spec.virtual_f32_sha256 + { + return Err(KarError::Integrity( + "KAR archive/provenance identity mismatch", + )); + } + // A stamp for exactly this file in exactly this state (see verify_stamp.rs) stands in for the full + // SHA-256 + CRC pass; a sealed memfd has no stable identity and always takes the full pass. + let identity = reader + .file + .metadata() + .ok() + .and_then(|m| crate::verify_stamp::FileIdentity::of(&m)); + let stamps = crate::verify_stamp::global(); + // An unlinked sealed memfd: only if the parent attested the copy (see `set_attested_archive`). + let attested_memfd = identity.is_none() && crate::verify_stamp::attested_archive() && is_unlinked(&reader.file); + let stamped = matches!((stamps, identity.as_ref()), (Some(s), Some(id)) if s.trusts("kar", &profile.spec.archive_sha256, id)); + let trusted = attested_memfd || stamped; + let trust = if sparse_pin.is_some() { + KarTrust::SparseExtents + } else if attested_memfd { + KarTrust::AttestedMemfd + } else if stamped { + KarTrust::Stamp + } else { + KarTrust::FullPass + }; + // A sparse copy never takes a stamp or an attestation: those speak for the whole archive, which it does not hold. + if sparse_pin.is_none() && !trusted { + reader.verify_integrity(profile.spec.archive_bytes, &profile.spec.archive_sha256)?; + if let (Some(stamps), Some(before)) = (stamps, identity) + && reader + .file + .metadata() + .ok() + .and_then(|m| crate::verify_stamp::FileIdentity::of(&m)) + == Some(before) + { + let _ = stamps.record("kar", &profile.spec.archive_sha256, &before); + } + } + let mut parts = Vec::new(); + let mut books = Vec::new(); + let mut book_at_list = Vec::new(); + parts + .try_reserve_exact(profile.spec.parts.len()) + .map_err(|_| KarError::Allocation)?; + books + .try_reserve_exact(profile.spec.parts.len()) + .map_err(|_| KarError::Allocation)?; + for p in &profile.spec.parts { + let index = reader + .sources + .iter() + .position(|s| s.name == p.name) + .ok_or(KarError::Profile("KAR PLE partition missing"))?; + let s = &reader.sources[index]; + let record = &reader.directory[index * 192..(index + 1) * 192]; + if s.dimensions != [160, p.row_count] + || s.dtype != 0 + || s.storage_class != 0 + || record[45] != 0 + || u16_at(record, 46) != 32 + || s.planes_min > 2 + || s.planes_max < 2 + || s.digest != p.derived_f32_sha256 + || s.offset != p.derived_f32_offset + { + return Err(KarError::Profile( + "KAR PLE partition/source mapping mismatch", + )); + } + let scales = u64_at(record, 64); + let planes = s.planes_offset; + let stride = u64::from(s.plane_stride_bytes); + let book_at = u64_at(record, 80) + .checked_add(4) + .ok_or(KarError::Range("KAR PLE book overflow"))?; + let bytes = read_region(&mut reader.file, book_at, 8).map_err(typed)?; + let book = std::array::from_fn(|i| u16_at(&bytes, i * 2)); + if book.iter().any(|b| b & 0x7c00 == 0x7c00) { + return Err(KarError::Profile("KAR PLE nonfinite book")); + } + parts.push(VerifiedPart { + row_base: p.row_base, + row_count: p.row_count, + scales, + planes, + stride, + }); + books.push(book); + book_at_list.push(book_at); + } + let serve_extents = normalize_extents( + &extents::exact_reads(reader.payload_offset, &parts, &book_at_list)?, + profile.spec.archive_bytes, + )?; + if let Some(pin) = sparse_pin { + // Every byte a row read can touch lies inside the extents (a row read is bounded by its partition), so no + // read can land in a hole; then the bytes of the extents must be the pinned ones. + for part in &parts { + for read in part.reads()? { + if !extents_cover(&serve_extents, read.offset, read.len) { + return Err(KarError::Range("KAR PLE read outside the sparse extents")); + } + } + } + let digest = digest_extents(&reader.file, &serve_extents, |_| {})?; + if &digest != pin { + return Err(KarError::Integrity("KAR sparse extents SHA-256 mismatch")); + } + } + let after = reader.file.metadata().map_err(KarError::Io)?; + if after.len() != profile.spec.archive_bytes { + return Err(KarError::Integrity("KAR archive length changed")); + } + // An ordinary file must be in the very state that was verified (or stamped) at the start of this call. + if identity.is_some() && crate::verify_stamp::FileIdentity::of(&after) != identity { + return Err(KarError::Integrity("KAR archive file changed while it was verified")); + } + let startup = KarStartupRead { + trust, + metadata_bytes: reader.metadata_bytes, + book_bytes: 8 * parts.len() as u64, + hashed_bytes: if sparse_pin.is_some() { + extents_bytes(&serve_extents) + } else if trusted { + 0 + } else { + profile.spec.archive_bytes + }, + }; + Ok(Self { + reader, + profile, + parts, + books, + handles: std::sync::OnceLock::new(), + serve_extents, + sparse: sparse_pin.is_some(), + startup, + identity: if identity_recheck_enabled() { identity } else { None }, + }) + } + /// The ranges of the archive the serve path reads (page-aligned, sorted, merged). + pub fn serve_extents(&self) -> &[Extent] { + &self.serve_extents + } + /// Verified as a sparse copy (by the digest of its extents, not the whole archive). + pub fn is_sparse(&self) -> bool { + self.sparse + } + /// What opening this archive read from it, for the startup log (`KarStartupRead`). + pub fn startup_read(&self) -> KarStartupRead { + self.startup + } + /// True when row reads compare the open file with its verified state (an ordinary file, not a memfd). + pub fn rechecks_file_identity(&self) -> bool { + self.identity.is_some() + } + pub fn archive_sha256(&self) -> &[u8; 32] { + &self.profile.spec.archive_sha256 + } + pub fn archive_bytes(&self) -> u64 { + self.profile.spec.archive_bytes + } + /// Digest of the trusted provenance manifest; never the archive/source digest. + pub fn profile_sha256(&self) -> &[u8; 32] { + &self.profile.spec.provenance_sha256 + } + pub fn native_shard_sha256(&self) -> &[[u8; 32]; 2] { + &self.profile.spec.native_shard_sha256 + } + pub fn row_count(&self) -> u64 { + PLE_ROWS + } + pub fn partition_books(&self) -> &[[u16; 4]] { + &self.books + } + pub fn read_rows(&mut self, rows: &[u64; 16]) -> Result<[KarPleRowPacket; 16], KarError> { + if rows.iter().any(|r| *r >= PLE_ROWS) { + return Err(KarError::Range("KAR PLE row outside table")); + } + // 16 rows are 48 random reads of a cold file: eight threads on handles of their own, two rows each. A file the page cache + // holds answers each read in about a microsecond, and eight thread starts and joins then cost more than the reads + // (about 0.1 ms per token of a decode window); `warm_probe` reads the first row on this thread, times it, and reads the + // other fifteen here too when it was served from memory. + let packets = read_rows_parallel(self.row_handles(), &self.parts, self.archive_bytes(), self.identity.as_ref(), rows, 8, 2, true)?; + let mut out = [KarPleRowPacket { + payload: [0; 50], + partition: 0, + }; 16]; + out.copy_from_slice(&packets); + Ok(out) + } + /// Handles with a file object of their own (so reads through two of them can be in flight at once). + pub(super) fn row_handles(&self) -> &[File] { + self.handles + .get_or_init(|| independent_handles(&self.reader.file, ROW_HANDLES)) + } + /// `read_rows` over any number of rows: the same three region reads per row, the same bounds and non-finite + /// scale refusals, but positional (`pread`, no seek) and split over a few threads, because the batched prefill + /// reads every row of a chunk the cache does not hold at once (tens of thousands on a cold chunk). + pub fn read_rows_batch(&self, rows: &[u64]) -> Result, KarError> { + read_rows_parallel(self.row_handles(), &self.parts, self.archive_bytes(), self.identity.as_ref(), rows, 32, 512, false) + } + /// An owned reader of the same rows (handles of its own and a copy of the partition table) that another thread + /// can use while this artifact is busy: the prefill reads the rows of the next chunk ahead. + pub fn row_reader(&self) -> Result { + Ok(KarPleRowReader { + files: independent_handles(&self.reader.file, ROW_HANDLES), + parts: self.parts.clone(), + archive_bytes: self.archive_bytes(), + identity: self.identity, + }) + } +} diff --git a/crates/model-format/src/kar/independent_handles.rs b/crates/model-format/src/kar/independent_handles.rs new file mode 100644 index 00000000..16d07ff2 --- /dev/null +++ b/crates/model-format/src/kar/independent_handles.rs @@ -0,0 +1,211 @@ +//! Moved out of the parent module by STRA-338: fn independent_handles, fn reopen_independent, fn reopen_independent, impl KarPleRowReader, fn read_rows_parallel, fn check_archive_state .... + +#[allow(unused_imports)] +use super::*; + +/// `n` handles on `file` that can serve reads at the same time; the file itself when no more can be had. +pub(super) fn independent_handles(file: &File, n: usize) -> Vec { + let mut out = Vec::with_capacity(n); + for _ in 0..n { + match reopen_independent(file) { + Ok(f) => out.push(f), + Err(_) => break, + } + } + if out.is_empty() { + if let Ok(f) = file.try_clone() { + out.push(f); + } + } + out +} +#[cfg(windows)] +pub(super) fn reopen_independent(file: &File) -> std::io::Result { + leleka_libc_shim::reopen_file_read(file) +} +#[cfg(not(windows))] +pub(super) fn reopen_independent(file: &File) -> std::io::Result { + // positional reads of one descriptor do not queue behind each other + file.try_clone() +} +impl KarPleRowReader { + /// `max_threads` positional-read threads at most (one per 512 rows). + pub fn read_rows(&self, rows: &[u64], max_threads: usize) -> Result, KarError> { + read_rows_parallel(&self.files, &self.parts, self.archive_bytes, self.identity.as_ref(), rows, max_threads, 512, false) + } +} +#[allow(clippy::too_many_arguments)] +pub(super) fn read_rows_parallel( + files: &[File], + parts: &[VerifiedPart], + archive_bytes: u64, + identity: Option<&crate::verify_stamp::FileIdentity>, + rows: &[u64], + max_threads: usize, + min_rows_per_thread: usize, + warm_probe: bool, +) -> Result, KarError> { + let Some(first) = files.first() else { + return Err(KarError::Io(std::io::ErrorKind::NotFound.into())); + }; + if rows.iter().any(|r| *r >= PLE_ROWS) { + return Err(KarError::Range("KAR PLE row outside table")); + } + check_archive_state(first, archive_bytes, identity)?; + let mut packets = Vec::new(); + packets + .try_reserve_exact(rows.len()) + .map_err(|_| KarError::Allocation)?; + packets.resize( + rows.len(), + KarPleRowPacket { + payload: [0; 50], + partition: 0, + }, + ); + // positional reads of a file that is not in the page cache are latency-bound: many in flight + let workers = (rows.len() / min_rows_per_thread.max(1)).clamp(1, max_threads.max(1)); + if warm_probe && workers > 1 { + use std::sync::atomic::Ordering; + if COLD_SKIP.load(Ordering::Relaxed) > 0 { + COLD_SKIP.fetch_sub(1, Ordering::Relaxed); + } else { + let started = std::time::Instant::now(); + read_rows_chunk(first, parts, &rows[..1], &mut packets[..1])?; + if started.elapsed().as_nanos() <= WARM_ROW_NS { + read_rows_chunk(first, parts, &rows[1..], &mut packets[1..])?; + return Ok(packets); + } + COLD_SKIP.store(COLD_SKIP_CALLS, Ordering::Relaxed); + } + } + if workers == 1 { + read_rows_chunk(first, parts, rows, &mut packets)?; + } else { + let per = rows.len().div_ceil(workers); + let results: Vec> = std::thread::scope(|scope| { + let handles: Vec<_> = rows + .chunks(per) + .zip(packets.chunks_mut(per)) + .enumerate() + .map(|(i, (rows, out))| { + let file = &files[i % files.len()]; + scope.spawn(move || read_rows_chunk(file, parts, rows, out)) + }) + .collect(); + handles + .into_iter() + .map(|h| { + h.join() + .unwrap_or(Err(KarError::Format("KAR PLE reader thread panicked"))) + }) + .collect() + }); + for r in results { + r?; + } + } + Ok(packets) +} +/// The per-read guard of the archive: the pinned length, and for an ordinary file the state it had when it was verified. One `fstat` (the +/// length check always did one); a different size, modification time or change time (any write, `touch`, `chmod`, rename or hard link made +/// after verification) is refused rather than served. +pub(super) fn check_archive_state( + file: &File, + archive_bytes: u64, + identity: Option<&crate::verify_stamp::FileIdentity>, +) -> Result<(), KarError> { + let meta = file.metadata().map_err(KarError::Io)?; + if meta.len() != archive_bytes { + return Err(KarError::Integrity("KAR archive length changed")); + } + if let Some(expected) = identity + && crate::verify_stamp::FileIdentity::of(&meta).as_ref() != Some(expected) + { + return Err(KarError::Integrity("KAR archive file changed since it was verified")); + } + Ok(()) +} + +/// `LELEKA_KAR_IDENTITY_RECHECK=off` (or `0`) turns the per-read comparison with the verified file state off (a file system that does not +/// keep `ctime` stable, for example). Read once; the default is on. +pub(super) fn identity_recheck_enabled() -> bool { + static ENABLED: std::sync::OnceLock = std::sync::OnceLock::new(); + *ENABLED.get_or_init(|| { + !matches!( + std::env::var("LELEKA_KAR_IDENTITY_RECHECK").as_deref().map(str::trim), + Ok("off" | "0" | "no" | "false") + ) + }) +} + +pub(super) fn read_rows_chunk( + file: &File, + parts: &[VerifiedPart], + rows: &[u64], + out: &mut [KarPleRowPacket], +) -> Result<(), KarError> { + for (row, packet) in rows.iter().zip(out) { + let index = parts + .partition_point(|p| p.row_base <= *row) + .checked_sub(1) + .ok_or(KarError::Range("KAR PLE partition range"))?; + let p = &parts[index]; + let local = row - p.row_base; + if local >= p.row_count { + return Err(KarError::Range("KAR PLE local row range")); + } + let scale = p + .scales + .checked_add( + local + .checked_mul(10) + .ok_or(KarError::Range("KAR PLE scale overflow"))?, + ) + .ok_or(KarError::Range("KAR PLE scale overflow"))?; + read_at(file, scale, &mut packet.payload[..10])?; + for plane in 0..2usize { + let at = p + .planes + .checked_add( + (plane as u64) + .checked_mul(p.stride) + .ok_or(KarError::Range("KAR PLE plane overflow"))?, + ) + .and_then(|at| local.checked_mul(20).and_then(|n| at.checked_add(n))) + .ok_or(KarError::Range("KAR PLE plane overflow"))?; + read_at(file, at, &mut packet.payload[10 + plane * 20..30 + plane * 20])?; + } + if packet.payload[..10] + .as_chunks::<2>() + .0 + .iter() + .any(|b| u16::from_le_bytes(*b) & 0x7c00 == 0x7c00) + { + return Err(KarError::Profile("KAR PLE nonfinite scale")); + } + packet.partition = + u16::try_from(index).map_err(|_| KarError::Range("KAR PLE partition index"))?; + } + Ok(()) +} +#[cfg(unix)] +pub(super) fn read_at(file: &File, offset: u64, buffer: &mut [u8]) -> Result<(), KarError> { + use std::os::unix::fs::FileExt; + file.read_exact_at(buffer, offset).map_err(KarError::Io) +} +#[cfg(not(unix))] +pub(super) fn read_at(file: &File, offset: u64, buffer: &mut [u8]) -> Result<(), KarError> { + use std::os::windows::fs::FileExt; + let mut done = 0; + while done < buffer.len() { + let n = file + .seek_read(&mut buffer[done..], offset + done as u64) + .map_err(KarError::Io)?; + if n == 0 { + return Err(KarError::Io(std::io::ErrorKind::UnexpectedEof.into())); + } + done += n; + } + Ok(()) +} diff --git a/crates/model-format/src/kar/inspect_file.rs b/crates/model-format/src/kar/inspect_file.rs new file mode 100644 index 00000000..5b67e302 --- /dev/null +++ b/crates/model-format/src/kar/inspect_file.rs @@ -0,0 +1,286 @@ +//! Moved out of the parent module by STRA-338: fn inspect_file. + +#[allow(unused_imports)] +use super::*; + +pub(super) fn inspect_file(mut file: File) -> Result { + let file_bytes = file.metadata().map_err(|error| error.to_string())?.len(); + let header = read_region(&mut file, 0, HEADER_BYTES)?; + if &header[0..8] != b"KARCHIV2" || u32_at(&header, 8) != 2 { + return Err("unsupported KAR archive magic or version".into()); + } + if u32_at(&header, 12) != 0x04030201 + || u32_at(&header, 16) != HEADER_BYTES as u32 + || u32_at(&header, 20) != RECORD_BYTES as u32 + { + return Err("invalid KAR byte order or record size".into()); + } + if crc32(&header[..192]) != u32_at(&header, 192) { + return Err("KAR header CRC-32 mismatch".into()); + } + let directory_offset = u64_at(&header, 24); + let tensor_count = u32_at(&header, 32); + let string_offset = u64_at(&header, 40); + let string_bytes = u64_at(&header, 48); + let payload_offset = u64_at(&header, 56); + let archive_bytes = u64_at(&header, 64); + let total_elements = u64_at(&header, 72); + let payload_bits = u64_at(&header, 80); + let source_total_elements = u64_at(&header, 88); + let source_bytes = u64_at(&header, 120); + let accounted_bpw = f64::from_le_bytes(header[96..104].try_into().unwrap()); + let mut source_digest = [0; 32]; + source_digest.copy_from_slice(&header[128..160]); + if archive_bytes != file_bytes || archive_bytes < HEADER_BYTES as u64 { + return Err("KAR archive length mismatch".into()); + } + if tensor_count == 0 || tensor_count as usize > MAX_TENSORS || string_bytes > MAX_NAMES as u64 { + return Err("KAR metadata exceeds bounded inspector limits".into()); + } + if u32_at(&header, 36) != 0 + || header[106] != 1 + || total_elements == 0 + || total_elements > source_total_elements + || source_bytes == 0 + { + return Err("invalid KAR flags, digest algorithm, or element counts".into()); + } + let expected_bpw = archive_bytes as f64 * 8.0 / total_elements as f64; + if !accounted_bpw.is_finite() + || ((accounted_bpw - expected_bpw) / expected_bpw).abs() > 2f64.powi(-40) + { + return Err("KAR accounted_bpw does not match archive size".into()); + } + let directory_bytes = (tensor_count as u64) + .checked_mul(RECORD_BYTES as u64) + .ok_or("KAR directory length overflow")?; + let directory_end = directory_offset + .checked_add(directory_bytes) + .ok_or("KAR directory overflow")?; + let string_end = string_offset + .checked_add(string_bytes) + .ok_or("KAR string table overflow")?; + if !directory_offset.is_multiple_of(64) + || !string_offset.is_multiple_of(64) + || !payload_offset.is_multiple_of(256) + || directory_offset < HEADER_BYTES as u64 + || directory_end > string_offset + || string_end > payload_offset + || payload_offset > archive_bytes + { + return Err("invalid KAR metadata offsets or alignment".into()); + } + let names = read_region(&mut file, string_offset, string_bytes as usize)?; + let directory = read_region(&mut file, directory_offset, directory_bytes as usize)?; + let mut digest = Sha256::new(); + digest.update(&names); + digest.update(&directory); + if digest.finalize().as_slice() != &header[160..192] { + return Err("KAR directory digest mismatch".into()); + } + + let mut seen_names = HashSet::new(); + seen_names + .try_reserve(tensor_count as usize) + .map_err(|_| "KAR allocation failed")?; + let mut elements_sum = 0u64; + let mut bits_sum = 0u64; + let mut previous_end = payload_offset; + let mut min_planes = u8::MAX; + let mut max_planes = 0u8; + let mut sections = Vec::new(); + sections + .try_reserve_exact(tensor_count as usize) + .map_err(|_| "KAR allocation failed")?; + let mut sources = Vec::new(); + sources + .try_reserve_exact(tensor_count as usize) + .map_err(|_| "KAR allocation failed")?; + let (records, remainder) = directory.as_chunks::(); + debug_assert!(remainder.is_empty()); + for record in records { + let name_start = u32_at(record, 0) as usize; + let name_len = u16_at(record, 4) as usize; + let name_end = name_start + .checked_add(name_len) + .ok_or("KAR name offset overflow")?; + if name_end >= names.len() || names[name_end] != 0 { + return Err("invalid KAR tensor name bounds".into()); + } + let name = std::str::from_utf8(&names[name_start..name_end]) + .map_err(|_| "KAR tensor name is not UTF-8")?; + if !seen_names.insert(name) { + return Err("duplicate KAR tensor name".into()); + } + let n_dims = record[6] as usize; + let storage = record[7]; + if !(1..=4).contains(&n_dims) || storage > 1 || record[40] != 0 || record[41] > 2 { + return Err("unsupported KAR tensor layout".into()); + } + let dims = (0..4) + .map(|index| u64_at(record, 8 + index * 8)) + .collect::>(); + if dims[n_dims..].iter().any(|dim| *dim != 1) { + return Err("invalid KAR unused dimension".into()); + } + let product = dims[..n_dims] + .iter() + .try_fold(1u64, |acc, dim| acc.checked_mul(*dim)) + .ok_or("KAR tensor shape overflow")?; + let n_elements = u64_at(record, 48); + if product != n_elements || n_elements == 0 { + return Err("KAR tensor element count mismatch".into()); + } + elements_sum = elements_sum + .checked_add(n_elements) + .ok_or("KAR model element count overflow")?; + let mut source_digest = [0u8; 32]; + source_digest.copy_from_slice(&record[128..160]); + sources.push(KarTensorSource { + name: name.to_owned(), + dimensions: dims[..n_dims].to_vec(), + dtype: record[41], + digest: source_digest, + offset: u64_at(record, 160), + section_bytes: u64_at(record, 120), + storage_class: storage, + n_elements, + planes_min: record[43], + planes_max: record[44], + section_offset: u64_at(record, 112), + planes_offset: u64_at(record, 96), + plane_stride_bytes: u32_at(record, 104), + }); + let section_offset = u64_at(record, 112); + let section_bytes = u64_at(record, 120); + let section_end = section_offset + .checked_add(section_bytes) + .ok_or("KAR tensor section overflow")?; + if section_offset != previous_end + || !section_offset.is_multiple_of(256) + || section_end > archive_bytes + { + return Err("KAR tensor sections are not contiguous or bounded".into()); + } + previous_end = section_end; + sections.push(Section { + offset: section_offset, + bytes: section_bytes, + crc32: u32_at(record, 108), + }); + if storage == 0 { + let group = u16_at(record, 46) as u64; + let planes = record[42]; + let n_padded = u64_at(record, 56); + if group == 0 + || group > 1024 + || !group.is_multiple_of(32) + || !(1..=16).contains(&planes) + || record[43] == 0 + || record[43] > record[44] + || record[44] > planes + || record[45] > 1 + { + return Err("invalid KAR nested tensor parameters".into()); + } + let rounded = n_elements + .div_ceil(group) + .checked_mul(group) + .ok_or("KAR padded count overflow")?; + if n_padded != rounded { + return Err("KAR padded tensor count mismatch".into()); + } + let scales_offset = u64_at(record, 64); + let scales_bytes = u64_at(record, 72); + let books_offset = u64_at(record, 80); + let books_bytes = u64_at(record, 88); + let planes_offset = u64_at(record, 96); + let stride = u32_at(record, 104) as u64; + let expected_scales = (n_padded / group) + .checked_mul(2) + .ok_or("KAR scale count overflow")?; + let expected_books = (1u64 << (planes as u32 + 2)) - 4; + let plane_words_bytes = (n_padded / 32) + .checked_mul(4) + .ok_or("KAR plane size overflow")?; + let expected_stride = + round_up(plane_words_bytes, 16).ok_or("KAR plane stride overflow")?; + let books_start = scales_offset + .checked_add(scales_bytes) + .and_then(|value| round_up(value, 16)) + .ok_or("KAR books offset overflow")?; + let planes_start = books_offset + .checked_add(books_bytes) + .and_then(|value| round_up(value, 16)) + .ok_or("KAR planes offset overflow")?; + if scales_offset != section_offset + || scales_bytes != expected_scales + || books_offset != books_start + || books_bytes != expected_books + || planes_offset != planes_start + || stride != expected_stride + || planes_offset + .checked_add(planes as u64 * stride) + .is_none_or(|end| end > section_end) + { + return Err("invalid KAR nested tensor section layout".into()); + } + let tensor_bits = (planes as u64) + .checked_mul(n_padded) + .and_then(|bits| { + (n_padded / group) + .checked_mul(16) + .and_then(|scale_bits| bits.checked_add(scale_bits)) + }) + .ok_or("KAR tensor bit count overflow")?; + bits_sum = bits_sum + .checked_add(tensor_bits) + .ok_or("KAR coded bit count overflow")?; + min_planes = min_planes.min(record[43]); + max_planes = max_planes.max(record[44]); + } else { + if record[42..48].iter().any(|value| *value != 0) + || u64_at(record, 56) != n_elements + || record[64..104].iter().any(|value| *value != 0) + || u32_at(record, 104) != 0 + { + return Err("invalid KAR raw tensor metadata".into()); + } + let width = if record[41] == 0 { 4 } else { 2 }; + if section_bytes + < n_elements + .checked_mul(width) + .ok_or("KAR raw tensor size overflow")? + { + return Err("KAR raw tensor section is too small".into()); + } + } + } + if previous_end != archive_bytes + || elements_sum != total_elements + || bits_sum != payload_bits + || header[104] != if min_planes == u8::MAX { 0 } else { min_planes } + || header[105] != max_planes + { + return Err("KAR aggregate metadata mismatch".into()); + } + let summary = KarSummary { + archive_bytes, + tensor_count, + total_elements, + source_total_elements, + accounted_bpw, + source_digest, + source_bytes, + max_planes, + }; + Ok(Parsed { + summary, + file, + sections, + sources, + directory, + payload_offset, + metadata_bytes: HEADER_BYTES as u64 + string_bytes + directory_bytes, + }) +} diff --git a/crates/model-format/src/kar/read_region.rs b/crates/model-format/src/kar/read_region.rs new file mode 100644 index 00000000..44303bce --- /dev/null +++ b/crates/model-format/src/kar/read_region.rs @@ -0,0 +1,204 @@ +//! Moved out of the parent module by STRA-338: fn read_region, fn u16_at, fn u32_at, fn u64_at, fn crc32, fn crc32_step .... + +#[allow(unused_imports)] +use super::*; + + +pub(super) fn read_region(file: &mut File, offset: u64, length: usize) -> Result, String> { + file.seek(SeekFrom::Start(offset)) + .map_err(|error| error.to_string())?; + let mut bytes = Vec::new(); + bytes + .try_reserve_exact(length) + .map_err(|_| "KAR allocation failed")?; + bytes.resize(length, 0); + file.read_exact(&mut bytes) + .map_err(|error| error.to_string())?; + Ok(bytes) +} + +pub(super) fn u16_at(bytes: &[u8], offset: usize) -> u16 { + u16::from_le_bytes(bytes[offset..offset + 2].try_into().unwrap()) +} + +pub(super) fn u32_at(bytes: &[u8], offset: usize) -> u32 { + u32::from_le_bytes(bytes[offset..offset + 4].try_into().unwrap()) +} + +pub(super) fn u64_at(bytes: &[u8], offset: usize) -> u64 { + u64::from_le_bytes(bytes[offset..offset + 8].try_into().unwrap()) +} + +pub fn crc32(bytes: &[u8]) -> u32 { + !crc32_step(!0u32, bytes) +} +pub fn crc32_step(mut crc: u32, bytes: &[u8]) -> u32 { + let (blocks, tail) = bytes.as_chunks::<8>(); + for block in blocks { + let first = u32::from_le_bytes([block[0], block[1], block[2], block[3]]) ^ crc; + crc = CRC32_SLICES[6][(first & 255) as usize] + ^ CRC32_SLICES[5][((first >> 8) & 255) as usize] + ^ CRC32_SLICES[4][((first >> 16) & 255) as usize] + ^ CRC32_SLICES[3][(first >> 24) as usize] + ^ CRC32_SLICES[2][usize::from(block[4])] + ^ CRC32_SLICES[1][usize::from(block[5])] + ^ CRC32_SLICES[0][usize::from(block[6])] + ^ CRC32_TABLE[usize::from(block[7])]; + } + // Preserve the original scalar transition for all remaining zero to seven bytes. + for &byte in tail { + crc = (crc >> 8) ^ CRC32_TABLE[((crc ^ u32::from(byte)) & 255) as usize]; + } + crc +} + +/// Inspect has already admitted contiguous sections. Recheck their bounds here +/// before consuming bytes, including in the small streaming regression seam. +pub(super) fn integrity_sections(sections: &[Section], bytes: u64) -> Result<(), KarError> { + let mut end = sections.first().map_or(bytes, |s| s.offset); + for section in sections { + if section.offset != end || section.bytes == 0 { + return Err(KarError::Range("KAR integrity section bounds")); + } + end = end + .checked_add(section.bytes) + .filter(|end| *end <= bytes) + .ok_or(KarError::Range("KAR integrity section bounds"))?; + } + if sections.is_empty() || end != bytes { + return Err(KarError::Range("KAR integrity section bounds")); + } + Ok(()) +} + +/// The production form of [`verify_integrity_stream`]: one reader thread keeps chunks coming, SHA-256 of the +/// whole archive runs on the calling thread and the per-section CRC-32 on a second one, so the pass costs the +/// slower of the two instead of the read plus both. Same verdicts, same precedence: a SHA mismatch (or a short +/// archive) is reported before a CRC failure, and a CRC failure never shortcuts the full hash. +pub(super) fn verify_integrity_pipelined( + file: &File, + sections: &[Section], + bytes: u64, + pin: &[u8; 32], +) -> Result<(), KarError> { + integrity_sections(sections, bytes)?; + let (digest, total, crc) = crate::readahead::with_read_ahead(file, 0, bytes, 2, |mut receivers| { + let crc_rx = receivers.pop().expect("two receivers"); + let sha_rx = receivers.pop().expect("two receivers"); + std::thread::scope(|scope| { + let crc_thread = scope.spawn(move || -> std::io::Result<(bool, usize)> { + let (mut index, mut total, mut crc, mut failed) = (0usize, 0u64, !0u32, false); + for item in crc_rx { + let chunk = item?; + let end = total + chunk.len() as u64; + while let Some(section) = sections.get(index) { + if section.offset >= end { + break; + } + let section_end = section.offset + section.bytes; // Checked by integrity_sections. + let start = total.max(section.offset); + let stop = end.min(section_end); + crc = crc32_step(crc, &chunk[(start - total) as usize..(stop - total) as usize]); + if stop != section_end { + break; + } + failed |= !crc != section.crc32; + crc = !0u32; + index += 1; + } + total = end; + } + Ok((failed, index)) + }); + let mut digest = Sha256::new(); + let mut total = 0u64; + let mut read_error = None; + for item in sha_rx { + match item { + Ok(chunk) => { + digest.update(&chunk[..]); + total += chunk.len() as u64; + } + Err(error) => { + read_error = Some(error); + break; + } + } + } + let crc = crc_thread.join().expect("the CRC thread does not panic"); + match read_error { + Some(error) => Err(KarError::Io(error)), + None => crc.map(|c| (digest, total, c)).map_err(KarError::Io), + } + }) + })?; + let (crc_failed, index) = crc; + if total != bytes || digest.finalize().as_slice() != pin { + return Err(KarError::Integrity("KAR full archive SHA-256 mismatch")); + } + if crc_failed || index != sections.len() { + return Err(KarError::Integrity("KAR payload CRC-32 mismatch")); + } + Ok(()) +} + +/// The reference scan (kept for the tests that pin its verdicts; production uses the pipelined form above). +#[cfg_attr(not(test), allow(dead_code))] +pub(super) fn verify_integrity_stream( + file: &mut impl Read, + sections: &[Section], + bytes: u64, + pin: &[u8; 32], + buffer: &mut [u8], +) -> Result<(), KarError> { + integrity_sections(sections, bytes)?; + if buffer.is_empty() { + return Err(KarError::Range("KAR integrity buffer is empty")); + } + let mut digest = Sha256::new(); + let mut total = 0u64; + let mut index = 0; + let mut crc = !0u32; + let mut crc_failed = false; + loop { + let n = file.read(buffer).map_err(KarError::Io)?; + if n == 0 { + break; + } + let end = total + .checked_add(n as u64) + .ok_or(KarError::Range("KAR hash length overflow"))?; + digest.update(&buffer[..n]); // Metadata and padding belong to the SHA too. + while let Some(section) = sections.get(index) { + if section.offset >= end { + break; + } + let section_end = section.offset + section.bytes; // Checked above. + let start = total.max(section.offset); + let stop = end.min(section_end); + crc = crc32_step( + crc, + &buffer[(start - total) as usize..(stop - total) as usize], + ); + if stop != section_end { + break; + } + crc_failed |= !crc != section.crc32; + crc = !0u32; + index += 1; + } + total = end; + } + // A CRC failure never shortcuts the full hash or changes SHA-first precedence. + if total != bytes || digest.finalize().as_slice() != pin { + return Err(KarError::Integrity("KAR full archive SHA-256 mismatch")); + } + if crc_failed || index != sections.len() { + return Err(KarError::Integrity("KAR payload CRC-32 mismatch")); + } + Ok(()) +} + +pub(super) fn round_up(value: u64, alignment: u64) -> Option { + value.div_ceil(alignment).checked_mul(alignment) +} diff --git a/crates/model-format/src/kar_extents.rs b/crates/model-format/src/kar_extents.rs index bdf86054..07caa717 100644 --- a/crates/model-format/src/kar_extents.rs +++ b/crates/model-format/src/kar_extents.rs @@ -55,151 +55,6 @@ pub struct Extent { pub len: u64, } -impl Extent { - pub fn new(offset: u64, len: u64) -> Self { - Self { offset, len } - } - pub fn end(&self) -> u64 { - self.offset + self.len - } -} - -/// Total bytes of a list of extents. -pub fn extents_bytes(extents: &[Extent]) -> u64 { - extents.iter().map(|e| e.len).sum() -} - -/// Page-align (outwards) and merge. The result is sorted, disjoint and non-adjacent; the last extent is clamped to -/// `archive_bytes`. A range beyond the archive is an error; empty ranges are dropped. -pub fn normalize_extents(raw: &[Extent], archive_bytes: u64) -> Result, KarError> { - let mut ranges = Vec::new(); - ranges - .try_reserve_exact(raw.len()) - .map_err(|_| KarError::Allocation)?; - for e in raw.iter().filter(|e| e.len > 0) { - let end = e - .offset - .checked_add(e.len) - .filter(|end| *end <= archive_bytes) - .ok_or(KarError::Range("KAR extent outside the archive"))?; - let start = e.offset / EXTENT_ALIGN * EXTENT_ALIGN; - let end = round_up(end, EXTENT_ALIGN) - .ok_or(KarError::Range("KAR extent overflow"))? - .min(archive_bytes); - ranges.push((start, end)); - } - ranges.sort_unstable(); - let mut out: Vec = Vec::with_capacity(ranges.len()); - for (start, end) in ranges { - match out.last_mut() { - Some(last) if start <= last.end() => { - if end > last.end() { - last.len = end - last.offset; - } - } - _ => out.push(Extent::new(start, end - start)), - } - } - Ok(out) -} - -/// Is `[offset, offset + len)` inside one extent of the sorted, disjoint list? -pub fn extents_cover(extents: &[Extent], offset: u64, len: u64) -> bool { - if len == 0 { - return true; - } - let Some(end) = offset.checked_add(len) else { return false }; - let index = extents.partition_point(|e| e.offset <= offset); - index > 0 && extents[index - 1].end() >= end -} - -/// Bytes of `extents` that fall inside `[offset, offset + len)`. -pub fn extents_overlap(extents: &[Extent], offset: u64, len: u64) -> u64 { - let end = offset.saturating_add(len); - extents - .iter() - .map(|e| e.end().min(end).saturating_sub(e.offset.max(offset))) - .sum() -} - -/// The pinned hash of a sparse copy: SHA-256 over the domain tag, the number of extents, `(offset, len)` of each, and -/// then the bytes of each extent in order. `read(offset, buffer)` must fill the buffer from the archive (or its sparse -/// copy); `progress(bytes)` is called after each chunk and may sleep to throttle the pass. -pub fn digest_extents_with( - extents: &[Extent], - mut read: impl FnMut(u64, &mut [u8]) -> Result<(), KarError>, - mut progress: impl FnMut(u64), -) -> Result<[u8; 32], KarError> { - let mut hash = Sha256::new(); - hash.update(DOMAIN); - hash.update((extents.len() as u64).to_le_bytes()); - for e in extents { - hash.update(e.offset.to_le_bytes()); - hash.update(e.len.to_le_bytes()); - } - let mut buffer = Vec::new(); - buffer - .try_reserve_exact(HASH_CHUNK) - .map_err(|_| KarError::Allocation)?; - buffer.resize(HASH_CHUNK, 0); - for e in extents { - let mut done = 0u64; - while done < e.len { - let n = (e.len - done).min(HASH_CHUNK as u64) as usize; - read(e.offset + done, &mut buffer[..n])?; - hash.update(&buffer[..n]); - done += n as u64; - progress(n as u64); - } - } - Ok(hash.finalize().into()) -} - -/// [`digest_extents_with`] over a file (positional reads). -pub fn digest_extents( - file: &std::fs::File, - extents: &[Extent], - progress: impl FnMut(u64), -) -> Result<[u8; 32], KarError> { - digest_extents_with(extents, |offset, buffer| read_at(file, offset, buffer), progress) -} - -impl VerifiedPart { - /// The bytes `read_rows_chunk` reads for this partition: the scales, and the first [`PLE_PLANES`] planes. - pub(super) fn reads(&self) -> Result<[Extent; 3], KarError> { - let rows = self.row_count; - let plane_bytes = rows - .checked_mul(PLE_ROW_PLANE_BYTES) - .ok_or(KarError::Range("KAR PLE plane overflow"))?; - let scale_bytes = rows - .checked_mul(PLE_ROW_SCALE_BYTES) - .ok_or(KarError::Range("KAR PLE scale overflow"))?; - let plane = |k: u64| -> Result { - let at = k - .checked_mul(self.stride) - .and_then(|n| self.planes.checked_add(n)) - .ok_or(KarError::Range("KAR PLE plane overflow"))?; - Ok(Extent::new(at, plane_bytes)) - }; - Ok([Extent::new(self.scales, scale_bytes), plane(0)?, plane(1)?]) - } -} - -/// Every range the serve path reads, exactly (not page-aligned): the metadata `[0, payload_offset)`, the two-word -/// books the verifier reads, and the rows of the PLE partitions. -pub(super) fn exact_reads( - payload_offset: u64, - parts: &[VerifiedPart], - book_at: &[u64], -) -> Result, KarError> { - let mut out = vec![Extent::new(0, payload_offset)]; - for (part, book) in parts.iter().zip(book_at) { - out.extend(part.reads()?); - out.push(Extent::new(*book, 8)); - } - Ok(out) -} - /// One partition of the PLE table as the census sees it. #[derive(Clone, Debug, PartialEq, Eq)] pub struct PartReads { @@ -222,140 +77,6 @@ pub struct ServeReads { pub extents: Vec, } -impl ServeReads { - pub fn exact_bytes(&self) -> u64 { - extents_bytes(&self.exact) - } - pub fn extent_bytes(&self) -> u64 { - extents_bytes(&self.extents) - } -} - -fn merge_exact(mut raw: Vec) -> Vec { - raw.retain(|e| e.len > 0); - raw.sort_unstable(); - let mut out: Vec = Vec::with_capacity(raw.len()); - for e in raw { - match out.last_mut() { - Some(last) if e.offset <= last.end() => { - if e.end() > last.end() { - last.len = e.end() - last.offset; - } - } - _ => out.push(e), - } - } - out -} - -/// The `VerifiedPart` a PLE partition record yields (the same fields `VerifiedKarPleArtifact::verify` derives from the -/// raw directory bytes), plus the position of its first book. -pub(super) fn part_from_record(record: &KarNestedRecord, row_base: u64) -> Result<(VerifiedPart, u64), KarError> { - if record.dimensions.len() != 2 - || record.dimensions[0] != 160 - || record.group != 32 - || record.nesting != 0 - || record.planes_min > 2 - || record.planes_max < 2 - || record.planes_stored < 2 - { - return Err(KarError::Profile("KAR PLE partition/source mapping mismatch")); - } - let part = VerifiedPart { - row_base, - row_count: record.dimensions[1], - scales: record.scales_offset, - planes: record.planes_offset, - stride: u64::from(record.plane_stride_bytes), - }; - let book = record - .books_offset - .checked_add(4) - .ok_or(KarError::Range("KAR PLE book overflow"))?; - Ok((part, book)) -} - -impl KarInspection { - /// Offset of the first tensor section; everything before it is header, directory and names. - pub fn payload_offset(&self) -> u64 { - self.payload_offset - } - - /// What the serve path reads of this archive, derived from the directory alone. `part_names` are the PLE - /// partitions in row order ([`PLE_PART_NAMES`] for the pinned archive). - pub fn serve_reads(&self, part_names: &[&str]) -> Result { - let mut parts = Vec::new(); - let mut verified = Vec::new(); - let mut books = Vec::new(); - let mut row_base = 0u64; - for name in part_names { - let record = self.nested_record(name)?; - let (part, book) = part_from_record(&record, row_base)?; - row_base = row_base - .checked_add(part.row_count) - .ok_or(KarError::Range("KAR PLE row count overflow"))?; - let [scales, p0, p1] = part.reads()?; - parts.push(PartReads { - name: record.name.clone(), - rows: part.row_count, - scales, - planes: [p0, p1], - book: Extent::new(book, 8), - }); - verified.push(part); - books.push(book); - } - let archive_bytes = self.summary.archive_bytes; - let raw = exact_reads(self.payload_offset, &verified, &books)?; - let exact = merge_exact(raw.clone()); - let extents = normalize_extents(&raw, archive_bytes)?; - Ok(ServeReads { - metadata: Extent::new(0, self.payload_offset), - parts, - exact, - extents, - }) - } - - /// The read-only report of the directory: every record, the class of each, what the serve path reads of it. - pub fn census(&self, part_names: &[&str]) -> Result { - let serve = self.serve_reads(part_names)?; - let nested = self.nested_records()?; - let mut records = Vec::with_capacity(self.sources.len()); - for source in &self.sources { - let ple = serve.parts.iter().find(|p| p.name == source.name); - let stored = nested - .iter() - .find(|n| n.name == source.name) - .map(|n| n.planes_stored); - let class = match (ple.is_some(), source.storage_class) { - (true, _) => RecordClass::PleRows, - (false, 0) => RecordClass::NestedUnread, - (false, _) => RecordClass::RawUnread, - }; - let section = Extent::new(source.section_offset, source.section_bytes); - records.push(CensusRecord { - name: source.name.clone(), - class, - dimensions: source.dimensions.clone(), - dtype: source.dtype, - n_elements: source.n_elements, - planes_stored: stored, - section, - exact_read_bytes: extents_overlap(&serve.exact, section.offset, section.len), - extent_bytes: extents_overlap(&serve.extents, section.offset, section.len), - }); - } - Ok(KarCensus { - archive_bytes: self.summary.archive_bytes, - payload_offset: self.payload_offset, - records, - metadata_extent_bytes: extents_overlap(&serve.extents, 0, serve.metadata.len), - serve, - }) - } -} - /// What the serve path does with a record. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum RecordClass { @@ -367,16 +88,6 @@ pub enum RecordClass { RawUnread, } -impl RecordClass { - pub fn label(self) -> &'static str { - match self { - Self::PleRows => "ple-rows (read)", - Self::NestedUnread => "nested (never read)", - Self::RawUnread => "raw (never read)", - } - } -} - #[derive(Clone, Debug)] pub struct CensusRecord { pub name: String, @@ -413,118 +124,11 @@ pub struct ClassTotals { pub extent_bytes: u64, } -impl KarCensus { - pub fn totals(&self, class: RecordClass) -> ClassTotals { - let mut t = ClassTotals::default(); - for r in self.records.iter().filter(|r| r.class == class) { - t.records += 1; - t.elements += r.n_elements; - t.section_bytes += r.section.len; - t.exact_read_bytes += r.exact_read_bytes; - t.extent_bytes += r.extent_bytes; - } - t - } - - /// Bytes of the archive that no sparse copy needs. - pub fn unread_extent_bytes(&self) -> u64 { - self.archive_bytes - self.serve.extent_bytes() - } - - /// Render the report. `all_records` lists every record (otherwise only the totals and the PLE partitions). - pub fn render(&self, all_records: bool) -> String { - let gib = |b: u64| b as f64 / (1u64 << 30) as f64; - let pct = |part: u64, whole: u64| 100.0 * part as f64 / whole.max(1) as f64; - let mut out = String::new(); - let _ = writeln!(out, "archive_bytes={}", self.archive_bytes); - let _ = writeln!(out, "tensor_records={}", self.records.len()); - let _ = writeln!( - out, - "metadata: header+directory+names = [0, {}) = {} bytes (page-aligned copy: {} bytes)", - self.payload_offset, self.payload_offset, self.metadata_extent_bytes - ); - if all_records { - let _ = writeln!(out, "\n# index class section_offset section_bytes elements planes read_exact in_sparse_copy name dims"); - for (i, r) in self.records.iter().enumerate() { - let _ = writeln!( - out, - "{i:>5} {:<20} {:>16} {:>15} {:>14} {:>6} {:>12} {:>14} {} {:?}", - r.class.label(), - r.section.offset, - r.section.len, - r.n_elements, - r.planes_stored.map_or("raw".to_owned(), |p| p.to_string()), - r.exact_read_bytes, - r.extent_bytes, - r.name, - r.dimensions - ); - } - } else { - for (i, r) in self.records.iter().enumerate().filter(|(_, r)| r.class == RecordClass::PleRows) { - let _ = writeln!( - out, - "ple record {i}: {} section [{}, +{}) read_exact={} in_sparse_copy={}", - r.name, r.section.offset, r.section.len, r.exact_read_bytes, r.extent_bytes - ); - } - } - let _ = writeln!(out, "\n# totals per kind"); - let _ = writeln!(out, "kind records elements section_bytes read_exact_bytes sparse_copy_bytes"); - for class in [RecordClass::PleRows, RecordClass::NestedUnread, RecordClass::RawUnread] { - let t = self.totals(class); - let _ = writeln!( - out, - "{:<20} {:>8} {:>14} {:>16} {:>17} {:>18}", - class.label(), - t.records, - t.elements, - t.section_bytes, - t.exact_read_bytes, - t.extent_bytes - ); - } - let _ = writeln!(out, "\n# serve path reads (derived from the same geometry as read_rows_chunk)"); - for p in &self.serve.parts { - let _ = writeln!( - out, - "part {}: rows={} scales=[{}, +{}) plane0=[{}, +{}) plane1=[{}, +{}) book=[{}, +8)", - p.name, - p.rows, - p.scales.offset, - p.scales.len, - p.planes[0].offset, - p.planes[0].len, - p.planes[1].offset, - p.planes[1].len, - p.book.offset - ); - } - let exact = self.serve.exact_bytes(); - let ext = self.serve.extent_bytes(); - let _ = writeln!(out, "serve_read_exact_bytes={exact} ({:.3} GiB, {:.2} % of the archive)", gib(exact), pct(exact, self.archive_bytes)); - let _ = writeln!(out, "sparse_copy_bytes={ext} ({:.3} GiB, {:.2} % of the archive) in {} extents", gib(ext), pct(ext, self.archive_bytes), self.serve.extents.len()); - let unread = self.unread_extent_bytes(); - let _ = writeln!(out, "never_read_bytes={unread} ({:.3} GiB, {:.2} % of the archive; archive minus the sparse copy)", gib(unread), pct(unread, self.archive_bytes)); - let nested = self.totals(RecordClass::NestedUnread); - let raw = self.totals(RecordClass::RawUnread); - let _ = writeln!( - out, - "unread_records_section_bytes={} (nested {} + raw {})", - nested.section_bytes + raw.section_bytes, - nested.section_bytes, - raw.section_bytes - ); - if let Some(first) = self.records.iter().find(|r| r.class == RecordClass::PleRows) { - let _ = writeln!( - out, - "bytes_before_first_ple_section={} ({:.2} % of the archive)", - first.section.offset, - pct(first.section.offset, self.archive_bytes) - ); - } - let _ = writeln!(out, "ple_rows_expected={PLE_ROWS}"); - let _ = writeln!(out, "ple_rows_found={}", self.serve.parts.iter().map(|p| p.rows).sum::()); - out - } -} +#[path = "kar_extents/impl_extent.rs"] +mod impl_extent; +#[allow(unused_imports)] +pub use impl_extent::*; +#[path = "kar_extents/impl_karinspection.rs"] +mod impl_karinspection; +#[allow(unused_imports)] +pub use impl_karinspection::*; diff --git a/crates/model-format/src/kar_extents/impl_extent.rs b/crates/model-format/src/kar_extents/impl_extent.rs new file mode 100644 index 00000000..7750a56f --- /dev/null +++ b/crates/model-format/src/kar_extents/impl_extent.rs @@ -0,0 +1,203 @@ +//! Moved out of the parent module by STRA-338: impl Extent, fn extents_bytes, fn normalize_extents, fn extents_cover, fn extents_overlap, fn digest_extents_with .... + +#[allow(unused_imports)] +use super::*; + + +impl Extent { + pub fn new(offset: u64, len: u64) -> Self { + Self { offset, len } + } + pub fn end(&self) -> u64 { + self.offset + self.len + } +} + +/// Total bytes of a list of extents. +pub fn extents_bytes(extents: &[Extent]) -> u64 { + extents.iter().map(|e| e.len).sum() +} + +/// Page-align (outwards) and merge. The result is sorted, disjoint and non-adjacent; the last extent is clamped to +/// `archive_bytes`. A range beyond the archive is an error; empty ranges are dropped. +pub fn normalize_extents(raw: &[Extent], archive_bytes: u64) -> Result, KarError> { + let mut ranges = Vec::new(); + ranges + .try_reserve_exact(raw.len()) + .map_err(|_| KarError::Allocation)?; + for e in raw.iter().filter(|e| e.len > 0) { + let end = e + .offset + .checked_add(e.len) + .filter(|end| *end <= archive_bytes) + .ok_or(KarError::Range("KAR extent outside the archive"))?; + let start = e.offset / EXTENT_ALIGN * EXTENT_ALIGN; + let end = round_up(end, EXTENT_ALIGN) + .ok_or(KarError::Range("KAR extent overflow"))? + .min(archive_bytes); + ranges.push((start, end)); + } + ranges.sort_unstable(); + let mut out: Vec = Vec::with_capacity(ranges.len()); + for (start, end) in ranges { + match out.last_mut() { + Some(last) if start <= last.end() => { + if end > last.end() { + last.len = end - last.offset; + } + } + _ => out.push(Extent::new(start, end - start)), + } + } + Ok(out) +} + +/// Is `[offset, offset + len)` inside one extent of the sorted, disjoint list? +pub fn extents_cover(extents: &[Extent], offset: u64, len: u64) -> bool { + if len == 0 { + return true; + } + let Some(end) = offset.checked_add(len) else { return false }; + let index = extents.partition_point(|e| e.offset <= offset); + index > 0 && extents[index - 1].end() >= end +} + +/// Bytes of `extents` that fall inside `[offset, offset + len)`. +pub fn extents_overlap(extents: &[Extent], offset: u64, len: u64) -> u64 { + let end = offset.saturating_add(len); + extents + .iter() + .map(|e| e.end().min(end).saturating_sub(e.offset.max(offset))) + .sum() +} + +/// The pinned hash of a sparse copy: SHA-256 over the domain tag, the number of extents, `(offset, len)` of each, and +/// then the bytes of each extent in order. `read(offset, buffer)` must fill the buffer from the archive (or its sparse +/// copy); `progress(bytes)` is called after each chunk and may sleep to throttle the pass. +pub fn digest_extents_with( + extents: &[Extent], + mut read: impl FnMut(u64, &mut [u8]) -> Result<(), KarError>, + mut progress: impl FnMut(u64), +) -> Result<[u8; 32], KarError> { + let mut hash = Sha256::new(); + hash.update(DOMAIN); + hash.update((extents.len() as u64).to_le_bytes()); + for e in extents { + hash.update(e.offset.to_le_bytes()); + hash.update(e.len.to_le_bytes()); + } + let mut buffer = Vec::new(); + buffer + .try_reserve_exact(HASH_CHUNK) + .map_err(|_| KarError::Allocation)?; + buffer.resize(HASH_CHUNK, 0); + for e in extents { + let mut done = 0u64; + while done < e.len { + let n = (e.len - done).min(HASH_CHUNK as u64) as usize; + read(e.offset + done, &mut buffer[..n])?; + hash.update(&buffer[..n]); + done += n as u64; + progress(n as u64); + } + } + Ok(hash.finalize().into()) +} + +/// [`digest_extents_with`] over a file (positional reads). +pub fn digest_extents( + file: &std::fs::File, + extents: &[Extent], + progress: impl FnMut(u64), +) -> Result<[u8; 32], KarError> { + digest_extents_with(extents, |offset, buffer| read_at(file, offset, buffer), progress) +} + +impl VerifiedPart { + /// The bytes `read_rows_chunk` reads for this partition: the scales, and the first [`PLE_PLANES`] planes. + pub(in super::super) fn reads(&self) -> Result<[Extent; 3], KarError> { + let rows = self.row_count; + let plane_bytes = rows + .checked_mul(PLE_ROW_PLANE_BYTES) + .ok_or(KarError::Range("KAR PLE plane overflow"))?; + let scale_bytes = rows + .checked_mul(PLE_ROW_SCALE_BYTES) + .ok_or(KarError::Range("KAR PLE scale overflow"))?; + let plane = |k: u64| -> Result { + let at = k + .checked_mul(self.stride) + .and_then(|n| self.planes.checked_add(n)) + .ok_or(KarError::Range("KAR PLE plane overflow"))?; + Ok(Extent::new(at, plane_bytes)) + }; + Ok([Extent::new(self.scales, scale_bytes), plane(0)?, plane(1)?]) + } +} + +/// Every range the serve path reads, exactly (not page-aligned): the metadata `[0, payload_offset)`, the two-word +/// books the verifier reads, and the rows of the PLE partitions. +pub(in super::super) fn exact_reads( + payload_offset: u64, + parts: &[VerifiedPart], + book_at: &[u64], +) -> Result, KarError> { + let mut out = vec![Extent::new(0, payload_offset)]; + for (part, book) in parts.iter().zip(book_at) { + out.extend(part.reads()?); + out.push(Extent::new(*book, 8)); + } + Ok(out) +} + +impl ServeReads { + pub fn exact_bytes(&self) -> u64 { + extents_bytes(&self.exact) + } + pub fn extent_bytes(&self) -> u64 { + extents_bytes(&self.extents) + } +} + +pub(super) fn merge_exact(mut raw: Vec) -> Vec { + raw.retain(|e| e.len > 0); + raw.sort_unstable(); + let mut out: Vec = Vec::with_capacity(raw.len()); + for e in raw { + match out.last_mut() { + Some(last) if e.offset <= last.end() => { + if e.end() > last.end() { + last.len = e.end() - last.offset; + } + } + _ => out.push(e), + } + } + out +} + +/// The `VerifiedPart` a PLE partition record yields (the same fields `VerifiedKarPleArtifact::verify` derives from the +/// raw directory bytes), plus the position of its first book. +pub(in super::super) fn part_from_record(record: &KarNestedRecord, row_base: u64) -> Result<(VerifiedPart, u64), KarError> { + if record.dimensions.len() != 2 + || record.dimensions[0] != 160 + || record.group != 32 + || record.nesting != 0 + || record.planes_min > 2 + || record.planes_max < 2 + || record.planes_stored < 2 + { + return Err(KarError::Profile("KAR PLE partition/source mapping mismatch")); + } + let part = VerifiedPart { + row_base, + row_count: record.dimensions[1], + scales: record.scales_offset, + planes: record.planes_offset, + stride: u64::from(record.plane_stride_bytes), + }; + let book = record + .books_offset + .checked_add(4) + .ok_or(KarError::Range("KAR PLE book overflow"))?; + Ok((part, book)) +} diff --git a/crates/model-format/src/kar_extents/impl_karinspection.rs b/crates/model-format/src/kar_extents/impl_karinspection.rs new file mode 100644 index 00000000..a39968bd --- /dev/null +++ b/crates/model-format/src/kar_extents/impl_karinspection.rs @@ -0,0 +1,212 @@ +//! Moved out of the parent module by STRA-338: impl KarInspection, impl RecordClass, impl KarCensus. + +#[allow(unused_imports)] +use super::*; + + +impl KarInspection { + /// Offset of the first tensor section; everything before it is header, directory and names. + pub fn payload_offset(&self) -> u64 { + self.payload_offset + } + + /// What the serve path reads of this archive, derived from the directory alone. `part_names` are the PLE + /// partitions in row order ([`PLE_PART_NAMES`] for the pinned archive). + pub fn serve_reads(&self, part_names: &[&str]) -> Result { + let mut parts = Vec::new(); + let mut verified = Vec::new(); + let mut books = Vec::new(); + let mut row_base = 0u64; + for name in part_names { + let record = self.nested_record(name)?; + let (part, book) = part_from_record(&record, row_base)?; + row_base = row_base + .checked_add(part.row_count) + .ok_or(KarError::Range("KAR PLE row count overflow"))?; + let [scales, p0, p1] = part.reads()?; + parts.push(PartReads { + name: record.name.clone(), + rows: part.row_count, + scales, + planes: [p0, p1], + book: Extent::new(book, 8), + }); + verified.push(part); + books.push(book); + } + let archive_bytes = self.summary.archive_bytes; + let raw = exact_reads(self.payload_offset, &verified, &books)?; + let exact = merge_exact(raw.clone()); + let extents = normalize_extents(&raw, archive_bytes)?; + Ok(ServeReads { + metadata: Extent::new(0, self.payload_offset), + parts, + exact, + extents, + }) + } + + /// The read-only report of the directory: every record, the class of each, what the serve path reads of it. + pub fn census(&self, part_names: &[&str]) -> Result { + let serve = self.serve_reads(part_names)?; + let nested = self.nested_records()?; + let mut records = Vec::with_capacity(self.sources.len()); + for source in &self.sources { + let ple = serve.parts.iter().find(|p| p.name == source.name); + let stored = nested + .iter() + .find(|n| n.name == source.name) + .map(|n| n.planes_stored); + let class = match (ple.is_some(), source.storage_class) { + (true, _) => RecordClass::PleRows, + (false, 0) => RecordClass::NestedUnread, + (false, _) => RecordClass::RawUnread, + }; + let section = Extent::new(source.section_offset, source.section_bytes); + records.push(CensusRecord { + name: source.name.clone(), + class, + dimensions: source.dimensions.clone(), + dtype: source.dtype, + n_elements: source.n_elements, + planes_stored: stored, + section, + exact_read_bytes: extents_overlap(&serve.exact, section.offset, section.len), + extent_bytes: extents_overlap(&serve.extents, section.offset, section.len), + }); + } + Ok(KarCensus { + archive_bytes: self.summary.archive_bytes, + payload_offset: self.payload_offset, + records, + metadata_extent_bytes: extents_overlap(&serve.extents, 0, serve.metadata.len), + serve, + }) + } +} + +impl RecordClass { + pub fn label(self) -> &'static str { + match self { + Self::PleRows => "ple-rows (read)", + Self::NestedUnread => "nested (never read)", + Self::RawUnread => "raw (never read)", + } + } +} + +impl KarCensus { + pub fn totals(&self, class: RecordClass) -> ClassTotals { + let mut t = ClassTotals::default(); + for r in self.records.iter().filter(|r| r.class == class) { + t.records += 1; + t.elements += r.n_elements; + t.section_bytes += r.section.len; + t.exact_read_bytes += r.exact_read_bytes; + t.extent_bytes += r.extent_bytes; + } + t + } + + /// Bytes of the archive that no sparse copy needs. + pub fn unread_extent_bytes(&self) -> u64 { + self.archive_bytes - self.serve.extent_bytes() + } + + /// Render the report. `all_records` lists every record (otherwise only the totals and the PLE partitions). + pub fn render(&self, all_records: bool) -> String { + let gib = |b: u64| b as f64 / (1u64 << 30) as f64; + let pct = |part: u64, whole: u64| 100.0 * part as f64 / whole.max(1) as f64; + let mut out = String::new(); + let _ = writeln!(out, "archive_bytes={}", self.archive_bytes); + let _ = writeln!(out, "tensor_records={}", self.records.len()); + let _ = writeln!( + out, + "metadata: header+directory+names = [0, {}) = {} bytes (page-aligned copy: {} bytes)", + self.payload_offset, self.payload_offset, self.metadata_extent_bytes + ); + if all_records { + let _ = writeln!(out, "\n# index class section_offset section_bytes elements planes read_exact in_sparse_copy name dims"); + for (i, r) in self.records.iter().enumerate() { + let _ = writeln!( + out, + "{i:>5} {:<20} {:>16} {:>15} {:>14} {:>6} {:>12} {:>14} {} {:?}", + r.class.label(), + r.section.offset, + r.section.len, + r.n_elements, + r.planes_stored.map_or("raw".to_owned(), |p| p.to_string()), + r.exact_read_bytes, + r.extent_bytes, + r.name, + r.dimensions + ); + } + } else { + for (i, r) in self.records.iter().enumerate().filter(|(_, r)| r.class == RecordClass::PleRows) { + let _ = writeln!( + out, + "ple record {i}: {} section [{}, +{}) read_exact={} in_sparse_copy={}", + r.name, r.section.offset, r.section.len, r.exact_read_bytes, r.extent_bytes + ); + } + } + let _ = writeln!(out, "\n# totals per kind"); + let _ = writeln!(out, "kind records elements section_bytes read_exact_bytes sparse_copy_bytes"); + for class in [RecordClass::PleRows, RecordClass::NestedUnread, RecordClass::RawUnread] { + let t = self.totals(class); + let _ = writeln!( + out, + "{:<20} {:>8} {:>14} {:>16} {:>17} {:>18}", + class.label(), + t.records, + t.elements, + t.section_bytes, + t.exact_read_bytes, + t.extent_bytes + ); + } + let _ = writeln!(out, "\n# serve path reads (derived from the same geometry as read_rows_chunk)"); + for p in &self.serve.parts { + let _ = writeln!( + out, + "part {}: rows={} scales=[{}, +{}) plane0=[{}, +{}) plane1=[{}, +{}) book=[{}, +8)", + p.name, + p.rows, + p.scales.offset, + p.scales.len, + p.planes[0].offset, + p.planes[0].len, + p.planes[1].offset, + p.planes[1].len, + p.book.offset + ); + } + let exact = self.serve.exact_bytes(); + let ext = self.serve.extent_bytes(); + let _ = writeln!(out, "serve_read_exact_bytes={exact} ({:.3} GiB, {:.2} % of the archive)", gib(exact), pct(exact, self.archive_bytes)); + let _ = writeln!(out, "sparse_copy_bytes={ext} ({:.3} GiB, {:.2} % of the archive) in {} extents", gib(ext), pct(ext, self.archive_bytes), self.serve.extents.len()); + let unread = self.unread_extent_bytes(); + let _ = writeln!(out, "never_read_bytes={unread} ({:.3} GiB, {:.2} % of the archive; archive minus the sparse copy)", gib(unread), pct(unread, self.archive_bytes)); + let nested = self.totals(RecordClass::NestedUnread); + let raw = self.totals(RecordClass::RawUnread); + let _ = writeln!( + out, + "unread_records_section_bytes={} (nested {} + raw {})", + nested.section_bytes + raw.section_bytes, + nested.section_bytes, + raw.section_bytes + ); + if let Some(first) = self.records.iter().find(|r| r.class == RecordClass::PleRows) { + let _ = writeln!( + out, + "bytes_before_first_ple_section={} ({:.2} % of the archive)", + first.section.offset, + pct(first.section.offset, self.archive_bytes) + ); + } + let _ = writeln!(out, "ple_rows_expected={PLE_ROWS}"); + let _ = writeln!(out, "ple_rows_found={}", self.serve.parts.iter().map(|p| p.rows).sum::()); + out + } +} diff --git a/crates/model-format/src/kar_kernel_model.rs b/crates/model-format/src/kar_kernel_model.rs index aa55de7e..aa43e786 100644 --- a/crates/model-format/src/kar_kernel_model.rs +++ b/crates/model-format/src/kar_kernel_model.rs @@ -55,21 +55,7 @@ pub const STATUS_NONFINITE_OUTPUT: u32 = 4; pub enum KernelModelError { Rejected(&'static str), } -impl fmt::Display for KernelModelError { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - let Self::Rejected(message) = self; - f.write_str(message) - } -} -impl std::error::Error for KernelModelError {} type Result = std::result::Result; -fn reject(message: &'static str) -> Result { - Err(KernelModelError::Rejected(message)) -} - -fn round_up(value: u64, alignment: u64) -> u64 { - value.div_ceil(alignment) * alignment -} /// One archive byte range and where it lands in the device packet. #[derive(Debug, Clone, Copy, PartialEq, Eq)] @@ -112,133 +98,6 @@ pub struct WindowPlan { pub params: DecodeParams, } -impl WindowPlan { - pub fn packet_bytes(&self) -> u64 { - u64::from(self.params.packet_bytes) - } - pub fn output_bytes(&self) -> u64 { - u64::from(self.count) * 4 - } - pub fn grid_blocks(&self) -> u32 { - self.count.div_ceil(BLOCK_THREADS) - } - /// Every archive range the stager must read, in packet order. - pub fn ranges(&self) -> impl Iterator { - [&self.book, &self.scales] - .into_iter() - .chain(self.planes.iter()) - } - /// Total archive bytes copied into the packet (excludes padding). - pub fn staged_source_bytes(&self) -> u64 { - self.ranges().map(|r| r.len).sum() - } -} - -/// Plan one bounded window of a NESTED record at `level`. -pub fn plan_window( - record: &KarNestedRecord, - level: u8, - start: u64, - count: u64, -) -> Result { - if record.validate().is_err() { - return reject("KAR nested record layout is invalid"); - } - if record.nesting != NESTING_TOPDOWN { - return reject("KAR GPU decode supports top-down nesting only"); - } - if !(MIN_LEVEL..=MAX_LEVEL).contains(&level) { - return reject("KAR GPU level must be 2..=5"); - } - if level > record.planes_stored { - return reject("KAR level exceeds the planes stored in the record"); - } - if level < record.planes_min || level > record.planes_max { - return reject("KAR level is outside the record's certified dial"); - } - if count == 0 || count > MAX_RANGE_ELEMENTS { - return reject("KAR decode count must be 1..=16,777,216"); - } - let end = start - .checked_add(count) - .filter(|end| *end <= record.n_elements); - let Some(end) = end else { - return reject("KAR decode range exceeds the tensor"); - }; - let group = u64::from(record.group); - let first_word = start / 32; - let window_words = end.div_ceil(32) - first_word; - let first_group = start / group; - let window_groups = end.div_ceil(group) - first_group; - let head32 = start % 32; - let head_group = start % group; - let level_u64 = u64::from(level); - // Book for level L sits after the tables for levels 1..L-1: (2^L - 2) f16. - let book_skip = ((1u64 << level) - 2) * 2; - let book_len = (1u64 << level) * 2; - if book_skip + book_len > record.books_bytes { - return reject("KAR book range exceeds the record"); - } - let scales_len = window_groups * 2; - if (first_group + window_groups) * 2 > record.scales_bytes { - return reject("KAR scale range exceeds the record"); - } - let stride = u64::from(record.plane_stride_bytes); - let words_len = window_words * 4; - if (first_word + window_words) * 4 > stride { - return reject("KAR plane word range exceeds the plane stride"); - } - let scales_packet = BOOK_REGION_BYTES; - let planes_packet = round_up(scales_packet + scales_len, PACKET_ALIGN); - let plane_stride_words = round_up(window_words, 4); - let packet_bytes = planes_packet + level_u64 * plane_stride_words * 4; - if packet_bytes > u64::from(u32::MAX >> 1) { - return reject("KAR packet exceeds 2 GiB"); - } - let planes = (0..level_u64) - .map(|plane| ByteRange { - archive_offset: record.planes_offset + plane * stride + first_word * 4, - len: words_len, - packet_offset: planes_packet + plane * plane_stride_words * 4, - }) - .collect(); - // All values below were bounded above (count <= 2^24, packet < 2^31). - let to_u32 = |v: u64| v as u32; - Ok(WindowPlan { - level, - group: record.group, - start, - count: to_u32(count), - first_word, - first_group, - book: ByteRange { - archive_offset: record.books_offset + book_skip, - len: book_len, - packet_offset: 0, - }, - scales: ByteRange { - archive_offset: record.scales_offset + first_group * 2, - len: scales_len, - packet_offset: scales_packet, - }, - planes, - params: DecodeParams { - level: u32::from(level), - staged_planes: u32::from(level), - count: to_u32(count), - head32: to_u32(head32), - head_group: to_u32(head_group), - group: record.group, - scales_offset: to_u32(scales_packet), - planes_offset: to_u32(planes_packet), - plane_stride_words: to_u32(plane_stride_words), - window_words: to_u32(window_words), - window_groups: to_u32(window_groups), - packet_bytes: to_u32(packet_bytes), - }, - }) -} - /// A whole-row window plus the geometry the multiply kernel needs. #[derive(Debug, Clone, PartialEq, Eq)] pub struct RowPlan { @@ -246,275 +105,18 @@ pub struct RowPlan { pub columns: u32, pub rows: u32, } - -/// Plan `rows` complete rows starting at `first_row`. A row is `dims[0]` -/// consecutive weights; rows of higher dimensions are flattened in order, so -/// expert `e` of a `[cols, rows, experts]` tensor starts at row `e * rows`. -pub fn plan_rows( - record: &KarNestedRecord, - level: u8, - first_row: u64, - rows: u64, -) -> Result { - let Some(&columns) = record.dimensions.first() else { - return reject("KAR record has no dimensions"); - }; - if columns == 0 || columns > MAX_COLUMNS || rows == 0 { - return reject("KAR row length or row count is out of range"); - } - let total_rows = record.n_elements / columns; - if first_row - .checked_add(rows) - .is_none_or(|end| end > total_rows) - { - return reject("KAR row range exceeds the tensor"); - } - let (Some(start), Some(count)) = (first_row.checked_mul(columns), rows.checked_mul(columns)) - else { - return reject("KAR row range overflows"); - }; - let window = plan_window(record, level, start, count)?; - Ok(RowPlan { - window, - columns: columns as u32, - rows: rows as u32, - }) -} - -/// Row range of one expert in a `[cols, rows, experts]` record. -pub fn expert_rows(record: &KarNestedRecord, expert: u64) -> Result<(u64, u64)> { - if record.dimensions.len() != 3 { - return reject("KAR expert tensor must have three dimensions"); - } - let (rows, experts) = (record.dimensions[1], record.dimensions[2]); - if expert >= experts { - return reject("KAR expert index is outside the tensor"); - } - Ok((expert * rows, rows)) -} - -// ---------------------------------------------------------------- f16 -> f32 - -/// Exact binary16 -> binary32 widening (the device uses `__half2float`). -pub fn f16_to_f32(bits: u16) -> f32 { - let sign = u32::from(bits & 0x8000) << 16; - let exponent = u32::from((bits >> 10) & 0x1f); - let mantissa = u32::from(bits & 0x3ff); - let out = match exponent { - 0 if mantissa == 0 => sign, - 0 => { - let shift = mantissa.leading_zeros() - 21; - sign | ((113 - shift) << 23) | (((mantissa << shift) & 0x3ff) << 13) - } - 31 => sign | 0x7f80_0000 | (mantissa << 13), - _ => sign | ((exponent + 112) << 23) | (mantissa << 13), - }; - f32::from_bits(out) -} -fn nonfinite_f16(bits: u16) -> bool { - bits & 0x7c00 == 0x7c00 -} const NAN_BITS: u32 = 0x7fc0_0000; -fn le16(bytes: &[u8], at: usize) -> u16 { - u16::from_le_bytes([bytes[at], bytes[at + 1]]) -} -fn le32(bytes: &[u8], at: usize) -> u32 { - u32::from_le_bytes([bytes[at], bytes[at + 1], bytes[at + 2], bytes[at + 3]]) -} - -/// The argument guard at the top of `leleka_kar_decode_levels_f32`. It runs in -/// 64-bit arithmetic before any packet byte is read, so a corrupt parameter -/// block cannot cause an out-of-bounds device read. -pub fn decode_params_valid(p: &DecodeParams) -> bool { - let level = u64::from(p.level); - let count = u64::from(p.count); - let group = u64::from(p.group); - if !(u64::from(MIN_LEVEL)..=u64::from(MAX_LEVEL)).contains(&level) - || level > u64::from(p.staged_planes) - || count == 0 - || count > MAX_RANGE_ELEMENTS - || group == 0 - || group > 1024 - || !group.is_multiple_of(32) - || p.head32 >= 32 - || u64::from(p.head_group) >= group - || !p.scales_offset.is_multiple_of(2) - || !p.planes_offset.is_multiple_of(4) - || !p.plane_stride_words.is_multiple_of(4) - || p.window_words > p.plane_stride_words - || u64::from(p.packet_bytes) < BOOK_REGION_BYTES - { - return false; - } - // Every staged word / group the loop can touch exists, and every region - // lies inside the packet. - let words_needed = (u64::from(p.head32) + count).div_ceil(32); - let groups_needed = (u64::from(p.head_group) + count - 1) / group + 1; - words_needed <= u64::from(p.window_words) - && groups_needed <= u64::from(p.window_groups) - && u64::from(p.scales_offset) + 2 * u64::from(p.window_groups) <= u64::from(p.packet_bytes) - && u64::from(p.planes_offset) + level * u64::from(p.plane_stride_words) * 4 - <= u64::from(p.packet_bytes) -} - -/// `gridDim.x` for a decode of `count` elements. -pub fn decode_grid(count: u32) -> u32 { - count.div_ceil(BLOCK_THREADS) -} - -/// Literal model of `leleka_kar_decode_levels_f32`: block loop, shared book -/// load plus barrier, then one thread per output element. Returns the status -/// word. On `STATUS_BAD_ARGUMENT` no output element is written. -pub fn kernel_decode(p: &DecodeParams, packet: &[u8], out: &mut [f32]) -> u32 { - let mut status = 0u32; - if !decode_params_valid(p) - || packet.len() < p.packet_bytes as usize - || out.len() < p.count as usize - { - return STATUS_BAD_ARGUMENT; - } - let level = p.level; - for block in 0..decode_grid(p.count) { - // Shared-memory book as f32, loaded by the first 2^L threads, then - // __syncthreads(). Any non-finite table entry flags the launch. - let mut book = [0f32; 32]; - for thread in 0..BLOCK_THREADS { - if thread < (1 << level) { - let bits = le16(packet, 2 * thread as usize); - if nonfinite_f16(bits) { - status |= STATUS_NONFINITE_INPUT; - } - book[thread as usize] = f16_to_f32(bits); - } - } - // ---- barrier ---- - for thread in 0..BLOCK_THREADS { - let i = block * BLOCK_THREADS + thread; - if i >= p.count { - continue; - } - let position = p.head32 + i; - let word = position / 32; - let bit = position % 32; - let group_index = (p.head_group + i) / p.group; - let mut code = 0u32; - for plane in 0..level { - let at = p.planes_offset as usize - + (plane as usize * p.plane_stride_words as usize + word as usize) * 4; - code = (code << 1) | ((le32(packet, at) >> bit) & 1); - } - let scale_bits = le16(packet, p.scales_offset as usize + 2 * group_index as usize); - if nonfinite_f16(scale_bits) { - status |= STATUS_NONFINITE_INPUT; - out[i as usize] = f32::from_bits(NAN_BITS); - continue; - } - // Single binary32 multiply (device: __fmul_rn), as in kar_codec. - out[i as usize] = book[code as usize] * f16_to_f32(scale_bits); - } - } - status -} - -/// Literal model of `leleka_kar_multiply_f32`: one block per (row, token), -/// 256 lanes striding the columns with separately rounded multiply/add, then -/// the fixed 128..1 shared-memory tree. Output is `[token][row]`. -#[allow(clippy::needless_range_loop)] // lane indices mirror threadIdx.x -pub fn kernel_multiply( - weights: &[f32], - input: &[f32], - columns: u32, - rows: u32, - tokens: u32, - out: &mut [f32], -) -> u32 { - let (cols, nrows) = (columns as usize, rows as usize); - if columns == 0 - || rows == 0 - || tokens == 0 - || tokens > MAX_TOKENS - || u64::from(columns) > MAX_COLUMNS - || u64::from(columns) * u64::from(rows) > MAX_RANGE_ELEMENTS - || weights.len() < cols * nrows - || input.len() < cols * tokens as usize - || out.len() < nrows * tokens as usize - { - return STATUS_BAD_ARGUMENT; - } - let mut status = 0u32; - for token in 0..tokens as usize { - for row in 0..nrows { - let mut partial = [0f32; BLOCK_THREADS as usize]; - for lane in 0..BLOCK_THREADS as usize { - let mut sum = 0f32; - let mut column = lane; - while column < cols { - sum += weights[row * cols + column] * input[token * cols + column]; - column += BLOCK_THREADS as usize; - } - partial[lane] = sum; - } - let mut stride = (BLOCK_THREADS / 2) as usize; - while stride > 0 { - for lane in 0..stride { - partial[lane] += partial[lane + stride]; - } - stride >>= 1; - } - if !partial[0].is_finite() { - status |= STATUS_NONFINITE_OUTPUT; - } - out[token * nrows + row] = partial[0]; - } - } - status -} - /// Largest SwiGLU width of one launch. pub const MAX_SWIGLU_VALUES: u64 = 1 << 20; -/// Model of `leleka_kar_swiglu_f32`: `silu(gate) * up` in binary32. The device -/// uses `expf`, which is not guaranteed to match Rust's `exp` bit for bit; the -/// GPU smoke compares this stage with a tolerance, never as a bit claim. -pub fn kernel_swiglu(gate: &[f32], up: &[f32], act: &mut [f32]) -> u32 { - let values = gate.len(); - if values == 0 || values as u64 > MAX_SWIGLU_VALUES || up.len() != values || act.len() < values - { - return STATUS_BAD_ARGUMENT; - } - let mut status = 0; - for ((out, g), u) in act.iter_mut().zip(gate).zip(up) { - let result = (g / (1.0 + (-g).exp())) * u; - if !result.is_finite() { - status |= STATUS_NONFINITE_OUTPUT; - } - *out = result; - } - status -} - -/// Copy the planned ranges out of an in-memory archive image into a zeroed -/// packet. Production stages from a verified mapping through the same -/// `WindowPlan::ranges`; this is the reference stager. -pub fn stage_packet(plan: &WindowPlan, archive: &[u8]) -> Result> { - let mut packet = vec![0u8; plan.packet_bytes() as usize]; - for range in plan.ranges() { - let (Some(source_end), Some(packet_end)) = ( - range.archive_offset.checked_add(range.len), - range.packet_offset.checked_add(range.len), - ) else { - return reject("KAR stage range overflows"); - }; - if source_end > archive.len() as u64 || packet_end > packet.len() as u64 { - return reject("KAR stage range is outside the archive or packet"); - } - packet[range.packet_offset as usize..packet_end as usize] - .copy_from_slice(&archive[range.archive_offset as usize..source_end as usize]); - } - Ok(packet) -} - #[cfg(test)] #[path = "../tests/kar_kernel_model/mod.rs"] mod tests; + +mod impl_fmt_display_for; +#[allow(unused_imports)] +pub use impl_fmt_display_for::*; +mod decode_params_valid; +#[allow(unused_imports)] +pub use decode_params_valid::*; diff --git a/crates/model-format/src/kar_kernel_model/decode_params_valid.rs b/crates/model-format/src/kar_kernel_model/decode_params_valid.rs new file mode 100644 index 00000000..904d4ef6 --- /dev/null +++ b/crates/model-format/src/kar_kernel_model/decode_params_valid.rs @@ -0,0 +1,194 @@ +//! Moved out of the parent module by STRA-338: fn decode_params_valid, fn decode_grid, fn kernel_decode, fn kernel_multiply, fn kernel_swiglu, fn stage_packet. + +#[allow(unused_imports)] +use super::*; + + +/// The argument guard at the top of `leleka_kar_decode_levels_f32`. It runs in +/// 64-bit arithmetic before any packet byte is read, so a corrupt parameter +/// block cannot cause an out-of-bounds device read. +pub fn decode_params_valid(p: &DecodeParams) -> bool { + let level = u64::from(p.level); + let count = u64::from(p.count); + let group = u64::from(p.group); + if !(u64::from(MIN_LEVEL)..=u64::from(MAX_LEVEL)).contains(&level) + || level > u64::from(p.staged_planes) + || count == 0 + || count > MAX_RANGE_ELEMENTS + || group == 0 + || group > 1024 + || !group.is_multiple_of(32) + || p.head32 >= 32 + || u64::from(p.head_group) >= group + || !p.scales_offset.is_multiple_of(2) + || !p.planes_offset.is_multiple_of(4) + || !p.plane_stride_words.is_multiple_of(4) + || p.window_words > p.plane_stride_words + || u64::from(p.packet_bytes) < BOOK_REGION_BYTES + { + return false; + } + // Every staged word / group the loop can touch exists, and every region + // lies inside the packet. + let words_needed = (u64::from(p.head32) + count).div_ceil(32); + let groups_needed = (u64::from(p.head_group) + count - 1) / group + 1; + words_needed <= u64::from(p.window_words) + && groups_needed <= u64::from(p.window_groups) + && u64::from(p.scales_offset) + 2 * u64::from(p.window_groups) <= u64::from(p.packet_bytes) + && u64::from(p.planes_offset) + level * u64::from(p.plane_stride_words) * 4 + <= u64::from(p.packet_bytes) +} + +/// `gridDim.x` for a decode of `count` elements. +pub fn decode_grid(count: u32) -> u32 { + count.div_ceil(BLOCK_THREADS) +} + +/// Literal model of `leleka_kar_decode_levels_f32`: block loop, shared book +/// load plus barrier, then one thread per output element. Returns the status +/// word. On `STATUS_BAD_ARGUMENT` no output element is written. +pub fn kernel_decode(p: &DecodeParams, packet: &[u8], out: &mut [f32]) -> u32 { + let mut status = 0u32; + if !decode_params_valid(p) + || packet.len() < p.packet_bytes as usize + || out.len() < p.count as usize + { + return STATUS_BAD_ARGUMENT; + } + let level = p.level; + for block in 0..decode_grid(p.count) { + // Shared-memory book as f32, loaded by the first 2^L threads, then + // __syncthreads(). Any non-finite table entry flags the launch. + let mut book = [0f32; 32]; + for thread in 0..BLOCK_THREADS { + if thread < (1 << level) { + let bits = le16(packet, 2 * thread as usize); + if nonfinite_f16(bits) { + status |= STATUS_NONFINITE_INPUT; + } + book[thread as usize] = f16_to_f32(bits); + } + } + // ---- barrier ---- + for thread in 0..BLOCK_THREADS { + let i = block * BLOCK_THREADS + thread; + if i >= p.count { + continue; + } + let position = p.head32 + i; + let word = position / 32; + let bit = position % 32; + let group_index = (p.head_group + i) / p.group; + let mut code = 0u32; + for plane in 0..level { + let at = p.planes_offset as usize + + (plane as usize * p.plane_stride_words as usize + word as usize) * 4; + code = (code << 1) | ((le32(packet, at) >> bit) & 1); + } + let scale_bits = le16(packet, p.scales_offset as usize + 2 * group_index as usize); + if nonfinite_f16(scale_bits) { + status |= STATUS_NONFINITE_INPUT; + out[i as usize] = f32::from_bits(NAN_BITS); + continue; + } + // Single binary32 multiply (device: __fmul_rn), as in kar_codec. + out[i as usize] = book[code as usize] * f16_to_f32(scale_bits); + } + } + status +} + +/// Literal model of `leleka_kar_multiply_f32`: one block per (row, token), +/// 256 lanes striding the columns with separately rounded multiply/add, then +/// the fixed 128..1 shared-memory tree. Output is `[token][row]`. +#[allow(clippy::needless_range_loop)] // lane indices mirror threadIdx.x +pub fn kernel_multiply( + weights: &[f32], + input: &[f32], + columns: u32, + rows: u32, + tokens: u32, + out: &mut [f32], +) -> u32 { + let (cols, nrows) = (columns as usize, rows as usize); + if columns == 0 + || rows == 0 + || tokens == 0 + || tokens > MAX_TOKENS + || u64::from(columns) > MAX_COLUMNS + || u64::from(columns) * u64::from(rows) > MAX_RANGE_ELEMENTS + || weights.len() < cols * nrows + || input.len() < cols * tokens as usize + || out.len() < nrows * tokens as usize + { + return STATUS_BAD_ARGUMENT; + } + let mut status = 0u32; + for token in 0..tokens as usize { + for row in 0..nrows { + let mut partial = [0f32; BLOCK_THREADS as usize]; + for lane in 0..BLOCK_THREADS as usize { + let mut sum = 0f32; + let mut column = lane; + while column < cols { + sum += weights[row * cols + column] * input[token * cols + column]; + column += BLOCK_THREADS as usize; + } + partial[lane] = sum; + } + let mut stride = (BLOCK_THREADS / 2) as usize; + while stride > 0 { + for lane in 0..stride { + partial[lane] += partial[lane + stride]; + } + stride >>= 1; + } + if !partial[0].is_finite() { + status |= STATUS_NONFINITE_OUTPUT; + } + out[token * nrows + row] = partial[0]; + } + } + status +} + +/// Model of `leleka_kar_swiglu_f32`: `silu(gate) * up` in binary32. The device +/// uses `expf`, which is not guaranteed to match Rust's `exp` bit for bit; the +/// GPU smoke compares this stage with a tolerance, never as a bit claim. +pub fn kernel_swiglu(gate: &[f32], up: &[f32], act: &mut [f32]) -> u32 { + let values = gate.len(); + if values == 0 || values as u64 > MAX_SWIGLU_VALUES || up.len() != values || act.len() < values + { + return STATUS_BAD_ARGUMENT; + } + let mut status = 0; + for ((out, g), u) in act.iter_mut().zip(gate).zip(up) { + let result = (g / (1.0 + (-g).exp())) * u; + if !result.is_finite() { + status |= STATUS_NONFINITE_OUTPUT; + } + *out = result; + } + status +} + +/// Copy the planned ranges out of an in-memory archive image into a zeroed +/// packet. Production stages from a verified mapping through the same +/// `WindowPlan::ranges`; this is the reference stager. +pub fn stage_packet(plan: &WindowPlan, archive: &[u8]) -> Result> { + let mut packet = vec![0u8; plan.packet_bytes() as usize]; + for range in plan.ranges() { + let (Some(source_end), Some(packet_end)) = ( + range.archive_offset.checked_add(range.len), + range.packet_offset.checked_add(range.len), + ) else { + return reject("KAR stage range overflows"); + }; + if source_end > archive.len() as u64 || packet_end > packet.len() as u64 { + return reject("KAR stage range is outside the archive or packet"); + } + packet[range.packet_offset as usize..packet_end as usize] + .copy_from_slice(&archive[range.archive_offset as usize..source_end as usize]); + } + Ok(packet) +} diff --git a/crates/model-format/src/kar_kernel_model/impl_fmt_display_for.rs b/crates/model-format/src/kar_kernel_model/impl_fmt_display_for.rs new file mode 100644 index 00000000..a73aa140 --- /dev/null +++ b/crates/model-format/src/kar_kernel_model/impl_fmt_display_for.rs @@ -0,0 +1,221 @@ +//! Moved out of the parent module by STRA-338: impl fmt_Display_for, impl std_error_Error, fn reject, fn round_up, impl WindowPlan, fn plan_window .... + +#[allow(unused_imports)] +use super::*; + +impl fmt::Display for KernelModelError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + let Self::Rejected(message) = self; + f.write_str(message) + } +} +impl std::error::Error for KernelModelError {} +pub(super) fn reject(message: &'static str) -> Result { + Err(KernelModelError::Rejected(message)) +} + +pub(super) fn round_up(value: u64, alignment: u64) -> u64 { + value.div_ceil(alignment) * alignment +} + +impl WindowPlan { + pub fn packet_bytes(&self) -> u64 { + u64::from(self.params.packet_bytes) + } + pub fn output_bytes(&self) -> u64 { + u64::from(self.count) * 4 + } + pub fn grid_blocks(&self) -> u32 { + self.count.div_ceil(BLOCK_THREADS) + } + /// Every archive range the stager must read, in packet order. + pub fn ranges(&self) -> impl Iterator { + [&self.book, &self.scales] + .into_iter() + .chain(self.planes.iter()) + } + /// Total archive bytes copied into the packet (excludes padding). + pub fn staged_source_bytes(&self) -> u64 { + self.ranges().map(|r| r.len).sum() + } +} + +/// Plan one bounded window of a NESTED record at `level`. +pub fn plan_window( + record: &KarNestedRecord, + level: u8, + start: u64, + count: u64, +) -> Result { + if record.validate().is_err() { + return reject("KAR nested record layout is invalid"); + } + if record.nesting != NESTING_TOPDOWN { + return reject("KAR GPU decode supports top-down nesting only"); + } + if !(MIN_LEVEL..=MAX_LEVEL).contains(&level) { + return reject("KAR GPU level must be 2..=5"); + } + if level > record.planes_stored { + return reject("KAR level exceeds the planes stored in the record"); + } + if level < record.planes_min || level > record.planes_max { + return reject("KAR level is outside the record's certified dial"); + } + if count == 0 || count > MAX_RANGE_ELEMENTS { + return reject("KAR decode count must be 1..=16,777,216"); + } + let end = start + .checked_add(count) + .filter(|end| *end <= record.n_elements); + let Some(end) = end else { + return reject("KAR decode range exceeds the tensor"); + }; + let group = u64::from(record.group); + let first_word = start / 32; + let window_words = end.div_ceil(32) - first_word; + let first_group = start / group; + let window_groups = end.div_ceil(group) - first_group; + let head32 = start % 32; + let head_group = start % group; + let level_u64 = u64::from(level); + // Book for level L sits after the tables for levels 1..L-1: (2^L - 2) f16. + let book_skip = ((1u64 << level) - 2) * 2; + let book_len = (1u64 << level) * 2; + if book_skip + book_len > record.books_bytes { + return reject("KAR book range exceeds the record"); + } + let scales_len = window_groups * 2; + if (first_group + window_groups) * 2 > record.scales_bytes { + return reject("KAR scale range exceeds the record"); + } + let stride = u64::from(record.plane_stride_bytes); + let words_len = window_words * 4; + if (first_word + window_words) * 4 > stride { + return reject("KAR plane word range exceeds the plane stride"); + } + let scales_packet = BOOK_REGION_BYTES; + let planes_packet = round_up(scales_packet + scales_len, PACKET_ALIGN); + let plane_stride_words = round_up(window_words, 4); + let packet_bytes = planes_packet + level_u64 * plane_stride_words * 4; + if packet_bytes > u64::from(u32::MAX >> 1) { + return reject("KAR packet exceeds 2 GiB"); + } + let planes = (0..level_u64) + .map(|plane| ByteRange { + archive_offset: record.planes_offset + plane * stride + first_word * 4, + len: words_len, + packet_offset: planes_packet + plane * plane_stride_words * 4, + }) + .collect(); + // All values below were bounded above (count <= 2^24, packet < 2^31). + let to_u32 = |v: u64| v as u32; + Ok(WindowPlan { + level, + group: record.group, + start, + count: to_u32(count), + first_word, + first_group, + book: ByteRange { + archive_offset: record.books_offset + book_skip, + len: book_len, + packet_offset: 0, + }, + scales: ByteRange { + archive_offset: record.scales_offset + first_group * 2, + len: scales_len, + packet_offset: scales_packet, + }, + planes, + params: DecodeParams { + level: u32::from(level), + staged_planes: u32::from(level), + count: to_u32(count), + head32: to_u32(head32), + head_group: to_u32(head_group), + group: record.group, + scales_offset: to_u32(scales_packet), + planes_offset: to_u32(planes_packet), + plane_stride_words: to_u32(plane_stride_words), + window_words: to_u32(window_words), + window_groups: to_u32(window_groups), + packet_bytes: to_u32(packet_bytes), + }, + }) +} + +/// Plan `rows` complete rows starting at `first_row`. A row is `dims[0]` +/// consecutive weights; rows of higher dimensions are flattened in order, so +/// expert `e` of a `[cols, rows, experts]` tensor starts at row `e * rows`. +pub fn plan_rows( + record: &KarNestedRecord, + level: u8, + first_row: u64, + rows: u64, +) -> Result { + let Some(&columns) = record.dimensions.first() else { + return reject("KAR record has no dimensions"); + }; + if columns == 0 || columns > MAX_COLUMNS || rows == 0 { + return reject("KAR row length or row count is out of range"); + } + let total_rows = record.n_elements / columns; + if first_row + .checked_add(rows) + .is_none_or(|end| end > total_rows) + { + return reject("KAR row range exceeds the tensor"); + } + let (Some(start), Some(count)) = (first_row.checked_mul(columns), rows.checked_mul(columns)) + else { + return reject("KAR row range overflows"); + }; + let window = plan_window(record, level, start, count)?; + Ok(RowPlan { + window, + columns: columns as u32, + rows: rows as u32, + }) +} + +/// Row range of one expert in a `[cols, rows, experts]` record. +pub fn expert_rows(record: &KarNestedRecord, expert: u64) -> Result<(u64, u64)> { + if record.dimensions.len() != 3 { + return reject("KAR expert tensor must have three dimensions"); + } + let (rows, experts) = (record.dimensions[1], record.dimensions[2]); + if expert >= experts { + return reject("KAR expert index is outside the tensor"); + } + Ok((expert * rows, rows)) +} + +// ---------------------------------------------------------------- f16 -> f32 + +/// Exact binary16 -> binary32 widening (the device uses `__half2float`). +pub fn f16_to_f32(bits: u16) -> f32 { + let sign = u32::from(bits & 0x8000) << 16; + let exponent = u32::from((bits >> 10) & 0x1f); + let mantissa = u32::from(bits & 0x3ff); + let out = match exponent { + 0 if mantissa == 0 => sign, + 0 => { + let shift = mantissa.leading_zeros() - 21; + sign | ((113 - shift) << 23) | (((mantissa << shift) & 0x3ff) << 13) + } + 31 => sign | 0x7f80_0000 | (mantissa << 13), + _ => sign | ((exponent + 112) << 23) | (mantissa << 13), + }; + f32::from_bits(out) +} +pub(super) fn nonfinite_f16(bits: u16) -> bool { + bits & 0x7c00 == 0x7c00 +} + +pub(super) fn le16(bytes: &[u8], at: usize) -> u16 { + u16::from_le_bytes([bytes[at], bytes[at + 1]]) +} +pub(super) fn le32(bytes: &[u8], at: usize) -> u32 { + u32::from_le_bytes([bytes[at], bytes[at + 1], bytes[at + 2], bytes[at + 3]]) +} diff --git a/crates/model-format/src/kar_levels.rs b/crates/model-format/src/kar_levels.rs index aee4a51a..ea48b8dd 100644 --- a/crates/model-format/src/kar_levels.rs +++ b/crates/model-format/src/kar_levels.rs @@ -51,24 +51,6 @@ pub enum KarLevelsError { /// The CPU reference saw a device-style status or a non-finite value. NonFinite, } -impl fmt::Display for KarLevelsError { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - match self { - Self::Policy(reason) | Self::Overlay(reason) => f.write_str(reason), - Self::UnknownTensor(name) => write!(f, "KAR tensor {name} is not a NESTED record"), - Self::Window { tensor, reason } => write!(f, "{tensor}: {reason}"), - Self::Read => f.write_str("KAR archive range read failed"), - Self::HostAllocation => f.write_str("KAR host packet allocation failed"), - Self::Layout(reason) => f.write_str(reason), - Self::NonFinite => f.write_str("KAR expert computation produced a non-finite value"), - Self::Budget { needed, available } => write!( - f, - "KAR scratch needs {needed} bytes but only {available} remain" - ), - } - } -} -impl std::error::Error for KarLevelsError {} type Result = std::result::Result; // ------------------------------------------------------------------ classes @@ -85,41 +67,6 @@ pub enum TensorClass { Output, Other, } -impl TensorClass { - pub const ALL: [TensorClass; 7] = [ - Self::RoutedExpert, - Self::SharedExpert, - Self::DenseFfn, - Self::Attention, - Self::Embedding, - Self::Output, - Self::Other, - ]; - pub fn classify(name: &str) -> Self { - let tail = name.rsplit('.').nth(1).unwrap_or(name); - if tail.ends_with("_exps") { - Self::RoutedExpert - } else if tail.ends_with("_shexp") { - Self::SharedExpert - } else if matches!(tail, "ffn_gate" | "ffn_up" | "ffn_down") { - Self::DenseFfn - } else if tail.starts_with("attn_") || tail.starts_with("ssm_") { - Self::Attention - } else if tail.ends_with("token_embd") { - Self::Embedding - } else if name == "output.weight" { - Self::Output - } else { - Self::Other - } - } - fn index(self) -> usize { - Self::ALL - .iter() - .position(|c| *c == self) - .expect("class is in ALL") - } -} /// A level per class with a fallback. Every level is bounded to 2..=5 at /// construction, so an unrepresentable policy cannot exist. @@ -128,30 +75,6 @@ pub struct ClassLevels { default: u8, per_class: [Option; 7], } -impl ClassLevels { - pub fn uniform(level: u8) -> Result { - check_level(level)?; - Ok(Self { - default: level, - per_class: [None; 7], - }) - } - pub fn with(mut self, class: TensorClass, level: u8) -> Result { - check_level(level)?; - self.per_class[class.index()] = Some(level); - Ok(self) - } - pub fn level_for(&self, class: TensorClass) -> u8 { - self.per_class[class.index()].unwrap_or(self.default) - } -} -fn check_level(level: u8) -> Result<()> { - if (MIN_LEVEL..=MAX_LEVEL).contains(&level) { - Ok(()) - } else { - Err(KarLevelsError::Policy("KAR policy level must be 2..=5")) - } -} /// Levels for tensors served from the base archive and from the overlay. #[derive(Clone, Copy, Debug, PartialEq, Eq)] @@ -174,56 +97,6 @@ pub struct ArchiveView { archive_bytes: u64, records: BTreeMap, } -impl ArchiveView { - /// `records` must come from an archive whose payload CRCs and full SHA-256 - /// were verified by the caller; this only re-validates record layouts. - pub fn from_records( - sha256: [u8; 32], - archive_bytes: u64, - records: Vec, - ) -> Result { - let mut map = BTreeMap::new(); - for record in records { - let section_end = record - .section_offset - .checked_add(record.section_bytes) - .ok_or(KarLevelsError::Overlay("KAR section overflows"))?; - if record.validate().is_err() || section_end > archive_bytes { - return Err(KarLevelsError::Overlay( - "KAR record layout is invalid or outside its archive", - )); - } - if map.insert(record.name.clone(), record).is_some() { - return Err(KarLevelsError::Overlay("duplicate KAR record name")); - } - } - Ok(Self { - sha256, - archive_bytes, - records: map, - }) - } - pub fn from_inspection( - inspection: &KarInspection, - sha256: [u8; 32], - ) -> std::result::Result> { - let records = inspection.nested_records()?; - Ok(Self::from_records( - sha256, - inspection.summary().archive_bytes, - records, - )?) - } - pub fn records(&self) -> impl Iterator { - self.records.values() - } - pub fn sha256(&self) -> &[u8; 32] { - &self.sha256 - } - pub fn archive_bytes(&self) -> u64 { - self.archive_bytes - } -} // ----------------------------------------------------------------- selector @@ -233,101 +106,6 @@ pub struct KarLevelSelector { policy: LevelPolicy, } -impl KarLevelSelector { - /// Overlay records must replace same-named base records with identical - /// shape; anything else is a mapping the resolver should have rejected. - pub fn new( - base: ArchiveView, - overlay: Option, - policy: LevelPolicy, - ) -> Result { - if let Some(overlay) = &overlay { - if overlay.sha256 == base.sha256 { - return Err(KarLevelsError::Overlay( - "overlay archive is the base archive", - )); - } - for (name, replacement) in &overlay.records { - let Some(original) = base.records.get(name) else { - return Err(KarLevelsError::Overlay( - "overlay record has no base record to replace", - )); - }; - if original.dimensions != replacement.dimensions - || original.n_elements != replacement.n_elements - { - return Err(KarLevelsError::Overlay( - "overlay record shape differs from its base record", - )); - } - } - } - Ok(Self { - base, - overlay, - policy, - }) - } - - /// Which archive serves `name` and at which level, per class policy. - pub fn resolve(&self, name: &str) -> Result> { - let class = TensorClass::classify(name); - let (slot, record, level) = match self.overlay.as_ref().and_then(|o| o.records.get(name)) { - Some(record) => ( - ArchiveSlot::Overlay, - record, - self.policy.overlay.level_for(class), - ), - None => { - let record = self - .base - .records - .get(name) - .ok_or_else(|| KarLevelsError::UnknownTensor(name.to_owned()))?; - (ArchiveSlot::Base, record, self.policy.base.level_for(class)) - } - }; - Ok(Selection { - class, - slot, - level, - record, - }) - } - - pub fn archive(&self, slot: ArchiveSlot) -> Option<&ArchiveView> { - match slot { - ArchiveSlot::Base => Some(&self.base), - ArchiveSlot::Overlay => self.overlay.as_ref(), - } - } - - /// Compressed bytes if every named tensor stayed resident at its selected - /// level (the libkar `kar_reserve` prefix), checked against a budget. - pub fn resident_bytes<'a>( - &self, - names: impl IntoIterator, - budget: u64, - ) -> Result { - let mut total = 0u64; - for name in names { - total = total - .checked_add(self.resolve(name)?.resident_prefix_bytes()?) - .ok_or(KarLevelsError::Budget { - needed: u64::MAX, - available: budget, - })?; - } - if total > budget { - return Err(KarLevelsError::Budget { - needed: total, - available: budget, - }); - } - Ok(total) - } -} - /// One resolved tensor: archive, level and record. Cheap to copy around. #[derive(Clone, Copy)] pub struct Selection<'a> { @@ -337,60 +115,6 @@ pub struct Selection<'a> { pub record: &'a KarNestedRecord, } -impl Selection<'_> { - fn window_error(&self, reason: KernelModelError) -> KarLevelsError { - KarLevelsError::Window { - tensor: self.record.name.clone(), - reason, - } - } - - /// Bytes the whole level-`level` prefix of this record occupies when kept - /// resident compressed (section start through the last used plane). - pub fn resident_prefix_bytes(&self) -> Result { - let r = self.record; - if !(r.planes_min..=r.planes_max).contains(&self.level) { - return Err(self.window_error(KernelModelError::Rejected( - "KAR level is outside the record's certified dial", - ))); - } - r.planes_offset - .checked_sub(r.section_offset) - .and_then(|prefix| { - prefix.checked_add(u64::from(self.level) * u64::from(r.plane_stride_bytes)) - }) - .filter(|bytes| *bytes <= r.section_bytes) - .ok_or(KarLevelsError::Overlay("invalid KAR resident prefix size")) - } - - /// Bounded flat element window `[start, start + count)`. - pub fn window(&self, start: u64, count: u64) -> Result { - let plan = model::plan_window(self.record, self.level, start, count) - .map_err(|reason| self.window_error(reason))?; - Ok(GpuWindow::new(self.slot, plan)) - } - - /// `rows` complete rows from `first_row`, ready for the F32 multiply. - pub fn rows(&self, first_row: u64, rows: u64, tokens: u32) -> Result { - let plan = model::plan_rows(self.record, self.level, first_row, rows) - .map_err(|reason| self.window_error(reason))?; - GpuRows::new(self.slot, plan, tokens) - } - - /// One expert matrix of a `[cols, rows, experts]` record. - pub fn expert(&self, expert: u64, tokens: u32) -> Result { - let (first, rows) = - model::expert_rows(self.record, expert).map_err(|reason| self.window_error(reason))?; - self.rows(first, rows, tokens) - } -} - -// ---------------------------------------------------------------- GPU plans - -fn align(bytes: u64) -> u64 { - bytes.div_ceil(SCRATCH_ALIGN) * SCRATCH_ALIGN -} - /// Everything needed to stage and launch one decode window. The driver /// derives its own `DecodeGeometry` from `plan.params`; the runtime checks the /// two for equality before any launch. @@ -399,23 +123,6 @@ pub struct GpuWindow { pub slot: ArchiveSlot, pub plan: WindowPlan, } -impl GpuWindow { - fn new(slot: ArchiveSlot, plan: WindowPlan) -> Self { - Self { slot, plan } - } - /// Archive bytes the stager copies into the packet (no padding). - pub fn staged_source_bytes(&self) -> u64 { - self.plan.staged_source_bytes() - } - /// Device scratch for decode only: packet + F32 output + status word. - pub fn scratch(&self) -> ScratchBytes { - ScratchBytes::of(&[ - u64::from(self.plan.params.packet_bytes), - u64::from(self.plan.params.count) * 4, - STATUS_BYTES, - ]) - } -} /// `[tokens][columns]` input times `[rows][columns]` weights. #[derive(Clone, Copy, Debug, PartialEq, Eq)] @@ -424,17 +131,6 @@ pub struct RowShape { pub rows: u32, pub tokens: u32, } -impl RowShape { - pub fn weights_bytes(&self) -> u64 { - u64::from(self.columns) * u64::from(self.rows) * 4 - } - pub fn input_bytes(&self) -> u64 { - u64::from(self.columns) * u64::from(self.tokens) * 4 - } - pub fn output_bytes(&self) -> u64 { - u64::from(self.rows) * u64::from(self.tokens) * 4 - } -} /// A whole-row window plus the multiply shape and its extra buffers. #[derive(Clone, Debug)] @@ -442,31 +138,6 @@ pub struct GpuRows { pub window: GpuWindow, pub shape: RowShape, } -impl GpuRows { - fn new(slot: ArchiveSlot, plan: RowPlan, tokens: u32) -> Result { - if tokens == 0 || tokens > MAX_TOKENS { - return Err(KarLevelsError::Policy("KAR multiply tokens must be 1..=8")); - } - Ok(Self { - window: GpuWindow::new(slot, plan.window), - shape: RowShape { - columns: plan.columns, - rows: plan.rows, - tokens, - }, - }) - } - /// packet + decoded F32 weights + input + output + status, each aligned. - pub fn scratch(&self) -> ScratchBytes { - ScratchBytes::of(&[ - u64::from(self.window.plan.params.packet_bytes), - self.shape.weights_bytes(), - self.shape.input_bytes(), - self.shape.output_bytes(), - STATUS_BYTES, - ]) - } -} // ------------------------------------------------------------------- budget @@ -477,14 +148,6 @@ pub struct ScratchBytes { /// Sum with each buffer rounded up to `SCRATCH_ALIGN`. pub aligned: u64, } -impl ScratchBytes { - pub fn of(buffers: &[u64]) -> Self { - Self { - raw: buffers.iter().sum(), - aligned: buffers.iter().map(|b| align(*b)).sum(), - } - } -} /// Simple additive scratch ledger. Reuse across sequential windows is modeled /// by `peak`, concurrent use by reserving each window. @@ -493,32 +156,6 @@ pub struct ScratchBudget { limit: u64, reserved: u64, } -impl ScratchBudget { - pub fn new(limit: u64) -> Self { - Self { limit, reserved: 0 } - } - pub fn remaining(&self) -> u64 { - self.limit - self.reserved - } - pub fn reserve(&mut self, scratch: ScratchBytes) -> Result<()> { - let available = self.remaining(); - if scratch.aligned > available { - return Err(KarLevelsError::Budget { - needed: scratch.aligned, - available, - }); - } - self.reserved += scratch.aligned; - Ok(()) - } - pub fn release(&mut self, scratch: ScratchBytes) { - self.reserved = self.reserved.saturating_sub(scratch.aligned); - } - /// Largest single-window requirement when one scratch set is reused. - pub fn peak(scratch: impl IntoIterator) -> u64 { - scratch.into_iter().map(|s| s.aligned).max().unwrap_or(0) - } -} #[cfg(test)] #[path = "../tests/kar_levels/mod.rs"] @@ -528,139 +165,19 @@ mod tests; pub const EXPERT_ROLES: [&str; 3] = ["ffn_gate_exps", "ffn_up_exps", "ffn_down_exps"]; -/// GGUF-style tensor name of one routed-expert bank (`role` 0 gate, 1 up, 2 down). -pub fn expert_tensor_name(layer: u32, role: usize) -> String { - format!("blk.{layer}.{}.weight", EXPERT_ROLES[role]) -} - -impl KarLevelSelector { - /// Every layer x gate/up/down bank exists with exactly `[hidden, ff, - /// experts]` (down: `[ff, hidden, experts]`) and the first and last expert - /// are plannable at the selected level. Called at load, never lazily. - pub fn validate_expert_map( - &self, - layers: u32, - experts: u32, - hidden: u64, - ff: u64, - ) -> Result<()> { - for layer in 0..layers { - for role in 0..3 { - let selection = self.resolve(&expert_tensor_name(layer, role))?; - let want = if role == 2 { - [ff, hidden, u64::from(experts)] - } else { - [hidden, ff, u64::from(experts)] - }; - if selection.record.dimensions != want { - return Err(KarLevelsError::Layout("KAR expert tensor shape differs")); - } - for expert in [0, u64::from(experts) - 1] { - selection.expert(expert, 1)?; - } - } - } - Ok(()) - } - - /// Plan the three matrices of one routed expert at their policy levels. - pub fn plan_expert(&self, layer: u32, expert: u32) -> Result<[GpuRows; 3]> { - let plan = |role| -> Result { - self.resolve(&expert_tensor_name(layer, role))? - .expert(u64::from(expert), 1) - }; - Ok([plan(0)?, plan(1)?, plan(2)?]) - } -} - /// Read access to an archive's bytes: the retained verified descriptor in /// production, an in-memory image in tests. pub trait RangeSource { fn read_exact_at(&self, offset: u64, out: &mut [u8]) -> std::result::Result<(), KarError>; } use crate::kar::KarError; -#[cfg(any(unix, windows))] -impl RangeSource for KarInspection { - fn read_exact_at(&self, offset: u64, out: &mut [u8]) -> std::result::Result<(), KarError> { - KarInspection::read_exact_at(self, offset, out) - } -} -impl RangeSource for [u8] { - fn read_exact_at(&self, offset: u64, out: &mut [u8]) -> std::result::Result<(), KarError> { - let end = offset - .checked_add(out.len() as u64) - .filter(|end| *end <= self.len() as u64) - .ok_or(KarError::Range("image read exceeds the archive"))?; - out.copy_from_slice(&self[offset as usize..end as usize]); - Ok(()) - } -} -/// Copy exactly the planned archive ranges into a zeroed packet. -pub fn stage_window(source: &S, plan: &WindowPlan) -> Result> { - let len = plan.packet_bytes() as usize; - let mut packet = Vec::new(); - packet - .try_reserve_exact(len) - .map_err(|_| KarLevelsError::HostAllocation)?; - packet.resize(len, 0); - for range in plan.ranges() { - let (at, size) = (range.packet_offset as usize, range.len as usize); - let slot = packet.get_mut(at..at + size).ok_or(KarLevelsError::Layout( - "KAR packet range escapes its packet", - ))?; - source - .read_exact_at(range.archive_offset, slot) - .map_err(|_| KarLevelsError::Read)?; - } - Ok(packet) -} - -/// Device scratch of one expert FFN as the closed CUDA program allocates it: -/// three packets, one reused F32 weight matrix, input, gate/up/act -/// intermediates, output and the status word, each rounded to the granularity. -pub fn expert_scratch(rows: &[GpuRows; 3]) -> ScratchBytes { - let weights = rows - .iter() - .map(|r| r.shape.weights_bytes()) - .max() - .unwrap_or(0); - let hidden = u64::from(rows[0].shape.columns) * 4; - let ff = u64::from(rows[0].shape.rows) * 4; - let mut buffers: Vec = rows - .iter() - .map(|r| u64::from(r.window.plan.params.packet_bytes)) - .collect(); - buffers.extend([weights, hidden, ff, ff, ff, hidden, STATUS_BYTES]); - ScratchBytes::of(&buffers) -} - -/// CPU transcription of what the device pipeline computes for one expert, built -/// from the kernel model (decode, F32 multiply, SwiGLU). It is the reference a -/// GPU smoke compares against; the SwiGLU stage differs from the device `expf` -/// by libm rounding only, so a device comparison uses a stated tolerance there. -pub fn cpu_reference_mlp( - rows: &[GpuRows; 3], - packets: &[Vec; 3], - input: &[f32], -) -> Result> { - let apply = |index: usize, x: &[f32]| -> Result> { - let r = &rows[index]; - let mut weights = vec![0f32; r.window.plan.params.count as usize]; - if model::kernel_decode(&r.window.plan.params, &packets[index], &mut weights) != 0 { - return Err(KarLevelsError::NonFinite); - } - let mut out = vec![0f32; r.shape.rows as usize]; - if model::kernel_multiply(&weights, x, r.shape.columns, r.shape.rows, 1, &mut out) != 0 { - return Err(KarLevelsError::NonFinite); - } - Ok(out) - }; - let gate = apply(0, input)?; - let up = apply(1, input)?; - let mut act = vec![0f32; gate.len()]; - if model::kernel_swiglu(&gate, &up, &mut act) != 0 { - return Err(KarLevelsError::NonFinite); - } - apply(2, &act) -} +mod impl_fmt_display_for; +#[allow(unused_imports)] +pub use impl_fmt_display_for::*; +mod impl_selection; +#[allow(unused_imports)] +pub use impl_selection::*; +mod expert_scratch; +#[allow(unused_imports)] +pub use expert_scratch::*; diff --git a/crates/model-format/src/kar_levels/expert_scratch.rs b/crates/model-format/src/kar_levels/expert_scratch.rs new file mode 100644 index 00000000..0680b121 --- /dev/null +++ b/crates/model-format/src/kar_levels/expert_scratch.rs @@ -0,0 +1,54 @@ +//! Moved out of the parent module by STRA-338: fn expert_scratch, fn cpu_reference_mlp. + +#[allow(unused_imports)] +use super::*; + + +/// Device scratch of one expert FFN as the closed CUDA program allocates it: +/// three packets, one reused F32 weight matrix, input, gate/up/act +/// intermediates, output and the status word, each rounded to the granularity. +pub fn expert_scratch(rows: &[GpuRows; 3]) -> ScratchBytes { + let weights = rows + .iter() + .map(|r| r.shape.weights_bytes()) + .max() + .unwrap_or(0); + let hidden = u64::from(rows[0].shape.columns) * 4; + let ff = u64::from(rows[0].shape.rows) * 4; + let mut buffers: Vec = rows + .iter() + .map(|r| u64::from(r.window.plan.params.packet_bytes)) + .collect(); + buffers.extend([weights, hidden, ff, ff, ff, hidden, STATUS_BYTES]); + ScratchBytes::of(&buffers) +} + +/// CPU transcription of what the device pipeline computes for one expert, built +/// from the kernel model (decode, F32 multiply, SwiGLU). It is the reference a +/// GPU smoke compares against; the SwiGLU stage differs from the device `expf` +/// by libm rounding only, so a device comparison uses a stated tolerance there. +pub fn cpu_reference_mlp( + rows: &[GpuRows; 3], + packets: &[Vec; 3], + input: &[f32], +) -> Result> { + let apply = |index: usize, x: &[f32]| -> Result> { + let r = &rows[index]; + let mut weights = vec![0f32; r.window.plan.params.count as usize]; + if model::kernel_decode(&r.window.plan.params, &packets[index], &mut weights) != 0 { + return Err(KarLevelsError::NonFinite); + } + let mut out = vec![0f32; r.shape.rows as usize]; + if model::kernel_multiply(&weights, x, r.shape.columns, r.shape.rows, 1, &mut out) != 0 { + return Err(KarLevelsError::NonFinite); + } + Ok(out) + }; + let gate = apply(0, input)?; + let up = apply(1, input)?; + let mut act = vec![0f32; gate.len()]; + if model::kernel_swiglu(&gate, &up, &mut act) != 0 { + return Err(KarLevelsError::NonFinite); + } + apply(2, &act) +} diff --git a/crates/model-format/src/kar_levels/impl_fmt_display_for.rs b/crates/model-format/src/kar_levels/impl_fmt_display_for.rs new file mode 100644 index 00000000..d299a759 --- /dev/null +++ b/crates/model-format/src/kar_levels/impl_fmt_display_for.rs @@ -0,0 +1,227 @@ +//! Moved out of the parent module by STRA-338: impl fmt_Display_for, impl std_error_Error, impl TensorClass, impl ClassLevels, fn check_level, impl ArchiveView .... + +#[allow(unused_imports)] +use super::*; + +impl fmt::Display for KarLevelsError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Self::Policy(reason) | Self::Overlay(reason) => f.write_str(reason), + Self::UnknownTensor(name) => write!(f, "KAR tensor {name} is not a NESTED record"), + Self::Window { tensor, reason } => write!(f, "{tensor}: {reason}"), + Self::Read => f.write_str("KAR archive range read failed"), + Self::HostAllocation => f.write_str("KAR host packet allocation failed"), + Self::Layout(reason) => f.write_str(reason), + Self::NonFinite => f.write_str("KAR expert computation produced a non-finite value"), + Self::Budget { needed, available } => write!( + f, + "KAR scratch needs {needed} bytes but only {available} remain" + ), + } + } +} +impl std::error::Error for KarLevelsError {} +impl TensorClass { + pub const ALL: [TensorClass; 7] = [ + Self::RoutedExpert, + Self::SharedExpert, + Self::DenseFfn, + Self::Attention, + Self::Embedding, + Self::Output, + Self::Other, + ]; + pub fn classify(name: &str) -> Self { + let tail = name.rsplit('.').nth(1).unwrap_or(name); + if tail.ends_with("_exps") { + Self::RoutedExpert + } else if tail.ends_with("_shexp") { + Self::SharedExpert + } else if matches!(tail, "ffn_gate" | "ffn_up" | "ffn_down") { + Self::DenseFfn + } else if tail.starts_with("attn_") || tail.starts_with("ssm_") { + Self::Attention + } else if tail.ends_with("token_embd") { + Self::Embedding + } else if name == "output.weight" { + Self::Output + } else { + Self::Other + } + } + pub(super) fn index(self) -> usize { + Self::ALL + .iter() + .position(|c| *c == self) + .expect("class is in ALL") + } +} +impl ClassLevels { + pub fn uniform(level: u8) -> Result { + check_level(level)?; + Ok(Self { + default: level, + per_class: [None; 7], + }) + } + pub fn with(mut self, class: TensorClass, level: u8) -> Result { + check_level(level)?; + self.per_class[class.index()] = Some(level); + Ok(self) + } + pub fn level_for(&self, class: TensorClass) -> u8 { + self.per_class[class.index()].unwrap_or(self.default) + } +} +pub(super) fn check_level(level: u8) -> Result<()> { + if (MIN_LEVEL..=MAX_LEVEL).contains(&level) { + Ok(()) + } else { + Err(KarLevelsError::Policy("KAR policy level must be 2..=5")) + } +} +impl ArchiveView { + /// `records` must come from an archive whose payload CRCs and full SHA-256 + /// were verified by the caller; this only re-validates record layouts. + pub fn from_records( + sha256: [u8; 32], + archive_bytes: u64, + records: Vec, + ) -> Result { + let mut map = BTreeMap::new(); + for record in records { + let section_end = record + .section_offset + .checked_add(record.section_bytes) + .ok_or(KarLevelsError::Overlay("KAR section overflows"))?; + if record.validate().is_err() || section_end > archive_bytes { + return Err(KarLevelsError::Overlay( + "KAR record layout is invalid or outside its archive", + )); + } + if map.insert(record.name.clone(), record).is_some() { + return Err(KarLevelsError::Overlay("duplicate KAR record name")); + } + } + Ok(Self { + sha256, + archive_bytes, + records: map, + }) + } + pub fn from_inspection( + inspection: &KarInspection, + sha256: [u8; 32], + ) -> std::result::Result> { + let records = inspection.nested_records()?; + Ok(Self::from_records( + sha256, + inspection.summary().archive_bytes, + records, + )?) + } + pub fn records(&self) -> impl Iterator { + self.records.values() + } + pub fn sha256(&self) -> &[u8; 32] { + &self.sha256 + } + pub fn archive_bytes(&self) -> u64 { + self.archive_bytes + } +} + +impl KarLevelSelector { + /// Overlay records must replace same-named base records with identical + /// shape; anything else is a mapping the resolver should have rejected. + pub fn new( + base: ArchiveView, + overlay: Option, + policy: LevelPolicy, + ) -> Result { + if let Some(overlay) = &overlay { + if overlay.sha256 == base.sha256 { + return Err(KarLevelsError::Overlay( + "overlay archive is the base archive", + )); + } + for (name, replacement) in &overlay.records { + let Some(original) = base.records.get(name) else { + return Err(KarLevelsError::Overlay( + "overlay record has no base record to replace", + )); + }; + if original.dimensions != replacement.dimensions + || original.n_elements != replacement.n_elements + { + return Err(KarLevelsError::Overlay( + "overlay record shape differs from its base record", + )); + } + } + } + Ok(Self { + base, + overlay, + policy, + }) + } + + /// Which archive serves `name` and at which level, per class policy. + pub fn resolve(&self, name: &str) -> Result> { + let class = TensorClass::classify(name); + let (slot, record, level) = match self.overlay.as_ref().and_then(|o| o.records.get(name)) { + Some(record) => ( + ArchiveSlot::Overlay, + record, + self.policy.overlay.level_for(class), + ), + None => { + let record = self + .base + .records + .get(name) + .ok_or_else(|| KarLevelsError::UnknownTensor(name.to_owned()))?; + (ArchiveSlot::Base, record, self.policy.base.level_for(class)) + } + }; + Ok(Selection { + class, + slot, + level, + record, + }) + } + + pub fn archive(&self, slot: ArchiveSlot) -> Option<&ArchiveView> { + match slot { + ArchiveSlot::Base => Some(&self.base), + ArchiveSlot::Overlay => self.overlay.as_ref(), + } + } + + /// Compressed bytes if every named tensor stayed resident at its selected + /// level (the libkar `kar_reserve` prefix), checked against a budget. + pub fn resident_bytes<'a>( + &self, + names: impl IntoIterator, + budget: u64, + ) -> Result { + let mut total = 0u64; + for name in names { + total = total + .checked_add(self.resolve(name)?.resident_prefix_bytes()?) + .ok_or(KarLevelsError::Budget { + needed: u64::MAX, + available: budget, + })?; + } + if total > budget { + return Err(KarLevelsError::Budget { + needed: total, + available: budget, + }); + } + Ok(total) + } +} diff --git a/crates/model-format/src/kar_levels/impl_selection.rs b/crates/model-format/src/kar_levels/impl_selection.rs new file mode 100644 index 00000000..9cadde76 --- /dev/null +++ b/crates/model-format/src/kar_levels/impl_selection.rs @@ -0,0 +1,227 @@ +//! Moved out of the parent module by STRA-338: impl Selection, fn align, impl GpuWindow, impl RowShape, impl GpuRows, impl ScratchBytes .... + +#[allow(unused_imports)] +use super::*; + + +impl Selection<'_> { + pub(super) fn window_error(&self, reason: KernelModelError) -> KarLevelsError { + KarLevelsError::Window { + tensor: self.record.name.clone(), + reason, + } + } + + /// Bytes the whole level-`level` prefix of this record occupies when kept + /// resident compressed (section start through the last used plane). + pub fn resident_prefix_bytes(&self) -> Result { + let r = self.record; + if !(r.planes_min..=r.planes_max).contains(&self.level) { + return Err(self.window_error(KernelModelError::Rejected( + "KAR level is outside the record's certified dial", + ))); + } + r.planes_offset + .checked_sub(r.section_offset) + .and_then(|prefix| { + prefix.checked_add(u64::from(self.level) * u64::from(r.plane_stride_bytes)) + }) + .filter(|bytes| *bytes <= r.section_bytes) + .ok_or(KarLevelsError::Overlay("invalid KAR resident prefix size")) + } + + /// Bounded flat element window `[start, start + count)`. + pub fn window(&self, start: u64, count: u64) -> Result { + let plan = model::plan_window(self.record, self.level, start, count) + .map_err(|reason| self.window_error(reason))?; + Ok(GpuWindow::new(self.slot, plan)) + } + + /// `rows` complete rows from `first_row`, ready for the F32 multiply. + pub fn rows(&self, first_row: u64, rows: u64, tokens: u32) -> Result { + let plan = model::plan_rows(self.record, self.level, first_row, rows) + .map_err(|reason| self.window_error(reason))?; + GpuRows::new(self.slot, plan, tokens) + } + + /// One expert matrix of a `[cols, rows, experts]` record. + pub fn expert(&self, expert: u64, tokens: u32) -> Result { + let (first, rows) = + model::expert_rows(self.record, expert).map_err(|reason| self.window_error(reason))?; + self.rows(first, rows, tokens) + } +} + +// ---------------------------------------------------------------- GPU plans + +pub(super) fn align(bytes: u64) -> u64 { + bytes.div_ceil(SCRATCH_ALIGN) * SCRATCH_ALIGN +} +impl GpuWindow { + pub(super) fn new(slot: ArchiveSlot, plan: WindowPlan) -> Self { + Self { slot, plan } + } + /// Archive bytes the stager copies into the packet (no padding). + pub fn staged_source_bytes(&self) -> u64 { + self.plan.staged_source_bytes() + } + /// Device scratch for decode only: packet + F32 output + status word. + pub fn scratch(&self) -> ScratchBytes { + ScratchBytes::of(&[ + u64::from(self.plan.params.packet_bytes), + u64::from(self.plan.params.count) * 4, + STATUS_BYTES, + ]) + } +} +impl RowShape { + pub fn weights_bytes(&self) -> u64 { + u64::from(self.columns) * u64::from(self.rows) * 4 + } + pub fn input_bytes(&self) -> u64 { + u64::from(self.columns) * u64::from(self.tokens) * 4 + } + pub fn output_bytes(&self) -> u64 { + u64::from(self.rows) * u64::from(self.tokens) * 4 + } +} +impl GpuRows { + pub(super) fn new(slot: ArchiveSlot, plan: RowPlan, tokens: u32) -> Result { + if tokens == 0 || tokens > MAX_TOKENS { + return Err(KarLevelsError::Policy("KAR multiply tokens must be 1..=8")); + } + Ok(Self { + window: GpuWindow::new(slot, plan.window), + shape: RowShape { + columns: plan.columns, + rows: plan.rows, + tokens, + }, + }) + } + /// packet + decoded F32 weights + input + output + status, each aligned. + pub fn scratch(&self) -> ScratchBytes { + ScratchBytes::of(&[ + u64::from(self.window.plan.params.packet_bytes), + self.shape.weights_bytes(), + self.shape.input_bytes(), + self.shape.output_bytes(), + STATUS_BYTES, + ]) + } +} +impl ScratchBytes { + pub fn of(buffers: &[u64]) -> Self { + Self { + raw: buffers.iter().sum(), + aligned: buffers.iter().map(|b| align(*b)).sum(), + } + } +} +impl ScratchBudget { + pub fn new(limit: u64) -> Self { + Self { limit, reserved: 0 } + } + pub fn remaining(&self) -> u64 { + self.limit - self.reserved + } + pub fn reserve(&mut self, scratch: ScratchBytes) -> Result<()> { + let available = self.remaining(); + if scratch.aligned > available { + return Err(KarLevelsError::Budget { + needed: scratch.aligned, + available, + }); + } + self.reserved += scratch.aligned; + Ok(()) + } + pub fn release(&mut self, scratch: ScratchBytes) { + self.reserved = self.reserved.saturating_sub(scratch.aligned); + } + /// Largest single-window requirement when one scratch set is reused. + pub fn peak(scratch: impl IntoIterator) -> u64 { + scratch.into_iter().map(|s| s.aligned).max().unwrap_or(0) + } +} + +/// GGUF-style tensor name of one routed-expert bank (`role` 0 gate, 1 up, 2 down). +pub fn expert_tensor_name(layer: u32, role: usize) -> String { + format!("blk.{layer}.{}.weight", EXPERT_ROLES[role]) +} + +impl KarLevelSelector { + /// Every layer x gate/up/down bank exists with exactly `[hidden, ff, + /// experts]` (down: `[ff, hidden, experts]`) and the first and last expert + /// are plannable at the selected level. Called at load, never lazily. + pub fn validate_expert_map( + &self, + layers: u32, + experts: u32, + hidden: u64, + ff: u64, + ) -> Result<()> { + for layer in 0..layers { + for role in 0..3 { + let selection = self.resolve(&expert_tensor_name(layer, role))?; + let want = if role == 2 { + [ff, hidden, u64::from(experts)] + } else { + [hidden, ff, u64::from(experts)] + }; + if selection.record.dimensions != want { + return Err(KarLevelsError::Layout("KAR expert tensor shape differs")); + } + for expert in [0, u64::from(experts) - 1] { + selection.expert(expert, 1)?; + } + } + } + Ok(()) + } + + /// Plan the three matrices of one routed expert at their policy levels. + pub fn plan_expert(&self, layer: u32, expert: u32) -> Result<[GpuRows; 3]> { + let plan = |role| -> Result { + self.resolve(&expert_tensor_name(layer, role))? + .expert(u64::from(expert), 1) + }; + Ok([plan(0)?, plan(1)?, plan(2)?]) + } +} +#[cfg(any(unix, windows))] +impl RangeSource for KarInspection { + fn read_exact_at(&self, offset: u64, out: &mut [u8]) -> std::result::Result<(), KarError> { + KarInspection::read_exact_at(self, offset, out) + } +} +impl RangeSource for [u8] { + fn read_exact_at(&self, offset: u64, out: &mut [u8]) -> std::result::Result<(), KarError> { + let end = offset + .checked_add(out.len() as u64) + .filter(|end| *end <= self.len() as u64) + .ok_or(KarError::Range("image read exceeds the archive"))?; + out.copy_from_slice(&self[offset as usize..end as usize]); + Ok(()) + } +} + +/// Copy exactly the planned archive ranges into a zeroed packet. +pub fn stage_window(source: &S, plan: &WindowPlan) -> Result> { + let len = plan.packet_bytes() as usize; + let mut packet = Vec::new(); + packet + .try_reserve_exact(len) + .map_err(|_| KarLevelsError::HostAllocation)?; + packet.resize(len, 0); + for range in plan.ranges() { + let (at, size) = (range.packet_offset as usize, range.len as usize); + let slot = packet.get_mut(at..at + size).ok_or(KarLevelsError::Layout( + "KAR packet range escapes its packet", + ))?; + source + .read_exact_at(range.archive_offset, slot) + .map_err(|_| KarLevelsError::Read)?; + } + Ok(packet) +} diff --git a/crates/model-format/src/ple_reader.rs b/crates/model-format/src/ple_reader.rs index 82e2c6d1..2aa9a7e8 100644 --- a/crates/model-format/src/ple_reader.rs +++ b/crates/model-format/src/ple_reader.rs @@ -58,45 +58,9 @@ pub trait PageSource: Send + Sync + 'static { } } -impl PageSource for File { - fn read_at(&self, buf: &mut [u8], offset: u64) -> io::Result { - #[cfg(unix)] - { - std::os::unix::fs::FileExt::read_at(self, buf, offset) - } - #[cfg(windows)] - { - std::os::windows::fs::FileExt::seek_read(self, buf, offset) - } - #[cfg(not(any(unix, windows)))] - { - let _ = (buf, offset); - Err(io::Error::new( - io::ErrorKind::Unsupported, - "positional reads unavailable", - )) - } - } - - fn len(&self) -> io::Result { - Ok(self.metadata()?.len()) - } -} - #[derive(Clone, Debug, PartialEq, Eq)] pub struct PleError(pub String); -impl fmt::Display for PleError { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - f.write_str(&self.0) - } -} -impl std::error::Error for PleError {} - -fn err(message: impl Into) -> Result { - Err(PleError(format!("PleReader: {}", message.into()))) -} - #[derive(Clone, Debug)] pub struct PleReaderConfig { /// Byte offset of row 0 in the file. @@ -115,20 +79,6 @@ pub struct PleReaderConfig { pub expected_len: Option, } -impl PleReaderConfig { - pub fn new(table_offset: u64, n_rows: u64) -> Self { - Self { - table_offset, - n_rows, - row_bytes: ROW_BYTES, - max_inflight: 64, - cache_rows: 0, - io_threads: None, - expected_len: None, - } - } -} - #[derive(Clone, Debug, Default)] pub struct ReaderStats { /// Rows asked for. @@ -155,18 +105,6 @@ pub struct ReaderStats { pub read_us: Vec, } -impl ReaderStats { - pub fn percentile(&self, q: f64) -> f64 { - if self.read_us.is_empty() { - return 0.0; - } - let mut v = self.read_us.clone(); - let k = ((q * (v.len() - 1) as f64 + 0.5) as usize).min(v.len() - 1); - v.select_nth_unstable_by(k, f32::total_cmp); - f64::from(v[k]) - } -} - /// Set-associative row cache: 8 ways per set, round-robin replacement inside a /// set. Bounded by construction. #[derive(Debug, Default)] @@ -179,67 +117,6 @@ pub struct RowCache { used: u64, } -impl RowCache { - pub fn new(rows: u64, row_bytes: usize) -> Self { - let sets = rows / WAYS as u64; - let slots = (sets as usize) * WAYS; - Self { - sets, - rb: row_bytes, - keys: vec![EMPTY; slots], - data: vec![0; slots * row_bytes], - next: vec![0; sets as usize], - used: 0, - } - } - - fn mix(row: u32) -> u64 { - let x = u64::from(row).wrapping_mul(0x9E37_79B9_7F4A_7C15); - x ^ (x >> 29) - } - - pub fn capacity(&self) -> u64 { - self.sets * WAYS as u64 - } - - pub fn len(&self) -> u64 { - self.used - } - - pub fn is_empty(&self) -> bool { - self.used == 0 - } - - pub fn find(&self, row: u32) -> Option<&[u8]> { - if self.sets == 0 { - return None; - } - let s = (Self::mix(row) % self.sets) as usize; - (0..WAYS) - .find(|&w| self.keys[s * WAYS + w] == row) - .map(|w| { - let at = (s * WAYS + w) * self.rb; - &self.data[at..at + self.rb] - }) - } - - pub fn insert(&mut self, row: u32, bytes: &[u8]) { - if self.sets == 0 || self.find(row).is_some() { - return; - } - debug_assert_eq!(bytes.len(), self.rb); - let s = (Self::mix(row) % self.sets) as usize; - let w = usize::from(self.next[s]); - self.next[s] = ((w + 1) % WAYS) as u8; - if self.keys[s * WAYS + w] == EMPTY { - self.used += 1; - } - self.keys[s * WAYS + w] = row; - let at = (s * WAYS + w) * self.rb; - self.data[at..at + self.rb].copy_from_slice(bytes); - } -} - /// One row inside a read. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub struct Use { @@ -258,58 +135,6 @@ pub struct PlannedRead { pub uses: Vec, } -/// Plan the reads of a ticket exactly as `PleReader::issue` does: cache hits -/// and out-of-range rows are resolved into `out` immediately, the rest are -/// grouped by first page (a later row on the page may widen the read to two -/// pages) and sorted by offset. -pub fn plan_reads( - rows: &[u32], - cfg: &PleReaderConfig, - cache: &RowCache, - out: &mut [u8], - stats: &mut ReaderStats, -) -> Vec { - let rb = cfg.row_bytes; - let mut by_page: HashMap = HashMap::new(); - let mut jobs: Vec = Vec::new(); - for (i, &row) in rows.iter().enumerate() { - let dst = &mut out[i * rb..(i + 1) * rb]; - stats.requests += 1; - if u64::from(row) >= cfg.n_rows { - dst.fill(0); - continue; - } - if let Some(hit) = cache.find(row) { - dst.copy_from_slice(hit); - stats.cache_hits += 1; - continue; - } - let at = cfg.table_offset + u64::from(row) * rb as u64; - let first = at / PAGE as u64 * PAGE as u64; - let length = ((at + rb as u64 - 1) / PAGE as u64 * PAGE as u64 - first) as usize + PAGE; - let used = Use { - row, - in_page: (at - first) as usize, - slot: i, - }; - if let Some(&j) = by_page.get(&first) { - jobs[j].length = jobs[j].length.max(length); - jobs[j].uses.push(used); - stats.dedup_rows += 1; - } else { - by_page.insert(first, jobs.len()); - jobs.push(PlannedRead { - offset: first, - length, - uses: vec![used], - }); - } - } - // Sorted by offset: prefill chunks then read the SSD in near-sequential order. - jobs.sort_by_key(|job| job.offset); - jobs -} - struct Job { read: PlannedRead, ticket: u32, @@ -354,13 +179,6 @@ struct Shared { keep_cv: Condvar, } -fn lock(m: &Mutex) -> MutexGuard<'_, State> { - // A panicking worker must not wedge the reader: the data is still coherent - // (every mutation is completed before the lock is released) and the error - // path reports failures through `State::error`. - m.lock().unwrap_or_else(|poisoned| poisoned.into_inner()) -} - /// Heap buffer whose usable window starts on a 4 KiB boundary, for unbuffered sources. struct AlignedBuf { raw: Vec, @@ -368,238 +186,6 @@ struct AlignedBuf { len: usize, } -impl AlignedBuf { - fn new(len: usize) -> Self { - let raw = vec![0u8; len + PAGE]; - let start = (PAGE - raw.as_ptr() as usize % PAGE) % PAGE; - Self { raw, start, len } - } - fn window(&mut self, len: usize) -> &mut [u8] { - &mut self.raw[self.start..self.start + len.min(self.len)] - } -} - -/// Whether `source` serves one page-aligned page read at the page holding -/// `offset`, through a 4 KiB-aligned buffer. Used to accept an unbuffered -/// (O_DIRECT) handle only once it demonstrably works on this filesystem. -pub fn probe_aligned_read(source: &dyn PageSource, offset: u64) -> bool { - let mut buf = AlignedBuf::new(PAGE); - let page = offset / PAGE as u64 * PAGE as u64; - matches!(read_full_at(source, buf.window(PAGE), page), Ok(n) if n > 0) -} - -fn read_full_at(source: &dyn PageSource, buf: &mut [u8], offset: u64) -> io::Result { - let mut total = 0; - while total < buf.len() { - match source.read_at(&mut buf[total..], offset + total as u64) { - Ok(0) => break, - Ok(n) => total += n, - Err(e) if e.kind() == io::ErrorKind::Interrupted => {} - Err(e) => return Err(e), - } - } - Ok(total) -} - -impl State { - fn record_latency(&mut self, us: f64) { - self.stats.read_us_sum += us; - if self.stats.read_us.len() < LATENCY_RING { - self.stats.read_us.push(us as f32); - } else { - self.stats.read_us[self.ring_pos % LATENCY_RING] = us as f32; - self.ring_pos += 1; - } - } - - /// A job that will never run: its ticket no longer waits for it. - fn cancel_queued(&mut self) { - let queued: Vec = self.queue.drain(..).collect(); - for job in queued { - self.release(job.ticket); - } - } - - fn release(&mut self, ticket: u32) { - if let Some(t) = self.tickets.get_mut(&ticket) { - t.pending = t.pending.saturating_sub(1); - } - } - - fn fail(&mut self, message: &str) { - if self.error.is_none() { - self.error = Some(PleError(format!("PleReader: {message}"))); - } - self.cancel_queued(); - } - - /// When the next keep-alive read is due, or `None` when none is: it is off, - /// the reader failed, or no rows were asked for within the window (the SSD - /// may then sleep; the next `issue` re-arms it). - fn keepalive_due(&self, now: Instant) -> Option { - let k = &self.keep; - let issued = k.last_issue?; - if k.period.is_zero() || self.error.is_some() || now.duration_since(issued) > k.window { - return None; - } - Some(k.last_read.unwrap_or(issued) + k.period) - } -} - -impl Shared { - /// Run one job: the read happens outside the lock. - fn run(&self, job: Job, issued: Instant, delay: Duration) { - let mut buf = AlignedBuf::new(2 * PAGE); - let length = job.read.length; - // A source that panics is a failed read like any other: the worker survives, the reader fails and every ticket is released. - // Unwinding past this point would end the worker with the job's ticket still pending, and its `collect` would wait for ever. - let read = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { - read_full_at(self.source.as_ref(), buf.window(length), job.read.offset) - })) - .unwrap_or_else(|_| Err(io::Error::other("the page source panicked"))); - let mut late = false; - if !delay.is_zero() { - let spent = issued.elapsed(); - if spent < delay { - late = true; - thread::sleep(delay - spent); - } - } - let mut st = lock(&self.state); - st.inflight -= 1; - if late { - st.stats.late_injected += 1; - } - let elapsed_us = issued.elapsed().as_secs_f64() * 1e6; - if job.keepalive { - // A failed keep-alive turns the keep-alive off, not the reader. - match read { - Ok(_) => { - st.stats.keepalive_reads += 1; - st.stats.keepalive_us_max = st.stats.keepalive_us_max.max(elapsed_us); - } - Err(_) => st.keep.period = Duration::ZERO, - } - drop(st); - self.work.notify_all(); - self.done.notify_all(); - return; - } - match read { - Err(e) => { - st.fail(&format!("a table read failed ({e})")); - st.release(job.ticket); - } - Ok(bytes) => { - st.record_latency(elapsed_us); - st.stats.bytes += bytes as u64; - let rb = self.cfg.row_bytes; - if job.read.uses.iter().any(|u| u.in_page + rb > bytes) { - st.fail("short read inside the table"); - st.release(job.ticket); - } else { - let data = buf.window(length); - for u in &job.read.uses { - let row = &data[u.in_page..u.in_page + rb]; - if let Some(t) = st.tickets.get_mut(&job.ticket) { - t.out[u.slot * rb..(u.slot + 1) * rb].copy_from_slice(row); - } - st.cache.insert(u.row, row); - } - st.release(job.ticket); - } - } - } - drop(st); - self.work.notify_all(); - self.done.notify_all(); - } - - /// Take the next job (marking it in flight) or `None` when there is none. - fn start(&self, st: &mut State) -> Option<(Job, Instant, Duration)> { - let job = st.queue.pop_front()?; - let now = Instant::now(); - st.inflight += 1; - st.keep.last_read = Some(now); - if !job.keepalive { - st.stats.reads += 1; - } - Some((job, now, st.delay)) - } - - fn worker(self: &Arc) { - loop { - let started = { - let mut st = lock(&self.state); - loop { - if st.stop && st.queue.is_empty() { - return; - } - if let Some(started) = self.start(&mut st) { - break started; - } - st = self.work.wait(st).unwrap_or_else(|p| p.into_inner()); - } - }; - self.run(started.0, started.1, started.2); - } - } - - fn keepalive_worker(self: &Arc) { - let mut st = lock(&self.state); - while !st.stop { - let now = Instant::now(); - match st.keepalive_due(now) { - None => st = self.keep_cv.wait(st).unwrap_or_else(|p| p.into_inner()), - Some(due) if now >= due => { - if st.queue.is_empty() && st.inflight == 0 { - // One page of the table, a different one each time, so the - // SSD really reads (not its controller's buffer). - st.keep.rng ^= st.keep.rng << 13; - st.keep.rng ^= st.keep.rng >> 7; - st.keep.rng ^= st.keep.rng << 17; - let first = self.cfg.table_offset / PAGE as u64; - let end = (self.cfg.table_offset - + self.cfg.n_rows * self.cfg.row_bytes as u64) - / PAGE as u64; - let page = first - + if end > first { - st.keep.rng % (end - first) - } else { - 0 - }; - st.queue.push_back(Job { - read: PlannedRead { - offset: page * PAGE as u64, - length: PAGE, - uses: Vec::new(), - }, - ticket: 0, - keepalive: true, - }); - self.work.notify_one(); - } - // Re-evaluate after the period (or when woken). - let wait = st.keep.period.max(Duration::from_millis(1)); - st = self - .keep_cv - .wait_timeout(st, wait) - .unwrap_or_else(|p| p.into_inner()) - .0; - } - Some(due) => { - let wait = (due - now).max(Duration::from_millis(1)); - st = self - .keep_cv - .wait_timeout(st, wait) - .unwrap_or_else(|p| p.into_inner()) - .0; - } - } - } - } -} - /// Handle to a ticket issued by [`PleReader::issue`]. Dropping it without /// collecting abandons the rows (reads in flight still warm the cache). pub struct Ticket { @@ -607,284 +193,24 @@ pub struct Ticket { shared: Arc, } -impl Drop for Ticket { - fn drop(&mut self) { - lock(&self.shared.state).tickets.remove(&self.id); - } -} - pub struct PleReader { shared: Arc, workers: Vec>, keepalive: Option>, } -impl PleReader { - /// `source` is the table's file. The table must fit exactly in it from - /// `table_offset` (the caller's GGUF parse checks that; the length is - /// checked here too). - pub fn open(source: Arc, cfg: PleReaderConfig) -> Result { - if cfg.max_inflight == 0 || cfg.max_inflight > 1024 { - return err("max_inflight must be 1..1024"); - } - if cfg.row_bytes == 0 || cfg.row_bytes > PAGE { - return err("row_bytes must be 1..4096"); - } - if cfg.n_rows > u64::from(EMPTY) { - return err("the row count exceeds the 32-bit row index"); - } - let table_end = cfg - .n_rows - .checked_mul(cfg.row_bytes as u64) - .and_then(|bytes| bytes.checked_add(cfg.table_offset)); - let len = source - .len() - .map_err(|e| PleError(format!("PleReader: cannot size the table file ({e})")))?; - if table_end.is_none_or(|end| end > len) { - return err("the table extends past the end of the file"); - } - if cfg.expected_len.is_some_and(|expected| expected != len) { - return err("the table file changed size after verification"); - } - let threads = match cfg.io_threads { - None => cfg.max_inflight.min(DEFAULT_IO_THREADS), - Some(n) => n.min(cfg.max_inflight), - }; - let seed = 0x9E37_79B9_7F4A_7C15 - ^ std::time::SystemTime::now() - .duration_since(std::time::UNIX_EPOCH) - .map_or(1, |d| d.as_micros() as u64); - let state = State { - queue: VecDeque::new(), - tickets: HashMap::new(), - next_ticket: 1, - cache: RowCache::new(cfg.cache_rows, cfg.row_bytes), - stats: ReaderStats::default(), - ring_pos: 0, - delay: Duration::ZERO, - error: None, - stop: false, - inflight: 0, - keep: KeepAlive { - rng: if seed == 0 { 1 } else { seed }, - ..KeepAlive::default() - }, - }; - let shared = Arc::new(Shared { - source, - inline: threads == 0, - cfg, - state: Mutex::new(state), - work: Condvar::new(), - done: Condvar::new(), - keep_cv: Condvar::new(), - }); - let mut reader = Self { - shared: Arc::clone(&shared), - workers: Vec::new(), - keepalive: None, - }; - for index in 0..threads { - let worker = Arc::clone(&shared); - let spawned = thread::Builder::new() - .name(format!("ple-reader-{index}")) - .spawn(move || worker.worker()); - match spawned { - Ok(handle) => reader.workers.push(handle), - Err(e) => return err(format!("cannot create I/O worker: {e}")), - } - } - Ok(reader) - } - - pub fn row_bytes(&self) -> usize { - self.shared.cfg.row_bytes - } - - pub fn rows(&self) -> u64 { - self.shared.cfg.n_rows - } - - /// Start fetching `rows`; row `i`'s raw bytes land at `row_bytes * i` of - /// the buffer `collect` returns. Out-of-range rows produce zero bytes. - pub fn issue(&self, rows: &[u32]) -> Ticket { - let shared = &self.shared; - let rb = shared.cfg.row_bytes; - let mut st = lock(&shared.state); - let id = st.next_ticket; - st.next_ticket = st.next_ticket.wrapping_add(1).max(1); - let now = Instant::now(); - let rearm = !st.keep.period.is_zero() - && st - .keep - .last_issue - .is_none_or(|last| now.duration_since(last) > st.keep.window); - st.keep.last_issue = Some(now); - let mut out = vec![0u8; rows.len() * rb]; - let State { cache, stats, .. } = &mut *st; - let reads = plan_reads(rows, &shared.cfg, cache, &mut out, stats); - let mut pending = reads.len(); - if st.error.is_some() { - pending = 0; // the reader failed: `collect` reports it, nothing is queued - } else { - for read in reads { - st.queue.push_back(Job { - read, - ticket: id, - keepalive: false, - }); - } - } - st.tickets.insert(id, TicketState { pending, out }); - drop(st); - if pending > 0 { - shared.work.notify_all(); - } - if rearm || pending > 0 { - shared.keep_cv.notify_all(); - } - Ticket { - id, - shared: Arc::clone(shared), - } - } - - /// Block until every row of the ticket is in the returned buffer. - pub fn collect(&self, ticket: Ticket) -> Result, PleError> { - let shared = &self.shared; - if !Arc::ptr_eq(&ticket.shared, shared) { - return err("ticket from another reader"); - } - let start = Instant::now(); - let mut st = lock(&shared.state); - if !st.tickets.contains_key(&ticket.id) { - return err("unknown ticket"); - } - loop { - let pending = st.tickets.get(&ticket.id).map_or(0, |t| t.pending); - if pending == 0 { - break; - } - if shared.inline { - // No workers: this thread performs the reads itself. - if let Some((job, issued, delay)) = shared.start(&mut st) { - drop(st); - shared.run(job, issued, delay); - st = lock(&shared.state); - continue; - } - } - st = shared.done.wait(st).unwrap_or_else(|p| p.into_inner()); - } - if let Some(e) = st.error.clone() { - return Err(e); - } - st.stats.wait_us += start.elapsed().as_secs_f64() * 1e6; - let out = st.tickets.remove(&ticket.id).map(|t| t.out); - drop(st); - // The same-FD size observation the verified GGUF reader makes around its streams. - if let Some(expected) = shared.cfg.expected_len { - match shared.source.len() { - Ok(len) if len == expected => {} - _ => { - let mut st = lock(&shared.state); - st.fail("the table file changed size after verification"); - return Err(st - .error - .clone() - .unwrap_or_else(|| PleError("PleReader: size check failed".into()))); - } - } - } - out.ok_or_else(|| PleError("PleReader: unknown ticket".into())) - } - - /// `issue` then `collect`. - pub fn read_rows(&self, rows: &[u32]) -> Result, PleError> { - self.collect(self.issue(rows)) - } - - /// Keep the SSD awake while the table is in use (worker mode only; call - /// after `open`): when no read has gone out for `period`, one page of the - /// table is read, until `window` after the last `issue`. A keep-alive read - /// that fails turns it off. A zero period turns it off. - pub fn set_keepalive(&mut self, period: Duration, window: Duration) { - let threaded = !self.shared.inline; - { - let mut st = lock(&self.shared.state); - st.keep.period = if threaded { period } else { Duration::ZERO }; - st.keep.window = window; - } - if threaded && !period.is_zero() && self.keepalive.is_none() { - let worker = Arc::clone(&self.shared); - if let Ok(handle) = thread::Builder::new() - .name("ple-reader-keepalive".into()) - .spawn(move || worker.keepalive_worker()) - { - self.keepalive = Some(handle); - } - } - self.shared.keep_cv.notify_all(); - } - - /// Fault injection for tests and for the plan's P2 exit check: every read - /// completes no earlier than `delay` after it was issued. Zero disables. - pub fn set_injected_delay(&self, delay: Duration) { - lock(&self.shared.state).delay = delay; - } - - /// A consistent copy of the counters. - pub fn snapshot(&self) -> ReaderStats { - lock(&self.shared.state).stats.clone() - } - - pub fn reset_stats(&self) { - let mut st = lock(&self.shared.state); - st.stats = ReaderStats::default(); - st.ring_pos = 0; - } - - pub fn cache_capacity(&self) -> u64 { - lock(&self.shared.state).cache.capacity() - } - - pub fn cache_size(&self) -> u64 { - lock(&self.shared.state).cache.len() - } - - /// Stop the workers (unsubmitted work is dropped, reads in flight finish). - pub fn close(&mut self) { - { - let mut st = lock(&self.shared.state); - st.stop = true; - st.cancel_queued(); - } - self.shared.work.notify_all(); - self.shared.keep_cv.notify_all(); - self.shared.done.notify_all(); - for handle in self.workers.drain(..) { - let _ = handle.join(); - } - if let Some(handle) = self.keepalive.take() { - let _ = handle.join(); - } - } -} - -impl fmt::Debug for PleReader { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - f.debug_struct("PleReader") - .field("rows", &self.shared.cfg.n_rows) - .field("workers", &self.workers.len()) - .finish() - } -} - -impl Drop for PleReader { - fn drop(&mut self) { - self.close(); - } -} - #[cfg(test)] mod tests; + +mod impl_pagesource_for_file; +#[allow(unused_imports)] +pub use impl_pagesource_for_file::*; +mod impl_state; +#[allow(unused_imports)] +pub use impl_state::*; +mod impl_plereader; +#[allow(unused_imports)] +pub use impl_plereader::*; +mod impl_fmt_debug_for; +#[allow(unused_imports)] +pub use impl_fmt_debug_for::*; diff --git a/crates/model-format/src/ple_reader/impl_fmt_debug_for.rs b/crates/model-format/src/ple_reader/impl_fmt_debug_for.rs new file mode 100644 index 00000000..64f70ced --- /dev/null +++ b/crates/model-format/src/ple_reader/impl_fmt_debug_for.rs @@ -0,0 +1,20 @@ +//! Moved out of the parent module by STRA-338: impl fmt_Debug_for, impl Drop_for_PleReader. + +#[allow(unused_imports)] +use super::*; + + +impl fmt::Debug for PleReader { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_struct("PleReader") + .field("rows", &self.shared.cfg.n_rows) + .field("workers", &self.workers.len()) + .finish() + } +} + +impl Drop for PleReader { + fn drop(&mut self) { + self.close(); + } +} diff --git a/crates/model-format/src/ple_reader/impl_pagesource_for_file.rs b/crates/model-format/src/ple_reader/impl_pagesource_for_file.rs new file mode 100644 index 00000000..4b1d6cb8 --- /dev/null +++ b/crates/model-format/src/ple_reader/impl_pagesource_for_file.rs @@ -0,0 +1,220 @@ +//! Moved out of the parent module by STRA-338: impl PageSource_for_File, impl fmt_Display_for, impl std_error_Error, fn err, impl PleReaderConfig, impl ReaderStats .... + +#[allow(unused_imports)] +use super::*; + + +impl PageSource for File { + fn read_at(&self, buf: &mut [u8], offset: u64) -> io::Result { + #[cfg(unix)] + { + std::os::unix::fs::FileExt::read_at(self, buf, offset) + } + #[cfg(windows)] + { + std::os::windows::fs::FileExt::seek_read(self, buf, offset) + } + #[cfg(not(any(unix, windows)))] + { + let _ = (buf, offset); + Err(io::Error::new( + io::ErrorKind::Unsupported, + "positional reads unavailable", + )) + } + } + + fn len(&self) -> io::Result { + Ok(self.metadata()?.len()) + } +} + +impl fmt::Display for PleError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str(&self.0) + } +} +impl std::error::Error for PleError {} + +pub(super) fn err(message: impl Into) -> Result { + Err(PleError(format!("PleReader: {}", message.into()))) +} + +impl PleReaderConfig { + pub fn new(table_offset: u64, n_rows: u64) -> Self { + Self { + table_offset, + n_rows, + row_bytes: ROW_BYTES, + max_inflight: 64, + cache_rows: 0, + io_threads: None, + expected_len: None, + } + } +} + +impl ReaderStats { + pub fn percentile(&self, q: f64) -> f64 { + if self.read_us.is_empty() { + return 0.0; + } + let mut v = self.read_us.clone(); + let k = ((q * (v.len() - 1) as f64 + 0.5) as usize).min(v.len() - 1); + v.select_nth_unstable_by(k, f32::total_cmp); + f64::from(v[k]) + } +} + +impl RowCache { + pub fn new(rows: u64, row_bytes: usize) -> Self { + let sets = rows / WAYS as u64; + let slots = (sets as usize) * WAYS; + Self { + sets, + rb: row_bytes, + keys: vec![EMPTY; slots], + data: vec![0; slots * row_bytes], + next: vec![0; sets as usize], + used: 0, + } + } + + pub(super) fn mix(row: u32) -> u64 { + let x = u64::from(row).wrapping_mul(0x9E37_79B9_7F4A_7C15); + x ^ (x >> 29) + } + + pub fn capacity(&self) -> u64 { + self.sets * WAYS as u64 + } + + pub fn len(&self) -> u64 { + self.used + } + + pub fn is_empty(&self) -> bool { + self.used == 0 + } + + pub fn find(&self, row: u32) -> Option<&[u8]> { + if self.sets == 0 { + return None; + } + let s = (Self::mix(row) % self.sets) as usize; + (0..WAYS) + .find(|&w| self.keys[s * WAYS + w] == row) + .map(|w| { + let at = (s * WAYS + w) * self.rb; + &self.data[at..at + self.rb] + }) + } + + pub fn insert(&mut self, row: u32, bytes: &[u8]) { + if self.sets == 0 || self.find(row).is_some() { + return; + } + debug_assert_eq!(bytes.len(), self.rb); + let s = (Self::mix(row) % self.sets) as usize; + let w = usize::from(self.next[s]); + self.next[s] = ((w + 1) % WAYS) as u8; + if self.keys[s * WAYS + w] == EMPTY { + self.used += 1; + } + self.keys[s * WAYS + w] = row; + let at = (s * WAYS + w) * self.rb; + self.data[at..at + self.rb].copy_from_slice(bytes); + } +} + +/// Plan the reads of a ticket exactly as `PleReader::issue` does: cache hits +/// and out-of-range rows are resolved into `out` immediately, the rest are +/// grouped by first page (a later row on the page may widen the read to two +/// pages) and sorted by offset. +pub fn plan_reads( + rows: &[u32], + cfg: &PleReaderConfig, + cache: &RowCache, + out: &mut [u8], + stats: &mut ReaderStats, +) -> Vec { + let rb = cfg.row_bytes; + let mut by_page: HashMap = HashMap::new(); + let mut jobs: Vec = Vec::new(); + for (i, &row) in rows.iter().enumerate() { + let dst = &mut out[i * rb..(i + 1) * rb]; + stats.requests += 1; + if u64::from(row) >= cfg.n_rows { + dst.fill(0); + continue; + } + if let Some(hit) = cache.find(row) { + dst.copy_from_slice(hit); + stats.cache_hits += 1; + continue; + } + let at = cfg.table_offset + u64::from(row) * rb as u64; + let first = at / PAGE as u64 * PAGE as u64; + let length = ((at + rb as u64 - 1) / PAGE as u64 * PAGE as u64 - first) as usize + PAGE; + let used = Use { + row, + in_page: (at - first) as usize, + slot: i, + }; + if let Some(&j) = by_page.get(&first) { + jobs[j].length = jobs[j].length.max(length); + jobs[j].uses.push(used); + stats.dedup_rows += 1; + } else { + by_page.insert(first, jobs.len()); + jobs.push(PlannedRead { + offset: first, + length, + uses: vec![used], + }); + } + } + // Sorted by offset: prefill chunks then read the SSD in near-sequential order. + jobs.sort_by_key(|job| job.offset); + jobs +} + +pub(super) fn lock(m: &Mutex) -> MutexGuard<'_, State> { + // A panicking worker must not wedge the reader: the data is still coherent + // (every mutation is completed before the lock is released) and the error + // path reports failures through `State::error`. + m.lock().unwrap_or_else(|poisoned| poisoned.into_inner()) +} + +impl AlignedBuf { + pub(super) fn new(len: usize) -> Self { + let raw = vec![0u8; len + PAGE]; + let start = (PAGE - raw.as_ptr() as usize % PAGE) % PAGE; + Self { raw, start, len } + } + pub(super) fn window(&mut self, len: usize) -> &mut [u8] { + &mut self.raw[self.start..self.start + len.min(self.len)] + } +} + +/// Whether `source` serves one page-aligned page read at the page holding +/// `offset`, through a 4 KiB-aligned buffer. Used to accept an unbuffered +/// (O_DIRECT) handle only once it demonstrably works on this filesystem. +pub fn probe_aligned_read(source: &dyn PageSource, offset: u64) -> bool { + let mut buf = AlignedBuf::new(PAGE); + let page = offset / PAGE as u64 * PAGE as u64; + matches!(read_full_at(source, buf.window(PAGE), page), Ok(n) if n > 0) +} + +pub(super) fn read_full_at(source: &dyn PageSource, buf: &mut [u8], offset: u64) -> io::Result { + let mut total = 0; + while total < buf.len() { + match source.read_at(&mut buf[total..], offset + total as u64) { + Ok(0) => break, + Ok(n) => total += n, + Err(e) if e.kind() == io::ErrorKind::Interrupted => {} + Err(e) => return Err(e), + } + } + Ok(total) +} diff --git a/crates/model-format/src/ple_reader/impl_plereader.rs b/crates/model-format/src/ple_reader/impl_plereader.rs new file mode 100644 index 00000000..aa435509 --- /dev/null +++ b/crates/model-format/src/ple_reader/impl_plereader.rs @@ -0,0 +1,257 @@ +//! Moved out of the parent module by STRA-338: impl PleReader. + +#[allow(unused_imports)] +use super::*; + + +impl PleReader { + /// `source` is the table's file. The table must fit exactly in it from + /// `table_offset` (the caller's GGUF parse checks that; the length is + /// checked here too). + pub fn open(source: Arc, cfg: PleReaderConfig) -> Result { + if cfg.max_inflight == 0 || cfg.max_inflight > 1024 { + return err("max_inflight must be 1..1024"); + } + if cfg.row_bytes == 0 || cfg.row_bytes > PAGE { + return err("row_bytes must be 1..4096"); + } + if cfg.n_rows > u64::from(EMPTY) { + return err("the row count exceeds the 32-bit row index"); + } + let table_end = cfg + .n_rows + .checked_mul(cfg.row_bytes as u64) + .and_then(|bytes| bytes.checked_add(cfg.table_offset)); + let len = source + .len() + .map_err(|e| PleError(format!("PleReader: cannot size the table file ({e})")))?; + if table_end.is_none_or(|end| end > len) { + return err("the table extends past the end of the file"); + } + if cfg.expected_len.is_some_and(|expected| expected != len) { + return err("the table file changed size after verification"); + } + let threads = match cfg.io_threads { + None => cfg.max_inflight.min(DEFAULT_IO_THREADS), + Some(n) => n.min(cfg.max_inflight), + }; + let seed = 0x9E37_79B9_7F4A_7C15 + ^ std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .map_or(1, |d| d.as_micros() as u64); + let state = State { + queue: VecDeque::new(), + tickets: HashMap::new(), + next_ticket: 1, + cache: RowCache::new(cfg.cache_rows, cfg.row_bytes), + stats: ReaderStats::default(), + ring_pos: 0, + delay: Duration::ZERO, + error: None, + stop: false, + inflight: 0, + keep: KeepAlive { + rng: if seed == 0 { 1 } else { seed }, + ..KeepAlive::default() + }, + }; + let shared = Arc::new(Shared { + source, + inline: threads == 0, + cfg, + state: Mutex::new(state), + work: Condvar::new(), + done: Condvar::new(), + keep_cv: Condvar::new(), + }); + let mut reader = Self { + shared: Arc::clone(&shared), + workers: Vec::new(), + keepalive: None, + }; + for index in 0..threads { + let worker = Arc::clone(&shared); + let spawned = thread::Builder::new() + .name(format!("ple-reader-{index}")) + .spawn(move || worker.worker()); + match spawned { + Ok(handle) => reader.workers.push(handle), + Err(e) => return err(format!("cannot create I/O worker: {e}")), + } + } + Ok(reader) + } + + pub fn row_bytes(&self) -> usize { + self.shared.cfg.row_bytes + } + + pub fn rows(&self) -> u64 { + self.shared.cfg.n_rows + } + + /// Start fetching `rows`; row `i`'s raw bytes land at `row_bytes * i` of + /// the buffer `collect` returns. Out-of-range rows produce zero bytes. + pub fn issue(&self, rows: &[u32]) -> Ticket { + let shared = &self.shared; + let rb = shared.cfg.row_bytes; + let mut st = lock(&shared.state); + let id = st.next_ticket; + st.next_ticket = st.next_ticket.wrapping_add(1).max(1); + let now = Instant::now(); + let rearm = !st.keep.period.is_zero() + && st + .keep + .last_issue + .is_none_or(|last| now.duration_since(last) > st.keep.window); + st.keep.last_issue = Some(now); + let mut out = vec![0u8; rows.len() * rb]; + let State { cache, stats, .. } = &mut *st; + let reads = plan_reads(rows, &shared.cfg, cache, &mut out, stats); + let mut pending = reads.len(); + if st.error.is_some() { + pending = 0; // the reader failed: `collect` reports it, nothing is queued + } else { + for read in reads { + st.queue.push_back(Job { + read, + ticket: id, + keepalive: false, + }); + } + } + st.tickets.insert(id, TicketState { pending, out }); + drop(st); + if pending > 0 { + shared.work.notify_all(); + } + if rearm || pending > 0 { + shared.keep_cv.notify_all(); + } + Ticket { + id, + shared: Arc::clone(shared), + } + } + + /// Block until every row of the ticket is in the returned buffer. + pub fn collect(&self, ticket: Ticket) -> Result, PleError> { + let shared = &self.shared; + if !Arc::ptr_eq(&ticket.shared, shared) { + return err("ticket from another reader"); + } + let start = Instant::now(); + let mut st = lock(&shared.state); + if !st.tickets.contains_key(&ticket.id) { + return err("unknown ticket"); + } + loop { + let pending = st.tickets.get(&ticket.id).map_or(0, |t| t.pending); + if pending == 0 { + break; + } + if shared.inline { + // No workers: this thread performs the reads itself. + if let Some((job, issued, delay)) = shared.start(&mut st) { + drop(st); + shared.run(job, issued, delay); + st = lock(&shared.state); + continue; + } + } + st = shared.done.wait(st).unwrap_or_else(|p| p.into_inner()); + } + if let Some(e) = st.error.clone() { + return Err(e); + } + st.stats.wait_us += start.elapsed().as_secs_f64() * 1e6; + let out = st.tickets.remove(&ticket.id).map(|t| t.out); + drop(st); + // The same-FD size observation the verified GGUF reader makes around its streams. + if let Some(expected) = shared.cfg.expected_len { + match shared.source.len() { + Ok(len) if len == expected => {} + _ => { + let mut st = lock(&shared.state); + st.fail("the table file changed size after verification"); + return Err(st + .error + .clone() + .unwrap_or_else(|| PleError("PleReader: size check failed".into()))); + } + } + } + out.ok_or_else(|| PleError("PleReader: unknown ticket".into())) + } + + /// `issue` then `collect`. + pub fn read_rows(&self, rows: &[u32]) -> Result, PleError> { + self.collect(self.issue(rows)) + } + + /// Keep the SSD awake while the table is in use (worker mode only; call + /// after `open`): when no read has gone out for `period`, one page of the + /// table is read, until `window` after the last `issue`. A keep-alive read + /// that fails turns it off. A zero period turns it off. + pub fn set_keepalive(&mut self, period: Duration, window: Duration) { + let threaded = !self.shared.inline; + { + let mut st = lock(&self.shared.state); + st.keep.period = if threaded { period } else { Duration::ZERO }; + st.keep.window = window; + } + if threaded && !period.is_zero() && self.keepalive.is_none() { + let worker = Arc::clone(&self.shared); + if let Ok(handle) = thread::Builder::new() + .name("ple-reader-keepalive".into()) + .spawn(move || worker.keepalive_worker()) + { + self.keepalive = Some(handle); + } + } + self.shared.keep_cv.notify_all(); + } + + /// Fault injection for tests and for the plan's P2 exit check: every read + /// completes no earlier than `delay` after it was issued. Zero disables. + pub fn set_injected_delay(&self, delay: Duration) { + lock(&self.shared.state).delay = delay; + } + + /// A consistent copy of the counters. + pub fn snapshot(&self) -> ReaderStats { + lock(&self.shared.state).stats.clone() + } + + pub fn reset_stats(&self) { + let mut st = lock(&self.shared.state); + st.stats = ReaderStats::default(); + st.ring_pos = 0; + } + + pub fn cache_capacity(&self) -> u64 { + lock(&self.shared.state).cache.capacity() + } + + pub fn cache_size(&self) -> u64 { + lock(&self.shared.state).cache.len() + } + + /// Stop the workers (unsubmitted work is dropped, reads in flight finish). + pub fn close(&mut self) { + { + let mut st = lock(&self.shared.state); + st.stop = true; + st.cancel_queued(); + } + self.shared.work.notify_all(); + self.shared.keep_cv.notify_all(); + self.shared.done.notify_all(); + for handle in self.workers.drain(..) { + let _ = handle.join(); + } + if let Some(handle) = self.keepalive.take() { + let _ = handle.join(); + } + } +} diff --git a/crates/model-format/src/ple_reader/impl_state.rs b/crates/model-format/src/ple_reader/impl_state.rs new file mode 100644 index 00000000..7caca794 --- /dev/null +++ b/crates/model-format/src/ple_reader/impl_state.rs @@ -0,0 +1,210 @@ +//! Moved out of the parent module by STRA-338: impl State, impl Shared, impl Drop_for_Ticket. + +#[allow(unused_imports)] +use super::*; + + +impl State { + pub(super) fn record_latency(&mut self, us: f64) { + self.stats.read_us_sum += us; + if self.stats.read_us.len() < LATENCY_RING { + self.stats.read_us.push(us as f32); + } else { + self.stats.read_us[self.ring_pos % LATENCY_RING] = us as f32; + self.ring_pos += 1; + } + } + + /// A job that will never run: its ticket no longer waits for it. + pub(super) fn cancel_queued(&mut self) { + let queued: Vec = self.queue.drain(..).collect(); + for job in queued { + self.release(job.ticket); + } + } + + pub(super) fn release(&mut self, ticket: u32) { + if let Some(t) = self.tickets.get_mut(&ticket) { + t.pending = t.pending.saturating_sub(1); + } + } + + pub(super) fn fail(&mut self, message: &str) { + if self.error.is_none() { + self.error = Some(PleError(format!("PleReader: {message}"))); + } + self.cancel_queued(); + } + + /// When the next keep-alive read is due, or `None` when none is: it is off, + /// the reader failed, or no rows were asked for within the window (the SSD + /// may then sleep; the next `issue` re-arms it). + pub(super) fn keepalive_due(&self, now: Instant) -> Option { + let k = &self.keep; + let issued = k.last_issue?; + if k.period.is_zero() || self.error.is_some() || now.duration_since(issued) > k.window { + return None; + } + Some(k.last_read.unwrap_or(issued) + k.period) + } +} + +impl Shared { + /// Run one job: the read happens outside the lock. + pub(super) fn run(&self, job: Job, issued: Instant, delay: Duration) { + let mut buf = AlignedBuf::new(2 * PAGE); + let length = job.read.length; + // A source that panics is a failed read like any other: the worker survives, the reader fails and every ticket is released. + // Unwinding past this point would end the worker with the job's ticket still pending, and its `collect` would wait for ever. + let read = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { + read_full_at(self.source.as_ref(), buf.window(length), job.read.offset) + })) + .unwrap_or_else(|_| Err(io::Error::other("the page source panicked"))); + let mut late = false; + if !delay.is_zero() { + let spent = issued.elapsed(); + if spent < delay { + late = true; + thread::sleep(delay - spent); + } + } + let mut st = lock(&self.state); + st.inflight -= 1; + if late { + st.stats.late_injected += 1; + } + let elapsed_us = issued.elapsed().as_secs_f64() * 1e6; + if job.keepalive { + // A failed keep-alive turns the keep-alive off, not the reader. + match read { + Ok(_) => { + st.stats.keepalive_reads += 1; + st.stats.keepalive_us_max = st.stats.keepalive_us_max.max(elapsed_us); + } + Err(_) => st.keep.period = Duration::ZERO, + } + drop(st); + self.work.notify_all(); + self.done.notify_all(); + return; + } + match read { + Err(e) => { + st.fail(&format!("a table read failed ({e})")); + st.release(job.ticket); + } + Ok(bytes) => { + st.record_latency(elapsed_us); + st.stats.bytes += bytes as u64; + let rb = self.cfg.row_bytes; + if job.read.uses.iter().any(|u| u.in_page + rb > bytes) { + st.fail("short read inside the table"); + st.release(job.ticket); + } else { + let data = buf.window(length); + for u in &job.read.uses { + let row = &data[u.in_page..u.in_page + rb]; + if let Some(t) = st.tickets.get_mut(&job.ticket) { + t.out[u.slot * rb..(u.slot + 1) * rb].copy_from_slice(row); + } + st.cache.insert(u.row, row); + } + st.release(job.ticket); + } + } + } + drop(st); + self.work.notify_all(); + self.done.notify_all(); + } + + /// Take the next job (marking it in flight) or `None` when there is none. + pub(super) fn start(&self, st: &mut State) -> Option<(Job, Instant, Duration)> { + let job = st.queue.pop_front()?; + let now = Instant::now(); + st.inflight += 1; + st.keep.last_read = Some(now); + if !job.keepalive { + st.stats.reads += 1; + } + Some((job, now, st.delay)) + } + + pub(super) fn worker(self: &Arc) { + loop { + let started = { + let mut st = lock(&self.state); + loop { + if st.stop && st.queue.is_empty() { + return; + } + if let Some(started) = self.start(&mut st) { + break started; + } + st = self.work.wait(st).unwrap_or_else(|p| p.into_inner()); + } + }; + self.run(started.0, started.1, started.2); + } + } + + pub(super) fn keepalive_worker(self: &Arc) { + let mut st = lock(&self.state); + while !st.stop { + let now = Instant::now(); + match st.keepalive_due(now) { + None => st = self.keep_cv.wait(st).unwrap_or_else(|p| p.into_inner()), + Some(due) if now >= due => { + if st.queue.is_empty() && st.inflight == 0 { + // One page of the table, a different one each time, so the + // SSD really reads (not its controller's buffer). + st.keep.rng ^= st.keep.rng << 13; + st.keep.rng ^= st.keep.rng >> 7; + st.keep.rng ^= st.keep.rng << 17; + let first = self.cfg.table_offset / PAGE as u64; + let end = (self.cfg.table_offset + + self.cfg.n_rows * self.cfg.row_bytes as u64) + / PAGE as u64; + let page = first + + if end > first { + st.keep.rng % (end - first) + } else { + 0 + }; + st.queue.push_back(Job { + read: PlannedRead { + offset: page * PAGE as u64, + length: PAGE, + uses: Vec::new(), + }, + ticket: 0, + keepalive: true, + }); + self.work.notify_one(); + } + // Re-evaluate after the period (or when woken). + let wait = st.keep.period.max(Duration::from_millis(1)); + st = self + .keep_cv + .wait_timeout(st, wait) + .unwrap_or_else(|p| p.into_inner()) + .0; + } + Some(due) => { + let wait = (due - now).max(Duration::from_millis(1)); + st = self + .keep_cv + .wait_timeout(st, wait) + .unwrap_or_else(|p| p.into_inner()) + .0; + } + } + } + } +} + +impl Drop for Ticket { + fn drop(&mut self) { + lock(&self.shared.state).tickets.remove(&self.id); + } +} diff --git a/crates/model-format/src/qwen4exp.rs b/crates/model-format/src/qwen4exp.rs index d7a2eca9..b289b7ea 100644 --- a/crates/model-format/src/qwen4exp.rs +++ b/crates/model-format/src/qwen4exp.rs @@ -106,30 +106,6 @@ pub enum BindingError { Io(Box), } -impl fmt::Display for BindingError { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - match self { - Self::Identity(shard) => write!(f, "artifact identity rejected for shard {shard}"), - Self::Split(field) => write!(f, "split metadata rejected: {field}"), - Self::Metadata(field) => write!(f, "model metadata rejected: {field}"), - Self::Tokenizer(field) => write!(f, "tokenizer metadata rejected: {field}"), - Self::Role(role) => write!(f, "tensor role rejected: {role}"), - Self::Geometry(role) => write!(f, "tensor geometry rejected: {role}"), - Self::Range(role) => write!(f, "tensor range rejected: {role}"), - Self::Io(_) => f.write_str("GGUF stream I/O failed"), - } - } -} - -impl Error for BindingError { - fn source(&self) -> Option<&(dyn Error + 'static)> { - match self { - Self::Io(error) => Some(error.as_ref()), - _ => None, - } - } -} - #[derive(Clone, Debug, PartialEq)] pub struct Qwen4ExpTopology { architecture: String, @@ -178,67 +154,6 @@ macro_rules! topology_u32_accessors { )+}; } -impl Qwen4ExpTopology { - pub fn architecture(&self) -> &str { - &self.architecture - } - pub fn rms_epsilon(&self) -> f64 { - self.rms_epsilon - } - pub fn rope_frequency_base(&self) -> f64 { - self.rope_frequency_base - } - pub fn compression_ratios(&self) -> &[u64] { - &self.compression_ratios - } - pub fn rope_dimension_sections(&self) -> &[u64] { - &self.rope_dimension_sections - } - pub fn ple_layers(&self) -> &[u64] { - &self.ple_layers - } - pub fn ple_head_offsets(&self) -> &[u64] { - &self.ple_head_offsets - } - pub fn ple_head_vocab_sizes(&self) -> &[u64] { - &self.ple_head_vocab_sizes - } - pub fn ple_layer_multipliers(&self) -> &[u64] { - &self.ple_layer_multipliers - } - topology_u32_accessors!( - block_count => block_count, - embedding_length => embedding_length, - context_length => context_length, - full_attention_interval => full_attention_interval, - expert_count => expert_count, - expert_used_count => expert_used_count, - expert_feed_forward_length => expert_feed_forward_length, - expert_shared_feed_forward_length => expert_shared_feed_forward_length, - attention_head_count => attention_head_count, - attention_head_count_kv => attention_head_count_kv, - attention_key_length => attention_key_length, - attention_value_length => attention_value_length, - hc_count => hc_count, - hc_low_rank => hc_low_rank, - rope_dimension_count => rope_dimension_count, - indexer_head_count => indexer_head_count, - indexer_key_length => indexer_key_length, - indexer_top_k => indexer_top_k, - ssm_conv_kernel => ssm_conv_kernel, - ssm_state_size => ssm_state_size, - ssm_group_count => ssm_group_count, - ssm_time_step_rank => ssm_time_step_rank, - ssm_inner_size => ssm_inner_size, - per_layer_embedding_length => per_layer_embedding_length, - ple_ngram_size => ple_ngram_size, - ple_heads_per_ngram => ple_heads_per_ngram, - ple_conv_kernel => ple_conv_kernel, - ple_eos_token_id => ple_eos_token_id, - ple_image_token_id => ple_image_token_id, - ); -} - #[derive(Clone, Debug, Eq, PartialEq)] pub struct ResolvedTensor { shard: u8, @@ -251,30 +166,6 @@ pub struct ResolvedTensor { file_size: u64, } -impl ResolvedTensor { - pub fn shard(&self) -> u8 { - self.shard - } - pub fn tensor_number(&self) -> usize { - self.tensor_number - } - pub fn name(&self) -> &str { - &self.name - } - pub fn kind(&self) -> u32 { - self.kind - } - pub fn dimensions(&self) -> &[u64] { - &self.dimensions - } - pub fn absolute_start(&self) -> u64 { - self.absolute_start - } - pub fn byte_length(&self) -> u64 { - self.byte_length - } -} - /// A row table inside a verified shard, readable by position. #[derive(Debug)] pub struct RowTableSource { @@ -297,291 +188,6 @@ pub struct Qwen4ExpArtifact { resident_experts: Option, } -impl Qwen4ExpArtifact { - pub fn bind(shard0: VerifiedGgufFile, shard1: VerifiedGgufFile) -> Result { - let owners = [shard0, shard1]; - for (index, owner) in owners.iter().enumerate() { - let (size, digest) = PINNED_IDENTITIES[index]; - if owner.index().summary.file_size != size || owner.artifact_sha256() != digest { - return Err(BindingError::Identity(index as u8)); - } - } - Self::bind_after_identity(owners) - } - - fn bind_after_identity(owners: [VerifiedGgufFile; 2]) -> Result { - let mut owners = owners; - validate_owner_index_split(&owners)?; - let split_metadata = [ - owners[0].split_snapshot().map_err(BindingError::Io)?, - owners[1].split_snapshot().map_err(BindingError::Io)?, - ]; - validate_owner_metadata_split(&split_metadata)?; - let mut snapshots = [ - owners[0].profile_snapshot().map_err(BindingError::Io)?, - owners[1].profile_snapshot().map_err(BindingError::Io)?, - ]; - // Profile/topology admission precedes tokenizer parsing and validation. - if snapshots[0].architecture.as_deref() != Some("qwen4exp") { - return Err(BindingError::Metadata("general.architecture")); - } - if snapshots[1] - .architecture - .as_deref() - .is_some_and(|value| value != "qwen4exp") - { - return Err(BindingError::Metadata("general.architecture")); - } - topology(&snapshots[0])?; - snapshots[0].tokenizer = owners[0].tokenizer_snapshot().map_err(BindingError::Io)?; - let [metadata0, metadata1] = snapshots; - let views = [ - LogicalShardView { - index: owners[0].index(), - metadata: metadata0, - }, - LogicalShardView { - index: owners[1].index(), - metadata: metadata1, - }, - ]; - let validated = validate_logical_views(views)?; - Ok(Self { - shards: owners, - topology: validated.topology, - tokenizer: validated.tokenizer, - roles: validated.roles, - resident_experts: None, - }) - } - - pub fn topology(&self) -> &Qwen4ExpTopology { - &self.topology - } - pub fn tokenizer(&self) -> &TokenizerMetadata { - &self.tokenizer - } - - pub fn tensor(&self, role: TensorRole) -> Result<&ResolvedTensor, BindingError> { - self.roles - .get(&role) - .ok_or(BindingError::Role("not_present")) - } - - /// Recheck the retained verified source without rereading immutable weights. - pub fn validate_tensor_source(&mut self, role: TensorRole) -> Result<(), BindingError> { - let tensor = self - .roles - .get(&role) - .ok_or(BindingError::Role("not_present"))?; - self.shards[tensor.shard as usize] - .stream_tensor(tensor.tensor_number, 0, 0, |_| Ok(())) - .map_err(BindingError::Io) - } - - /// Geometry and a duplicated descriptor of a 2-D row table, for positional - /// batched reads that must return exactly the bytes `stream_row` would. - /// Row 0 and the last row pass the single-row planner's admission. - pub fn row_table_source(&self, role: TensorRole) -> Result { - let tensor = self - .roles - .get(&role) - .ok_or(BindingError::Role("not_present"))?; - if tensor.dimensions.len() != 2 { - return Err(BindingError::Role("rank_mismatch")); - } - let n_rows = tensor.dimensions[1]; - let (first, row_bytes) = plan_row(tensor, 0, None)?; - let (last, _) = plan_row( - tensor, - n_rows - .checked_sub(1) - .ok_or(BindingError::Range("row_index"))?, - None, - )?; - if first != 0 || last != (n_rows - 1) * row_bytes { - return Err(BindingError::Geometry("row_stride")); - } - let file = self.shards[tensor.shard as usize] - .duplicate_descriptor() - .map_err(BindingError::Io)?; - Ok(RowTableSource { - file, - table_offset: tensor.absolute_start, - n_rows, - row_bytes, - file_size: tensor.file_size, - }) - } - - pub fn stream_row( - &mut self, - role: TensorRole, - row: u64, - mut consume: impl FnMut(&[u8]) -> io::Result<()>, - ) -> Result<(), BindingError> { - let tensor = self - .roles - .get(&role) - .ok_or(BindingError::Role("not_present"))?; - let range = plan_row(tensor, row, None)?; - self.shards[tensor.shard as usize] - .stream_tensor(tensor.tensor_number, range.0, range.1, |chunk| { - consume(chunk) - }) - .map_err(BindingError::Io) - } - - /// Whole native token table from the same retained verified GGUF owner. - /// This closed global source does not widen the expert/row planners. - pub fn stream_token_embedding( - &mut self, - consume: impl FnMut(&[u8]) -> io::Result<()>, - ) -> Result<(), BindingError> { - let tensor = self - .roles - .get(&TensorRole::Global(GlobalRole::TokenEmbedding)) - .ok_or(BindingError::Role("not_present"))?; - if tensor.shard != 0 || tensor.dimensions != [2560, 248320] || tensor.byte_length == 0 { - return Err(BindingError::Range("token_embedding_extent")); - } - self.shards[tensor.shard as usize] - .stream_tensor(tensor.tensor_number, 0, tensor.byte_length, consume) - .map_err(BindingError::Io) - } - - pub fn stream_expert_row( - &mut self, - role: TensorRole, - expert: u64, - row: u64, - mut consume: impl FnMut(&[u8]) -> io::Result<()>, - ) -> Result<(), BindingError> { - let tensor = self - .roles - .get(&role) - .ok_or(BindingError::Role("not_present"))?; - let range = plan_row(tensor, row, Some(expert))?; - self.shards[tensor.shard as usize] - .stream_tensor(tensor.tensor_number, range.0, range.1, |chunk| { - consume(chunk) - }) - .map_err(BindingError::Io) - } - - /// Exact existing expert-row planner with a caller-owned initialized final - /// span. No geometry/range widening or source reopen; errors drop the owner. - pub fn read_expert_rows_owned( - &mut self, - role: TensorRole, - expert: u64, - first: u64, - count: u64, - bytes: Box<[u8]>, - ) -> Result, BindingError> { - let tensor = self - .roles - .get(&role) - .ok_or(BindingError::Role("not_present"))?; - let range = plan_stream_rows(tensor, role, first, count, Some(expert))?; - if range.1 != bytes.len() as u64 { - return Err(BindingError::Range("owned_expert_extent")); - } - if let Some(bank) = &self.resident_experts { - let resident = bank.tensor(role, tensor)?; - let bytes = self.shards[tensor.shard as usize] - .copy_resident_tensor(resident, range.0, bytes) - .map_err(BindingError::Io)?; - bank.note_copy(bytes.len()); - Ok(bytes) - } else { - self.shards[tensor.shard as usize] - .read_tensor_owned(tensor.tensor_number, range.0, bytes) - .map_err(BindingError::Io) - } - } - - /// Stream 1..64 ordered rows, or one complete closed MoE matrix. - /// The retained verified file is never reopened. All geometry and complete - /// span checks precede the first callback; chunks may cross row boundaries - /// and remain bounded by the 16 MiB file-stream buffer. - pub fn stream_rows( - &mut self, - role: TensorRole, - first: u64, - count: u64, - consume: impl FnMut(&[u8]) -> io::Result<()>, - ) -> Result<(), BindingError> { - let tensor = self - .roles - .get(&role) - .ok_or(BindingError::Role("not_present"))?; - let range = plan_stream_rows(tensor, role, first, count, None)?; - self.shards[tensor.shard as usize] - .stream_tensor(tensor.tensor_number, range.0, range.1, consume) - .map_err(BindingError::Io) - } - - /// Stream 1..64 rows or one complete closed MoE matrix of one expert. - /// Callback chunk boundaries are independent of encoded row boundaries. - /// File-size checks and consumer-error propagation are the same as for - /// `stream_expert_row`; no decoding or numeric operation is performed. - pub fn stream_expert_rows( - &mut self, - role: TensorRole, - expert: u64, - first: u64, - count: u64, - consume: impl FnMut(&[u8]) -> io::Result<()>, - ) -> Result<(), BindingError> { - let tensor = self - .roles - .get(&role) - .ok_or(BindingError::Role("not_present"))?; - let range = plan_stream_rows(tensor, role, first, count, Some(expert))?; - self.shards[tensor.shard as usize] - .stream_tensor(tensor.tensor_number, range.0, range.1, consume) - .map_err(BindingError::Io) - } -} - -fn validate_owner_index_split(owners: &[VerifiedGgufFile; 2]) -> Result<(), BindingError> { - for (number, owner) in owners.iter().enumerate() { - let summary = &owner.index().summary; - if summary.split_no != Some(number as u64) { - return Err(BindingError::Split("split.no")); - } - if summary.split_count != Some(2) { - return Err(BindingError::Split("split.count")); - } - if summary.split_tensors_count != Some(1224) { - return Err(BindingError::Split("split.tensors.count")); - } - } - for (number, owner) in owners.iter().enumerate() { - let expected = if number == 0 { 1223 } else { 1 }; - if owner.index().tensors.len() != expected { - return Err(BindingError::Split("indexed_tensor_count")); - } - } - Ok(()) -} - -fn validate_owner_metadata_split(metadata: &[MetadataSnapshot; 2]) -> Result<(), BindingError> { - for (number, snapshot) in metadata.iter().enumerate() { - if snapshot.split_no != Some(number as u64) { - return Err(BindingError::Split("split.no")); - } - if snapshot.split_count != Some(2) { - return Err(BindingError::Split("split.count")); - } - if snapshot.split_tensors_count != Some(1224) { - return Err(BindingError::Split("split.tensors.count")); - } - } - Ok(()) -} - struct LogicalShardView<'a> { index: &'a TensorIndex, metadata: MetadataSnapshot, @@ -593,261 +199,6 @@ struct ValidatedBindingView { roles: BTreeMap, } -fn required_uint(metadata: &MetadataSnapshot, key: &'static str) -> Result { - match metadata.values.get(key) { - Some(MetadataValue::Unsigned(value)) => Ok(*value), - Some(MetadataValue::Signed(value)) if *value >= 0 => Ok(*value as u64), - _ => Err(BindingError::Metadata(key)), - } -} - -fn required_u32( - metadata: &MetadataSnapshot, - key: &'static str, - expected: u32, -) -> Result { - let value = required_uint(metadata, key)?; - if value != u64::from(expected) { - return Err(BindingError::Metadata(key)); - } - Ok(expected) -} - -fn required_float(metadata: &MetadataSnapshot, key: &'static str) -> Result { - match metadata.values.get(key) { - Some(MetadataValue::Float(value)) if value.is_finite() && *value > 0.0 => Ok(*value), - Some(MetadataValue::Unsigned(value)) if *value > 0 => Ok(*value as f64), - Some(MetadataValue::Signed(value)) if *value > 0 => Ok(*value as f64), - _ => Err(BindingError::Metadata(key)), - } -} - -fn required_array( - metadata: &MetadataSnapshot, - key: &'static str, - expected: &[u64], -) -> Result, BindingError> { - let values = match metadata.values.get(key) { - Some(MetadataValue::UnsignedArray(values)) => values.clone(), - Some(MetadataValue::SignedArray(values)) => values - .iter() - .map(|value| u64::try_from(*value).map_err(|_| BindingError::Metadata(key))) - .collect::, _>>()?, - _ => return Err(BindingError::Metadata(key)), - }; - if values != expected { - return Err(BindingError::Metadata(key)); - } - Ok(values) -} - -fn topology(metadata: &MetadataSnapshot) -> Result { - if metadata.architecture.as_deref() != Some("qwen4exp") { - return Err(BindingError::Metadata("general.architecture")); - } - let block_count = required_u32(metadata, "qwen4exp.block_count", 48)?; - let embedding_length = required_u32(metadata, "qwen4exp.embedding_length", 2560)?; - let compression_ratios = required_array( - metadata, - "qwen4exp.attention.compress_ratios", - &(0..48) - .map(|layer| if layer % 4 == 3 { 4 } else { 0 }) - .collect::>(), - )?; - let full_attention_interval = required_u32(metadata, "qwen4exp.full_attention_interval", 4)?; - let expert_count = required_u32(metadata, "qwen4exp.expert_count", 512)?; - let expert_used_count = required_u32(metadata, "qwen4exp.expert_used_count", 10)?; - let expert_feed_forward_length = - required_u32(metadata, "qwen4exp.expert_feed_forward_length", 640)?; - let expert_shared_feed_forward_length = - required_u32(metadata, "qwen4exp.expert_shared_feed_forward_length", 640)?; - let attention_head_count = required_u32(metadata, "qwen4exp.attention.head_count", 24)?; - let attention_head_count_kv = required_u32(metadata, "qwen4exp.attention.head_count_kv", 2)?; - let attention_key_length = required_u32(metadata, "qwen4exp.attention.key_length", 256)?; - let attention_value_length = required_u32(metadata, "qwen4exp.attention.value_length", 256)?; - let rms_epsilon = required_float(metadata, "qwen4exp.attention.layer_norm_rms_epsilon")?; - if (rms_epsilon - 1.0e-6).abs() > 1.0e-12 { - return Err(BindingError::Metadata( - "qwen4exp.attention.layer_norm_rms_epsilon", - )); - } - let hc_count = required_u32(metadata, "qwen4exp.hyper_connection.count", 4)?; - let hc_low_rank = required_u32(metadata, "qwen4exp.hyper_connection.low_rank", 320)?; - let rope_dimension_count = required_u32(metadata, "qwen4exp.rope.dimension_count", 64)?; - let rope_dimension_sections = required_array( - metadata, - "qwen4exp.rope.dimension_sections", - &[11, 11, 10, 0], - )?; - let rope_frequency_base = required_float(metadata, "qwen4exp.rope.freq_base")?; - if rope_frequency_base != 10_000_000.0 { - return Err(BindingError::Metadata("qwen4exp.rope.freq_base")); - } - let indexer_head_count = required_u32(metadata, "qwen4exp.attention.indexer.head_count", 4)?; - let indexer_key_length = required_u32(metadata, "qwen4exp.attention.indexer.key_length", 128)?; - let indexer_top_k = required_u32(metadata, "qwen4exp.attention.indexer.top_k", 2048)?; - let ssm_conv_kernel = required_u32(metadata, "qwen4exp.ssm.conv_kernel", 4)?; - let ssm_state_size = required_u32(metadata, "qwen4exp.ssm.state_size", 128)?; - let ssm_group_count = required_u32(metadata, "qwen4exp.ssm.group_count", 16)?; - let ssm_time_step_rank = required_u32(metadata, "qwen4exp.ssm.time_step_rank", 48)?; - let ssm_inner_size = required_u32(metadata, "qwen4exp.ssm.inner_size", 6144)?; - let per_layer_embedding_length = - required_u32(metadata, "qwen4exp.embedding_length_per_layer_input", 160)?; - let ple_layers = required_array(metadata, "qwen4exp.ple.layers", &[1])?; - let ple_ngram_size = required_u32(metadata, "qwen4exp.ple.ngram_size", 3)?; - let ple_heads_per_ngram = required_u32(metadata, "qwen4exp.ple.heads_per_ngram", 8)?; - let ple_conv_kernel = required_u32(metadata, "qwen4exp.ple.conv_kernel", 4)?; - let ple_eos_token_id = required_u32(metadata, "qwen4exp.ple.eos_token_id", 248_044)?; - let ple_image_token_id = required_u32(metadata, "qwen4exp.ple.image_token_id", 248_056)?; - let ple_head_offsets = required_array( - metadata, - "qwen4exp.ple.head_offsets", - &[ - 0, - 20_000_003, - 40_000_026, - 60_000_059, - 80_000_106, - 100_000_165, - 120_000_228, - 140_000_297, - 160_000_374, - 180_000_455, - 200_000_548, - 220_000_655, - 240_000_802, - 260_000_955, - 280_001_114, - 300_001_275, - ], - )?; - let ple_head_vocab_sizes = required_array( - metadata, - "qwen4exp.ple.head_vocab_sizes", - &[ - 20_000_003, 20_000_023, 20_000_033, 20_000_047, 20_000_059, 20_000_063, 20_000_069, - 20_000_077, 20_000_081, 20_000_093, 20_000_107, 20_000_147, 20_000_153, 20_000_159, - 20_000_161, 20_000_171, - ], - )?; - let ple_layer_multipliers = required_array( - metadata, - "qwen4exp.ple.layer_multipliers", - &[23_703_573_157_769, 20_109_073_645_365, 8_052_911_324_071], - )?; - let context_length = required_u32(metadata, "qwen4exp.context_length", 262_144)?; - Ok(Qwen4ExpTopology { - architecture: "qwen4exp".to_owned(), - block_count, - embedding_length, - context_length, - compression_ratios, - full_attention_interval, - expert_count, - expert_used_count, - expert_feed_forward_length, - expert_shared_feed_forward_length, - attention_head_count, - attention_head_count_kv, - attention_key_length, - attention_value_length, - rms_epsilon, - hc_count, - hc_low_rank, - rope_dimension_count, - rope_dimension_sections, - rope_frequency_base, - indexer_head_count, - indexer_key_length, - indexer_top_k, - ssm_conv_kernel, - ssm_state_size, - ssm_group_count, - ssm_time_step_rank, - ssm_inner_size, - per_layer_embedding_length, - ple_layers, - ple_ngram_size, - ple_heads_per_ngram, - ple_conv_kernel, - ple_eos_token_id, - ple_image_token_id, - ple_head_offsets, - ple_head_vocab_sizes, - ple_layer_multipliers, - }) -} - -fn validate_tokenizer(tokenizer: &TokenizerMetadata) -> Result<(), BindingError> { - let id = |name: &str| tokenizer.special_ids.get(name).copied(); - if id("tokenizer.ggml.bos_token_id") != Some(248_044) { - return Err(BindingError::Tokenizer("tokenizer.ggml.bos_token_id")); - } - if id("tokenizer.ggml.padding_token_id") != Some(248_044) { - return Err(BindingError::Tokenizer("tokenizer.ggml.padding_token_id")); - } - if id("tokenizer.ggml.eos_token_id") != Some(248_046) { - return Err(BindingError::Tokenizer("tokenizer.ggml.eos_token_id")); - } - Ok(()) -} - -fn validate_logical_views( - mut shards: [LogicalShardView<'_>; 2], -) -> Result { - for (number, shard) in shards.iter().enumerate() { - let (expected_no, expected_count) = (number as u64, 2); - if shard.index.summary.split_no != Some(expected_no) - || shard.metadata.split_no != Some(expected_no) - { - return Err(BindingError::Split("split.no")); - } - if shard.index.summary.split_count != Some(expected_count) - || shard.metadata.split_count != Some(expected_count) - { - return Err(BindingError::Split("split.count")); - } - if shard.index.summary.split_tensors_count != Some(1224) - || shard.metadata.split_tensors_count != Some(1224) - { - return Err(BindingError::Split("split.tensors.count")); - } - } - for (number, shard) in shards.iter().enumerate() { - let expected_tensors = if number == 0 { 1223 } else { 1 }; - if shard.index.tensors.len() != expected_tensors { - return Err(BindingError::Split("indexed_tensor_count")); - } - } - if shards[0].metadata.architecture.as_deref() != Some("qwen4exp") { - return Err(BindingError::Metadata("general.architecture")); - } - if shards[1] - .metadata - .architecture - .as_deref() - .is_some_and(|value| value != "qwen4exp") - { - return Err(BindingError::Metadata("general.architecture")); - } - let topology = topology(&shards[0].metadata)?; - let tokenizer = gguf::validate_tokenizer_metadata( - shards[0] - .metadata - .tokenizer - .take() - .ok_or(BindingError::Tokenizer("required_fields"))?, - ) - .map_err(|_| BindingError::Tokenizer("invalid_metadata"))?; - validate_tokenizer(&tokenizer)?; - let roles = validate_role_inventory(&shards)?; - Ok(ValidatedBindingView { - topology, - tokenizer, - roles, - }) -} - struct ExpectedTensor { role: TensorRole, name: String, @@ -856,624 +207,6 @@ struct ExpectedTensor { kind: Option, } -fn expected_inventory() -> Vec { - let mut expected = Vec::with_capacity(1224); - let mut add = |role, name: String, dimensions: &[u64], shard, kind| { - expected.push(ExpectedTensor { - role, - name, - dimensions: dimensions.to_vec(), - shard, - kind, - }); - }; - for (role, name, dimensions, kind) in [ - ( - GlobalRole::TokenEmbedding, - "token_embd.weight", - &[2560, 248320][..], - None, - ), - ( - GlobalRole::Output, - "output.weight", - &[2560, 248320][..], - None, - ), - ( - GlobalRole::OutputHcDown, - "output_hc_down.weight", - &[10240, 320][..], - None, - ), - ( - GlobalRole::OutputHcNorm, - "output_hc_norm.weight", - &[10240][..], - Some(0), - ), - ( - GlobalRole::OutputHcUp, - "output_hc_up.weight", - &[320, 10240][..], - None, - ), - ] { - add( - TensorRole::Global(role), - name.to_owned(), - dimensions, - 0, - kind, - ); - } - add( - TensorRole::Global(GlobalRole::PerLayerTokenEmbedding), - "per_layer_token_embd.weight".to_owned(), - &[160, 320_001_536], - 1, - Some(20), - ); - - for layer in 0..48u8 { - let prefix = format!("blk.{layer}."); - let common = [ - ( - LayerRole::HcAttnDown, - "hc_attn_down.weight", - &[10240, 320][..], - None, - ), - ( - LayerRole::HcAttnUp, - "hc_attn_up.weight", - &[320, 10240][..], - None, - ), - ( - LayerRole::HcAttnInject, - "hc_attn_inject.weight", - &[10240, 4][..], - None, - ), - ( - LayerRole::HcAttnNorm, - "hc_attn_norm.weight", - &[10240][..], - Some(0), - ), - ( - LayerRole::HcFfnDown, - "hc_ffn_down.weight", - &[10240, 320][..], - None, - ), - ( - LayerRole::HcFfnUp, - "hc_ffn_up.weight", - &[320, 10240][..], - None, - ), - ( - LayerRole::HcFfnInject, - "hc_ffn_inject.weight", - &[10240, 4][..], - None, - ), - ( - LayerRole::HcFfnNorm, - "hc_ffn_norm.weight", - &[10240][..], - Some(0), - ), - ( - LayerRole::FfnGateInp, - "ffn_gate_inp.weight", - &[2560, 512][..], - Some(30), - ), - ( - LayerRole::FfnGateInpShared, - "ffn_gate_inp_shexp.weight", - &[2560][..], - Some(30), - ), - ( - LayerRole::FfnGateShared, - "ffn_gate_shexp.weight", - &[2560, 640][..], - None, - ), - ( - LayerRole::FfnUpShared, - "ffn_up_shexp.weight", - &[2560, 640][..], - None, - ), - ( - LayerRole::FfnDownShared, - "ffn_down_shexp.weight", - &[640, 2560][..], - None, - ), - ( - LayerRole::FfnGateExperts, - "ffn_gate_exps.weight", - &[2560, 640, 512][..], - None, - ), - ( - LayerRole::FfnUpExperts, - "ffn_up_exps.weight", - &[2560, 640, 512][..], - None, - ), - ( - LayerRole::FfnDownExperts, - "ffn_down_exps.weight", - &[640, 2560, 512][..], - None, - ), - ]; - for (role, name, dimensions, kind) in common { - add( - TensorRole::Layer { layer, role }, - format!("{prefix}{name}"), - dimensions, - 0, - kind, - ); - } - let family = if layer % 4 == 3 { - [ - (LayerRole::AttnQ, "attn_q.weight", &[2560, 12288][..], None), - (LayerRole::AttnK, "attn_k.weight", &[2560, 512][..], None), - (LayerRole::AttnV, "attn_v.weight", &[2560, 512][..], None), - ( - LayerRole::AttnOutput, - "attn_output.weight", - &[6144, 2560][..], - None, - ), - ( - LayerRole::AttnQNorm, - "attn_q_norm.weight", - &[256][..], - Some(0), - ), - ( - LayerRole::AttnKNorm, - "attn_k_norm.weight", - &[256][..], - Some(0), - ), - ( - LayerRole::IndexerQProj, - "indexer.q_proj.weight", - &[2560, 512][..], - None, - ), - ( - LayerRole::IndexerKProj, - "indexer.k_proj.weight", - &[2560, 128][..], - None, - ), - ( - LayerRole::IndexerQNorm, - "indexer.q_norm.weight", - &[128][..], - Some(0), - ), - ( - LayerRole::IndexerKNorm, - "indexer.k_norm.weight", - &[128][..], - Some(0), - ), - ] - .to_vec() - } else { - [ - ( - LayerRole::AttnQkv, - "attn_qkv.weight", - &[2560, 10240][..], - None, - ), - ( - LayerRole::AttnGate, - "attn_gate.weight", - &[2560, 6144][..], - None, - ), - (LayerRole::SsmOut, "ssm_out.weight", &[6144, 2560][..], None), - ( - LayerRole::SsmConv1d, - "ssm_conv1d.weight", - &[4, 10240][..], - None, - ), - ( - LayerRole::SsmAlpha, - "ssm_alpha.weight", - &[2560, 48][..], - None, - ), - (LayerRole::SsmBeta, "ssm_beta.weight", &[2560, 48][..], None), - (LayerRole::SsmA, "ssm_a", &[48][..], Some(0)), - (LayerRole::SsmDtBias, "ssm_dt.bias", &[48][..], Some(0)), - (LayerRole::SsmNorm, "ssm_norm.weight", &[128][..], Some(0)), - ] - .to_vec() - }; - for (role, name, dimensions, kind) in family { - add( - TensorRole::Layer { layer, role }, - format!("{prefix}{name}"), - dimensions, - 0, - kind, - ); - } - if layer == 1 { - for (role, name, dimensions, kind) in [ - ( - LayerRole::PleConv1d, - "ple_conv1d.weight", - &[4, 10240][..], - Some(1), - ), - ( - LayerRole::PleKey, - "ple_key.weight", - &[2560, 10240][..], - Some(30), - ), - ( - LayerRole::PleNormConv, - "ple_norm_conv.weight", - &[10240][..], - Some(0), - ), - ( - LayerRole::PleNormKey, - "ple_norm_key.weight", - &[10240][..], - Some(0), - ), - ( - LayerRole::PleNormQuery, - "ple_norm_query.weight", - &[10240][..], - Some(0), - ), - ( - LayerRole::PleValue, - "ple_value.weight", - &[2560, 2560][..], - Some(30), - ), - ] { - add( - TensorRole::Layer { layer, role }, - format!("{prefix}{name}"), - dimensions, - 0, - kind, - ); - } - } - } - expected -} - -fn validate_role_inventory( - shards: &[LogicalShardView<'_>; 2], -) -> Result, BindingError> { - let expected = expected_inventory(); - if expected.len() != 1224 { - return Err(BindingError::Role("registry_count")); - } - let by_name = expected - .iter() - .map(|item| (item.name.as_str(), item)) - .collect::>(); - let allowed_kinds: BTreeSet = [0, 1, 8, 12, 13, 14, 18, 20, 21, 22, 23, 30, 42] - .into_iter() - .collect(); - let mut actual = BTreeMap::new(); - let mut roles = BTreeMap::new(); - let mut spans: [Vec<(u64, u64)>; 2] = [Vec::new(), Vec::new()]; - for (shard_number, shard) in shards.iter().enumerate() { - for (tensor_number, tensor) in shard.index.tensors.iter().enumerate() { - if actual - .insert( - tensor.name.as_str(), - (shard_number as u8, tensor_number, tensor), - ) - .is_some() - { - return Err(BindingError::Role("duplicate_name")); - } - } - } - for spec in &expected { - let (shard_number, tensor_number, tensor) = actual - .get(spec.name.as_str()) - .ok_or(BindingError::Role("missing_name"))?; - if spec.shard != *shard_number { - return Err(BindingError::Role("wrong_shard")); - } - if tensor.dimensions != spec.dimensions { - return Err(BindingError::Geometry("dimensions")); - } - if !allowed_kinds.contains(&tensor.kind) - || spec.kind.is_some_and(|kind| kind != tensor.kind) - { - return Err(BindingError::Geometry("kind")); - } - let (block_elements, block_bytes) = - gguf::block_geometry(tensor.kind).ok_or(BindingError::Geometry("kind"))?; - if tensor.dimensions.first().copied().unwrap_or(0) == 0 - || tensor.dimensions[0] % block_elements != 0 - { - return Err(BindingError::Geometry("block_alignment")); - } - let elements = tensor - .dimensions - .iter() - .try_fold(1u64, |value, dim| value.checked_mul(*dim)) - .ok_or(BindingError::Geometry("element_count"))?; - let bytes = elements - .checked_div(block_elements) - .and_then(|blocks| blocks.checked_mul(block_bytes)) - .ok_or(BindingError::Geometry("byte_count"))?; - if tensor.bytes == 0 || tensor.bytes != bytes { - return Err(BindingError::Geometry("indexed_byte_count")); - } - let shard = &shards[*shard_number as usize]; - let absolute_start = shard - .index - .summary - .data_start - .checked_add(tensor.offset) - .ok_or(BindingError::Range("absolute_start"))?; - if absolute_start < shard.index.summary.data_start { - return Err(BindingError::Range("data_bounds")); - } - let absolute_end = absolute_start - .checked_add(tensor.bytes) - .ok_or(BindingError::Range("absolute_end"))?; - if absolute_end > shard.index.summary.file_size { - return Err(BindingError::Range("file_bounds")); - } - spans[*shard_number as usize].push((absolute_start, absolute_end)); - let resolved = ResolvedTensor { - shard: *shard_number, - tensor_number: *tensor_number, - name: tensor.name.clone(), - kind: tensor.kind, - dimensions: tensor.dimensions.clone(), - absolute_start, - byte_length: tensor.bytes, - file_size: shard.index.summary.file_size, - }; - if roles.insert(spec.role, resolved).is_some() { - return Err(BindingError::Role("duplicate_role")); - } - } - if actual.keys().any(|name| !by_name.contains_key(name)) || roles.len() != expected.len() { - return Err(BindingError::Role("missing_name")); - } - for span_set in &mut spans { - span_set.sort_unstable(); - if span_set.windows(2).any(|pair| pair[0].1 > pair[1].0) { - return Err(BindingError::Range("overlapping_tensors")); - } - } - Ok(roles) -} - -fn plan_row( - tensor: &ResolvedTensor, - row: u64, - expert: Option, -) -> Result<(u64, u64), BindingError> { - let dimensions = &tensor.dimensions; - match (dimensions.len(), expert) { - (1, None) if matches!(tensor.kind, 0 | 1 | 30) => {} - (1, None) => return Err(BindingError::Geometry("kind")), - (2, None) | (3, Some(_)) => {} - (1 | 2, Some(_)) | (3, None) => return Err(BindingError::Role("rank_mismatch")), - _ => return Err(BindingError::Role("rank")), - } - let (block_elements, block_bytes) = - gguf::block_geometry(tensor.kind).ok_or(BindingError::Geometry("kind"))?; - let dim0 = *dimensions.first().ok_or(BindingError::Geometry("rank"))?; - if dim0 == 0 || dim0 % block_elements != 0 { - return Err(BindingError::Geometry("block_alignment")); - } - let elements = dimensions - .iter() - .try_fold(1u64, |value, dim| value.checked_mul(*dim)) - .ok_or(BindingError::Geometry("element_count"))?; - let indexed_bytes = elements - .checked_div(block_elements) - .and_then(|blocks| blocks.checked_mul(block_bytes)) - .ok_or(BindingError::Geometry("byte_count"))?; - if tensor.byte_length == 0 || indexed_bytes != tensor.byte_length { - return Err(BindingError::Geometry("indexed_byte_count")); - } - let row_bytes = (dim0 / block_elements) - .checked_mul(block_bytes) - .ok_or(BindingError::Range("row_bytes"))?; - let relative = match (dimensions.len(), expert) { - (1, None) if row == 0 => Some(0), - (2, None) if row < dimensions[1] => row.checked_mul(row_bytes), - (3, Some(expert)) if expert < dimensions[2] && row < dimensions[1] => expert - .checked_mul(dimensions[1]) - .and_then(|base| base.checked_add(row)) - .and_then(|index| index.checked_mul(row_bytes)), - (1..=3, _) => return Err(BindingError::Range("row_index")), - _ => unreachable!("rank checked above"), - } - .ok_or(BindingError::Range("row_offset"))?; - if row_bytes == 0 - || relative - .checked_add(row_bytes) - .is_none_or(|end| end > tensor.byte_length) - { - return Err(BindingError::Range("tensor_bounds")); - } - if tensor - .absolute_start - .checked_add(relative) - .and_then(|start| start.checked_add(row_bytes)) - .is_none_or(|end| end > tensor.file_size) - { - return Err(BindingError::Range("file_bounds")); - } - Ok((relative, row_bytes)) -} - -/// Plan an exact finite row tile using the existing single-row geometry -/// admission at both endpoints. The same expert is supplied for both endpoints. -fn plan_rows( - tensor: &ResolvedTensor, - first: u64, - count: u64, - expert: Option, -) -> Result<(u64, u64), BindingError> { - if !(1..=64).contains(&count) { - return Err(BindingError::Range("row_count")); - } - plan_row_span(tensor, first, count, expert) -} - -/// Larger spans are restricted to one complete, source-defined matrix. -/// Other roles and partial ranges retain the existing 64-row admission. -fn plan_stream_rows( - tensor: &ResolvedTensor, - role: TensorRole, - first: u64, - count: u64, - expert: Option, -) -> Result<(u64, u64), BindingError> { - if count <= 64 { - return plan_rows(tensor, first, count, expert); - } - use LayerRole as L; - let (columns, rows, routed) = match role { - TensorRole::Layer { - role: L::FfnGateExperts | L::FfnUpExperts, - .. - } => (2560, 640, true), - TensorRole::Layer { - role: L::FfnDownExperts, - .. - } => (640, 2560, true), - TensorRole::Layer { - role: L::FfnGateShared | L::FfnUpShared, - .. - } => (2560, 640, false), - TensorRole::Layer { - role: L::FfnDownShared, - .. - } => (640, 2560, false), - TensorRole::Layer { - role: L::AttnQkv, .. - } => (2560, 10240, false), - TensorRole::Layer { - role: L::AttnGate, .. - } => (2560, 6144, false), - TensorRole::Layer { - role: L::SsmConv1d, .. - } => (4, 10240, false), - TensorRole::Layer { - layer: 1, - role: L::PleKey, - } if tensor.kind == 30 => (2560, 10240, false), - TensorRole::Layer { - layer: 1, - role: L::PleValue, - } if tensor.kind == 30 => (2560, 2560, false), - TensorRole::Layer { - layer: 1, - role: L::PleConv1d, - } if tensor.kind == 1 => (4, 10240, false), - TensorRole::Layer { - role: L::SsmOut | L::AttnOutput, - .. - } => (6144, 2560, false), - TensorRole::Layer { role: L::AttnQ, .. } => (2560, 12288, false), - TensorRole::Layer { - role: L::AttnK | L::AttnV | L::IndexerQProj | L::FfnGateInp, - .. - } => (2560, 512, false), - TensorRole::Layer { - role: L::IndexerKProj, - .. - } => (2560, 128, false), - TensorRole::Layer { - role: L::HcAttnDown | L::HcFfnDown, - .. - } - | TensorRole::Global(GlobalRole::OutputHcDown) => (10240, 320, false), - TensorRole::Layer { - role: L::HcAttnUp | L::HcFfnUp, - .. - } - | TensorRole::Global(GlobalRole::OutputHcUp) => (320, 10240, false), - // The complete vocabulary-major head / embedding table: the native head and embedding owners - // (`generate.cpp` NativeHead / embedding upload) read each as ONE whole-tensor stream. - TensorRole::Global(GlobalRole::Output | GlobalRole::TokenEmbedding) => (2560, 248320, false), - _ => return Err(BindingError::Range("row_count")), - }; - let expected = [columns, rows, 512]; - if first != 0 - || count != rows - || expert.is_some() != routed - || tensor.dimensions != expected[..if routed { 3 } else { 2 }] - { - return Err(BindingError::Range("row_count")); - } - plan_row_span(tensor, first, count, expert) -} - -fn plan_row_span( - tensor: &ResolvedTensor, - first: u64, - count: u64, - expert: Option, -) -> Result<(u64, u64), BindingError> { - let end_row = first - .checked_add(count) - .ok_or(BindingError::Range("row_index"))?; - let (offset, row_bytes) = plan_row(tensor, first, expert)?; - let (last_offset, last_bytes) = plan_row(tensor, end_row - 1, expert)?; - let bytes = row_bytes - .checked_mul(count) - .ok_or(BindingError::Range("byte_count"))?; - let end = offset - .checked_add(bytes) - .ok_or(BindingError::Range("row_offset"))?; - if last_bytes != row_bytes - || last_offset.checked_add(last_bytes) != Some(end) - || end > tensor.byte_length - { - return Err(BindingError::Range("tensor_bounds")); - } - if tensor - .absolute_start - .checked_add(end) - .is_none_or(|absolute_end| absolute_end > tensor.file_size) - { - return Err(BindingError::Range("file_bounds")); - } - Ok((offset, bytes)) -} - #[cfg(test)] #[path = "../tests/qwen_artifact_binding/mod.rs"] mod qwen_artifact_binding_tests; @@ -1849,163 +582,6 @@ pub struct RoutedMoeSourceScope<'source> { expert_count: u32, resident_experts: Option<&'source expert_source_bank::ResidentExpertBank>, } -impl RoutedMoeSourceScope<'_> { - /// Point the same loan at another expert of its layer: a group fence (one source observation at - /// begin and one at finish) covering every expert of a layer group. Every request after this still - /// rechecks its exact indexed tensor, as before. - pub fn retarget(&mut self, expert: u32) -> Result<(), BindingError> { - if expert >= self.expert_count { - return Err(BindingError::Range("routed_moe_source")); - } - self.expert = expert; - Ok(()) - } - fn role(&self, role: LayerRole) -> Result { - if !matches!( - role, - LayerRole::FfnGateExperts | LayerRole::FfnUpExperts | LayerRole::FfnDownExperts - ) { - return Err(BindingError::Role("routed_moe_source")); - } - Ok(TensorRole::Layer { - layer: self.layer, - role, - }) - } - /// Every request rechecks its exact immutable indexed tensor and empty-span - /// extent. Source length observations belong to begin/explicit finish. - pub fn tensor(&self, role: LayerRole) -> Result<&ResolvedTensor, BindingError> { - let tensor = self - .roles - .get(&self.role(role)?) - .ok_or(BindingError::Role("not_present"))?; - if tensor.shard != 0 { - return Err(BindingError::Geometry("routed_moe_source_shard")); - } - Ok(tensor) - } - pub fn validate_descriptor(&self, role: LayerRole) -> Result<(), BindingError> { - let tensor = self.tensor(role)?; - self.source - .validate_tensor(tensor.tensor_number) - .map_err(BindingError::Io) - } - /// One complete actual matrix of this source's fixed expert only. - pub fn stream_matrix( - &mut self, - role: LayerRole, - consume: impl FnMut(&[u8]) -> io::Result<()>, - ) -> Result<(), BindingError> { - let tensor_role = self.role(role)?; - let tensor = self - .roles - .get(&tensor_role) - .ok_or(BindingError::Role("not_present"))?; - if tensor.shard != 0 { - return Err(BindingError::Geometry("routed_moe_source_shard")); - } - let rows = if role == LayerRole::FfnDownExperts { - 2560 - } else { - 640 - }; - let range = plan_stream_rows(tensor, tensor_role, 0, rows, Some(u64::from(self.expert)))?; - self.source - .stream_tensor(tensor.tensor_number, range.0, range.1, consume) - .map_err(BindingError::Io) - } - /// Whole fixed-expert span into its initialized final owner, retaining the - /// same real source loan and full original stream bounds/size observations. - pub fn read_matrix_owned( - &mut self, - role: LayerRole, - bytes: Box<[u8]>, - ) -> Result, BindingError> { - let tensor_role = self.role(role)?; - let tensor = self - .roles - .get(&tensor_role) - .ok_or(BindingError::Role("not_present"))?; - if tensor.shard != 0 { - return Err(BindingError::Geometry("routed_moe_source_shard")); - } - let rows = if role == LayerRole::FfnDownExperts { - 2560 - } else { - 640 - }; - let range = plan_stream_rows(tensor, tensor_role, 0, rows, Some(u64::from(self.expert)))?; - if range.1 != bytes.len() as u64 { - return Err(BindingError::Range("owned_expert_extent")); - } - if let Some(bank) = self.resident_experts { - let resident = bank.tensor(tensor_role, tensor)?; - let bytes = self - .source - .copy_resident_tensor(resident, range.0, bytes) - .map_err(BindingError::Io)?; - bank.note_copy(bytes.len()); - Ok(bytes) - } else { - self.source - .read_tensor_owned(tensor.tensor_number, range.0, bytes) - .map_err(BindingError::Io) - } - } - - /// No-copy, fixed expert span of the actual retained catalog. The source - /// fence stays held; completion still requires explicit finish. - pub fn resident_matrix_span( - &self, - role: LayerRole, - ) -> Result { - let tensor_role = self.role(role)?; - let tensor = self.tensor(role)?; - self.validate_descriptor(role)?; - let bank = self - .resident_experts - .ok_or(BindingError::Role("resident_expert_source_absent"))?; - bank.span(tensor_role, tensor, self.expert) - } - - /// Consumes the actual source loan. A failed finish is not publication. - pub fn finish(self) -> Result<(), BindingError> { - self.source.finish().map_err(BindingError::Io) - } -} -impl Qwen4ExpArtifact { - pub fn begin_routed_moe_source( - &mut self, - layer: u32, - expert: u32, - ) -> Result, BindingError> { - if layer >= self.topology.block_count || expert >= self.topology.expert_count { - return Err(BindingError::Range("routed_moe_source")); - } - let layer = u8::try_from(layer).map_err(|_| BindingError::Range("layer"))?; - let gate = self - .roles - .get(&TensorRole::Layer { - layer, - role: LayerRole::FfnGateExperts, - }) - .ok_or(BindingError::Role("not_present"))?; - if gate.shard != 0 { - return Err(BindingError::Geometry("routed_moe_source_shard")); - } - let source = self.shards[0] - .begin_source_fence(gate.tensor_number) - .map_err(BindingError::Io)?; - Ok(RoutedMoeSourceScope { - source, - roles: &self.roles, - layer, - expert, - expert_count: self.topology.expert_count, - resident_experts: self.resident_experts.as_ref(), - }) - } -} #[path = "qwen4exp_expert_source_bank.rs"] mod expert_source_bank; @@ -2022,3 +598,28 @@ pub use expert_source_bank::ProvisionalExpertSource; #[path = "qwen4exp_file_expert_source.rs"] mod file_expert_source; pub use file_expert_source::{FileExpertExtent, FileExpertSourceLease}; + +mod impl_fmt_display_for; +#[allow(unused_imports)] +pub use impl_fmt_display_for::*; +mod impl_qwen4expartifact; +#[allow(unused_imports)] +pub use impl_qwen4expartifact::*; +mod validate_owner_index_split; +#[allow(unused_imports)] +pub use validate_owner_index_split::*; +mod validate_logical_views; +#[allow(unused_imports)] +pub use validate_logical_views::*; +mod expected_inventory; +#[allow(unused_imports)] +pub use expected_inventory::*; +mod validate_role_inventory; +#[allow(unused_imports)] +pub use validate_role_inventory::*; +mod plan_stream_rows; +#[allow(unused_imports)] +pub use plan_stream_rows::*; +mod impl_qwen4expartifact_2; +#[allow(unused_imports)] +pub use impl_qwen4expartifact_2::*; diff --git a/crates/model-format/src/qwen4exp/expected_inventory.rs b/crates/model-format/src/qwen4exp/expected_inventory.rs new file mode 100644 index 00000000..b3424915 --- /dev/null +++ b/crates/model-format/src/qwen4exp/expected_inventory.rs @@ -0,0 +1,317 @@ +//! Moved out of the parent module by STRA-338: fn expected_inventory. + +#[allow(unused_imports)] +use super::*; + + +pub(super) fn expected_inventory() -> Vec { + let mut expected = Vec::with_capacity(1224); + let mut add = |role, name: String, dimensions: &[u64], shard, kind| { + expected.push(ExpectedTensor { + role, + name, + dimensions: dimensions.to_vec(), + shard, + kind, + }); + }; + for (role, name, dimensions, kind) in [ + ( + GlobalRole::TokenEmbedding, + "token_embd.weight", + &[2560, 248320][..], + None, + ), + ( + GlobalRole::Output, + "output.weight", + &[2560, 248320][..], + None, + ), + ( + GlobalRole::OutputHcDown, + "output_hc_down.weight", + &[10240, 320][..], + None, + ), + ( + GlobalRole::OutputHcNorm, + "output_hc_norm.weight", + &[10240][..], + Some(0), + ), + ( + GlobalRole::OutputHcUp, + "output_hc_up.weight", + &[320, 10240][..], + None, + ), + ] { + add( + TensorRole::Global(role), + name.to_owned(), + dimensions, + 0, + kind, + ); + } + add( + TensorRole::Global(GlobalRole::PerLayerTokenEmbedding), + "per_layer_token_embd.weight".to_owned(), + &[160, 320_001_536], + 1, + Some(20), + ); + + for layer in 0..48u8 { + let prefix = format!("blk.{layer}."); + let common = [ + ( + LayerRole::HcAttnDown, + "hc_attn_down.weight", + &[10240, 320][..], + None, + ), + ( + LayerRole::HcAttnUp, + "hc_attn_up.weight", + &[320, 10240][..], + None, + ), + ( + LayerRole::HcAttnInject, + "hc_attn_inject.weight", + &[10240, 4][..], + None, + ), + ( + LayerRole::HcAttnNorm, + "hc_attn_norm.weight", + &[10240][..], + Some(0), + ), + ( + LayerRole::HcFfnDown, + "hc_ffn_down.weight", + &[10240, 320][..], + None, + ), + ( + LayerRole::HcFfnUp, + "hc_ffn_up.weight", + &[320, 10240][..], + None, + ), + ( + LayerRole::HcFfnInject, + "hc_ffn_inject.weight", + &[10240, 4][..], + None, + ), + ( + LayerRole::HcFfnNorm, + "hc_ffn_norm.weight", + &[10240][..], + Some(0), + ), + ( + LayerRole::FfnGateInp, + "ffn_gate_inp.weight", + &[2560, 512][..], + Some(30), + ), + ( + LayerRole::FfnGateInpShared, + "ffn_gate_inp_shexp.weight", + &[2560][..], + Some(30), + ), + ( + LayerRole::FfnGateShared, + "ffn_gate_shexp.weight", + &[2560, 640][..], + None, + ), + ( + LayerRole::FfnUpShared, + "ffn_up_shexp.weight", + &[2560, 640][..], + None, + ), + ( + LayerRole::FfnDownShared, + "ffn_down_shexp.weight", + &[640, 2560][..], + None, + ), + ( + LayerRole::FfnGateExperts, + "ffn_gate_exps.weight", + &[2560, 640, 512][..], + None, + ), + ( + LayerRole::FfnUpExperts, + "ffn_up_exps.weight", + &[2560, 640, 512][..], + None, + ), + ( + LayerRole::FfnDownExperts, + "ffn_down_exps.weight", + &[640, 2560, 512][..], + None, + ), + ]; + for (role, name, dimensions, kind) in common { + add( + TensorRole::Layer { layer, role }, + format!("{prefix}{name}"), + dimensions, + 0, + kind, + ); + } + let family = if layer % 4 == 3 { + [ + (LayerRole::AttnQ, "attn_q.weight", &[2560, 12288][..], None), + (LayerRole::AttnK, "attn_k.weight", &[2560, 512][..], None), + (LayerRole::AttnV, "attn_v.weight", &[2560, 512][..], None), + ( + LayerRole::AttnOutput, + "attn_output.weight", + &[6144, 2560][..], + None, + ), + ( + LayerRole::AttnQNorm, + "attn_q_norm.weight", + &[256][..], + Some(0), + ), + ( + LayerRole::AttnKNorm, + "attn_k_norm.weight", + &[256][..], + Some(0), + ), + ( + LayerRole::IndexerQProj, + "indexer.q_proj.weight", + &[2560, 512][..], + None, + ), + ( + LayerRole::IndexerKProj, + "indexer.k_proj.weight", + &[2560, 128][..], + None, + ), + ( + LayerRole::IndexerQNorm, + "indexer.q_norm.weight", + &[128][..], + Some(0), + ), + ( + LayerRole::IndexerKNorm, + "indexer.k_norm.weight", + &[128][..], + Some(0), + ), + ] + .to_vec() + } else { + [ + ( + LayerRole::AttnQkv, + "attn_qkv.weight", + &[2560, 10240][..], + None, + ), + ( + LayerRole::AttnGate, + "attn_gate.weight", + &[2560, 6144][..], + None, + ), + (LayerRole::SsmOut, "ssm_out.weight", &[6144, 2560][..], None), + ( + LayerRole::SsmConv1d, + "ssm_conv1d.weight", + &[4, 10240][..], + None, + ), + ( + LayerRole::SsmAlpha, + "ssm_alpha.weight", + &[2560, 48][..], + None, + ), + (LayerRole::SsmBeta, "ssm_beta.weight", &[2560, 48][..], None), + (LayerRole::SsmA, "ssm_a", &[48][..], Some(0)), + (LayerRole::SsmDtBias, "ssm_dt.bias", &[48][..], Some(0)), + (LayerRole::SsmNorm, "ssm_norm.weight", &[128][..], Some(0)), + ] + .to_vec() + }; + for (role, name, dimensions, kind) in family { + add( + TensorRole::Layer { layer, role }, + format!("{prefix}{name}"), + dimensions, + 0, + kind, + ); + } + if layer == 1 { + for (role, name, dimensions, kind) in [ + ( + LayerRole::PleConv1d, + "ple_conv1d.weight", + &[4, 10240][..], + Some(1), + ), + ( + LayerRole::PleKey, + "ple_key.weight", + &[2560, 10240][..], + Some(30), + ), + ( + LayerRole::PleNormConv, + "ple_norm_conv.weight", + &[10240][..], + Some(0), + ), + ( + LayerRole::PleNormKey, + "ple_norm_key.weight", + &[10240][..], + Some(0), + ), + ( + LayerRole::PleNormQuery, + "ple_norm_query.weight", + &[10240][..], + Some(0), + ), + ( + LayerRole::PleValue, + "ple_value.weight", + &[2560, 2560][..], + Some(30), + ), + ] { + add( + TensorRole::Layer { layer, role }, + format!("{prefix}{name}"), + dimensions, + 0, + kind, + ); + } + } + } + expected +} diff --git a/crates/model-format/src/qwen4exp/impl_fmt_display_for.rs b/crates/model-format/src/qwen4exp/impl_fmt_display_for.rs new file mode 100644 index 00000000..a487fd90 --- /dev/null +++ b/crates/model-format/src/qwen4exp/impl_fmt_display_for.rs @@ -0,0 +1,114 @@ +//! Moved out of the parent module by STRA-338: impl fmt_Display_for, impl Error_for_BindingError, impl Qwen4ExpTopology, impl ResolvedTensor. + +#[allow(unused_imports)] +use super::*; + + +impl fmt::Display for BindingError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Self::Identity(shard) => write!(f, "artifact identity rejected for shard {shard}"), + Self::Split(field) => write!(f, "split metadata rejected: {field}"), + Self::Metadata(field) => write!(f, "model metadata rejected: {field}"), + Self::Tokenizer(field) => write!(f, "tokenizer metadata rejected: {field}"), + Self::Role(role) => write!(f, "tensor role rejected: {role}"), + Self::Geometry(role) => write!(f, "tensor geometry rejected: {role}"), + Self::Range(role) => write!(f, "tensor range rejected: {role}"), + Self::Io(_) => f.write_str("GGUF stream I/O failed"), + } + } +} + +impl Error for BindingError { + fn source(&self) -> Option<&(dyn Error + 'static)> { + match self { + Self::Io(error) => Some(error.as_ref()), + _ => None, + } + } +} + +impl Qwen4ExpTopology { + pub fn architecture(&self) -> &str { + &self.architecture + } + pub fn rms_epsilon(&self) -> f64 { + self.rms_epsilon + } + pub fn rope_frequency_base(&self) -> f64 { + self.rope_frequency_base + } + pub fn compression_ratios(&self) -> &[u64] { + &self.compression_ratios + } + pub fn rope_dimension_sections(&self) -> &[u64] { + &self.rope_dimension_sections + } + pub fn ple_layers(&self) -> &[u64] { + &self.ple_layers + } + pub fn ple_head_offsets(&self) -> &[u64] { + &self.ple_head_offsets + } + pub fn ple_head_vocab_sizes(&self) -> &[u64] { + &self.ple_head_vocab_sizes + } + pub fn ple_layer_multipliers(&self) -> &[u64] { + &self.ple_layer_multipliers + } + topology_u32_accessors!( + block_count => block_count, + embedding_length => embedding_length, + context_length => context_length, + full_attention_interval => full_attention_interval, + expert_count => expert_count, + expert_used_count => expert_used_count, + expert_feed_forward_length => expert_feed_forward_length, + expert_shared_feed_forward_length => expert_shared_feed_forward_length, + attention_head_count => attention_head_count, + attention_head_count_kv => attention_head_count_kv, + attention_key_length => attention_key_length, + attention_value_length => attention_value_length, + hc_count => hc_count, + hc_low_rank => hc_low_rank, + rope_dimension_count => rope_dimension_count, + indexer_head_count => indexer_head_count, + indexer_key_length => indexer_key_length, + indexer_top_k => indexer_top_k, + ssm_conv_kernel => ssm_conv_kernel, + ssm_state_size => ssm_state_size, + ssm_group_count => ssm_group_count, + ssm_time_step_rank => ssm_time_step_rank, + ssm_inner_size => ssm_inner_size, + per_layer_embedding_length => per_layer_embedding_length, + ple_ngram_size => ple_ngram_size, + ple_heads_per_ngram => ple_heads_per_ngram, + ple_conv_kernel => ple_conv_kernel, + ple_eos_token_id => ple_eos_token_id, + ple_image_token_id => ple_image_token_id, + ); +} + +impl ResolvedTensor { + pub fn shard(&self) -> u8 { + self.shard + } + pub fn tensor_number(&self) -> usize { + self.tensor_number + } + pub fn name(&self) -> &str { + &self.name + } + pub fn kind(&self) -> u32 { + self.kind + } + pub fn dimensions(&self) -> &[u64] { + &self.dimensions + } + pub fn absolute_start(&self) -> u64 { + self.absolute_start + } + pub fn byte_length(&self) -> u64 { + self.byte_length + } +} diff --git a/crates/model-format/src/qwen4exp/impl_qwen4expartifact.rs b/crates/model-format/src/qwen4exp/impl_qwen4expartifact.rs new file mode 100644 index 00000000..194ce285 --- /dev/null +++ b/crates/model-format/src/qwen4exp/impl_qwen4expartifact.rs @@ -0,0 +1,253 @@ +//! Moved out of the parent module by STRA-338: impl Qwen4ExpArtifact. + +#[allow(unused_imports)] +use super::*; + + +impl Qwen4ExpArtifact { + pub fn bind(shard0: VerifiedGgufFile, shard1: VerifiedGgufFile) -> Result { + let owners = [shard0, shard1]; + for (index, owner) in owners.iter().enumerate() { + let (size, digest) = PINNED_IDENTITIES[index]; + if owner.index().summary.file_size != size || owner.artifact_sha256() != digest { + return Err(BindingError::Identity(index as u8)); + } + } + Self::bind_after_identity(owners) + } + + pub(super) fn bind_after_identity(owners: [VerifiedGgufFile; 2]) -> Result { + let mut owners = owners; + validate_owner_index_split(&owners)?; + let split_metadata = [ + owners[0].split_snapshot().map_err(BindingError::Io)?, + owners[1].split_snapshot().map_err(BindingError::Io)?, + ]; + validate_owner_metadata_split(&split_metadata)?; + let mut snapshots = [ + owners[0].profile_snapshot().map_err(BindingError::Io)?, + owners[1].profile_snapshot().map_err(BindingError::Io)?, + ]; + // Profile/topology admission precedes tokenizer parsing and validation. + if snapshots[0].architecture.as_deref() != Some("qwen4exp") { + return Err(BindingError::Metadata("general.architecture")); + } + if snapshots[1] + .architecture + .as_deref() + .is_some_and(|value| value != "qwen4exp") + { + return Err(BindingError::Metadata("general.architecture")); + } + topology(&snapshots[0])?; + snapshots[0].tokenizer = owners[0].tokenizer_snapshot().map_err(BindingError::Io)?; + let [metadata0, metadata1] = snapshots; + let views = [ + LogicalShardView { + index: owners[0].index(), + metadata: metadata0, + }, + LogicalShardView { + index: owners[1].index(), + metadata: metadata1, + }, + ]; + let validated = validate_logical_views(views)?; + Ok(Self { + shards: owners, + topology: validated.topology, + tokenizer: validated.tokenizer, + roles: validated.roles, + resident_experts: None, + }) + } + + pub fn topology(&self) -> &Qwen4ExpTopology { + &self.topology + } + pub fn tokenizer(&self) -> &TokenizerMetadata { + &self.tokenizer + } + + pub fn tensor(&self, role: TensorRole) -> Result<&ResolvedTensor, BindingError> { + self.roles + .get(&role) + .ok_or(BindingError::Role("not_present")) + } + + /// Recheck the retained verified source without rereading immutable weights. + pub fn validate_tensor_source(&mut self, role: TensorRole) -> Result<(), BindingError> { + let tensor = self + .roles + .get(&role) + .ok_or(BindingError::Role("not_present"))?; + self.shards[tensor.shard as usize] + .stream_tensor(tensor.tensor_number, 0, 0, |_| Ok(())) + .map_err(BindingError::Io) + } + + /// Geometry and a duplicated descriptor of a 2-D row table, for positional + /// batched reads that must return exactly the bytes `stream_row` would. + /// Row 0 and the last row pass the single-row planner's admission. + pub fn row_table_source(&self, role: TensorRole) -> Result { + let tensor = self + .roles + .get(&role) + .ok_or(BindingError::Role("not_present"))?; + if tensor.dimensions.len() != 2 { + return Err(BindingError::Role("rank_mismatch")); + } + let n_rows = tensor.dimensions[1]; + let (first, row_bytes) = plan_row(tensor, 0, None)?; + let (last, _) = plan_row( + tensor, + n_rows + .checked_sub(1) + .ok_or(BindingError::Range("row_index"))?, + None, + )?; + if first != 0 || last != (n_rows - 1) * row_bytes { + return Err(BindingError::Geometry("row_stride")); + } + let file = self.shards[tensor.shard as usize] + .duplicate_descriptor() + .map_err(BindingError::Io)?; + Ok(RowTableSource { + file, + table_offset: tensor.absolute_start, + n_rows, + row_bytes, + file_size: tensor.file_size, + }) + } + + pub fn stream_row( + &mut self, + role: TensorRole, + row: u64, + mut consume: impl FnMut(&[u8]) -> io::Result<()>, + ) -> Result<(), BindingError> { + let tensor = self + .roles + .get(&role) + .ok_or(BindingError::Role("not_present"))?; + let range = plan_row(tensor, row, None)?; + self.shards[tensor.shard as usize] + .stream_tensor(tensor.tensor_number, range.0, range.1, |chunk| { + consume(chunk) + }) + .map_err(BindingError::Io) + } + + /// Whole native token table from the same retained verified GGUF owner. + /// This closed global source does not widen the expert/row planners. + pub fn stream_token_embedding( + &mut self, + consume: impl FnMut(&[u8]) -> io::Result<()>, + ) -> Result<(), BindingError> { + let tensor = self + .roles + .get(&TensorRole::Global(GlobalRole::TokenEmbedding)) + .ok_or(BindingError::Role("not_present"))?; + if tensor.shard != 0 || tensor.dimensions != [2560, 248320] || tensor.byte_length == 0 { + return Err(BindingError::Range("token_embedding_extent")); + } + self.shards[tensor.shard as usize] + .stream_tensor(tensor.tensor_number, 0, tensor.byte_length, consume) + .map_err(BindingError::Io) + } + + pub fn stream_expert_row( + &mut self, + role: TensorRole, + expert: u64, + row: u64, + mut consume: impl FnMut(&[u8]) -> io::Result<()>, + ) -> Result<(), BindingError> { + let tensor = self + .roles + .get(&role) + .ok_or(BindingError::Role("not_present"))?; + let range = plan_row(tensor, row, Some(expert))?; + self.shards[tensor.shard as usize] + .stream_tensor(tensor.tensor_number, range.0, range.1, |chunk| { + consume(chunk) + }) + .map_err(BindingError::Io) + } + + /// Exact existing expert-row planner with a caller-owned initialized final + /// span. No geometry/range widening or source reopen; errors drop the owner. + pub fn read_expert_rows_owned( + &mut self, + role: TensorRole, + expert: u64, + first: u64, + count: u64, + bytes: Box<[u8]>, + ) -> Result, BindingError> { + let tensor = self + .roles + .get(&role) + .ok_or(BindingError::Role("not_present"))?; + let range = plan_stream_rows(tensor, role, first, count, Some(expert))?; + if range.1 != bytes.len() as u64 { + return Err(BindingError::Range("owned_expert_extent")); + } + if let Some(bank) = &self.resident_experts { + let resident = bank.tensor(role, tensor)?; + let bytes = self.shards[tensor.shard as usize] + .copy_resident_tensor(resident, range.0, bytes) + .map_err(BindingError::Io)?; + bank.note_copy(bytes.len()); + Ok(bytes) + } else { + self.shards[tensor.shard as usize] + .read_tensor_owned(tensor.tensor_number, range.0, bytes) + .map_err(BindingError::Io) + } + } + + /// Stream 1..64 ordered rows, or one complete closed MoE matrix. + /// The retained verified file is never reopened. All geometry and complete + /// span checks precede the first callback; chunks may cross row boundaries + /// and remain bounded by the 16 MiB file-stream buffer. + pub fn stream_rows( + &mut self, + role: TensorRole, + first: u64, + count: u64, + consume: impl FnMut(&[u8]) -> io::Result<()>, + ) -> Result<(), BindingError> { + let tensor = self + .roles + .get(&role) + .ok_or(BindingError::Role("not_present"))?; + let range = plan_stream_rows(tensor, role, first, count, None)?; + self.shards[tensor.shard as usize] + .stream_tensor(tensor.tensor_number, range.0, range.1, consume) + .map_err(BindingError::Io) + } + + /// Stream 1..64 rows or one complete closed MoE matrix of one expert. + /// Callback chunk boundaries are independent of encoded row boundaries. + /// File-size checks and consumer-error propagation are the same as for + /// `stream_expert_row`; no decoding or numeric operation is performed. + pub fn stream_expert_rows( + &mut self, + role: TensorRole, + expert: u64, + first: u64, + count: u64, + consume: impl FnMut(&[u8]) -> io::Result<()>, + ) -> Result<(), BindingError> { + let tensor = self + .roles + .get(&role) + .ok_or(BindingError::Role("not_present"))?; + let range = plan_stream_rows(tensor, role, first, count, Some(expert))?; + self.shards[tensor.shard as usize] + .stream_tensor(tensor.tensor_number, range.0, range.1, consume) + .map_err(BindingError::Io) + } +} diff --git a/crates/model-format/src/qwen4exp/impl_qwen4expartifact_2.rs b/crates/model-format/src/qwen4exp/impl_qwen4expartifact_2.rs new file mode 100644 index 00000000..f7464ce1 --- /dev/null +++ b/crates/model-format/src/qwen4exp/impl_qwen4expartifact_2.rs @@ -0,0 +1,38 @@ +//! Moved out of the parent module by STRA-338: impl Qwen4ExpArtifact. + +#[allow(unused_imports)] +use super::*; + +impl Qwen4ExpArtifact { + pub fn begin_routed_moe_source( + &mut self, + layer: u32, + expert: u32, + ) -> Result, BindingError> { + if layer >= self.topology.block_count || expert >= self.topology.expert_count { + return Err(BindingError::Range("routed_moe_source")); + } + let layer = u8::try_from(layer).map_err(|_| BindingError::Range("layer"))?; + let gate = self + .roles + .get(&TensorRole::Layer { + layer, + role: LayerRole::FfnGateExperts, + }) + .ok_or(BindingError::Role("not_present"))?; + if gate.shard != 0 { + return Err(BindingError::Geometry("routed_moe_source_shard")); + } + let source = self.shards[0] + .begin_source_fence(gate.tensor_number) + .map_err(BindingError::Io)?; + Ok(RoutedMoeSourceScope { + source, + roles: &self.roles, + layer, + expert, + expert_count: self.topology.expert_count, + resident_experts: self.resident_experts.as_ref(), + }) + } +} diff --git a/crates/model-format/src/qwen4exp/plan_stream_rows.rs b/crates/model-format/src/qwen4exp/plan_stream_rows.rs new file mode 100644 index 00000000..7847c2fc --- /dev/null +++ b/crates/model-format/src/qwen4exp/plan_stream_rows.rs @@ -0,0 +1,252 @@ +//! Moved out of the parent module by STRA-338: fn plan_stream_rows, fn plan_row_span, impl RoutedMoeSourceScope. + +#[allow(unused_imports)] +use super::*; + + +/// Larger spans are restricted to one complete, source-defined matrix. +/// Other roles and partial ranges retain the existing 64-row admission. +pub(super) fn plan_stream_rows( + tensor: &ResolvedTensor, + role: TensorRole, + first: u64, + count: u64, + expert: Option, +) -> Result<(u64, u64), BindingError> { + if count <= 64 { + return plan_rows(tensor, first, count, expert); + } + use LayerRole as L; + let (columns, rows, routed) = match role { + TensorRole::Layer { + role: L::FfnGateExperts | L::FfnUpExperts, + .. + } => (2560, 640, true), + TensorRole::Layer { + role: L::FfnDownExperts, + .. + } => (640, 2560, true), + TensorRole::Layer { + role: L::FfnGateShared | L::FfnUpShared, + .. + } => (2560, 640, false), + TensorRole::Layer { + role: L::FfnDownShared, + .. + } => (640, 2560, false), + TensorRole::Layer { + role: L::AttnQkv, .. + } => (2560, 10240, false), + TensorRole::Layer { + role: L::AttnGate, .. + } => (2560, 6144, false), + TensorRole::Layer { + role: L::SsmConv1d, .. + } => (4, 10240, false), + TensorRole::Layer { + layer: 1, + role: L::PleKey, + } if tensor.kind == 30 => (2560, 10240, false), + TensorRole::Layer { + layer: 1, + role: L::PleValue, + } if tensor.kind == 30 => (2560, 2560, false), + TensorRole::Layer { + layer: 1, + role: L::PleConv1d, + } if tensor.kind == 1 => (4, 10240, false), + TensorRole::Layer { + role: L::SsmOut | L::AttnOutput, + .. + } => (6144, 2560, false), + TensorRole::Layer { role: L::AttnQ, .. } => (2560, 12288, false), + TensorRole::Layer { + role: L::AttnK | L::AttnV | L::IndexerQProj | L::FfnGateInp, + .. + } => (2560, 512, false), + TensorRole::Layer { + role: L::IndexerKProj, + .. + } => (2560, 128, false), + TensorRole::Layer { + role: L::HcAttnDown | L::HcFfnDown, + .. + } + | TensorRole::Global(GlobalRole::OutputHcDown) => (10240, 320, false), + TensorRole::Layer { + role: L::HcAttnUp | L::HcFfnUp, + .. + } + | TensorRole::Global(GlobalRole::OutputHcUp) => (320, 10240, false), + // The complete vocabulary-major head / embedding table: the native head and embedding owners + // (`generate.cpp` NativeHead / embedding upload) read each as ONE whole-tensor stream. + TensorRole::Global(GlobalRole::Output | GlobalRole::TokenEmbedding) => (2560, 248320, false), + _ => return Err(BindingError::Range("row_count")), + }; + let expected = [columns, rows, 512]; + if first != 0 + || count != rows + || expert.is_some() != routed + || tensor.dimensions != expected[..if routed { 3 } else { 2 }] + { + return Err(BindingError::Range("row_count")); + } + plan_row_span(tensor, first, count, expert) +} + +pub(super) fn plan_row_span( + tensor: &ResolvedTensor, + first: u64, + count: u64, + expert: Option, +) -> Result<(u64, u64), BindingError> { + let end_row = first + .checked_add(count) + .ok_or(BindingError::Range("row_index"))?; + let (offset, row_bytes) = plan_row(tensor, first, expert)?; + let (last_offset, last_bytes) = plan_row(tensor, end_row - 1, expert)?; + let bytes = row_bytes + .checked_mul(count) + .ok_or(BindingError::Range("byte_count"))?; + let end = offset + .checked_add(bytes) + .ok_or(BindingError::Range("row_offset"))?; + if last_bytes != row_bytes + || last_offset.checked_add(last_bytes) != Some(end) + || end > tensor.byte_length + { + return Err(BindingError::Range("tensor_bounds")); + } + if tensor + .absolute_start + .checked_add(end) + .is_none_or(|absolute_end| absolute_end > tensor.file_size) + { + return Err(BindingError::Range("file_bounds")); + } + Ok((offset, bytes)) +} +impl RoutedMoeSourceScope<'_> { + /// Point the same loan at another expert of its layer: a group fence (one source observation at + /// begin and one at finish) covering every expert of a layer group. Every request after this still + /// rechecks its exact indexed tensor, as before. + pub fn retarget(&mut self, expert: u32) -> Result<(), BindingError> { + if expert >= self.expert_count { + return Err(BindingError::Range("routed_moe_source")); + } + self.expert = expert; + Ok(()) + } + pub(super) fn role(&self, role: LayerRole) -> Result { + if !matches!( + role, + LayerRole::FfnGateExperts | LayerRole::FfnUpExperts | LayerRole::FfnDownExperts + ) { + return Err(BindingError::Role("routed_moe_source")); + } + Ok(TensorRole::Layer { + layer: self.layer, + role, + }) + } + /// Every request rechecks its exact immutable indexed tensor and empty-span + /// extent. Source length observations belong to begin/explicit finish. + pub fn tensor(&self, role: LayerRole) -> Result<&ResolvedTensor, BindingError> { + let tensor = self + .roles + .get(&self.role(role)?) + .ok_or(BindingError::Role("not_present"))?; + if tensor.shard != 0 { + return Err(BindingError::Geometry("routed_moe_source_shard")); + } + Ok(tensor) + } + pub fn validate_descriptor(&self, role: LayerRole) -> Result<(), BindingError> { + let tensor = self.tensor(role)?; + self.source + .validate_tensor(tensor.tensor_number) + .map_err(BindingError::Io) + } + /// One complete actual matrix of this source's fixed expert only. + pub fn stream_matrix( + &mut self, + role: LayerRole, + consume: impl FnMut(&[u8]) -> io::Result<()>, + ) -> Result<(), BindingError> { + let tensor_role = self.role(role)?; + let tensor = self + .roles + .get(&tensor_role) + .ok_or(BindingError::Role("not_present"))?; + if tensor.shard != 0 { + return Err(BindingError::Geometry("routed_moe_source_shard")); + } + let rows = if role == LayerRole::FfnDownExperts { + 2560 + } else { + 640 + }; + let range = plan_stream_rows(tensor, tensor_role, 0, rows, Some(u64::from(self.expert)))?; + self.source + .stream_tensor(tensor.tensor_number, range.0, range.1, consume) + .map_err(BindingError::Io) + } + /// Whole fixed-expert span into its initialized final owner, retaining the + /// same real source loan and full original stream bounds/size observations. + pub fn read_matrix_owned( + &mut self, + role: LayerRole, + bytes: Box<[u8]>, + ) -> Result, BindingError> { + let tensor_role = self.role(role)?; + let tensor = self + .roles + .get(&tensor_role) + .ok_or(BindingError::Role("not_present"))?; + if tensor.shard != 0 { + return Err(BindingError::Geometry("routed_moe_source_shard")); + } + let rows = if role == LayerRole::FfnDownExperts { + 2560 + } else { + 640 + }; + let range = plan_stream_rows(tensor, tensor_role, 0, rows, Some(u64::from(self.expert)))?; + if range.1 != bytes.len() as u64 { + return Err(BindingError::Range("owned_expert_extent")); + } + if let Some(bank) = self.resident_experts { + let resident = bank.tensor(tensor_role, tensor)?; + let bytes = self + .source + .copy_resident_tensor(resident, range.0, bytes) + .map_err(BindingError::Io)?; + bank.note_copy(bytes.len()); + Ok(bytes) + } else { + self.source + .read_tensor_owned(tensor.tensor_number, range.0, bytes) + .map_err(BindingError::Io) + } + } + + /// No-copy, fixed expert span of the actual retained catalog. The source + /// fence stays held; completion still requires explicit finish. + pub fn resident_matrix_span( + &self, + role: LayerRole, + ) -> Result { + let tensor_role = self.role(role)?; + let tensor = self.tensor(role)?; + self.validate_descriptor(role)?; + let bank = self + .resident_experts + .ok_or(BindingError::Role("resident_expert_source_absent"))?; + bank.span(tensor_role, tensor, self.expert) + } + + /// Consumes the actual source loan. A failed finish is not publication. + pub fn finish(self) -> Result<(), BindingError> { + self.source.finish().map_err(BindingError::Io) + } +} diff --git a/crates/model-format/src/qwen4exp/validate_logical_views.rs b/crates/model-format/src/qwen4exp/validate_logical_views.rs new file mode 100644 index 00000000..43bae635 --- /dev/null +++ b/crates/model-format/src/qwen4exp/validate_logical_views.rs @@ -0,0 +1,61 @@ +//! Moved out of the parent module by STRA-338: fn validate_logical_views. + +#[allow(unused_imports)] +use super::*; + + +pub(super) fn validate_logical_views( + mut shards: [LogicalShardView<'_>; 2], +) -> Result { + for (number, shard) in shards.iter().enumerate() { + let (expected_no, expected_count) = (number as u64, 2); + if shard.index.summary.split_no != Some(expected_no) + || shard.metadata.split_no != Some(expected_no) + { + return Err(BindingError::Split("split.no")); + } + if shard.index.summary.split_count != Some(expected_count) + || shard.metadata.split_count != Some(expected_count) + { + return Err(BindingError::Split("split.count")); + } + if shard.index.summary.split_tensors_count != Some(1224) + || shard.metadata.split_tensors_count != Some(1224) + { + return Err(BindingError::Split("split.tensors.count")); + } + } + for (number, shard) in shards.iter().enumerate() { + let expected_tensors = if number == 0 { 1223 } else { 1 }; + if shard.index.tensors.len() != expected_tensors { + return Err(BindingError::Split("indexed_tensor_count")); + } + } + if shards[0].metadata.architecture.as_deref() != Some("qwen4exp") { + return Err(BindingError::Metadata("general.architecture")); + } + if shards[1] + .metadata + .architecture + .as_deref() + .is_some_and(|value| value != "qwen4exp") + { + return Err(BindingError::Metadata("general.architecture")); + } + let topology = topology(&shards[0].metadata)?; + let tokenizer = gguf::validate_tokenizer_metadata( + shards[0] + .metadata + .tokenizer + .take() + .ok_or(BindingError::Tokenizer("required_fields"))?, + ) + .map_err(|_| BindingError::Tokenizer("invalid_metadata"))?; + validate_tokenizer(&tokenizer)?; + let roles = validate_role_inventory(&shards)?; + Ok(ValidatedBindingView { + topology, + tokenizer, + roles, + }) +} diff --git a/crates/model-format/src/qwen4exp/validate_owner_index_split.rs b/crates/model-format/src/qwen4exp/validate_owner_index_split.rs new file mode 100644 index 00000000..46ef6d2b --- /dev/null +++ b/crates/model-format/src/qwen4exp/validate_owner_index_split.rs @@ -0,0 +1,241 @@ +//! Moved out of the parent module by STRA-338: fn validate_owner_index_split, fn validate_owner_metadata_split, fn required_uint, fn required_u32, fn required_float, fn required_array .... + +#[allow(unused_imports)] +use super::*; + + +pub(super) fn validate_owner_index_split(owners: &[VerifiedGgufFile; 2]) -> Result<(), BindingError> { + for (number, owner) in owners.iter().enumerate() { + let summary = &owner.index().summary; + if summary.split_no != Some(number as u64) { + return Err(BindingError::Split("split.no")); + } + if summary.split_count != Some(2) { + return Err(BindingError::Split("split.count")); + } + if summary.split_tensors_count != Some(1224) { + return Err(BindingError::Split("split.tensors.count")); + } + } + for (number, owner) in owners.iter().enumerate() { + let expected = if number == 0 { 1223 } else { 1 }; + if owner.index().tensors.len() != expected { + return Err(BindingError::Split("indexed_tensor_count")); + } + } + Ok(()) +} + +pub(super) fn validate_owner_metadata_split(metadata: &[MetadataSnapshot; 2]) -> Result<(), BindingError> { + for (number, snapshot) in metadata.iter().enumerate() { + if snapshot.split_no != Some(number as u64) { + return Err(BindingError::Split("split.no")); + } + if snapshot.split_count != Some(2) { + return Err(BindingError::Split("split.count")); + } + if snapshot.split_tensors_count != Some(1224) { + return Err(BindingError::Split("split.tensors.count")); + } + } + Ok(()) +} + +pub(super) fn required_uint(metadata: &MetadataSnapshot, key: &'static str) -> Result { + match metadata.values.get(key) { + Some(MetadataValue::Unsigned(value)) => Ok(*value), + Some(MetadataValue::Signed(value)) if *value >= 0 => Ok(*value as u64), + _ => Err(BindingError::Metadata(key)), + } +} + +pub(super) fn required_u32( + metadata: &MetadataSnapshot, + key: &'static str, + expected: u32, +) -> Result { + let value = required_uint(metadata, key)?; + if value != u64::from(expected) { + return Err(BindingError::Metadata(key)); + } + Ok(expected) +} + +pub(super) fn required_float(metadata: &MetadataSnapshot, key: &'static str) -> Result { + match metadata.values.get(key) { + Some(MetadataValue::Float(value)) if value.is_finite() && *value > 0.0 => Ok(*value), + Some(MetadataValue::Unsigned(value)) if *value > 0 => Ok(*value as f64), + Some(MetadataValue::Signed(value)) if *value > 0 => Ok(*value as f64), + _ => Err(BindingError::Metadata(key)), + } +} + +pub(super) fn required_array( + metadata: &MetadataSnapshot, + key: &'static str, + expected: &[u64], +) -> Result, BindingError> { + let values = match metadata.values.get(key) { + Some(MetadataValue::UnsignedArray(values)) => values.clone(), + Some(MetadataValue::SignedArray(values)) => values + .iter() + .map(|value| u64::try_from(*value).map_err(|_| BindingError::Metadata(key))) + .collect::, _>>()?, + _ => return Err(BindingError::Metadata(key)), + }; + if values != expected { + return Err(BindingError::Metadata(key)); + } + Ok(values) +} + +pub(super) fn topology(metadata: &MetadataSnapshot) -> Result { + if metadata.architecture.as_deref() != Some("qwen4exp") { + return Err(BindingError::Metadata("general.architecture")); + } + let block_count = required_u32(metadata, "qwen4exp.block_count", 48)?; + let embedding_length = required_u32(metadata, "qwen4exp.embedding_length", 2560)?; + let compression_ratios = required_array( + metadata, + "qwen4exp.attention.compress_ratios", + &(0..48) + .map(|layer| if layer % 4 == 3 { 4 } else { 0 }) + .collect::>(), + )?; + let full_attention_interval = required_u32(metadata, "qwen4exp.full_attention_interval", 4)?; + let expert_count = required_u32(metadata, "qwen4exp.expert_count", 512)?; + let expert_used_count = required_u32(metadata, "qwen4exp.expert_used_count", 10)?; + let expert_feed_forward_length = + required_u32(metadata, "qwen4exp.expert_feed_forward_length", 640)?; + let expert_shared_feed_forward_length = + required_u32(metadata, "qwen4exp.expert_shared_feed_forward_length", 640)?; + let attention_head_count = required_u32(metadata, "qwen4exp.attention.head_count", 24)?; + let attention_head_count_kv = required_u32(metadata, "qwen4exp.attention.head_count_kv", 2)?; + let attention_key_length = required_u32(metadata, "qwen4exp.attention.key_length", 256)?; + let attention_value_length = required_u32(metadata, "qwen4exp.attention.value_length", 256)?; + let rms_epsilon = required_float(metadata, "qwen4exp.attention.layer_norm_rms_epsilon")?; + if (rms_epsilon - 1.0e-6).abs() > 1.0e-12 { + return Err(BindingError::Metadata( + "qwen4exp.attention.layer_norm_rms_epsilon", + )); + } + let hc_count = required_u32(metadata, "qwen4exp.hyper_connection.count", 4)?; + let hc_low_rank = required_u32(metadata, "qwen4exp.hyper_connection.low_rank", 320)?; + let rope_dimension_count = required_u32(metadata, "qwen4exp.rope.dimension_count", 64)?; + let rope_dimension_sections = required_array( + metadata, + "qwen4exp.rope.dimension_sections", + &[11, 11, 10, 0], + )?; + let rope_frequency_base = required_float(metadata, "qwen4exp.rope.freq_base")?; + if rope_frequency_base != 10_000_000.0 { + return Err(BindingError::Metadata("qwen4exp.rope.freq_base")); + } + let indexer_head_count = required_u32(metadata, "qwen4exp.attention.indexer.head_count", 4)?; + let indexer_key_length = required_u32(metadata, "qwen4exp.attention.indexer.key_length", 128)?; + let indexer_top_k = required_u32(metadata, "qwen4exp.attention.indexer.top_k", 2048)?; + let ssm_conv_kernel = required_u32(metadata, "qwen4exp.ssm.conv_kernel", 4)?; + let ssm_state_size = required_u32(metadata, "qwen4exp.ssm.state_size", 128)?; + let ssm_group_count = required_u32(metadata, "qwen4exp.ssm.group_count", 16)?; + let ssm_time_step_rank = required_u32(metadata, "qwen4exp.ssm.time_step_rank", 48)?; + let ssm_inner_size = required_u32(metadata, "qwen4exp.ssm.inner_size", 6144)?; + let per_layer_embedding_length = + required_u32(metadata, "qwen4exp.embedding_length_per_layer_input", 160)?; + let ple_layers = required_array(metadata, "qwen4exp.ple.layers", &[1])?; + let ple_ngram_size = required_u32(metadata, "qwen4exp.ple.ngram_size", 3)?; + let ple_heads_per_ngram = required_u32(metadata, "qwen4exp.ple.heads_per_ngram", 8)?; + let ple_conv_kernel = required_u32(metadata, "qwen4exp.ple.conv_kernel", 4)?; + let ple_eos_token_id = required_u32(metadata, "qwen4exp.ple.eos_token_id", 248_044)?; + let ple_image_token_id = required_u32(metadata, "qwen4exp.ple.image_token_id", 248_056)?; + let ple_head_offsets = required_array( + metadata, + "qwen4exp.ple.head_offsets", + &[ + 0, + 20_000_003, + 40_000_026, + 60_000_059, + 80_000_106, + 100_000_165, + 120_000_228, + 140_000_297, + 160_000_374, + 180_000_455, + 200_000_548, + 220_000_655, + 240_000_802, + 260_000_955, + 280_001_114, + 300_001_275, + ], + )?; + let ple_head_vocab_sizes = required_array( + metadata, + "qwen4exp.ple.head_vocab_sizes", + &[ + 20_000_003, 20_000_023, 20_000_033, 20_000_047, 20_000_059, 20_000_063, 20_000_069, + 20_000_077, 20_000_081, 20_000_093, 20_000_107, 20_000_147, 20_000_153, 20_000_159, + 20_000_161, 20_000_171, + ], + )?; + let ple_layer_multipliers = required_array( + metadata, + "qwen4exp.ple.layer_multipliers", + &[23_703_573_157_769, 20_109_073_645_365, 8_052_911_324_071], + )?; + let context_length = required_u32(metadata, "qwen4exp.context_length", 262_144)?; + Ok(Qwen4ExpTopology { + architecture: "qwen4exp".to_owned(), + block_count, + embedding_length, + context_length, + compression_ratios, + full_attention_interval, + expert_count, + expert_used_count, + expert_feed_forward_length, + expert_shared_feed_forward_length, + attention_head_count, + attention_head_count_kv, + attention_key_length, + attention_value_length, + rms_epsilon, + hc_count, + hc_low_rank, + rope_dimension_count, + rope_dimension_sections, + rope_frequency_base, + indexer_head_count, + indexer_key_length, + indexer_top_k, + ssm_conv_kernel, + ssm_state_size, + ssm_group_count, + ssm_time_step_rank, + ssm_inner_size, + per_layer_embedding_length, + ple_layers, + ple_ngram_size, + ple_heads_per_ngram, + ple_conv_kernel, + ple_eos_token_id, + ple_image_token_id, + ple_head_offsets, + ple_head_vocab_sizes, + ple_layer_multipliers, + }) +} + +pub(super) fn validate_tokenizer(tokenizer: &TokenizerMetadata) -> Result<(), BindingError> { + let id = |name: &str| tokenizer.special_ids.get(name).copied(); + if id("tokenizer.ggml.bos_token_id") != Some(248_044) { + return Err(BindingError::Tokenizer("tokenizer.ggml.bos_token_id")); + } + if id("tokenizer.ggml.padding_token_id") != Some(248_044) { + return Err(BindingError::Tokenizer("tokenizer.ggml.padding_token_id")); + } + if id("tokenizer.ggml.eos_token_id") != Some(248_046) { + return Err(BindingError::Tokenizer("tokenizer.ggml.eos_token_id")); + } + Ok(()) +} diff --git a/crates/model-format/src/qwen4exp/validate_role_inventory.rs b/crates/model-format/src/qwen4exp/validate_role_inventory.rs new file mode 100644 index 00000000..b5bb4cf3 --- /dev/null +++ b/crates/model-format/src/qwen4exp/validate_role_inventory.rs @@ -0,0 +1,188 @@ +//! Moved out of the parent module by STRA-338: fn validate_role_inventory, fn plan_row, fn plan_rows. + +#[allow(unused_imports)] +use super::*; + + +pub(super) fn validate_role_inventory( + shards: &[LogicalShardView<'_>; 2], +) -> Result, BindingError> { + let expected = expected_inventory(); + if expected.len() != 1224 { + return Err(BindingError::Role("registry_count")); + } + let by_name = expected + .iter() + .map(|item| (item.name.as_str(), item)) + .collect::>(); + let allowed_kinds: BTreeSet = [0, 1, 8, 12, 13, 14, 18, 20, 21, 22, 23, 30, 42] + .into_iter() + .collect(); + let mut actual = BTreeMap::new(); + let mut roles = BTreeMap::new(); + let mut spans: [Vec<(u64, u64)>; 2] = [Vec::new(), Vec::new()]; + for (shard_number, shard) in shards.iter().enumerate() { + for (tensor_number, tensor) in shard.index.tensors.iter().enumerate() { + if actual + .insert( + tensor.name.as_str(), + (shard_number as u8, tensor_number, tensor), + ) + .is_some() + { + return Err(BindingError::Role("duplicate_name")); + } + } + } + for spec in &expected { + let (shard_number, tensor_number, tensor) = actual + .get(spec.name.as_str()) + .ok_or(BindingError::Role("missing_name"))?; + if spec.shard != *shard_number { + return Err(BindingError::Role("wrong_shard")); + } + if tensor.dimensions != spec.dimensions { + return Err(BindingError::Geometry("dimensions")); + } + if !allowed_kinds.contains(&tensor.kind) + || spec.kind.is_some_and(|kind| kind != tensor.kind) + { + return Err(BindingError::Geometry("kind")); + } + let (block_elements, block_bytes) = + gguf::block_geometry(tensor.kind).ok_or(BindingError::Geometry("kind"))?; + if tensor.dimensions.first().copied().unwrap_or(0) == 0 + || tensor.dimensions[0] % block_elements != 0 + { + return Err(BindingError::Geometry("block_alignment")); + } + let elements = tensor + .dimensions + .iter() + .try_fold(1u64, |value, dim| value.checked_mul(*dim)) + .ok_or(BindingError::Geometry("element_count"))?; + let bytes = elements + .checked_div(block_elements) + .and_then(|blocks| blocks.checked_mul(block_bytes)) + .ok_or(BindingError::Geometry("byte_count"))?; + if tensor.bytes == 0 || tensor.bytes != bytes { + return Err(BindingError::Geometry("indexed_byte_count")); + } + let shard = &shards[*shard_number as usize]; + let absolute_start = shard + .index + .summary + .data_start + .checked_add(tensor.offset) + .ok_or(BindingError::Range("absolute_start"))?; + if absolute_start < shard.index.summary.data_start { + return Err(BindingError::Range("data_bounds")); + } + let absolute_end = absolute_start + .checked_add(tensor.bytes) + .ok_or(BindingError::Range("absolute_end"))?; + if absolute_end > shard.index.summary.file_size { + return Err(BindingError::Range("file_bounds")); + } + spans[*shard_number as usize].push((absolute_start, absolute_end)); + let resolved = ResolvedTensor { + shard: *shard_number, + tensor_number: *tensor_number, + name: tensor.name.clone(), + kind: tensor.kind, + dimensions: tensor.dimensions.clone(), + absolute_start, + byte_length: tensor.bytes, + file_size: shard.index.summary.file_size, + }; + if roles.insert(spec.role, resolved).is_some() { + return Err(BindingError::Role("duplicate_role")); + } + } + if actual.keys().any(|name| !by_name.contains_key(name)) || roles.len() != expected.len() { + return Err(BindingError::Role("missing_name")); + } + for span_set in &mut spans { + span_set.sort_unstable(); + if span_set.windows(2).any(|pair| pair[0].1 > pair[1].0) { + return Err(BindingError::Range("overlapping_tensors")); + } + } + Ok(roles) +} + +pub(super) fn plan_row( + tensor: &ResolvedTensor, + row: u64, + expert: Option, +) -> Result<(u64, u64), BindingError> { + let dimensions = &tensor.dimensions; + match (dimensions.len(), expert) { + (1, None) if matches!(tensor.kind, 0 | 1 | 30) => {} + (1, None) => return Err(BindingError::Geometry("kind")), + (2, None) | (3, Some(_)) => {} + (1 | 2, Some(_)) | (3, None) => return Err(BindingError::Role("rank_mismatch")), + _ => return Err(BindingError::Role("rank")), + } + let (block_elements, block_bytes) = + gguf::block_geometry(tensor.kind).ok_or(BindingError::Geometry("kind"))?; + let dim0 = *dimensions.first().ok_or(BindingError::Geometry("rank"))?; + if dim0 == 0 || dim0 % block_elements != 0 { + return Err(BindingError::Geometry("block_alignment")); + } + let elements = dimensions + .iter() + .try_fold(1u64, |value, dim| value.checked_mul(*dim)) + .ok_or(BindingError::Geometry("element_count"))?; + let indexed_bytes = elements + .checked_div(block_elements) + .and_then(|blocks| blocks.checked_mul(block_bytes)) + .ok_or(BindingError::Geometry("byte_count"))?; + if tensor.byte_length == 0 || indexed_bytes != tensor.byte_length { + return Err(BindingError::Geometry("indexed_byte_count")); + } + let row_bytes = (dim0 / block_elements) + .checked_mul(block_bytes) + .ok_or(BindingError::Range("row_bytes"))?; + let relative = match (dimensions.len(), expert) { + (1, None) if row == 0 => Some(0), + (2, None) if row < dimensions[1] => row.checked_mul(row_bytes), + (3, Some(expert)) if expert < dimensions[2] && row < dimensions[1] => expert + .checked_mul(dimensions[1]) + .and_then(|base| base.checked_add(row)) + .and_then(|index| index.checked_mul(row_bytes)), + (1..=3, _) => return Err(BindingError::Range("row_index")), + _ => unreachable!("rank checked above"), + } + .ok_or(BindingError::Range("row_offset"))?; + if row_bytes == 0 + || relative + .checked_add(row_bytes) + .is_none_or(|end| end > tensor.byte_length) + { + return Err(BindingError::Range("tensor_bounds")); + } + if tensor + .absolute_start + .checked_add(relative) + .and_then(|start| start.checked_add(row_bytes)) + .is_none_or(|end| end > tensor.file_size) + { + return Err(BindingError::Range("file_bounds")); + } + Ok((relative, row_bytes)) +} + +/// Plan an exact finite row tile using the existing single-row geometry +/// admission at both endpoints. The same expert is supplied for both endpoints. +pub(super) fn plan_rows( + tensor: &ResolvedTensor, + first: u64, + count: u64, + expert: Option, +) -> Result<(u64, u64), BindingError> { + if !(1..=64).contains(&count) { + return Err(BindingError::Range("row_count")); + } + plan_row_span(tensor, first, count, expert) +} diff --git a/crates/model-format/src/qwen4exp_digest_capture.rs b/crates/model-format/src/qwen4exp_digest_capture.rs index 16f55b98..e811fac0 100644 --- a/crates/model-format/src/qwen4exp_digest_capture.rs +++ b/crates/model-format/src/qwen4exp_digest_capture.rs @@ -30,438 +30,6 @@ pub struct ProvisionalExpertSource { incremental: Option, } -fn capture_admit( - capacity: usize, - future: usize, - available: usize, -) -> Result<(), ResidentExpertSourceError> { - let headroom = - usize::try_from(FUTURE_HEADROOM).map_err(|_| ResidentExpertSourceError::MemoryAdmission)?; - if capacity as u64 > SOURCE_CAP - || capacity - .checked_add(future) - .and_then(|n| n.checked_add(headroom)) - .is_none_or(|n| n > available) - { - return Err(ResidentExpertSourceError::MemoryAdmission); - } - Ok(()) -} - -fn provisional_descriptor( - index: &TensorIndex, - role: TensorRole, -) -> Result { - let TensorRole::Layer { - layer, - role: layer_role, - } = role - else { - return Err(ResidentExpertSourceError::Geometry); - }; - let suffix = match layer_role { - LayerRole::FfnGateExperts => "ffn_gate_exps.weight", - LayerRole::FfnUpExperts => "ffn_up_exps.weight", - LayerRole::FfnDownExperts => "ffn_down_exps.weight", - _ => return Err(ResidentExpertSourceError::Geometry), - }; - let name = format!("blk.{layer}.{suffix}"); - let (tensor_number, tensor) = index - .tensors - .iter() - .enumerate() - .find(|(_, tensor)| tensor.name == name) - .ok_or(ResidentExpertSourceError::Geometry)?; - let absolute_start = index - .summary - .data_start - .checked_add(tensor.offset) - .ok_or(ResidentExpertSourceError::Geometry)?; - let resolved = ResolvedTensor { - shard: 0, - tensor_number, - name, - kind: tensor.kind, - dimensions: tensor.dimensions.clone(), - absolute_start, - byte_length: tensor.bytes, - file_size: index.summary.file_size, - }; - let descriptor = checked_descriptor(role, &resolved)?; - if absolute_start - .checked_add(descriptor.bytes as u64) - .is_none_or(|n| n > descriptor.file_size) - { - return Err(ResidentExpertSourceError::Geometry); - } - Ok(descriptor) -} - -impl ProvisionalExpertSource { - fn empty() -> Self { - Self { - cells: Vec::new(), - banks: Vec::new(), - error: None, - source: None, - charged: 0, - source_bytes: 0, - observed: 0, - incremental: None, - } - } - fn fail(&mut self, error: ResidentExpertSourceError) { - if self.error.is_none() { - self.error = Some(error); - } - self.cells.clear(); - self.banks.clear(); - self.source = None; - self.incremental = None; - } - pub(crate) fn geometry_failure() -> Self { - let mut capture = Self::empty(); - capture.fail(ResidentExpertSourceError::Geometry); - capture - } - pub(crate) fn prepare(index: &TensorIndex, retained_kar: Option<&File>) -> Self { - let mut capture = Self::empty(); - if let Err(error) = capture.prepare_inner(index, retained_kar) { - capture.fail(error); - } - capture - } - fn prepare_inner( - &mut self, - index: &TensorIndex, - retained_kar: Option<&File>, - ) -> Result<(), ResidentExpertSourceError> { - // Observation ONLY: seals/SHA/CRC stay at the original later KAR gate. - // The keeper's already retained memfd pages are in MemAvailable, so its - // 55 GiB is not also charged as a future allocation. - let observed_kar = retained_kar - .and_then(|file| file.metadata().ok()) - .filter(|metadata| metadata.is_file() && metadata.len() == RETAINED_KAR_BYTES) - .ok_or(ResidentExpertSourceError::MemoryAdmission)?; - let _ = observed_kar; - if index.summary.file_size != PINNED_IDENTITIES[0].0 || index.tensors.len() != 1223 { - return Err(ResidentExpertSourceError::Geometry); - } - self.cells - .try_reserve_exact(BANKS) - .map_err(|_| ResidentExpertSourceError::Allocation)?; - self.banks - .try_reserve_exact(BANKS) - .map_err(|_| ResidentExpertSourceError::Allocation)?; - self.charged = self - .cells - .capacity() - .checked_mul(size_of::()) - .and_then(|n| n.checked_add(self.banks.capacity().checked_mul(size_of::())?)) - .and_then(|n| n.checked_add(size_of::() + size_of::())) - .ok_or(ResidentExpertSourceError::MemoryAdmission)?; - // First geometry pass prevents allocation before complete closed layout. - for layer in 0..48 { - for role in [ - LayerRole::FfnGateExperts, - LayerRole::FfnUpExperts, - LayerRole::FfnDownExperts, - ] { - let descriptor = provisional_descriptor(index, TensorRole::Layer { layer, role })?; - self.source_bytes = self - .source_bytes - .checked_add(descriptor.bytes) - .ok_or(ResidentExpertSourceError::Geometry)?; - } - } - let planned = self - .charged - .checked_add(self.source_bytes) - .ok_or(ResidentExpertSourceError::MemoryAdmission)?; - self.observed = memory_available()?; - capture_admit(planned, FUTURE_OWNERS, self.observed)?; - let mut remaining = self.source_bytes; - for layer in 0..48 { - for role in [ - LayerRole::FfnGateExperts, - LayerRole::FfnUpExperts, - LayerRole::FfnDownExperts, - ] { - let descriptor = provisional_descriptor(index, TensorRole::Layer { layer, role })?; - for previous in &self.cells { - let left = previous.descriptor.absolute_start; - let right = left + previous.descriptor.bytes as u64; - let start = descriptor.absolute_start; - let end = start + descriptor.bytes as u64; - if left < end && start < right { - return Err(ResidentExpertSourceError::Geometry); - } - } - capture_admit(remaining, FUTURE_OWNERS, memory_available()?)?; - let mut bytes = Vec::new(); - bytes - .try_reserve_exact(descriptor.bytes) - .map_err(|_| ResidentExpertSourceError::Allocation)?; - let charged_bytes = bytes.capacity(); - self.charged = self - .charged - .checked_add(charged_bytes) - .ok_or(ResidentExpertSourceError::MemoryAdmission)?; - if self.charged as u64 > SOURCE_CAP { - return Err(ResidentExpertSourceError::MemoryAdmission); - } - capture_admit( - remaining - .checked_sub(descriptor.bytes) - .and_then(|n| n.checked_add(charged_bytes)) - .ok_or(ResidentExpertSourceError::MemoryAdmission)?, - FUTURE_OWNERS, - memory_available()?, - )?; - bytes.resize(descriptor.bytes, 0); - self.cells.push(CapturedTensor { - descriptor, - bytes: bytes.into_boxed_slice(), - charged_bytes, - covered: 0, - }); - remaining -= descriptor.bytes; - } - } - capture_admit(0, FUTURE_OWNERS, memory_available()?)?; - Ok(()) - } - pub(crate) fn observe(&mut self, position: u64, chunk: &[u8]) { - if let Some(incremental) = &mut self.incremental { - #[cfg(test)] - let available = incremental.test_available; - let result = incremental.observe_inner(position, chunk, || { - #[cfg(test)] - if let Some(available) = available { - return Ok(available); - } - memory_available() - }); - if let Err(error) = result { - self.fail(error); - } - return; - } - if self.error.is_some() { - return; - } - let Some(end) = position.checked_add(chunk.len() as u64) else { - self.fail(ResidentExpertSourceError::Geometry); - return; - }; - for cell in &mut self.cells { - let start = cell.descriptor.absolute_start; - let bank_end = start + cell.descriptor.bytes as u64; - let left = start.max(position); - let right = bank_end.min(end); - if left >= right { - continue; - } - let offset = (left - start) as usize; - let count = (right - left) as usize; - if offset != cell.covered { - self.fail(ResidentExpertSourceError::Geometry); - return; - } - let source = (left - position) as usize; - cell.bytes[offset..offset + count].copy_from_slice(&chunk[source..source + count]); - cell.covered += count; - } - } - pub(crate) fn bind_verified(&mut self, source: &mut VerifiedGgufFile) { - if self.error.is_none() - && self.incremental.is_some() - && let Err(error) = self.finish_incremental(source) - { - self.fail(error); - } - if self.error.is_some() { - return; - } - let checked = (|| { - for cell in &self.cells { - if cell.covered != cell.bytes.len() - || provisional_descriptor(source.index(), cell.descriptor.role)? - != cell.descriptor - { - return Err(ResidentExpertSourceError::Geometry); - } - } - source - .capture_source_identity() - .map_err(|error| ResidentExpertSourceError::Read(BindingError::Io(error))) - })(); - match checked { - Ok(identity) => self.source = Some(identity), - Err(error) => self.fail(error), - } - } -} - -impl Qwen4ExpArtifact { - /// Same-FD full digest/index, with non-consumable optional expert capture. - /// `retained_kar` is an observational owned FD, never KAR admission. - pub fn open_shard0_with_expert_capture( - path: &Path, - expected_digest: &str, - retained_kar: Option<&File>, - ) -> Result<(VerifiedGgufFile, ProvisionalExpertSource), Box> { - gguf::open_expert_capture(path, expected_digest, retained_kar) - } - /// At the ORIGINAL selected bank boundary only: preceding genuine KAR, - /// MTP and profile gates remain the caller's mandatory responsibility. - pub fn adopt_resident_expert_capture( - &mut self, - mut capture: ProvisionalExpertSource, - ) -> Result { - if self.resident_experts.is_some() { - return Err(ResidentExpertSourceError::AlreadyEnabled); - } - if self.topology.block_count != 48 || self.topology.expert_count != 512 { - return Err(ResidentExpertSourceError::Geometry); - } - if let Some(error) = capture.error.take() { - return Err(error); - } - if capture.cells.len() != BANKS - || !capture.banks.is_empty() - || capture.charged as u64 > SOURCE_CAP - { - return Err(ResidentExpertSourceError::Geometry); - } - let identity = capture.source.ok_or(ResidentExpertSourceError::Geometry)?; - self.shards[0] - .validate_capture_identity(identity) - .map_err(|error| ResidentExpertSourceError::Read(BindingError::Io(error)))?; - // Revalidate EVERY bound descriptor before minting even the first final - // tensor. Full finite admission still happens at each selected role. - for (number, cell) in capture.cells.iter().enumerate() { - let resolved = self - .roles - .get(&cell.descriptor.role) - .ok_or(ResidentExpertSourceError::Geometry)?; - if slot(cell.descriptor.role).map_err(ResidentExpertSourceError::Read)? != number - || checked_descriptor(cell.descriptor.role, resolved)? != cell.descriptor - || cell.covered != cell.bytes.len() - { - return Err(ResidentExpertSourceError::Geometry); - } - self.shards[0] - .stream_tensor(cell.descriptor.tensor_number, 0, 0, |_| Ok(())) - .map_err(|error| ResidentExpertSourceError::Read(BindingError::Io(error)))?; - } - // Existing captured Boxes stay in place. Charge only the new small - // shared owners/directory before any wrapping/publication. - let retention = retention_metadata_bytes()?; - capture.charged = capture - .charged - .checked_add(retention) - .ok_or(ResidentExpertSourceError::MemoryAdmission)?; - if capture.charged as u64 > SOURCE_CAP { - return Err(ResidentExpertSourceError::MemoryAdmission); - } - let observed = memory_available()?; - capture_admit(retention, 0, observed)?; // payload pages already resident - for cell in capture.cells { - let tensor = self.shards[0] - .admit_captured_tensor( - identity, - cell.descriptor.tensor_number, - cell.bytes, - cell.charged_bytes, - ) - .map_err(|error| ResidentExpertSourceError::Read(BindingError::Io(error)))?; - capture.banks.push(Bank { - descriptor: cell.descriptor, - tensor: tensor.into_retained(), - }); - } - capture_admit(0, 0, memory_available()?)?; - let report = ResidentExpertSourceReport { - source_bytes: capture.source_bytes as u64, - charged_bytes: capture.charged as u64, - bank_count: BANKS as u32, - source_cap_bytes: SOURCE_CAP, - observed_mem_available_bytes: observed as u64, - future_headroom_bytes: FUTURE_HEADROOM, - shard0_sha256: self.shards[0].artifact_sha256(), - copied_spans: 0, - copied_bytes: 0, - file_mapped: false, - }; - self.resident_experts = Some(ResidentExpertBank { - banks: Rc::new(capture.banks), - report, - copied_spans: Cell::new(0), - copied_bytes: Cell::new(0), - }); - Ok(report) - } -} - -#[cfg(test)] -impl ProvisionalExpertSource { - pub(crate) fn test_cells(index: &TensorIndex) -> Self { - let tensor = &index.tensors[0]; - let descriptor = BankDescriptor { - role: TensorRole::Layer { - layer: 0, - role: LayerRole::FfnGateExperts, - }, - tensor_number: 0, - raw_kind: tensor.kind, - absolute_start: index.summary.data_start + tensor.offset, - file_size: index.summary.file_size, - bytes: tensor.bytes as usize, - }; - let mut capture = Self::empty(); - capture.cells.push(CapturedTensor { - descriptor, - bytes: vec![0; descriptor.bytes].into_boxed_slice(), - charged_bytes: descriptor.bytes, - covered: 0, - }); - capture - } - pub(crate) fn test_bytes(&self) -> Option<&[u8]> { - self.cells - .first() - .filter(|cell| cell.covered == cell.bytes.len()) - .map(|cell| &*cell.bytes) - } - pub(crate) fn test_discarded(&self) -> bool { - self.error.is_some() && self.cells.is_empty() - } - pub(crate) fn test_memory(capacity: usize, future: usize, available: usize) -> bool { - capture_admit(capacity, future, available).is_ok() - } - pub(crate) fn test_mint( - self, - source: &mut VerifiedGgufFile, - ) -> Result> { - // Transport-only fixture: this is NOT the production 144-bank adoption. - if self.error.is_some() || self.cells.len() != 1 { - return Err("incomplete capture".into()); - } - let cell = self.cells.into_iter().next().ok_or("empty capture")?; - if cell.covered != cell.bytes.len() { - return Err("incomplete capture".into()); - } - let identity = source.capture_source_identity()?; - source.admit_captured_tensor( - identity, - cell.descriptor.tensor_number, - cell.bytes, - cell.charged_bytes, - ) - } -} - struct IncrementalTensor { descriptor: BankDescriptor, bytes: Vec, @@ -473,347 +41,27 @@ struct IncrementalCapture { #[cfg(test)] test_available: Option, } -impl IncrementalCapture { - fn remaining_commitment(&self) -> Result { - self.cells.iter().try_fold(0usize, |remaining, cell| { - if cell.bytes.capacity() != cell.charged_bytes - || cell.bytes.len() != cell.covered - || cell.covered > cell.descriptor.bytes - || cell.descriptor.bytes > cell.charged_bytes - { - return Err(ResidentExpertSourceError::Geometry); - } - remaining - .checked_add(cell.charged_bytes - cell.bytes.len()) - .ok_or(ResidentExpertSourceError::MemoryAdmission) - }) - } - fn observe_inner( - &mut self, - position: u64, - chunk: &[u8], - mut available: impl FnMut() -> Result, - ) -> Result<(), ResidentExpertSourceError> { - let end = position - .checked_add(chunk.len() as u64) - .ok_or(ResidentExpertSourceError::Geometry)?; - let mut remaining = self.remaining_commitment()?; - for cell in &mut self.cells { - let start = cell.descriptor.absolute_start; - let bank_end = start - .checked_add(cell.descriptor.bytes as u64) - .ok_or(ResidentExpertSourceError::Geometry)?; - let left = start.max(position); - let right = bank_end.min(end); - if left >= right { - continue; - } - let offset = - usize::try_from(left - start).map_err(|_| ResidentExpertSourceError::Geometry)?; - let count = - usize::try_from(right - left).map_err(|_| ResidentExpertSourceError::Geometry)?; - let next = offset - .checked_add(count) - .ok_or(ResidentExpertSourceError::Geometry)?; - if offset != cell.covered - || offset != cell.bytes.len() - || next > cell.descriptor.bytes - || next > cell.bytes.capacity() - { - return Err(ResidentExpertSourceError::Geometry); - } - let source = usize::try_from(left - position) - .map_err(|_| ResidentExpertSourceError::Geometry)?; - let selected = chunk - .get( - source - ..source - .checked_add(count) - .ok_or(ResidentExpertSourceError::Geometry)?, - ) - .ok_or(ResidentExpertSourceError::Geometry)?; - // Actual snapshot immediately BEFORE touching this span. All other - // reserved banks and capacity slack stay committed; no VM credit. - let next_remaining = remaining - .checked_sub(count) - .ok_or(ResidentExpertSourceError::MemoryAdmission)?; - capture_admit(remaining, FUTURE_OWNERS, available()?)?; - cell.bytes.extend_from_slice(selected); // proven within reservation - cell.covered = next; - remaining = next_remaining; - } - Ok(()) - } -} - -impl ProvisionalExpertSource { - pub(crate) fn prepare_incremental(index: &TensorIndex, retained_kar: Option<&File>) -> Self { - let mut capture = Self::empty(); - if let Err(error) = capture.prepare_incremental_inner(index, retained_kar) { - capture.fail(error); - } - capture - } - fn prepare_incremental_inner( - &mut self, - index: &TensorIndex, - retained_kar: Option<&File>, - ) -> Result<(), ResidentExpertSourceError> { - // Observation ONLY: seals/SHA/CRC stay at the original later KAR gate. - // The keeper's already retained memfd pages are in MemAvailable, so its - // 55 GiB is not also charged as a future allocation. - let observed_kar = retained_kar - .and_then(|file| file.metadata().ok()) - .filter(|metadata| metadata.is_file() && metadata.len() == RETAINED_KAR_BYTES) - .ok_or(ResidentExpertSourceError::MemoryAdmission)?; - let _ = observed_kar; - if index.summary.file_size != PINNED_IDENTITIES[0].0 || index.tensors.len() != 1223 { - return Err(ResidentExpertSourceError::Geometry); - } - self.cells - .try_reserve_exact(BANKS) - .map_err(|_| ResidentExpertSourceError::Allocation)?; - self.banks - .try_reserve_exact(BANKS) - .map_err(|_| ResidentExpertSourceError::Allocation)?; - let mut incremental_cells = Vec::new(); - incremental_cells - .try_reserve_exact(BANKS) - .map_err(|_| ResidentExpertSourceError::Allocation)?; - self.incremental = Some(IncrementalCapture { - cells: incremental_cells, - #[cfg(test)] - test_available: None, - }); - self.charged = self - .cells - .capacity() - .checked_mul(size_of::()) - .and_then(|n| n.checked_add(self.banks.capacity().checked_mul(size_of::())?)) - .and_then(|n| { - n.checked_add( - self.incremental - .as_ref()? - .cells - .capacity() - .checked_mul(size_of::())?, - ) - }) - .and_then(|n| n.checked_add(size_of::() + size_of::())) - .ok_or(ResidentExpertSourceError::MemoryAdmission)?; - // First geometry pass prevents allocation before complete closed layout. - for layer in 0..48 { - for role in [ - LayerRole::FfnGateExperts, - LayerRole::FfnUpExperts, - LayerRole::FfnDownExperts, - ] { - let descriptor = provisional_descriptor(index, TensorRole::Layer { layer, role })?; - self.source_bytes = self - .source_bytes - .checked_add(descriptor.bytes) - .ok_or(ResidentExpertSourceError::Geometry)?; - } - } - let planned = self - .charged - .checked_add(self.source_bytes) - .ok_or(ResidentExpertSourceError::MemoryAdmission)?; - self.observed = memory_available()?; - capture_admit(planned, FUTURE_OWNERS, self.observed)?; - let mut remaining = self.source_bytes; - for layer in 0..48 { - for role in [ - LayerRole::FfnGateExperts, - LayerRole::FfnUpExperts, - LayerRole::FfnDownExperts, - ] { - let descriptor = provisional_descriptor(index, TensorRole::Layer { layer, role })?; - for previous in &self - .incremental - .as_ref() - .ok_or(ResidentExpertSourceError::Geometry)? - .cells - { - let left = previous.descriptor.absolute_start; - let right = left + previous.descriptor.bytes as u64; - let start = descriptor.absolute_start; - let end = start + descriptor.bytes as u64; - if left < end && start < right { - return Err(ResidentExpertSourceError::Geometry); - } - } - // Reserved but untouched pages remain a full commitment. Unlike the - // original zero-fill, reserve does not make them resident yet. - let committed = self - .charged - .checked_add(remaining) - .ok_or(ResidentExpertSourceError::MemoryAdmission)?; - capture_admit(committed, FUTURE_OWNERS, memory_available()?)?; - let mut bytes = Vec::new(); - bytes - .try_reserve_exact(descriptor.bytes) - .map_err(|_| ResidentExpertSourceError::Allocation)?; - let charged_bytes = bytes.capacity(); - self.charged = self - .charged - .checked_add(charged_bytes) - .ok_or(ResidentExpertSourceError::MemoryAdmission)?; - if self.charged as u64 > SOURCE_CAP { - return Err(ResidentExpertSourceError::MemoryAdmission); - } - capture_admit( - self.charged - .checked_add( - remaining - .checked_sub(descriptor.bytes) - .ok_or(ResidentExpertSourceError::MemoryAdmission)?, - ) - .ok_or(ResidentExpertSourceError::MemoryAdmission)?, - FUTURE_OWNERS, - memory_available()?, - )?; - self.incremental - .as_mut() - .ok_or(ResidentExpertSourceError::Geometry)? - .cells - .push(IncrementalTensor { - descriptor, - bytes, - charged_bytes, - covered: 0, - }); - remaining -= descriptor.bytes; - } - } - capture_admit(self.charged, FUTURE_OWNERS, memory_available()?)?; - Ok(()) - } - fn finish_incremental( - &mut self, - source: &VerifiedGgufFile, - ) -> Result<(), ResidentExpertSourceError> { - let incremental = self - .incremental - .as_ref() - .ok_or(ResidentExpertSourceError::Geometry)?; - if !self.cells.is_empty() - || incremental.cells.len() != BANKS - || self.cells.capacity() < incremental.cells.len() - { - return Err(ResidentExpertSourceError::Geometry); - } - for cell in &incremental.cells { - if cell.covered != cell.descriptor.bytes - || cell.bytes.len() != cell.descriptor.bytes - || cell.bytes.capacity() != cell.charged_bytes - || provisional_descriptor(source.index(), cell.descriptor.role)? != cell.descriptor - { - return Err(ResidentExpertSourceError::Geometry); - } - } - // Original whole SHA/strict index completed before bind calls this. - // Move only fully initialized spans into the unchanged opaque gate. - let incremental = self - .incremental - .take() - .ok_or(ResidentExpertSourceError::Geometry)?; - for cell in incremental.cells { - self.cells.push(CapturedTensor { - descriptor: cell.descriptor, - bytes: cell.bytes.into_boxed_slice(), - charged_bytes: cell.charged_bytes, - covered: cell.covered, - }); - } - Ok(()) - } -} -impl Qwen4ExpArtifact { - /// Separately selected incremental capture; original prezeroed API remains. - pub fn open_shard0_with_expert_capture_incremental( - path: &Path, - expected_digest: &str, - retained_kar: Option<&File>, - ) -> Result<(VerifiedGgufFile, ProvisionalExpertSource), Box> { - gguf::open_incremental_expert_capture(path, expected_digest, retained_kar) - } -} - -#[cfg(test)] -impl ProvisionalExpertSource { - fn test_incremental_cells(index: &TensorIndex) -> Self { - let mut capture = Self::test_cells(index); - let original = capture.cells.pop().unwrap(); - let mut bytes = Vec::new(); - bytes.try_reserve_exact(original.descriptor.bytes).unwrap(); - let charged_bytes = bytes.capacity(); - capture.incremental = Some(IncrementalCapture { - cells: vec![IncrementalTensor { - descriptor: original.descriptor, - bytes, - charged_bytes, - covered: 0, - }], - test_available: Some(usize::MAX), - }); - capture - } - fn test_remaining_commitment(&self) -> Result { - self.incremental - .as_ref() - .ok_or(ResidentExpertSourceError::Geometry)? - .remaining_commitment() - } - fn test_observe_inner( - &mut self, - position: u64, - chunk: &[u8], - available: impl FnMut() -> Result, - ) -> Result<(), ResidentExpertSourceError> { - self.incremental - .as_mut() - .ok_or(ResidentExpertSourceError::Geometry)? - .observe_inner(position, chunk, available) - } - fn test_incremental_bytes(&self) -> Option<&[u8]> { - self.incremental - .as_ref()? - .cells - .first() - .filter(|cell| { - cell.covered == cell.descriptor.bytes && cell.bytes.len() == cell.descriptor.bytes - }) - .map(|cell| cell.bytes.as_slice()) - } - fn test_incremental_mint( - mut self, - source: &mut VerifiedGgufFile, - ) -> Result> { - // Transport-only actual tiny source; never production144-bank adoption. - if self.error.is_some() { - return Err("failed capture".into()); - } - let mut incremental = self - .incremental - .take() - .ok_or("missing incremental capture")?; - if incremental.cells.len() != 1 { - return Err("not one fixture span".into()); - } - let cell = incremental.cells.pop().ok_or("missing span")?; - if cell.covered != cell.descriptor.bytes || cell.bytes.len() != cell.descriptor.bytes { - return Err("incomplete capture".into()); - } - let identity = source.capture_source_identity()?; - source.admit_captured_tensor( - identity, - cell.descriptor.tensor_number, - cell.bytes.into_boxed_slice(), - cell.charged_bytes, - ) - } -} #[cfg(test)] #[path = "qwen4exp_digest_capture_incremental_sdet.rs"] mod incremental_sdet; + +#[path = "qwen4exp_digest_capture/capture_admit.rs"] +mod capture_admit; +#[allow(unused_imports)] +pub use capture_admit::*; +#[path = "qwen4exp_digest_capture/impl_provisionalexpertsource.rs"] +mod impl_provisionalexpertsource; +#[allow(unused_imports)] +pub use impl_provisionalexpertsource::*; +#[path = "qwen4exp_digest_capture/impl_qwen4expartifact.rs"] +mod impl_qwen4expartifact; +#[allow(unused_imports)] +pub use impl_qwen4expartifact::*; +#[path = "qwen4exp_digest_capture/impl_provisionalexpertsource_2.rs"] +mod impl_provisionalexpertsource_2; +#[allow(unused_imports)] +pub use impl_provisionalexpertsource_2::*; +#[path = "qwen4exp_digest_capture/impl_provisionalexpertsource_3.rs"] +mod impl_provisionalexpertsource_3; +#[allow(unused_imports)] +pub use impl_provisionalexpertsource_3::*; diff --git a/crates/model-format/src/qwen4exp_digest_capture/capture_admit.rs b/crates/model-format/src/qwen4exp_digest_capture/capture_admit.rs new file mode 100644 index 00000000..fe77d05d --- /dev/null +++ b/crates/model-format/src/qwen4exp_digest_capture/capture_admit.rs @@ -0,0 +1,72 @@ +//! Moved out of the parent module by STRA-338: fn capture_admit, fn provisional_descriptor. + +#[allow(unused_imports)] +use super::*; + + +pub(super) fn capture_admit( + capacity: usize, + future: usize, + available: usize, +) -> Result<(), ResidentExpertSourceError> { + let headroom = + usize::try_from(FUTURE_HEADROOM).map_err(|_| ResidentExpertSourceError::MemoryAdmission)?; + if capacity as u64 > SOURCE_CAP + || capacity + .checked_add(future) + .and_then(|n| n.checked_add(headroom)) + .is_none_or(|n| n > available) + { + return Err(ResidentExpertSourceError::MemoryAdmission); + } + Ok(()) +} + +pub(super) fn provisional_descriptor( + index: &TensorIndex, + role: TensorRole, +) -> Result { + let TensorRole::Layer { + layer, + role: layer_role, + } = role + else { + return Err(ResidentExpertSourceError::Geometry); + }; + let suffix = match layer_role { + LayerRole::FfnGateExperts => "ffn_gate_exps.weight", + LayerRole::FfnUpExperts => "ffn_up_exps.weight", + LayerRole::FfnDownExperts => "ffn_down_exps.weight", + _ => return Err(ResidentExpertSourceError::Geometry), + }; + let name = format!("blk.{layer}.{suffix}"); + let (tensor_number, tensor) = index + .tensors + .iter() + .enumerate() + .find(|(_, tensor)| tensor.name == name) + .ok_or(ResidentExpertSourceError::Geometry)?; + let absolute_start = index + .summary + .data_start + .checked_add(tensor.offset) + .ok_or(ResidentExpertSourceError::Geometry)?; + let resolved = ResolvedTensor { + shard: 0, + tensor_number, + name, + kind: tensor.kind, + dimensions: tensor.dimensions.clone(), + absolute_start, + byte_length: tensor.bytes, + file_size: index.summary.file_size, + }; + let descriptor = checked_descriptor(role, &resolved)?; + if absolute_start + .checked_add(descriptor.bytes as u64) + .is_none_or(|n| n > descriptor.file_size) + { + return Err(ResidentExpertSourceError::Geometry); + } + Ok(descriptor) +} diff --git a/crates/model-format/src/qwen4exp_digest_capture/impl_provisionalexpertsource.rs b/crates/model-format/src/qwen4exp_digest_capture/impl_provisionalexpertsource.rs new file mode 100644 index 00000000..79329a85 --- /dev/null +++ b/crates/model-format/src/qwen4exp_digest_capture/impl_provisionalexpertsource.rs @@ -0,0 +1,211 @@ +//! Moved out of the parent module by STRA-338: impl ProvisionalExpertSource. + +#[allow(unused_imports)] +use super::*; + + +impl ProvisionalExpertSource { + pub(super) fn empty() -> Self { + Self { + cells: Vec::new(), + banks: Vec::new(), + error: None, + source: None, + charged: 0, + source_bytes: 0, + observed: 0, + incremental: None, + } + } + pub(super) fn fail(&mut self, error: ResidentExpertSourceError) { + if self.error.is_none() { + self.error = Some(error); + } + self.cells.clear(); + self.banks.clear(); + self.source = None; + self.incremental = None; + } + pub(crate) fn geometry_failure() -> Self { + let mut capture = Self::empty(); + capture.fail(ResidentExpertSourceError::Geometry); + capture + } + pub(crate) fn prepare(index: &TensorIndex, retained_kar: Option<&File>) -> Self { + let mut capture = Self::empty(); + if let Err(error) = capture.prepare_inner(index, retained_kar) { + capture.fail(error); + } + capture + } + pub(super) fn prepare_inner( + &mut self, + index: &TensorIndex, + retained_kar: Option<&File>, + ) -> Result<(), ResidentExpertSourceError> { + // Observation ONLY: seals/SHA/CRC stay at the original later KAR gate. + // The keeper's already retained memfd pages are in MemAvailable, so its + // 55 GiB is not also charged as a future allocation. + let observed_kar = retained_kar + .and_then(|file| file.metadata().ok()) + .filter(|metadata| metadata.is_file() && metadata.len() == RETAINED_KAR_BYTES) + .ok_or(ResidentExpertSourceError::MemoryAdmission)?; + let _ = observed_kar; + if index.summary.file_size != PINNED_IDENTITIES[0].0 || index.tensors.len() != 1223 { + return Err(ResidentExpertSourceError::Geometry); + } + self.cells + .try_reserve_exact(BANKS) + .map_err(|_| ResidentExpertSourceError::Allocation)?; + self.banks + .try_reserve_exact(BANKS) + .map_err(|_| ResidentExpertSourceError::Allocation)?; + self.charged = self + .cells + .capacity() + .checked_mul(size_of::()) + .and_then(|n| n.checked_add(self.banks.capacity().checked_mul(size_of::())?)) + .and_then(|n| n.checked_add(size_of::() + size_of::())) + .ok_or(ResidentExpertSourceError::MemoryAdmission)?; + // First geometry pass prevents allocation before complete closed layout. + for layer in 0..48 { + for role in [ + LayerRole::FfnGateExperts, + LayerRole::FfnUpExperts, + LayerRole::FfnDownExperts, + ] { + let descriptor = provisional_descriptor(index, TensorRole::Layer { layer, role })?; + self.source_bytes = self + .source_bytes + .checked_add(descriptor.bytes) + .ok_or(ResidentExpertSourceError::Geometry)?; + } + } + let planned = self + .charged + .checked_add(self.source_bytes) + .ok_or(ResidentExpertSourceError::MemoryAdmission)?; + self.observed = memory_available()?; + capture_admit(planned, FUTURE_OWNERS, self.observed)?; + let mut remaining = self.source_bytes; + for layer in 0..48 { + for role in [ + LayerRole::FfnGateExperts, + LayerRole::FfnUpExperts, + LayerRole::FfnDownExperts, + ] { + let descriptor = provisional_descriptor(index, TensorRole::Layer { layer, role })?; + for previous in &self.cells { + let left = previous.descriptor.absolute_start; + let right = left + previous.descriptor.bytes as u64; + let start = descriptor.absolute_start; + let end = start + descriptor.bytes as u64; + if left < end && start < right { + return Err(ResidentExpertSourceError::Geometry); + } + } + capture_admit(remaining, FUTURE_OWNERS, memory_available()?)?; + let mut bytes = Vec::new(); + bytes + .try_reserve_exact(descriptor.bytes) + .map_err(|_| ResidentExpertSourceError::Allocation)?; + let charged_bytes = bytes.capacity(); + self.charged = self + .charged + .checked_add(charged_bytes) + .ok_or(ResidentExpertSourceError::MemoryAdmission)?; + if self.charged as u64 > SOURCE_CAP { + return Err(ResidentExpertSourceError::MemoryAdmission); + } + capture_admit( + remaining + .checked_sub(descriptor.bytes) + .and_then(|n| n.checked_add(charged_bytes)) + .ok_or(ResidentExpertSourceError::MemoryAdmission)?, + FUTURE_OWNERS, + memory_available()?, + )?; + bytes.resize(descriptor.bytes, 0); + self.cells.push(CapturedTensor { + descriptor, + bytes: bytes.into_boxed_slice(), + charged_bytes, + covered: 0, + }); + remaining -= descriptor.bytes; + } + } + capture_admit(0, FUTURE_OWNERS, memory_available()?)?; + Ok(()) + } + pub(crate) fn observe(&mut self, position: u64, chunk: &[u8]) { + if let Some(incremental) = &mut self.incremental { + #[cfg(test)] + let available = incremental.test_available; + let result = incremental.observe_inner(position, chunk, || { + #[cfg(test)] + if let Some(available) = available { + return Ok(available); + } + memory_available() + }); + if let Err(error) = result { + self.fail(error); + } + return; + } + if self.error.is_some() { + return; + } + let Some(end) = position.checked_add(chunk.len() as u64) else { + self.fail(ResidentExpertSourceError::Geometry); + return; + }; + for cell in &mut self.cells { + let start = cell.descriptor.absolute_start; + let bank_end = start + cell.descriptor.bytes as u64; + let left = start.max(position); + let right = bank_end.min(end); + if left >= right { + continue; + } + let offset = (left - start) as usize; + let count = (right - left) as usize; + if offset != cell.covered { + self.fail(ResidentExpertSourceError::Geometry); + return; + } + let source = (left - position) as usize; + cell.bytes[offset..offset + count].copy_from_slice(&chunk[source..source + count]); + cell.covered += count; + } + } + pub(crate) fn bind_verified(&mut self, source: &mut VerifiedGgufFile) { + if self.error.is_none() + && self.incremental.is_some() + && let Err(error) = self.finish_incremental(source) + { + self.fail(error); + } + if self.error.is_some() { + return; + } + let checked = (|| { + for cell in &self.cells { + if cell.covered != cell.bytes.len() + || provisional_descriptor(source.index(), cell.descriptor.role)? + != cell.descriptor + { + return Err(ResidentExpertSourceError::Geometry); + } + } + source + .capture_source_identity() + .map_err(|error| ResidentExpertSourceError::Read(BindingError::Io(error))) + })(); + match checked { + Ok(identity) => self.source = Some(identity), + Err(error) => self.fail(error), + } + } +} diff --git a/crates/model-format/src/qwen4exp_digest_capture/impl_provisionalexpertsource_2.rs b/crates/model-format/src/qwen4exp_digest_capture/impl_provisionalexpertsource_2.rs new file mode 100644 index 00000000..be5a0a17 --- /dev/null +++ b/crates/model-format/src/qwen4exp_digest_capture/impl_provisionalexpertsource_2.rs @@ -0,0 +1,199 @@ +//! Moved out of the parent module by STRA-338: impl ProvisionalExpertSource, impl Qwen4ExpArtifact. + +#[allow(unused_imports)] +use super::*; + + +impl ProvisionalExpertSource { + pub(crate) fn prepare_incremental(index: &TensorIndex, retained_kar: Option<&File>) -> Self { + let mut capture = Self::empty(); + if let Err(error) = capture.prepare_incremental_inner(index, retained_kar) { + capture.fail(error); + } + capture + } + pub(super) fn prepare_incremental_inner( + &mut self, + index: &TensorIndex, + retained_kar: Option<&File>, + ) -> Result<(), ResidentExpertSourceError> { + // Observation ONLY: seals/SHA/CRC stay at the original later KAR gate. + // The keeper's already retained memfd pages are in MemAvailable, so its + // 55 GiB is not also charged as a future allocation. + let observed_kar = retained_kar + .and_then(|file| file.metadata().ok()) + .filter(|metadata| metadata.is_file() && metadata.len() == RETAINED_KAR_BYTES) + .ok_or(ResidentExpertSourceError::MemoryAdmission)?; + let _ = observed_kar; + if index.summary.file_size != PINNED_IDENTITIES[0].0 || index.tensors.len() != 1223 { + return Err(ResidentExpertSourceError::Geometry); + } + self.cells + .try_reserve_exact(BANKS) + .map_err(|_| ResidentExpertSourceError::Allocation)?; + self.banks + .try_reserve_exact(BANKS) + .map_err(|_| ResidentExpertSourceError::Allocation)?; + let mut incremental_cells = Vec::new(); + incremental_cells + .try_reserve_exact(BANKS) + .map_err(|_| ResidentExpertSourceError::Allocation)?; + self.incremental = Some(IncrementalCapture { + cells: incremental_cells, + #[cfg(test)] + test_available: None, + }); + self.charged = self + .cells + .capacity() + .checked_mul(size_of::()) + .and_then(|n| n.checked_add(self.banks.capacity().checked_mul(size_of::())?)) + .and_then(|n| { + n.checked_add( + self.incremental + .as_ref()? + .cells + .capacity() + .checked_mul(size_of::())?, + ) + }) + .and_then(|n| n.checked_add(size_of::() + size_of::())) + .ok_or(ResidentExpertSourceError::MemoryAdmission)?; + // First geometry pass prevents allocation before complete closed layout. + for layer in 0..48 { + for role in [ + LayerRole::FfnGateExperts, + LayerRole::FfnUpExperts, + LayerRole::FfnDownExperts, + ] { + let descriptor = provisional_descriptor(index, TensorRole::Layer { layer, role })?; + self.source_bytes = self + .source_bytes + .checked_add(descriptor.bytes) + .ok_or(ResidentExpertSourceError::Geometry)?; + } + } + let planned = self + .charged + .checked_add(self.source_bytes) + .ok_or(ResidentExpertSourceError::MemoryAdmission)?; + self.observed = memory_available()?; + capture_admit(planned, FUTURE_OWNERS, self.observed)?; + let mut remaining = self.source_bytes; + for layer in 0..48 { + for role in [ + LayerRole::FfnGateExperts, + LayerRole::FfnUpExperts, + LayerRole::FfnDownExperts, + ] { + let descriptor = provisional_descriptor(index, TensorRole::Layer { layer, role })?; + for previous in &self + .incremental + .as_ref() + .ok_or(ResidentExpertSourceError::Geometry)? + .cells + { + let left = previous.descriptor.absolute_start; + let right = left + previous.descriptor.bytes as u64; + let start = descriptor.absolute_start; + let end = start + descriptor.bytes as u64; + if left < end && start < right { + return Err(ResidentExpertSourceError::Geometry); + } + } + // Reserved but untouched pages remain a full commitment. Unlike the + // original zero-fill, reserve does not make them resident yet. + let committed = self + .charged + .checked_add(remaining) + .ok_or(ResidentExpertSourceError::MemoryAdmission)?; + capture_admit(committed, FUTURE_OWNERS, memory_available()?)?; + let mut bytes = Vec::new(); + bytes + .try_reserve_exact(descriptor.bytes) + .map_err(|_| ResidentExpertSourceError::Allocation)?; + let charged_bytes = bytes.capacity(); + self.charged = self + .charged + .checked_add(charged_bytes) + .ok_or(ResidentExpertSourceError::MemoryAdmission)?; + if self.charged as u64 > SOURCE_CAP { + return Err(ResidentExpertSourceError::MemoryAdmission); + } + capture_admit( + self.charged + .checked_add( + remaining + .checked_sub(descriptor.bytes) + .ok_or(ResidentExpertSourceError::MemoryAdmission)?, + ) + .ok_or(ResidentExpertSourceError::MemoryAdmission)?, + FUTURE_OWNERS, + memory_available()?, + )?; + self.incremental + .as_mut() + .ok_or(ResidentExpertSourceError::Geometry)? + .cells + .push(IncrementalTensor { + descriptor, + bytes, + charged_bytes, + covered: 0, + }); + remaining -= descriptor.bytes; + } + } + capture_admit(self.charged, FUTURE_OWNERS, memory_available()?)?; + Ok(()) + } + pub(super) fn finish_incremental( + &mut self, + source: &VerifiedGgufFile, + ) -> Result<(), ResidentExpertSourceError> { + let incremental = self + .incremental + .as_ref() + .ok_or(ResidentExpertSourceError::Geometry)?; + if !self.cells.is_empty() + || incremental.cells.len() != BANKS + || self.cells.capacity() < incremental.cells.len() + { + return Err(ResidentExpertSourceError::Geometry); + } + for cell in &incremental.cells { + if cell.covered != cell.descriptor.bytes + || cell.bytes.len() != cell.descriptor.bytes + || cell.bytes.capacity() != cell.charged_bytes + || provisional_descriptor(source.index(), cell.descriptor.role)? != cell.descriptor + { + return Err(ResidentExpertSourceError::Geometry); + } + } + // Original whole SHA/strict index completed before bind calls this. + // Move only fully initialized spans into the unchanged opaque gate. + let incremental = self + .incremental + .take() + .ok_or(ResidentExpertSourceError::Geometry)?; + for cell in incremental.cells { + self.cells.push(CapturedTensor { + descriptor: cell.descriptor, + bytes: cell.bytes.into_boxed_slice(), + charged_bytes: cell.charged_bytes, + covered: cell.covered, + }); + } + Ok(()) + } +} +impl Qwen4ExpArtifact { + /// Separately selected incremental capture; original prezeroed API remains. + pub fn open_shard0_with_expert_capture_incremental( + path: &Path, + expected_digest: &str, + retained_kar: Option<&File>, + ) -> Result<(VerifiedGgufFile, ProvisionalExpertSource), Box> { + gguf::open_incremental_expert_capture(path, expected_digest, retained_kar) + } +} diff --git a/crates/model-format/src/qwen4exp_digest_capture/impl_provisionalexpertsource_3.rs b/crates/model-format/src/qwen4exp_digest_capture/impl_provisionalexpertsource_3.rs new file mode 100644 index 00000000..7080a5d8 --- /dev/null +++ b/crates/model-format/src/qwen4exp_digest_capture/impl_provisionalexpertsource_3.rs @@ -0,0 +1,80 @@ +//! Moved out of the parent module by STRA-338: impl ProvisionalExpertSource. + +#[allow(unused_imports)] +use super::*; + + +#[cfg(test)] +impl ProvisionalExpertSource { + pub(super) fn test_incremental_cells(index: &TensorIndex) -> Self { + let mut capture = Self::test_cells(index); + let original = capture.cells.pop().unwrap(); + let mut bytes = Vec::new(); + bytes.try_reserve_exact(original.descriptor.bytes).unwrap(); + let charged_bytes = bytes.capacity(); + capture.incremental = Some(IncrementalCapture { + cells: vec![IncrementalTensor { + descriptor: original.descriptor, + bytes, + charged_bytes, + covered: 0, + }], + test_available: Some(usize::MAX), + }); + capture + } + pub(super) fn test_remaining_commitment(&self) -> Result { + self.incremental + .as_ref() + .ok_or(ResidentExpertSourceError::Geometry)? + .remaining_commitment() + } + pub(super) fn test_observe_inner( + &mut self, + position: u64, + chunk: &[u8], + available: impl FnMut() -> Result, + ) -> Result<(), ResidentExpertSourceError> { + self.incremental + .as_mut() + .ok_or(ResidentExpertSourceError::Geometry)? + .observe_inner(position, chunk, available) + } + pub(super) fn test_incremental_bytes(&self) -> Option<&[u8]> { + self.incremental + .as_ref()? + .cells + .first() + .filter(|cell| { + cell.covered == cell.descriptor.bytes && cell.bytes.len() == cell.descriptor.bytes + }) + .map(|cell| cell.bytes.as_slice()) + } + pub(super) fn test_incremental_mint( + mut self, + source: &mut VerifiedGgufFile, + ) -> Result> { + // Transport-only actual tiny source; never production144-bank adoption. + if self.error.is_some() { + return Err("failed capture".into()); + } + let mut incremental = self + .incremental + .take() + .ok_or("missing incremental capture")?; + if incremental.cells.len() != 1 { + return Err("not one fixture span".into()); + } + let cell = incremental.cells.pop().ok_or("missing span")?; + if cell.covered != cell.descriptor.bytes || cell.bytes.len() != cell.descriptor.bytes { + return Err("incomplete capture".into()); + } + let identity = source.capture_source_identity()?; + source.admit_captured_tensor( + identity, + cell.descriptor.tensor_number, + cell.bytes.into_boxed_slice(), + cell.charged_bytes, + ) + } +} diff --git a/crates/model-format/src/qwen4exp_digest_capture/impl_qwen4expartifact.rs b/crates/model-format/src/qwen4exp_digest_capture/impl_qwen4expartifact.rs new file mode 100644 index 00000000..1fa090f1 --- /dev/null +++ b/crates/model-format/src/qwen4exp_digest_capture/impl_qwen4expartifact.rs @@ -0,0 +1,236 @@ +//! Moved out of the parent module by STRA-338: impl Qwen4ExpArtifact, impl ProvisionalExpertSource, impl IncrementalCapture. + +#[allow(unused_imports)] +use super::*; + + +impl Qwen4ExpArtifact { + /// Same-FD full digest/index, with non-consumable optional expert capture. + /// `retained_kar` is an observational owned FD, never KAR admission. + pub fn open_shard0_with_expert_capture( + path: &Path, + expected_digest: &str, + retained_kar: Option<&File>, + ) -> Result<(VerifiedGgufFile, ProvisionalExpertSource), Box> { + gguf::open_expert_capture(path, expected_digest, retained_kar) + } + /// At the ORIGINAL selected bank boundary only: preceding genuine KAR, + /// MTP and profile gates remain the caller's mandatory responsibility. + pub fn adopt_resident_expert_capture( + &mut self, + mut capture: ProvisionalExpertSource, + ) -> Result { + if self.resident_experts.is_some() { + return Err(ResidentExpertSourceError::AlreadyEnabled); + } + if self.topology.block_count != 48 || self.topology.expert_count != 512 { + return Err(ResidentExpertSourceError::Geometry); + } + if let Some(error) = capture.error.take() { + return Err(error); + } + if capture.cells.len() != BANKS + || !capture.banks.is_empty() + || capture.charged as u64 > SOURCE_CAP + { + return Err(ResidentExpertSourceError::Geometry); + } + let identity = capture.source.ok_or(ResidentExpertSourceError::Geometry)?; + self.shards[0] + .validate_capture_identity(identity) + .map_err(|error| ResidentExpertSourceError::Read(BindingError::Io(error)))?; + // Revalidate EVERY bound descriptor before minting even the first final + // tensor. Full finite admission still happens at each selected role. + for (number, cell) in capture.cells.iter().enumerate() { + let resolved = self + .roles + .get(&cell.descriptor.role) + .ok_or(ResidentExpertSourceError::Geometry)?; + if slot(cell.descriptor.role).map_err(ResidentExpertSourceError::Read)? != number + || checked_descriptor(cell.descriptor.role, resolved)? != cell.descriptor + || cell.covered != cell.bytes.len() + { + return Err(ResidentExpertSourceError::Geometry); + } + self.shards[0] + .stream_tensor(cell.descriptor.tensor_number, 0, 0, |_| Ok(())) + .map_err(|error| ResidentExpertSourceError::Read(BindingError::Io(error)))?; + } + // Existing captured Boxes stay in place. Charge only the new small + // shared owners/directory before any wrapping/publication. + let retention = retention_metadata_bytes()?; + capture.charged = capture + .charged + .checked_add(retention) + .ok_or(ResidentExpertSourceError::MemoryAdmission)?; + if capture.charged as u64 > SOURCE_CAP { + return Err(ResidentExpertSourceError::MemoryAdmission); + } + let observed = memory_available()?; + capture_admit(retention, 0, observed)?; // payload pages already resident + for cell in capture.cells { + let tensor = self.shards[0] + .admit_captured_tensor( + identity, + cell.descriptor.tensor_number, + cell.bytes, + cell.charged_bytes, + ) + .map_err(|error| ResidentExpertSourceError::Read(BindingError::Io(error)))?; + capture.banks.push(Bank { + descriptor: cell.descriptor, + tensor: tensor.into_retained(), + }); + } + capture_admit(0, 0, memory_available()?)?; + let report = ResidentExpertSourceReport { + source_bytes: capture.source_bytes as u64, + charged_bytes: capture.charged as u64, + bank_count: BANKS as u32, + source_cap_bytes: SOURCE_CAP, + observed_mem_available_bytes: observed as u64, + future_headroom_bytes: FUTURE_HEADROOM, + shard0_sha256: self.shards[0].artifact_sha256(), + copied_spans: 0, + copied_bytes: 0, + file_mapped: false, + }; + self.resident_experts = Some(ResidentExpertBank { + banks: Rc::new(capture.banks), + report, + copied_spans: Cell::new(0), + copied_bytes: Cell::new(0), + }); + Ok(report) + } +} + +#[cfg(test)] +impl ProvisionalExpertSource { + pub(crate) fn test_cells(index: &TensorIndex) -> Self { + let tensor = &index.tensors[0]; + let descriptor = BankDescriptor { + role: TensorRole::Layer { + layer: 0, + role: LayerRole::FfnGateExperts, + }, + tensor_number: 0, + raw_kind: tensor.kind, + absolute_start: index.summary.data_start + tensor.offset, + file_size: index.summary.file_size, + bytes: tensor.bytes as usize, + }; + let mut capture = Self::empty(); + capture.cells.push(CapturedTensor { + descriptor, + bytes: vec![0; descriptor.bytes].into_boxed_slice(), + charged_bytes: descriptor.bytes, + covered: 0, + }); + capture + } + pub(crate) fn test_bytes(&self) -> Option<&[u8]> { + self.cells + .first() + .filter(|cell| cell.covered == cell.bytes.len()) + .map(|cell| &*cell.bytes) + } + pub(crate) fn test_discarded(&self) -> bool { + self.error.is_some() && self.cells.is_empty() + } + pub(crate) fn test_memory(capacity: usize, future: usize, available: usize) -> bool { + capture_admit(capacity, future, available).is_ok() + } + pub(crate) fn test_mint( + self, + source: &mut VerifiedGgufFile, + ) -> Result> { + // Transport-only fixture: this is NOT the production 144-bank adoption. + if self.error.is_some() || self.cells.len() != 1 { + return Err("incomplete capture".into()); + } + let cell = self.cells.into_iter().next().ok_or("empty capture")?; + if cell.covered != cell.bytes.len() { + return Err("incomplete capture".into()); + } + let identity = source.capture_source_identity()?; + source.admit_captured_tensor( + identity, + cell.descriptor.tensor_number, + cell.bytes, + cell.charged_bytes, + ) + } +} +impl IncrementalCapture { + pub(super) fn remaining_commitment(&self) -> Result { + self.cells.iter().try_fold(0usize, |remaining, cell| { + if cell.bytes.capacity() != cell.charged_bytes + || cell.bytes.len() != cell.covered + || cell.covered > cell.descriptor.bytes + || cell.descriptor.bytes > cell.charged_bytes + { + return Err(ResidentExpertSourceError::Geometry); + } + remaining + .checked_add(cell.charged_bytes - cell.bytes.len()) + .ok_or(ResidentExpertSourceError::MemoryAdmission) + }) + } + pub(super) fn observe_inner( + &mut self, + position: u64, + chunk: &[u8], + mut available: impl FnMut() -> Result, + ) -> Result<(), ResidentExpertSourceError> { + let end = position + .checked_add(chunk.len() as u64) + .ok_or(ResidentExpertSourceError::Geometry)?; + let mut remaining = self.remaining_commitment()?; + for cell in &mut self.cells { + let start = cell.descriptor.absolute_start; + let bank_end = start + .checked_add(cell.descriptor.bytes as u64) + .ok_or(ResidentExpertSourceError::Geometry)?; + let left = start.max(position); + let right = bank_end.min(end); + if left >= right { + continue; + } + let offset = + usize::try_from(left - start).map_err(|_| ResidentExpertSourceError::Geometry)?; + let count = + usize::try_from(right - left).map_err(|_| ResidentExpertSourceError::Geometry)?; + let next = offset + .checked_add(count) + .ok_or(ResidentExpertSourceError::Geometry)?; + if offset != cell.covered + || offset != cell.bytes.len() + || next > cell.descriptor.bytes + || next > cell.bytes.capacity() + { + return Err(ResidentExpertSourceError::Geometry); + } + let source = usize::try_from(left - position) + .map_err(|_| ResidentExpertSourceError::Geometry)?; + let selected = chunk + .get( + source + ..source + .checked_add(count) + .ok_or(ResidentExpertSourceError::Geometry)?, + ) + .ok_or(ResidentExpertSourceError::Geometry)?; + // Actual snapshot immediately BEFORE touching this span. All other + // reserved banks and capacity slack stay committed; no VM credit. + let next_remaining = remaining + .checked_sub(count) + .ok_or(ResidentExpertSourceError::MemoryAdmission)?; + capture_admit(remaining, FUTURE_OWNERS, available()?)?; + cell.bytes.extend_from_slice(selected); // proven within reservation + cell.covered = next; + remaining = next_remaining; + } + Ok(()) + } +} diff --git a/crates/model-format/src/qwen4exp_expert_source_bank.rs b/crates/model-format/src/qwen4exp_expert_source_bank.rs index 7f838b8e..0dd5434e 100644 --- a/crates/model-format/src/qwen4exp_expert_source_bank.rs +++ b/crates/model-format/src/qwen4exp_expert_source_bank.rs @@ -7,13 +7,6 @@ use std::{fs::File, io::Read}; const BANKS: usize = 48 * 3; const SOURCE_CAP: u64 = 52 * 1024 * 1024 * 1024; const FUTURE_HEADROOM: u64 = 8 * 1024 * 1024 * 1024; -// Rc headers plus the small owners, never a second encoded payload allocation. -fn retention_metadata_bytes() -> Result { - BANKS - .checked_mul(gguf::ResidentTensor::retention_metadata_bytes()) - .and_then(|n| n.checked_add(size_of::>() + 2 * size_of::())) - .ok_or(ResidentExpertSourceError::MemoryAdmission) -} #[derive(Clone, Copy, Debug)] pub struct ResidentExpertSourceReport { @@ -37,12 +30,6 @@ pub enum ResidentExpertSourceError { AlreadyEnabled, Read(BindingError), } -impl fmt::Display for ResidentExpertSourceError { - fn fmt(&self, out: &mut fmt::Formatter<'_>) -> fmt::Result { - write!(out, "resident expert source: {self:?}") - } -} -impl Error for ResidentExpertSourceError {} #[derive(Clone, Copy, PartialEq, Eq)] struct BankDescriptor { @@ -64,375 +51,6 @@ pub(super) struct ResidentExpertBank { copied_bytes: Cell, } -fn checked_descriptor( - role: TensorRole, - tensor: &ResolvedTensor, -) -> Result { - use LayerRole as L; - let (columns, rows, kinds): (u64, u64, &[u32]) = match role { - TensorRole::Layer { - layer, - role: L::FfnGateExperts | L::FfnUpExperts, - } if layer < 48 => (2560, 640, &[18, 21, 22, 23]), - TensorRole::Layer { - layer, - role: L::FfnDownExperts, - } if layer < 48 => (640, 2560, &[20, 42]), - _ => return Err(ResidentExpertSourceError::Geometry), - }; - if tensor.shard != 0 - || tensor.dimensions != [columns, rows, 512] - || !kinds.contains(&tensor.kind) - { - return Err(ResidentExpertSourceError::Geometry); - } - let first = plan_stream_rows(tensor, role, 0, rows, Some(0)) - .map_err(|_| ResidentExpertSourceError::Geometry)?; - let last = plan_stream_rows(tensor, role, 0, rows, Some(511)) - .map_err(|_| ResidentExpertSourceError::Geometry)?; - if first.0 != 0 - || first.1 == 0 - || first.1.checked_mul(512) != Some(tensor.byte_length) - || Some(last.0) != first.1.checked_mul(511) - || last.1 != first.1 - || last.0.checked_add(last.1) != Some(tensor.byte_length) - { - return Err(ResidentExpertSourceError::Geometry); - } - Ok(BankDescriptor { - role, - tensor_number: tensor.tensor_number, - raw_kind: tensor.kind, - absolute_start: tensor.absolute_start, - file_size: tensor.file_size, - bytes: usize::try_from(tensor.byte_length) - .map_err(|_| ResidentExpertSourceError::Geometry)?, - }) -} -fn slot(role: TensorRole) -> Result { - let (layer, role) = match role { - TensorRole::Layer { layer, role } if layer < 48 => (layer, role), - _ => return Err(BindingError::Role("resident_expert_role")), - }; - let role = match role { - LayerRole::FfnGateExperts => 0, - LayerRole::FfnUpExperts => 1, - LayerRole::FfnDownExperts => 2, - _ => return Err(BindingError::Role("resident_expert_role")), - }; - Ok(usize::from(layer) * 3 + role) -} -// Existing resident KAR and other owners are already reflected in MemAvailable. -// This is a snapshot, never an allocation reservation or a guarantee against races. -fn memory_available() -> Result { - #[cfg(target_os = "linux")] - { - let mut text = String::new(); - File::open("/proc/meminfo") - .map_err(|_| ResidentExpertSourceError::MemoryAdmission)? - .take(65537) - .read_to_string(&mut text) - .map_err(|_| ResidentExpertSourceError::MemoryAdmission)?; - if text.len() > 65536 { - return Err(ResidentExpertSourceError::MemoryAdmission); - } - parse_memory_available(&text) - } - #[cfg(windows)] - { - let (total, available) = leleka_libc_shim::physical_memory().ok_or(ResidentExpertSourceError::MemoryAdmission)?; - parse_memory_available(&format!("MemTotal: {} kB -MemAvailable: {} kB -", total / 1024, available / 1024)) - } - #[cfg(not(any(target_os = "linux", windows)))] - { - Err(ResidentExpertSourceError::MemoryAdmission) - } -} -#[cfg(any(target_os = "linux", windows, test))] -fn parse_memory_available(text: &str) -> Result { - let mut available = None; - let mut total = None; - for line in text.lines() { - let mut parts = line.split_ascii_whitespace(); - let Some(key) = parts.next() else { continue }; - let destination = match key { - "MemAvailable:" => &mut available, - "MemTotal:" => &mut total, - _ => continue, - }; - if destination.is_some() { - return Err(ResidentExpertSourceError::MemoryAdmission); - } - let value = parts - .next() - .ok_or(ResidentExpertSourceError::MemoryAdmission)? - .parse::() - .map_err(|_| ResidentExpertSourceError::MemoryAdmission)?; - if parts.next() != Some("kB") || parts.next().is_some() { - return Err(ResidentExpertSourceError::MemoryAdmission); - } - *destination = Some( - value - .checked_mul(1024) - .ok_or(ResidentExpertSourceError::MemoryAdmission)?, - ); - } - let available = available.ok_or(ResidentExpertSourceError::MemoryAdmission)?; - let total = total.ok_or(ResidentExpertSourceError::MemoryAdmission)?; - if total == 0 || available > total { - return Err(ResidentExpertSourceError::MemoryAdmission); - } - Ok(available) -} -fn admit(capacity: usize, available: usize) -> Result<(), ResidentExpertSourceError> { - if capacity as u64 > SOURCE_CAP - || (capacity as u64) - .checked_add(FUTURE_HEADROOM) - .is_none_or(|n| n > available as u64) - { - return Err(ResidentExpertSourceError::MemoryAdmission); - } - Ok(()) -} - -#[cfg(test)] -pub(crate) fn test_resident_source_memory_admission( - text: &str, - capacity: usize, -) -> Result<(), ResidentExpertSourceError> { - admit(capacity, parse_memory_available(text)?) -} -impl ResidentExpertBank { - pub(super) fn note_copy(&self, bytes: usize) { - self.copied_spans - .set(self.copied_spans.get().saturating_add(1)); - self.copied_bytes - .set(self.copied_bytes.get().saturating_add(bytes as u64)); - } - fn report(&self) -> ResidentExpertSourceReport { - ResidentExpertSourceReport { - copied_spans: self.copied_spans.get(), - copied_bytes: self.copied_bytes.get(), - ..self.report - } - } - pub(super) fn tensor( - &self, - role: TensorRole, - tensor: &ResolvedTensor, - ) -> Result<&gguf::ResidentTensor, BindingError> { - let descriptor = checked_descriptor(role, tensor) - .map_err(|_| BindingError::Geometry("resident_expert_descriptor"))?; - let bank = self - .banks - .get(slot(role)?) - .ok_or(BindingError::Geometry("resident_expert_directory"))?; - if bank.descriptor != descriptor || bank.tensor.len() != descriptor.bytes { - return Err(BindingError::Geometry("resident_expert_descriptor")); - } - Ok(&bank.tensor) - } -} -impl Qwen4ExpArtifact { - /// Explicit fresh-owner load; called before publishing a selected binding. - /// No tensor finite admission is performed on unused expert banks. - pub fn load_resident_expert_source( - &mut self, - ) -> Result { - if self.resident_experts.is_some() { - return Err(ResidentExpertSourceError::AlreadyEnabled); - } - if self.topology.block_count != 48 || self.topology.expert_count != 512 { - return Err(ResidentExpertSourceError::Geometry); - } - let mut plan = Vec::new(); - plan.try_reserve_exact(BANKS) - .map_err(|_| ResidentExpertSourceError::Allocation)?; - let mut banks = Vec::new(); - banks - .try_reserve_exact(BANKS) - .map_err(|_| ResidentExpertSourceError::Allocation)?; - let metadata = plan - .capacity() - .checked_mul(size_of::()) - .and_then(|v| v.checked_add(banks.capacity().checked_mul(size_of::())?)) - .and_then(|v| v.checked_add(size_of::() + 2 * size_of::())) - .and_then(|v| v.checked_add(retention_metadata_bytes().ok()?)) - .ok_or(ResidentExpertSourceError::Geometry)?; - let mut source_bytes = 0usize; - for layer in 0..48 { - for role in [ - LayerRole::FfnGateExperts, - LayerRole::FfnUpExperts, - LayerRole::FfnDownExperts, - ] { - let role = TensorRole::Layer { layer, role }; - let tensor = self - .roles - .get(&role) - .ok_or(ResidentExpertSourceError::Geometry)?; - let descriptor = checked_descriptor(role, tensor)?; - source_bytes = source_bytes - .checked_add(descriptor.bytes) - .ok_or(ResidentExpertSourceError::Geometry)?; - plan.push(descriptor); - } - } - let planned = source_bytes - .checked_add(metadata) - .ok_or(ResidentExpertSourceError::Geometry)?; - let observed = memory_available()?; - admit(planned, observed)?; - let mut charged = metadata; - let mut remaining = source_bytes; - for descriptor in plan { - // The current snapshot reflects already initialized bank pages too. - admit(remaining, memory_available()?)?; - let ceiling = usize::try_from( - SOURCE_CAP - .checked_sub(charged as u64) - .ok_or(ResidentExpertSourceError::MemoryAdmission)?, - ) - .map_err(|_| ResidentExpertSourceError::MemoryAdmission)?; - let tensor = self.shards[0] - .load_resident_tensor(descriptor.tensor_number, ceiling) - .map_err(|error| match error { - gguf::ResidentLoadError::Allocation => ResidentExpertSourceError::Allocation, - gguf::ResidentLoadError::Budget => ResidentExpertSourceError::MemoryAdmission, - gguf::ResidentLoadError::Source(error) => { - ResidentExpertSourceError::Read(BindingError::Io(error)) - } - })?; - charged = charged - .checked_add(tensor.charged_bytes()) - .ok_or(ResidentExpertSourceError::MemoryAdmission)?; - if charged as u64 > SOURCE_CAP { - return Err(ResidentExpertSourceError::MemoryAdmission); - } - remaining = remaining - .checked_sub(descriptor.bytes) - .ok_or(ResidentExpertSourceError::Geometry)?; - banks.push(Bank { - descriptor, - tensor: tensor.into_retained(), - }); - } - // Bank publication itself retains the same current-source refusal. - let last = banks.last().ok_or(ResidentExpertSourceError::Geometry)?; - self.shards[0] - .stream_tensor(last.descriptor.tensor_number, 0, 0, |_| Ok(())) - .map_err(|error| ResidentExpertSourceError::Read(BindingError::Io(error)))?; - admit(0, memory_available()?)?; - if remaining != 0 || banks.len() != BANKS { - return Err(ResidentExpertSourceError::Geometry); - } - let report = ResidentExpertSourceReport { - source_bytes: source_bytes as u64, - charged_bytes: charged as u64, - bank_count: BANKS as u32, - source_cap_bytes: SOURCE_CAP, - observed_mem_available_bytes: observed as u64, - future_headroom_bytes: FUTURE_HEADROOM, - shard0_sha256: self.shards[0].artifact_sha256(), - copied_spans: 0, - copied_bytes: 0, - file_mapped: false, - }; - self.resident_experts = Some(ResidentExpertBank { - banks: Rc::new(banks), - report, - copied_spans: Cell::new(0), - copied_bytes: Cell::new(0), - }); - Ok(report) - } - pub fn resident_expert_source_report(&self) -> Option { - self.resident_experts.as_ref().map(|bank| bank.report()) - } - - /// The low-RAM source (the Original's `--mmap-experts`, GGUF shards in place: generate.cpp - /// `src.set_gguf(o.native_preset)` + `FileExpertSource::open`): the same 144 banks, but each is a read-only - /// shared mapping of shard 0 instead of a RAM copy. Nothing is read at load; the OS file cache holds the - /// experts that are used and can give the memory back. The bytes are the verified file's, so every consumer - /// sees exactly what the resident copy would hold. No `MemAvailable` admission: the mapping commits no RAM. - #[cfg(any(target_os = "linux", windows))] - pub fn load_mapped_expert_source( - &mut self, - ) -> Result { - if self.resident_experts.is_some() { - return Err(ResidentExpertSourceError::AlreadyEnabled); - } - if self.topology.block_count != 48 || self.topology.expert_count != 512 { - return Err(ResidentExpertSourceError::Geometry); - } - let mut banks = Vec::new(); - banks - .try_reserve_exact(BANKS) - .map_err(|_| ResidentExpertSourceError::Allocation)?; - let mut source_bytes = 0usize; - for layer in 0..48 { - for role in [ - LayerRole::FfnGateExperts, - LayerRole::FfnUpExperts, - LayerRole::FfnDownExperts, - ] { - let role = TensorRole::Layer { layer, role }; - let tensor = self - .roles - .get(&role) - .ok_or(ResidentExpertSourceError::Geometry)?; - let descriptor = checked_descriptor(role, tensor)?; - source_bytes = source_bytes - .checked_add(descriptor.bytes) - .ok_or(ResidentExpertSourceError::Geometry)?; - if source_bytes as u64 > SOURCE_CAP { - return Err(ResidentExpertSourceError::MemoryAdmission); - } - let mapped = self.shards[0] - .map_resident_tensor(descriptor.tensor_number) - .map_err(|error| match error { - gguf::ResidentLoadError::Allocation => ResidentExpertSourceError::Allocation, - gguf::ResidentLoadError::Budget => ResidentExpertSourceError::MemoryAdmission, - gguf::ResidentLoadError::Source(error) => { - ResidentExpertSourceError::Read(BindingError::Io(error)) - } - })?; - if mapped.len() != descriptor.bytes { - return Err(ResidentExpertSourceError::Geometry); - } - banks.push(Bank { - descriptor, - tensor: mapped.into_retained(), - }); - } - } - if banks.len() != BANKS { - return Err(ResidentExpertSourceError::Geometry); - } - let report = ResidentExpertSourceReport { - source_bytes: source_bytes as u64, - charged_bytes: source_bytes as u64, - bank_count: BANKS as u32, - source_cap_bytes: SOURCE_CAP, - observed_mem_available_bytes: 0, - future_headroom_bytes: 0, - shard0_sha256: self.shards[0].artifact_sha256(), - copied_spans: 0, - copied_bytes: 0, - file_mapped: true, - }; - self.resident_experts = Some(ResidentExpertBank { - banks: Rc::new(banks), - report, - copied_spans: Cell::new(0), - copied_bytes: Cell::new(0), - }); - Ok(report) - } -} - #[path = "qwen4exp_digest_capture.rs"] mod digest_capture; pub use digest_capture::ProvisionalExpertSource; @@ -443,28 +61,6 @@ pub struct ResidentExpertBankLease { banks: Rc>, report: ResidentExpertSourceReport, } -impl ResidentExpertBankLease { - pub fn bank_count(&self) -> usize { - self.banks.len() - } - pub fn source_bytes(&self) -> u64 { - self.report.source_bytes - } - pub fn charged_source_bytes(&self) -> u64 { - self.report.charged_bytes - } - /// The banks are read-only shared mappings of the verified shard (the low-RAM source): page-locking them - /// would read and lock the whole file in RAM, so their consumers copy from pageable memory instead. - pub fn file_mapped(&self) -> bool { - self.report.file_mapped - } - pub fn retention_metadata_bytes(&self) -> usize { - // Complete lease was minted only after this checked closed bound. - BANKS * gguf::ResidentTensor::retention_metadata_bytes() - + size_of::>() - + 2 * size_of::() - } -} /// Exact named bank retained from an admitted catalog, not caller bytes/ranges. /// `bytes` is initialized immutable addressability, never a finite/pinned proof. #[derive(Clone)] @@ -472,96 +68,6 @@ pub struct ResidentExpertBankMember { descriptor: BankDescriptor, tensor: Rc, } -impl ResidentExpertBankMember { - pub fn role(&self) -> TensorRole { - self.descriptor.role - } - pub fn raw_kind(&self) -> u32 { - self.descriptor.raw_kind - } - pub fn tensor_number(&self) -> usize { - self.descriptor.tensor_number - } - pub fn absolute_start(&self) -> u64 { - self.descriptor.absolute_start - } - pub fn bytes(&self) -> &[u8] { - self.tensor.retained_bytes() - } - pub fn file_mapped(&self) -> bool { - self.tensor.file_mapped() - } - pub fn belongs_to_lease(&self, lease: &ResidentExpertBankLease) -> bool { - slot(self.descriptor.role) - .ok() - .and_then(|n| lease.banks.get(n)) - .is_some_and(|bank| { - bank.descriptor == self.descriptor && Rc::ptr_eq(&bank.tensor, &self.tensor) - }) - } -} -impl Qwen4ExpArtifact { - /// Short actual artifact borrow; result owns all144 existing allocations. - pub fn resident_expert_bank_lease(&self) -> Result { - let bank = self - .resident_experts - .as_ref() - .ok_or(BindingError::Role("resident_expert_source_absent"))?; - if bank.banks.len() != BANKS - || bank.report.bank_count != BANKS as u32 - || bank.report.charged_bytes > SOURCE_CAP - { - return Err(BindingError::Geometry("resident_expert_directory")); - } - for (number, member) in bank.banks.iter().enumerate() { - let tensor = self - .roles - .get(&member.descriptor.role) - .ok_or(BindingError::Geometry("resident_expert_descriptor"))?; - if slot(member.descriptor.role)? != number { - return Err(BindingError::Geometry("resident_expert_directory")); - } - bank.tensor(member.descriptor.role, tensor)?; - self.shards[0] - .validate_retained_tensor(&member.tensor) - .map_err(BindingError::Io)?; - } - Ok(ResidentExpertBankLease { - banks: Rc::clone(&bank.banks), - report: bank.report(), - }) - } - /// Rechecks real catalog membership/current sameFD before releasing borrow. - pub fn resident_expert_bank_member( - &self, - lease: &ResidentExpertBankLease, - layer: u8, - role: LayerRole, - ) -> Result { - let bank = self - .resident_experts - .as_ref() - .ok_or(BindingError::Role("resident_expert_source_absent"))?; - if !Rc::ptr_eq(&bank.banks, &lease.banks) || lease.banks.len() != BANKS { - return Err(BindingError::Geometry("resident_expert_directory")); - } - let role = TensorRole::Layer { layer, role }; - let number = slot(role)?; - let resolved = self - .roles - .get(&role) - .ok_or(BindingError::Geometry("resident_expert_descriptor"))?; - bank.tensor(role, resolved)?; - let member = &lease.banks[number]; - self.shards[0] - .validate_retained_tensor(&member.tensor) - .map_err(BindingError::Io)?; - Ok(ResidentExpertBankMember { - descriptor: member.descriptor, - tensor: Rc::clone(&member.tensor), - }) - } -} /// Immutable initialized fixed-expert addressability, not source health, /// registration, finite data or a runtime row/Context certificate. @@ -572,72 +78,16 @@ pub struct ResidentExpertBankSpan { offset: usize, length: usize, } -impl ResidentExpertBankSpan { - pub fn bytes(&self) -> &[u8] { - &self.member.bytes()[self.offset..self.offset + self.length] - } - pub fn offset(&self) -> usize { - self.offset - } - pub fn expert(&self) -> u32 { - self.expert - } - pub fn role(&self) -> TensorRole { - self.member.role() - } - pub fn raw_kind(&self) -> u32 { - self.member.raw_kind() - } - /// The bytes are a read-only shared mapping of the verified shard (the low-RAM source), so a read - /// may fault the page in from the file. - pub fn file_mapped(&self) -> bool { - self.member.file_mapped() - } - pub fn belongs_to(&self, member: &ResidentExpertBankMember) -> bool { - self.member.descriptor == member.descriptor - && Rc::ptr_eq(&self.member.tensor, &member.tensor) - } -} -impl ResidentExpertBank { - pub(super) fn span( - &self, - role: TensorRole, - tensor: &ResolvedTensor, - expert: u32, - ) -> Result { - if expert >= 512 { - return Err(BindingError::Range("resident_expert")); - } - self.tensor(role, tensor)?; - let rows = if matches!( - role, - TensorRole::Layer { - role: LayerRole::FfnDownExperts, - .. - } - ) { - 2560 - } else { - 640 - }; - let (offset, length) = plan_stream_rows(tensor, role, 0, rows, Some(u64::from(expert)))?; - let offset = usize::try_from(offset).map_err(|_| BindingError::Range("resident_expert"))?; - let length = usize::try_from(length).map_err(|_| BindingError::Range("resident_expert"))?; - let bank = &self.banks[slot(role)?]; - if offset - .checked_add(length) - .is_none_or(|end| end > bank.tensor.retained_bytes().len()) - { - return Err(BindingError::Range("resident_expert")); - } - Ok(ResidentExpertBankSpan { - member: ResidentExpertBankMember { - descriptor: bank.descriptor, - tensor: Rc::clone(&bank.tensor), - }, - expert, - offset, - length, - }) - } -} + +#[path = "qwen4exp_expert_source_bank/retention_metadata_bytes.rs"] +mod retention_metadata_bytes; +#[allow(unused_imports)] +pub use retention_metadata_bytes::*; +#[path = "qwen4exp_expert_source_bank/impl_qwen4expartifact.rs"] +mod impl_qwen4expartifact; +#[allow(unused_imports)] +pub use impl_qwen4expartifact::*; +#[path = "qwen4exp_expert_source_bank/impl_qwen4expartifact_2.rs"] +mod impl_qwen4expartifact_2; +#[allow(unused_imports)] +pub use impl_qwen4expartifact_2::*; diff --git a/crates/model-format/src/qwen4exp_expert_source_bank/impl_qwen4expartifact.rs b/crates/model-format/src/qwen4exp_expert_source_bank/impl_qwen4expartifact.rs new file mode 100644 index 00000000..cdbe1f6f --- /dev/null +++ b/crates/model-format/src/qwen4exp_expert_source_bank/impl_qwen4expartifact.rs @@ -0,0 +1,252 @@ +//! Moved out of the parent module by STRA-338: impl Qwen4ExpArtifact, impl ResidentExpertBankLease, impl ResidentExpertBankMember. + +#[allow(unused_imports)] +use super::*; + +impl Qwen4ExpArtifact { + /// Explicit fresh-owner load; called before publishing a selected binding. + /// No tensor finite admission is performed on unused expert banks. + pub fn load_resident_expert_source( + &mut self, + ) -> Result { + if self.resident_experts.is_some() { + return Err(ResidentExpertSourceError::AlreadyEnabled); + } + if self.topology.block_count != 48 || self.topology.expert_count != 512 { + return Err(ResidentExpertSourceError::Geometry); + } + let mut plan = Vec::new(); + plan.try_reserve_exact(BANKS) + .map_err(|_| ResidentExpertSourceError::Allocation)?; + let mut banks = Vec::new(); + banks + .try_reserve_exact(BANKS) + .map_err(|_| ResidentExpertSourceError::Allocation)?; + let metadata = plan + .capacity() + .checked_mul(size_of::()) + .and_then(|v| v.checked_add(banks.capacity().checked_mul(size_of::())?)) + .and_then(|v| v.checked_add(size_of::() + 2 * size_of::())) + .and_then(|v| v.checked_add(retention_metadata_bytes().ok()?)) + .ok_or(ResidentExpertSourceError::Geometry)?; + let mut source_bytes = 0usize; + for layer in 0..48 { + for role in [ + LayerRole::FfnGateExperts, + LayerRole::FfnUpExperts, + LayerRole::FfnDownExperts, + ] { + let role = TensorRole::Layer { layer, role }; + let tensor = self + .roles + .get(&role) + .ok_or(ResidentExpertSourceError::Geometry)?; + let descriptor = checked_descriptor(role, tensor)?; + source_bytes = source_bytes + .checked_add(descriptor.bytes) + .ok_or(ResidentExpertSourceError::Geometry)?; + plan.push(descriptor); + } + } + let planned = source_bytes + .checked_add(metadata) + .ok_or(ResidentExpertSourceError::Geometry)?; + let observed = memory_available()?; + admit(planned, observed)?; + let mut charged = metadata; + let mut remaining = source_bytes; + for descriptor in plan { + // The current snapshot reflects already initialized bank pages too. + admit(remaining, memory_available()?)?; + let ceiling = usize::try_from( + SOURCE_CAP + .checked_sub(charged as u64) + .ok_or(ResidentExpertSourceError::MemoryAdmission)?, + ) + .map_err(|_| ResidentExpertSourceError::MemoryAdmission)?; + let tensor = self.shards[0] + .load_resident_tensor(descriptor.tensor_number, ceiling) + .map_err(|error| match error { + gguf::ResidentLoadError::Allocation => ResidentExpertSourceError::Allocation, + gguf::ResidentLoadError::Budget => ResidentExpertSourceError::MemoryAdmission, + gguf::ResidentLoadError::Source(error) => { + ResidentExpertSourceError::Read(BindingError::Io(error)) + } + })?; + charged = charged + .checked_add(tensor.charged_bytes()) + .ok_or(ResidentExpertSourceError::MemoryAdmission)?; + if charged as u64 > SOURCE_CAP { + return Err(ResidentExpertSourceError::MemoryAdmission); + } + remaining = remaining + .checked_sub(descriptor.bytes) + .ok_or(ResidentExpertSourceError::Geometry)?; + banks.push(Bank { + descriptor, + tensor: tensor.into_retained(), + }); + } + // Bank publication itself retains the same current-source refusal. + let last = banks.last().ok_or(ResidentExpertSourceError::Geometry)?; + self.shards[0] + .stream_tensor(last.descriptor.tensor_number, 0, 0, |_| Ok(())) + .map_err(|error| ResidentExpertSourceError::Read(BindingError::Io(error)))?; + admit(0, memory_available()?)?; + if remaining != 0 || banks.len() != BANKS { + return Err(ResidentExpertSourceError::Geometry); + } + let report = ResidentExpertSourceReport { + source_bytes: source_bytes as u64, + charged_bytes: charged as u64, + bank_count: BANKS as u32, + source_cap_bytes: SOURCE_CAP, + observed_mem_available_bytes: observed as u64, + future_headroom_bytes: FUTURE_HEADROOM, + shard0_sha256: self.shards[0].artifact_sha256(), + copied_spans: 0, + copied_bytes: 0, + file_mapped: false, + }; + self.resident_experts = Some(ResidentExpertBank { + banks: Rc::new(banks), + report, + copied_spans: Cell::new(0), + copied_bytes: Cell::new(0), + }); + Ok(report) + } + pub fn resident_expert_source_report(&self) -> Option { + self.resident_experts.as_ref().map(|bank| bank.report()) + } + + /// The low-RAM source (the Original's `--mmap-experts`, GGUF shards in place: generate.cpp + /// `src.set_gguf(o.native_preset)` + `FileExpertSource::open`): the same 144 banks, but each is a read-only + /// shared mapping of shard 0 instead of a RAM copy. Nothing is read at load; the OS file cache holds the + /// experts that are used and can give the memory back. The bytes are the verified file's, so every consumer + /// sees exactly what the resident copy would hold. No `MemAvailable` admission: the mapping commits no RAM. + #[cfg(any(target_os = "linux", windows))] + pub fn load_mapped_expert_source( + &mut self, + ) -> Result { + if self.resident_experts.is_some() { + return Err(ResidentExpertSourceError::AlreadyEnabled); + } + if self.topology.block_count != 48 || self.topology.expert_count != 512 { + return Err(ResidentExpertSourceError::Geometry); + } + let mut banks = Vec::new(); + banks + .try_reserve_exact(BANKS) + .map_err(|_| ResidentExpertSourceError::Allocation)?; + let mut source_bytes = 0usize; + for layer in 0..48 { + for role in [ + LayerRole::FfnGateExperts, + LayerRole::FfnUpExperts, + LayerRole::FfnDownExperts, + ] { + let role = TensorRole::Layer { layer, role }; + let tensor = self + .roles + .get(&role) + .ok_or(ResidentExpertSourceError::Geometry)?; + let descriptor = checked_descriptor(role, tensor)?; + source_bytes = source_bytes + .checked_add(descriptor.bytes) + .ok_or(ResidentExpertSourceError::Geometry)?; + if source_bytes as u64 > SOURCE_CAP { + return Err(ResidentExpertSourceError::MemoryAdmission); + } + let mapped = self.shards[0] + .map_resident_tensor(descriptor.tensor_number) + .map_err(|error| match error { + gguf::ResidentLoadError::Allocation => ResidentExpertSourceError::Allocation, + gguf::ResidentLoadError::Budget => ResidentExpertSourceError::MemoryAdmission, + gguf::ResidentLoadError::Source(error) => { + ResidentExpertSourceError::Read(BindingError::Io(error)) + } + })?; + if mapped.len() != descriptor.bytes { + return Err(ResidentExpertSourceError::Geometry); + } + banks.push(Bank { + descriptor, + tensor: mapped.into_retained(), + }); + } + } + if banks.len() != BANKS { + return Err(ResidentExpertSourceError::Geometry); + } + let report = ResidentExpertSourceReport { + source_bytes: source_bytes as u64, + charged_bytes: source_bytes as u64, + bank_count: BANKS as u32, + source_cap_bytes: SOURCE_CAP, + observed_mem_available_bytes: 0, + future_headroom_bytes: 0, + shard0_sha256: self.shards[0].artifact_sha256(), + copied_spans: 0, + copied_bytes: 0, + file_mapped: true, + }; + self.resident_experts = Some(ResidentExpertBank { + banks: Rc::new(banks), + report, + copied_spans: Cell::new(0), + copied_bytes: Cell::new(0), + }); + Ok(report) + } +} +impl ResidentExpertBankLease { + pub fn bank_count(&self) -> usize { + self.banks.len() + } + pub fn source_bytes(&self) -> u64 { + self.report.source_bytes + } + pub fn charged_source_bytes(&self) -> u64 { + self.report.charged_bytes + } + /// The banks are read-only shared mappings of the verified shard (the low-RAM source): page-locking them + /// would read and lock the whole file in RAM, so their consumers copy from pageable memory instead. + pub fn file_mapped(&self) -> bool { + self.report.file_mapped + } + pub fn retention_metadata_bytes(&self) -> usize { + // Complete lease was minted only after this checked closed bound. + BANKS * gguf::ResidentTensor::retention_metadata_bytes() + + size_of::>() + + 2 * size_of::() + } +} +impl ResidentExpertBankMember { + pub fn role(&self) -> TensorRole { + self.descriptor.role + } + pub fn raw_kind(&self) -> u32 { + self.descriptor.raw_kind + } + pub fn tensor_number(&self) -> usize { + self.descriptor.tensor_number + } + pub fn absolute_start(&self) -> u64 { + self.descriptor.absolute_start + } + pub fn bytes(&self) -> &[u8] { + self.tensor.retained_bytes() + } + pub fn file_mapped(&self) -> bool { + self.tensor.file_mapped() + } + pub fn belongs_to_lease(&self, lease: &ResidentExpertBankLease) -> bool { + slot(self.descriptor.role) + .ok() + .and_then(|n| lease.banks.get(n)) + .is_some_and(|bank| { + bank.descriptor == self.descriptor && Rc::ptr_eq(&bank.tensor, &self.tensor) + }) + } +} diff --git a/crates/model-format/src/qwen4exp_expert_source_bank/impl_qwen4expartifact_2.rs b/crates/model-format/src/qwen4exp_expert_source_bank/impl_qwen4expartifact_2.rs new file mode 100644 index 00000000..f8d7578a --- /dev/null +++ b/crates/model-format/src/qwen4exp_expert_source_bank/impl_qwen4expartifact_2.rs @@ -0,0 +1,136 @@ +//! Moved out of the parent module by STRA-338: impl Qwen4ExpArtifact, impl ResidentExpertBankSpan, impl ResidentExpertBank. + +#[allow(unused_imports)] +use super::*; + +impl Qwen4ExpArtifact { + /// Short actual artifact borrow; result owns all144 existing allocations. + pub fn resident_expert_bank_lease(&self) -> Result { + let bank = self + .resident_experts + .as_ref() + .ok_or(BindingError::Role("resident_expert_source_absent"))?; + if bank.banks.len() != BANKS + || bank.report.bank_count != BANKS as u32 + || bank.report.charged_bytes > SOURCE_CAP + { + return Err(BindingError::Geometry("resident_expert_directory")); + } + for (number, member) in bank.banks.iter().enumerate() { + let tensor = self + .roles + .get(&member.descriptor.role) + .ok_or(BindingError::Geometry("resident_expert_descriptor"))?; + if slot(member.descriptor.role)? != number { + return Err(BindingError::Geometry("resident_expert_directory")); + } + bank.tensor(member.descriptor.role, tensor)?; + self.shards[0] + .validate_retained_tensor(&member.tensor) + .map_err(BindingError::Io)?; + } + Ok(ResidentExpertBankLease { + banks: Rc::clone(&bank.banks), + report: bank.report(), + }) + } + /// Rechecks real catalog membership/current sameFD before releasing borrow. + pub fn resident_expert_bank_member( + &self, + lease: &ResidentExpertBankLease, + layer: u8, + role: LayerRole, + ) -> Result { + let bank = self + .resident_experts + .as_ref() + .ok_or(BindingError::Role("resident_expert_source_absent"))?; + if !Rc::ptr_eq(&bank.banks, &lease.banks) || lease.banks.len() != BANKS { + return Err(BindingError::Geometry("resident_expert_directory")); + } + let role = TensorRole::Layer { layer, role }; + let number = slot(role)?; + let resolved = self + .roles + .get(&role) + .ok_or(BindingError::Geometry("resident_expert_descriptor"))?; + bank.tensor(role, resolved)?; + let member = &lease.banks[number]; + self.shards[0] + .validate_retained_tensor(&member.tensor) + .map_err(BindingError::Io)?; + Ok(ResidentExpertBankMember { + descriptor: member.descriptor, + tensor: Rc::clone(&member.tensor), + }) + } +} +impl ResidentExpertBankSpan { + pub fn bytes(&self) -> &[u8] { + &self.member.bytes()[self.offset..self.offset + self.length] + } + pub fn offset(&self) -> usize { + self.offset + } + pub fn expert(&self) -> u32 { + self.expert + } + pub fn role(&self) -> TensorRole { + self.member.role() + } + pub fn raw_kind(&self) -> u32 { + self.member.raw_kind() + } + /// The bytes are a read-only shared mapping of the verified shard (the low-RAM source), so a read + /// may fault the page in from the file. + pub fn file_mapped(&self) -> bool { + self.member.file_mapped() + } + pub fn belongs_to(&self, member: &ResidentExpertBankMember) -> bool { + self.member.descriptor == member.descriptor + && Rc::ptr_eq(&self.member.tensor, &member.tensor) + } +} +impl ResidentExpertBank { + pub(in super::super) fn span( + &self, + role: TensorRole, + tensor: &ResolvedTensor, + expert: u32, + ) -> Result { + if expert >= 512 { + return Err(BindingError::Range("resident_expert")); + } + self.tensor(role, tensor)?; + let rows = if matches!( + role, + TensorRole::Layer { + role: LayerRole::FfnDownExperts, + .. + } + ) { + 2560 + } else { + 640 + }; + let (offset, length) = plan_stream_rows(tensor, role, 0, rows, Some(u64::from(expert)))?; + let offset = usize::try_from(offset).map_err(|_| BindingError::Range("resident_expert"))?; + let length = usize::try_from(length).map_err(|_| BindingError::Range("resident_expert"))?; + let bank = &self.banks[slot(role)?]; + if offset + .checked_add(length) + .is_none_or(|end| end > bank.tensor.retained_bytes().len()) + { + return Err(BindingError::Range("resident_expert")); + } + Ok(ResidentExpertBankSpan { + member: ResidentExpertBankMember { + descriptor: bank.descriptor, + tensor: Rc::clone(&bank.tensor), + }, + expert, + offset, + length, + }) + } +} diff --git a/crates/model-format/src/qwen4exp_expert_source_bank/retention_metadata_bytes.rs b/crates/model-format/src/qwen4exp_expert_source_bank/retention_metadata_bytes.rs new file mode 100644 index 00000000..6ee88a5f --- /dev/null +++ b/crates/model-format/src/qwen4exp_expert_source_bank/retention_metadata_bytes.rs @@ -0,0 +1,190 @@ +//! Moved out of the parent module by STRA-338: fn retention_metadata_bytes, impl fmt_Display_for, impl Error_for_ResidentExpertSourceError, fn checked_descriptor, fn slot, fn memory_available .... + +#[allow(unused_imports)] +use super::*; + +// Rc headers plus the small owners, never a second encoded payload allocation. +pub(super) fn retention_metadata_bytes() -> Result { + BANKS + .checked_mul(gguf::ResidentTensor::retention_metadata_bytes()) + .and_then(|n| n.checked_add(size_of::>() + 2 * size_of::())) + .ok_or(ResidentExpertSourceError::MemoryAdmission) +} +impl fmt::Display for ResidentExpertSourceError { + fn fmt(&self, out: &mut fmt::Formatter<'_>) -> fmt::Result { + write!(out, "resident expert source: {self:?}") + } +} +impl Error for ResidentExpertSourceError {} + +pub(super) fn checked_descriptor( + role: TensorRole, + tensor: &ResolvedTensor, +) -> Result { + use LayerRole as L; + let (columns, rows, kinds): (u64, u64, &[u32]) = match role { + TensorRole::Layer { + layer, + role: L::FfnGateExperts | L::FfnUpExperts, + } if layer < 48 => (2560, 640, &[18, 21, 22, 23]), + TensorRole::Layer { + layer, + role: L::FfnDownExperts, + } if layer < 48 => (640, 2560, &[20, 42]), + _ => return Err(ResidentExpertSourceError::Geometry), + }; + if tensor.shard != 0 + || tensor.dimensions != [columns, rows, 512] + || !kinds.contains(&tensor.kind) + { + return Err(ResidentExpertSourceError::Geometry); + } + let first = plan_stream_rows(tensor, role, 0, rows, Some(0)) + .map_err(|_| ResidentExpertSourceError::Geometry)?; + let last = plan_stream_rows(tensor, role, 0, rows, Some(511)) + .map_err(|_| ResidentExpertSourceError::Geometry)?; + if first.0 != 0 + || first.1 == 0 + || first.1.checked_mul(512) != Some(tensor.byte_length) + || Some(last.0) != first.1.checked_mul(511) + || last.1 != first.1 + || last.0.checked_add(last.1) != Some(tensor.byte_length) + { + return Err(ResidentExpertSourceError::Geometry); + } + Ok(BankDescriptor { + role, + tensor_number: tensor.tensor_number, + raw_kind: tensor.kind, + absolute_start: tensor.absolute_start, + file_size: tensor.file_size, + bytes: usize::try_from(tensor.byte_length) + .map_err(|_| ResidentExpertSourceError::Geometry)?, + }) +} +pub(super) fn slot(role: TensorRole) -> Result { + let (layer, role) = match role { + TensorRole::Layer { layer, role } if layer < 48 => (layer, role), + _ => return Err(BindingError::Role("resident_expert_role")), + }; + let role = match role { + LayerRole::FfnGateExperts => 0, + LayerRole::FfnUpExperts => 1, + LayerRole::FfnDownExperts => 2, + _ => return Err(BindingError::Role("resident_expert_role")), + }; + Ok(usize::from(layer) * 3 + role) +} +// Existing resident KAR and other owners are already reflected in MemAvailable. +// This is a snapshot, never an allocation reservation or a guarantee against races. +pub(super) fn memory_available() -> Result { + #[cfg(target_os = "linux")] + { + let mut text = String::new(); + File::open("/proc/meminfo") + .map_err(|_| ResidentExpertSourceError::MemoryAdmission)? + .take(65537) + .read_to_string(&mut text) + .map_err(|_| ResidentExpertSourceError::MemoryAdmission)?; + if text.len() > 65536 { + return Err(ResidentExpertSourceError::MemoryAdmission); + } + parse_memory_available(&text) + } + #[cfg(windows)] + { + let (total, available) = leleka_libc_shim::physical_memory().ok_or(ResidentExpertSourceError::MemoryAdmission)?; + parse_memory_available(&format!("MemTotal: {} kB +MemAvailable: {} kB +", total / 1024, available / 1024)) + } + #[cfg(not(any(target_os = "linux", windows)))] + { + Err(ResidentExpertSourceError::MemoryAdmission) + } +} +#[cfg(any(target_os = "linux", windows, test))] +pub(super) fn parse_memory_available(text: &str) -> Result { + let mut available = None; + let mut total = None; + for line in text.lines() { + let mut parts = line.split_ascii_whitespace(); + let Some(key) = parts.next() else { continue }; + let destination = match key { + "MemAvailable:" => &mut available, + "MemTotal:" => &mut total, + _ => continue, + }; + if destination.is_some() { + return Err(ResidentExpertSourceError::MemoryAdmission); + } + let value = parts + .next() + .ok_or(ResidentExpertSourceError::MemoryAdmission)? + .parse::() + .map_err(|_| ResidentExpertSourceError::MemoryAdmission)?; + if parts.next() != Some("kB") || parts.next().is_some() { + return Err(ResidentExpertSourceError::MemoryAdmission); + } + *destination = Some( + value + .checked_mul(1024) + .ok_or(ResidentExpertSourceError::MemoryAdmission)?, + ); + } + let available = available.ok_or(ResidentExpertSourceError::MemoryAdmission)?; + let total = total.ok_or(ResidentExpertSourceError::MemoryAdmission)?; + if total == 0 || available > total { + return Err(ResidentExpertSourceError::MemoryAdmission); + } + Ok(available) +} +pub(super) fn admit(capacity: usize, available: usize) -> Result<(), ResidentExpertSourceError> { + if capacity as u64 > SOURCE_CAP + || (capacity as u64) + .checked_add(FUTURE_HEADROOM) + .is_none_or(|n| n > available as u64) + { + return Err(ResidentExpertSourceError::MemoryAdmission); + } + Ok(()) +} + +#[cfg(test)] +pub(crate) fn test_resident_source_memory_admission( + text: &str, + capacity: usize, +) -> Result<(), ResidentExpertSourceError> { + admit(capacity, parse_memory_available(text)?) +} +impl ResidentExpertBank { + pub(in super::super) fn note_copy(&self, bytes: usize) { + self.copied_spans + .set(self.copied_spans.get().saturating_add(1)); + self.copied_bytes + .set(self.copied_bytes.get().saturating_add(bytes as u64)); + } + pub(super) fn report(&self) -> ResidentExpertSourceReport { + ResidentExpertSourceReport { + copied_spans: self.copied_spans.get(), + copied_bytes: self.copied_bytes.get(), + ..self.report + } + } + pub(in super::super) fn tensor( + &self, + role: TensorRole, + tensor: &ResolvedTensor, + ) -> Result<&gguf::ResidentTensor, BindingError> { + let descriptor = checked_descriptor(role, tensor) + .map_err(|_| BindingError::Geometry("resident_expert_descriptor"))?; + let bank = self + .banks + .get(slot(role)?) + .ok_or(BindingError::Geometry("resident_expert_directory"))?; + if bank.descriptor != descriptor || bank.tensor.len() != descriptor.bytes { + return Err(BindingError::Geometry("resident_expert_descriptor")); + } + Ok(&bank.tensor) + } +} diff --git a/crates/npu-service/src/engine.rs b/crates/npu-service/src/engine.rs index 9d8afd7c..28caa39c 100644 --- a/crates/npu-service/src/engine.rs +++ b/crates/npu-service/src/engine.rs @@ -61,52 +61,6 @@ struct Matrix<'a> { bytes: &'a [u8], } -impl Weights { - fn matrix(&self, name: &str, expert: Option) -> Result, String> { - let info = self - .gguf - .tensor(name) - .ok_or_else(|| format!("the model has no tensor {name}"))?; - let format = match info.tensor_type { - TensorType::Q8_0 => Format::Q8_0, - TensorType::Mxfp4 => Format::Mxfp4, - other => { - return Err(format!( - "{name} is {other:?}; only Q8_0 and MXFP4 weights are supported" - )); - } - }; - let k = *info.dims.first().ok_or("a tensor without dimensions")? as usize; - if !k.is_multiple_of(GROUP) { - return Err(format!("{name} has {k} columns, not a multiple of {GROUP}")); - } - let row_bytes = k / GROUP * format.block_bytes(); - let total_rows = info.dims[1..].iter().product::() as usize; - let (first, n) = match expert { - None => (0, total_rows), - Some(e) => { - if info.dims.len() != 3 || e >= info.dims[2] as usize { - return Err(format!("{name} has no expert {e}")); - } - let per = info.dims[1] as usize; - (e * per, per) - } - }; - let start = self.gguf.absolute_offset(info) as usize + first * row_bytes; - let bytes = self - .map - .as_bytes() - .get(start..start + n * row_bytes) - .ok_or_else(|| format!("{name} lies outside the model file"))?; - Ok(Matrix { - format, - n, - k, - bytes, - }) - } -} - struct Slot { request: Request, x: Tensor, @@ -138,84 +92,6 @@ struct Runtime { pairs: Vec, } -fn ov_error(e: leleka_openvino::Error) -> String { - e.to_string() -} - -impl Runtime { - fn make_slot(&self, key: Key) -> Result { - let (k, n, bucket) = key; - let g = k / GROUP; - let mut request = self.graphs[&key].request().map_err(ov_error)?; - let x = - Tensor::new(&self.ov, Element::F16, &[bucket as i64, k as i64]).map_err(ov_error)?; - let w = Tensor::new(&self.ov, Element::I8, &[n as i64, g as i64, GROUP as i64]) - .map_err(ov_error)?; - let s = Tensor::new(&self.ov, Element::F16, &[n as i64, g as i64, 1]).map_err(ov_error)?; - request.set_input(0, &x).map_err(ov_error)?; - request.set_input(1, &w).map_err(ov_error)?; - request.set_input(2, &s).map_err(ov_error)?; - Ok(Slot { - request, - x, - w, - s, - loaded: None, - shifts: Vec::new(), - }) - } - - /// The index of the slot pair for a shape, compiling the graph on first use. - fn pair(&mut self, key: Key) -> Result { - if let Some(i) = self.index.get(&key) { - return Ok(*i); - } - if !self.graphs.contains_key(&key) { - let (xml, bin) = graph::matmul_ir(key.2, key.0, key.1); - let compiled = self - .core - .compile(&self.device, &xml, &bin) - .map_err(ov_error)?; - self.graphs.insert(key, compiled); - } - let pair = Pair { - slots: [self.make_slot(key)?, self.make_slot(key)?], - next: 0, - }; - self.pairs.push(pair); - self.index.insert(key, self.pairs.len() - 1); - Ok(self.pairs.len() - 1) - } -} - -/// Two distinct elements of a slice, mutably. -fn two_mut(items: &mut [T], i: usize, j: usize) -> (&mut T, &mut T) { - assert_ne!(i, j); - if i < j { - let (a, b) = items.split_at_mut(j); - (&mut a[i], &mut b[0]) - } else { - let (a, b) = items.split_at_mut(i); - (&mut b[0], &mut a[j]) - } -} - -/// Expand `matrix` into the slot's weight and scale tensors and record what it holds. -fn load(slot: &mut Slot, matrix: &Matrix<'_>, id: (String, Option)) -> Result<(), String> { - expand::expand_parallel( - matrix.format, - matrix.bytes, - slot.w.bytes_mut().map_err(ov_error)?, - slot.s.bytes_mut().map_err(ov_error)?, - ); - slot.shifts = expand::normalize_scales(slot.s.bytes_mut().map_err(ov_error)?, matrix.n); - if slot.shifts.iter().all(|s| *s == 0) { - slot.shifts.clear(); - } - slot.loaded = Some(id); - Ok(()) -} - pub struct Engine { runtime: Runtime, weights: Weights, @@ -225,10 +101,6 @@ pub struct Engine { profile: Profile, } -fn io_error(what: &str, e: impl std::fmt::Display) -> String { - format!("{what}: {e}") -} - /// What a product needs resolved before it can run. struct Plan<'a> { bucket: usize, @@ -237,228 +109,6 @@ struct Plan<'a> { id: (String, Option), } -fn plan<'a>(weights: &'a Weights, p: &Product) -> Result, String> { - if p.rows == 0 { - return Err("a product needs at least one row".into()); - } - let bucket = Engine::bucket_for(p.rows).ok_or_else(|| { - format!( - "{} rows exceed the largest bucket {}", - p.rows, - BUCKETS[BUCKETS.len() - 1] - ) - })?; - let matrix = weights.matrix(&p.name, p.expert)?; - let key = (matrix.k, matrix.n, bucket); - Ok(Plan { - bucket, - matrix, - key, - id: (p.name.clone(), p.expert), - }) -} - -impl Engine { - pub fn new(options: &Options) -> Result { - let ov = OpenVino::load(&options.openvino_dll).map_err(ov_error)?; - let mut core = Core::new(&ov).map_err(ov_error)?; - if let Some(dir) = &options.cache_dir { - core = core.with_cache_dir(dir).map_err(ov_error)?; - } - let devices = core.devices().map_err(ov_error)?; - if !devices.contains(&options.device) { - return Err(format!( - "OpenVINO has no device {}; it offers {devices:?}", - options.device - )); - } - let device_name = core - .property(&options.device, "FULL_DEVICE_NAME") - .unwrap_or_default(); - let file = File::open(&options.model).map_err(|e| io_error("cannot open the model", e))?; - let size = file - .metadata() - .map_err(|e| io_error("cannot stat the model", e))? - .len(); - let gguf = Gguf::read(BufReader::with_capacity(1 << 20, file), size) - .map_err(|e| io_error("invalid GGUF", e))?; - let map = ReadMap::open(&options.model).map_err(|e| io_error("cannot map the model", e))?; - let shm = - Shared::open(&options.shm).map_err(|e| io_error("cannot map the shared region", e))?; - Ok(Self { - runtime: Runtime { - ov, - core, - device: options.device.clone(), - graphs: HashMap::new(), - index: HashMap::new(), - pairs: Vec::new(), - }, - weights: Weights { gguf, map }, - shm, - device_name, - scratch: Vec::new(), - profile: Profile::default(), - }) - } - - pub fn device_name(&self) -> &str { - &self.device_name - } - - /// The bucket for `rows`, if the graphs cover it. - pub fn bucket_for(rows: usize) -> Option { - BUCKETS.iter().copied().find(|b| *b >= rows) - } - - /// Run one product (see [`Engine::run_batch`]). - pub fn run(&mut self, p: &Product) -> Result { - self.run_batch(std::slice::from_ref(p)) - .pop() - .expect("one result per product") - } - - /// Run products one after another. Activations are read from and the result written to the shared region - /// as little-endian half floats: `rows * k` in, `rows * n` out (plus the scale shifts, if any, after it). - /// Knowing the next product, the weights it needs are expanded on a second thread while the device runs - /// the current one. - pub fn run_batch(&mut self, list: &[Product]) -> Vec> { - (0..list.len()).map(|i| self.run_at(list, i)).collect() - } - - fn run_at(&mut self, list: &[Product], i: usize) -> Result { - let started = Instant::now(); - let Self { - runtime, - weights, - shm, - scratch, - profile, - .. - } = self; - let p = &list[i]; - let cur = plan(weights, p)?; - let (n, k) = (cur.matrix.n, cur.matrix.k); - let (in_bytes, out_bytes) = (p.rows * k * 2, p.rows * n * 2); - - let mut buffer = std::mem::take(scratch); - buffer.resize(in_bytes.max(out_bytes), 0); - let lap = Instant::now(); - shm.read(p.in_offset, &mut buffer[..in_bytes]) - .map_err(|e| io_error("reading the activations", e))?; - profile.read_in += lap.elapsed(); - - // pairs for this product and the next one (compiling graphs the first time) - let lap = Instant::now(); - let ci = runtime.pair(cur.key)?; - let next = list.get(i + 1).and_then(|np| plan(weights, np).ok()); - let ni = match &next { - Some(nx) => runtime.pair(nx.key).ok(), - None => None, - }; - profile.compile += lap.elapsed(); - - // the slot for this product, expanding synchronously if nobody prefetched it - let lap = Instant::now(); - let idx = { - let pair = &mut runtime.pairs[ci]; - let found = (0..2).find(|s| pair.slots[*s].loaded.as_ref() == Some(&cur.id)); - let idx = match found { - Some(s) => s, - None => { - let s = pair.next; - load(&mut pair.slots[s], &cur.matrix, cur.id.clone())?; - s - } - }; - pair.next = 1 - idx; - idx - }; - profile.expand += lap.elapsed(); - - // borrow the current slot and, if there is a next product to prepare, its target slot - let (slot, target): (&mut Slot, Option<(&mut Slot, &Plan<'_>)>) = match (ni, &next) { - (Some(ni), Some(nx)) if ni == ci => { - let [a, b] = &mut runtime.pairs[ci].slots; - let (cur_slot, other) = if idx == 0 { (a, b) } else { (b, a) }; - let wanted = other.loaded.as_ref() != Some(&nx.id); - (cur_slot, wanted.then_some((other, nx))) - } - (Some(ni), Some(nx)) => { - let (a, b) = two_mut(&mut runtime.pairs, ci, ni); - let hit = (0..2).find(|s| b.slots[*s].loaded.as_ref() == Some(&nx.id)); - let target = if hit.is_some() { - None - } else { - let t = b.next; - b.next = 1 - t; - Some((&mut b.slots[t], nx)) - }; - (&mut a.slots[idx], target) - } - _ => (&mut runtime.pairs[ci].slots[idx], None), - }; - - let lap = Instant::now(); - let outcome: Result = std::thread::scope(|scope| { - let prefetch = target.map(|(tgt, nx)| { - scope.spawn(move || { - // a failed prefetch leaves the slot unloaded; the product then loads it itself and - // reports the error - let _ = load(tgt, &nx.matrix, nx.id.clone()); - }) - }); - let result = (|| { - slot.x.write(0, &buffer[..in_bytes]).map_err(ov_error)?; - slot.x.bytes_mut().map_err(ov_error)?[in_bytes..].fill(0); - slot.request.infer().map_err(ov_error)?; - slot.request - .output(0) - .map_err(ov_error)? - .read(0, &mut buffer[..out_bytes]) - .map_err(ov_error)?; - shm.write(p.out_offset, &buffer[..out_bytes]) - .map_err(|e| io_error("writing the result", e))?; - let shifted = !slot.shifts.is_empty(); - if shifted { - shm.write(p.out_offset + out_bytes, &slot.shifts) - .map_err(|e| io_error("writing the scale shifts", e))?; - } - Ok(Done { - micros: 0, - bucket: cur.bucket, - shifted, - }) - })(); - if let Some(handle) = prefetch { - let _ = handle.join(); - } - result - }); - profile.infer += lap.elapsed(); - *scratch = buffer; - profile.calls += 1; - outcome.map(|mut done| { - done.micros = started.elapsed().as_micros() as u64; - done - }) - } - - /// Where the time of all products so far went, one line. - pub fn profile_report(&self) -> String { - let p = &self.profile; - let ms = |d: Duration| d.as_secs_f64() * 1e3; - format!( - "{} products: read activations {:.0} ms | slots/compile {:.0} | expand weights (not prefetched) {:.0} | run on the device incl. prefetch {:.0}", - p.calls, - ms(p.read_in), - ms(p.compile), - ms(p.expand), - ms(p.infer), - ) - } -} - /// Time spent in each phase of `Engine::run_batch`, summed over products. #[derive(Default)] struct Profile { @@ -468,3 +118,10 @@ struct Profile { expand: Duration, infer: Duration, } + +mod impl_weights; +#[allow(unused_imports)] +pub use impl_weights::*; +mod impl_engine; +#[allow(unused_imports)] +pub use impl_engine::*; diff --git a/crates/npu-service/src/engine/impl_engine.rs b/crates/npu-service/src/engine/impl_engine.rs new file mode 100644 index 00000000..30597557 --- /dev/null +++ b/crates/npu-service/src/engine/impl_engine.rs @@ -0,0 +1,206 @@ +//! Moved out of the parent module by STRA-338: impl Engine. + +#[allow(unused_imports)] +use super::*; + + +impl Engine { + pub fn new(options: &Options) -> Result { + let ov = OpenVino::load(&options.openvino_dll).map_err(ov_error)?; + let mut core = Core::new(&ov).map_err(ov_error)?; + if let Some(dir) = &options.cache_dir { + core = core.with_cache_dir(dir).map_err(ov_error)?; + } + let devices = core.devices().map_err(ov_error)?; + if !devices.contains(&options.device) { + return Err(format!( + "OpenVINO has no device {}; it offers {devices:?}", + options.device + )); + } + let device_name = core + .property(&options.device, "FULL_DEVICE_NAME") + .unwrap_or_default(); + let file = File::open(&options.model).map_err(|e| io_error("cannot open the model", e))?; + let size = file + .metadata() + .map_err(|e| io_error("cannot stat the model", e))? + .len(); + let gguf = Gguf::read(BufReader::with_capacity(1 << 20, file), size) + .map_err(|e| io_error("invalid GGUF", e))?; + let map = ReadMap::open(&options.model).map_err(|e| io_error("cannot map the model", e))?; + let shm = + Shared::open(&options.shm).map_err(|e| io_error("cannot map the shared region", e))?; + Ok(Self { + runtime: Runtime { + ov, + core, + device: options.device.clone(), + graphs: HashMap::new(), + index: HashMap::new(), + pairs: Vec::new(), + }, + weights: Weights { gguf, map }, + shm, + device_name, + scratch: Vec::new(), + profile: Profile::default(), + }) + } + + pub fn device_name(&self) -> &str { + &self.device_name + } + + /// The bucket for `rows`, if the graphs cover it. + pub fn bucket_for(rows: usize) -> Option { + BUCKETS.iter().copied().find(|b| *b >= rows) + } + + /// Run one product (see [`Engine::run_batch`]). + pub fn run(&mut self, p: &Product) -> Result { + self.run_batch(std::slice::from_ref(p)) + .pop() + .expect("one result per product") + } + + /// Run products one after another. Activations are read from and the result written to the shared region + /// as little-endian half floats: `rows * k` in, `rows * n` out (plus the scale shifts, if any, after it). + /// Knowing the next product, the weights it needs are expanded on a second thread while the device runs + /// the current one. + pub fn run_batch(&mut self, list: &[Product]) -> Vec> { + (0..list.len()).map(|i| self.run_at(list, i)).collect() + } + + pub(super) fn run_at(&mut self, list: &[Product], i: usize) -> Result { + let started = Instant::now(); + let Self { + runtime, + weights, + shm, + scratch, + profile, + .. + } = self; + let p = &list[i]; + let cur = plan(weights, p)?; + let (n, k) = (cur.matrix.n, cur.matrix.k); + let (in_bytes, out_bytes) = (p.rows * k * 2, p.rows * n * 2); + + let mut buffer = std::mem::take(scratch); + buffer.resize(in_bytes.max(out_bytes), 0); + let lap = Instant::now(); + shm.read(p.in_offset, &mut buffer[..in_bytes]) + .map_err(|e| io_error("reading the activations", e))?; + profile.read_in += lap.elapsed(); + + // pairs for this product and the next one (compiling graphs the first time) + let lap = Instant::now(); + let ci = runtime.pair(cur.key)?; + let next = list.get(i + 1).and_then(|np| plan(weights, np).ok()); + let ni = match &next { + Some(nx) => runtime.pair(nx.key).ok(), + None => None, + }; + profile.compile += lap.elapsed(); + + // the slot for this product, expanding synchronously if nobody prefetched it + let lap = Instant::now(); + let idx = { + let pair = &mut runtime.pairs[ci]; + let found = (0..2).find(|s| pair.slots[*s].loaded.as_ref() == Some(&cur.id)); + let idx = match found { + Some(s) => s, + None => { + let s = pair.next; + load(&mut pair.slots[s], &cur.matrix, cur.id.clone())?; + s + } + }; + pair.next = 1 - idx; + idx + }; + profile.expand += lap.elapsed(); + + // borrow the current slot and, if there is a next product to prepare, its target slot + let (slot, target): (&mut Slot, Option<(&mut Slot, &Plan<'_>)>) = match (ni, &next) { + (Some(ni), Some(nx)) if ni == ci => { + let [a, b] = &mut runtime.pairs[ci].slots; + let (cur_slot, other) = if idx == 0 { (a, b) } else { (b, a) }; + let wanted = other.loaded.as_ref() != Some(&nx.id); + (cur_slot, wanted.then_some((other, nx))) + } + (Some(ni), Some(nx)) => { + let (a, b) = two_mut(&mut runtime.pairs, ci, ni); + let hit = (0..2).find(|s| b.slots[*s].loaded.as_ref() == Some(&nx.id)); + let target = if hit.is_some() { + None + } else { + let t = b.next; + b.next = 1 - t; + Some((&mut b.slots[t], nx)) + }; + (&mut a.slots[idx], target) + } + _ => (&mut runtime.pairs[ci].slots[idx], None), + }; + + let lap = Instant::now(); + let outcome: Result = std::thread::scope(|scope| { + let prefetch = target.map(|(tgt, nx)| { + scope.spawn(move || { + // a failed prefetch leaves the slot unloaded; the product then loads it itself and + // reports the error + let _ = load(tgt, &nx.matrix, nx.id.clone()); + }) + }); + let result = (|| { + slot.x.write(0, &buffer[..in_bytes]).map_err(ov_error)?; + slot.x.bytes_mut().map_err(ov_error)?[in_bytes..].fill(0); + slot.request.infer().map_err(ov_error)?; + slot.request + .output(0) + .map_err(ov_error)? + .read(0, &mut buffer[..out_bytes]) + .map_err(ov_error)?; + shm.write(p.out_offset, &buffer[..out_bytes]) + .map_err(|e| io_error("writing the result", e))?; + let shifted = !slot.shifts.is_empty(); + if shifted { + shm.write(p.out_offset + out_bytes, &slot.shifts) + .map_err(|e| io_error("writing the scale shifts", e))?; + } + Ok(Done { + micros: 0, + bucket: cur.bucket, + shifted, + }) + })(); + if let Some(handle) = prefetch { + let _ = handle.join(); + } + result + }); + profile.infer += lap.elapsed(); + *scratch = buffer; + profile.calls += 1; + outcome.map(|mut done| { + done.micros = started.elapsed().as_micros() as u64; + done + }) + } + + /// Where the time of all products so far went, one line. + pub fn profile_report(&self) -> String { + let p = &self.profile; + let ms = |d: Duration| d.as_secs_f64() * 1e3; + format!( + "{} products: read activations {:.0} ms | slots/compile {:.0} | expand weights (not prefetched) {:.0} | run on the device incl. prefetch {:.0}", + p.calls, + ms(p.read_in), + ms(p.compile), + ms(p.expand), + ms(p.infer), + ) + } +} diff --git a/crates/npu-service/src/engine/impl_weights.rs b/crates/npu-service/src/engine/impl_weights.rs new file mode 100644 index 00000000..add371ee --- /dev/null +++ b/crates/npu-service/src/engine/impl_weights.rs @@ -0,0 +1,154 @@ +//! Moved out of the parent module by STRA-338: impl Weights, fn ov_error, impl Runtime, fn two_mut, fn load, fn io_error .... + +#[allow(unused_imports)] +use super::*; + + +impl Weights { + pub(super) fn matrix(&self, name: &str, expert: Option) -> Result, String> { + let info = self + .gguf + .tensor(name) + .ok_or_else(|| format!("the model has no tensor {name}"))?; + let format = match info.tensor_type { + TensorType::Q8_0 => Format::Q8_0, + TensorType::Mxfp4 => Format::Mxfp4, + other => { + return Err(format!( + "{name} is {other:?}; only Q8_0 and MXFP4 weights are supported" + )); + } + }; + let k = *info.dims.first().ok_or("a tensor without dimensions")? as usize; + if !k.is_multiple_of(GROUP) { + return Err(format!("{name} has {k} columns, not a multiple of {GROUP}")); + } + let row_bytes = k / GROUP * format.block_bytes(); + let total_rows = info.dims[1..].iter().product::() as usize; + let (first, n) = match expert { + None => (0, total_rows), + Some(e) => { + if info.dims.len() != 3 || e >= info.dims[2] as usize { + return Err(format!("{name} has no expert {e}")); + } + let per = info.dims[1] as usize; + (e * per, per) + } + }; + let start = self.gguf.absolute_offset(info) as usize + first * row_bytes; + let bytes = self + .map + .as_bytes() + .get(start..start + n * row_bytes) + .ok_or_else(|| format!("{name} lies outside the model file"))?; + Ok(Matrix { + format, + n, + k, + bytes, + }) + } +} + +pub(super) fn ov_error(e: leleka_openvino::Error) -> String { + e.to_string() +} + +impl Runtime { + pub(super) fn make_slot(&self, key: Key) -> Result { + let (k, n, bucket) = key; + let g = k / GROUP; + let mut request = self.graphs[&key].request().map_err(ov_error)?; + let x = + Tensor::new(&self.ov, Element::F16, &[bucket as i64, k as i64]).map_err(ov_error)?; + let w = Tensor::new(&self.ov, Element::I8, &[n as i64, g as i64, GROUP as i64]) + .map_err(ov_error)?; + let s = Tensor::new(&self.ov, Element::F16, &[n as i64, g as i64, 1]).map_err(ov_error)?; + request.set_input(0, &x).map_err(ov_error)?; + request.set_input(1, &w).map_err(ov_error)?; + request.set_input(2, &s).map_err(ov_error)?; + Ok(Slot { + request, + x, + w, + s, + loaded: None, + shifts: Vec::new(), + }) + } + + /// The index of the slot pair for a shape, compiling the graph on first use. + pub(super) fn pair(&mut self, key: Key) -> Result { + if let Some(i) = self.index.get(&key) { + return Ok(*i); + } + if !self.graphs.contains_key(&key) { + let (xml, bin) = graph::matmul_ir(key.2, key.0, key.1); + let compiled = self + .core + .compile(&self.device, &xml, &bin) + .map_err(ov_error)?; + self.graphs.insert(key, compiled); + } + let pair = Pair { + slots: [self.make_slot(key)?, self.make_slot(key)?], + next: 0, + }; + self.pairs.push(pair); + self.index.insert(key, self.pairs.len() - 1); + Ok(self.pairs.len() - 1) + } +} + +/// Two distinct elements of a slice, mutably. +pub(super) fn two_mut(items: &mut [T], i: usize, j: usize) -> (&mut T, &mut T) { + assert_ne!(i, j); + if i < j { + let (a, b) = items.split_at_mut(j); + (&mut a[i], &mut b[0]) + } else { + let (a, b) = items.split_at_mut(i); + (&mut b[0], &mut a[j]) + } +} + +/// Expand `matrix` into the slot's weight and scale tensors and record what it holds. +pub(super) fn load(slot: &mut Slot, matrix: &Matrix<'_>, id: (String, Option)) -> Result<(), String> { + expand::expand_parallel( + matrix.format, + matrix.bytes, + slot.w.bytes_mut().map_err(ov_error)?, + slot.s.bytes_mut().map_err(ov_error)?, + ); + slot.shifts = expand::normalize_scales(slot.s.bytes_mut().map_err(ov_error)?, matrix.n); + if slot.shifts.iter().all(|s| *s == 0) { + slot.shifts.clear(); + } + slot.loaded = Some(id); + Ok(()) +} + +pub(super) fn io_error(what: &str, e: impl std::fmt::Display) -> String { + format!("{what}: {e}") +} + +pub(super) fn plan<'a>(weights: &'a Weights, p: &Product) -> Result, String> { + if p.rows == 0 { + return Err("a product needs at least one row".into()); + } + let bucket = Engine::bucket_for(p.rows).ok_or_else(|| { + format!( + "{} rows exceed the largest bucket {}", + p.rows, + BUCKETS[BUCKETS.len() - 1] + ) + })?; + let matrix = weights.matrix(&p.name, p.expert)?; + let key = (matrix.k, matrix.n, bucket); + Ok(Plan { + bucket, + matrix, + key, + id: (p.name.clone(), p.expert), + }) +} diff --git a/crates/runtime-client/src/backend.rs b/crates/runtime-client/src/backend.rs index ff22fa64..7c1efe07 100644 --- a/crates/runtime-client/src/backend.rs +++ b/crates/runtime-client/src/backend.rs @@ -26,19 +26,6 @@ use crate::{ convert, proto, }; -/// A failed call to the runtime, as one structured warning (rate limited per event by the log layer): the gRPC code and -/// the runtime's own short reason, never request content. -fn log_status(event: &str, status: &tonic::Status) { - leleka_obs::warn( - "runtime-client", - event, - &[ - ("code", format!("{:?}", status.code()).as_str().into()), - ("reason", status.message().into()), - ], - ); -} - pub struct GrpcBackend { runtime: Handle, address: SocketAddr, @@ -67,403 +54,12 @@ struct ActiveRequest { epoch: String, } -fn error(code: api::ErrorCode, message: impl Into, retryable: bool) -> api::BackendError { - api::BackendError { - code, - message: message.into(), - retryable, - } -} - -/// A transport or protocol failure is `BackendUnavailable` (the caller attaches again); a refusal -/// that proves nothing was accepted keeps its meaning. -fn from_status(status: &tonic::Status) -> api::BackendError { - let proven_unaccepted = status - .metadata() - .get("x-leleka-accepted") - .and_then(|v| v.to_str().ok()) - == Some("false"); - let (code, retryable) = match status.code() { - Code::InvalidArgument => (api::ErrorCode::InvalidRequest, false), - Code::FailedPrecondition => (api::ErrorCode::UnsupportedModel, false), - Code::ResourceExhausted => (api::ErrorCode::ResourceExhausted, proven_unaccepted), - Code::Unauthenticated | Code::PermissionDenied => (api::ErrorCode::Internal, false), - Code::Unavailable | Code::DeadlineExceeded | Code::Cancelled | Code::DataLoss => { - (api::ErrorCode::BackendUnavailable, false) - } - _ => (api::ErrorCode::Internal, false), - }; - error( - code, - format!("runtime: {} ({:?})", status.message(), status.code()), - retryable, - ) -} - -impl GrpcBackend { - pub fn new(runtime: Handle, address: SocketAddr, token: String) -> Self { - Self { - runtime, - address, - token, - client: None, - attached: None, - active: Arc::new(Mutex::new(None)), - prefix_summary: Mutex::new(None), - memory_report: Mutex::new(None), - telemetry_report: Mutex::new(None), - } - } - - /// The current runtime snapshot, connecting first if needed. A failure forgets the connection - /// so the next call connects again. - fn snapshot(&mut self) -> Result { - if self.client.is_none() { - let (address, token) = (self.address, self.token.clone()); - let client = match self - .runtime - .block_on(RuntimeClient::connect(address, token)) - { - Ok(client) => client, - Err(status) => { - log_status("connect_failed", &status); - return Err(from_status(&status)); - } - }; - leleka_obs::info( - "runtime-client", - "connected", - &[("engine", address.to_string().as_str().into())], - ); - self.client = Some(client); - } - let client = self.client.as_mut().expect("client was just set"); - match self.runtime.block_on(client.snapshot()) { - Ok(snapshot) => Ok(snapshot), - Err(status) => { - self.client = None; - log_status("snapshot_failed", &status); - Err(from_status(&status)) - } - } - } -} - -impl api::Backend for GrpcBackend { - fn identity(&self) -> api::BackendIdentity { - api::BackendIdentity { - name: "leleka-runtime-grpc".into(), - implementation_version: env!("CARGO_PKG_VERSION").into(), - api_version: api::BACKEND_API_VERSION, - } - } - - /// What the runtime advertises right now: re-read on every call (a health probe), empty when - /// it is unreachable, has no model loaded, or has restarted since the attach. - fn capabilities(&self) -> api::BackendCapabilities { - // `capabilities` takes `&self` by contract; the probe needs a connection of its own. - let (address, token) = (self.address, self.token.clone()); - let attached = self.attached.clone(); - let existing = self.client.clone(); - let probe = self.runtime.block_on(async move { - let mut client = match existing { - Some(client) => client, - None => match RuntimeClient::connect(address, token).await { - Ok(client) => client, - Err(status) => { - log_status("probe_failed", &status); - return None; - } - }, - }; - match client.snapshot().await { - Ok(snapshot) => Some(snapshot), - Err(status) => { - log_status("probe_failed", &status); - None - } - } - }); - // the probe is one snapshot read per health tick: keep its prefix-cache summary for `prefix_cache_summary` - if let Ok(mut cell) = self.memory_report.lock() { - // memory pressure matters before and without a loaded model: no epoch/ready condition, only a non-empty report - *cell = probe - .as_ref() - .filter(|snapshot| !snapshot.memory_json.is_empty()) - .map(|snapshot| snapshot.memory_json.clone()); - } - if let Ok(mut cell) = self.telemetry_report.lock() { - *cell = probe - .as_ref() - .filter(|snapshot| !snapshot.telemetry_json.is_empty()) - .map(|snapshot| snapshot.telemetry_json.clone()); - } - if let Ok(mut cell) = self.prefix_summary.lock() { - *cell = probe - .as_ref() - .filter(|snapshot| { - snapshot.model_ready - && !snapshot.prefix_cache_json.is_empty() - && attached.as_ref().is_some_and(|a| a.epoch == snapshot.epoch) - }) - .map(|snapshot| snapshot.prefix_cache_json.clone()); - } - match (probe, attached) { - (Some(snapshot), Some(attached)) - if snapshot.model_ready - && snapshot.epoch == attached.epoch - && snapshot - .loaded - .as_ref() - .is_some_and(|l| l.handle == attached.handle) => - { - snapshot - .capabilities - .as_ref() - .map(convert::capabilities_from_proto) - .unwrap_or_default() - } - _ => api::BackendCapabilities::default(), - } - } - - /// The runtime's prefix-cache summary as of the last `capabilities` probe (one health tick old at most); `None` when the - /// runtime is unreachable, restarted since the attach, or has no such cache. - fn prefix_cache_summary(&self) -> Option { - self.prefix_summary - .lock() - .ok() - .and_then(|cell| cell.clone()) - } - - /// The runtime's memory-governor report as of the last `capabilities` probe; `None` when unreachable or it has none. - fn memory_report(&self) -> Option { - self.memory_report.lock().ok().and_then(|cell| cell.clone()) - } - - /// The runtime's telemetry document as of the last `capabilities` probe; `None` when unreachable or it has none. - fn telemetry_report(&self) -> Option { - self.telemetry_report - .lock() - .ok() - .and_then(|cell| cell.clone()) - } - - fn load( - &mut self, - model: api::ModelDescriptor, - config: api::RuntimeConfig, - ) -> Result { - self.attached = None; - let snapshot = self.snapshot()?; - let loaded = match snapshot.loaded.as_ref().filter(|_| snapshot.model_ready) { - Some(loaded) => convert::loaded_from_proto(loaded).map_err(|s| from_status(&s))?, - None => { - return Err(error( - api::ErrorCode::BackendUnavailable, - "the runtime has no model loaded; load it with leleka-cli", - true, - )); - } - }; - loaded.validate_for_load(&model, &config).map_err(|_| { - error( - api::ErrorCode::UnsupportedModel, - "the runtime's loaded model, load configuration or mode is not the one expected", - false, - ) - })?; - self.attached = Some(Attached { - epoch: snapshot.epoch, - handle: loaded.handle.clone(), - }); - Ok(loaded) - } - - fn start_generation( - &mut self, - model: &api::LoadedModel, - request: api::GenerationRequest, - ) -> Result { - let attached = self.attached.clone().ok_or_else(|| { - error( - api::ErrorCode::BackendUnavailable, - "not attached to a loaded model", - true, - ) - })?; - if attached.handle != model.handle { - return Err(error( - api::ErrorCode::BackendUnavailable, - "stale model handle", - true, - )); - } - // Fresh identity check: the runtime may have restarted since the last call. - let snapshot = match self.snapshot() { - Ok(snapshot) => snapshot, - Err(error) => { - self.attached = None; - return Err(error); - } - }; - let still = snapshot - .loaded - .as_ref() - .is_some_and(|l| l.handle == attached.handle); - if snapshot.epoch != attached.epoch || !snapshot.model_ready || !still { - self.attached = None; - return Err(error( - api::ErrorCode::BackendUnavailable, - "the runtime restarted or unloaded the model", - true, - )); - } - let mut wire = proto::GenerateRequest { - request_id: request.request_id.clone(), - expected_epoch: attached.epoch.clone(), - handle: attached.handle.clone(), - ..Default::default() - }; - convert::apply_generation_request(&mut wire, &request); - let client = self.client.as_mut().expect("snapshot connected the client"); - let generation = self - .runtime - .block_on(client.generate(wire)) - .map_err(|status| { - log_status("generate_failed", &status); - from_status(&status) - })?; - *self.active.lock().expect("active lock") = Some(ActiveRequest { - id: request.request_id, - epoch: attached.epoch, - }); - let (sink, stream) = api::GenerationSink::channel(); - let active = Arc::clone(&self.active); - self.runtime.spawn(pump(generation, sink, active)); - Ok(stream) - } - - fn cancel(&mut self, request_id: &str) -> Result<(), api::BackendError> { - let active = self.active.lock().expect("active lock").clone(); - let Some(active) = active.filter(|a| a.id == request_id) else { - return Err(error( - api::ErrorCode::InvalidRequest, - "generation is not active", - false, - )); - }; - let Some(client) = self.client.as_mut() else { - return Err(error( - api::ErrorCode::BackendUnavailable, - "not connected", - true, - )); - }; - self.runtime - .block_on(client.cancel(proto::CancelRequest { - request_id: active.id, - expected_epoch: active.epoch, - })) - .map(|_| ()) - .map_err(|status| from_status(&status)) - } - - fn reconfigure(&mut self, settings_json: &str) -> Result { - let Some(attached) = self.attached.clone() else { - return Err(error( - api::ErrorCode::BackendUnavailable, - "no model is attached", - true, - )); - }; - let Some(client) = self.client.as_mut() else { - return Err(error( - api::ErrorCode::BackendUnavailable, - "not connected", - true, - )); - }; - let reply = self - .runtime - .block_on(client.reconfigure(proto::ReconfigureRequest { - operation_id: String::new(), - expected_epoch: attached.epoch, - settings_json: settings_json.to_owned(), - })) - .map_err(|status| from_status(&status))?; - if reply.ok { - return Ok(reply.effective_json); - } - let code = match reply.error_code.as_str() { - "invalid" => api::ErrorCode::InvalidRequest, - "unsupported" => api::ErrorCode::UnsupportedModel, - "exhausted" => api::ErrorCode::ResourceExhausted, - "unavailable" => api::ErrorCode::BackendUnavailable, - _ => api::ErrorCode::Internal, - }; - Err(api::BackendError { - code, - message: reply.error, - retryable: reply.retryable, - }) - } - - fn unload(&mut self, _: api::LoadedModel) -> Result<(), api::BackendError> { - Err(error( - api::ErrorCode::InvalidRequest, - "this backend only attaches to a loaded runtime; unload it with leleka-cli", - false, - )) - } -} - -/// Completes when the consumer dropped its stream. -async fn consumer_gone(sink: &api::GenerationSink) { - while !sink.is_closed() { - tokio::time::sleep(std::time::Duration::from_millis(50)).await; - } -} - -/// Forward frames to the consumer. A transport failure or a malformed frame ends the stream -/// *without* a terminal event, which the consumer reports as a lost engine; dropping `generation` -/// afterwards asks the runtime to cancel the request. -async fn pump( - mut generation: RuntimeGeneration, - sink: api::GenerationSink, - active: Arc>>, -) { - let clear = |active: &Arc>>| { - *active.lock().expect("active lock") = None; - }; - loop { - // A consumer that dropped the stream is a cancellation the runtime must hear about. - if sink.is_closed() { - break; // dropping `generation` below sends the Cancel - } - let frame = tokio::select! { - frame = generation.message() => match frame { - Ok(Some(frame)) => frame, - Ok(None) | Err(_) => break, - }, - // The consumer can go away while the runtime is silent (a long prefill). - () = consumer_gone(&sink) => break, - }; - let Some(payload) = frame.payload else { break }; - if matches!(payload, proto::generation_frame::Payload::Accepted(_)) { - continue; - } - let Ok(event) = convert::event_from_proto(payload) else { - break; - }; - let terminal = matches!(event, api::GenerationEvent::Terminal(_)); - // Release the active slot before the terminal is visible, so the next generation can start. - if terminal { - clear(&active); - } - if sink.emit(event).is_err() || terminal { - return; - } - } - clear(&active); -} +mod log_status; +#[allow(unused_imports)] +pub use log_status::*; +mod impl_api_backend_for; +#[allow(unused_imports)] +pub use impl_api_backend_for::*; +mod consumer_gone; +#[allow(unused_imports)] +pub use consumer_gone::*; diff --git a/crates/runtime-client/src/backend/consumer_gone.rs b/crates/runtime-client/src/backend/consumer_gone.rs new file mode 100644 index 00000000..8569a7fe --- /dev/null +++ b/crates/runtime-client/src/backend/consumer_gone.rs @@ -0,0 +1,54 @@ +//! Moved out of the parent module by STRA-338: fn consumer_gone, fn pump. + +#[allow(unused_imports)] +use super::*; + +/// Completes when the consumer dropped its stream. +pub(super) async fn consumer_gone(sink: &api::GenerationSink) { + while !sink.is_closed() { + tokio::time::sleep(std::time::Duration::from_millis(50)).await; + } +} + +/// Forward frames to the consumer. A transport failure or a malformed frame ends the stream +/// *without* a terminal event, which the consumer reports as a lost engine; dropping `generation` +/// afterwards asks the runtime to cancel the request. +pub(super) async fn pump( + mut generation: RuntimeGeneration, + sink: api::GenerationSink, + active: Arc>>, +) { + let clear = |active: &Arc>>| { + *active.lock().expect("active lock") = None; + }; + loop { + // A consumer that dropped the stream is a cancellation the runtime must hear about. + if sink.is_closed() { + break; // dropping `generation` below sends the Cancel + } + let frame = tokio::select! { + frame = generation.message() => match frame { + Ok(Some(frame)) => frame, + Ok(None) | Err(_) => break, + }, + // The consumer can go away while the runtime is silent (a long prefill). + () = consumer_gone(&sink) => break, + }; + let Some(payload) = frame.payload else { break }; + if matches!(payload, proto::generation_frame::Payload::Accepted(_)) { + continue; + } + let Ok(event) = convert::event_from_proto(payload) else { + break; + }; + let terminal = matches!(event, api::GenerationEvent::Terminal(_)); + // Release the active slot before the terminal is visible, so the next generation can start. + if terminal { + clear(&active); + } + if sink.emit(event).is_err() || terminal { + return; + } + } + clear(&active); +} diff --git a/crates/runtime-client/src/backend/impl_api_backend_for.rs b/crates/runtime-client/src/backend/impl_api_backend_for.rs new file mode 100644 index 00000000..117162a6 --- /dev/null +++ b/crates/runtime-client/src/backend/impl_api_backend_for.rs @@ -0,0 +1,273 @@ +//! Moved out of the parent module by STRA-338: impl api_Backend_for. + +#[allow(unused_imports)] +use super::*; + +impl api::Backend for GrpcBackend { + fn identity(&self) -> api::BackendIdentity { + api::BackendIdentity { + name: "leleka-runtime-grpc".into(), + implementation_version: env!("CARGO_PKG_VERSION").into(), + api_version: api::BACKEND_API_VERSION, + } + } + + /// What the runtime advertises right now: re-read on every call (a health probe), empty when + /// it is unreachable, has no model loaded, or has restarted since the attach. + fn capabilities(&self) -> api::BackendCapabilities { + // `capabilities` takes `&self` by contract; the probe needs a connection of its own. + let (address, token) = (self.address, self.token.clone()); + let attached = self.attached.clone(); + let existing = self.client.clone(); + let probe = self.runtime.block_on(async move { + let mut client = match existing { + Some(client) => client, + None => match RuntimeClient::connect(address, token).await { + Ok(client) => client, + Err(status) => { + log_status("probe_failed", &status); + return None; + } + }, + }; + match client.snapshot().await { + Ok(snapshot) => Some(snapshot), + Err(status) => { + log_status("probe_failed", &status); + None + } + } + }); + // the probe is one snapshot read per health tick: keep its prefix-cache summary for `prefix_cache_summary` + if let Ok(mut cell) = self.memory_report.lock() { + // memory pressure matters before and without a loaded model: no epoch/ready condition, only a non-empty report + *cell = probe + .as_ref() + .filter(|snapshot| !snapshot.memory_json.is_empty()) + .map(|snapshot| snapshot.memory_json.clone()); + } + if let Ok(mut cell) = self.telemetry_report.lock() { + *cell = probe + .as_ref() + .filter(|snapshot| !snapshot.telemetry_json.is_empty()) + .map(|snapshot| snapshot.telemetry_json.clone()); + } + if let Ok(mut cell) = self.prefix_summary.lock() { + *cell = probe + .as_ref() + .filter(|snapshot| { + snapshot.model_ready + && !snapshot.prefix_cache_json.is_empty() + && attached.as_ref().is_some_and(|a| a.epoch == snapshot.epoch) + }) + .map(|snapshot| snapshot.prefix_cache_json.clone()); + } + match (probe, attached) { + (Some(snapshot), Some(attached)) + if snapshot.model_ready + && snapshot.epoch == attached.epoch + && snapshot + .loaded + .as_ref() + .is_some_and(|l| l.handle == attached.handle) => + { + snapshot + .capabilities + .as_ref() + .map(convert::capabilities_from_proto) + .unwrap_or_default() + } + _ => api::BackendCapabilities::default(), + } + } + + /// The runtime's prefix-cache summary as of the last `capabilities` probe (one health tick old at most); `None` when the + /// runtime is unreachable, restarted since the attach, or has no such cache. + fn prefix_cache_summary(&self) -> Option { + self.prefix_summary + .lock() + .ok() + .and_then(|cell| cell.clone()) + } + + /// The runtime's memory-governor report as of the last `capabilities` probe; `None` when unreachable or it has none. + fn memory_report(&self) -> Option { + self.memory_report.lock().ok().and_then(|cell| cell.clone()) + } + + /// The runtime's telemetry document as of the last `capabilities` probe; `None` when unreachable or it has none. + fn telemetry_report(&self) -> Option { + self.telemetry_report + .lock() + .ok() + .and_then(|cell| cell.clone()) + } + + fn load( + &mut self, + model: api::ModelDescriptor, + config: api::RuntimeConfig, + ) -> Result { + self.attached = None; + let snapshot = self.snapshot()?; + let loaded = match snapshot.loaded.as_ref().filter(|_| snapshot.model_ready) { + Some(loaded) => convert::loaded_from_proto(loaded).map_err(|s| from_status(&s))?, + None => { + return Err(error( + api::ErrorCode::BackendUnavailable, + "the runtime has no model loaded; load it with leleka-cli", + true, + )); + } + }; + loaded.validate_for_load(&model, &config).map_err(|_| { + error( + api::ErrorCode::UnsupportedModel, + "the runtime's loaded model, load configuration or mode is not the one expected", + false, + ) + })?; + self.attached = Some(Attached { + epoch: snapshot.epoch, + handle: loaded.handle.clone(), + }); + Ok(loaded) + } + + fn start_generation( + &mut self, + model: &api::LoadedModel, + request: api::GenerationRequest, + ) -> Result { + let attached = self.attached.clone().ok_or_else(|| { + error( + api::ErrorCode::BackendUnavailable, + "not attached to a loaded model", + true, + ) + })?; + if attached.handle != model.handle { + return Err(error( + api::ErrorCode::BackendUnavailable, + "stale model handle", + true, + )); + } + // Fresh identity check: the runtime may have restarted since the last call. + let snapshot = match self.snapshot() { + Ok(snapshot) => snapshot, + Err(error) => { + self.attached = None; + return Err(error); + } + }; + let still = snapshot + .loaded + .as_ref() + .is_some_and(|l| l.handle == attached.handle); + if snapshot.epoch != attached.epoch || !snapshot.model_ready || !still { + self.attached = None; + return Err(error( + api::ErrorCode::BackendUnavailable, + "the runtime restarted or unloaded the model", + true, + )); + } + let mut wire = proto::GenerateRequest { + request_id: request.request_id.clone(), + expected_epoch: attached.epoch.clone(), + handle: attached.handle.clone(), + ..Default::default() + }; + convert::apply_generation_request(&mut wire, &request); + let client = self.client.as_mut().expect("snapshot connected the client"); + let generation = self + .runtime + .block_on(client.generate(wire)) + .map_err(|status| { + log_status("generate_failed", &status); + from_status(&status) + })?; + *self.active.lock().expect("active lock") = Some(ActiveRequest { + id: request.request_id, + epoch: attached.epoch, + }); + let (sink, stream) = api::GenerationSink::channel(); + let active = Arc::clone(&self.active); + self.runtime.spawn(pump(generation, sink, active)); + Ok(stream) + } + + fn cancel(&mut self, request_id: &str) -> Result<(), api::BackendError> { + let active = self.active.lock().expect("active lock").clone(); + let Some(active) = active.filter(|a| a.id == request_id) else { + return Err(error( + api::ErrorCode::InvalidRequest, + "generation is not active", + false, + )); + }; + let Some(client) = self.client.as_mut() else { + return Err(error( + api::ErrorCode::BackendUnavailable, + "not connected", + true, + )); + }; + self.runtime + .block_on(client.cancel(proto::CancelRequest { + request_id: active.id, + expected_epoch: active.epoch, + })) + .map(|_| ()) + .map_err(|status| from_status(&status)) + } + + fn reconfigure(&mut self, settings_json: &str) -> Result { + let Some(attached) = self.attached.clone() else { + return Err(error( + api::ErrorCode::BackendUnavailable, + "no model is attached", + true, + )); + }; + let Some(client) = self.client.as_mut() else { + return Err(error( + api::ErrorCode::BackendUnavailable, + "not connected", + true, + )); + }; + let reply = self + .runtime + .block_on(client.reconfigure(proto::ReconfigureRequest { + operation_id: String::new(), + expected_epoch: attached.epoch, + settings_json: settings_json.to_owned(), + })) + .map_err(|status| from_status(&status))?; + if reply.ok { + return Ok(reply.effective_json); + } + let code = match reply.error_code.as_str() { + "invalid" => api::ErrorCode::InvalidRequest, + "unsupported" => api::ErrorCode::UnsupportedModel, + "exhausted" => api::ErrorCode::ResourceExhausted, + "unavailable" => api::ErrorCode::BackendUnavailable, + _ => api::ErrorCode::Internal, + }; + Err(api::BackendError { + code, + message: reply.error, + retryable: reply.retryable, + }) + } + + fn unload(&mut self, _: api::LoadedModel) -> Result<(), api::BackendError> { + Err(error( + api::ErrorCode::InvalidRequest, + "this backend only attaches to a loaded runtime; unload it with leleka-cli", + false, + )) + } +} diff --git a/crates/runtime-client/src/backend/log_status.rs b/crates/runtime-client/src/backend/log_status.rs new file mode 100644 index 00000000..38dbf488 --- /dev/null +++ b/crates/runtime-client/src/backend/log_status.rs @@ -0,0 +1,103 @@ +//! Moved out of the parent module by STRA-338: fn log_status, fn error, fn from_status, impl GrpcBackend. + +#[allow(unused_imports)] +use super::*; + +/// A failed call to the runtime, as one structured warning (rate limited per event by the log layer): the gRPC code and +/// the runtime's own short reason, never request content. +pub(super) fn log_status(event: &str, status: &tonic::Status) { + leleka_obs::warn( + "runtime-client", + event, + &[ + ("code", format!("{:?}", status.code()).as_str().into()), + ("reason", status.message().into()), + ], + ); +} + +pub(super) fn error( + code: api::ErrorCode, + message: impl Into, + retryable: bool, +) -> api::BackendError { + api::BackendError { + code, + message: message.into(), + retryable, + } +} + +/// A transport or protocol failure is `BackendUnavailable` (the caller attaches again); a refusal +/// that proves nothing was accepted keeps its meaning. +pub(super) fn from_status(status: &tonic::Status) -> api::BackendError { + let proven_unaccepted = status + .metadata() + .get("x-leleka-accepted") + .and_then(|v| v.to_str().ok()) + == Some("false"); + let (code, retryable) = match status.code() { + Code::InvalidArgument => (api::ErrorCode::InvalidRequest, false), + Code::FailedPrecondition => (api::ErrorCode::UnsupportedModel, false), + Code::ResourceExhausted => (api::ErrorCode::ResourceExhausted, proven_unaccepted), + Code::Unauthenticated | Code::PermissionDenied => (api::ErrorCode::Internal, false), + Code::Unavailable | Code::DeadlineExceeded | Code::Cancelled | Code::DataLoss => { + (api::ErrorCode::BackendUnavailable, false) + } + _ => (api::ErrorCode::Internal, false), + }; + error( + code, + format!("runtime: {} ({:?})", status.message(), status.code()), + retryable, + ) +} + +impl GrpcBackend { + pub fn new(runtime: Handle, address: SocketAddr, token: String) -> Self { + Self { + runtime, + address, + token, + client: None, + attached: None, + active: Arc::new(Mutex::new(None)), + prefix_summary: Mutex::new(None), + memory_report: Mutex::new(None), + telemetry_report: Mutex::new(None), + } + } + + /// The current runtime snapshot, connecting first if needed. A failure forgets the connection + /// so the next call connects again. + pub(super) fn snapshot(&mut self) -> Result { + if self.client.is_none() { + let (address, token) = (self.address, self.token.clone()); + let client = match self + .runtime + .block_on(RuntimeClient::connect(address, token)) + { + Ok(client) => client, + Err(status) => { + log_status("connect_failed", &status); + return Err(from_status(&status)); + } + }; + leleka_obs::info( + "runtime-client", + "connected", + &[("engine", address.to_string().as_str().into())], + ); + self.client = Some(client); + } + let client = self.client.as_mut().expect("client was just set"); + match self.runtime.block_on(client.snapshot()) { + Ok(snapshot) => Ok(snapshot), + Err(status) => { + self.client = None; + log_status("snapshot_failed", &status); + Err(from_status(&status)) + } + } + } +} diff --git a/crates/serving-policy/src/cvec.rs b/crates/serving-policy/src/cvec.rs index 1c420638..7d1d594e 100644 --- a/crates/serving-policy/src/cvec.rs +++ b/crates/serving-policy/src/cvec.rs @@ -36,158 +36,6 @@ struct Cursor<'a> { at: usize, } -impl<'a> Cursor<'a> { - fn take(&mut self, n: usize) -> Result<&'a [u8], String> { - let end = self - .at - .checked_add(n) - .filter(|end| *end <= self.bytes.len()) - .ok_or("GGUF file is truncated")?; - let slice = &self.bytes[self.at..end]; - self.at = end; - Ok(slice) - } - - fn u32(&mut self) -> Result { - Ok(u32::from_le_bytes( - self.take(4)?.try_into().expect("4 bytes"), - )) - } - - fn u64(&mut self) -> Result { - Ok(u64::from_le_bytes( - self.take(8)?.try_into().expect("8 bytes"), - )) - } - - fn string(&mut self) -> Result { - let len = usize::try_from(self.u64()?).map_err(|_| "GGUF string is too long")?; - if len > 1 << 24 { - return Err("GGUF string is too long".into()); - } - Ok(String::from_utf8_lossy(self.take(len)?).into_owned()) - } -} - -/// Skip (or read, for strings) one metadata value of type `kind`. -fn value(cursor: &mut Cursor<'_>, kind: u32) -> Result, String> { - let fixed = |bytes: usize, cursor: &mut Cursor<'_>| cursor.take(bytes).map(|_| None); - match kind { - 0 | 1 | 7 => fixed(1, cursor), - 2 | 3 => fixed(2, cursor), - 4..=6 => fixed(4, cursor), - 10..=12 => fixed(8, cursor), - 8 => cursor.string().map(Some), - 9 => { - let element = cursor.u32()?; - let count = cursor.u64()?; - if count > 1 << 28 { - return Err("GGUF array is too long".into()); - } - for _ in 0..count { - value(cursor, element)?; - } - Ok(None) - } - other => Err(format!("unknown GGUF metadata type {other}")), - } -} - -/// Parse a GGUF v2/v3 file held in memory (little endian). -pub fn parse_gguf(bytes: &[u8]) -> Result { - let mut cursor = Cursor { bytes, at: 0 }; - if cursor.take(4)? != b"GGUF" { - return Err("not a GGUF file".into()); - } - let version = cursor.u32()?; - if !(2..=3).contains(&version) { - return Err(format!("unsupported GGUF version {version}")); - } - let tensors = cursor.u64()?; - let entries = cursor.u64()?; - if tensors > 1 << 20 || entries > 1 << 20 { - return Err("GGUF header counts are implausible".into()); - } - let mut file = VectorFile::default(); - let mut alignment = 32u64; - for _ in 0..entries { - let key = cursor.string()?; - let kind = cursor.u32()?; - if key == "general.alignment" && kind == 4 { - alignment = u64::from(cursor.u32()?).max(1); - continue; - } - let text = value(&mut cursor, kind)?; - match key.as_str() { - "general.architecture" => file.architecture = text, - "controlvector.model_hint" => file.model_hint = text, - _ => {} - } - } - struct Info { - name: String, - kind: u32, - elements: u64, - offset: u64, - } - let mut infos = Vec::new(); - for _ in 0..tensors { - let name = cursor.string()?; - let dims = cursor.u32()?; - if dims > 8 { - return Err("GGUF tensor has too many dimensions".into()); - } - let mut elements = 1u64; - for _ in 0..dims { - elements = elements - .checked_mul(cursor.u64()?) - .ok_or("GGUF tensor is too large")?; - } - let kind = cursor.u32()?; - let offset = cursor.u64()?; - infos.push(Info { - name, - kind, - elements, - offset, - }); - } - let data_start = (cursor.at as u64).div_ceil(alignment) * alignment; - for info in infos { - let mut values = Vec::new(); - if info.kind == 0 { - let begin = data_start - .checked_add(info.offset) - .ok_or("GGUF tensor offset overflows")?; - let len = info - .elements - .checked_mul(4) - .ok_or("GGUF tensor is too large")?; - let end = begin - .checked_add(len) - .ok_or("GGUF tensor offset overflows")?; - let data = usize::try_from(begin) - .ok() - .zip(usize::try_from(end).ok()) - .and_then(|(b, e)| bytes.get(b..e)) - .ok_or("GGUF tensor data is truncated")?; - values = data - .as_chunks::<4>() - .0 - .iter() - .map(|c| f32::from_le_bytes(*c)) - .collect(); - } - file.tensors.push(VectorTensor { - name: info.name, - kind: info.kind, - elements: info.elements, - values, - }); - } - Ok(file) -} - #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum Mode { Project, @@ -206,17 +54,6 @@ pub struct Options { pub single: i32, } -impl Default for Options { - fn default() -> Self { - Self { - first: -1, - last: -1, - mode: Mode::Add, - single: -1, - } - } -} - /// What the kernel uploads. #[derive(Clone, Debug, PartialEq)] pub struct Tables { @@ -234,188 +71,12 @@ pub struct Tables { pub warnings: Vec, } -/// C `strtol(s, nullptr, 10)`: whitespace, sign, digits; no digits is 0. -fn strtol(text: &str) -> i64 { - let trimmed = text.trim_start(); - let (negative, digits) = match trimmed.as_bytes().first() { - Some(b'-') => (true, &trimmed[1..]), - Some(b'+') => (false, &trimmed[1..]), - _ => (false, trimmed), - }; - let mut value: i64 = 0; - for byte in digits.bytes().take_while(u8::is_ascii_digit) { - value = value - .saturating_mul(10) - .saturating_add(i64::from(byte - b'0')); - } - if negative { -value } else { value } -} - -/// `load_control_vectors`: `files` are `(label for messages, parsed file, scale)`. -pub fn build_tables( - files: &[(String, VectorFile, f32)], - n_layers: usize, - n_embd: usize, - options: Options, -) -> Result { - let (layers, width) = (n_layers as i64, n_embd as i64); - let mut data = vec![0.0f32; n_layers * n_embd]; - let mut have = vec![false; n_layers]; - let mut warnings = Vec::new(); - for (label, file, scale) in files { - if file.architecture.as_deref() != Some("controlvector") { - return Err(format!( - "{label}: not a control vector GGUF (general.architecture is not 'controlvector')" - )); - } - if let Some(hint) = file.model_hint.as_deref() - && hint != "qwen4exp" - { - warnings.push(format!("{label} was made for '{hint}', not qwen4exp")); - } - let mut found = 0; - for tensor in &file.tensors { - let Some(rest) = tensor.name.strip_prefix("direction.") else { - continue; - }; - let layer = strtol(rest); - if layer < 1 || layer >= layers { - continue; // layer 0 has no vector; past the model is ignored, as in llama.cpp - } - if tensor.kind != 0 || tensor.elements != n_embd as u64 { - return Err(format!("{label}: {} must be {width} f32", tensor.name)); - } - let row = &mut data[layer as usize * n_embd..(layer as usize + 1) * n_embd]; - for (target, source) in row.iter_mut().zip(&tensor.values) { - *target += scale * source; - } - have[layer as usize] = true; - found += 1; - } - if found == 0 { - return Err(format!("{label}: no direction. tensors")); - } - } - let first = if options.first <= 0 { 1 } else { options.first }; - let last = if options.last <= 0 || i64::from(options.last) >= layers { - (layers - 1) as i32 - } else { - options.last - }; - let single = if options.mode == Mode::Project { - options.single - } else { - -1 - }; - if single >= 0 && (i64::from(single) >= layers || !have[single as usize]) { - return Err(format!( - "--cvec-dir single:{single}: the vector has no direction for that layer" - )); - } - let mut dir = vec![0.0f32; n_layers * n_embd]; - let mut s = vec![0.0f32; n_layers]; - let mut steered = 0; - for layer in first..=last { - let source = if single >= 0 { single } else { layer } as usize; - if source >= n_layers || !have[source] || layer as usize >= n_layers { - continue; - } - let d = &data[source * n_embd..(source + 1) * n_embd]; - let target = layer as usize; - match options.mode { - Mode::Project => { - let norm = d - .iter() - .map(|v| f64::from(*v) * f64::from(*v)) - .sum::() - .sqrt(); - if norm <= 0.0 { - continue; - } - s[target] = norm as f32; - for (j, value) in d.iter().enumerate() { - dir[target * n_embd + j] = (f64::from(*value) / norm) as f32; - } - } - Mode::Add => { - s[target] = 1.0; - dir[target * n_embd..(target + 1) * n_embd].copy_from_slice(d); - } - } - steered += 1; - } - if steered == 0 { - return Err(format!( - "the control vector has no direction in layers {first}..{last}" - )); - } - let summary = format!( - "{}:{first}-{last}{}", - if options.mode == Mode::Project { - "project" - } else { - "add" - }, - if single >= 0 { - format!(":single{single}") - } else { - String::new() - } - ); - Ok(Tables { - dir, - s, - mode: options.mode, - first, - last, - steered, - summary, - warnings, - }) -} - -/// `--control-vector-scaled FILE:SCALE[,FILE:SCALE...]`: the last colon splits, so a path with a -/// drive letter keeps it. `Err` is the engine's usage message. -pub fn parse_scaled_list(text: &str) -> Result, String> { - let mut out = Vec::new(); - for item in text.split(',') { - let bad = || format!("--control-vector-scaled: expected FILE:SCALE, got '{item}'"); - let (path, scale) = item.rsplit_once(':').ok_or_else(bad)?; - if path.is_empty() { - return Err(bad()); - } - out.push((path.to_owned(), strtof_exact(scale).ok_or_else(bad)?)); - } - Ok(out) -} - -/// `strtof` that must consume the whole text and find at least one character. -fn strtof_exact(text: &str) -> Option { - if text.is_empty() || text.trim() != text { - return None; - } - text.parse::().ok() -} - -/// `--cvec-dir per-layer|single:L`. -pub fn parse_dir(text: &str) -> Result { - if text == "per-layer" { - return Ok(-1); - } - if let Some(rest) = text.strip_prefix("single:") { - return Ok(i32::try_from(strtol(rest)).unwrap_or(0)); - } - Err(format!("--cvec-dir: per-layer or single:L, got '{text}'")) -} - -/// `--cvec-mode add|project`. -pub fn parse_mode(text: &str) -> Result { - match text { - "project" => Ok(Mode::Project), - "add" => Ok(Mode::Add), - other => Err(format!("--cvec-mode: add or project, got '{other}'")), - } -} - #[cfg(test)] mod tests; + +mod impl_cursor; +#[allow(unused_imports)] +pub use impl_cursor::*; +mod build_tables; +#[allow(unused_imports)] +pub use build_tables::*; diff --git a/crates/serving-policy/src/cvec/build_tables.rs b/crates/serving-policy/src/cvec/build_tables.rs new file mode 100644 index 00000000..a53b058c --- /dev/null +++ b/crates/serving-policy/src/cvec/build_tables.rs @@ -0,0 +1,170 @@ +//! Moved out of the parent module by STRA-338: fn build_tables, fn parse_scaled_list, fn strtof_exact, fn parse_dir, fn parse_mode. + +#[allow(unused_imports)] +use super::*; + +/// `load_control_vectors`: `files` are `(label for messages, parsed file, scale)`. +pub fn build_tables( + files: &[(String, VectorFile, f32)], + n_layers: usize, + n_embd: usize, + options: Options, +) -> Result { + let (layers, width) = (n_layers as i64, n_embd as i64); + let mut data = vec![0.0f32; n_layers * n_embd]; + let mut have = vec![false; n_layers]; + let mut warnings = Vec::new(); + for (label, file, scale) in files { + if file.architecture.as_deref() != Some("controlvector") { + return Err(format!( + "{label}: not a control vector GGUF (general.architecture is not 'controlvector')" + )); + } + if let Some(hint) = file.model_hint.as_deref() + && hint != "qwen4exp" + { + warnings.push(format!("{label} was made for '{hint}', not qwen4exp")); + } + let mut found = 0; + for tensor in &file.tensors { + let Some(rest) = tensor.name.strip_prefix("direction.") else { + continue; + }; + let layer = strtol(rest); + if layer < 1 || layer >= layers { + continue; // layer 0 has no vector; past the model is ignored, as in llama.cpp + } + if tensor.kind != 0 || tensor.elements != n_embd as u64 { + return Err(format!("{label}: {} must be {width} f32", tensor.name)); + } + let row = &mut data[layer as usize * n_embd..(layer as usize + 1) * n_embd]; + for (target, source) in row.iter_mut().zip(&tensor.values) { + *target += scale * source; + } + have[layer as usize] = true; + found += 1; + } + if found == 0 { + return Err(format!("{label}: no direction. tensors")); + } + } + let first = if options.first <= 0 { 1 } else { options.first }; + let last = if options.last <= 0 || i64::from(options.last) >= layers { + (layers - 1) as i32 + } else { + options.last + }; + let single = if options.mode == Mode::Project { + options.single + } else { + -1 + }; + if single >= 0 && (i64::from(single) >= layers || !have[single as usize]) { + return Err(format!( + "--cvec-dir single:{single}: the vector has no direction for that layer" + )); + } + let mut dir = vec![0.0f32; n_layers * n_embd]; + let mut s = vec![0.0f32; n_layers]; + let mut steered = 0; + for layer in first..=last { + let source = if single >= 0 { single } else { layer } as usize; + if source >= n_layers || !have[source] || layer as usize >= n_layers { + continue; + } + let d = &data[source * n_embd..(source + 1) * n_embd]; + let target = layer as usize; + match options.mode { + Mode::Project => { + let norm = d + .iter() + .map(|v| f64::from(*v) * f64::from(*v)) + .sum::() + .sqrt(); + if norm <= 0.0 { + continue; + } + s[target] = norm as f32; + for (j, value) in d.iter().enumerate() { + dir[target * n_embd + j] = (f64::from(*value) / norm) as f32; + } + } + Mode::Add => { + s[target] = 1.0; + dir[target * n_embd..(target + 1) * n_embd].copy_from_slice(d); + } + } + steered += 1; + } + if steered == 0 { + return Err(format!( + "the control vector has no direction in layers {first}..{last}" + )); + } + let summary = format!( + "{}:{first}-{last}{}", + if options.mode == Mode::Project { + "project" + } else { + "add" + }, + if single >= 0 { + format!(":single{single}") + } else { + String::new() + } + ); + Ok(Tables { + dir, + s, + mode: options.mode, + first, + last, + steered, + summary, + warnings, + }) +} + +/// `--control-vector-scaled FILE:SCALE[,FILE:SCALE...]`: the last colon splits, so a path with a +/// drive letter keeps it. `Err` is the engine's usage message. +pub fn parse_scaled_list(text: &str) -> Result, String> { + let mut out = Vec::new(); + for item in text.split(',') { + let bad = || format!("--control-vector-scaled: expected FILE:SCALE, got '{item}'"); + let (path, scale) = item.rsplit_once(':').ok_or_else(bad)?; + if path.is_empty() { + return Err(bad()); + } + out.push((path.to_owned(), strtof_exact(scale).ok_or_else(bad)?)); + } + Ok(out) +} + +/// `strtof` that must consume the whole text and find at least one character. +pub(super) fn strtof_exact(text: &str) -> Option { + if text.is_empty() || text.trim() != text { + return None; + } + text.parse::().ok() +} + +/// `--cvec-dir per-layer|single:L`. +pub fn parse_dir(text: &str) -> Result { + if text == "per-layer" { + return Ok(-1); + } + if let Some(rest) = text.strip_prefix("single:") { + return Ok(i32::try_from(strtol(rest)).unwrap_or(0)); + } + Err(format!("--cvec-dir: per-layer or single:L, got '{text}'")) +} + +/// `--cvec-mode add|project`. +pub fn parse_mode(text: &str) -> Result { + match text { + "project" => Ok(Mode::Project), + "add" => Ok(Mode::Add), + other => Err(format!("--cvec-mode: add or project, got '{other}'")), + } +} diff --git a/crates/serving-policy/src/cvec/impl_cursor.rs b/crates/serving-policy/src/cvec/impl_cursor.rs new file mode 100644 index 00000000..136505aa --- /dev/null +++ b/crates/serving-policy/src/cvec/impl_cursor.rs @@ -0,0 +1,184 @@ +//! Moved out of the parent module by STRA-338: impl Cursor, fn value, fn parse_gguf, impl Default_for_Options, fn strtol. + +#[allow(unused_imports)] +use super::*; + +impl<'a> Cursor<'a> { + pub(super) fn take(&mut self, n: usize) -> Result<&'a [u8], String> { + let end = self + .at + .checked_add(n) + .filter(|end| *end <= self.bytes.len()) + .ok_or("GGUF file is truncated")?; + let slice = &self.bytes[self.at..end]; + self.at = end; + Ok(slice) + } + + pub(super) fn u32(&mut self) -> Result { + Ok(u32::from_le_bytes( + self.take(4)?.try_into().expect("4 bytes"), + )) + } + + pub(super) fn u64(&mut self) -> Result { + Ok(u64::from_le_bytes( + self.take(8)?.try_into().expect("8 bytes"), + )) + } + + pub(super) fn string(&mut self) -> Result { + let len = usize::try_from(self.u64()?).map_err(|_| "GGUF string is too long")?; + if len > 1 << 24 { + return Err("GGUF string is too long".into()); + } + Ok(String::from_utf8_lossy(self.take(len)?).into_owned()) + } +} + +/// Skip (or read, for strings) one metadata value of type `kind`. +pub(super) fn value(cursor: &mut Cursor<'_>, kind: u32) -> Result, String> { + let fixed = |bytes: usize, cursor: &mut Cursor<'_>| cursor.take(bytes).map(|_| None); + match kind { + 0 | 1 | 7 => fixed(1, cursor), + 2 | 3 => fixed(2, cursor), + 4..=6 => fixed(4, cursor), + 10..=12 => fixed(8, cursor), + 8 => cursor.string().map(Some), + 9 => { + let element = cursor.u32()?; + let count = cursor.u64()?; + if count > 1 << 28 { + return Err("GGUF array is too long".into()); + } + for _ in 0..count { + value(cursor, element)?; + } + Ok(None) + } + other => Err(format!("unknown GGUF metadata type {other}")), + } +} + +/// Parse a GGUF v2/v3 file held in memory (little endian). +pub fn parse_gguf(bytes: &[u8]) -> Result { + let mut cursor = Cursor { bytes, at: 0 }; + if cursor.take(4)? != b"GGUF" { + return Err("not a GGUF file".into()); + } + let version = cursor.u32()?; + if !(2..=3).contains(&version) { + return Err(format!("unsupported GGUF version {version}")); + } + let tensors = cursor.u64()?; + let entries = cursor.u64()?; + if tensors > 1 << 20 || entries > 1 << 20 { + return Err("GGUF header counts are implausible".into()); + } + let mut file = VectorFile::default(); + let mut alignment = 32u64; + for _ in 0..entries { + let key = cursor.string()?; + let kind = cursor.u32()?; + if key == "general.alignment" && kind == 4 { + alignment = u64::from(cursor.u32()?).max(1); + continue; + } + let text = value(&mut cursor, kind)?; + match key.as_str() { + "general.architecture" => file.architecture = text, + "controlvector.model_hint" => file.model_hint = text, + _ => {} + } + } + struct Info { + name: String, + kind: u32, + elements: u64, + offset: u64, + } + let mut infos = Vec::new(); + for _ in 0..tensors { + let name = cursor.string()?; + let dims = cursor.u32()?; + if dims > 8 { + return Err("GGUF tensor has too many dimensions".into()); + } + let mut elements = 1u64; + for _ in 0..dims { + elements = elements + .checked_mul(cursor.u64()?) + .ok_or("GGUF tensor is too large")?; + } + let kind = cursor.u32()?; + let offset = cursor.u64()?; + infos.push(Info { + name, + kind, + elements, + offset, + }); + } + let data_start = (cursor.at as u64).div_ceil(alignment) * alignment; + for info in infos { + let mut values = Vec::new(); + if info.kind == 0 { + let begin = data_start + .checked_add(info.offset) + .ok_or("GGUF tensor offset overflows")?; + let len = info + .elements + .checked_mul(4) + .ok_or("GGUF tensor is too large")?; + let end = begin + .checked_add(len) + .ok_or("GGUF tensor offset overflows")?; + let data = usize::try_from(begin) + .ok() + .zip(usize::try_from(end).ok()) + .and_then(|(b, e)| bytes.get(b..e)) + .ok_or("GGUF tensor data is truncated")?; + values = data + .as_chunks::<4>() + .0 + .iter() + .map(|c| f32::from_le_bytes(*c)) + .collect(); + } + file.tensors.push(VectorTensor { + name: info.name, + kind: info.kind, + elements: info.elements, + values, + }); + } + Ok(file) +} + +impl Default for Options { + fn default() -> Self { + Self { + first: -1, + last: -1, + mode: Mode::Add, + single: -1, + } + } +} + +/// C `strtol(s, nullptr, 10)`: whitespace, sign, digits; no digits is 0. +pub(super) fn strtol(text: &str) -> i64 { + let trimmed = text.trim_start(); + let (negative, digits) = match trimmed.as_bytes().first() { + Some(b'-') => (true, &trimmed[1..]), + Some(b'+') => (false, &trimmed[1..]), + _ => (false, trimmed), + }; + let mut value: i64 = 0; + for byte in digits.bytes().take_while(u8::is_ascii_digit) { + value = value + .saturating_mul(10) + .saturating_add(i64::from(byte - b'0')); + } + if negative { -value } else { value } +} diff --git a/crates/serving-policy/src/shared.rs b/crates/serving-policy/src/shared.rs index 2fc13916..02da4efd 100644 --- a/crates/serving-policy/src/shared.rs +++ b/crates/serving-policy/src/shared.rs @@ -39,187 +39,6 @@ pub struct SharedDefaults { pub experimental_speed_projection: Option, } -impl SharedDefaults { - pub fn is_empty(&self) -> bool { - *self == Self::default() - } - - /// The JSON object `/settings` answers with and persists (`defaults`). - pub fn to_json(&self) -> Value { - let mut out = Map::new(); - if let Some(v) = &self.reasoning_effort { - out.insert("reasoning_effort".into(), Value::String(v.clone())); - } - if let Some(v) = self.temperature { - out.insert("temperature".into(), float_value(v)); - } - if let Some(v) = self.top_p { - out.insert("top_p".into(), float_value(v)); - } - if let Some(v) = self.top_k { - out.insert("top_k".into(), Value::from(v)); - } - if let Some(v) = self.seed { - out.insert("seed".into(), Value::from(v)); - } - if let Some(v) = self.max_tokens { - out.insert("max_tokens".into(), Value::from(v)); - } - if let Some(v) = self.experimental_speed_projection { - out.insert("experimental_speed_projection".into(), Value::Bool(v)); - } - Value::Object(out) - } - - /// The sampling subset the shared settings carry. - pub fn sampling(&self) -> RequestSampling { - RequestSampling { - temperature: self.temperature, - top_p: self.top_p, - top_k: self.top_k, - seed: self.seed, - ..Default::default() - } - } -} - -fn float_value(v: f64) -> Value { - Number::from_f64(v).map_or(Value::Null, Value::Number) -} - -/// Python's `repr()` of a JSON-ish value, for the Original's error text. -pub fn py_repr(value: &Value) -> String { - match value { - Value::Null => "None".into(), - Value::Bool(true) => "True".into(), - Value::Bool(false) => "False".into(), - Value::Number(n) => match n.as_i64() { - Some(i) => i.to_string(), - None => match n.as_u64() { - Some(u) => u.to_string(), - None => py_float_repr(n.as_f64().unwrap_or(f64::NAN)), - }, - }, - Value::String(s) => py_str_repr(s), - Value::Array(items) => format!( - "[{}]", - items.iter().map(py_repr).collect::>().join(", ") - ), - Value::Object(map) => format!( - "{{{}}}", - map.iter() - .map(|(k, v)| format!("{}: {}", py_str_repr(k), py_repr(v))) - .collect::>() - .join(", ") - ), - } -} - -/// Python's `repr(str)`: single quotes unless the text has a single and no double quote. -pub fn py_str_repr(s: &str) -> String { - let quote = if s.contains('\'') && !s.contains('"') { - '"' - } else { - '\'' - }; - let mut out = String::new(); - out.push(quote); - for c in s.chars() { - match c { - '\\' => out.push_str("\\\\"), - '\n' => out.push_str("\\n"), - '\r' => out.push_str("\\r"), - '\t' => out.push_str("\\t"), - c if c == quote => { - out.push('\\'); - out.push(c); - } - c if (c as u32) < 0x20 || c as u32 == 0x7f => { - out.push_str(&format!("\\x{:02x}", c as u32)); - } - c => out.push(c), - } - } - out.push(quote); - out -} - -fn is_number(v: &Value) -> bool { - v.is_number() -} - -fn as_f64(v: &Value) -> Option { - v.as_f64() -} - -/// An integral number as `i128`, or `None`. -fn integral(v: &Value) -> Option { - if let Some(i) = v.as_i64() { - return Some(i128::from(i)); - } - if let Some(u) = v.as_u64() { - return Some(i128::from(u)); - } - let f = v.as_f64()?; - (f.is_finite() && f.fract() == 0.0 && f.abs() < 1e18).then_some(f as i128) -} - -/// `clean_shared_defaults`: `Ok` with only the known, valid keys; `Err` names the first bad one -/// (the message the Original's `ValueError` carries). -pub fn clean_shared_defaults(defaults: &Value) -> Result { - let map = match defaults { - Value::Null => return Ok(SharedDefaults::default()), - Value::Object(map) => map, - _ => return Err("defaults must be an object".into()), - }; - let mut out = SharedDefaults::default(); - for (key, value) in map { - if value.is_null() || value.as_str() == Some("") { - continue; - } - match key.as_str() { - "reasoning_effort" => match value.as_str() { - Some(e @ ("none" | "low" | "medium" | "high")) => { - out.reasoning_effort = Some(e.to_owned()); - } - _ => return Err("reasoning_effort: none, low, medium or high".into()), - }, - "temperature" => match as_f64(value) { - Some(t) if is_number(value) && (0.0..=2.0).contains(&t) => { - out.temperature = Some(t) - } - _ => return Err("temperature: 0..2".into()), - }, - "top_p" => match as_f64(value) { - Some(p) if is_number(value) && p > 0.0 && p <= 1.0 => out.top_p = Some(p), - _ => return Err("top_p: 0 < top_p <= 1".into()), - }, - "top_k" => match integral(value) { - Some(k) if is_number(value) && (1..=64).contains(&k) => out.top_k = Some(k as i64), - _ => return Err("top_k: an integer 1..64".into()), - }, - "seed" => match integral(value) { - Some(s) if is_number(value) && s > 0 && s <= i128::from(u64::MAX) => { - out.seed = Some(s as u64); - } - _ => return Err("seed: a positive integer".into()), - }, - "max_tokens" => match integral(value) { - Some(s) if is_number(value) && s > 0 && s <= i128::from(u64::MAX) => { - out.max_tokens = Some(s as u64); - } - _ => return Err("max_tokens: a positive integer".into()), - }, - "experimental_speed_projection" => match value.as_bool() { - Some(b) => out.experimental_speed_projection = Some(b), - None => return Err("experimental_speed_projection: true or false".into()), - }, - other => return Err(format!("unknown setting {}", py_str_repr(other))), - } - } - Ok(out) -} - /// The run config's `sampling` block (`sampling_defaults_from_config`). #[derive(Clone, Debug, Default, PartialEq)] pub struct ConfigSampling { @@ -229,181 +48,18 @@ pub struct ConfigSampling { pub ignored: Vec, } -fn config_error(key: &str, value: &Value, expected: &str) -> String { - format!( - "[strata] config sampling.{key}={}: {expected}", - py_repr(value) - ) -} - -/// Parse the config's `sampling` object. A bad value is an error (the Original stops the start). -pub fn sampling_defaults_from_config(block: &Value) -> Result { - let map = match block { - Value::Null => return Ok(ConfigSampling::default()), - Value::Object(map) => map, - _ => return Err("[strata] config sampling: expected an object".into()), - }; - let mut out = ConfigSampling::default(); - for (key, value) in map { - if value.is_null() { - continue; - } - let number = is_number(value); - let f = as_f64(value).filter(|_| number); - match key.as_str() { - "temperature" => match f { - Some(v) if v >= 0.0 => out.sampling.temperature = Some(v), - _ => { - return Err(config_error( - key, - value, - "expected a number >= 0 (0 = greedy)", - )); - } - }, - "top_p" => match f { - Some(v) if v > 0.0 && v <= 1.0 => out.sampling.top_p = Some(v), - _ => return Err(config_error(key, value, "expected 0 < top_p <= 1")), - }, - "min_p" => match f { - Some(v) if (0.0..=1.0).contains(&v) => out.sampling.min_p = Some(v), - _ => return Err(config_error(key, value, "expected 0 <= min_p <= 1")), - }, - "top_k" => match integral(value) { - Some(k) if number && (1..=64).contains(&k) => out.sampling.top_k = Some(k as i64), - _ => { - return Err(config_error( - key, - value, - "the sampled path takes an integer 1..64", - )); - } - }, - "presence_penalty" => match f { - Some(v) if v >= 0.0 => out.sampling.presence_penalty = Some(v), - _ => return Err(config_error(key, value, "expected a number >= 0")), - }, - "frequency_penalty" => match f { - Some(v) if v >= 0.0 => out.sampling.frequency_penalty = Some(v), - _ => return Err(config_error(key, value, "expected a number >= 0")), - }, - "repetition_penalty" => match f { - Some(v) if v > 0.0 => out.sampling.repetition_penalty = Some(v), - _ => return Err(config_error(key, value, "expected a number > 0 (1 = off)")), - }, - "penalty_last_n" => match integral(value) { - Some(n) if number && (0..=i128::from(i32::MAX)).contains(&n) => { - out.sampling.penalty_last_n = Some(n as i64); - } - _ => { - return Err(config_error(key, value, "expected a non-negative integer")); - } - }, - "seed" => match integral(value) { - Some(s) if number && s > 0 && s <= i128::from(u64::MAX) => { - out.sampling.seed = Some(s as u64); - } - _ => return Err(config_error(key, value, "expected a positive integer")), - }, - "experimental_speed_projection" => match value.as_bool() { - Some(b) => out.experimental_speed_projection = Some(b), - None => { - return Err(config_error( - key, - value, - "expected true or false (the default for requests that leave it out, when the engine has the vector)", - )); - } - }, - other => out.ignored.push(other.to_owned()), - } - } - // The request boundary of this port refuses temperatures above 2; a default must be usable. - out.sampling - .validate_config_defaults() - .map_err(|e| format!("[strata] config sampling.{}: {}", e.field, e.expected))?; - Ok(out) -} - -/// `Service.set_aliases`: the config's `aliases` - a list of names (or one comma-separated string), like -/// llama-server's `--alias`. Names are trimmed; empty names, the model's own name and duplicates are -/// dropped. `Err` for anything else. -pub fn normalize_aliases(value: &Value, model: &str) -> Result, String> { - let names: Vec = match value { - Value::Null => Vec::new(), - Value::String(text) => text.split(',').map(str::to_owned).collect(), - Value::Array(items) if items.iter().all(Value::is_string) => items - .iter() - .filter_map(|v| v.as_str().map(str::to_owned)) - .collect(), - other => { - return Err(format!( - "aliases={}: expected a list of model names", - py_repr(other) - )); - } - }; - let mut out: Vec = Vec::new(); - for name in names { - let name = name.trim().to_owned(); - if !name.is_empty() && name != model && !out.contains(&name) { - out.push(name); - } - } - Ok(out) -} - -/// The defaults a request starts from: the config block, then the shared settings on top -/// (`{**sampling_defaults, **shared}`). The speed-projection default comes the same way. -pub fn merged_defaults(config: &ConfigSampling, shared: &SharedDefaults) -> MergedDefaults { - MergedDefaults { - sampling: RequestSampling::overlay(&config.sampling, &shared.sampling()), - experimental_speed_projection: shared - .experimental_speed_projection - .or(config.experimental_speed_projection), - } -} - #[derive(Clone, Debug, Default, PartialEq)] pub struct MergedDefaults { pub sampling: RequestSampling, pub experimental_speed_projection: Option, } -impl MergedDefaults { - /// `default_generation_settings.params` of `GET /props` (llama-server names). - pub fn props_params(&self, shared: &SharedDefaults) -> Value { - let mut params = Map::new(); - let s = &self.sampling; - let mut put = |name: &str, value: Option| { - if let Some(v) = value { - params.insert(name.to_owned(), v); - } - }; - put("temperature", s.temperature.map(float_value)); - put("top_p", s.top_p.map(float_value)); - put("top_k", s.top_k.map(Value::from)); - put("min_p", s.min_p.map(float_value)); - put("seed", s.seed.map(Value::from)); - put("repeat_penalty", s.repetition_penalty.map(float_value)); - put("presence_penalty", s.presence_penalty.map(float_value)); - put("frequency_penalty", s.frequency_penalty.map(float_value)); - put("repeat_last_n", s.penalty_last_n.map(Value::from)); - params.insert( - "n_predict".into(), - shared.max_tokens.map_or(Value::from(-1), Value::from), - ); - Value::Object(params) - } -} - -/// `with_shared`, `max_tokens` half: the shared limit when the request has none of its own. -pub fn shared_max_tokens(request_max: Option, shared: &SharedDefaults) -> Option { - match request_max { - Some(n) if n > 0 => Some(n), - _ => shared.max_tokens.or(request_max), - } -} - #[cfg(test)] mod tests; + +mod impl_shareddefaults; +#[allow(unused_imports)] +pub use impl_shareddefaults::*; +mod sampling_defaults_from_config; +#[allow(unused_imports)] +pub use sampling_defaults_from_config::*; diff --git a/crates/serving-policy/src/shared/impl_shareddefaults.rs b/crates/serving-policy/src/shared/impl_shareddefaults.rs new file mode 100644 index 00000000..545777b0 --- /dev/null +++ b/crates/serving-policy/src/shared/impl_shareddefaults.rs @@ -0,0 +1,192 @@ +//! Moved out of the parent module by STRA-338: impl SharedDefaults, fn float_value, fn py_repr, fn py_str_repr, fn is_number, fn as_f64 .... + +#[allow(unused_imports)] +use super::*; + +impl SharedDefaults { + pub fn is_empty(&self) -> bool { + *self == Self::default() + } + + /// The JSON object `/settings` answers with and persists (`defaults`). + pub fn to_json(&self) -> Value { + let mut out = Map::new(); + if let Some(v) = &self.reasoning_effort { + out.insert("reasoning_effort".into(), Value::String(v.clone())); + } + if let Some(v) = self.temperature { + out.insert("temperature".into(), float_value(v)); + } + if let Some(v) = self.top_p { + out.insert("top_p".into(), float_value(v)); + } + if let Some(v) = self.top_k { + out.insert("top_k".into(), Value::from(v)); + } + if let Some(v) = self.seed { + out.insert("seed".into(), Value::from(v)); + } + if let Some(v) = self.max_tokens { + out.insert("max_tokens".into(), Value::from(v)); + } + if let Some(v) = self.experimental_speed_projection { + out.insert("experimental_speed_projection".into(), Value::Bool(v)); + } + Value::Object(out) + } + + /// The sampling subset the shared settings carry. + pub fn sampling(&self) -> RequestSampling { + RequestSampling { + temperature: self.temperature, + top_p: self.top_p, + top_k: self.top_k, + seed: self.seed, + ..Default::default() + } + } +} + +pub(super) fn float_value(v: f64) -> Value { + Number::from_f64(v).map_or(Value::Null, Value::Number) +} + +/// Python's `repr()` of a JSON-ish value, for the Original's error text. +pub fn py_repr(value: &Value) -> String { + match value { + Value::Null => "None".into(), + Value::Bool(true) => "True".into(), + Value::Bool(false) => "False".into(), + Value::Number(n) => match n.as_i64() { + Some(i) => i.to_string(), + None => match n.as_u64() { + Some(u) => u.to_string(), + None => py_float_repr(n.as_f64().unwrap_or(f64::NAN)), + }, + }, + Value::String(s) => py_str_repr(s), + Value::Array(items) => format!( + "[{}]", + items.iter().map(py_repr).collect::>().join(", ") + ), + Value::Object(map) => format!( + "{{{}}}", + map.iter() + .map(|(k, v)| format!("{}: {}", py_str_repr(k), py_repr(v))) + .collect::>() + .join(", ") + ), + } +} + +/// Python's `repr(str)`: single quotes unless the text has a single and no double quote. +pub fn py_str_repr(s: &str) -> String { + let quote = if s.contains('\'') && !s.contains('"') { + '"' + } else { + '\'' + }; + let mut out = String::new(); + out.push(quote); + for c in s.chars() { + match c { + '\\' => out.push_str("\\\\"), + '\n' => out.push_str("\\n"), + '\r' => out.push_str("\\r"), + '\t' => out.push_str("\\t"), + c if c == quote => { + out.push('\\'); + out.push(c); + } + c if (c as u32) < 0x20 || c as u32 == 0x7f => { + out.push_str(&format!("\\x{:02x}", c as u32)); + } + c => out.push(c), + } + } + out.push(quote); + out +} + +pub(super) fn is_number(v: &Value) -> bool { + v.is_number() +} + +pub(super) fn as_f64(v: &Value) -> Option { + v.as_f64() +} + +/// An integral number as `i128`, or `None`. +pub(super) fn integral(v: &Value) -> Option { + if let Some(i) = v.as_i64() { + return Some(i128::from(i)); + } + if let Some(u) = v.as_u64() { + return Some(i128::from(u)); + } + let f = v.as_f64()?; + (f.is_finite() && f.fract() == 0.0 && f.abs() < 1e18).then_some(f as i128) +} + +/// `clean_shared_defaults`: `Ok` with only the known, valid keys; `Err` names the first bad one +/// (the message the Original's `ValueError` carries). +pub fn clean_shared_defaults(defaults: &Value) -> Result { + let map = match defaults { + Value::Null => return Ok(SharedDefaults::default()), + Value::Object(map) => map, + _ => return Err("defaults must be an object".into()), + }; + let mut out = SharedDefaults::default(); + for (key, value) in map { + if value.is_null() || value.as_str() == Some("") { + continue; + } + match key.as_str() { + "reasoning_effort" => match value.as_str() { + Some(e @ ("none" | "low" | "medium" | "high")) => { + out.reasoning_effort = Some(e.to_owned()); + } + _ => return Err("reasoning_effort: none, low, medium or high".into()), + }, + "temperature" => match as_f64(value) { + Some(t) if is_number(value) && (0.0..=2.0).contains(&t) => { + out.temperature = Some(t) + } + _ => return Err("temperature: 0..2".into()), + }, + "top_p" => match as_f64(value) { + Some(p) if is_number(value) && p > 0.0 && p <= 1.0 => out.top_p = Some(p), + _ => return Err("top_p: 0 < top_p <= 1".into()), + }, + "top_k" => match integral(value) { + Some(k) if is_number(value) && (1..=64).contains(&k) => out.top_k = Some(k as i64), + _ => return Err("top_k: an integer 1..64".into()), + }, + "seed" => match integral(value) { + Some(s) if is_number(value) && s > 0 && s <= i128::from(u64::MAX) => { + out.seed = Some(s as u64); + } + _ => return Err("seed: a positive integer".into()), + }, + "max_tokens" => match integral(value) { + Some(s) if is_number(value) && s > 0 && s <= i128::from(u64::MAX) => { + out.max_tokens = Some(s as u64); + } + _ => return Err("max_tokens: a positive integer".into()), + }, + "experimental_speed_projection" => match value.as_bool() { + Some(b) => out.experimental_speed_projection = Some(b), + None => return Err("experimental_speed_projection: true or false".into()), + }, + other => return Err(format!("unknown setting {}", py_str_repr(other))), + } + } + Ok(out) +} + +pub(super) fn config_error(key: &str, value: &Value, expected: &str) -> String { + format!( + "[strata] config sampling.{key}={}: {expected}", + py_repr(value) + ) +} diff --git a/crates/serving-policy/src/shared/sampling_defaults_from_config.rs b/crates/serving-policy/src/shared/sampling_defaults_from_config.rs new file mode 100644 index 00000000..1be78431 --- /dev/null +++ b/crates/serving-policy/src/shared/sampling_defaults_from_config.rs @@ -0,0 +1,167 @@ +//! Moved out of the parent module by STRA-338: fn sampling_defaults_from_config, fn normalize_aliases, fn merged_defaults, impl MergedDefaults, fn shared_max_tokens. + +#[allow(unused_imports)] +use super::*; + +/// Parse the config's `sampling` object. A bad value is an error (the Original stops the start). +pub fn sampling_defaults_from_config(block: &Value) -> Result { + let map = match block { + Value::Null => return Ok(ConfigSampling::default()), + Value::Object(map) => map, + _ => return Err("[strata] config sampling: expected an object".into()), + }; + let mut out = ConfigSampling::default(); + for (key, value) in map { + if value.is_null() { + continue; + } + let number = is_number(value); + let f = as_f64(value).filter(|_| number); + match key.as_str() { + "temperature" => match f { + Some(v) if v >= 0.0 => out.sampling.temperature = Some(v), + _ => { + return Err(config_error( + key, + value, + "expected a number >= 0 (0 = greedy)", + )); + } + }, + "top_p" => match f { + Some(v) if v > 0.0 && v <= 1.0 => out.sampling.top_p = Some(v), + _ => return Err(config_error(key, value, "expected 0 < top_p <= 1")), + }, + "min_p" => match f { + Some(v) if (0.0..=1.0).contains(&v) => out.sampling.min_p = Some(v), + _ => return Err(config_error(key, value, "expected 0 <= min_p <= 1")), + }, + "top_k" => match integral(value) { + Some(k) if number && (1..=64).contains(&k) => out.sampling.top_k = Some(k as i64), + _ => { + return Err(config_error( + key, + value, + "the sampled path takes an integer 1..64", + )); + } + }, + "presence_penalty" => match f { + Some(v) if v >= 0.0 => out.sampling.presence_penalty = Some(v), + _ => return Err(config_error(key, value, "expected a number >= 0")), + }, + "frequency_penalty" => match f { + Some(v) if v >= 0.0 => out.sampling.frequency_penalty = Some(v), + _ => return Err(config_error(key, value, "expected a number >= 0")), + }, + "repetition_penalty" => match f { + Some(v) if v > 0.0 => out.sampling.repetition_penalty = Some(v), + _ => return Err(config_error(key, value, "expected a number > 0 (1 = off)")), + }, + "penalty_last_n" => match integral(value) { + Some(n) if number && (0..=i128::from(i32::MAX)).contains(&n) => { + out.sampling.penalty_last_n = Some(n as i64); + } + _ => { + return Err(config_error(key, value, "expected a non-negative integer")); + } + }, + "seed" => match integral(value) { + Some(s) if number && s > 0 && s <= i128::from(u64::MAX) => { + out.sampling.seed = Some(s as u64); + } + _ => return Err(config_error(key, value, "expected a positive integer")), + }, + "experimental_speed_projection" => match value.as_bool() { + Some(b) => out.experimental_speed_projection = Some(b), + None => { + return Err(config_error( + key, + value, + "expected true or false (the default for requests that leave it out, when the engine has the vector)", + )); + } + }, + other => out.ignored.push(other.to_owned()), + } + } + // The request boundary of this port refuses temperatures above 2; a default must be usable. + out.sampling + .validate_config_defaults() + .map_err(|e| format!("[strata] config sampling.{}: {}", e.field, e.expected))?; + Ok(out) +} + +/// `Service.set_aliases`: the config's `aliases` - a list of names (or one comma-separated string), like +/// llama-server's `--alias`. Names are trimmed; empty names, the model's own name and duplicates are +/// dropped. `Err` for anything else. +pub fn normalize_aliases(value: &Value, model: &str) -> Result, String> { + let names: Vec = match value { + Value::Null => Vec::new(), + Value::String(text) => text.split(',').map(str::to_owned).collect(), + Value::Array(items) if items.iter().all(Value::is_string) => items + .iter() + .filter_map(|v| v.as_str().map(str::to_owned)) + .collect(), + other => { + return Err(format!( + "aliases={}: expected a list of model names", + py_repr(other) + )); + } + }; + let mut out: Vec = Vec::new(); + for name in names { + let name = name.trim().to_owned(); + if !name.is_empty() && name != model && !out.contains(&name) { + out.push(name); + } + } + Ok(out) +} + +/// The defaults a request starts from: the config block, then the shared settings on top +/// (`{**sampling_defaults, **shared}`). The speed-projection default comes the same way. +pub fn merged_defaults(config: &ConfigSampling, shared: &SharedDefaults) -> MergedDefaults { + MergedDefaults { + sampling: RequestSampling::overlay(&config.sampling, &shared.sampling()), + experimental_speed_projection: shared + .experimental_speed_projection + .or(config.experimental_speed_projection), + } +} + +impl MergedDefaults { + /// `default_generation_settings.params` of `GET /props` (llama-server names). + pub fn props_params(&self, shared: &SharedDefaults) -> Value { + let mut params = Map::new(); + let s = &self.sampling; + let mut put = |name: &str, value: Option| { + if let Some(v) = value { + params.insert(name.to_owned(), v); + } + }; + put("temperature", s.temperature.map(float_value)); + put("top_p", s.top_p.map(float_value)); + put("top_k", s.top_k.map(Value::from)); + put("min_p", s.min_p.map(float_value)); + put("seed", s.seed.map(Value::from)); + put("repeat_penalty", s.repetition_penalty.map(float_value)); + put("presence_penalty", s.presence_penalty.map(float_value)); + put("frequency_penalty", s.frequency_penalty.map(float_value)); + put("repeat_last_n", s.penalty_last_n.map(Value::from)); + params.insert( + "n_predict".into(), + shared.max_tokens.map_or(Value::from(-1), Value::from), + ); + Value::Object(params) + } +} + +/// `with_shared`, `max_tokens` half: the shared limit when the request has none of its own. +pub fn shared_max_tokens(request_max: Option, shared: &SharedDefaults) -> Option { + match request_max { + Some(n) if n > 0 => Some(n), + _ => shared.max_tokens.or(request_max), + } +} diff --git a/crates/tokenizer/src/fast.rs b/crates/tokenizer/src/fast.rs index b8014618..48ee1ff2 100644 --- a/crates/tokenizer/src/fast.rs +++ b/crates/tokenizer/src/fast.rs @@ -23,25 +23,6 @@ const NUMBER: u8 = 4; const SPACE: u8 = 8; const LETTER_OR_MARK: u8 = LETTER | MARK; -fn unicode_ranges(pattern: &str) -> Result, String> { - let hir = ParserBuilder::new() - .build() - .parse(pattern) - .map_err(|e| e.to_string())?; - match hir.kind() { - HirKind::Class(Class::Unicode(class)) => Ok(class - .iter() - .map(|range| (range.start() as u32, range.end() as u32)) - .collect()), - _ => Err(format!("{pattern} is not a Unicode class")), - } -} - -fn contains(ranges: &[(u32, u32)], code: u32) -> bool { - let at = ranges.partition_point(|&(start, _)| start <= code); - at > 0 && ranges[at - 1].1 >= code -} - /// Unicode classes of the pre-tokenizer pattern, as flag bits per scalar value. pub struct Classes { ascii: [u8; 128], @@ -49,165 +30,6 @@ pub struct Classes { flags: Vec, } -impl Classes { - pub fn new() -> Result { - let sets = [ - (LETTER, unicode_ranges(r"\p{L}")?), - (MARK, unicode_ranges(r"\p{M}")?), - (NUMBER, unicode_ranges(r"\p{N}")?), - (SPACE, unicode_ranges(r"\s")?), - ]; - let flags_of = |code: u32| { - sets.iter() - .filter(|(_, ranges)| contains(ranges, code)) - .fold(0u8, |bits, (flag, _)| bits | flag) - }; - let mut ascii = [0u8; 128]; - for (code, slot) in ascii.iter_mut().enumerate() { - *slot = flags_of(code as u32); - } - let mut bounds = vec![0u32]; - for (_, ranges) in &sets { - for &(start, end) in ranges { - bounds.push(start); - bounds.push(end + 1); - } - } - bounds.sort_unstable(); - bounds.dedup(); - bounds.retain(|&b| b <= 0x10FFFF); - let flags = bounds.iter().map(|&start| flags_of(start)).collect(); - Ok(Self { - ascii, - starts: bounds, - flags, - }) - } - - #[inline] - fn flags_of(&self, c: char) -> u8 { - let code = c as u32; - if code < 128 { - self.ascii[code as usize] - } else { - let at = self.starts.partition_point(|&start| start <= code); - self.flags[at - 1] - } - } - - /// The character at byte offset `i`: (class flags, char, byte length). - #[inline] - fn at(&self, text: &str, i: usize) -> Option<(u8, char, usize)> { - let byte = *text.as_bytes().get(i)?; - if byte < 128 { - Some((self.ascii[byte as usize], byte as char, 1)) - } else { - let c = text[i..].chars().next()?; - Some((self.flags_of(c), c, c.len_utf8())) - } - } - - #[inline] - fn letters_end(&self, text: &str, mut i: usize) -> usize { - while let Some((flags, _, len)) = self.at(text, i) { - if flags & LETTER_OR_MARK == 0 { - break; - } - i += len; - } - i - } - - /// End of the pre-token that starts at byte `i` (`i < text.len()`), for the pattern - /// - /// ```text - /// (?:'[sS]|'[tT]|'[rR][eE]|'[vV][eE]|'[mM]|'[lL][lL]|'[dD]) - /// |[^\r\n\p{L}\p{N}]?[\p{L}\p{M}]+ - /// |\p{N} - /// | ?[^\s\p{L}\p{M}\p{N}]+[\r\n]* - /// |\s*[\r\n]+ - /// |\s+(?!\S) - /// |\s+ - /// ``` - /// - /// with leftmost-first alternation and backtracking quantifiers. Every scalar value falls in exactly one of letter/mark, - /// number, symbol (none of the three and not white space) or white space, so some alternative always matches. - pub fn piece_end(&self, text: &str, i: usize) -> usize { - let bytes = text.as_bytes(); - let (flags, c, len) = self.at(text, i).expect("piece_end past the end"); - // 1: contractions - if c == '\'' { - let at = |k: usize| bytes.get(i + k).copied(); - match at(1) { - Some(b's' | b'S' | b't' | b'T' | b'm' | b'M' | b'd' | b'D') => return i + 2, - Some(b'r' | b'R' | b'v' | b'V') if matches!(at(2), Some(b'e' | b'E')) => { - return i + 3; - } - Some(b'l' | b'L') if matches!(at(2), Some(b'l' | b'L')) => return i + 3, - _ => {} - } - } - // 2: [^\r\n\p{L}\p{N}]?[\p{L}\p{M}]+ (a mark is both a possible prefix and a letter; either reading ends in the same place) - if flags & LETTER_OR_MARK != 0 { - return self.letters_end(text, i + len); - } - if c != '\r' - && c != '\n' - && flags & (LETTER | NUMBER) == 0 - && let Some((next, _, _)) = self.at(text, i + len) - && next & LETTER_OR_MARK != 0 - { - return self.letters_end(text, i + len); - } - // 3: \p{N} - if flags & NUMBER != 0 { - return i + len; - } - // 4: ?[^\s\p{L}\p{M}\p{N}]+[\r\n]* - let start = if c == ' ' { i + 1 } else { i }; - if let Some((first, _, _)) = self.at(text, start) - && first & (SPACE | LETTER | MARK | NUMBER) == 0 - { - let mut end = start; - while let Some((f, _, l)) = self.at(text, end) { - if f & (SPACE | LETTER | MARK | NUMBER) != 0 { - break; - } - end += l; - } - while matches!(bytes.get(end), Some(b'\r' | b'\n')) { - end += 1; - } - return end; - } - // 5-7: white space. \s*[\r\n]+ ends at the last line break of the run; \s+(?!\S) gives the run back one character - // unless the text ends; \s+ takes a lone character. - debug_assert!(flags & SPACE != 0); - let mut end = i; - let mut last_break = 0; - let mut last_len = 0; - let mut count = 0; - while let Some((f, ch, l)) = self.at(text, end) { - if f & SPACE == 0 { - break; - } - end += l; - last_len = l; - count += 1; - if ch == '\r' || ch == '\n' { - last_break = end; - } - } - if last_break > 0 { - return last_break; - } - if end == text.len() || count < 2 { - return end; - } - end - last_len - } -} - const EMPTY: u64 = u64::MAX; /// `(left id, right id) -> (rank, merged id)`, open addressing with a multiplicative hash. @@ -217,50 +39,6 @@ struct PairTable { shift: u32, } -impl PairTable { - fn with_capacity(entries: usize) -> Self { - let slots = (entries * 2).max(16).next_power_of_two(); - Self { - keys: vec![EMPTY; slots], - values: vec![(0, 0); slots], - shift: 64 - slots.trailing_zeros(), - } - } - - #[inline] - fn slot(&self, key: u64) -> usize { - (key.wrapping_mul(0x9E37_79B9_7F4A_7C15) >> self.shift) as usize - } - - fn insert(&mut self, left: u32, right: u32, rank: u32, merged: u32) { - let key = (u64::from(left) << 32) | u64::from(right); - let mask = self.keys.len() - 1; - let mut at = self.slot(key); - while self.keys[at] != EMPTY { - at = (at + 1) & mask; - } - self.keys[at] = key; - self.values[at] = (rank, merged); - } - - #[inline] - fn get(&self, left: u32, right: u32) -> Option<(u32, u32)> { - let key = (u64::from(left) << 32) | u64::from(right); - let mask = self.keys.len() - 1; - let mut at = self.slot(key); - loop { - let stored = self.keys[at]; - if stored == key { - return Some(self.values[at]); - } - if stored == EMPTY { - return None; - } - at = (at + 1) & mask; - } - } -} - const NO_RANK: u32 = u32::MAX; pub struct Fast { @@ -269,167 +47,16 @@ pub struct Fast { byte_ids: [u32; 256], } -impl Fast { - /// `None` when the vocabulary is not one the id-based merge reproduces exactly (see the module notes). - pub fn build( - vocab: &HashMap, - merges: &[(String, String)], - byte_chars: &[char; 256], - ) -> Option { - let mut byte_ids = [0u32; 256]; - for (byte, ch) in byte_chars.iter().enumerate() { - byte_ids[byte] = *vocab.get(ch.to_string().as_str())?; - } - let mut pairs = PairTable::with_capacity(merges.len()); - let mut joined = String::new(); - for (rank, (left, right)) in merges.iter().enumerate() { - joined.clear(); - joined.push_str(left); - joined.push_str(right); - let merged = *vocab.get(joined.as_str())?; - pairs.insert( - *vocab.get(left.as_str())?, - *vocab.get(right.as_str())?, - u32::try_from(rank).ok()?, - merged, - ); - } - let classes = Classes::new().ok()?; - Some(Self { - classes, - pairs, - byte_ids, - }) - } - - /// Byte-level BPE of one pre-token. - pub fn encode_piece(&self, piece: &[u8], out: &mut Vec, scratch: &mut Scratch) { - if piece.len() == 1 { - out.push(self.byte_ids[piece[0] as usize]); - return; - } - let parts = &mut scratch.parts; - let ranks = &mut scratch.ranks; - parts.clear(); - parts.extend(piece.iter().map(|&byte| self.byte_ids[byte as usize])); - if parts.len() > 48 { - self.merge_long(parts); - out.extend_from_slice(parts); - return; - } - ranks.clear(); - for pair in parts.windows(2) { - ranks.push( - self.pairs - .get(pair[0], pair[1]) - .map_or(NO_RANK, |(rank, _)| rank), - ); - } - loop { - let mut best = NO_RANK; - let mut at = 0; - for (index, &rank) in ranks.iter().enumerate() { - if rank < best { - best = rank; - at = index; - } - } - if best == NO_RANK { - break; - } - let (_, merged) = self - .pairs - .get(parts[at], parts[at + 1]) - .expect("ranked pair is in the table"); - parts[at] = merged; - parts.remove(at + 1); - ranks.remove(at); - if at > 0 { - ranks[at - 1] = self - .pairs - .get(parts[at - 1], parts[at]) - .map_or(NO_RANK, |(rank, _)| rank); - } - if at + 1 < parts.len() { - ranks[at] = self - .pairs - .get(parts[at], parts[at + 1]) - .map_or(NO_RANK, |(rank, _)| rank); - } - } - out.extend_from_slice(parts); - } - - /// The linked-list and heap form for long pieces (the same merge order: lowest rank first, leftmost on ties). - fn merge_long(&self, parts: &mut Vec) { - use std::{cmp::Reverse, collections::BinaryHeap}; - type MergeQueue = BinaryHeap>; - let n = parts.len(); - let mut next: Vec = (1..=n).collect(); - let mut prev: Vec = (0..n as isize).map(|i| i - 1).collect(); - let mut alive = vec![true; n]; - let mut version = vec![0u32; n]; - let mut queue: MergeQueue = BinaryHeap::new(); - let push = |queue: &mut MergeQueue, - parts: &[u32], - next: &[usize], - version: &[u32], - left: usize| { - let right = next[left]; - if right < n - && let Some((rank, _)) = self.pairs.get(parts[left], parts[right]) - { - queue.push(Reverse(( - rank, - left as u32, - right as u32, - version[left], - version[right], - ))); - } - }; - for left in 0..n.saturating_sub(1) { - push(&mut queue, parts, &next, &version, left); - } - while let Some(Reverse((_, left, right, left_version, right_version))) = queue.pop() { - let (left, right) = (left as usize, right as usize); - if !alive[left] - || !alive[right] - || next[left] != right - || version[left] != left_version - || version[right] != right_version - { - continue; - } - let (_, merged) = self - .pairs - .get(parts[left], parts[right]) - .expect("queued pair is in the table"); - parts[left] = merged; - alive[right] = false; - next[left] = next[right]; - version[left] += 1; - if next[left] < n { - prev[next[left]] = left as isize; - } - push(&mut queue, parts, &next, &version, left); - if prev[left] >= 0 { - push(&mut queue, parts, &next, &version, prev[left] as usize); - } - } - let mut result = Vec::with_capacity(n); - let mut current = 0usize; - while current < n { - result.push(parts[current]); - current = next[current]; - } - *parts = result; - } -} - /// Reusable buffers of one encoding call. #[derive(Default)] pub struct Scratch { parts: Vec, ranks: Vec, } + +mod unicode_ranges; +#[allow(unused_imports)] +pub use unicode_ranges::*; +mod impl_fast; +#[allow(unused_imports)] +pub use impl_fast::*; diff --git a/crates/tokenizer/src/fast/impl_fast.rs b/crates/tokenizer/src/fast/impl_fast.rs new file mode 100644 index 00000000..77bb65b4 --- /dev/null +++ b/crates/tokenizer/src/fast/impl_fast.rs @@ -0,0 +1,162 @@ +//! Moved out of the parent module by STRA-338: impl Fast. + +#[allow(unused_imports)] +use super::*; + +impl Fast { + /// `None` when the vocabulary is not one the id-based merge reproduces exactly (see the module notes). + pub fn build( + vocab: &HashMap, + merges: &[(String, String)], + byte_chars: &[char; 256], + ) -> Option { + let mut byte_ids = [0u32; 256]; + for (byte, ch) in byte_chars.iter().enumerate() { + byte_ids[byte] = *vocab.get(ch.to_string().as_str())?; + } + let mut pairs = PairTable::with_capacity(merges.len()); + let mut joined = String::new(); + for (rank, (left, right)) in merges.iter().enumerate() { + joined.clear(); + joined.push_str(left); + joined.push_str(right); + let merged = *vocab.get(joined.as_str())?; + pairs.insert( + *vocab.get(left.as_str())?, + *vocab.get(right.as_str())?, + u32::try_from(rank).ok()?, + merged, + ); + } + let classes = Classes::new().ok()?; + Some(Self { + classes, + pairs, + byte_ids, + }) + } + + /// Byte-level BPE of one pre-token. + pub fn encode_piece(&self, piece: &[u8], out: &mut Vec, scratch: &mut Scratch) { + if piece.len() == 1 { + out.push(self.byte_ids[piece[0] as usize]); + return; + } + let parts = &mut scratch.parts; + let ranks = &mut scratch.ranks; + parts.clear(); + parts.extend(piece.iter().map(|&byte| self.byte_ids[byte as usize])); + if parts.len() > 48 { + self.merge_long(parts); + out.extend_from_slice(parts); + return; + } + ranks.clear(); + for pair in parts.windows(2) { + ranks.push( + self.pairs + .get(pair[0], pair[1]) + .map_or(NO_RANK, |(rank, _)| rank), + ); + } + loop { + let mut best = NO_RANK; + let mut at = 0; + for (index, &rank) in ranks.iter().enumerate() { + if rank < best { + best = rank; + at = index; + } + } + if best == NO_RANK { + break; + } + let (_, merged) = self + .pairs + .get(parts[at], parts[at + 1]) + .expect("ranked pair is in the table"); + parts[at] = merged; + parts.remove(at + 1); + ranks.remove(at); + if at > 0 { + ranks[at - 1] = self + .pairs + .get(parts[at - 1], parts[at]) + .map_or(NO_RANK, |(rank, _)| rank); + } + if at + 1 < parts.len() { + ranks[at] = self + .pairs + .get(parts[at], parts[at + 1]) + .map_or(NO_RANK, |(rank, _)| rank); + } + } + out.extend_from_slice(parts); + } + + /// The linked-list and heap form for long pieces (the same merge order: lowest rank first, leftmost on ties). + pub(super) fn merge_long(&self, parts: &mut Vec) { + use std::{cmp::Reverse, collections::BinaryHeap}; + type MergeQueue = BinaryHeap>; + let n = parts.len(); + let mut next: Vec = (1..=n).collect(); + let mut prev: Vec = (0..n as isize).map(|i| i - 1).collect(); + let mut alive = vec![true; n]; + let mut version = vec![0u32; n]; + let mut queue: MergeQueue = BinaryHeap::new(); + let push = |queue: &mut MergeQueue, + parts: &[u32], + next: &[usize], + version: &[u32], + left: usize| { + let right = next[left]; + if right < n + && let Some((rank, _)) = self.pairs.get(parts[left], parts[right]) + { + queue.push(Reverse(( + rank, + left as u32, + right as u32, + version[left], + version[right], + ))); + } + }; + for left in 0..n.saturating_sub(1) { + push(&mut queue, parts, &next, &version, left); + } + while let Some(Reverse((_, left, right, left_version, right_version))) = queue.pop() { + let (left, right) = (left as usize, right as usize); + if !alive[left] + || !alive[right] + || next[left] != right + || version[left] != left_version + || version[right] != right_version + { + continue; + } + let (_, merged) = self + .pairs + .get(parts[left], parts[right]) + .expect("queued pair is in the table"); + parts[left] = merged; + alive[right] = false; + next[left] = next[right]; + version[left] += 1; + if next[left] < n { + prev[next[left]] = left as isize; + } + push(&mut queue, parts, &next, &version, left); + if prev[left] >= 0 { + push(&mut queue, parts, &next, &version, prev[left] as usize); + } + } + let mut result = Vec::with_capacity(n); + let mut current = 0usize; + while current < n { + result.push(parts[current]); + current = next[current]; + } + *parts = result; + } +} diff --git a/crates/tokenizer/src/fast/unicode_ranges.rs b/crates/tokenizer/src/fast/unicode_ranges.rs new file mode 100644 index 00000000..4e35afe9 --- /dev/null +++ b/crates/tokenizer/src/fast/unicode_ranges.rs @@ -0,0 +1,226 @@ +//! Moved out of the parent module by STRA-338: fn unicode_ranges, fn contains, impl Classes, impl PairTable. + +#[allow(unused_imports)] +use super::*; + +pub(super) fn unicode_ranges(pattern: &str) -> Result, String> { + let hir = ParserBuilder::new() + .build() + .parse(pattern) + .map_err(|e| e.to_string())?; + match hir.kind() { + HirKind::Class(Class::Unicode(class)) => Ok(class + .iter() + .map(|range| (range.start() as u32, range.end() as u32)) + .collect()), + _ => Err(format!("{pattern} is not a Unicode class")), + } +} + +pub(super) fn contains(ranges: &[(u32, u32)], code: u32) -> bool { + let at = ranges.partition_point(|&(start, _)| start <= code); + at > 0 && ranges[at - 1].1 >= code +} + +impl Classes { + pub fn new() -> Result { + let sets = [ + (LETTER, unicode_ranges(r"\p{L}")?), + (MARK, unicode_ranges(r"\p{M}")?), + (NUMBER, unicode_ranges(r"\p{N}")?), + (SPACE, unicode_ranges(r"\s")?), + ]; + let flags_of = |code: u32| { + sets.iter() + .filter(|(_, ranges)| contains(ranges, code)) + .fold(0u8, |bits, (flag, _)| bits | flag) + }; + let mut ascii = [0u8; 128]; + for (code, slot) in ascii.iter_mut().enumerate() { + *slot = flags_of(code as u32); + } + let mut bounds = vec![0u32]; + for (_, ranges) in &sets { + for &(start, end) in ranges { + bounds.push(start); + bounds.push(end + 1); + } + } + bounds.sort_unstable(); + bounds.dedup(); + bounds.retain(|&b| b <= 0x10FFFF); + let flags = bounds.iter().map(|&start| flags_of(start)).collect(); + Ok(Self { + ascii, + starts: bounds, + flags, + }) + } + + #[inline] + pub(super) fn flags_of(&self, c: char) -> u8 { + let code = c as u32; + if code < 128 { + self.ascii[code as usize] + } else { + let at = self.starts.partition_point(|&start| start <= code); + self.flags[at - 1] + } + } + + /// The character at byte offset `i`: (class flags, char, byte length). + #[inline] + pub(super) fn at(&self, text: &str, i: usize) -> Option<(u8, char, usize)> { + let byte = *text.as_bytes().get(i)?; + if byte < 128 { + Some((self.ascii[byte as usize], byte as char, 1)) + } else { + let c = text[i..].chars().next()?; + Some((self.flags_of(c), c, c.len_utf8())) + } + } + + #[inline] + pub(super) fn letters_end(&self, text: &str, mut i: usize) -> usize { + while let Some((flags, _, len)) = self.at(text, i) { + if flags & LETTER_OR_MARK == 0 { + break; + } + i += len; + } + i + } + + /// End of the pre-token that starts at byte `i` (`i < text.len()`), for the pattern + /// + /// ```text + /// (?:'[sS]|'[tT]|'[rR][eE]|'[vV][eE]|'[mM]|'[lL][lL]|'[dD]) + /// |[^\r\n\p{L}\p{N}]?[\p{L}\p{M}]+ + /// |\p{N} + /// | ?[^\s\p{L}\p{M}\p{N}]+[\r\n]* + /// |\s*[\r\n]+ + /// |\s+(?!\S) + /// |\s+ + /// ``` + /// + /// with leftmost-first alternation and backtracking quantifiers. Every scalar value falls in exactly one of letter/mark, + /// number, symbol (none of the three and not white space) or white space, so some alternative always matches. + pub fn piece_end(&self, text: &str, i: usize) -> usize { + let bytes = text.as_bytes(); + let (flags, c, len) = self.at(text, i).expect("piece_end past the end"); + // 1: contractions + if c == '\'' { + let at = |k: usize| bytes.get(i + k).copied(); + match at(1) { + Some(b's' | b'S' | b't' | b'T' | b'm' | b'M' | b'd' | b'D') => return i + 2, + Some(b'r' | b'R' | b'v' | b'V') if matches!(at(2), Some(b'e' | b'E')) => { + return i + 3; + } + Some(b'l' | b'L') if matches!(at(2), Some(b'l' | b'L')) => return i + 3, + _ => {} + } + } + // 2: [^\r\n\p{L}\p{N}]?[\p{L}\p{M}]+ (a mark is both a possible prefix and a letter; either reading ends in the same place) + if flags & LETTER_OR_MARK != 0 { + return self.letters_end(text, i + len); + } + if c != '\r' + && c != '\n' + && flags & (LETTER | NUMBER) == 0 + && let Some((next, _, _)) = self.at(text, i + len) + && next & LETTER_OR_MARK != 0 + { + return self.letters_end(text, i + len); + } + // 3: \p{N} + if flags & NUMBER != 0 { + return i + len; + } + // 4: ?[^\s\p{L}\p{M}\p{N}]+[\r\n]* + let start = if c == ' ' { i + 1 } else { i }; + if let Some((first, _, _)) = self.at(text, start) + && first & (SPACE | LETTER | MARK | NUMBER) == 0 + { + let mut end = start; + while let Some((f, _, l)) = self.at(text, end) { + if f & (SPACE | LETTER | MARK | NUMBER) != 0 { + break; + } + end += l; + } + while matches!(bytes.get(end), Some(b'\r' | b'\n')) { + end += 1; + } + return end; + } + // 5-7: white space. \s*[\r\n]+ ends at the last line break of the run; \s+(?!\S) gives the run back one character + // unless the text ends; \s+ takes a lone character. + debug_assert!(flags & SPACE != 0); + let mut end = i; + let mut last_break = 0; + let mut last_len = 0; + let mut count = 0; + while let Some((f, ch, l)) = self.at(text, end) { + if f & SPACE == 0 { + break; + } + end += l; + last_len = l; + count += 1; + if ch == '\r' || ch == '\n' { + last_break = end; + } + } + if last_break > 0 { + return last_break; + } + if end == text.len() || count < 2 { + return end; + } + end - last_len + } +} + +impl PairTable { + pub(super) fn with_capacity(entries: usize) -> Self { + let slots = (entries * 2).max(16).next_power_of_two(); + Self { + keys: vec![EMPTY; slots], + values: vec![(0, 0); slots], + shift: 64 - slots.trailing_zeros(), + } + } + + #[inline] + pub(super) fn slot(&self, key: u64) -> usize { + (key.wrapping_mul(0x9E37_79B9_7F4A_7C15) >> self.shift) as usize + } + + pub(super) fn insert(&mut self, left: u32, right: u32, rank: u32, merged: u32) { + let key = (u64::from(left) << 32) | u64::from(right); + let mask = self.keys.len() - 1; + let mut at = self.slot(key); + while self.keys[at] != EMPTY { + at = (at + 1) & mask; + } + self.keys[at] = key; + self.values[at] = (rank, merged); + } + + #[inline] + pub(super) fn get(&self, left: u32, right: u32) -> Option<(u32, u32)> { + let key = (u64::from(left) << 32) | u64::from(right); + let mask = self.keys.len() - 1; + let mut at = self.slot(key); + loop { + let stored = self.keys[at]; + if stored == key { + return Some(self.values[at]); + } + if stored == EMPTY { + return None; + } + at = (at + 1) & mask; + } + } +} diff --git a/crates/tokenizer/src/gguf_bpe.rs b/crates/tokenizer/src/gguf_bpe.rs index 7fc82bed..b072f24c 100644 --- a/crates/tokenizer/src/gguf_bpe.rs +++ b/crates/tokenizer/src/gguf_bpe.rs @@ -40,40 +40,6 @@ pub enum TokenizerError { Unsupported(String), } -impl fmt::Display for TokenizerError { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - match self { - Self::Missing(what) => write!(f, "tokenizer data missing: {what}"), - Self::Invalid(what) => write!(f, "invalid tokenizer data: {what}"), - Self::Unsupported(what) => write!(f, "unsupported tokenizer: {what}"), - } - } -} - -impl std::error::Error for TokenizerError {} - -/// The GPT-2 byte-to-character alphabet, indexed by byte (tests and tools). -pub fn byte_alphabet() -> [char; 256] { - byte_chars() -} - -/// The GPT-2 byte-to-character map: printable bytes map to themselves, the others to 256 and up. -fn byte_chars() -> [char; 256] { - let mut table = ['\0'; 256]; - let mut next = 256u32; - for (b, slot) in table.iter_mut().enumerate() { - let printable = matches!(b, 33..=126 | 161..=172 | 174..=255); - *slot = if printable { - char::from_u32(b as u32).expect("latin-1 scalar") - } else { - let c = char::from_u32(next).expect("scalar below the surrogates"); - next += 1; - c - }; - } - table -} - pub struct GgufBpe { /// Token text in the byte-as-character form, indexed by id. tokens: Vec, @@ -91,348 +57,21 @@ pub struct GgufBpe { pub pad: Option, } -impl GgufBpe { - /// Read the tokenizer from the metadata of a GGUF file. - pub fn from_gguf(g: &Gguf) -> Result { - match g.get_str("tokenizer.ggml.model") { - Some("gpt2") => {} - other => return Err(TokenizerError::Unsupported(format!("model {other:?}"))), - } - match g.get_str("tokenizer.ggml.pre") { - Some("gpt-4o") => {} - other => { - return Err(TokenizerError::Unsupported(format!( - "pre-tokenizer {other:?}" - ))); - } - } - let strings = |key: &str| -> Result, TokenizerError> { - g.get(key) - .and_then(Value::as_array) - .ok_or_else(|| TokenizerError::Missing(key.into()))? - .iter() - .map(|v| { - v.as_str() - .ok_or_else(|| TokenizerError::Invalid(format!("{key}: not a string"))) - }) - .collect() - }; - let tokens = strings("tokenizer.ggml.tokens")?; - let merges = strings("tokenizer.ggml.merges")?; - let types: Vec = match g.get("tokenizer.ggml.token_type") { - Some(Value::Array(a)) => a - .iter() - .map(|v| match v { - Value::I32(t) => Ok(i64::from(*t)), - Value::U32(t) => Ok(i64::from(*t)), - _ => Err(TokenizerError::Invalid("token_type: not an integer".into())), - }) - .collect::>()?, - _ => vec![1; tokens.len()], - }; - let special_id = |key: &str| g.get_u64(key).and_then(|v| u32::try_from(v).ok()); - Self::from_parts( - &tokens, - &types, - &merges, - special_id("tokenizer.ggml.bos_token_id"), - special_id("tokenizer.ggml.eos_token_id"), - special_id("tokenizer.ggml.padding_token_id"), - ) - } - - /// Build from the vocabulary pieces (`merges` are `"left right"` strings). - pub fn from_parts( - tokens: &[&str], - types: &[i64], - merges: &[&str], - bos: Option, - eos: Option, - pad: Option, - ) -> Result { - if tokens.is_empty() || types.len() != tokens.len() { - return Err(TokenizerError::Invalid( - "token and type counts differ or are zero".into(), - )); - } - let mut ids = HashMap::with_capacity(tokens.len()); - for (id, token) in tokens.iter().enumerate() { - if ids.insert((*token).to_owned(), id as u32).is_some() { - return Err(TokenizerError::Invalid(format!( - "duplicate token {token:?}" - ))); - } - } - let byte_char = byte_chars(); - let char_byte: HashMap = byte_char - .iter() - .enumerate() - .map(|(b, c)| (*c, b as u8)) - .collect(); - let mut byte_id = [u32::MAX; 256]; - for (b, c) in byte_char.iter().enumerate() { - let mut buf = [0u8; 4]; - byte_id[b] = *ids.get(c.encode_utf8(&mut buf) as &str).ok_or_else(|| { - TokenizerError::Invalid(format!("vocabulary lacks the token for byte {b}")) - })?; - } - let mut merge_map = HashMap::with_capacity(merges.len()); - for (rank, merge) in merges.iter().enumerate() { - let (left, right) = merge - .split_once(' ') - .ok_or_else(|| TokenizerError::Invalid(format!("merge {merge:?}")))?; - let (Some(l), Some(r)) = (ids.get(left), ids.get(right)) else { - return Err(TokenizerError::Invalid(format!( - "merge {merge:?} names an unknown token" - ))); - }; - let Some(merged) = ids.get(&format!("{left}{right}")) else { - continue; // a merge whose result is not a token can never apply - }; - merge_map.entry((*l, *r)).or_insert((rank as u32, *merged)); - } - let is_special: Vec = types - .iter() - .map(|t| *t == TYPE_CONTROL || *t == TYPE_USER_DEFINED) - .collect(); - let matcher = |wanted: &dyn Fn(i64) -> bool| -> Result { - let ids: Vec = (0..tokens.len() as u32) - .filter(|i| wanted(types[*i as usize]) && !tokens[*i as usize].is_empty()) - .collect(); - if ids.is_empty() { - return Ok(None); - } - let literals: Vec<&str> = ids.iter().map(|i| tokens[*i as usize]).collect(); - let search = AhoCorasickBuilder::new() - .match_kind(MatchKind::LeftmostLongest) - .build(&literals) - .map_err(|e| TokenizerError::Invalid(format!("special tokens: {e}")))?; - Ok(Some((search, ids))) - }; - let specials = matcher(&|t| t == TYPE_CONTROL || t == TYPE_USER_DEFINED)?; - let pattern = Regex::new(GPT4O_PATTERN) - .map_err(|e| TokenizerError::Invalid(format!("pre-tokenizer expression: {e}")))?; - for id in [bos, eos, pad].into_iter().flatten() { - if id as usize >= tokens.len() { - return Err(TokenizerError::Invalid(format!("special id {id}"))); - } - } - Ok(Self { - tokens: tokens.iter().map(|t| (*t).to_owned()).collect(), - ids, - merges: merge_map, - pattern, - specials, - is_special, - byte_char, - char_byte, - byte_id, - bos, - eos, - pad, - }) - } - - pub fn vocab_size(&self) -> usize { - self.tokens.len() - } - - /// Id of the token with exactly this text (special tokens included), if any. - pub fn token_id(&self, text: &str) -> Option { - self.ids.get(text).copied() - } - - pub fn is_special(&self, id: u32) -> bool { - self.is_special.get(id as usize).copied().unwrap_or(false) - } - - /// Token ids of `text`. With `parse_special`, occurrences of special-token text (such as - /// `<|endoftext|>` or `<|start|>`) become those tokens. Without it NO special token is ever produced, - /// so text that came from a user cannot forge role or channel markers. (llama.cpp's server still - /// turns some Harmony markers into tokens in that mode; Leleka deliberately does not.) - pub fn encode(&self, text: &str, parse_special: bool) -> Vec { - let mut out = Vec::new(); - let matcher = if parse_special { &self.specials } else { &None }; - match matcher { - Some((search, ids)) => { - let mut last = 0; - for m in search.find_iter(text) { - self.encode_plain(&text[last..m.start()], &mut out); - out.push(ids[m.pattern().as_usize()]); - last = m.end(); - } - self.encode_plain(&text[last..], &mut out); - } - None => self.encode_plain(text, &mut out), - } - out - } - - fn encode_plain(&self, text: &str, out: &mut Vec) { - if text.is_empty() { - return; - } - let mut position = 0; - for piece in self.pattern.find_iter(text) { - // an expression error cannot happen for these inputs; treat the rest as one piece if it does - let Ok(m) = piece else { - self.merge_piece(&text[position..], out); - return; - }; - if m.start() > position { - self.merge_piece(&text[position..m.start()], out); // not matched by any alternative - } - self.merge_piece(m.as_str(), out); - position = m.end(); - } - if position < text.len() { - self.merge_piece(&text[position..], out); - } - } - - /// Byte-pair merge of one pre-tokenized piece. - fn merge_piece(&self, piece: &str, out: &mut Vec) { - let mut ids: Vec = piece - .bytes() - .map(|b| self.byte_id[usize::from(b)]) - .collect(); - let n = ids.len(); - if n <= 1 { - out.extend(ids); - return; - } - let mut prev: Vec = (0..n).map(|i| i.wrapping_sub(1)).collect(); - let mut next: Vec = (1..=n).collect(); // n marks the end - let mut alive = vec![true; n]; - let mut heap = BinaryHeap::new(); - let push = |heap: &mut BinaryHeap>, - left: usize, - right: usize, - ids: &[u32]| { - if let Some((rank, _)) = self.merges.get(&(ids[left], ids[right])) { - heap.push(Reverse((*rank, left, ids[left], ids[right]))); - } - }; - for i in 0..n - 1 { - push(&mut heap, i, i + 1, &ids); - } - while let Some(Reverse((_, left, left_id, right_id))) = heap.pop() { - let right = next[left]; - // stale entries: a symbol changed or died since the pair was queued - if !alive[left] || right >= n || !alive[right] { - continue; - } - if ids[left] != left_id || ids[right] != right_id { - continue; - } - let (_, merged) = self.merges[&(left_id, right_id)]; - ids[left] = merged; - alive[right] = false; - next[left] = next[right]; - if next[right] < n { - prev[next[right]] = left; - } - if prev[left] != usize::MAX { - push(&mut heap, prev[left], left, &ids); - } - if next[left] < n { - push(&mut heap, left, next[left], &ids); - } - } - let mut i = 0; - while i < n { - out.push(ids[i]); - i = next[i]; - } - } - - /// The bytes the tokens stand for. Special tokens contribute their literal text. - pub fn decode_bytes(&self, ids: &[u32]) -> Vec { - let mut out = Vec::new(); - for id in ids { - let Some(token) = self.tokens.get(*id as usize) else { - continue; - }; - if self.is_special[*id as usize] { - out.extend_from_slice(token.as_bytes()); - } else { - out.extend( - token - .chars() - .map(|c| self.char_byte.get(&c).copied().unwrap_or(b'?')), - ); - } - } - out - } - - /// The text of `ids`, with invalid UTF-8 (a token run that splits a character) replaced. - pub fn decode(&self, ids: &[u32]) -> String { - String::from_utf8_lossy(&self.decode_bytes(ids)).into_owned() - } - - /// The byte-as-character form of a token, for diagnostics. - pub fn token_text(&self, id: u32) -> Option<&str> { - self.tokens.get(id as usize).map(String::as_str) - } - - /// The character the GPT-2 map gives a byte. - pub fn byte_char(&self, byte: u8) -> char { - self.byte_char[usize::from(byte)] - } -} - /// Turns a stream of token bytes into text deltas that never split a UTF-8 character. #[derive(Default)] pub struct Utf8Stream { pending: Vec, } -impl Utf8Stream { - /// Add bytes; returns the longest valid prefix of everything pending (invalid sequences become - /// U+FFFD) and keeps an incomplete trailing character for the next call. - pub fn push(&mut self, bytes: &[u8]) -> String { - self.pending.extend_from_slice(bytes); - let mut out = String::new(); - let mut rest = &self.pending[..]; - loop { - match std::str::from_utf8(rest) { - Ok(s) => { - out.push_str(s); - rest = &[]; - break; - } - Err(e) => { - let (good, bad) = rest.split_at(e.valid_up_to()); - out.push_str(std::str::from_utf8(good).expect("validated prefix")); - match e.error_len() { - Some(len) => { - out.push('\u{FFFD}'); - rest = &bad[len..]; - } - None => { - rest = bad; // incomplete at the end: wait for more bytes - break; - } - } - } - } - } - self.pending = rest.to_vec(); - out - } - - /// Flush an incomplete trailing character as U+FFFD. - pub fn finish(&mut self) -> String { - let out = if self.pending.is_empty() { - String::new() - } else { - String::from_utf8_lossy(&self.pending).into_owned() - }; - self.pending.clear(); - out - } -} - #[cfg(test)] mod tests; + +mod impl_fmt_display_for; +#[allow(unused_imports)] +pub use impl_fmt_display_for::*; +mod impl_ggufbpe; +#[allow(unused_imports)] +pub use impl_ggufbpe::*; +mod impl_utf8stream; +#[allow(unused_imports)] +pub use impl_utf8stream::*; diff --git a/crates/tokenizer/src/gguf_bpe/impl_fmt_display_for.rs b/crates/tokenizer/src/gguf_bpe/impl_fmt_display_for.rs new file mode 100644 index 00000000..a338f6fc --- /dev/null +++ b/crates/tokenizer/src/gguf_bpe/impl_fmt_display_for.rs @@ -0,0 +1,38 @@ +//! Moved out of the parent module by STRA-338: impl fmt_Display_for, impl std_error_Error, fn byte_alphabet, fn byte_chars. + +#[allow(unused_imports)] +use super::*; + +impl fmt::Display for TokenizerError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Self::Missing(what) => write!(f, "tokenizer data missing: {what}"), + Self::Invalid(what) => write!(f, "invalid tokenizer data: {what}"), + Self::Unsupported(what) => write!(f, "unsupported tokenizer: {what}"), + } + } +} + +impl std::error::Error for TokenizerError {} + +/// The GPT-2 byte-to-character alphabet, indexed by byte (tests and tools). +pub fn byte_alphabet() -> [char; 256] { + byte_chars() +} + +/// The GPT-2 byte-to-character map: printable bytes map to themselves, the others to 256 and up. +pub(super) fn byte_chars() -> [char; 256] { + let mut table = ['\0'; 256]; + let mut next = 256u32; + for (b, slot) in table.iter_mut().enumerate() { + let printable = matches!(b, 33..=126 | 161..=172 | 174..=255); + *slot = if printable { + char::from_u32(b as u32).expect("latin-1 scalar") + } else { + let c = char::from_u32(next).expect("scalar below the surrogates"); + next += 1; + c + }; + } + table +} diff --git a/crates/tokenizer/src/gguf_bpe/impl_ggufbpe.rs b/crates/tokenizer/src/gguf_bpe/impl_ggufbpe.rs new file mode 100644 index 00000000..61cb95c8 --- /dev/null +++ b/crates/tokenizer/src/gguf_bpe/impl_ggufbpe.rs @@ -0,0 +1,295 @@ +//! Moved out of the parent module by STRA-338: impl GgufBpe. + +#[allow(unused_imports)] +use super::*; + +impl GgufBpe { + /// Read the tokenizer from the metadata of a GGUF file. + pub fn from_gguf(g: &Gguf) -> Result { + match g.get_str("tokenizer.ggml.model") { + Some("gpt2") => {} + other => return Err(TokenizerError::Unsupported(format!("model {other:?}"))), + } + match g.get_str("tokenizer.ggml.pre") { + Some("gpt-4o") => {} + other => { + return Err(TokenizerError::Unsupported(format!( + "pre-tokenizer {other:?}" + ))); + } + } + let strings = |key: &str| -> Result, TokenizerError> { + g.get(key) + .and_then(Value::as_array) + .ok_or_else(|| TokenizerError::Missing(key.into()))? + .iter() + .map(|v| { + v.as_str() + .ok_or_else(|| TokenizerError::Invalid(format!("{key}: not a string"))) + }) + .collect() + }; + let tokens = strings("tokenizer.ggml.tokens")?; + let merges = strings("tokenizer.ggml.merges")?; + let types: Vec = match g.get("tokenizer.ggml.token_type") { + Some(Value::Array(a)) => a + .iter() + .map(|v| match v { + Value::I32(t) => Ok(i64::from(*t)), + Value::U32(t) => Ok(i64::from(*t)), + _ => Err(TokenizerError::Invalid("token_type: not an integer".into())), + }) + .collect::>()?, + _ => vec![1; tokens.len()], + }; + let special_id = |key: &str| g.get_u64(key).and_then(|v| u32::try_from(v).ok()); + Self::from_parts( + &tokens, + &types, + &merges, + special_id("tokenizer.ggml.bos_token_id"), + special_id("tokenizer.ggml.eos_token_id"), + special_id("tokenizer.ggml.padding_token_id"), + ) + } + + /// Build from the vocabulary pieces (`merges` are `"left right"` strings). + pub fn from_parts( + tokens: &[&str], + types: &[i64], + merges: &[&str], + bos: Option, + eos: Option, + pad: Option, + ) -> Result { + if tokens.is_empty() || types.len() != tokens.len() { + return Err(TokenizerError::Invalid( + "token and type counts differ or are zero".into(), + )); + } + let mut ids = HashMap::with_capacity(tokens.len()); + for (id, token) in tokens.iter().enumerate() { + if ids.insert((*token).to_owned(), id as u32).is_some() { + return Err(TokenizerError::Invalid(format!( + "duplicate token {token:?}" + ))); + } + } + let byte_char = byte_chars(); + let char_byte: HashMap = byte_char + .iter() + .enumerate() + .map(|(b, c)| (*c, b as u8)) + .collect(); + let mut byte_id = [u32::MAX; 256]; + for (b, c) in byte_char.iter().enumerate() { + let mut buf = [0u8; 4]; + byte_id[b] = *ids.get(c.encode_utf8(&mut buf) as &str).ok_or_else(|| { + TokenizerError::Invalid(format!("vocabulary lacks the token for byte {b}")) + })?; + } + let mut merge_map = HashMap::with_capacity(merges.len()); + for (rank, merge) in merges.iter().enumerate() { + let (left, right) = merge + .split_once(' ') + .ok_or_else(|| TokenizerError::Invalid(format!("merge {merge:?}")))?; + let (Some(l), Some(r)) = (ids.get(left), ids.get(right)) else { + return Err(TokenizerError::Invalid(format!( + "merge {merge:?} names an unknown token" + ))); + }; + let Some(merged) = ids.get(&format!("{left}{right}")) else { + continue; // a merge whose result is not a token can never apply + }; + merge_map.entry((*l, *r)).or_insert((rank as u32, *merged)); + } + let is_special: Vec = types + .iter() + .map(|t| *t == TYPE_CONTROL || *t == TYPE_USER_DEFINED) + .collect(); + let matcher = |wanted: &dyn Fn(i64) -> bool| -> Result { + let ids: Vec = (0..tokens.len() as u32) + .filter(|i| wanted(types[*i as usize]) && !tokens[*i as usize].is_empty()) + .collect(); + if ids.is_empty() { + return Ok(None); + } + let literals: Vec<&str> = ids.iter().map(|i| tokens[*i as usize]).collect(); + let search = AhoCorasickBuilder::new() + .match_kind(MatchKind::LeftmostLongest) + .build(&literals) + .map_err(|e| TokenizerError::Invalid(format!("special tokens: {e}")))?; + Ok(Some((search, ids))) + }; + let specials = matcher(&|t| t == TYPE_CONTROL || t == TYPE_USER_DEFINED)?; + let pattern = Regex::new(GPT4O_PATTERN) + .map_err(|e| TokenizerError::Invalid(format!("pre-tokenizer expression: {e}")))?; + for id in [bos, eos, pad].into_iter().flatten() { + if id as usize >= tokens.len() { + return Err(TokenizerError::Invalid(format!("special id {id}"))); + } + } + Ok(Self { + tokens: tokens.iter().map(|t| (*t).to_owned()).collect(), + ids, + merges: merge_map, + pattern, + specials, + is_special, + byte_char, + char_byte, + byte_id, + bos, + eos, + pad, + }) + } + + pub fn vocab_size(&self) -> usize { + self.tokens.len() + } + + /// Id of the token with exactly this text (special tokens included), if any. + pub fn token_id(&self, text: &str) -> Option { + self.ids.get(text).copied() + } + + pub fn is_special(&self, id: u32) -> bool { + self.is_special.get(id as usize).copied().unwrap_or(false) + } + + /// Token ids of `text`. With `parse_special`, occurrences of special-token text (such as + /// `<|endoftext|>` or `<|start|>`) become those tokens. Without it NO special token is ever produced, + /// so text that came from a user cannot forge role or channel markers. (llama.cpp's server still + /// turns some Harmony markers into tokens in that mode; Leleka deliberately does not.) + pub fn encode(&self, text: &str, parse_special: bool) -> Vec { + let mut out = Vec::new(); + let matcher = if parse_special { &self.specials } else { &None }; + match matcher { + Some((search, ids)) => { + let mut last = 0; + for m in search.find_iter(text) { + self.encode_plain(&text[last..m.start()], &mut out); + out.push(ids[m.pattern().as_usize()]); + last = m.end(); + } + self.encode_plain(&text[last..], &mut out); + } + None => self.encode_plain(text, &mut out), + } + out + } + + pub(super) fn encode_plain(&self, text: &str, out: &mut Vec) { + if text.is_empty() { + return; + } + let mut position = 0; + for piece in self.pattern.find_iter(text) { + // an expression error cannot happen for these inputs; treat the rest as one piece if it does + let Ok(m) = piece else { + self.merge_piece(&text[position..], out); + return; + }; + if m.start() > position { + self.merge_piece(&text[position..m.start()], out); // not matched by any alternative + } + self.merge_piece(m.as_str(), out); + position = m.end(); + } + if position < text.len() { + self.merge_piece(&text[position..], out); + } + } + + /// Byte-pair merge of one pre-tokenized piece. + pub(super) fn merge_piece(&self, piece: &str, out: &mut Vec) { + let mut ids: Vec = piece + .bytes() + .map(|b| self.byte_id[usize::from(b)]) + .collect(); + let n = ids.len(); + if n <= 1 { + out.extend(ids); + return; + } + let mut prev: Vec = (0..n).map(|i| i.wrapping_sub(1)).collect(); + let mut next: Vec = (1..=n).collect(); // n marks the end + let mut alive = vec![true; n]; + let mut heap = BinaryHeap::new(); + let push = |heap: &mut BinaryHeap>, + left: usize, + right: usize, + ids: &[u32]| { + if let Some((rank, _)) = self.merges.get(&(ids[left], ids[right])) { + heap.push(Reverse((*rank, left, ids[left], ids[right]))); + } + }; + for i in 0..n - 1 { + push(&mut heap, i, i + 1, &ids); + } + while let Some(Reverse((_, left, left_id, right_id))) = heap.pop() { + let right = next[left]; + // stale entries: a symbol changed or died since the pair was queued + if !alive[left] || right >= n || !alive[right] { + continue; + } + if ids[left] != left_id || ids[right] != right_id { + continue; + } + let (_, merged) = self.merges[&(left_id, right_id)]; + ids[left] = merged; + alive[right] = false; + next[left] = next[right]; + if next[right] < n { + prev[next[right]] = left; + } + if prev[left] != usize::MAX { + push(&mut heap, prev[left], left, &ids); + } + if next[left] < n { + push(&mut heap, left, next[left], &ids); + } + } + let mut i = 0; + while i < n { + out.push(ids[i]); + i = next[i]; + } + } + + /// The bytes the tokens stand for. Special tokens contribute their literal text. + pub fn decode_bytes(&self, ids: &[u32]) -> Vec { + let mut out = Vec::new(); + for id in ids { + let Some(token) = self.tokens.get(*id as usize) else { + continue; + }; + if self.is_special[*id as usize] { + out.extend_from_slice(token.as_bytes()); + } else { + out.extend( + token + .chars() + .map(|c| self.char_byte.get(&c).copied().unwrap_or(b'?')), + ); + } + } + out + } + + /// The text of `ids`, with invalid UTF-8 (a token run that splits a character) replaced. + pub fn decode(&self, ids: &[u32]) -> String { + String::from_utf8_lossy(&self.decode_bytes(ids)).into_owned() + } + + /// The byte-as-character form of a token, for diagnostics. + pub fn token_text(&self, id: u32) -> Option<&str> { + self.tokens.get(id as usize).map(String::as_str) + } + + /// The character the GPT-2 map gives a byte. + pub fn byte_char(&self, byte: u8) -> char { + self.byte_char[usize::from(byte)] + } +} diff --git a/crates/tokenizer/src/gguf_bpe/impl_utf8stream.rs b/crates/tokenizer/src/gguf_bpe/impl_utf8stream.rs new file mode 100644 index 00000000..d5aa694c --- /dev/null +++ b/crates/tokenizer/src/gguf_bpe/impl_utf8stream.rs @@ -0,0 +1,50 @@ +//! Moved out of the parent module by STRA-338: impl Utf8Stream. + +#[allow(unused_imports)] +use super::*; + +impl Utf8Stream { + /// Add bytes; returns the longest valid prefix of everything pending (invalid sequences become + /// U+FFFD) and keeps an incomplete trailing character for the next call. + pub fn push(&mut self, bytes: &[u8]) -> String { + self.pending.extend_from_slice(bytes); + let mut out = String::new(); + let mut rest = &self.pending[..]; + loop { + match std::str::from_utf8(rest) { + Ok(s) => { + out.push_str(s); + rest = &[]; + break; + } + Err(e) => { + let (good, bad) = rest.split_at(e.valid_up_to()); + out.push_str(std::str::from_utf8(good).expect("validated prefix")); + match e.error_len() { + Some(len) => { + out.push('\u{FFFD}'); + rest = &bad[len..]; + } + None => { + rest = bad; // incomplete at the end: wait for more bytes + break; + } + } + } + } + } + self.pending = rest.to_vec(); + out + } + + /// Flush an incomplete trailing character as U+FFFD. + pub fn finish(&mut self) -> String { + let out = if self.pending.is_empty() { + String::new() + } else { + String::from_utf8_lossy(&self.pending).into_owned() + }; + self.pending.clear(); + out + } +} diff --git a/desktop-core/src/gateway.rs b/desktop-core/src/gateway.rs index 472084a0..eae0df55 100644 --- a/desktop-core/src/gateway.rs +++ b/desktop-core/src/gateway.rs @@ -63,257 +63,12 @@ struct Inner { // Bounded process-local ownership, never response text or prompts. owners: Mutex>, } -fn secret(name: &str) -> Result { - if name.is_empty() || !name.bytes().all(|c| c.is_ascii_alphanumeric() || c == b'_') { - return Err("invalid credential environment name".into()); - } - let value = std::env::var(name).map_err(|_| "credential environment variable is missing")?; - if value.len() < 16 || value.len() > 4096 || value.bytes().any(|c| c.is_ascii_control()) { - return Err("credential must contain 16..4096 non-control bytes".into()); - } - Ok(value) -} -impl Gateway { - pub(crate) async fn dispatch(&self, headers: HeaderMap, body: Bytes) -> Response { - responses(State(self.clone()), headers, body).await - } - pub(crate) fn ready_catalog(&self) -> Vec { - let ready: HashSet<_> = self - .0 - .pool - .snapshot() - .workers - .into_iter() - .filter(|w| w.ready) - .map(|w| w.id) - .collect(); - self.0 - .config - .deployments - .iter() - .filter(|d| ready.contains(&d.id)) - .map(|d| json!({"id":d.id,"object":"model","owned_by":"configured-pool"})) - .chain( - self.0 - .config - .aliases - .iter() - .filter(|(_, members)| members.iter().any(|m| ready.contains(m))) - .map(|(id, _)| json!({"id":id,"object":"model","owned_by":"configured-pool"})), - ) - .collect() - } - pub fn new(config: Config) -> Result { - let token = secret(&config.token_env)?; - Self::with_token(config, token) - } - /// Explicit token injection is useful for an embedding host and isolated tests. - pub fn with_token(config: Config, token: String) -> Result { - if config.schema_version != 1 - || !config.listen.ip().is_loopback() - || token.len() < 16 - || config.queue_timeout_ms == 0 - || config.queue_timeout_ms > 3_600_000 - || config.request_timeout_ms == 0 - || config.request_timeout_ms > 86_400_000 - || config.queue_limit > 64 - || config.aliases.len() > 256 - { - return Err("invalid gateway limits or non-loopback bind".into()); - } - let mut endpoints = HashSet::new(); - for d in &config.deployments { - let u = reqwest::Url::parse(&d.endpoint).map_err(|_| "invalid endpoint")?; - let ip = u - .host_str() - .unwrap_or("") - .trim_matches(['[', ']']) - .parse::() - .map_err(|_| "endpoint must use a loopback IP")?; - if !ip.is_loopback() - || u.scheme() != "http" - || u.path() != "/" - || u.query().is_some() - || u.fragment().is_some() - || !u.username().is_empty() - || u.password().is_some() - || !endpoints.insert(u.to_string()) - || d.model.is_empty() - || d.id.len() > 128 - { - return Err("invalid, duplicate or non-loopback endpoint".into()); - } - } - let ids: HashSet<_> = config.deployments.iter().map(|d| d.id.as_str()).collect(); - for (alias, members) in &config.aliases { - if alias.is_empty() - || ids.contains(alias.as_str()) - || members.is_empty() - || members.len() > 256 - || members.iter().any(|m| !ids.contains(m.as_str())) - { - return Err("invalid pool alias".into()); - } - } - let pool = Pool::new( - config - .deployments - .iter() - .map(|d| Worker { - id: d.id.clone(), - group: d.group.clone(), - slots: d.slots, - request_bytes: d.request_bytes, - }) - .collect(), - config - .groups - .iter() - .map(|g| ResourceGroup { - id: g.id.clone(), - slots: g.slots, - available_bytes: g.available_bytes, - }) - .collect(), - config.queue_limit, - ) - .map_err(|_| "invalid resource capacity")?; - let upstream_tokens = config - .deployments - .iter() - .map(|d| d.token_env.as_deref().map(secret).transpose()) - .collect::>()?; - let client = reqwest::Client::builder() - .no_proxy() - .redirect(reqwest::redirect::Policy::none()) - .connect_timeout(Duration::from_secs(5)) - .build() - .map_err(|_| "HTTP client initialization failed")?; - Ok(Self(Arc::new(Inner { - config, - pool, - token, - upstream_tokens, - client, - owners: Mutex::new(VecDeque::new()), - }))) - } - pub(crate) fn matches_credential(&self, token: &str) -> bool { - bool::from(token.as_bytes().ct_eq(self.0.token.as_bytes())) - } - pub(crate) fn clear_response_owners(&self) { - self.0.owners.lock().unwrap().clear(); - } - pub(crate) fn set_managed_ready(&self, ready: bool) { - for i in 0..self.0.config.deployments.len() { - let _ = self.0.pool.set_ready(i, ready); - } - } - pub(crate) fn idle(&self) -> bool { - let s = self.0.pool.snapshot(); - s.active == 0 && s.queued == 0 - } - pub fn router(&self) -> Router { - Router::new() - .route("/v1/models", get(models)) - .route("/v1/responses", post(responses)) - .route("/pool/status", get(status)) - .layer(DefaultBodyLimit::max(2 * 1024 * 1024)) - .with_state(self.clone()) - } - fn authorized(&self, h: &HeaderMap) -> bool { - h.get("authorization") - .and_then(|v| v.to_str().ok()) - .and_then(|s| s.strip_prefix("Bearer ")) - .is_some_and(|s| bool::from(s.as_bytes().ct_eq(self.0.token.as_bytes()))) - } - fn remember(&self, id: String, worker: usize) { - if id.is_empty() || id.len() > 256 { - return; - } - let mut owners = self.0.owners.lock().unwrap(); - // A collision is ambiguous; sentinel ownership rejects further continuations. - let owner = owners - .iter() - .find(|(key, _)| key == &id) - .map(|(_, w)| if *w == worker { worker } else { usize::MAX }) - .unwrap_or(worker); - owners.retain(|(key, _)| key != &id); - owners.push_back((id, owner)); - if owners.len() > 4096 { - owners.pop_front(); - } - } -} -fn error(code: StatusCode, kind: &str) -> Response { - let mut response = (code, Json(json!({"error":{"type":kind,"message":kind}}))).into_response(); - if code == StatusCode::TOO_MANY_REQUESTS { - response - .headers_mut() - .insert("retry-after", "1".parse().unwrap()); - } - response -} -async fn models(State(g): State, h: HeaderMap) -> Response { - if !g.authorized(&h) { - return error(StatusCode::UNAUTHORIZED, "unauthorized"); - } - let ids = - g.0.config - .deployments - .iter() - .map(|d| d.id.clone()) - .chain(g.0.config.aliases.keys().cloned()); - Json(json!({"object":"list","data":ids.map(|id|json!({"id":id,"object":"model","owned_by":"configured-pool"})).collect::>()})).into_response() -} -async fn status(State(g): State, h: HeaderMap) -> Response { - if !g.authorized(&h) { - return error(StatusCode::UNAUTHORIZED, "unauthorized"); - } - Json(json!({"schema_version":1,"pool":g.0.pool.snapshot()})).into_response() -} -fn required_caps(v: &Value, out: &mut HashSet<&'static str>) { - match v { - Value::Array(a) => { - for v in a { - required_caps(v, out) - } - } - Value::Object(m) => { - match m.get("type").and_then(Value::as_str) { - Some("input_image") => { - out.insert("image"); - } - Some("input_audio") => { - out.insert("audio"); - } - Some("input_file") => { - out.insert("file"); - } - _ => {} - } - for v in m.values() { - required_caps(v, out); - } - } - _ => {} - } -} struct InFlight { g: Gateway, worker: usize, lease: Option, complete: bool, } -impl Drop for InFlight { - fn drop(&mut self) { - // Client disconnect does not prove upstream stopped computing. Quarantine before releasing. - if !self.complete { - let _ = self.g.0.pool.set_ready(self.worker, false); - } - self.lease.take(); - } -} #[derive(Default)] struct Terminal { line: Vec, @@ -322,275 +77,13 @@ struct Terminal { complete: bool, response_id: Option, } -impl Terminal { - fn feed(&mut self, bytes: &[u8]) { - for b in bytes { - if *b == b'\n' { - let line = self.line.strip_suffix(b"\r").unwrap_or(&self.line); - if line.is_empty() { - if !self.overflow - && let Ok(v) = serde_json::from_slice::(&self.data) - && matches!( - v.get("type").and_then(Value::as_str), - Some("response.completed" | "response.failed" | "response.incomplete") - ) - { - self.complete = true; - self.response_id = v - .pointer("/response/id") - .and_then(Value::as_str) - .map(str::to_owned); - } - self.data.clear(); - self.overflow = false; - } else if !self.overflow - && let Some(data) = line.strip_prefix(b"data:") - { - if self.data.len() + data.len() + 1 > 1024 * 1024 { - self.overflow = true; - } else { - self.data.extend_from_slice(data); - self.data.push(b'\n'); - } - } - self.line.clear(); - } else if self.line.len() < 1024 * 1024 { - self.line.push(*b); - } else { - self.overflow = true; - } - } - } -} -async fn responses(State(g): State, h: HeaderMap, body: Bytes) -> Response { - if !g.authorized(&h) { - return error(StatusCode::UNAUTHORIZED, "unauthorized"); - } - let mut v: Value = match serde_json::from_slice(&body) { - Ok(Value::Object(v)) => Value::Object(v), - _ => return error(StatusCode::BAD_REQUEST, "invalid_json"), - }; - if v.get("conversation").is_some_and(|v| !v.is_null()) - || v.get("background") == Some(&Value::Bool(true)) - { - return error(StatusCode::BAD_REQUEST, "unsupported_stateful_mode"); - } - let Some(model) = v.get("model").and_then(Value::as_str) else { - return error(StatusCode::BAD_REQUEST, "model_required"); - }; - let mut eligible: Vec<_> = - g.0.config - .deployments - .iter() - .enumerate() - .filter(|(_, d)| { - d.id == model - || g.0 - .config - .aliases - .get(model) - .is_some_and(|m| m.contains(&d.id)) - }) - .map(|(i, _)| i) - .collect(); - if eligible.is_empty() { - return error(StatusCode::NOT_FOUND, "unknown_model"); - } - let mut caps = HashSet::from(["responses"]); - required_caps(v.get("input").unwrap_or(&Value::Null), &mut caps); - if v.get("tools") - .is_some_and(|v| v.as_array().is_none_or(|a| !a.is_empty())) - { - caps.insert("tools"); - } - if v.get("reasoning").is_some_and(|v| !v.is_null()) { - caps.insert("reasoning"); - } - if v.pointer("/text/format/type") - .and_then(Value::as_str) - .is_some_and(|s| s != "text") - { - caps.insert("structured_output"); - } - eligible.retain(|i| { - caps.iter().all(|c| { - g.0.config.deployments[*i] - .capabilities - .iter() - .any(|x| x == c) - }) - }); - if let Some(previous) = v.get("previous_response_id").filter(|v| !v.is_null()) { - let owner = previous.as_str().and_then(|id| { - g.0.owners - .lock() - .unwrap() - .iter() - .find(|(key, _)| key == id) - .map(|(_, w)| *w) - }); - let Some(owner) = owner else { - return error(StatusCode::CONFLICT, "unknown_response_owner"); - }; - eligible.retain(|i| *i == owner); - } - if eligible.is_empty() { - return error(StatusCode::CONFLICT, "no_compatible_deployment"); - } - let lease = match g - .0 - .pool - .acquire(eligible, Duration::from_millis(g.0.config.queue_timeout_ms)) - .await - { - Ok(l) => l, - Err(AdmissionError::Full) => return error(StatusCode::TOO_MANY_REQUESTS, "queue_full"), - Err(AdmissionError::Expired) => return error(StatusCode::GATEWAY_TIMEOUT, "queue_timeout"), - Err(_) => return error(StatusCode::SERVICE_UNAVAILABLE, "admission_failed"), - }; - let worker = lease.worker(); - let mut guard = InFlight { - g: g.clone(), - worker, - lease: Some(lease), - complete: false, - }; - let d = &g.0.config.deployments[worker]; - v["model"] = Value::String(d.model.clone()); - let streaming = v.get("stream") == Some(&Value::Bool(true)); - let deadline = - tokio::time::Instant::now() + Duration::from_millis(g.0.config.request_timeout_ms); - let mut request = - g.0.client - .post(format!("{}/v1/responses", d.endpoint.trim_end_matches('/'))) - .header("content-type", "application/json") - .body(serde_json::to_vec(&v).unwrap()); - if let Some(token) = &g.0.upstream_tokens[worker] { - request = request.bearer_auth(token); - } - let response = match tokio::time::timeout_at(deadline, request.send()).await { - Ok(Ok(r)) => r, - _ => return error(StatusCode::BAD_GATEWAY, "upstream_unavailable"), - }; - let code = response.status(); - let is_sse = response - .headers() - .get("content-type") - .and_then(|v| v.to_str().ok()) - .is_some_and(|s| s.starts_with("text/event-stream")); - if code.is_success() && streaming && !is_sse { - return error(StatusCode::BAD_GATEWAY, "upstream_stream_type"); - } - let content_type = if is_sse { - "text/event-stream" - } else { - "application/json" - }; - let mut result = if streaming && code.is_success() { - let stream = response.bytes_stream(); - let stream = futures_util::stream::unfold( - (Box::pin(stream), guard, Terminal::default(), false), - move |(mut source, mut guard, mut terminal, done)| async move { - if done { - return None; - } - match tokio::time::timeout_at(deadline, source.next()).await { - Ok(Some(Ok(bytes))) => { - terminal.feed(&bytes); - if let Some(id) = terminal.response_id.take() { - guard.g.remember(id, guard.worker); - } - Some(( - Ok::<_, std::io::Error>(bytes), - (source, guard, terminal, false), - )) - } - Ok(None) => { - guard.complete = terminal.complete; - if terminal.complete { - if let Some(id) = terminal.response_id.take() { - guard.g.remember(id, guard.worker); - } - None - } else { - Some(( - Err(std::io::Error::other("upstream missing terminal event")), - (source, guard, terminal, true), - )) - } - } - _ => Some(( - Err(std::io::Error::other("upstream stream interrupted")), - (source, guard, terminal, true), - )), - } - }, - ); - (code, Body::from_stream(stream)).into_response() - } else { - let mut data = Vec::new(); - let mut stream = response.bytes_stream(); - loop { - match tokio::time::timeout_at(deadline, stream.next()).await { - Ok(Some(Ok(bytes))) if data.len() + bytes.len() <= 8 * 1024 * 1024 => { - data.extend_from_slice(&bytes) - } - Ok(None) => break, - _ => return error(StatusCode::BAD_GATEWAY, "upstream_body_failed"), - } - } - if code.is_success() { - let parsed = serde_json::from_slice::(&data).ok(); - if !matches!( - parsed - .as_ref() - .and_then(|v| v.get("status")) - .and_then(Value::as_str), - Some("completed" | "failed" | "incomplete") - ) { - return error(StatusCode::BAD_GATEWAY, "upstream_missing_terminal_status"); - } - if let Some(id) = parsed - .as_ref() - .and_then(|v| v.get("id")) - .and_then(Value::as_str) - { - g.remember(id.into(), worker); - } - } - guard.complete = true; - (code, Body::from(data)).into_response() - }; - result - .headers_mut() - .insert("content-type", content_type.parse().unwrap()); - result - .headers_mut() - .insert("cache-control", "no-store".parse().unwrap()); - // IDs are validated as HTTP values instead of panicking on administrator input. - if let Ok(id) = d.id.parse() { - result.headers_mut().insert("x-strata-deployment", id); - } - result -} -pub async fn serve(config: Config) -> Result<(), Box> { - let address = config.listen; - let g = Gateway::new(config)?; - let listener = tokio::net::TcpListener::bind(address).await?; - leleka_obs::emit_always( - leleka_obs::Level::Info, - "gateway", - "listening", - &[ - ("addr", listener.local_addr()?.to_string().as_str().into()), - ("msg", "Strata pool listening".into()), - ], - ); - axum::serve(listener, g.router()) - .with_graceful_shutdown(async { - let _ = tokio::signal::ctrl_c().await; - }) - .await?; - Ok(()) -} +mod secret; +#[allow(unused_imports)] +pub use secret::*; +mod impl_drop_for_inflight; +#[allow(unused_imports)] +pub use impl_drop_for_inflight::*; +mod responses; +#[allow(unused_imports)] +pub use responses::*; diff --git a/desktop-core/src/gateway/impl_drop_for_inflight.rs b/desktop-core/src/gateway/impl_drop_for_inflight.rs new file mode 100644 index 00000000..8459e1c8 --- /dev/null +++ b/desktop-core/src/gateway/impl_drop_for_inflight.rs @@ -0,0 +1,54 @@ +//! Moved out of the parent module by STRA-338: impl Drop_for_InFlight, impl Terminal. + +#[allow(unused_imports)] +use super::*; + +impl Drop for InFlight { + fn drop(&mut self) { + // Client disconnect does not prove upstream stopped computing. Quarantine before releasing. + if !self.complete { + let _ = self.g.0.pool.set_ready(self.worker, false); + } + self.lease.take(); + } +} +impl Terminal { + pub(super) fn feed(&mut self, bytes: &[u8]) { + for b in bytes { + if *b == b'\n' { + let line = self.line.strip_suffix(b"\r").unwrap_or(&self.line); + if line.is_empty() { + if !self.overflow + && let Ok(v) = serde_json::from_slice::(&self.data) + && matches!( + v.get("type").and_then(Value::as_str), + Some("response.completed" | "response.failed" | "response.incomplete") + ) + { + self.complete = true; + self.response_id = v + .pointer("/response/id") + .and_then(Value::as_str) + .map(str::to_owned); + } + self.data.clear(); + self.overflow = false; + } else if !self.overflow + && let Some(data) = line.strip_prefix(b"data:") + { + if self.data.len() + data.len() + 1 > 1024 * 1024 { + self.overflow = true; + } else { + self.data.extend_from_slice(data); + self.data.push(b'\n'); + } + } + self.line.clear(); + } else if self.line.len() < 1024 * 1024 { + self.line.push(*b); + } else { + self.overflow = true; + } + } + } +} diff --git a/desktop-core/src/gateway/responses.rs b/desktop-core/src/gateway/responses.rs new file mode 100644 index 00000000..2ecee482 --- /dev/null +++ b/desktop-core/src/gateway/responses.rs @@ -0,0 +1,237 @@ +//! Moved out of the parent module by STRA-338: fn responses, fn serve. + +#[allow(unused_imports)] +use super::*; + +pub(super) async fn responses(State(g): State, h: HeaderMap, body: Bytes) -> Response { + if !g.authorized(&h) { + return error(StatusCode::UNAUTHORIZED, "unauthorized"); + } + let mut v: Value = match serde_json::from_slice(&body) { + Ok(Value::Object(v)) => Value::Object(v), + _ => return error(StatusCode::BAD_REQUEST, "invalid_json"), + }; + if v.get("conversation").is_some_and(|v| !v.is_null()) + || v.get("background") == Some(&Value::Bool(true)) + { + return error(StatusCode::BAD_REQUEST, "unsupported_stateful_mode"); + } + let Some(model) = v.get("model").and_then(Value::as_str) else { + return error(StatusCode::BAD_REQUEST, "model_required"); + }; + let mut eligible: Vec<_> = + g.0.config + .deployments + .iter() + .enumerate() + .filter(|(_, d)| { + d.id == model + || g.0 + .config + .aliases + .get(model) + .is_some_and(|m| m.contains(&d.id)) + }) + .map(|(i, _)| i) + .collect(); + if eligible.is_empty() { + return error(StatusCode::NOT_FOUND, "unknown_model"); + } + let mut caps = HashSet::from(["responses"]); + required_caps(v.get("input").unwrap_or(&Value::Null), &mut caps); + if v.get("tools") + .is_some_and(|v| v.as_array().is_none_or(|a| !a.is_empty())) + { + caps.insert("tools"); + } + if v.get("reasoning").is_some_and(|v| !v.is_null()) { + caps.insert("reasoning"); + } + if v.pointer("/text/format/type") + .and_then(Value::as_str) + .is_some_and(|s| s != "text") + { + caps.insert("structured_output"); + } + eligible.retain(|i| { + caps.iter().all(|c| { + g.0.config.deployments[*i] + .capabilities + .iter() + .any(|x| x == c) + }) + }); + if let Some(previous) = v.get("previous_response_id").filter(|v| !v.is_null()) { + let owner = previous.as_str().and_then(|id| { + g.0.owners + .lock() + .unwrap() + .iter() + .find(|(key, _)| key == id) + .map(|(_, w)| *w) + }); + let Some(owner) = owner else { + return error(StatusCode::CONFLICT, "unknown_response_owner"); + }; + eligible.retain(|i| *i == owner); + } + if eligible.is_empty() { + return error(StatusCode::CONFLICT, "no_compatible_deployment"); + } + let lease = match g + .0 + .pool + .acquire(eligible, Duration::from_millis(g.0.config.queue_timeout_ms)) + .await + { + Ok(l) => l, + Err(AdmissionError::Full) => return error(StatusCode::TOO_MANY_REQUESTS, "queue_full"), + Err(AdmissionError::Expired) => return error(StatusCode::GATEWAY_TIMEOUT, "queue_timeout"), + Err(_) => return error(StatusCode::SERVICE_UNAVAILABLE, "admission_failed"), + }; + let worker = lease.worker(); + let mut guard = InFlight { + g: g.clone(), + worker, + lease: Some(lease), + complete: false, + }; + let d = &g.0.config.deployments[worker]; + v["model"] = Value::String(d.model.clone()); + let streaming = v.get("stream") == Some(&Value::Bool(true)); + let deadline = + tokio::time::Instant::now() + Duration::from_millis(g.0.config.request_timeout_ms); + let mut request = + g.0.client + .post(format!("{}/v1/responses", d.endpoint.trim_end_matches('/'))) + .header("content-type", "application/json") + .body(serde_json::to_vec(&v).unwrap()); + if let Some(token) = &g.0.upstream_tokens[worker] { + request = request.bearer_auth(token); + } + let response = match tokio::time::timeout_at(deadline, request.send()).await { + Ok(Ok(r)) => r, + _ => return error(StatusCode::BAD_GATEWAY, "upstream_unavailable"), + }; + let code = response.status(); + let is_sse = response + .headers() + .get("content-type") + .and_then(|v| v.to_str().ok()) + .is_some_and(|s| s.starts_with("text/event-stream")); + if code.is_success() && streaming && !is_sse { + return error(StatusCode::BAD_GATEWAY, "upstream_stream_type"); + } + let content_type = if is_sse { + "text/event-stream" + } else { + "application/json" + }; + let mut result = if streaming && code.is_success() { + let stream = response.bytes_stream(); + let stream = futures_util::stream::unfold( + (Box::pin(stream), guard, Terminal::default(), false), + move |(mut source, mut guard, mut terminal, done)| async move { + if done { + return None; + } + match tokio::time::timeout_at(deadline, source.next()).await { + Ok(Some(Ok(bytes))) => { + terminal.feed(&bytes); + if let Some(id) = terminal.response_id.take() { + guard.g.remember(id, guard.worker); + } + Some(( + Ok::<_, std::io::Error>(bytes), + (source, guard, terminal, false), + )) + } + Ok(None) => { + guard.complete = terminal.complete; + if terminal.complete { + if let Some(id) = terminal.response_id.take() { + guard.g.remember(id, guard.worker); + } + None + } else { + Some(( + Err(std::io::Error::other("upstream missing terminal event")), + (source, guard, terminal, true), + )) + } + } + _ => Some(( + Err(std::io::Error::other("upstream stream interrupted")), + (source, guard, terminal, true), + )), + } + }, + ); + (code, Body::from_stream(stream)).into_response() + } else { + let mut data = Vec::new(); + let mut stream = response.bytes_stream(); + loop { + match tokio::time::timeout_at(deadline, stream.next()).await { + Ok(Some(Ok(bytes))) if data.len() + bytes.len() <= 8 * 1024 * 1024 => { + data.extend_from_slice(&bytes) + } + Ok(None) => break, + _ => return error(StatusCode::BAD_GATEWAY, "upstream_body_failed"), + } + } + if code.is_success() { + let parsed = serde_json::from_slice::(&data).ok(); + if !matches!( + parsed + .as_ref() + .and_then(|v| v.get("status")) + .and_then(Value::as_str), + Some("completed" | "failed" | "incomplete") + ) { + return error(StatusCode::BAD_GATEWAY, "upstream_missing_terminal_status"); + } + if let Some(id) = parsed + .as_ref() + .and_then(|v| v.get("id")) + .and_then(Value::as_str) + { + g.remember(id.into(), worker); + } + } + guard.complete = true; + (code, Body::from(data)).into_response() + }; + result + .headers_mut() + .insert("content-type", content_type.parse().unwrap()); + result + .headers_mut() + .insert("cache-control", "no-store".parse().unwrap()); + // IDs are validated as HTTP values instead of panicking on administrator input. + if let Ok(id) = d.id.parse() { + result.headers_mut().insert("x-strata-deployment", id); + } + result +} + +pub async fn serve(config: Config) -> Result<(), Box> { + let address = config.listen; + let g = Gateway::new(config)?; + let listener = tokio::net::TcpListener::bind(address).await?; + leleka_obs::emit_always( + leleka_obs::Level::Info, + "gateway", + "listening", + &[ + ("addr", listener.local_addr()?.to_string().as_str().into()), + ("msg", "Strata pool listening".into()), + ], + ); + axum::serve(listener, g.router()) + .with_graceful_shutdown(async { + let _ = tokio::signal::ctrl_c().await; + }) + .await?; + Ok(()) +} diff --git a/desktop-core/src/gateway/secret.rs b/desktop-core/src/gateway/secret.rs new file mode 100644 index 00000000..246f76a7 --- /dev/null +++ b/desktop-core/src/gateway/secret.rs @@ -0,0 +1,241 @@ +//! Moved out of the parent module by STRA-338: fn secret, impl Gateway, fn error, fn models, fn status, fn required_caps. + +#[allow(unused_imports)] +use super::*; + +pub(super) fn secret(name: &str) -> Result { + if name.is_empty() || !name.bytes().all(|c| c.is_ascii_alphanumeric() || c == b'_') { + return Err("invalid credential environment name".into()); + } + let value = std::env::var(name).map_err(|_| "credential environment variable is missing")?; + if value.len() < 16 || value.len() > 4096 || value.bytes().any(|c| c.is_ascii_control()) { + return Err("credential must contain 16..4096 non-control bytes".into()); + } + Ok(value) +} +impl Gateway { + pub(crate) async fn dispatch(&self, headers: HeaderMap, body: Bytes) -> Response { + responses(State(self.clone()), headers, body).await + } + pub(crate) fn ready_catalog(&self) -> Vec { + let ready: HashSet<_> = self + .0 + .pool + .snapshot() + .workers + .into_iter() + .filter(|w| w.ready) + .map(|w| w.id) + .collect(); + self.0 + .config + .deployments + .iter() + .filter(|d| ready.contains(&d.id)) + .map(|d| json!({"id":d.id,"object":"model","owned_by":"configured-pool"})) + .chain( + self.0 + .config + .aliases + .iter() + .filter(|(_, members)| members.iter().any(|m| ready.contains(m))) + .map(|(id, _)| json!({"id":id,"object":"model","owned_by":"configured-pool"})), + ) + .collect() + } + pub fn new(config: Config) -> Result { + let token = secret(&config.token_env)?; + Self::with_token(config, token) + } + /// Explicit token injection is useful for an embedding host and isolated tests. + pub fn with_token(config: Config, token: String) -> Result { + if config.schema_version != 1 + || !config.listen.ip().is_loopback() + || token.len() < 16 + || config.queue_timeout_ms == 0 + || config.queue_timeout_ms > 3_600_000 + || config.request_timeout_ms == 0 + || config.request_timeout_ms > 86_400_000 + || config.queue_limit > 64 + || config.aliases.len() > 256 + { + return Err("invalid gateway limits or non-loopback bind".into()); + } + let mut endpoints = HashSet::new(); + for d in &config.deployments { + let u = reqwest::Url::parse(&d.endpoint).map_err(|_| "invalid endpoint")?; + let ip = u + .host_str() + .unwrap_or("") + .trim_matches(['[', ']']) + .parse::() + .map_err(|_| "endpoint must use a loopback IP")?; + if !ip.is_loopback() + || u.scheme() != "http" + || u.path() != "/" + || u.query().is_some() + || u.fragment().is_some() + || !u.username().is_empty() + || u.password().is_some() + || !endpoints.insert(u.to_string()) + || d.model.is_empty() + || d.id.len() > 128 + { + return Err("invalid, duplicate or non-loopback endpoint".into()); + } + } + let ids: HashSet<_> = config.deployments.iter().map(|d| d.id.as_str()).collect(); + for (alias, members) in &config.aliases { + if alias.is_empty() + || ids.contains(alias.as_str()) + || members.is_empty() + || members.len() > 256 + || members.iter().any(|m| !ids.contains(m.as_str())) + { + return Err("invalid pool alias".into()); + } + } + let pool = Pool::new( + config + .deployments + .iter() + .map(|d| Worker { + id: d.id.clone(), + group: d.group.clone(), + slots: d.slots, + request_bytes: d.request_bytes, + }) + .collect(), + config + .groups + .iter() + .map(|g| ResourceGroup { + id: g.id.clone(), + slots: g.slots, + available_bytes: g.available_bytes, + }) + .collect(), + config.queue_limit, + ) + .map_err(|_| "invalid resource capacity")?; + let upstream_tokens = config + .deployments + .iter() + .map(|d| d.token_env.as_deref().map(secret).transpose()) + .collect::>()?; + let client = reqwest::Client::builder() + .no_proxy() + .redirect(reqwest::redirect::Policy::none()) + .connect_timeout(Duration::from_secs(5)) + .build() + .map_err(|_| "HTTP client initialization failed")?; + Ok(Self(Arc::new(Inner { + config, + pool, + token, + upstream_tokens, + client, + owners: Mutex::new(VecDeque::new()), + }))) + } + pub(crate) fn matches_credential(&self, token: &str) -> bool { + bool::from(token.as_bytes().ct_eq(self.0.token.as_bytes())) + } + pub(crate) fn clear_response_owners(&self) { + self.0.owners.lock().unwrap().clear(); + } + pub(crate) fn set_managed_ready(&self, ready: bool) { + for i in 0..self.0.config.deployments.len() { + let _ = self.0.pool.set_ready(i, ready); + } + } + pub(crate) fn idle(&self) -> bool { + let s = self.0.pool.snapshot(); + s.active == 0 && s.queued == 0 + } + pub fn router(&self) -> Router { + Router::new() + .route("/v1/models", get(models)) + .route("/v1/responses", post(responses)) + .route("/pool/status", get(status)) + .layer(DefaultBodyLimit::max(2 * 1024 * 1024)) + .with_state(self.clone()) + } + pub(super) fn authorized(&self, h: &HeaderMap) -> bool { + h.get("authorization") + .and_then(|v| v.to_str().ok()) + .and_then(|s| s.strip_prefix("Bearer ")) + .is_some_and(|s| bool::from(s.as_bytes().ct_eq(self.0.token.as_bytes()))) + } + pub(super) fn remember(&self, id: String, worker: usize) { + if id.is_empty() || id.len() > 256 { + return; + } + let mut owners = self.0.owners.lock().unwrap(); + // A collision is ambiguous; sentinel ownership rejects further continuations. + let owner = owners + .iter() + .find(|(key, _)| key == &id) + .map(|(_, w)| if *w == worker { worker } else { usize::MAX }) + .unwrap_or(worker); + owners.retain(|(key, _)| key != &id); + owners.push_back((id, owner)); + if owners.len() > 4096 { + owners.pop_front(); + } + } +} +pub(super) fn error(code: StatusCode, kind: &str) -> Response { + let mut response = (code, Json(json!({"error":{"type":kind,"message":kind}}))).into_response(); + if code == StatusCode::TOO_MANY_REQUESTS { + response + .headers_mut() + .insert("retry-after", "1".parse().unwrap()); + } + response +} +pub(super) async fn models(State(g): State, h: HeaderMap) -> Response { + if !g.authorized(&h) { + return error(StatusCode::UNAUTHORIZED, "unauthorized"); + } + let ids = + g.0.config + .deployments + .iter() + .map(|d| d.id.clone()) + .chain(g.0.config.aliases.keys().cloned()); + Json(json!({"object":"list","data":ids.map(|id|json!({"id":id,"object":"model","owned_by":"configured-pool"})).collect::>()})).into_response() +} +pub(super) async fn status(State(g): State, h: HeaderMap) -> Response { + if !g.authorized(&h) { + return error(StatusCode::UNAUTHORIZED, "unauthorized"); + } + Json(json!({"schema_version":1,"pool":g.0.pool.snapshot()})).into_response() +} +pub(super) fn required_caps(v: &Value, out: &mut HashSet<&'static str>) { + match v { + Value::Array(a) => { + for v in a { + required_caps(v, out) + } + } + Value::Object(m) => { + match m.get("type").and_then(Value::as_str) { + Some("input_image") => { + out.insert("image"); + } + Some("input_audio") => { + out.insert("audio"); + } + Some("input_file") => { + out.insert("file"); + } + _ => {} + } + for v in m.values() { + required_caps(v, out); + } + } + _ => {} + } +} diff --git a/desktop-core/src/managed_worker.rs b/desktop-core/src/managed_worker.rs index 203b79e3..cdb5847d 100644 --- a/desktop-core/src/managed_worker.rs +++ b/desktop-core/src/managed_worker.rs @@ -33,82 +33,6 @@ pub struct Profile { #[serde(default = "default_capabilities")] pub capabilities: Vec, } -fn default_capabilities() -> Vec { - vec!["responses".into()] -} -impl Profile { - pub fn validate(&self) -> Result<(), String> { - if self.schema_version != 1 - || self.id.is_empty() - || self.id.len() > 128 - || !self - .id - .bytes() - .all(|b| b.is_ascii_alphanumeric() || b == b'-' || b == b'_') - || self.capabilities.is_empty() - || self.capabilities.len() > 16 - || !self.capabilities.iter().any(|c| c == "responses") - || self.capabilities.iter().any(|c| { - ![ - "responses", - "tools", - "reasoning", - "structured_output", - "image", - "audio", - "file", - ] - .contains(&c.as_str()) - }) - || self.model.is_empty() - || self.model.len() > 256 - || self.model.chars().any(char::is_control) - || !self.executable.is_absolute() - || !self.executable.is_file() - || self.args.len() > 256 - || self.args.iter().any(|a| a.len() > 4096 || a.contains('\0')) - || self.args.iter().map(String::len).sum::() > 32768 - || !self.endpoint.ip().is_loopback() - || self.endpoint.port() < 1024 - || !(100..=3600000).contains(&self.startup_timeout_ms) - { - return Err("invalid managed worker profile".into()); - } - Ok(()) - } - pub fn gateway(&self, token: String) -> Result { - self.validate()?; - let gateway = Gateway::with_token( - gateway::Config { - schema_version: 1, - listen: SocketAddr::new(IpAddr::from([127, 0, 0, 1]), 0), - token_env: "UNUSED".into(), - queue_limit: 16, - queue_timeout_ms: 1000, - request_timeout_ms: 3600000, - groups: vec![gateway::Group { - id: self.id.clone(), - slots: 1, - available_bytes: 1, - }], - deployments: vec![gateway::Deployment { - id: self.id.clone(), - model: self.model.clone(), - endpoint: format!("http://{}", self.endpoint), - token_env: None, - group: self.id.clone(), - slots: 1, - request_bytes: 1, - capabilities: self.capabilities.clone(), - }], - aliases: BTreeMap::new(), - }, - token, - )?; - gateway.set_managed_ready(false); - Ok(gateway) - } -} #[derive(Clone)] pub struct Manager(Arc); struct Owner { @@ -118,359 +42,16 @@ struct Owner { task: JoinHandle<()>, gateway: Gateway, } -impl Drop for Owner { - fn drop(&mut self) { - self.task.abort(); - } -} -impl Manager { - pub fn new(profile: Profile, gateway: Gateway) -> Result { - Self::with_journal(profile, gateway, None) - } - pub fn with_journal( - profile: Profile, - gateway: Gateway, - path: Option<&std::path::Path>, - ) -> Result { - profile.validate()?; - gateway.set_managed_ready(false); - let (journal, entries) = if let Some(path) = path { - let (j, e) = Journal::open(path, &profile)?; - (Some(j), e) - } else { - (None, Entries::new()) - }; - let blocked = entries.values().any(|(_, r)| r.status == "indeterminate"); - let (state_tx, state) = watch::channel(WorkerState { - profile_id: profile.id.clone(), - model: profile.model.clone(), - phase: "stopped".into(), - pid: 0, - reason: String::new(), - }); - let records = Arc::new(Mutex::new(History { - entries, - journal, - blocked, - })); - let (tx, rx) = mpsc::channel(8); - let task = tokio::spawn(run(profile, gateway.clone(), state_tx, records.clone(), rx)); - Ok(Self(Arc::new(Owner { - tx, - records, - state, - task, - gateway, - }))) - } - pub fn durable(&self) -> bool { - self.0.records.lock().unwrap().journal.is_some() - } - pub fn state(&self) -> WorkerState { - let mut state = self.0.state.borrow().clone(); - if self.0.records.lock().unwrap().blocked { - state.phase = "failed".into(); - state.reason = "reconciliation_required".into(); - } - state - } - pub fn operation(&self, id: &str) -> Result { - self.0 - .records - .lock() - .unwrap() - .entries - .get( - &uuid::Uuid::parse_str(id) - .map_err(|_| Status::invalid_argument("operation UUID required"))? - .to_string(), - ) - .map(|(_, r)| r.clone()) - .ok_or_else(|| Status::not_found("unknown operation for this epoch")) - } - pub fn submit(&self, mut c: WorkerCommand) -> Result { - c.operation_id = uuid::Uuid::parse_str(&c.operation_id) - .map_err(|_| Status::invalid_argument("operation UUID required"))? - .to_string(); - if !(1..=2).contains(&c.action) - || c.drain_timeout_ms > 30000 - || (c.action == 1 && c.drain_timeout_ms != 0) - || c.expected_epoch.len() > 128 - { - return Err(Status::invalid_argument( - "invalid worker action or drain timeout", - )); - } - let mut records = self.0.records.lock().unwrap(); - if let Some((old, result)) = records.entries.get(&c.operation_id) { - return if old.action == c.action && old.drain_timeout_ms == c.drain_timeout_ms { - Ok(result.clone()) - } else { - Err(Status::already_exists( - "operation ID has different parameters", - )) - }; - } - if records.blocked { - return Err(Status::failed_precondition( - "journal reconciliation required", - )); - } - if records.entries.len() >= 256 { - return Err(Status::resource_exhausted( - "operation history full; reconcile before new epoch", - )); - } - let permit = self - .0 - .tx - .try_reserve() - .map_err(|_| Status::resource_exhausted("worker command queue full"))?; - let result = WorkerOperation { - operation_id: c.operation_id.clone(), - status: "accepted".into(), - reason: String::new(), - }; - if records.persist(&c, &result).is_err() { - self.0.gateway.set_managed_ready(false); - return Err(Status::internal("journal unavailable; reconcile operation")); - } - records - .entries - .insert(c.operation_id.clone(), (c.clone(), result.clone())); - permit.send(c); - Ok(result) - } -} -fn state(tx: &watch::Sender, phase: &str, pid: u32, reason: &str) { - tx.send_modify(|s| { - s.phase = phase.into(); - s.pid = pid; - s.reason = reason.into(); - }); -} -async fn healthy(client: &reqwest::Client, profile: &Profile) -> bool { - let Ok(response) = client - .get(format!("http://{}/health", profile.endpoint)) - .send() - .await - else { - return false; - }; - if !response.status().is_success() { - return false; - } - let mut response = response; - let mut data = vec![]; - loop { - match response.chunk().await { - Ok(Some(b)) if data.len() + b.len() <= 65536 => data.extend(b), - Ok(None) => break, - _ => return false, - } - } - let Ok(value) = serde_json::from_slice::(&data) else { - return false; - }; - value["status"] == "ok" && value["loaded"] == true && value["model"] == profile.model -} -async fn terminate(child: &mut Option) -> Result<(), &'static str> { - if let Some(c) = child { - c.start_kill().map_err(|_| "stop_failed")?; - tokio::time::timeout(Duration::from_secs(5), c.wait()) - .await - .map_err(|_| "stop_timeout")? - .map_err(|_| "wait_failed")?; - } - *child = None; - Ok(()) -} -async fn start( - profile: &Profile, - gateway: &Gateway, - tx: &watch::Sender, - child: &mut Option, - client: &reqwest::Client, -) -> Result<(), &'static str> { - if let Some(c) = child.as_mut() - && c.try_wait().map_err(|_| "wait_failed")?.is_some() - { - *child = None; - } - if child.is_some() { - return if tx.borrow().phase == "ready" { - Ok(()) - } else { - Err("stop_existing_owned_worker_first") - }; - } - gateway.set_managed_ready(false); - // Binding a temporary listener proves the endpoint was free before spawn. - let listener = tokio::net::TcpListener::bind(profile.endpoint) - .await - .map_err(|_| "endpoint_occupied")?; - drop(listener); - gateway.clear_response_owners(); - state(tx, "starting", 0, ""); - let mut command = Command::new(&profile.executable); - command.args(&profile.args).env_clear(); - for key in [ - "PATH", - "HOME", - "USER", - "TMPDIR", - "TEMP", - "TMP", - "SystemRoot", - "WINDIR", - "LD_LIBRARY_PATH", - "DYLD_LIBRARY_PATH", - "CUDA_VISIBLE_DEVICES", - ] { - if let Some(value) = std::env::var_os(key) { - // Even a nonstandard token variable must not leak through the allowlist. - if !gateway.matches_credential(&value.to_string_lossy()) { - command.env(key, value); - } - } - } - command - .env("STRATA_WORKER_ENDPOINT", profile.endpoint.to_string()) - .env("STRATA_WORKER_MODEL", &profile.model); - let process = command - .stdin(Stdio::null()) - .stdout(Stdio::null()) - .stderr(Stdio::null()) - .kill_on_drop(true) - .spawn() - .map_err(|_| "spawn_failed")?; - let pid = process.id().unwrap_or(0); - *child = Some(process); - state(tx, "starting", pid, ""); - let deadline = tokio::time::Instant::now() + Duration::from_millis(profile.startup_timeout_ms); - while tokio::time::Instant::now() < deadline { - if child - .as_mut() - .unwrap() - .try_wait() - .map_err(|_| "wait_failed")? - .is_some() - { - *child = None; - return Err("worker_exited"); - } - if healthy(client, profile).await - && child - .as_mut() - .unwrap() - .try_wait() - .map_err(|_| "wait_failed")? - .is_none() - { - gateway.set_managed_ready(true); - state(tx, "ready", pid, ""); - return Ok(()); - } - tokio::time::sleep(Duration::from_millis(50)).await; - } - terminate(child).await?; - Err("startup_timeout") -} -async fn stop( - gateway: &Gateway, - tx: &watch::Sender, - child: &mut Option, - grace: u32, -) -> Result<(), &'static str> { - gateway.set_managed_ready(false); - state( - tx, - "draining", - child.as_ref().and_then(Child::id).unwrap_or(0), - "", - ); - let deadline = tokio::time::Instant::now() + Duration::from_millis(grace as u64); - while !gateway.idle() { - if tokio::time::Instant::now() >= deadline { - return Err("drain_timeout"); - } - tokio::time::sleep(Duration::from_millis(25)).await; - } - terminate(child).await?; - state(tx, "stopped", 0, ""); - Ok(()) -} struct History { entries: Entries, journal: Option, blocked: bool, } -impl History { - fn persist(&mut self, c: &WorkerCommand, r: &WorkerOperation) -> Result<(), ()> { - if self.blocked { - return Err(()); - } - if let Some(j) = self.journal.as_mut() - && j.append(c, r).is_err() - { - self.blocked = true; - return Err(()); - } - Ok(()) - } - fn update(&mut self, c: &WorkerCommand, status: &str, reason: &str) -> Result<(), ()> { - let r = WorkerOperation { - operation_id: c.operation_id.clone(), - status: status.into(), - reason: reason.into(), - }; - if self.persist(c, &r).is_err() { - if let Some((_, old)) = self.entries.get_mut(&c.operation_id) { - old.status = "indeterminate".into(); - old.reason = "journal_unavailable".into(); - } - return Err(()); - } - self.entries.insert(c.operation_id.clone(), (c.clone(), r)); - Ok(()) - } -} type Records = Arc>; -async fn run( - profile: Profile, - gateway: Gateway, - tx: watch::Sender, - records: Records, - mut rx: mpsc::Receiver, -) { - let client = reqwest::Client::builder() - .no_proxy() - .redirect(reqwest::redirect::Policy::none()) - .timeout(Duration::from_millis(500)) - .build() - .expect("HTTP client"); - let mut child: Option = None; - let mut tick = tokio::time::interval(Duration::from_millis(200)); - loop { - tokio::select! { - command=rx.recv()=>{ - let Some(command)=command else{break}; - if records.lock().unwrap().update(&command,"running","").is_err(){gateway.set_managed_ready(false);continue} - let result=if command.action==1 {start(&profile,&gateway,&tx,&mut child,&client).await}else{stop(&gateway,&tx,&mut child,command.drain_timeout_ms).await}; - if let Err(reason)=result {gateway.set_managed_ready(false);state(&tx,"failed",child.as_ref().and_then(Child::id).unwrap_or(0),reason);} - if records.lock().unwrap().update(&command,if result.is_ok(){"succeeded"}else{"failed"},result.err().unwrap_or("")).is_err(){gateway.set_managed_ready(false);} - }, - _=tick.tick()=>{ - if let Some(c)=child.as_mut() { - match c.try_wait() { - Ok(Some(_))=>{child=None;gateway.set_managed_ready(false);state(&tx,"failed",0,"worker_exited");}, - Err(_)=>{gateway.set_managed_ready(false);state(&tx,"failed",c.id().unwrap_or(0),"wait_failed");}, - Ok(None)=>{} - } - } - } - } - } - gateway.set_managed_ready(false); - let _ = terminate(&mut child).await; -} + +mod default_capabilities; +#[allow(unused_imports)] +pub use default_capabilities::*; +mod start; +#[allow(unused_imports)] +pub use start::*; diff --git a/desktop-core/src/managed_worker/default_capabilities.rs b/desktop-core/src/managed_worker/default_capabilities.rs new file mode 100644 index 00000000..f27b49d1 --- /dev/null +++ b/desktop-core/src/managed_worker/default_capabilities.rs @@ -0,0 +1,248 @@ +//! Moved out of the parent module by STRA-338: fn default_capabilities, impl Profile, impl Drop_for_Owner, impl Manager, fn state, fn healthy .... + +#[allow(unused_imports)] +use super::*; + +pub(super) fn default_capabilities() -> Vec { + vec!["responses".into()] +} +impl Profile { + pub fn validate(&self) -> Result<(), String> { + if self.schema_version != 1 + || self.id.is_empty() + || self.id.len() > 128 + || !self + .id + .bytes() + .all(|b| b.is_ascii_alphanumeric() || b == b'-' || b == b'_') + || self.capabilities.is_empty() + || self.capabilities.len() > 16 + || !self.capabilities.iter().any(|c| c == "responses") + || self.capabilities.iter().any(|c| { + ![ + "responses", + "tools", + "reasoning", + "structured_output", + "image", + "audio", + "file", + ] + .contains(&c.as_str()) + }) + || self.model.is_empty() + || self.model.len() > 256 + || self.model.chars().any(char::is_control) + || !self.executable.is_absolute() + || !self.executable.is_file() + || self.args.len() > 256 + || self.args.iter().any(|a| a.len() > 4096 || a.contains('\0')) + || self.args.iter().map(String::len).sum::() > 32768 + || !self.endpoint.ip().is_loopback() + || self.endpoint.port() < 1024 + || !(100..=3600000).contains(&self.startup_timeout_ms) + { + return Err("invalid managed worker profile".into()); + } + Ok(()) + } + pub fn gateway(&self, token: String) -> Result { + self.validate()?; + let gateway = Gateway::with_token( + gateway::Config { + schema_version: 1, + listen: SocketAddr::new(IpAddr::from([127, 0, 0, 1]), 0), + token_env: "UNUSED".into(), + queue_limit: 16, + queue_timeout_ms: 1000, + request_timeout_ms: 3600000, + groups: vec![gateway::Group { + id: self.id.clone(), + slots: 1, + available_bytes: 1, + }], + deployments: vec![gateway::Deployment { + id: self.id.clone(), + model: self.model.clone(), + endpoint: format!("http://{}", self.endpoint), + token_env: None, + group: self.id.clone(), + slots: 1, + request_bytes: 1, + capabilities: self.capabilities.clone(), + }], + aliases: BTreeMap::new(), + }, + token, + )?; + gateway.set_managed_ready(false); + Ok(gateway) + } +} +impl Drop for Owner { + fn drop(&mut self) { + self.task.abort(); + } +} +impl Manager { + pub fn new(profile: Profile, gateway: Gateway) -> Result { + Self::with_journal(profile, gateway, None) + } + pub fn with_journal( + profile: Profile, + gateway: Gateway, + path: Option<&std::path::Path>, + ) -> Result { + profile.validate()?; + gateway.set_managed_ready(false); + let (journal, entries) = if let Some(path) = path { + let (j, e) = Journal::open(path, &profile)?; + (Some(j), e) + } else { + (None, Entries::new()) + }; + let blocked = entries.values().any(|(_, r)| r.status == "indeterminate"); + let (state_tx, state) = watch::channel(WorkerState { + profile_id: profile.id.clone(), + model: profile.model.clone(), + phase: "stopped".into(), + pid: 0, + reason: String::new(), + }); + let records = Arc::new(Mutex::new(History { + entries, + journal, + blocked, + })); + let (tx, rx) = mpsc::channel(8); + let task = tokio::spawn(run(profile, gateway.clone(), state_tx, records.clone(), rx)); + Ok(Self(Arc::new(Owner { + tx, + records, + state, + task, + gateway, + }))) + } + pub fn durable(&self) -> bool { + self.0.records.lock().unwrap().journal.is_some() + } + pub fn state(&self) -> WorkerState { + let mut state = self.0.state.borrow().clone(); + if self.0.records.lock().unwrap().blocked { + state.phase = "failed".into(); + state.reason = "reconciliation_required".into(); + } + state + } + pub fn operation(&self, id: &str) -> Result { + self.0 + .records + .lock() + .unwrap() + .entries + .get( + &uuid::Uuid::parse_str(id) + .map_err(|_| Status::invalid_argument("operation UUID required"))? + .to_string(), + ) + .map(|(_, r)| r.clone()) + .ok_or_else(|| Status::not_found("unknown operation for this epoch")) + } + pub fn submit(&self, mut c: WorkerCommand) -> Result { + c.operation_id = uuid::Uuid::parse_str(&c.operation_id) + .map_err(|_| Status::invalid_argument("operation UUID required"))? + .to_string(); + if !(1..=2).contains(&c.action) + || c.drain_timeout_ms > 30000 + || (c.action == 1 && c.drain_timeout_ms != 0) + || c.expected_epoch.len() > 128 + { + return Err(Status::invalid_argument( + "invalid worker action or drain timeout", + )); + } + let mut records = self.0.records.lock().unwrap(); + if let Some((old, result)) = records.entries.get(&c.operation_id) { + return if old.action == c.action && old.drain_timeout_ms == c.drain_timeout_ms { + Ok(result.clone()) + } else { + Err(Status::already_exists( + "operation ID has different parameters", + )) + }; + } + if records.blocked { + return Err(Status::failed_precondition( + "journal reconciliation required", + )); + } + if records.entries.len() >= 256 { + return Err(Status::resource_exhausted( + "operation history full; reconcile before new epoch", + )); + } + let permit = self + .0 + .tx + .try_reserve() + .map_err(|_| Status::resource_exhausted("worker command queue full"))?; + let result = WorkerOperation { + operation_id: c.operation_id.clone(), + status: "accepted".into(), + reason: String::new(), + }; + if records.persist(&c, &result).is_err() { + self.0.gateway.set_managed_ready(false); + return Err(Status::internal("journal unavailable; reconcile operation")); + } + records + .entries + .insert(c.operation_id.clone(), (c.clone(), result.clone())); + permit.send(c); + Ok(result) + } +} +pub(super) fn state(tx: &watch::Sender, phase: &str, pid: u32, reason: &str) { + tx.send_modify(|s| { + s.phase = phase.into(); + s.pid = pid; + s.reason = reason.into(); + }); +} +pub(super) async fn healthy(client: &reqwest::Client, profile: &Profile) -> bool { + let Ok(response) = client + .get(format!("http://{}/health", profile.endpoint)) + .send() + .await + else { + return false; + }; + if !response.status().is_success() { + return false; + } + let mut response = response; + let mut data = vec![]; + loop { + match response.chunk().await { + Ok(Some(b)) if data.len() + b.len() <= 65536 => data.extend(b), + Ok(None) => break, + _ => return false, + } + } + let Ok(value) = serde_json::from_slice::(&data) else { + return false; + }; + value["status"] == "ok" && value["loaded"] == true && value["model"] == profile.model +} +pub(super) async fn terminate(child: &mut Option) -> Result<(), &'static str> { + if let Some(c) = child { + c.start_kill().map_err(|_| "stop_failed")?; + tokio::time::timeout(Duration::from_secs(5), c.wait()) + .await + .map_err(|_| "stop_timeout")? + .map_err(|_| "wait_failed")?; + } + *child = None; + Ok(()) +} diff --git a/desktop-core/src/managed_worker/start.rs b/desktop-core/src/managed_worker/start.rs new file mode 100644 index 00000000..b89c2814 --- /dev/null +++ b/desktop-core/src/managed_worker/start.rs @@ -0,0 +1,193 @@ +//! Moved out of the parent module by STRA-338: fn start, fn stop, impl History, fn run. + +#[allow(unused_imports)] +use super::*; + +pub(super) async fn start( + profile: &Profile, + gateway: &Gateway, + tx: &watch::Sender, + child: &mut Option, + client: &reqwest::Client, +) -> Result<(), &'static str> { + if let Some(c) = child.as_mut() + && c.try_wait().map_err(|_| "wait_failed")?.is_some() + { + *child = None; + } + if child.is_some() { + return if tx.borrow().phase == "ready" { + Ok(()) + } else { + Err("stop_existing_owned_worker_first") + }; + } + gateway.set_managed_ready(false); + // Binding a temporary listener proves the endpoint was free before spawn. + let listener = tokio::net::TcpListener::bind(profile.endpoint) + .await + .map_err(|_| "endpoint_occupied")?; + drop(listener); + gateway.clear_response_owners(); + state(tx, "starting", 0, ""); + let mut command = Command::new(&profile.executable); + command.args(&profile.args).env_clear(); + for key in [ + "PATH", + "HOME", + "USER", + "TMPDIR", + "TEMP", + "TMP", + "SystemRoot", + "WINDIR", + "LD_LIBRARY_PATH", + "DYLD_LIBRARY_PATH", + "CUDA_VISIBLE_DEVICES", + ] { + if let Some(value) = std::env::var_os(key) { + // Even a nonstandard token variable must not leak through the allowlist. + if !gateway.matches_credential(&value.to_string_lossy()) { + command.env(key, value); + } + } + } + command + .env("STRATA_WORKER_ENDPOINT", profile.endpoint.to_string()) + .env("STRATA_WORKER_MODEL", &profile.model); + let process = command + .stdin(Stdio::null()) + .stdout(Stdio::null()) + .stderr(Stdio::null()) + .kill_on_drop(true) + .spawn() + .map_err(|_| "spawn_failed")?; + let pid = process.id().unwrap_or(0); + *child = Some(process); + state(tx, "starting", pid, ""); + let deadline = tokio::time::Instant::now() + Duration::from_millis(profile.startup_timeout_ms); + while tokio::time::Instant::now() < deadline { + if child + .as_mut() + .unwrap() + .try_wait() + .map_err(|_| "wait_failed")? + .is_some() + { + *child = None; + return Err("worker_exited"); + } + if healthy(client, profile).await + && child + .as_mut() + .unwrap() + .try_wait() + .map_err(|_| "wait_failed")? + .is_none() + { + gateway.set_managed_ready(true); + state(tx, "ready", pid, ""); + return Ok(()); + } + tokio::time::sleep(Duration::from_millis(50)).await; + } + terminate(child).await?; + Err("startup_timeout") +} +pub(super) async fn stop( + gateway: &Gateway, + tx: &watch::Sender, + child: &mut Option, + grace: u32, +) -> Result<(), &'static str> { + gateway.set_managed_ready(false); + state( + tx, + "draining", + child.as_ref().and_then(Child::id).unwrap_or(0), + "", + ); + let deadline = tokio::time::Instant::now() + Duration::from_millis(grace as u64); + while !gateway.idle() { + if tokio::time::Instant::now() >= deadline { + return Err("drain_timeout"); + } + tokio::time::sleep(Duration::from_millis(25)).await; + } + terminate(child).await?; + state(tx, "stopped", 0, ""); + Ok(()) +} +impl History { + pub(super) fn persist(&mut self, c: &WorkerCommand, r: &WorkerOperation) -> Result<(), ()> { + if self.blocked { + return Err(()); + } + if let Some(j) = self.journal.as_mut() + && j.append(c, r).is_err() + { + self.blocked = true; + return Err(()); + } + Ok(()) + } + pub(super) fn update( + &mut self, + c: &WorkerCommand, + status: &str, + reason: &str, + ) -> Result<(), ()> { + let r = WorkerOperation { + operation_id: c.operation_id.clone(), + status: status.into(), + reason: reason.into(), + }; + if self.persist(c, &r).is_err() { + if let Some((_, old)) = self.entries.get_mut(&c.operation_id) { + old.status = "indeterminate".into(); + old.reason = "journal_unavailable".into(); + } + return Err(()); + } + self.entries.insert(c.operation_id.clone(), (c.clone(), r)); + Ok(()) + } +} +pub(super) async fn run( + profile: Profile, + gateway: Gateway, + tx: watch::Sender, + records: Records, + mut rx: mpsc::Receiver, +) { + let client = reqwest::Client::builder() + .no_proxy() + .redirect(reqwest::redirect::Policy::none()) + .timeout(Duration::from_millis(500)) + .build() + .expect("HTTP client"); + let mut child: Option = None; + let mut tick = tokio::time::interval(Duration::from_millis(200)); + loop { + tokio::select! { + command=rx.recv()=>{ + let Some(command)=command else{break}; + if records.lock().unwrap().update(&command,"running","").is_err(){gateway.set_managed_ready(false);continue} + let result=if command.action==1 {start(&profile,&gateway,&tx,&mut child,&client).await}else{stop(&gateway,&tx,&mut child,command.drain_timeout_ms).await}; + if let Err(reason)=result {gateway.set_managed_ready(false);state(&tx,"failed",child.as_ref().and_then(Child::id).unwrap_or(0),reason);} + if records.lock().unwrap().update(&command,if result.is_ok(){"succeeded"}else{"failed"},result.err().unwrap_or("")).is_err(){gateway.set_managed_ready(false);} + }, + _=tick.tick()=>{ + if let Some(c)=child.as_mut() { + match c.try_wait() { + Ok(Some(_))=>{child=None;gateway.set_managed_ready(false);state(&tx,"failed",0,"worker_exited");}, + Err(_)=>{gateway.set_managed_ready(false);state(&tx,"failed",c.id().unwrap_or(0),"wait_failed");}, + Ok(None)=>{} + } + } + } + } + } + gateway.set_managed_ready(false); + let _ = terminate(&mut child).await; +} diff --git a/desktop-core/src/runtime_gateway.rs b/desktop-core/src/runtime_gateway.rs index eba5a05b..d8437161 100644 --- a/desktop-core/src/runtime_gateway.rs +++ b/desktop-core/src/runtime_gateway.rs @@ -57,178 +57,6 @@ struct Inner { } #[derive(Clone)] pub struct Registry(Arc); - -fn credential(name: &str) -> Result { - if name.is_empty() || !name.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'_') { - return Err("invalid_credential_name".into()); - } - let token = std::env::var(name).map_err(|_| "missing_credential")?; - if token.len() < 32 || token.len() > 4096 || !token.bytes().all(|b| (0x21..=0x7e).contains(&b)) - { - return Err("invalid_credential".into()); - } - Ok(token) -} -impl Config { - pub fn read(path: &std::path::Path) -> Result { - use std::io::Read; - let file = std::fs::File::open(path).map_err(|_| "configuration_read_failed")?; - let mut bytes = Vec::new(); - file.take(1024 * 1024 + 1) - .read_to_end(&mut bytes) - .map_err(|_| "configuration_read_failed")?; - if bytes.len() > 1024 * 1024 { - return Err("configuration_limit".into()); - } - let config: Self = serde_json::from_slice(&bytes).map_err(|_| "invalid_configuration")?; - config.validate()?; - Ok(config) - } - pub fn credential(&self) -> Result { - credential(&self.token_env) - } - pub fn validate(&self) -> Result<(), String> { - if self.schema_version != 1 - || !self.listen.ip().is_loopback() - || self.listen.port() == 0 - || self.runtimes.is_empty() - || self.runtimes.len() > 64 - { - return Err("invalid_daemon_configuration".into()); - } - let mut ids = HashSet::new(); - for m in &self.runtimes { - let digest = m - .artifact_digest - .strip_prefix("sha256:") - .ok_or("invalid_model_digest")?; - if m.id.is_empty() - || m.id.len() > 128 - || !m - .id - .bytes() - .all(|b| b.is_ascii_alphanumeric() || b"-_.".contains(&b)) - || !ids.insert(&m.id) - || !m.address.ip().is_loopback() - || m.address.port() == 0 - || digest.len() != 64 - || !digest.bytes().all(|b| b.is_ascii_hexdigit()) - { - return Err("invalid_runtime_member".into()); - } - } - if let Some(pool) = &self.http_pool - && (pool.listen != self.listen - || pool.deployments.iter().any(|d| ids.contains(&d.id)) - || pool.aliases.keys().any(|id| ids.contains(id))) - { - return Err("conflicting_pool_configuration".into()); - } - Ok(()) - } -} -impl Registry { - pub fn new(config: Config) -> Result { - config.validate()?; - let experimental_native_tools = config.experimental_native_tools; - let token = credential(&config.token_env)?; - let peers = config - .runtimes - .into_iter() - .map(|m| { - Ok(Peer { - token: credential(&m.token_env)?, - config: m, - state: Mutex::new(MemberState { - client: None, - snapshot: None, - blocked: false, - }), - }) - }) - .collect::, String>>()?; - let fallback = config - .http_pool - .map(|p| gateway::Gateway::with_token(p, token.clone())) - .transpose()?; - Ok(Self(Arc::new(Inner { - token, - peers, - fallback, - experimental_native_tools, - }))) - } - fn authorized(&self, h: &HeaderMap) -> bool { - h.get("authorization") - .and_then(|v| v.to_str().ok()) - .and_then(|v| v.strip_prefix("Bearer ")) - .is_some_and(|v| bool::from(v.as_bytes().ct_eq(self.0.token.as_bytes()))) - } - async fn observe(&self, index: usize) -> Option<(RuntimeClient, proto::Snapshot)> { - let peer = &self.0.peers[index]; - let mut state = peer.state.lock().await; - if state.blocked { - return None; - } - let result = async { - let mut client = match &state.client { - Some(c) => c.clone(), - None => RuntimeClient::connect(peer.config.address, peer.token.clone()).await?, - }; - let snap = client.snapshot().await?; - if let Some(prior) = &state.snapshot - && prior.epoch == snap.epoch - && prior.sequence > snap.sequence - { - return Err(tonic::Status::data_loss("snapshot_regression")); - } - if let Some(loaded) = &snap.loaded - && loaded - .descriptor - .as_ref() - .is_none_or(|d| d.artifact_digest != peer.config.artifact_digest) - { - return Err(tonic::Status::data_loss("runtime_model_identity_mismatch")); - } - Ok((client, snap)) - } - .await; - match result { - Ok((client, snap)) => { - state.client = Some(client.clone()); - state.snapshot = Some(snap.clone()); - Some((client, snap)) - } - Err(e) => { - state.client = None; - state.snapshot = None; - state.blocked = matches!( - e.code(), - tonic::Code::Unauthenticated - | tonic::Code::PermissionDenied - | tonic::Code::DataLoss - | tonic::Code::FailedPrecondition - | tonic::Code::InvalidArgument - ); - None - } - } - } - pub async fn refresh(&self) { - futures_util::future::join_all((0..self.0.peers.len()).map(|i| self.observe(i))).await; - } - pub fn router(&self) -> Router { - Router::new() - .route("/v1/models", get(models)) - .route("/v1/responses", post(responses)) - .route("/runtime/status", get(status)) - .route("/runtime/load", post(load)) - .route("/runtime/unload", post(unload)) - .route("/runtime/operation", post(operation)) - .layer(DefaultBodyLimit::max(1024 * 1024)) - .with_state(self.clone()) - } -} /// Commands can address only members already admitted by operator configuration. /// UUID and epoch identify uncertain outcomes; lifecycle calls are never replayed. #[derive(Deserialize)] @@ -241,281 +69,6 @@ struct Control { profile_id: Option, handle: Option, } -fn control(body: &Bytes) -> Result { - let c: Control = serde_json::from_slice(body).map_err(|_| "invalid_control_command")?; - if uuid::Uuid::parse_str(&c.operation_id).is_err() || uuid::Uuid::parse_str(&c.epoch).is_err() { - return Err("invalid_control_identity"); - } - Ok(c) -} -async fn control_peer( - r: &Registry, - c: &Control, -) -> Result<(RuntimeClient, proto::Snapshot), (StatusCode, &'static str)> { - let i = - r.0.peers - .iter() - .position(|p| p.config.id == c.model) - .ok_or((StatusCode::NOT_FOUND, "unknown_model"))?; - let pair = r - .observe(i) - .await - .ok_or((StatusCode::SERVICE_UNAVAILABLE, "runtime_unavailable"))?; - if pair.1.epoch != c.epoch { - return Err((StatusCode::CONFLICT, "runtime_epoch_changed")); - } - Ok(pair) -} -fn operation_value(c: &Control, result: Result) -> Response { - match result { - Ok(v)=>Json(json!({"operation_id":c.operation_id,"epoch":c.epoch,"state":v.state,"reason":v.reason,"loaded_handle":v.loaded.map(|v|v.handle)})).into_response(), - Err(_)=>(StatusCode::BAD_GATEWAY,Json(json!({"operation_id":c.operation_id,"epoch":c.epoch,"state":"outcome_unknown","error":{"type":"runtime_command_failed"}}))).into_response() - } -} -async fn load(State(r): State, h: HeaderMap, body: Bytes) -> Response { - if !r.authorized(&h) { - return error(StatusCode::UNAUTHORIZED, "unauthorized"); - } - let c = match control(&body) { - Ok(c) => c, - Err(e) => return error(StatusCode::BAD_REQUEST, e), - }; - if c.handle.is_some() { - return error(StatusCode::BAD_REQUEST, "unexpected_handle"); - } - let mode = match (c.mode.as_deref(), c.profile_id.as_deref()) { - (Some("native"), None) => proto::inference_mode::Selection::Native(proto::NativeMode {}), - (Some("kar-ple"), Some(id)) if !id.is_empty() && id.len() <= 128 => { - proto::inference_mode::Selection::KarPle(proto::KarPleMode { - profile_id: id.to_owned(), - }) - } - (Some("mtp"), Some(id @ ("qwen4exp-native-mtp-v1" | "qwen4exp-kar-ple-mtp-v1"))) => { - proto::inference_mode::Selection::Mtp(proto::MtpMode { - profile_id: id.to_owned(), - }) - } - _ => return error(StatusCode::BAD_REQUEST, "invalid_explicit_mode"), - }; - let (mut client, _) = match control_peer(&r, &c).await { - Ok(p) => p, - Err((code, e)) => return error(code, e), - }; - let d = leleka_runtime::backend::pinned_model_descriptor(); - if r.0 - .peers - .iter() - .find(|p| p.config.id == c.model) - .is_none_or(|p| p.config.artifact_digest != d.artifact_digest) - { - return error(StatusCode::BAD_REQUEST, "unsupported_model_identity"); - } - let result = client - .load(proto::LoadRequest { - operation_id: c.operation_id.clone(), - expected_epoch: c.epoch.clone(), - model: Some(proto::ModelDescriptor { - family: d.family, - architecture: d.architecture, - artifact_digest: d.artifact_digest, - weight_format: d.weight_format, - }), - config: Some(proto::LoadConfig { - version: 1, - mode: Some(proto::InferenceMode { - selection: Some(mode), - }), - gpu_memory_limit_bytes: None, - allow_experimental: matches!(c.mode.as_deref(), Some("kar-ple" | "mtp")), - }), - }) - .await; - operation_value(&c, result) -} -async fn unload(State(r): State, h: HeaderMap, body: Bytes) -> Response { - if !r.authorized(&h) { - return error(StatusCode::UNAUTHORIZED, "unauthorized"); - } - let c = match control(&body) { - Ok(c) => c, - Err(e) => return error(StatusCode::BAD_REQUEST, e), - }; - if c.mode.is_some() || c.profile_id.is_some() { - return error(StatusCode::BAD_REQUEST, "unexpected_mode"); - } - let Some(handle) = c.handle.as_ref().filter(|s| { - !s.is_empty() && s.len() <= 128 && s.bytes().all(|b| (0x21..=0x7e).contains(&b)) - }) else { - return error(StatusCode::BAD_REQUEST, "expected_handle_required"); - }; - let (mut client, _) = match control_peer(&r, &c).await { - Ok(p) => p, - Err((code, e)) => return error(code, e), - }; - let result = client - .unload(proto::UnloadRequest { - operation_id: c.operation_id.clone(), - expected_epoch: c.epoch.clone(), - handle: handle.clone(), - }) - .await; - operation_value(&c, result) -} -async fn operation(State(r): State, h: HeaderMap, body: Bytes) -> Response { - if !r.authorized(&h) { - return error(StatusCode::UNAUTHORIZED, "unauthorized"); - } - let c = match control(&body) { - Ok(c) => c, - Err(e) => return error(StatusCode::BAD_REQUEST, e), - }; - if c.mode.is_some() || c.profile_id.is_some() || c.handle.is_some() { - return error(StatusCode::BAD_REQUEST, "unexpected_mode"); - } - let (mut client, _) = match control_peer(&r, &c).await { - Ok(p) => p, - Err((code, e)) => return error(code, e), - }; - let result = client - .operation(proto::OperationQuery { - operation_id: c.operation_id.clone(), - expected_epoch: c.epoch.clone(), - }) - .await; - operation_value(&c, result) -} -fn error(code: StatusCode, kind: &str) -> Response { - (code, Json(json!({"error":{"type":kind,"message":kind}}))).into_response() -} -async fn models(State(r): State, h: HeaderMap) -> Response { - if !r.authorized(&h) { - return error(StatusCode::UNAUTHORIZED, "unauthorized"); - } - let observed = futures_util::future::join_all((0..r.0.peers.len()).map(|i| r.observe(i))).await; - let mut data = - r.0.fallback - .as_ref() - .map(gateway::Gateway::ready_catalog) - .unwrap_or_default(); - for (i, entry) in observed.into_iter().enumerate() { - if let Some((_, snap)) = entry - && snap.model_ready - && let Some(loaded) = snap.loaded - { - data.push(json!({"id":r.0.peers[i].config.id,"object":"model","owned_by":"leleka-runtime","artifact_digest":r.0.peers[i].config.artifact_digest,"mode_identity_digest":loaded.mode_identity_digest})); - } - } - Json(json!({"object":"list","data":data})).into_response() -} -async fn status(State(r): State, h: HeaderMap) -> Response { - if !r.authorized(&h) { - return error(StatusCode::UNAUTHORIZED, "unauthorized"); - } - let mut states = Vec::new(); - r.refresh().await; - for p in &r.0.peers { - let s = p.state.lock().await; - states.push(json!({"id":p.config.id,"connected":s.snapshot.is_some(),"epoch":s.snapshot.as_ref().map(|v|&v.epoch),"loaded_handle":s.snapshot.as_ref().and_then(|v|v.loaded.as_ref()).map(|v|&v.handle),"model_ready":s.snapshot.as_ref().is_some_and(|v|v.model_ready),"configuration_action_required":s.blocked})); - } - Json(json!({"schema_version":1,"runtimes":states})).into_response() -} -fn render(v: &Value) -> Result<(String, u32, FixedPoint), &'static str> { - let o = v.as_object().ok_or("invalid_json")?; - for (key, value) in o { - match key.as_str() { - "model" | "input" | "instructions" | "stream" | "max_output_tokens" => {} - key if leleka_serving_policy::fixed::SAMPLING_KEYS.contains(&key) => {} - "store" if value == &Value::Bool(false) => {} - "tools" if value.as_array().is_some_and(Vec::is_empty) => {} - "text" if value == &json!({"format":{"type":"text"}}) => {} - _ => return Err("unsupported_request_field"), - } - } - if o.get("stream").is_some_and(|v| !v.is_boolean()) { - return Err("invalid_stream"); - } - let sampling = crate::runtime_sampling::from_json(o)?; - let cap = o - .get("max_output_tokens") - .map(|v| v.as_u64().ok_or("invalid_output_limit")) - .transpose()? - .unwrap_or(256); - if !(1..=4096).contains(&cap) { - return Err("invalid_output_limit"); - } - let mut owned = Vec::new(); - if let Some(s) = o.get("instructions") { - owned.push(( - Role::System, - s.as_str().ok_or("invalid_instructions")?.to_owned(), - )); - } - match o.get("input").ok_or("input_required")? { - Value::String(s) => owned.push((Role::User, s.clone())), - Value::Array(items) if !items.is_empty() && items.len() <= 1024 => { - for item in items { - let fields = item.as_object().ok_or("invalid_message")?; - if fields - .keys() - .any(|k| !matches!(k.as_str(), "type" | "role" | "content")) - || fields.get("type").is_some_and(|t| t != "message") - { - return Err("unsupported_input_item"); - } - let role = match item.get("role").and_then(Value::as_str) { - Some("system") => Role::System, - Some("developer") => Role::Developer, - Some("user") => Role::User, - Some("assistant") => Role::Assistant, - _ => return Err("invalid_role"), - }; - let content = match item.get("content").ok_or("content_required")? { - Value::String(s) => s.clone(), - Value::Array(parts) => { - let mut s = String::new(); - for part in parts { - if !matches!( - part.get("type").and_then(Value::as_str), - Some("input_text" | "output_text") - ) || part.as_object().is_none_or(|m| { - m.keys().any(|k| !matches!(k.as_str(), "type" | "text")) - }) { - return Err("unsupported_content"); - } - s.push_str( - part.get("text") - .and_then(Value::as_str) - .ok_or("invalid_text")?, - ); - } - s - } - _ => return Err("invalid_content"), - }; - owned.push((role, content)); - } - } - _ => return Err("invalid_input"), - } - let messages = owned - .iter() - .map(|(role, content)| Message { - role: *role, - content, - reasoning: None, - parts: None, - }) - .collect::>(); - let prompt = runtime_prompt::render(&messages, Effort::None) - .map_err(|_| "prompt template rendering failed")?; - if prompt.len() > 1024 * 1024 { - return Err("prompt_limit"); - } - Ok((prompt, cap as u32, sampling)) -} -fn response_value(id: &str, model: &str, text: &str, status: &str, usage: &proto::Usage) -> Value { - json!({"id":id,"object":"response","created_at":std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map_or(0,|v|v.as_secs()),"model":model,"status":status,"output":[{"id":format!("msg_{id}"),"type":"message","role":"assistant","status":status,"content":[{"type":"output_text","text":text,"annotations":[]}]}],"usage":{"input_tokens":usage.input_tokens,"output_tokens":usage.output_tokens,"total_tokens":usage.input_tokens.saturating_add(usage.output_tokens),"input_tokens_details":{"cached_tokens":usage.reused_input_tokens}},"error":null,"incomplete_details":if status=="incomplete"{json!({"reason":"max_output_tokens"})}else{Value::Null}}) -} struct Trace { id: String, model: String, @@ -523,423 +76,19 @@ struct Trace { usage: proto::Usage, sequence: u64, } -impl Trace { - fn beginning(&mut self) -> Vec { - let mut initial = response_value(&self.id, &self.model, "", "in_progress", &self.usage); - initial["output"] = json!([]); - initial["usage"] = Value::Null; - let item = json!({"id":format!("msg_{}",self.id),"type":"message","role":"assistant","status":"in_progress","content":[]}); - vec![self.event("response.created",json!({"response":initial})),self.event("response.in_progress",json!({"response":initial})),self.event("response.output_item.added",json!({"output_index":0,"item":item})),self.event("response.content_part.added",json!({"item_id":format!("msg_{}",self.id),"output_index":0,"content_index":0,"part":{"type":"output_text","text":"","annotations":[]}}))] - } - fn interrupted(&mut self) -> Bytes { - let mut failed = response_value(&self.id, &self.model, &self.text, "failed", &self.usage); - failed["error"] = json!({"code":"runtime_interrupted","message":"runtime_interrupted"}); - self.event("response.failed", json!({"response":failed})) - } - fn event(&mut self, kind: &str, mut value: Value) -> Bytes { - value["type"] = json!(kind); - value["sequence_number"] = json!(self.sequence); - self.sequence += 1; - Bytes::from(format!("event: {kind}\ndata: {value}\n\n")) - } - fn frame(&mut self, frame: proto::GenerationFrame) -> Result, &'static str> { - match frame.payload.ok_or("missing_payload")? { - proto::generation_frame::Payload::Accepted(_) => Ok(Vec::new()), - proto::generation_frame::Payload::Text(delta) => { - if self.text.len() + delta.text.len() > 8 * 1024 * 1024 { - return Err("response_limit"); - } - self.text.push_str(&delta.text); - Ok(vec![self.event("response.output_text.delta",json!({"item_id":format!("msg_{}",self.id),"output_index":0,"content_index":0,"delta":delta.text}))]) - } - proto::generation_frame::Payload::Usage(usage) => { - self.usage = usage; - Ok(Vec::new()) - } - proto::generation_frame::Payload::Tool(_) => Err("unadvertised_tool_output"), - proto::generation_frame::Payload::Terminal(terminal) => { - if terminal.state == 1 && !matches!(terminal.reason.as_str(), "stop" | "length") { - return Err("unadvertised_finish_reason"); - } - if let Some(usage) = terminal.usage { - self.usage = usage; - } - let status = match terminal.state { - 1 if terminal.reason == "length" => "incomplete", - 1 => "completed", - _ => "failed", - }; - let mut value = - response_value(&self.id, &self.model, &self.text, status, &self.usage); - if status == "failed" { - value["error"] = - json!({"code":"runtime_interrupted","message":"runtime_interrupted"}); - } - let part = json!({"type":"output_text","text":self.text,"annotations":[]}); - let item = value["output"][0].clone(); - let mut events = Vec::new(); - if status != "failed" { - events.push(self.event("response.output_text.done",json!({"item_id":format!("msg_{}",self.id),"output_index":0,"content_index":0,"text":self.text}))); - events.push(self.event("response.content_part.done",json!({"item_id":format!("msg_{}",self.id),"output_index":0,"content_index":0,"part":part}))); - events.push(self.event( - "response.output_item.done", - json!({"output_index":0,"item":item}), - )); - } - events.push(self.event(&format!("response.{status}"), json!({"response":value}))); - Ok(events) - } - } - } -} -async fn accepted( - client: &mut RuntimeClient, - request: proto::GenerateRequest, -) -> Result { - let deadline = tokio::time::Instant::now() + Duration::from_secs(2); - for attempt in 0..3 { - let result = tokio::time::timeout_at(deadline, client.generate(request.clone())) - .await - .map_err(|_| tonic::Status::deadline_exceeded("dispatch_outcome_unknown"))?; - match result { - Ok(stream) => return Ok(stream), - Err(e) => { - let safe = e - .metadata() - .get("x-leleka-accepted") - .and_then(|v| v.to_str().ok()) - == Some("false") - && matches!( - e.code(), - tonic::Code::ResourceExhausted | tonic::Code::Unavailable - ); - if !safe || attempt == 2 { - return Err(e); - } - tokio::time::sleep(Duration::from_millis(50)).await; - } - } - } - Err(tonic::Status::unavailable("dispatch_refused")) -} -async fn responses(State(r): State, h: HeaderMap, body: Bytes) -> Response { - if !r.authorized(&h) { - return error(StatusCode::UNAUTHORIZED, "unauthorized"); - } - let v: Value = match serde_json::from_slice(&body) { - Ok(v) => v, - Err(_) => return error(StatusCode::BAD_REQUEST, "invalid_json"), - }; - let Some(model) = v.get("model").and_then(Value::as_str) else { - return error(StatusCode::BAD_REQUEST, "model_required"); - }; - let Some(index) = r.0.peers.iter().position(|p| p.config.id == model) else { - return match &r.0.fallback { - Some(g) => g.dispatch(h, body).await, - None => error(StatusCode::NOT_FOUND, "unknown_model"), - }; - }; - if r.0.experimental_native_tools && needs_tool_adapter(&v) { - return tool_responses(r, index, v).await; - } - let (prompt, cap, sampling) = match render(&v) { - Ok(v) => v, - Err(e) => return error(StatusCode::BAD_REQUEST, e), - }; - let Some((mut client, snapshot)) = r.observe(index).await else { - return error(StatusCode::SERVICE_UNAVAILABLE, "runtime_unavailable"); - }; - let Some(loaded) = snapshot.loaded.filter(|_| snapshot.model_ready) else { - return error(StatusCode::SERVICE_UNAVAILABLE, "model_not_ready"); - }; - let request_id = uuid::Uuid::new_v4().to_string(); - let mut generate = proto::GenerateRequest { - request_id: request_id.clone(), - expected_epoch: snapshot.epoch, - handle: loaded.handle, - prompt, - max_output_tokens: cap, - ..Default::default() - }; - crate::runtime_sampling::apply(&mut generate, &sampling); - let stream = match accepted(&mut client, generate).await { - Ok(s) => s, - Err(_) => return error(StatusCode::BAD_GATEWAY, "runtime_dispatch_failed"), - }; - let mut trace = Trace { - id: format!("resp_{}", request_id.replace('-', "")), - model: model.to_owned(), - text: String::new(), - usage: proto::Usage::default(), - sequence: 0, - }; - if v.get("stream") == Some(&Value::Bool(true)) { - let output = async_stream::stream! { - for event in trace.beginning(){yield Ok::(event);} - let mut stream=stream; - loop {match tokio::time::timeout(Duration::from_secs(3600),stream.message()).await { - Ok(Ok(Some(frame)))=>{let terminal=matches!(frame.payload,Some(proto::generation_frame::Payload::Terminal(_)));match trace.frame(frame){Ok(events)=>for event in events{yield Ok(event);},Err(_)=>{yield Ok(trace.interrupted());break;}}if terminal{break;}}, - _=>{yield Ok(trace.interrupted());break;} - }} - }; - let mut response = Body::from_stream(output).into_response(); - response - .headers_mut() - .insert("content-type", "text/event-stream".parse().unwrap()); - response - .headers_mut() - .insert("cache-control", "no-store".parse().unwrap()); - response - } else { - let mut stream = stream; - let mut terminal = None; - loop { - match tokio::time::timeout(Duration::from_secs(3600), stream.message()).await { - Ok(Ok(Some(frame))) => { - if let Some(proto::generation_frame::Payload::Terminal(t)) = &frame.payload { - terminal = Some(t.clone()); - } - if trace.frame(frame).is_err() { - return error(StatusCode::BAD_GATEWAY, "runtime_protocol_failed"); - } - } - Ok(Ok(None)) => break, - _ => return error(StatusCode::BAD_GATEWAY, "runtime_interrupted"), - } - } - let Some(t) = terminal else { - return error(StatusCode::BAD_GATEWAY, "runtime_missing_terminal"); - }; - if t.state != 1 { - return error(StatusCode::BAD_GATEWAY, "runtime_generation_failed"); - } - Json(response_value( - &trace.id, - &trace.model, - &trace.text, - if t.reason == "length" { - "incomplete" - } else { - "completed" - }, - &trace.usage, - )) - .into_response() - } -} - -fn needs_tool_adapter(value: &Value) -> bool { - value - .get("tools") - .is_some_and(|tools| !tools.as_array().is_some_and(Vec::is_empty)) - || value.get("tool_choice").is_some() - || value.get("parallel_tool_calls").is_some() - || value - .get("input") - .and_then(Value::as_array) - .is_some_and(|items| { - items.iter().any(|item| { - matches!( - item.get("type").and_then(Value::as_str), - Some( - "function_call" - | "function_call_output" - | "custom_tool_call" - | "custom_tool_call_output" - ) - ) - }) - }) -} - -async fn buffered_tool_generation( - mut stream: RuntimeGeneration, -) -> Result<(String, proto::Usage, String), &'static str> { - let mut text = String::new(); - loop { - let frame = tokio::time::timeout(Duration::from_secs(3600), stream.message()) - .await - .map_err(|_| "runtime_interrupted")? - .map_err(|_| "runtime_protocol_failed")? - .ok_or("runtime_missing_terminal")?; - match frame.payload.ok_or("runtime_protocol_failed")? { - proto::generation_frame::Payload::Accepted(_) => {} - proto::generation_frame::Payload::Text(delta) => { - if delta.text.len() > (8 * 1024 * 1024_usize).saturating_sub(text.len()) { - return Err("tool_output_limit"); - } - text.push_str(&delta.text); - } - proto::generation_frame::Payload::Usage(_) => {} - proto::generation_frame::Payload::Tool(_) => return Err("runtime_protocol_failed"), - proto::generation_frame::Payload::Terminal(terminal) => { - // RuntimeGeneration verifies actual HTTP2 EOF before returning - // this terminal. Unknown accepted transport is never retried. - if terminal.state != 1 { - return Err("runtime_generation_failed"); - } - if !matches!(terminal.reason.as_str(), "stop" | "length") { - return Err("runtime_protocol_failed"); - } - return Ok(( - text, - terminal.usage.ok_or("runtime_protocol_failed")?, - terminal.reason, - )); - } - } - } -} - -async fn validated_tool_generation( - registry: Registry, - index: usize, - plan: crate::runtime_tools::ToolPlan, - initial_request: proto::GenerateRequest, - initial_stream: RuntimeGeneration, - mode_identity_digest: String, -) -> Result< - ( - Vec, - proto::Usage, - String, - ), - &'static str, -> { - let mut stream = initial_stream; - let mut actual_usage = proto::Usage::default(); - for attempt in 0..2 { - let (raw, usage, reason) = buffered_tool_generation(stream).await?; - if usage.reused_input_tokens > usage.input_tokens { - return Err("runtime_protocol_failed"); - } - actual_usage.input_tokens = actual_usage - .input_tokens - .checked_add(usage.input_tokens) - .ok_or("runtime_protocol_failed")?; - actual_usage.output_tokens = actual_usage - .output_tokens - .checked_add(usage.output_tokens) - .ok_or("runtime_protocol_failed")?; - actual_usage.reused_input_tokens = actual_usage - .reused_input_tokens - .checked_add(usage.reused_input_tokens) - .ok_or("runtime_protocol_failed")?; - actual_usage - .input_tokens - .checked_add(actual_usage.output_tokens) - .ok_or("runtime_protocol_failed")?; - if let Ok(segments) = plan.policy.parse_output(&raw) { - return Ok((segments, actual_usage, reason)); - } - if attempt != 0 { - return Err("tool_retry_exhausted"); - } - // The previous operation completed and EOF was verified; none of its - // text/calls was published. This is a new model attempt, not a replay - // of an uncertain accepted request or any external tool action. - let (mut client, snapshot) = registry.observe(index).await.ok_or("runtime_interrupted")?; - let loaded = snapshot - .loaded - .filter(|_| snapshot.model_ready) - .ok_or("runtime_interrupted")?; - if snapshot.epoch != initial_request.expected_epoch - || loaded.handle != initial_request.handle - || loaded.mode_identity_digest != mode_identity_digest - { - return Err("runtime_interrupted"); - } - let mut request = initial_request.clone(); - request.request_id = uuid::Uuid::new_v4().to_string(); - stream = accepted(&mut client, request) - .await - .map_err(|_| "runtime_interrupted")?; - } - Err("tool_retry_exhausted") -} - -async fn tool_responses(registry: Registry, index: usize, value: Value) -> Response { - let plan = match crate::runtime_tools::prepare(&value) { - Ok(plan) => plan, - Err(code) => return error(StatusCode::BAD_REQUEST, code), - }; - let Some((mut client, snapshot)) = registry.observe(index).await else { - return error(StatusCode::SERVICE_UNAVAILABLE, "runtime_unavailable"); - }; - let Some(loaded) = snapshot.loaded.filter(|_| snapshot.model_ready) else { - return error(StatusCode::SERVICE_UNAVAILABLE, "model_not_ready"); - }; - let request_id = uuid::Uuid::new_v4().to_string(); - let mut request = proto::GenerateRequest { - request_id: request_id.clone(), - expected_epoch: snapshot.epoch, - handle: loaded.handle, - prompt: plan.prompt.clone(), - max_output_tokens: plan.max_output_tokens, - ..Default::default() - }; - crate::runtime_sampling::apply(&mut request, &plan.sampling); - let stream = match accepted(&mut client, request.clone()).await { - Ok(stream) => stream, - Err(_) => return error(StatusCode::BAD_GATEWAY, "runtime_dispatch_failed"), - }; - let mut publisher = crate::runtime_tool_response::ToolResponse::new( - format!("resp_{}", request_id.replace('-', "")), - registry.0.peers[index].config.id.clone(), - ); - let completion = validated_tool_generation( - registry, - index, - plan, - request, - stream, - loaded.mode_identity_digest, - ); - if value.get("stream") == Some(&Value::Bool(true)) { - let output = async_stream::stream! { - for event in publisher.beginning() { yield Ok::(event); } - tokio::pin!(completion); - let mut keepalive = tokio::time::interval(Duration::from_secs(15)); - keepalive.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Skip); - loop { - tokio::select! { - result = &mut completion => { - let events = match result { - Ok((segments, usage, reason)) => match publisher.complete(segments, &usage, &reason) { - Ok((events, _)) => events, - Err(_) => publisher.failed("runtime_tool_output_invalid").0, - }, - Err(code) => publisher.failed(code).0, - }; - for event in events { yield Ok(event); } - break; - } - _ = keepalive.tick() => yield Ok(Bytes::from_static(b": keepalive\n\n")), - } - } - }; - let mut response = Body::from_stream(output).into_response(); - response - .headers_mut() - .insert("content-type", "text/event-stream".parse().unwrap()); - response - .headers_mut() - .insert("cache-control", "no-store".parse().unwrap()); - response - } else { - match completion.await { - Ok((segments, usage, reason)) => match publisher.complete(segments, &usage, &reason) { - Ok((_, body)) => Json(body).into_response(), - Err(_) => ( - StatusCode::BAD_GATEWAY, - Json(publisher.failed("runtime_tool_output_invalid").1), - ) - .into_response(), - }, - Err(code) => (StatusCode::BAD_GATEWAY, Json(publisher.failed(code).1)).into_response(), - } - } -} #[cfg(test)] mod tests; + +mod credential; +#[allow(unused_imports)] +pub use credential::*; +mod load; +#[allow(unused_imports)] +pub use load::*; +mod response_value; +#[allow(unused_imports)] +pub use response_value::*; +mod buffered_tool_generation; +#[allow(unused_imports)] +pub use buffered_tool_generation::*; diff --git a/desktop-core/src/runtime_gateway/buffered_tool_generation.rs b/desktop-core/src/runtime_gateway/buffered_tool_generation.rs new file mode 100644 index 00000000..6ffee96d --- /dev/null +++ b/desktop-core/src/runtime_gateway/buffered_tool_generation.rs @@ -0,0 +1,193 @@ +//! Moved out of the parent module by STRA-338: fn buffered_tool_generation, fn validated_tool_generation, fn tool_responses. + +#[allow(unused_imports)] +use super::*; + +pub(super) async fn buffered_tool_generation( + mut stream: RuntimeGeneration, +) -> Result<(String, proto::Usage, String), &'static str> { + let mut text = String::new(); + loop { + let frame = tokio::time::timeout(Duration::from_secs(3600), stream.message()) + .await + .map_err(|_| "runtime_interrupted")? + .map_err(|_| "runtime_protocol_failed")? + .ok_or("runtime_missing_terminal")?; + match frame.payload.ok_or("runtime_protocol_failed")? { + proto::generation_frame::Payload::Accepted(_) => {} + proto::generation_frame::Payload::Text(delta) => { + if delta.text.len() > (8 * 1024 * 1024_usize).saturating_sub(text.len()) { + return Err("tool_output_limit"); + } + text.push_str(&delta.text); + } + proto::generation_frame::Payload::Usage(_) => {} + proto::generation_frame::Payload::Tool(_) => return Err("runtime_protocol_failed"), + proto::generation_frame::Payload::Terminal(terminal) => { + // RuntimeGeneration verifies actual HTTP2 EOF before returning + // this terminal. Unknown accepted transport is never retried. + if terminal.state != 1 { + return Err("runtime_generation_failed"); + } + if !matches!(terminal.reason.as_str(), "stop" | "length") { + return Err("runtime_protocol_failed"); + } + return Ok(( + text, + terminal.usage.ok_or("runtime_protocol_failed")?, + terminal.reason, + )); + } + } + } +} + +pub(super) async fn validated_tool_generation( + registry: Registry, + index: usize, + plan: crate::runtime_tools::ToolPlan, + initial_request: proto::GenerateRequest, + initial_stream: RuntimeGeneration, + mode_identity_digest: String, +) -> Result< + ( + Vec, + proto::Usage, + String, + ), + &'static str, +> { + let mut stream = initial_stream; + let mut actual_usage = proto::Usage::default(); + for attempt in 0..2 { + let (raw, usage, reason) = buffered_tool_generation(stream).await?; + if usage.reused_input_tokens > usage.input_tokens { + return Err("runtime_protocol_failed"); + } + actual_usage.input_tokens = actual_usage + .input_tokens + .checked_add(usage.input_tokens) + .ok_or("runtime_protocol_failed")?; + actual_usage.output_tokens = actual_usage + .output_tokens + .checked_add(usage.output_tokens) + .ok_or("runtime_protocol_failed")?; + actual_usage.reused_input_tokens = actual_usage + .reused_input_tokens + .checked_add(usage.reused_input_tokens) + .ok_or("runtime_protocol_failed")?; + actual_usage + .input_tokens + .checked_add(actual_usage.output_tokens) + .ok_or("runtime_protocol_failed")?; + if let Ok(segments) = plan.policy.parse_output(&raw) { + return Ok((segments, actual_usage, reason)); + } + if attempt != 0 { + return Err("tool_retry_exhausted"); + } + // The previous operation completed and EOF was verified; none of its + // text/calls was published. This is a new model attempt, not a replay + // of an uncertain accepted request or any external tool action. + let (mut client, snapshot) = registry.observe(index).await.ok_or("runtime_interrupted")?; + let loaded = snapshot + .loaded + .filter(|_| snapshot.model_ready) + .ok_or("runtime_interrupted")?; + if snapshot.epoch != initial_request.expected_epoch + || loaded.handle != initial_request.handle + || loaded.mode_identity_digest != mode_identity_digest + { + return Err("runtime_interrupted"); + } + let mut request = initial_request.clone(); + request.request_id = uuid::Uuid::new_v4().to_string(); + stream = accepted(&mut client, request) + .await + .map_err(|_| "runtime_interrupted")?; + } + Err("tool_retry_exhausted") +} + +pub(super) async fn tool_responses(registry: Registry, index: usize, value: Value) -> Response { + let plan = match crate::runtime_tools::prepare(&value) { + Ok(plan) => plan, + Err(code) => return error(StatusCode::BAD_REQUEST, code), + }; + let Some((mut client, snapshot)) = registry.observe(index).await else { + return error(StatusCode::SERVICE_UNAVAILABLE, "runtime_unavailable"); + }; + let Some(loaded) = snapshot.loaded.filter(|_| snapshot.model_ready) else { + return error(StatusCode::SERVICE_UNAVAILABLE, "model_not_ready"); + }; + let request_id = uuid::Uuid::new_v4().to_string(); + let mut request = proto::GenerateRequest { + request_id: request_id.clone(), + expected_epoch: snapshot.epoch, + handle: loaded.handle, + prompt: plan.prompt.clone(), + max_output_tokens: plan.max_output_tokens, + ..Default::default() + }; + crate::runtime_sampling::apply(&mut request, &plan.sampling); + let stream = match accepted(&mut client, request.clone()).await { + Ok(stream) => stream, + Err(_) => return error(StatusCode::BAD_GATEWAY, "runtime_dispatch_failed"), + }; + let mut publisher = crate::runtime_tool_response::ToolResponse::new( + format!("resp_{}", request_id.replace('-', "")), + registry.0.peers[index].config.id.clone(), + ); + let completion = validated_tool_generation( + registry, + index, + plan, + request, + stream, + loaded.mode_identity_digest, + ); + if value.get("stream") == Some(&Value::Bool(true)) { + let output = async_stream::stream! { + for event in publisher.beginning() { yield Ok::(event); } + tokio::pin!(completion); + let mut keepalive = tokio::time::interval(Duration::from_secs(15)); + keepalive.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Skip); + loop { + tokio::select! { + result = &mut completion => { + let events = match result { + Ok((segments, usage, reason)) => match publisher.complete(segments, &usage, &reason) { + Ok((events, _)) => events, + Err(_) => publisher.failed("runtime_tool_output_invalid").0, + }, + Err(code) => publisher.failed(code).0, + }; + for event in events { yield Ok(event); } + break; + } + _ = keepalive.tick() => yield Ok(Bytes::from_static(b": keepalive\n\n")), + } + } + }; + let mut response = Body::from_stream(output).into_response(); + response + .headers_mut() + .insert("content-type", "text/event-stream".parse().unwrap()); + response + .headers_mut() + .insert("cache-control", "no-store".parse().unwrap()); + response + } else { + match completion.await { + Ok((segments, usage, reason)) => match publisher.complete(segments, &usage, &reason) { + Ok((_, body)) => Json(body).into_response(), + Err(_) => ( + StatusCode::BAD_GATEWAY, + Json(publisher.failed("runtime_tool_output_invalid").1), + ) + .into_response(), + }, + Err(code) => (StatusCode::BAD_GATEWAY, Json(publisher.failed(code).1)).into_response(), + } + } +} diff --git a/desktop-core/src/runtime_gateway/credential.rs b/desktop-core/src/runtime_gateway/credential.rs new file mode 100644 index 00000000..d2fcdf76 --- /dev/null +++ b/desktop-core/src/runtime_gateway/credential.rs @@ -0,0 +1,210 @@ +//! Moved out of the parent module by STRA-338: fn credential, impl Config, impl Registry, fn control, fn control_peer, fn operation_value. + +#[allow(unused_imports)] +use super::*; + +pub(super) fn credential(name: &str) -> Result { + if name.is_empty() || !name.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'_') { + return Err("invalid_credential_name".into()); + } + let token = std::env::var(name).map_err(|_| "missing_credential")?; + if token.len() < 32 || token.len() > 4096 || !token.bytes().all(|b| (0x21..=0x7e).contains(&b)) + { + return Err("invalid_credential".into()); + } + Ok(token) +} +impl Config { + pub fn read(path: &std::path::Path) -> Result { + use std::io::Read; + let file = std::fs::File::open(path).map_err(|_| "configuration_read_failed")?; + let mut bytes = Vec::new(); + file.take(1024 * 1024 + 1) + .read_to_end(&mut bytes) + .map_err(|_| "configuration_read_failed")?; + if bytes.len() > 1024 * 1024 { + return Err("configuration_limit".into()); + } + let config: Self = serde_json::from_slice(&bytes).map_err(|_| "invalid_configuration")?; + config.validate()?; + Ok(config) + } + pub fn credential(&self) -> Result { + credential(&self.token_env) + } + pub fn validate(&self) -> Result<(), String> { + if self.schema_version != 1 + || !self.listen.ip().is_loopback() + || self.listen.port() == 0 + || self.runtimes.is_empty() + || self.runtimes.len() > 64 + { + return Err("invalid_daemon_configuration".into()); + } + let mut ids = HashSet::new(); + for m in &self.runtimes { + let digest = m + .artifact_digest + .strip_prefix("sha256:") + .ok_or("invalid_model_digest")?; + if m.id.is_empty() + || m.id.len() > 128 + || !m + .id + .bytes() + .all(|b| b.is_ascii_alphanumeric() || b"-_.".contains(&b)) + || !ids.insert(&m.id) + || !m.address.ip().is_loopback() + || m.address.port() == 0 + || digest.len() != 64 + || !digest.bytes().all(|b| b.is_ascii_hexdigit()) + { + return Err("invalid_runtime_member".into()); + } + } + if let Some(pool) = &self.http_pool + && (pool.listen != self.listen + || pool.deployments.iter().any(|d| ids.contains(&d.id)) + || pool.aliases.keys().any(|id| ids.contains(id))) + { + return Err("conflicting_pool_configuration".into()); + } + Ok(()) + } +} +impl Registry { + pub fn new(config: Config) -> Result { + config.validate()?; + let experimental_native_tools = config.experimental_native_tools; + let token = credential(&config.token_env)?; + let peers = config + .runtimes + .into_iter() + .map(|m| { + Ok(Peer { + token: credential(&m.token_env)?, + config: m, + state: Mutex::new(MemberState { + client: None, + snapshot: None, + blocked: false, + }), + }) + }) + .collect::, String>>()?; + let fallback = config + .http_pool + .map(|p| gateway::Gateway::with_token(p, token.clone())) + .transpose()?; + Ok(Self(Arc::new(Inner { + token, + peers, + fallback, + experimental_native_tools, + }))) + } + pub(super) fn authorized(&self, h: &HeaderMap) -> bool { + h.get("authorization") + .and_then(|v| v.to_str().ok()) + .and_then(|v| v.strip_prefix("Bearer ")) + .is_some_and(|v| bool::from(v.as_bytes().ct_eq(self.0.token.as_bytes()))) + } + pub(super) async fn observe(&self, index: usize) -> Option<(RuntimeClient, proto::Snapshot)> { + let peer = &self.0.peers[index]; + let mut state = peer.state.lock().await; + if state.blocked { + return None; + } + let result = async { + let mut client = match &state.client { + Some(c) => c.clone(), + None => RuntimeClient::connect(peer.config.address, peer.token.clone()).await?, + }; + let snap = client.snapshot().await?; + if let Some(prior) = &state.snapshot + && prior.epoch == snap.epoch + && prior.sequence > snap.sequence + { + return Err(tonic::Status::data_loss("snapshot_regression")); + } + if let Some(loaded) = &snap.loaded + && loaded + .descriptor + .as_ref() + .is_none_or(|d| d.artifact_digest != peer.config.artifact_digest) + { + return Err(tonic::Status::data_loss("runtime_model_identity_mismatch")); + } + Ok((client, snap)) + } + .await; + match result { + Ok((client, snap)) => { + state.client = Some(client.clone()); + state.snapshot = Some(snap.clone()); + Some((client, snap)) + } + Err(e) => { + state.client = None; + state.snapshot = None; + state.blocked = matches!( + e.code(), + tonic::Code::Unauthenticated + | tonic::Code::PermissionDenied + | tonic::Code::DataLoss + | tonic::Code::FailedPrecondition + | tonic::Code::InvalidArgument + ); + None + } + } + } + pub async fn refresh(&self) { + futures_util::future::join_all((0..self.0.peers.len()).map(|i| self.observe(i))).await; + } + pub fn router(&self) -> Router { + Router::new() + .route("/v1/models", get(models)) + .route("/v1/responses", post(responses)) + .route("/runtime/status", get(status)) + .route("/runtime/load", post(load)) + .route("/runtime/unload", post(unload)) + .route("/runtime/operation", post(operation)) + .layer(DefaultBodyLimit::max(1024 * 1024)) + .with_state(self.clone()) + } +} +pub(super) fn control(body: &Bytes) -> Result { + let c: Control = serde_json::from_slice(body).map_err(|_| "invalid_control_command")?; + if uuid::Uuid::parse_str(&c.operation_id).is_err() || uuid::Uuid::parse_str(&c.epoch).is_err() { + return Err("invalid_control_identity"); + } + Ok(c) +} +pub(super) async fn control_peer( + r: &Registry, + c: &Control, +) -> Result<(RuntimeClient, proto::Snapshot), (StatusCode, &'static str)> { + let i = + r.0.peers + .iter() + .position(|p| p.config.id == c.model) + .ok_or((StatusCode::NOT_FOUND, "unknown_model"))?; + let pair = r + .observe(i) + .await + .ok_or((StatusCode::SERVICE_UNAVAILABLE, "runtime_unavailable"))?; + if pair.1.epoch != c.epoch { + return Err((StatusCode::CONFLICT, "runtime_epoch_changed")); + } + Ok(pair) +} +pub(super) fn operation_value( + c: &Control, + result: Result, +) -> Response { + match result { + Ok(v)=>Json(json!({"operation_id":c.operation_id,"epoch":c.epoch,"state":v.state,"reason":v.reason,"loaded_handle":v.loaded.map(|v|v.handle)})).into_response(), + Err(_)=>(StatusCode::BAD_GATEWAY,Json(json!({"operation_id":c.operation_id,"epoch":c.epoch,"state":"outcome_unknown","error":{"type":"runtime_command_failed"}}))).into_response() + } +} diff --git a/desktop-core/src/runtime_gateway/load.rs b/desktop-core/src/runtime_gateway/load.rs new file mode 100644 index 00000000..239f4ceb --- /dev/null +++ b/desktop-core/src/runtime_gateway/load.rs @@ -0,0 +1,246 @@ +//! Moved out of the parent module by STRA-338: fn load, fn unload, fn operation, fn error, fn models, fn status .... + +#[allow(unused_imports)] +use super::*; + +pub(super) async fn load(State(r): State, h: HeaderMap, body: Bytes) -> Response { + if !r.authorized(&h) { + return error(StatusCode::UNAUTHORIZED, "unauthorized"); + } + let c = match control(&body) { + Ok(c) => c, + Err(e) => return error(StatusCode::BAD_REQUEST, e), + }; + if c.handle.is_some() { + return error(StatusCode::BAD_REQUEST, "unexpected_handle"); + } + let mode = match (c.mode.as_deref(), c.profile_id.as_deref()) { + (Some("native"), None) => proto::inference_mode::Selection::Native(proto::NativeMode {}), + (Some("kar-ple"), Some(id)) if !id.is_empty() && id.len() <= 128 => { + proto::inference_mode::Selection::KarPle(proto::KarPleMode { + profile_id: id.to_owned(), + }) + } + (Some("mtp"), Some(id @ ("qwen4exp-native-mtp-v1" | "qwen4exp-kar-ple-mtp-v1"))) => { + proto::inference_mode::Selection::Mtp(proto::MtpMode { + profile_id: id.to_owned(), + }) + } + _ => return error(StatusCode::BAD_REQUEST, "invalid_explicit_mode"), + }; + let (mut client, _) = match control_peer(&r, &c).await { + Ok(p) => p, + Err((code, e)) => return error(code, e), + }; + let d = leleka_runtime::backend::pinned_model_descriptor(); + if r.0 + .peers + .iter() + .find(|p| p.config.id == c.model) + .is_none_or(|p| p.config.artifact_digest != d.artifact_digest) + { + return error(StatusCode::BAD_REQUEST, "unsupported_model_identity"); + } + let result = client + .load(proto::LoadRequest { + operation_id: c.operation_id.clone(), + expected_epoch: c.epoch.clone(), + model: Some(proto::ModelDescriptor { + family: d.family, + architecture: d.architecture, + artifact_digest: d.artifact_digest, + weight_format: d.weight_format, + }), + config: Some(proto::LoadConfig { + version: 1, + mode: Some(proto::InferenceMode { + selection: Some(mode), + }), + gpu_memory_limit_bytes: None, + allow_experimental: matches!(c.mode.as_deref(), Some("kar-ple" | "mtp")), + }), + }) + .await; + operation_value(&c, result) +} +pub(super) async fn unload(State(r): State, h: HeaderMap, body: Bytes) -> Response { + if !r.authorized(&h) { + return error(StatusCode::UNAUTHORIZED, "unauthorized"); + } + let c = match control(&body) { + Ok(c) => c, + Err(e) => return error(StatusCode::BAD_REQUEST, e), + }; + if c.mode.is_some() || c.profile_id.is_some() { + return error(StatusCode::BAD_REQUEST, "unexpected_mode"); + } + let Some(handle) = c.handle.as_ref().filter(|s| { + !s.is_empty() && s.len() <= 128 && s.bytes().all(|b| (0x21..=0x7e).contains(&b)) + }) else { + return error(StatusCode::BAD_REQUEST, "expected_handle_required"); + }; + let (mut client, _) = match control_peer(&r, &c).await { + Ok(p) => p, + Err((code, e)) => return error(code, e), + }; + let result = client + .unload(proto::UnloadRequest { + operation_id: c.operation_id.clone(), + expected_epoch: c.epoch.clone(), + handle: handle.clone(), + }) + .await; + operation_value(&c, result) +} +pub(super) async fn operation(State(r): State, h: HeaderMap, body: Bytes) -> Response { + if !r.authorized(&h) { + return error(StatusCode::UNAUTHORIZED, "unauthorized"); + } + let c = match control(&body) { + Ok(c) => c, + Err(e) => return error(StatusCode::BAD_REQUEST, e), + }; + if c.mode.is_some() || c.profile_id.is_some() || c.handle.is_some() { + return error(StatusCode::BAD_REQUEST, "unexpected_mode"); + } + let (mut client, _) = match control_peer(&r, &c).await { + Ok(p) => p, + Err((code, e)) => return error(code, e), + }; + let result = client + .operation(proto::OperationQuery { + operation_id: c.operation_id.clone(), + expected_epoch: c.epoch.clone(), + }) + .await; + operation_value(&c, result) +} +pub(super) fn error(code: StatusCode, kind: &str) -> Response { + (code, Json(json!({"error":{"type":kind,"message":kind}}))).into_response() +} +pub(super) async fn models(State(r): State, h: HeaderMap) -> Response { + if !r.authorized(&h) { + return error(StatusCode::UNAUTHORIZED, "unauthorized"); + } + let observed = futures_util::future::join_all((0..r.0.peers.len()).map(|i| r.observe(i))).await; + let mut data = + r.0.fallback + .as_ref() + .map(gateway::Gateway::ready_catalog) + .unwrap_or_default(); + for (i, entry) in observed.into_iter().enumerate() { + if let Some((_, snap)) = entry + && snap.model_ready + && let Some(loaded) = snap.loaded + { + data.push(json!({"id":r.0.peers[i].config.id,"object":"model","owned_by":"leleka-runtime","artifact_digest":r.0.peers[i].config.artifact_digest,"mode_identity_digest":loaded.mode_identity_digest})); + } + } + Json(json!({"object":"list","data":data})).into_response() +} +pub(super) async fn status(State(r): State, h: HeaderMap) -> Response { + if !r.authorized(&h) { + return error(StatusCode::UNAUTHORIZED, "unauthorized"); + } + let mut states = Vec::new(); + r.refresh().await; + for p in &r.0.peers { + let s = p.state.lock().await; + states.push(json!({"id":p.config.id,"connected":s.snapshot.is_some(),"epoch":s.snapshot.as_ref().map(|v|&v.epoch),"loaded_handle":s.snapshot.as_ref().and_then(|v|v.loaded.as_ref()).map(|v|&v.handle),"model_ready":s.snapshot.as_ref().is_some_and(|v|v.model_ready),"configuration_action_required":s.blocked})); + } + Json(json!({"schema_version":1,"runtimes":states})).into_response() +} +pub(super) fn render(v: &Value) -> Result<(String, u32, FixedPoint), &'static str> { + let o = v.as_object().ok_or("invalid_json")?; + for (key, value) in o { + match key.as_str() { + "model" | "input" | "instructions" | "stream" | "max_output_tokens" => {} + key if leleka_serving_policy::fixed::SAMPLING_KEYS.contains(&key) => {} + "store" if value == &Value::Bool(false) => {} + "tools" if value.as_array().is_some_and(Vec::is_empty) => {} + "text" if value == &json!({"format":{"type":"text"}}) => {} + _ => return Err("unsupported_request_field"), + } + } + if o.get("stream").is_some_and(|v| !v.is_boolean()) { + return Err("invalid_stream"); + } + let sampling = crate::runtime_sampling::from_json(o)?; + let cap = o + .get("max_output_tokens") + .map(|v| v.as_u64().ok_or("invalid_output_limit")) + .transpose()? + .unwrap_or(256); + if !(1..=4096).contains(&cap) { + return Err("invalid_output_limit"); + } + let mut owned = Vec::new(); + if let Some(s) = o.get("instructions") { + owned.push(( + Role::System, + s.as_str().ok_or("invalid_instructions")?.to_owned(), + )); + } + match o.get("input").ok_or("input_required")? { + Value::String(s) => owned.push((Role::User, s.clone())), + Value::Array(items) if !items.is_empty() && items.len() <= 1024 => { + for item in items { + let fields = item.as_object().ok_or("invalid_message")?; + if fields + .keys() + .any(|k| !matches!(k.as_str(), "type" | "role" | "content")) + || fields.get("type").is_some_and(|t| t != "message") + { + return Err("unsupported_input_item"); + } + let role = match item.get("role").and_then(Value::as_str) { + Some("system") => Role::System, + Some("developer") => Role::Developer, + Some("user") => Role::User, + Some("assistant") => Role::Assistant, + _ => return Err("invalid_role"), + }; + let content = match item.get("content").ok_or("content_required")? { + Value::String(s) => s.clone(), + Value::Array(parts) => { + let mut s = String::new(); + for part in parts { + if !matches!( + part.get("type").and_then(Value::as_str), + Some("input_text" | "output_text") + ) || part.as_object().is_none_or(|m| { + m.keys().any(|k| !matches!(k.as_str(), "type" | "text")) + }) { + return Err("unsupported_content"); + } + s.push_str( + part.get("text") + .and_then(Value::as_str) + .ok_or("invalid_text")?, + ); + } + s + } + _ => return Err("invalid_content"), + }; + owned.push((role, content)); + } + } + _ => return Err("invalid_input"), + } + let messages = owned + .iter() + .map(|(role, content)| Message { + role: *role, + content, + reasoning: None, + parts: None, + }) + .collect::>(); + let prompt = runtime_prompt::render(&messages, Effort::None) + .map_err(|_| "prompt template rendering failed")?; + if prompt.len() > 1024 * 1024 { + return Err("prompt_limit"); + } + Ok((prompt, cap as u32, sampling)) +} diff --git a/desktop-core/src/runtime_gateway/response_value.rs b/desktop-core/src/runtime_gateway/response_value.rs new file mode 100644 index 00000000..305f22e1 --- /dev/null +++ b/desktop-core/src/runtime_gateway/response_value.rs @@ -0,0 +1,245 @@ +//! Moved out of the parent module by STRA-338: fn response_value, impl Trace, fn accepted, fn responses, fn needs_tool_adapter. + +#[allow(unused_imports)] +use super::*; + +pub(super) fn response_value( + id: &str, + model: &str, + text: &str, + status: &str, + usage: &proto::Usage, +) -> Value { + json!({"id":id,"object":"response","created_at":std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map_or(0,|v|v.as_secs()),"model":model,"status":status,"output":[{"id":format!("msg_{id}"),"type":"message","role":"assistant","status":status,"content":[{"type":"output_text","text":text,"annotations":[]}]}],"usage":{"input_tokens":usage.input_tokens,"output_tokens":usage.output_tokens,"total_tokens":usage.input_tokens.saturating_add(usage.output_tokens),"input_tokens_details":{"cached_tokens":usage.reused_input_tokens}},"error":null,"incomplete_details":if status=="incomplete"{json!({"reason":"max_output_tokens"})}else{Value::Null}}) +} +impl Trace { + pub(super) fn beginning(&mut self) -> Vec { + let mut initial = response_value(&self.id, &self.model, "", "in_progress", &self.usage); + initial["output"] = json!([]); + initial["usage"] = Value::Null; + let item = json!({"id":format!("msg_{}",self.id),"type":"message","role":"assistant","status":"in_progress","content":[]}); + vec![self.event("response.created",json!({"response":initial})),self.event("response.in_progress",json!({"response":initial})),self.event("response.output_item.added",json!({"output_index":0,"item":item})),self.event("response.content_part.added",json!({"item_id":format!("msg_{}",self.id),"output_index":0,"content_index":0,"part":{"type":"output_text","text":"","annotations":[]}}))] + } + pub(super) fn interrupted(&mut self) -> Bytes { + let mut failed = response_value(&self.id, &self.model, &self.text, "failed", &self.usage); + failed["error"] = json!({"code":"runtime_interrupted","message":"runtime_interrupted"}); + self.event("response.failed", json!({"response":failed})) + } + pub(super) fn event(&mut self, kind: &str, mut value: Value) -> Bytes { + value["type"] = json!(kind); + value["sequence_number"] = json!(self.sequence); + self.sequence += 1; + Bytes::from(format!("event: {kind}\ndata: {value}\n\n")) + } + pub(super) fn frame( + &mut self, + frame: proto::GenerationFrame, + ) -> Result, &'static str> { + match frame.payload.ok_or("missing_payload")? { + proto::generation_frame::Payload::Accepted(_) => Ok(Vec::new()), + proto::generation_frame::Payload::Text(delta) => { + if self.text.len() + delta.text.len() > 8 * 1024 * 1024 { + return Err("response_limit"); + } + self.text.push_str(&delta.text); + Ok(vec![self.event("response.output_text.delta",json!({"item_id":format!("msg_{}",self.id),"output_index":0,"content_index":0,"delta":delta.text}))]) + } + proto::generation_frame::Payload::Usage(usage) => { + self.usage = usage; + Ok(Vec::new()) + } + proto::generation_frame::Payload::Tool(_) => Err("unadvertised_tool_output"), + proto::generation_frame::Payload::Terminal(terminal) => { + if terminal.state == 1 && !matches!(terminal.reason.as_str(), "stop" | "length") { + return Err("unadvertised_finish_reason"); + } + if let Some(usage) = terminal.usage { + self.usage = usage; + } + let status = match terminal.state { + 1 if terminal.reason == "length" => "incomplete", + 1 => "completed", + _ => "failed", + }; + let mut value = + response_value(&self.id, &self.model, &self.text, status, &self.usage); + if status == "failed" { + value["error"] = + json!({"code":"runtime_interrupted","message":"runtime_interrupted"}); + } + let part = json!({"type":"output_text","text":self.text,"annotations":[]}); + let item = value["output"][0].clone(); + let mut events = Vec::new(); + if status != "failed" { + events.push(self.event("response.output_text.done",json!({"item_id":format!("msg_{}",self.id),"output_index":0,"content_index":0,"text":self.text}))); + events.push(self.event("response.content_part.done",json!({"item_id":format!("msg_{}",self.id),"output_index":0,"content_index":0,"part":part}))); + events.push(self.event( + "response.output_item.done", + json!({"output_index":0,"item":item}), + )); + } + events.push(self.event(&format!("response.{status}"), json!({"response":value}))); + Ok(events) + } + } + } +} +pub(super) async fn accepted( + client: &mut RuntimeClient, + request: proto::GenerateRequest, +) -> Result { + let deadline = tokio::time::Instant::now() + Duration::from_secs(2); + for attempt in 0..3 { + let result = tokio::time::timeout_at(deadline, client.generate(request.clone())) + .await + .map_err(|_| tonic::Status::deadline_exceeded("dispatch_outcome_unknown"))?; + match result { + Ok(stream) => return Ok(stream), + Err(e) => { + let safe = e + .metadata() + .get("x-leleka-accepted") + .and_then(|v| v.to_str().ok()) + == Some("false") + && matches!( + e.code(), + tonic::Code::ResourceExhausted | tonic::Code::Unavailable + ); + if !safe || attempt == 2 { + return Err(e); + } + tokio::time::sleep(Duration::from_millis(50)).await; + } + } + } + Err(tonic::Status::unavailable("dispatch_refused")) +} +pub(super) async fn responses(State(r): State, h: HeaderMap, body: Bytes) -> Response { + if !r.authorized(&h) { + return error(StatusCode::UNAUTHORIZED, "unauthorized"); + } + let v: Value = match serde_json::from_slice(&body) { + Ok(v) => v, + Err(_) => return error(StatusCode::BAD_REQUEST, "invalid_json"), + }; + let Some(model) = v.get("model").and_then(Value::as_str) else { + return error(StatusCode::BAD_REQUEST, "model_required"); + }; + let Some(index) = r.0.peers.iter().position(|p| p.config.id == model) else { + return match &r.0.fallback { + Some(g) => g.dispatch(h, body).await, + None => error(StatusCode::NOT_FOUND, "unknown_model"), + }; + }; + if r.0.experimental_native_tools && needs_tool_adapter(&v) { + return tool_responses(r, index, v).await; + } + let (prompt, cap, sampling) = match render(&v) { + Ok(v) => v, + Err(e) => return error(StatusCode::BAD_REQUEST, e), + }; + let Some((mut client, snapshot)) = r.observe(index).await else { + return error(StatusCode::SERVICE_UNAVAILABLE, "runtime_unavailable"); + }; + let Some(loaded) = snapshot.loaded.filter(|_| snapshot.model_ready) else { + return error(StatusCode::SERVICE_UNAVAILABLE, "model_not_ready"); + }; + let request_id = uuid::Uuid::new_v4().to_string(); + let mut generate = proto::GenerateRequest { + request_id: request_id.clone(), + expected_epoch: snapshot.epoch, + handle: loaded.handle, + prompt, + max_output_tokens: cap, + ..Default::default() + }; + crate::runtime_sampling::apply(&mut generate, &sampling); + let stream = match accepted(&mut client, generate).await { + Ok(s) => s, + Err(_) => return error(StatusCode::BAD_GATEWAY, "runtime_dispatch_failed"), + }; + let mut trace = Trace { + id: format!("resp_{}", request_id.replace('-', "")), + model: model.to_owned(), + text: String::new(), + usage: proto::Usage::default(), + sequence: 0, + }; + if v.get("stream") == Some(&Value::Bool(true)) { + let output = async_stream::stream! { + for event in trace.beginning(){yield Ok::(event);} + let mut stream=stream; + loop {match tokio::time::timeout(Duration::from_secs(3600),stream.message()).await { + Ok(Ok(Some(frame)))=>{let terminal=matches!(frame.payload,Some(proto::generation_frame::Payload::Terminal(_)));match trace.frame(frame){Ok(events)=>for event in events{yield Ok(event);},Err(_)=>{yield Ok(trace.interrupted());break;}}if terminal{break;}}, + _=>{yield Ok(trace.interrupted());break;} + }} + }; + let mut response = Body::from_stream(output).into_response(); + response + .headers_mut() + .insert("content-type", "text/event-stream".parse().unwrap()); + response + .headers_mut() + .insert("cache-control", "no-store".parse().unwrap()); + response + } else { + let mut stream = stream; + let mut terminal = None; + loop { + match tokio::time::timeout(Duration::from_secs(3600), stream.message()).await { + Ok(Ok(Some(frame))) => { + if let Some(proto::generation_frame::Payload::Terminal(t)) = &frame.payload { + terminal = Some(t.clone()); + } + if trace.frame(frame).is_err() { + return error(StatusCode::BAD_GATEWAY, "runtime_protocol_failed"); + } + } + Ok(Ok(None)) => break, + _ => return error(StatusCode::BAD_GATEWAY, "runtime_interrupted"), + } + } + let Some(t) = terminal else { + return error(StatusCode::BAD_GATEWAY, "runtime_missing_terminal"); + }; + if t.state != 1 { + return error(StatusCode::BAD_GATEWAY, "runtime_generation_failed"); + } + Json(response_value( + &trace.id, + &trace.model, + &trace.text, + if t.reason == "length" { + "incomplete" + } else { + "completed" + }, + &trace.usage, + )) + .into_response() + } +} + +pub(super) fn needs_tool_adapter(value: &Value) -> bool { + value + .get("tools") + .is_some_and(|tools| !tools.as_array().is_some_and(Vec::is_empty)) + || value.get("tool_choice").is_some() + || value.get("parallel_tool_calls").is_some() + || value + .get("input") + .and_then(Value::as_array) + .is_some_and(|items| { + items.iter().any(|item| { + matches!( + item.get("type").and_then(Value::as_str), + Some( + "function_call" + | "function_call_output" + | "custom_tool_call" + | "custom_tool_call_output" + ) + ) + }) + }) +} diff --git a/desktop-core/src/runtime_rpc.rs b/desktop-core/src/runtime_rpc.rs index c80735a0..59c2895f 100644 --- a/desktop-core/src/runtime_rpc.rs +++ b/desktop-core/src/runtime_rpc.rs @@ -64,720 +64,6 @@ struct Operation { digest: [u8; 32], result: proto::OperationResult, } - -fn lock(mutex: &Mutex) -> Result, Status> { - mutex - .lock() - .map_err(|_| Status::internal("runtime_state_unavailable")) -} -fn uuid(value: &str) -> Result<(), Status> { - if Uuid::parse_str(value).is_err() || value.len() != 36 { - return Err(refusal(tonic::Code::InvalidArgument, "invalid_uuid")); - } - Ok(()) -} -fn backend_status(error: &api::BackendError) -> Status { - let (code, reason) = match error.code { - api::ErrorCode::InvalidRequest => (tonic::Code::InvalidArgument, "invalid_generation"), - api::ErrorCode::UnsupportedModel => (tonic::Code::FailedPrecondition, "unsupported_model"), - api::ErrorCode::ResourceExhausted => (tonic::Code::ResourceExhausted, "runtime_capacity"), - api::ErrorCode::BackendUnavailable => (tonic::Code::Unavailable, "backend_unavailable"), - api::ErrorCode::Internal => (tonic::Code::Internal, "backend_failed"), - }; - // Unavailable/Internal can be a delivered-command acknowledgement failure. - // Only the facade's validation/capacity errors prove nonacceptance. - if matches!( - error.code, - api::ErrorCode::BackendUnavailable | api::ErrorCode::Internal - ) { - Status::new(code, reason) - } else { - refusal(code, reason) - } -} -fn bounded(value: &T, limit: usize) -> Result<(), Status> { - if value.encoded_len() > limit { - return Err(refusal(tonic::Code::ResourceExhausted, "message_limit")); - } - Ok(()) -} -fn operation_digest(kind: &[u8], value: &T) -> [u8; 32] { - let mut hash = Sha256::new(); - hash.update(kind); - hash.update(value.encode_to_vec()); - hash.finalize().into() -} -fn fence(state: &State, epoch: &str) -> Result<(), Status> { - if epoch != state.epoch { - return Err(refusal(tonic::Code::FailedPrecondition, "epoch_mismatch")); - } - Ok(()) -} -fn snapshot(state: &State) -> proto::Snapshot { - proto::Snapshot { - protocol_version: PROTOCOL_VERSION, - backend_api_version: u32::from(api::BACKEND_API_VERSION), - epoch: state.epoch.clone(), - sequence: state.sequence, - full_snapshot: true, - transport_ready: !state.stopping, - model_ready: state - .loaded - .as_ref() - .is_some_and(|m| state.capabilities.supports(&m.descriptor)) - && !state.stopping, - loaded: if state.stopping { - None - } else { - state.loaded.as_ref().map(loaded_to_proto) - }, - capabilities: Some(if state.stopping { - proto::Capabilities::default() - } else { - capabilities_to_proto(&state.capabilities) - }), - active_request_id: state.active.clone().unwrap_or_default(), - prefix_cache_json: if state.stopping { - String::new() - } else { - state.prefix_cache_json.clone() - }, - memory_json: if state.stopping { - String::new() - } else { - state.memory_json.clone() - }, - telemetry_json: if state.stopping { - String::new() - } else { - state.telemetry_json.clone() - }, - } -} -fn publish(inner: &Inner, state: &mut State) { - // Saturation closes future mutations rather than wrapping the cursor. - state.sequence = state.sequence.saturating_add(1); - let _ = inner.changes.send(snapshot(state)); -} -fn current_snapshot(inner: &Inner) -> Result { - refresh_capabilities(inner); - let state = lock(&inner.state)?; - Ok(snapshot(&state)) -} - -impl RuntimeServer { - pub fn new(backend: Box, token: String) -> Result { - if !valid_token(&token) { - return Err(Status::invalid_argument("invalid_runtime_credential")); - } - if !backend.identity().supports_current_api() { - return Err(Status::failed_precondition("backend_api_mismatch")); - } - let (changes, _) = broadcast::channel(EVENT_QUEUE); - Ok(Self { - inner: Arc::new(Inner { - backend: Mutex::new(backend), - token, - state: Mutex::new(State { - epoch: Uuid::new_v4().to_string(), - sequence: 1, - loaded: None, - capabilities: api::BackendCapabilities::default(), - operations: HashMap::new(), - requests: api::RecentIds::default(), - lifecycle_busy: false, - active: None, - stopping: false, - prefix_cache_json: String::new(), - memory_json: String::new(), - telemetry_json: String::new(), - }), - changes, - controls: Arc::new(Semaphore::new(16)), - watchers: Arc::new(Semaphore::new(16)), - }), - }) - } - pub async fn serve( - self, - listener: TcpListener, - shutdown: F, - ) -> Result<(), Box> - where - F: std::future::Future + Send + 'static, - { - literal_loopback(listener.local_addr()?)?; - let shutdown_inner = self.inner.clone(); - let shutdown = async move { - shutdown.await; - let active = if let Ok(mut state) = shutdown_inner.state.lock() { - state.stopping = true; - publish(&shutdown_inner, &mut state); - state.active.clone() - } else { - None - }; - if let Some(id) = active { - cancel_detached(shutdown_inner, id); - } - }; - tonic::transport::Server::builder() - .max_concurrent_streams(64) - .add_service( - proto::runtime_server::RuntimeServer::new(self) - .max_decoding_message_size(MESSAGE_LIMIT) - .max_encoding_message_size(MESSAGE_LIMIT), - ) - // `serve_with_incoming*` ignores the builder's `tcp_nodelay`, and Nagle's algorithm plus the client's delayed ACK - // holds every small response frame (the accept of a generation, each text delta, the terminal) for up to ~40 ms - // on loopback: the sockets are accepted here, so set TCP_NODELAY here. - .serve_with_incoming_shutdown( - tonic::transport::server::TcpIncoming::from(listener).with_nodelay(Some(true)), - shutdown, - ) - .await?; - Ok(()) - } - fn authorize( - &self, - request: &Request, - limit: usize, - ) -> Result { - if request - .remote_addr() - .is_none_or(|address| !address.ip().is_loopback()) - { - return Err(Status::permission_denied("loopback_required")); - } - let supplied = request - .metadata() - .get("authorization") - .and_then(|v| v.to_str().ok()) - .and_then(|v| v.strip_prefix("Bearer ")) - .unwrap_or(""); - if !bool::from(self.inner.token.as_bytes().ct_eq(supplied.as_bytes())) { - return Err(Status::unauthenticated("unauthorized")); - } - bounded(request.get_ref(), limit)?; - self.inner - .controls - .clone() - .try_acquire_owned() - .map_err(|_| refusal(tonic::Code::ResourceExhausted, "control_capacity")) - } - fn reserve( - &self, - id: &str, - epoch: &str, - digest: [u8; 32], - ) -> Result<(proto::OperationResult, bool), Status> { - uuid(id)?; - let mut state = lock(&self.inner.state)?; - fence(&state, epoch)?; - if let Some(old) = state.operations.get(id) { - if old.digest != digest { - return Err(refusal(tonic::Code::AlreadyExists, "operation_conflict")); - } - return Ok((old.result.clone(), false)); - } - if state.operations.len() >= MAX_IDS - || state.lifecycle_busy - || state.active.is_some() - || state.sequence == u64::MAX - || state.stopping - { - return Err(refusal( - tonic::Code::ResourceExhausted, - "lifecycle_capacity", - )); - } - let result = proto::OperationResult { - operation_id: id.to_owned(), - epoch: state.epoch.clone(), - state: proto::operation_result::State::Accepted as i32, - reason: "accepted".into(), - loaded: None, - }; - state.operations.insert( - id.to_owned(), - Operation { - digest, - result: result.clone(), - }, - ); - state.lifecycle_busy = true; - publish(&self.inner, &mut state); - Ok((result, true)) - } -} - -#[tonic::async_trait] -impl proto::runtime_server::Runtime for RuntimeServer { - async fn handshake( - &self, - request: Request, - ) -> Result, Status> { - let _permit = self.authorize(&request, FRAME_LIMIT)?; - let hello = request.into_inner(); - if hello.protocol_version != PROTOCOL_VERSION - || hello.backend_api_version != u32::from(api::BACKEND_API_VERSION) - { - return Err(refusal( - tonic::Code::FailedPrecondition, - "protocol_version_mismatch", - )); - } - Ok(Response::new(current_snapshot(&self.inner)?)) - } - async fn snapshot( - &self, - request: Request, - ) -> Result, Status> { - let _permit = self.authorize(&request, FRAME_LIMIT)?; - Ok(Response::new(current_snapshot(&self.inner)?)) - } - type WatchStream = WireStream; - async fn watch( - &self, - request: Request, - ) -> Result, Status> { - let _permit = self.authorize(&request, FRAME_LIMIT)?; - let watch_permit = self - .inner - .watchers - .clone() - .try_acquire_owned() - .map_err(|_| Status::resource_exhausted("watch_capacity"))?; - let mut changes = self.inner.changes.subscribe(); - let first = current_snapshot(&self.inner)?; - let inner = self.inner.clone(); - // Every notification is a full bounded observation, including cursor - // gaps/replacement epochs. It never starts or replays inference. - let stream = async_stream::try_stream! { - let _watch_permit = watch_permit; - let stopped = !first.transport_ready; - yield first; - if stopped { return; } - loop { - match changes.recv().await { - Ok(next) => { - let stopped = !next.transport_ready; - yield next; - if stopped { break; } - }, - Err(broadcast::error::RecvError::Lagged(_)) => { - let next = current_snapshot(&inner)?; - yield next; - } - Err(broadcast::error::RecvError::Closed) => break, - } - } - }; - Ok(Response::new(Box::pin(stream))) - } - async fn load( - &self, - request: Request, - ) -> Result, Status> { - let _permit = self.authorize(&request, FRAME_LIMIT)?; - let command = request.into_inner(); - let model = descriptor_from_proto( - command - .model - .as_ref() - .ok_or_else(|| refusal(tonic::Code::InvalidArgument, "missing_model"))?, - )?; - let config = config_from_proto( - command - .config - .as_ref() - .ok_or_else(|| refusal(tonic::Code::InvalidArgument, "missing_config"))?, - )?; - let mut canonical = command.clone(); - canonical.operation_id.clear(); - let digest = operation_digest(b"load\0", &canonical); - let (accepted, execute) = - self.reserve(&command.operation_id, &command.expected_epoch, digest)?; - if execute { - let inner = self.inner.clone(); - tokio::task::spawn_blocking(move || { - let mut guard = LifecycleGuard { - inner: inner.clone(), - operation_id: command.operation_id.clone(), - armed: true, - }; - let result = (|| { - let mut backend = lock(&inner.backend)?; - let loaded = backend - .load(model.clone(), config.clone()) - .map_err(|e| backend_status(&e))?; - loaded - .validate_for_load(&model, &config) - .map_err(|_| Status::internal("invalid_backend_load_result"))?; - Ok::<_, Status>((loaded, backend.capabilities())) - })(); - if let Ok(mut state) = inner.state.lock() { - let (phase, reason, loaded) = match result { - Ok((loaded, capabilities)) => { - state.loaded = Some(loaded.clone()); - state.capabilities = capabilities; - ( - proto::operation_result::State::Completed, - "completed", - Some(loaded_to_proto(&loaded)), - ) - } - Err(status) - if status - .metadata() - .get("x-leleka-accepted") - .and_then(|v| v.to_str().ok()) - == Some("false") => - { - (proto::operation_result::State::Failed, "load_failed", None) - } - Err(_) => { - state.loaded = None; - state.capabilities = api::BackendCapabilities::default(); - ( - proto::operation_result::State::Indeterminate, - "load_uncertain", - None, - ) - } - }; - if let Some(operation) = state.operations.get_mut(&command.operation_id) { - operation.result.state = phase as i32; - operation.result.reason = reason.into(); - operation.result.loaded = loaded; - } - state.lifecycle_busy = false; - guard.armed = false; - publish(&inner, &mut state); - } - }); - } - Ok(Response::new(accepted)) - } - async fn unload( - &self, - request: Request, - ) -> Result, Status> { - let _permit = self.authorize(&request, FRAME_LIMIT)?; - let command = request.into_inner(); - let mut canonical = command.clone(); - canonical.operation_id.clear(); - let digest = operation_digest(b"unload\0", &canonical); - let loaded = { - let state = lock(&self.inner.state)?; - fence(&state, &command.expected_epoch)?; - // Completed duplicates are resolved even when the model was unloaded. - if let Some(old) = state.operations.get(&command.operation_id) { - if old.digest != digest { - return Err(refusal(tonic::Code::AlreadyExists, "operation_conflict")); - } - return Ok(Response::new(old.result.clone())); - } - state - .loaded - .as_ref() - .filter(|m| m.handle == command.handle) - .cloned() - .ok_or_else(|| refusal(tonic::Code::FailedPrecondition, "stale_model_handle"))? - }; - let (accepted, execute) = - self.reserve(&command.operation_id, &command.expected_epoch, digest)?; - if execute { - let inner = self.inner.clone(); - tokio::task::spawn_blocking(move || { - let mut guard = LifecycleGuard { - inner: inner.clone(), - operation_id: command.operation_id.clone(), - armed: true, - }; - let result = lock(&inner.backend) - .and_then(|mut b| b.unload(loaded).map_err(|e| backend_status(&e))); - if let Ok(mut state) = inner.state.lock() { - // Failed/uncertain unload also closes model admission. - state.loaded = None; - state.capabilities = api::BackendCapabilities::default(); - if let Some(operation) = state.operations.get_mut(&command.operation_id) { - operation.result.state = if result.is_ok() { - proto::operation_result::State::Completed - } else { - proto::operation_result::State::Indeterminate - } as i32; - operation.result.reason = if result.is_ok() { - "completed" - } else { - "unload_uncertain" - } - .into(); - } - state.lifecycle_busy = false; - guard.armed = false; - publish(&inner, &mut state); - } - }); - } - Ok(Response::new(accepted)) - } - async fn operation( - &self, - request: Request, - ) -> Result, Status> { - let _permit = self.authorize(&request, FRAME_LIMIT)?; - let query = request.into_inner(); - uuid(&query.operation_id)?; - let state = lock(&self.inner.state)?; - if query.expected_epoch != state.epoch - || !state.operations.contains_key(&query.operation_id) - { - return Ok(Response::new(proto::OperationResult { - operation_id: query.operation_id, - epoch: state.epoch.clone(), - state: proto::operation_result::State::Indeterminate as i32, - reason: "unknown_operation".into(), - loaded: None, - })); - } - Ok(Response::new( - state.operations[&query.operation_id].result.clone(), - )) - } - type GenerateStream = WireStream; - async fn generate( - &self, - request: Request, - ) -> Result, Status> { - let _permit = self.authorize(&request, MESSAGE_LIMIT)?; - let command = request.into_inner(); - uuid(&command.request_id)?; - if command.prompt.len() > 1024 * 1024 - || command.max_output_tokens == 0 - || command.max_output_tokens > api::MAX_OUTPUT_TOKENS - { - return Err(refusal( - tonic::Code::InvalidArgument, - "unsupported_generation_request", - )); - } - // Sampling is served by the backend (Original sampler chain); the Original's documented - // ranges are enforced here too, so an out-of-contract request never reaches a worker. - let sampling = crate::runtime_sampling::to_backend(&command).map_err(|()| { - refusal( - tonic::Code::InvalidArgument, - "unsupported_generation_request", - ) - })?; - let loaded = { - let mut state = lock(&self.inner.state)?; - fence(&state, &command.expected_epoch)?; - if state.requests.contains(&command.request_id) { - // An old ID may have accepted/visible effects. Its rejection - // cannot authorize a retry of that identity on another member, - // including when this member's registry or slot is full. - return Err(Status::already_exists("generation_not_replayed")); - } - if state.active.is_some() - || state.lifecycle_busy - || state.stopping - || state.sequence == u64::MAX - { - return Err(refusal( - tonic::Code::ResourceExhausted, - "generation_capacity", - )); - } - let loaded = state - .loaded - .as_ref() - .filter(|m| m.handle == command.handle) - .cloned() - .ok_or_else(|| refusal(tonic::Code::FailedPrecondition, "stale_model_handle"))?; - if !state.capabilities.supports(&loaded.descriptor) { - return Err(refusal(tonic::Code::FailedPrecondition, "model_not_ready")); - } - state.requests.insert(&command.request_id); - state.active = Some(command.request_id.clone()); - publish(&self.inner, &mut state); - loaded - }; - let inner = self.inner.clone(); - let backend_request = api::GenerationRequest { - request_id: command.request_id.clone(), - prompt: command.prompt, - max_output_tokens: command.max_output_tokens, - temperature_milli: command.temperature_milli, - sampling, - }; - let mut acceptance_guard = AcceptanceGuard { - inner: self.inner.clone(), - id: command.request_id.clone(), - armed: true, - }; - let started = tokio::task::spawn_blocking(move || { - lock(&inner.backend)? - .start_generation(&loaded, backend_request) - .map_err(|e| backend_status(&e)) - }) - .await; - let stream = match started { - Ok(Ok(stream)) => stream, - other => { - let status = match other { - Ok(Err(status)) => status, - _ => Status::internal("generation_acceptance_uncertain"), - }; - if status - .metadata() - .get("x-leleka-accepted") - .and_then(|v| v.to_str().ok()) - == Some("false") - { - acceptance_guard.armed = false; - // This reservation is proved to have produced no accepted - // effects. Release only it, so the daemon's bounded retry - // may reuse the same identity. Uncertain/accepted IDs stay. - let mut state = lock(&self.inner.state)?; - state.requests.remove(&command.request_id); - if state.active.as_deref() == Some(&command.request_id) { - state.active = None; - } - publish(&self.inner, &mut state); - } else { - close_admission(&self.inner); - } - return Err(status); - } - }; - let (sender, receiver) = mpsc::channel(EVENT_QUEUE); - let inner = self.inner.clone(); - let id = command.request_id.clone(); - let epoch = command.expected_epoch.clone(); - tokio::task::spawn_blocking(move || pump(inner, id, epoch, stream, sender)); - acceptance_guard.armed = false; - let guarded = GenerationResponse { - receiver: ReceiverStream::new(receiver), - inner: self.inner.clone(), - id: command.request_id, - terminal: false, - }; - let mut response = Response::new(Box::pin(guarded) as Self::GenerateStream); - response.metadata_mut().insert( - "x-leleka-accepted", - "true".parse().expect("literal metadata"), - ); - Ok(response) - } - async fn reconfigure( - &self, - request: Request, - ) -> Result, Status> { - let _permit = self.authorize(&request, FRAME_LIMIT)?; - let command = request.into_inner(); - if command.settings_json.is_empty() || command.settings_json.len() > 4096 { - return Err(refusal(tonic::Code::InvalidArgument, "settings_size")); - } - { - let state = lock(&self.inner.state)?; - fence(&state, &command.expected_epoch)?; - if state.loaded.is_none() { - return Err(refusal(tonic::Code::FailedPrecondition, "no_model_loaded")); - } - if state.active.is_some() || state.lifecycle_busy { - return Err(refusal(tonic::Code::FailedPrecondition, "runtime_busy")); - } - } - let inner = self.inner.clone(); - let settings = command.settings_json.clone(); - let outcome = tokio::task::spawn_blocking(move || { - let mut backend = lock(&inner.backend)?; - Ok::<_, Status>(backend.reconfigure(&settings)) - }) - .await - .map_err(|_| Status::internal("reconfigure_uncertain"))??; - let reply = match outcome { - Ok(effective) => proto::ReconfigureReply { - operation_id: command.operation_id, - epoch: command.expected_epoch, - ok: true, - effective_json: effective, - ..Default::default() - }, - Err(error) => proto::ReconfigureReply { - operation_id: command.operation_id, - epoch: command.expected_epoch, - ok: false, - error_code: match error.code { - api::ErrorCode::InvalidRequest => "invalid", - api::ErrorCode::UnsupportedModel => "unsupported", - api::ErrorCode::ResourceExhausted => "exhausted", - api::ErrorCode::BackendUnavailable => "unavailable", - api::ErrorCode::Internal => "internal", - } - .to_owned(), - error: error.message, - retryable: error.retryable, - ..Default::default() - }, - }; - Ok(Response::new(reply)) - } - async fn cancel( - &self, - request: Request, - ) -> Result, Status> { - let _permit = self.authorize(&request, FRAME_LIMIT)?; - let command = request.into_inner(); - uuid(&command.request_id)?; - { - let state = lock(&self.inner.state)?; - fence(&state, &command.expected_epoch)?; - if !state.requests.contains(&command.request_id) { - return Err(refusal(tonic::Code::NotFound, "unknown_request")); - } - if state.active.as_deref() != Some(&command.request_id) { - return Ok(Response::new(proto::CancelAck { - request_id: command.request_id, - epoch: command.expected_epoch, - acknowledged: true, - })); - } - } - let inner = self.inner.clone(); - let id = command.request_id.clone(); - let outcome = tokio::task::spawn_blocking(move || { - let cancelled = lock(&inner.backend)? - .cancel(&id) - .map_err(|_| Status::internal("cancel_uncertain")); - // The request may have reached its terminal between the active - // check and the backend call; a finished request is already - // cancelled as far as the caller can observe. - if cancelled.is_err() && lock(&inner.state)?.active.as_deref() != Some(id.as_str()) { - return Ok(()); - } - cancelled - }) - .await - .map_err(|_| Status::internal("cancel_uncertain"))?; - outcome?; - Ok(Response::new(proto::CancelAck { - request_id: command.request_id, - epoch: command.expected_epoch, - acknowledged: true, - })) - } -} - -fn clear_active(inner: &Inner, id: &str) { - if let Ok(mut state) = inner.state.lock() - && state.active.as_deref() == Some(id) - { - state.active = None; - publish(inner, &mut state); - } -} /// A load/unload worker that panics must not leave the lifecycle gate shut /// with a stale "accepted" operation: it ends as indeterminate and model /// admission closes, exactly like any other uncertain lifecycle outcome. @@ -788,290 +74,33 @@ struct LifecycleGuard { /// completion, so a worker that finished can never touch a later operation. armed: bool, } -impl Drop for LifecycleGuard { - fn drop(&mut self) { - if !self.armed { - return; - } - if let Ok(mut state) = self.inner.state.lock() - && let Some(operation) = state.operations.get_mut(&self.operation_id) - && operation.result.state == proto::operation_result::State::Accepted as i32 - { - // Only this worker's own, still-unresolved operation is ended. - operation.result.state = proto::operation_result::State::Indeterminate as i32; - operation.result.reason = "lifecycle_worker_failed".into(); - state.lifecycle_busy = false; - state.loaded = None; - state.capabilities = api::BackendCapabilities::default(); - publish(&self.inner, &mut state); - } - } -} -fn close_admission(inner: &Inner) { - if let Ok(mut state) = inner.state.lock() { - state.loaded = None; - state.capabilities = api::BackendCapabilities::default(); - publish(inner, &mut state); - } -} -fn refresh_capabilities(inner: &Inner) { - // Observations must not wait behind a load/acceptance acknowledgement. - let (capabilities, summary, memory, telemetry) = match inner.backend.try_lock() { - Ok(backend) => ( - backend.capabilities(), - backend.prefix_cache_summary(), - backend.memory_report(), - backend.telemetry_report(), - ), - Err(std::sync::TryLockError::WouldBlock) => return, - Err(std::sync::TryLockError::Poisoned(_)) => { - (api::BackendCapabilities::default(), None, None, None) - } - }; - if let Ok(mut state) = inner.state.lock() { - // the summary changes with every request; watchers are told about it only through a snapshot they ask for - state.prefix_cache_json = summary.unwrap_or_default(); - state.memory_json = memory.unwrap_or_default(); - state.telemetry_json = telemetry.unwrap_or_default(); - let capabilities = if state.loaded.is_some() { - capabilities - } else { - api::BackendCapabilities::default() - }; - if state.capabilities != capabilities { - state.capabilities = capabilities; - publish(inner, &mut state); - } - } -} -fn cancel_detached(inner: Arc, id: String) { - tokio::task::spawn_blocking(move || { - if let Ok(mut backend) = inner.backend.lock() { - let _ = backend.cancel(&id); - } - }); -} struct AcceptanceGuard { inner: Arc, id: String, armed: bool, } -impl Drop for AcceptanceGuard { - fn drop(&mut self) { - if self.armed { - // The caller lost observation before acceptance was resolved. Keep - // the request fence and withdraw readiness; cancellation alone is - // not proof that the device completed or that the slot is reusable. - close_admission(&self.inner); - cancel_detached(self.inner.clone(), self.id.clone()); - } - } -} -fn cancel_and_drain(inner: &Arc, id: &str, source: &mut api::GenerationStream) { - if let Ok(mut backend) = inner.backend.lock() { - let _ = backend.cancel(id); - } - // Only a real terminal permits slot reuse. Missing/uncertain completion - // retains admission closed; no EOF is interpreted as device completion. - while let Ok(Some(event)) = source.recv() { - if matches!(event, api::GenerationEvent::Terminal(_)) { - refresh_capabilities(inner); - clear_active(inner, id); - break; - } - } -} -/// Releases the generation slot only for a terminal the backend really sent. -/// A synthesized terminal (the backend channel ended without one) gives no -/// completion proof, so the slot stays owned and model admission closes. -fn settle( - inner: &Arc, - id: &str, - source: &mut api::GenerationStream, - terminal: bool, - confirmed: bool, -) { - if terminal && confirmed { - refresh_capabilities(inner); - clear_active(inner, id); - } else if terminal { - close_admission(inner); - } else { - cancel_and_drain(inner, id, source); - } -} struct GenerationResponse { receiver: ReceiverStream>, inner: Arc, id: String, terminal: bool, } -impl Stream for GenerationResponse { - type Item = Result; - fn poll_next(mut self: Pin<&mut Self>, context: &mut Context<'_>) -> Poll> { - let result = Pin::new(&mut self.receiver).poll_next(context); - if let Poll::Ready(Some(Ok(frame))) = &result - && matches!( - frame.payload, - Some(proto::generation_frame::Payload::Terminal(_)) - ) - { - self.terminal = true; - } - result - } -} -impl Drop for GenerationResponse { - fn drop(&mut self) { - if !self.terminal { - cancel_detached(self.inner.clone(), self.id.clone()); - } - } -} -fn pump( - inner: Arc, - id: String, - epoch: String, - mut source: api::GenerationStream, - sender: mpsc::Sender>, -) { - let mut sequence = 1; - let accepted = proto::GenerationFrame { - request_id: id.clone(), - epoch: epoch.clone(), - sequence, - payload: Some(proto::generation_frame::Payload::Accepted( - proto::Accepted { accepted: true }, - )), - }; - if sender.blocking_send(Ok(accepted)).is_err() { - cancel_and_drain(&inner, &id, &mut source); - return; - } - loop { - let (event, confirmed) = match source.recv() { - Ok(Some(event)) => (event, true), - _ => ( - api::GenerationEvent::Terminal(api::GenerationTerminal::Failed { - code: api::ErrorCode::Internal, - message: "missing_terminal".into(), - retryable: false, - }), - false, - ), - }; - sequence += 1; - let terminal = matches!(event, api::GenerationEvent::Terminal(_)); - let frame = proto::GenerationFrame { - request_id: id.clone(), - epoch: epoch.clone(), - sequence, - payload: Some(event_to_proto(event)), - }; - if frame.encoded_len() > FRAME_LIMIT { - let failed = proto::GenerationFrame { - request_id: id.clone(), - epoch: epoch.clone(), - sequence, - payload: Some(event_to_proto(api::GenerationEvent::Terminal( - api::GenerationTerminal::Failed { - code: api::ErrorCode::ResourceExhausted, - message: "output_frame_limit".into(), - retryable: false, - }, - ))), - }; - let _ = sender.blocking_send(Ok(failed)); - settle(&inner, &id, &mut source, terminal, confirmed); - return; - } - if sender.blocking_send(Ok(frame)).is_err() { - settle(&inner, &id, &mut source, terminal, confirmed); - return; - } - if terminal { - settle(&inner, &id, &mut source, terminal, confirmed); - break; - } - } -} - -fn capabilities_to_proto(value: &api::BackendCapabilities) -> proto::Capabilities { - proto::Capabilities { - models: value - .supported_models - .iter() - .map(|m| proto::SupportedModelTuple { - family: m.family.clone(), - architecture: m.architecture.clone(), - weight_format: m.weight_format.clone(), - }) - .collect(), - max_concurrent_generations: u32::try_from(value.max_concurrent_generations).unwrap_or(0), - cancellation: value.supports_cancellation, - tool_call_streaming: value.supports_tool_call_streaming, - } -} -fn usage_to_proto(value: api::Usage) -> proto::Usage { - proto::Usage { - input_tokens: value.input_tokens, - output_tokens: value.output_tokens, - reused_input_tokens: value.reused_input_tokens, - } -} -fn event_to_proto(value: api::GenerationEvent) -> proto::generation_frame::Payload { - use proto::generation_frame::Payload; - match value { - api::GenerationEvent::TextDelta { text } => Payload::Text(proto::TextDelta { text }), - api::GenerationEvent::ToolCallDelta { - index, - id, - name, - arguments_delta, - } => Payload::Tool(proto::ToolCallDelta { - index, - id, - name, - arguments_delta, - }), - api::GenerationEvent::Usage(usage) => Payload::Usage(usage_to_proto(usage)), - api::GenerationEvent::Terminal(terminal) => Payload::Terminal(match terminal { - api::GenerationTerminal::Completed { reason, usage } => proto::Terminal { - state: 1, - reason: match reason { - api::FinishReason::Stop => "stop", - api::FinishReason::Length => "length", - api::FinishReason::ToolCalls => "tool_calls", - } - .into(), - usage: Some(usage_to_proto(usage)), - error_code: String::new(), - retryable: false, - }, - api::GenerationTerminal::Cancelled => proto::Terminal { - state: 3, - reason: "cancelled".into(), - usage: None, - error_code: String::new(), - retryable: false, - }, - api::GenerationTerminal::Failed { code, .. } => proto::Terminal { - state: 2, - reason: "generation_failed".into(), - usage: None, - error_code: match code { - api::ErrorCode::InvalidRequest => "invalid_request", - api::ErrorCode::UnsupportedModel => "unsupported_model", - api::ErrorCode::ResourceExhausted => "resource_exhausted", - api::ErrorCode::BackendUnavailable => "backend_unavailable", - api::ErrorCode::Internal => "internal", - } - .into(), - retryable: false, - }, - }), - } -} #[cfg(test)] mod tests; + +mod lock; +#[allow(unused_imports)] +pub use lock::*; +mod impl_runtimeserver; +#[allow(unused_imports)] +pub use impl_runtimeserver::*; +mod impl_proto_runtime_server_runtime; +#[allow(unused_imports)] +pub use impl_proto_runtime_server_runtime::*; +mod clear_active; +#[allow(unused_imports)] +pub use clear_active::*; +mod event_to_proto; +#[allow(unused_imports)] +pub use event_to_proto::*; diff --git a/desktop-core/src/runtime_rpc/clear_active.rs b/desktop-core/src/runtime_rpc/clear_active.rs new file mode 100644 index 00000000..fa0aa66d --- /dev/null +++ b/desktop-core/src/runtime_rpc/clear_active.rs @@ -0,0 +1,233 @@ +//! Moved out of the parent module by STRA-338: fn clear_active, impl Drop_for_LifecycleGuard, fn close_admission, fn refresh_capabilities, fn cancel_detached, impl Drop_for_AcceptanceGuard .... + +#[allow(unused_imports)] +use super::*; + +pub(super) fn clear_active(inner: &Inner, id: &str) { + if let Ok(mut state) = inner.state.lock() + && state.active.as_deref() == Some(id) + { + state.active = None; + publish(inner, &mut state); + } +} +impl Drop for LifecycleGuard { + fn drop(&mut self) { + if !self.armed { + return; + } + if let Ok(mut state) = self.inner.state.lock() + && let Some(operation) = state.operations.get_mut(&self.operation_id) + && operation.result.state == proto::operation_result::State::Accepted as i32 + { + // Only this worker's own, still-unresolved operation is ended. + operation.result.state = proto::operation_result::State::Indeterminate as i32; + operation.result.reason = "lifecycle_worker_failed".into(); + state.lifecycle_busy = false; + state.loaded = None; + state.capabilities = api::BackendCapabilities::default(); + publish(&self.inner, &mut state); + } + } +} +pub(super) fn close_admission(inner: &Inner) { + if let Ok(mut state) = inner.state.lock() { + state.loaded = None; + state.capabilities = api::BackendCapabilities::default(); + publish(inner, &mut state); + } +} +pub(super) fn refresh_capabilities(inner: &Inner) { + // Observations must not wait behind a load/acceptance acknowledgement. + let (capabilities, summary, memory, telemetry) = match inner.backend.try_lock() { + Ok(backend) => ( + backend.capabilities(), + backend.prefix_cache_summary(), + backend.memory_report(), + backend.telemetry_report(), + ), + Err(std::sync::TryLockError::WouldBlock) => return, + Err(std::sync::TryLockError::Poisoned(_)) => { + (api::BackendCapabilities::default(), None, None, None) + } + }; + if let Ok(mut state) = inner.state.lock() { + // the summary changes with every request; watchers are told about it only through a snapshot they ask for + state.prefix_cache_json = summary.unwrap_or_default(); + state.memory_json = memory.unwrap_or_default(); + state.telemetry_json = telemetry.unwrap_or_default(); + let capabilities = if state.loaded.is_some() { + capabilities + } else { + api::BackendCapabilities::default() + }; + if state.capabilities != capabilities { + state.capabilities = capabilities; + publish(inner, &mut state); + } + } +} +pub(super) fn cancel_detached(inner: Arc, id: String) { + tokio::task::spawn_blocking(move || { + if let Ok(mut backend) = inner.backend.lock() { + let _ = backend.cancel(&id); + } + }); +} +impl Drop for AcceptanceGuard { + fn drop(&mut self) { + if self.armed { + // The caller lost observation before acceptance was resolved. Keep + // the request fence and withdraw readiness; cancellation alone is + // not proof that the device completed or that the slot is reusable. + close_admission(&self.inner); + cancel_detached(self.inner.clone(), self.id.clone()); + } + } +} +pub(super) fn cancel_and_drain(inner: &Arc, id: &str, source: &mut api::GenerationStream) { + if let Ok(mut backend) = inner.backend.lock() { + let _ = backend.cancel(id); + } + // Only a real terminal permits slot reuse. Missing/uncertain completion + // retains admission closed; no EOF is interpreted as device completion. + while let Ok(Some(event)) = source.recv() { + if matches!(event, api::GenerationEvent::Terminal(_)) { + refresh_capabilities(inner); + clear_active(inner, id); + break; + } + } +} +/// Releases the generation slot only for a terminal the backend really sent. +/// A synthesized terminal (the backend channel ended without one) gives no +/// completion proof, so the slot stays owned and model admission closes. +pub(super) fn settle( + inner: &Arc, + id: &str, + source: &mut api::GenerationStream, + terminal: bool, + confirmed: bool, +) { + if terminal && confirmed { + refresh_capabilities(inner); + clear_active(inner, id); + } else if terminal { + close_admission(inner); + } else { + cancel_and_drain(inner, id, source); + } +} +impl Stream for GenerationResponse { + type Item = Result; + fn poll_next(mut self: Pin<&mut Self>, context: &mut Context<'_>) -> Poll> { + let result = Pin::new(&mut self.receiver).poll_next(context); + if let Poll::Ready(Some(Ok(frame))) = &result + && matches!( + frame.payload, + Some(proto::generation_frame::Payload::Terminal(_)) + ) + { + self.terminal = true; + } + result + } +} +impl Drop for GenerationResponse { + fn drop(&mut self) { + if !self.terminal { + cancel_detached(self.inner.clone(), self.id.clone()); + } + } +} +pub(super) fn pump( + inner: Arc, + id: String, + epoch: String, + mut source: api::GenerationStream, + sender: mpsc::Sender>, +) { + let mut sequence = 1; + let accepted = proto::GenerationFrame { + request_id: id.clone(), + epoch: epoch.clone(), + sequence, + payload: Some(proto::generation_frame::Payload::Accepted( + proto::Accepted { accepted: true }, + )), + }; + if sender.blocking_send(Ok(accepted)).is_err() { + cancel_and_drain(&inner, &id, &mut source); + return; + } + loop { + let (event, confirmed) = match source.recv() { + Ok(Some(event)) => (event, true), + _ => ( + api::GenerationEvent::Terminal(api::GenerationTerminal::Failed { + code: api::ErrorCode::Internal, + message: "missing_terminal".into(), + retryable: false, + }), + false, + ), + }; + sequence += 1; + let terminal = matches!(event, api::GenerationEvent::Terminal(_)); + let frame = proto::GenerationFrame { + request_id: id.clone(), + epoch: epoch.clone(), + sequence, + payload: Some(event_to_proto(event)), + }; + if frame.encoded_len() > FRAME_LIMIT { + let failed = proto::GenerationFrame { + request_id: id.clone(), + epoch: epoch.clone(), + sequence, + payload: Some(event_to_proto(api::GenerationEvent::Terminal( + api::GenerationTerminal::Failed { + code: api::ErrorCode::ResourceExhausted, + message: "output_frame_limit".into(), + retryable: false, + }, + ))), + }; + let _ = sender.blocking_send(Ok(failed)); + settle(&inner, &id, &mut source, terminal, confirmed); + return; + } + if sender.blocking_send(Ok(frame)).is_err() { + settle(&inner, &id, &mut source, terminal, confirmed); + return; + } + if terminal { + settle(&inner, &id, &mut source, terminal, confirmed); + break; + } + } +} + +pub(super) fn capabilities_to_proto(value: &api::BackendCapabilities) -> proto::Capabilities { + proto::Capabilities { + models: value + .supported_models + .iter() + .map(|m| proto::SupportedModelTuple { + family: m.family.clone(), + architecture: m.architecture.clone(), + weight_format: m.weight_format.clone(), + }) + .collect(), + max_concurrent_generations: u32::try_from(value.max_concurrent_generations).unwrap_or(0), + cancellation: value.supports_cancellation, + tool_call_streaming: value.supports_tool_call_streaming, + } +} +pub(super) fn usage_to_proto(value: api::Usage) -> proto::Usage { + proto::Usage { + input_tokens: value.input_tokens, + output_tokens: value.output_tokens, + reused_input_tokens: value.reused_input_tokens, + } +} diff --git a/desktop-core/src/runtime_rpc/event_to_proto.rs b/desktop-core/src/runtime_rpc/event_to_proto.rs new file mode 100644 index 00000000..eb7a11d7 --- /dev/null +++ b/desktop-core/src/runtime_rpc/event_to_proto.rs @@ -0,0 +1,58 @@ +//! Moved out of the parent module by STRA-338: fn event_to_proto. + +#[allow(unused_imports)] +use super::*; + +pub(super) fn event_to_proto(value: api::GenerationEvent) -> proto::generation_frame::Payload { + use proto::generation_frame::Payload; + match value { + api::GenerationEvent::TextDelta { text } => Payload::Text(proto::TextDelta { text }), + api::GenerationEvent::ToolCallDelta { + index, + id, + name, + arguments_delta, + } => Payload::Tool(proto::ToolCallDelta { + index, + id, + name, + arguments_delta, + }), + api::GenerationEvent::Usage(usage) => Payload::Usage(usage_to_proto(usage)), + api::GenerationEvent::Terminal(terminal) => Payload::Terminal(match terminal { + api::GenerationTerminal::Completed { reason, usage } => proto::Terminal { + state: 1, + reason: match reason { + api::FinishReason::Stop => "stop", + api::FinishReason::Length => "length", + api::FinishReason::ToolCalls => "tool_calls", + } + .into(), + usage: Some(usage_to_proto(usage)), + error_code: String::new(), + retryable: false, + }, + api::GenerationTerminal::Cancelled => proto::Terminal { + state: 3, + reason: "cancelled".into(), + usage: None, + error_code: String::new(), + retryable: false, + }, + api::GenerationTerminal::Failed { code, .. } => proto::Terminal { + state: 2, + reason: "generation_failed".into(), + usage: None, + error_code: match code { + api::ErrorCode::InvalidRequest => "invalid_request", + api::ErrorCode::UnsupportedModel => "unsupported_model", + api::ErrorCode::ResourceExhausted => "resource_exhausted", + api::ErrorCode::BackendUnavailable => "backend_unavailable", + api::ErrorCode::Internal => "internal", + } + .into(), + retryable: false, + }, + }), + } +} diff --git a/desktop-core/src/runtime_rpc/impl_proto_runtime_server_runtime.rs b/desktop-core/src/runtime_rpc/impl_proto_runtime_server_runtime.rs new file mode 100644 index 00000000..a4a2d98e --- /dev/null +++ b/desktop-core/src/runtime_rpc/impl_proto_runtime_server_runtime.rs @@ -0,0 +1,463 @@ +//! Moved out of the parent module by STRA-338: impl proto_runtime_server_Runtime. + +#[allow(unused_imports)] +use super::*; + +#[tonic::async_trait] +impl proto::runtime_server::Runtime for RuntimeServer { + async fn handshake( + &self, + request: Request, + ) -> Result, Status> { + let _permit = self.authorize(&request, FRAME_LIMIT)?; + let hello = request.into_inner(); + if hello.protocol_version != PROTOCOL_VERSION + || hello.backend_api_version != u32::from(api::BACKEND_API_VERSION) + { + return Err(refusal( + tonic::Code::FailedPrecondition, + "protocol_version_mismatch", + )); + } + Ok(Response::new(current_snapshot(&self.inner)?)) + } + async fn snapshot( + &self, + request: Request, + ) -> Result, Status> { + let _permit = self.authorize(&request, FRAME_LIMIT)?; + Ok(Response::new(current_snapshot(&self.inner)?)) + } + type WatchStream = WireStream; + async fn watch( + &self, + request: Request, + ) -> Result, Status> { + let _permit = self.authorize(&request, FRAME_LIMIT)?; + let watch_permit = self + .inner + .watchers + .clone() + .try_acquire_owned() + .map_err(|_| Status::resource_exhausted("watch_capacity"))?; + let mut changes = self.inner.changes.subscribe(); + let first = current_snapshot(&self.inner)?; + let inner = self.inner.clone(); + // Every notification is a full bounded observation, including cursor + // gaps/replacement epochs. It never starts or replays inference. + let stream = async_stream::try_stream! { + let _watch_permit = watch_permit; + let stopped = !first.transport_ready; + yield first; + if stopped { return; } + loop { + match changes.recv().await { + Ok(next) => { + let stopped = !next.transport_ready; + yield next; + if stopped { break; } + }, + Err(broadcast::error::RecvError::Lagged(_)) => { + let next = current_snapshot(&inner)?; + yield next; + } + Err(broadcast::error::RecvError::Closed) => break, + } + } + }; + Ok(Response::new(Box::pin(stream))) + } + async fn load( + &self, + request: Request, + ) -> Result, Status> { + let _permit = self.authorize(&request, FRAME_LIMIT)?; + let command = request.into_inner(); + let model = descriptor_from_proto( + command + .model + .as_ref() + .ok_or_else(|| refusal(tonic::Code::InvalidArgument, "missing_model"))?, + )?; + let config = config_from_proto( + command + .config + .as_ref() + .ok_or_else(|| refusal(tonic::Code::InvalidArgument, "missing_config"))?, + )?; + let mut canonical = command.clone(); + canonical.operation_id.clear(); + let digest = operation_digest(b"load\0", &canonical); + let (accepted, execute) = + self.reserve(&command.operation_id, &command.expected_epoch, digest)?; + if execute { + let inner = self.inner.clone(); + tokio::task::spawn_blocking(move || { + let mut guard = LifecycleGuard { + inner: inner.clone(), + operation_id: command.operation_id.clone(), + armed: true, + }; + let result = (|| { + let mut backend = lock(&inner.backend)?; + let loaded = backend + .load(model.clone(), config.clone()) + .map_err(|e| backend_status(&e))?; + loaded + .validate_for_load(&model, &config) + .map_err(|_| Status::internal("invalid_backend_load_result"))?; + Ok::<_, Status>((loaded, backend.capabilities())) + })(); + if let Ok(mut state) = inner.state.lock() { + let (phase, reason, loaded) = match result { + Ok((loaded, capabilities)) => { + state.loaded = Some(loaded.clone()); + state.capabilities = capabilities; + ( + proto::operation_result::State::Completed, + "completed", + Some(loaded_to_proto(&loaded)), + ) + } + Err(status) + if status + .metadata() + .get("x-leleka-accepted") + .and_then(|v| v.to_str().ok()) + == Some("false") => + { + (proto::operation_result::State::Failed, "load_failed", None) + } + Err(_) => { + state.loaded = None; + state.capabilities = api::BackendCapabilities::default(); + ( + proto::operation_result::State::Indeterminate, + "load_uncertain", + None, + ) + } + }; + if let Some(operation) = state.operations.get_mut(&command.operation_id) { + operation.result.state = phase as i32; + operation.result.reason = reason.into(); + operation.result.loaded = loaded; + } + state.lifecycle_busy = false; + guard.armed = false; + publish(&inner, &mut state); + } + }); + } + Ok(Response::new(accepted)) + } + async fn unload( + &self, + request: Request, + ) -> Result, Status> { + let _permit = self.authorize(&request, FRAME_LIMIT)?; + let command = request.into_inner(); + let mut canonical = command.clone(); + canonical.operation_id.clear(); + let digest = operation_digest(b"unload\0", &canonical); + let loaded = { + let state = lock(&self.inner.state)?; + fence(&state, &command.expected_epoch)?; + // Completed duplicates are resolved even when the model was unloaded. + if let Some(old) = state.operations.get(&command.operation_id) { + if old.digest != digest { + return Err(refusal(tonic::Code::AlreadyExists, "operation_conflict")); + } + return Ok(Response::new(old.result.clone())); + } + state + .loaded + .as_ref() + .filter(|m| m.handle == command.handle) + .cloned() + .ok_or_else(|| refusal(tonic::Code::FailedPrecondition, "stale_model_handle"))? + }; + let (accepted, execute) = + self.reserve(&command.operation_id, &command.expected_epoch, digest)?; + if execute { + let inner = self.inner.clone(); + tokio::task::spawn_blocking(move || { + let mut guard = LifecycleGuard { + inner: inner.clone(), + operation_id: command.operation_id.clone(), + armed: true, + }; + let result = lock(&inner.backend) + .and_then(|mut b| b.unload(loaded).map_err(|e| backend_status(&e))); + if let Ok(mut state) = inner.state.lock() { + // Failed/uncertain unload also closes model admission. + state.loaded = None; + state.capabilities = api::BackendCapabilities::default(); + if let Some(operation) = state.operations.get_mut(&command.operation_id) { + operation.result.state = if result.is_ok() { + proto::operation_result::State::Completed + } else { + proto::operation_result::State::Indeterminate + } as i32; + operation.result.reason = if result.is_ok() { + "completed" + } else { + "unload_uncertain" + } + .into(); + } + state.lifecycle_busy = false; + guard.armed = false; + publish(&inner, &mut state); + } + }); + } + Ok(Response::new(accepted)) + } + async fn operation( + &self, + request: Request, + ) -> Result, Status> { + let _permit = self.authorize(&request, FRAME_LIMIT)?; + let query = request.into_inner(); + uuid(&query.operation_id)?; + let state = lock(&self.inner.state)?; + if query.expected_epoch != state.epoch + || !state.operations.contains_key(&query.operation_id) + { + return Ok(Response::new(proto::OperationResult { + operation_id: query.operation_id, + epoch: state.epoch.clone(), + state: proto::operation_result::State::Indeterminate as i32, + reason: "unknown_operation".into(), + loaded: None, + })); + } + Ok(Response::new( + state.operations[&query.operation_id].result.clone(), + )) + } + type GenerateStream = WireStream; + async fn generate( + &self, + request: Request, + ) -> Result, Status> { + let _permit = self.authorize(&request, MESSAGE_LIMIT)?; + let command = request.into_inner(); + uuid(&command.request_id)?; + if command.prompt.len() > 1024 * 1024 + || command.max_output_tokens == 0 + || command.max_output_tokens > api::MAX_OUTPUT_TOKENS + { + return Err(refusal( + tonic::Code::InvalidArgument, + "unsupported_generation_request", + )); + } + // Sampling is served by the backend (Original sampler chain); the Original's documented + // ranges are enforced here too, so an out-of-contract request never reaches a worker. + let sampling = crate::runtime_sampling::to_backend(&command).map_err(|()| { + refusal( + tonic::Code::InvalidArgument, + "unsupported_generation_request", + ) + })?; + let loaded = { + let mut state = lock(&self.inner.state)?; + fence(&state, &command.expected_epoch)?; + if state.requests.contains(&command.request_id) { + // An old ID may have accepted/visible effects. Its rejection + // cannot authorize a retry of that identity on another member, + // including when this member's registry or slot is full. + return Err(Status::already_exists("generation_not_replayed")); + } + if state.active.is_some() + || state.lifecycle_busy + || state.stopping + || state.sequence == u64::MAX + { + return Err(refusal( + tonic::Code::ResourceExhausted, + "generation_capacity", + )); + } + let loaded = state + .loaded + .as_ref() + .filter(|m| m.handle == command.handle) + .cloned() + .ok_or_else(|| refusal(tonic::Code::FailedPrecondition, "stale_model_handle"))?; + if !state.capabilities.supports(&loaded.descriptor) { + return Err(refusal(tonic::Code::FailedPrecondition, "model_not_ready")); + } + state.requests.insert(&command.request_id); + state.active = Some(command.request_id.clone()); + publish(&self.inner, &mut state); + loaded + }; + let inner = self.inner.clone(); + let backend_request = api::GenerationRequest { + request_id: command.request_id.clone(), + prompt: command.prompt, + max_output_tokens: command.max_output_tokens, + temperature_milli: command.temperature_milli, + sampling, + }; + let mut acceptance_guard = AcceptanceGuard { + inner: self.inner.clone(), + id: command.request_id.clone(), + armed: true, + }; + let started = tokio::task::spawn_blocking(move || { + lock(&inner.backend)? + .start_generation(&loaded, backend_request) + .map_err(|e| backend_status(&e)) + }) + .await; + let stream = match started { + Ok(Ok(stream)) => stream, + other => { + let status = match other { + Ok(Err(status)) => status, + _ => Status::internal("generation_acceptance_uncertain"), + }; + if status + .metadata() + .get("x-leleka-accepted") + .and_then(|v| v.to_str().ok()) + == Some("false") + { + acceptance_guard.armed = false; + // This reservation is proved to have produced no accepted + // effects. Release only it, so the daemon's bounded retry + // may reuse the same identity. Uncertain/accepted IDs stay. + let mut state = lock(&self.inner.state)?; + state.requests.remove(&command.request_id); + if state.active.as_deref() == Some(&command.request_id) { + state.active = None; + } + publish(&self.inner, &mut state); + } else { + close_admission(&self.inner); + } + return Err(status); + } + }; + let (sender, receiver) = mpsc::channel(EVENT_QUEUE); + let inner = self.inner.clone(); + let id = command.request_id.clone(); + let epoch = command.expected_epoch.clone(); + tokio::task::spawn_blocking(move || pump(inner, id, epoch, stream, sender)); + acceptance_guard.armed = false; + let guarded = GenerationResponse { + receiver: ReceiverStream::new(receiver), + inner: self.inner.clone(), + id: command.request_id, + terminal: false, + }; + let mut response = Response::new(Box::pin(guarded) as Self::GenerateStream); + response.metadata_mut().insert( + "x-leleka-accepted", + "true".parse().expect("literal metadata"), + ); + Ok(response) + } + async fn reconfigure( + &self, + request: Request, + ) -> Result, Status> { + let _permit = self.authorize(&request, FRAME_LIMIT)?; + let command = request.into_inner(); + if command.settings_json.is_empty() || command.settings_json.len() > 4096 { + return Err(refusal(tonic::Code::InvalidArgument, "settings_size")); + } + { + let state = lock(&self.inner.state)?; + fence(&state, &command.expected_epoch)?; + if state.loaded.is_none() { + return Err(refusal(tonic::Code::FailedPrecondition, "no_model_loaded")); + } + if state.active.is_some() || state.lifecycle_busy { + return Err(refusal(tonic::Code::FailedPrecondition, "runtime_busy")); + } + } + let inner = self.inner.clone(); + let settings = command.settings_json.clone(); + let outcome = tokio::task::spawn_blocking(move || { + let mut backend = lock(&inner.backend)?; + Ok::<_, Status>(backend.reconfigure(&settings)) + }) + .await + .map_err(|_| Status::internal("reconfigure_uncertain"))??; + let reply = match outcome { + Ok(effective) => proto::ReconfigureReply { + operation_id: command.operation_id, + epoch: command.expected_epoch, + ok: true, + effective_json: effective, + ..Default::default() + }, + Err(error) => proto::ReconfigureReply { + operation_id: command.operation_id, + epoch: command.expected_epoch, + ok: false, + error_code: match error.code { + api::ErrorCode::InvalidRequest => "invalid", + api::ErrorCode::UnsupportedModel => "unsupported", + api::ErrorCode::ResourceExhausted => "exhausted", + api::ErrorCode::BackendUnavailable => "unavailable", + api::ErrorCode::Internal => "internal", + } + .to_owned(), + error: error.message, + retryable: error.retryable, + ..Default::default() + }, + }; + Ok(Response::new(reply)) + } + async fn cancel( + &self, + request: Request, + ) -> Result, Status> { + let _permit = self.authorize(&request, FRAME_LIMIT)?; + let command = request.into_inner(); + uuid(&command.request_id)?; + { + let state = lock(&self.inner.state)?; + fence(&state, &command.expected_epoch)?; + if !state.requests.contains(&command.request_id) { + return Err(refusal(tonic::Code::NotFound, "unknown_request")); + } + if state.active.as_deref() != Some(&command.request_id) { + return Ok(Response::new(proto::CancelAck { + request_id: command.request_id, + epoch: command.expected_epoch, + acknowledged: true, + })); + } + } + let inner = self.inner.clone(); + let id = command.request_id.clone(); + let outcome = tokio::task::spawn_blocking(move || { + let cancelled = lock(&inner.backend)? + .cancel(&id) + .map_err(|_| Status::internal("cancel_uncertain")); + // The request may have reached its terminal between the active + // check and the backend call; a finished request is already + // cancelled as far as the caller can observe. + if cancelled.is_err() && lock(&inner.state)?.active.as_deref() != Some(id.as_str()) { + return Ok(()); + } + cancelled + }) + .await + .map_err(|_| Status::internal("cancel_uncertain"))?; + outcome?; + Ok(Response::new(proto::CancelAck { + request_id: command.request_id, + epoch: command.expected_epoch, + acknowledged: true, + })) + } +} diff --git a/desktop-core/src/runtime_rpc/impl_runtimeserver.rs b/desktop-core/src/runtime_rpc/impl_runtimeserver.rs new file mode 100644 index 00000000..1e775a08 --- /dev/null +++ b/desktop-core/src/runtime_rpc/impl_runtimeserver.rs @@ -0,0 +1,150 @@ +//! Moved out of the parent module by STRA-338: impl RuntimeServer. + +#[allow(unused_imports)] +use super::*; + +impl RuntimeServer { + pub fn new(backend: Box, token: String) -> Result { + if !valid_token(&token) { + return Err(Status::invalid_argument("invalid_runtime_credential")); + } + if !backend.identity().supports_current_api() { + return Err(Status::failed_precondition("backend_api_mismatch")); + } + let (changes, _) = broadcast::channel(EVENT_QUEUE); + Ok(Self { + inner: Arc::new(Inner { + backend: Mutex::new(backend), + token, + state: Mutex::new(State { + epoch: Uuid::new_v4().to_string(), + sequence: 1, + loaded: None, + capabilities: api::BackendCapabilities::default(), + operations: HashMap::new(), + requests: api::RecentIds::default(), + lifecycle_busy: false, + active: None, + stopping: false, + prefix_cache_json: String::new(), + memory_json: String::new(), + telemetry_json: String::new(), + }), + changes, + controls: Arc::new(Semaphore::new(16)), + watchers: Arc::new(Semaphore::new(16)), + }), + }) + } + pub async fn serve( + self, + listener: TcpListener, + shutdown: F, + ) -> Result<(), Box> + where + F: std::future::Future + Send + 'static, + { + literal_loopback(listener.local_addr()?)?; + let shutdown_inner = self.inner.clone(); + let shutdown = async move { + shutdown.await; + let active = if let Ok(mut state) = shutdown_inner.state.lock() { + state.stopping = true; + publish(&shutdown_inner, &mut state); + state.active.clone() + } else { + None + }; + if let Some(id) = active { + cancel_detached(shutdown_inner, id); + } + }; + tonic::transport::Server::builder() + .max_concurrent_streams(64) + .add_service( + proto::runtime_server::RuntimeServer::new(self) + .max_decoding_message_size(MESSAGE_LIMIT) + .max_encoding_message_size(MESSAGE_LIMIT), + ) + // `serve_with_incoming*` ignores the builder's `tcp_nodelay`, and Nagle's algorithm plus the client's delayed ACK + // holds every small response frame (the accept of a generation, each text delta, the terminal) for up to ~40 ms + // on loopback: the sockets are accepted here, so set TCP_NODELAY here. + .serve_with_incoming_shutdown( + tonic::transport::server::TcpIncoming::from(listener).with_nodelay(Some(true)), + shutdown, + ) + .await?; + Ok(()) + } + pub(super) fn authorize( + &self, + request: &Request, + limit: usize, + ) -> Result { + if request + .remote_addr() + .is_none_or(|address| !address.ip().is_loopback()) + { + return Err(Status::permission_denied("loopback_required")); + } + let supplied = request + .metadata() + .get("authorization") + .and_then(|v| v.to_str().ok()) + .and_then(|v| v.strip_prefix("Bearer ")) + .unwrap_or(""); + if !bool::from(self.inner.token.as_bytes().ct_eq(supplied.as_bytes())) { + return Err(Status::unauthenticated("unauthorized")); + } + bounded(request.get_ref(), limit)?; + self.inner + .controls + .clone() + .try_acquire_owned() + .map_err(|_| refusal(tonic::Code::ResourceExhausted, "control_capacity")) + } + pub(super) fn reserve( + &self, + id: &str, + epoch: &str, + digest: [u8; 32], + ) -> Result<(proto::OperationResult, bool), Status> { + uuid(id)?; + let mut state = lock(&self.inner.state)?; + fence(&state, epoch)?; + if let Some(old) = state.operations.get(id) { + if old.digest != digest { + return Err(refusal(tonic::Code::AlreadyExists, "operation_conflict")); + } + return Ok((old.result.clone(), false)); + } + if state.operations.len() >= MAX_IDS + || state.lifecycle_busy + || state.active.is_some() + || state.sequence == u64::MAX + || state.stopping + { + return Err(refusal( + tonic::Code::ResourceExhausted, + "lifecycle_capacity", + )); + } + let result = proto::OperationResult { + operation_id: id.to_owned(), + epoch: state.epoch.clone(), + state: proto::operation_result::State::Accepted as i32, + reason: "accepted".into(), + loaded: None, + }; + state.operations.insert( + id.to_owned(), + Operation { + digest, + result: result.clone(), + }, + ); + state.lifecycle_busy = true; + publish(&self.inner, &mut state); + Ok((result, true)) + } +} diff --git a/desktop-core/src/runtime_rpc/lock.rs b/desktop-core/src/runtime_rpc/lock.rs new file mode 100644 index 00000000..f8e2e2d9 --- /dev/null +++ b/desktop-core/src/runtime_rpc/lock.rs @@ -0,0 +1,104 @@ +//! Moved out of the parent module by STRA-338: fn lock, fn uuid, fn backend_status, fn bounded, fn operation_digest, fn fence .... + +#[allow(unused_imports)] +use super::*; + +pub(super) fn lock(mutex: &Mutex) -> Result, Status> { + mutex + .lock() + .map_err(|_| Status::internal("runtime_state_unavailable")) +} +pub(super) fn uuid(value: &str) -> Result<(), Status> { + if Uuid::parse_str(value).is_err() || value.len() != 36 { + return Err(refusal(tonic::Code::InvalidArgument, "invalid_uuid")); + } + Ok(()) +} +pub(super) fn backend_status(error: &api::BackendError) -> Status { + let (code, reason) = match error.code { + api::ErrorCode::InvalidRequest => (tonic::Code::InvalidArgument, "invalid_generation"), + api::ErrorCode::UnsupportedModel => (tonic::Code::FailedPrecondition, "unsupported_model"), + api::ErrorCode::ResourceExhausted => (tonic::Code::ResourceExhausted, "runtime_capacity"), + api::ErrorCode::BackendUnavailable => (tonic::Code::Unavailable, "backend_unavailable"), + api::ErrorCode::Internal => (tonic::Code::Internal, "backend_failed"), + }; + // Unavailable/Internal can be a delivered-command acknowledgement failure. + // Only the facade's validation/capacity errors prove nonacceptance. + if matches!( + error.code, + api::ErrorCode::BackendUnavailable | api::ErrorCode::Internal + ) { + Status::new(code, reason) + } else { + refusal(code, reason) + } +} +pub(super) fn bounded(value: &T, limit: usize) -> Result<(), Status> { + if value.encoded_len() > limit { + return Err(refusal(tonic::Code::ResourceExhausted, "message_limit")); + } + Ok(()) +} +pub(super) fn operation_digest(kind: &[u8], value: &T) -> [u8; 32] { + let mut hash = Sha256::new(); + hash.update(kind); + hash.update(value.encode_to_vec()); + hash.finalize().into() +} +pub(super) fn fence(state: &State, epoch: &str) -> Result<(), Status> { + if epoch != state.epoch { + return Err(refusal(tonic::Code::FailedPrecondition, "epoch_mismatch")); + } + Ok(()) +} +pub(super) fn snapshot(state: &State) -> proto::Snapshot { + proto::Snapshot { + protocol_version: PROTOCOL_VERSION, + backend_api_version: u32::from(api::BACKEND_API_VERSION), + epoch: state.epoch.clone(), + sequence: state.sequence, + full_snapshot: true, + transport_ready: !state.stopping, + model_ready: state + .loaded + .as_ref() + .is_some_and(|m| state.capabilities.supports(&m.descriptor)) + && !state.stopping, + loaded: if state.stopping { + None + } else { + state.loaded.as_ref().map(loaded_to_proto) + }, + capabilities: Some(if state.stopping { + proto::Capabilities::default() + } else { + capabilities_to_proto(&state.capabilities) + }), + active_request_id: state.active.clone().unwrap_or_default(), + prefix_cache_json: if state.stopping { + String::new() + } else { + state.prefix_cache_json.clone() + }, + memory_json: if state.stopping { + String::new() + } else { + state.memory_json.clone() + }, + telemetry_json: if state.stopping { + String::new() + } else { + state.telemetry_json.clone() + }, + } +} +pub(super) fn publish(inner: &Inner, state: &mut State) { + // Saturation closes future mutations rather than wrapping the cursor. + state.sequence = state.sequence.saturating_add(1); + let _ = inner.changes.send(snapshot(state)); +} +pub(super) fn current_snapshot(inner: &Inner) -> Result { + refresh_capabilities(inner); + let state = lock(&inner.state)?; + Ok(snapshot(&state)) +} diff --git a/desktop-core/src/runtime_tools.rs b/desktop-core/src/runtime_tools.rs index c1d8a72f..fbece5e8 100644 --- a/desktop-core/src/runtime_tools.rs +++ b/desktop-core/src/runtime_tools.rs @@ -51,460 +51,7 @@ enum Choice { }, } -fn fields<'a>( - value: &'a Value, - allowed: &[&str], -) -> Result<&'a serde_json::Map, &'static str> { - let object = value.as_object().ok_or("expected_object")?; - if object.keys().any(|key| !allowed.contains(&key.as_str())) { - return Err("unsupported_field"); - } - Ok(object) -} - -fn optional_text(value: &Value, key: &str) -> Result<(), &'static str> { - if value.get(key).is_some_and(|v| !v.is_string()) { - return Err("invalid_text_field"); - } - Ok(()) -} - -fn local_refs(value: &Value) -> Result<(), &'static str> { - match value { - Value::Object(object) => { - for (key, child) in object { - if matches!(key.as_str(), "$ref" | "$dynamicRef" | "$recursiveRef") - && child - .as_str() - .is_none_or(|reference| !reference.starts_with('#')) - { - return Err("schema_references_must_be_local"); - } - local_refs(child)?; - } - } - Value::Array(array) => { - for child in array { - local_refs(child)?; - } - } - _ => {} - } - Ok(()) -} - -fn add_identity( - tool: &Value, - namespace: Option<&str>, - identities: &mut HashMap, -) -> Result<(), &'static str> { - let custom = match tool["type"].as_str() { - Some("function") => false, - Some("custom") => true, - _ => return Err("unsupported_tool_type"), - }; - fields( - tool, - if custom { - &["type", "name", "description", "format"] - } else { - &["type", "name", "description", "parameters", "strict"] - }, - )?; - optional_text(tool, "description")?; - if tool.get("strict").is_some_and(|v| !v.is_boolean()) { - return Err("invalid_strict"); - } - if let Some(schema) = tool.get("parameters") { - if !schema.is_object() || schema["type"] != "object" { - return Err("parameters_must_be_object_schema"); - } - local_refs(schema)?; - } - let name = tool["name"].as_str().ok_or("tool_name_required")?; - let flat_name = alias(name, namespace)?; - if identities.len() >= TOOL_LIMIT - || identities - .insert( - flat_name, - Identity { - name: name.to_owned(), - namespace: namespace.map(str::to_owned), - custom, - }, - ) - .is_some() - { - return Err("tool_limit_or_duplicate_identity"); - } - Ok(()) -} - -impl ToolPolicy { - fn new( - tools: &[Value], - selection: Option<&Value>, - parallel: bool, - ) -> Result { - if tools.len() > TOOL_LIMIT { - return Err("tool_limit"); - } - let mut identities = HashMap::new(); - for tool in tools { - if tool["type"] == "namespace" { - fields(tool, &["type", "name", "description", "tools"])?; - optional_text(tool, "description")?; - let name = tool["name"].as_str().ok_or("namespace_name_required")?; - alias(name, None)?; - let children = tool["tools"].as_array().ok_or("namespace_tools_required")?; - if children.is_empty() || children.len() > TOOL_LIMIT { - return Err("invalid_namespace_tools"); - } - for child in children { - add_identity(child, Some(name), &mut identities)?; - } - } else { - add_identity(tool, None, &mut identities)?; - } - } - let catalog = Catalog::new(tools)?; - let mut schemas = HashMap::new(); - for tool in &catalog.flat { - let schema = tool - .get("parameters") - .cloned() - .unwrap_or_else(|| json!({"type":"object"})); - local_refs(&schema)?; - let validator = jsonschema::options() - .offline() - .build(&schema) - .map_err(|_| "invalid_tool_schema")?; - schemas.insert( - tool["name"] - .as_str() - .ok_or("tool_name_required")? - .to_owned(), - validator, - ); - } - let mut policy = Self { - catalog, - identities, - schemas, - choice: Choice::Auto, - parallel, - }; - policy.choice = match selection { - None => Choice::Auto, - Some(Value::String(choice)) => match choice.as_str() { - "none" => Choice::None, - "auto" => Choice::Auto, - "required" if !policy.identities.is_empty() => Choice::Required, - _ => return Err("invalid_tool_choice"), - }, - Some(choice) if choice["type"] == "allowed_tools" => { - fields(choice, &["type", "mode", "tools"])?; - let required = match choice["mode"].as_str() { - Some("auto") => false, - Some("required") => true, - _ => return Err("invalid_allowed_tools_mode"), - }; - let selectors = choice["tools"].as_array().ok_or("allowed_tools_required")?; - if selectors.is_empty() || selectors.len() > TOOL_LIMIT { - return Err("invalid_allowed_tools"); - } - let mut names = HashSet::new(); - for selector in selectors { - let name = policy.selector(selector)?; - if !names.insert(name) { - return Err("duplicate_allowed_tool"); - } - } - Choice::Allowed { required, names } - } - Some(choice) => Choice::Forced(policy.selector(choice)?), - }; - Ok(policy) - } - - fn selector(&self, value: &Value) -> Result { - fields(value, &["type", "name", "namespace"])?; - let custom = match value["type"].as_str() { - Some("function") => false, - Some("custom") => true, - _ => return Err("invalid_tool_selector"), - }; - self.identity(value, custom) - } - - fn identity(&self, value: &Value, custom: bool) -> Result { - let name = value["name"].as_str().ok_or("tool_name_required")?; - let namespace = value - .get("namespace") - .map(|v| v.as_str().ok_or("invalid_namespace")) - .transpose()?; - let flat = alias(name, namespace)?; - let identity = self.identities.get(&flat).ok_or("undeclared_tool")?; - if identity.name != name - || identity.namespace.as_deref() != namespace - || identity.custom != custom - { - return Err("tool_identity_mismatch"); - } - Ok(flat) - } - - fn validated_call(&self, name: &str, arguments: &Value) -> Result { - if !arguments.is_object() - || !self - .schemas - .get(name) - .ok_or("undeclared_tool")? - .is_valid(arguments) - { - return Err("invalid_tool_arguments"); - } - let mut item = json!({"type":"function_call","name":name,"arguments":arguments.to_string(),"status":"completed"}); - self.catalog - .restore(&mut item) - .map_err(|_| "invalid_custom_input_or_grammar")?; - item.as_object_mut() - .ok_or("invalid_tool_item")? - .remove("status"); - Ok(item) - } - - pub fn parse_output(&self, output: &str) -> Result, &'static str> { - if output.len() > OUTPUT_LIMIT { - return Err("output_limit"); - } - let parsed = runtime_tool_parser::parse_complete(output, &self.catalog.flat) - .map_err(|_| "invalid_tool_output")?; - let mut result = Vec::new(); - let mut calls = 0usize; - for segment in parsed { - match segment { - Segment::Text(text) => { - if reserved_markup(&text) { - return Err("incomplete_or_orphan_tool_markup"); - } - result.push(ValidatedSegment::Text(text)); - } - Segment::Call { name, arguments } => { - calls += 1; - if calls > TOOL_LIMIT || (!self.parallel && calls > 1) { - return Err("tool_call_count"); - } - match &self.choice { - Choice::None => return Err("tool_choice_none"), - Choice::Forced(wanted) if wanted != &name || calls > 1 => { - return Err("forced_tool_mismatch"); - } - Choice::Allowed { names, .. } if !names.contains(&name) => { - return Err("tool_not_allowed"); - } - _ => {} - } - result.push(ValidatedSegment::Call( - self.validated_call(&name, &arguments)?, - )); - } - } - } - if calls == 0 - && matches!( - self.choice, - Choice::Required | Choice::Forced(_) | Choice::Allowed { required: true, .. } - ) - { - return Err("required_tool_missing"); - } - Ok(result) - } - - fn choice_instruction(&self) -> Option { - match &self.choice { - Choice::None => None, - Choice::Auto => None, - Choice::Required => { - Some("Call at least one declared tool in this response.".to_owned()) - } - Choice::Forced(name) => Some(format!( - "Call exactly one tool named {name} in this response." - )), - Choice::Allowed { required, names } => { - let mut names = names.iter().map(String::as_str).collect::>(); - names.sort_unstable(); - Some(format!( - "Only these tools may be called: {}. {}", - names.join(", "), - if *required { - "Call at least one." - } else { - "A text response is also allowed." - } - )) - } - } - } -} - -// Whole parsing cannot turn an unfinished or orphan control delimiter into text. -fn reserved_markup(text: &str) -> bool { - const TAGS: [&str; 6] = [ - "", - "", - "", - "", - ]; - [ - "')) - || (2..tag.len()).any(|length| text.ends_with(&tag[..length])) - }) -} - struct Count(usize); -impl Write for Count { - fn write(&mut self, bytes: &[u8]) -> io::Result { - self.0 = self - .0 - .checked_add(bytes.len()) - .filter(|size| *size <= REQUEST_LIMIT) - .ok_or_else(|| io::Error::other("request_limit"))?; - Ok(bytes.len()) - } - fn flush(&mut self) -> io::Result<()> { - Ok(()) - } -} - -pub fn prepare(request: &Value) -> Result { - serde_json::to_writer(Count(0), request).map_err(|_| "request_limit")?; - let object = fields( - request, - &[ - "model", - "input", - "instructions", - "stream", - "max_output_tokens", - "temperature", - "top_p", - "top_k", - "min_p", - "repetition_penalty", - "frequency_penalty", - "presence_penalty", - "penalty_last_n", - "seed", - "store", - "tools", - "tool_choice", - "parallel_tool_calls", - "text", - ], - )?; - if request["model"].as_str().is_none_or(str::is_empty) { - return Err("model_required"); - } - if object.get("stream").is_some_and(|v| !v.is_boolean()) { - return Err("invalid_stream"); - } - if object - .get("store") - .is_some_and(|v| v != &Value::Bool(false)) - { - return Err("unsupported_sampling_or_store"); - } - let sampling = crate::runtime_sampling::from_json(object)?; - if object - .get("text") - .is_some_and(|v| v != &json!({"format":{"type":"text"}})) - { - return Err("unsupported_text_format"); - } - let cap = object - .get("max_output_tokens") - .map(|v| v.as_u64().ok_or("invalid_output_limit")) - .transpose()? - .unwrap_or(256); - if !(1..=4096).contains(&cap) { - return Err("invalid_output_limit"); - } - let tools = object - .get("tools") - .map(|v| v.as_array().ok_or("invalid_tools")) - .transpose()? - .map(Vec::as_slice) - .unwrap_or(&[]); - let parallel = object - .get("parallel_tool_calls") - .map(|v| v.as_bool().ok_or("invalid_parallel_tool_calls")) - .transpose()? - .unwrap_or(true); - let policy = ToolPolicy::new(tools, object.get("tool_choice"), parallel)?; - let mut owned = Vec::new(); - if let Some(instructions) = object.get("instructions") { - owned.push(( - Role::System, - instructions - .as_str() - .ok_or("invalid_instructions")? - .to_owned(), - )); - } - if let Some(instruction) = policy.choice_instruction() { - owned.push((Role::System, instruction)); - } - if !parallel && !tools.is_empty() { - owned.push(( - Role::System, - "Call at most one tool in this response.".to_owned(), - )); - } - history( - object.get("input").ok_or("input_required")?, - &policy, - &mut owned, - )?; - let messages = owned - .iter() - .map(|(role, content)| Message { - role: *role, - content, - reasoning: None, - parts: None, - }) - .collect::>(); - let flat = if matches!(policy.choice, Choice::None) { - &[][..] - } else { - &policy.catalog.flat[..] - }; - let prompt = crate::runtime_prompt::render_with_tools(&messages, Effort::None, flat) - .map_err(|_| "prompt template rendering failed")?; - if prompt.len() > REQUEST_LIMIT { - return Err("prompt_limit"); - } - Ok(ToolPlan { - prompt, - max_output_tokens: cap as u32, - policy, - sampling, - }) -} struct Pending { id: String, @@ -513,212 +60,15 @@ struct Pending { output: Option, } -fn content(value: &Value, output: bool) -> Result { - if let Some(text) = value.as_str() { - return Ok(text.to_owned()); - } - let parts = value.as_array().ok_or("invalid_content")?; - if parts.len() > ITEM_LIMIT { - return Err("content_limit"); - } - let mut text = String::new(); - for (index, part) in parts.iter().enumerate() { - fields(part, &["type", "text", "annotations", "logprobs"])?; - for key in ["annotations", "logprobs"] { - if part.get(key).is_some_and(|metadata| { - part["type"] != "output_text" - || metadata.as_array().is_none_or(|items| !items.is_empty()) - }) { - return Err("unsupported_output_metadata"); - } - } - if !matches!(part["type"].as_str(), Some("input_text" | "output_text")) - || (output && part["type"] != "input_text") - { - return Err("unsupported_content"); - } - if output && index > 0 { - text.push('\n'); - } - text.push_str(part["text"].as_str().ok_or("invalid_text")?); - } - Ok(text) -} - -fn valid_id(value: &Value) -> Result<&str, &'static str> { - let id = value.as_str().ok_or("call_id_required")?; - if id.is_empty() || id.len() > 256 || !id.bytes().all(|b| b.is_ascii_graphic()) { - return Err("invalid_call_id"); - } - Ok(id) -} - -fn history( - input: &Value, - policy: &ToolPolicy, - owned: &mut Vec<(Role, String)>, -) -> Result<(), &'static str> { - if let Some(text) = input.as_str() { - owned.push((Role::User, text.to_owned())); - return Ok(()); - } - let items = input.as_array().ok_or("invalid_input")?; - if items.is_empty() || items.len() > ITEM_LIMIT { - return Err("input_item_limit"); - } - let mut pending: Vec = Vec::new(); - let mut seen = HashSet::new(); - let mut item_ids = HashSet::new(); - for item in items { - if let Some(id) = item.get("id") - && !item_ids.insert(valid_id(id)?.to_owned()) - { - return Err("duplicate_item_id"); - } - let kind = item - .get("type") - .map(|v| v.as_str().ok_or("invalid_item_type")) - .transpose()? - .unwrap_or("message"); - match kind { - "message" => { - fields(item, &["type", "id", "status", "role", "content"])?; - completed_item(item)?; - if !pending.is_empty() { - return Err("unresolved_tool_history"); - } - let role = match item["role"].as_str() { - Some("system") => Role::System, - Some("developer") => Role::Developer, - Some("user") => Role::User, - Some("assistant") => Role::Assistant, - _ => return Err("invalid_role"), - }; - owned.push(( - role, - content(item.get("content").ok_or("content_required")?, false)?, - )); - } - "function_call" | "custom_tool_call" => { - let custom = kind == "custom_tool_call"; - fields( - item, - if custom { - &[ - "type", - "id", - "status", - "call_id", - "name", - "namespace", - "input", - ] - } else { - &[ - "type", - "id", - "status", - "call_id", - "name", - "namespace", - "arguments", - ] - }, - )?; - completed_item(item)?; - if pending.iter().any(|call| call.output.is_some()) { - return Err("call_after_tool_result"); - } - let id = valid_id(&item["call_id"])?; - if !seen.insert(id.to_owned()) { - return Err("duplicate_call_id"); - } - let name = policy.identity(item, custom)?; - let arguments = if custom { - json!({"input":item["input"].as_str().ok_or("custom_input_required")?}) - } else { - serde_json::from_str(item["arguments"].as_str().ok_or("arguments_required")?) - .map_err(|_| "invalid_history_arguments")? - }; - policy.validated_call(&name, &arguments)?; - let mut markup = format!("\n\n"); - for (parameter, value) in arguments.as_object().ok_or("arguments_must_be_object")? { - alias(parameter, None).map_err(|_| "unsafe_parameter_name")?; - markup.push_str(&format!("\n")); - if let Some(text) = value.as_str() { - markup.push_str(text); - } else { - markup.push_str(&value.to_string()); - } - markup.push_str("\n\n"); - } - markup.push_str("\n"); - pending.push(Pending { - id: id.to_owned(), - custom, - markup, - output: None, - }); - } - "function_call_output" | "custom_tool_call_output" => { - fields(item, &["type", "id", "status", "call_id", "output"])?; - completed_item(item)?; - let id = valid_id(&item["call_id"])?; - let call = pending - .iter_mut() - .find(|call| call.id == id) - .ok_or("orphan_tool_result")?; - if call.custom != (kind == "custom_tool_call_output") || call.output.is_some() { - return Err("tool_result_identity_or_duplicate"); - } - call.output = Some(content(item.get("output").ok_or("output_required")?, true)?); - if pending.iter().all(|call| call.output.is_some()) { - let call_text = pending - .iter() - .map(|call| call.markup.as_str()) - .collect::>() - .join("\n"); - let output_text = pending - .iter() - .map(|call| { - format!( - "\n{}\n", - call.output.as_deref().unwrap_or_default() - ) - }) - .collect::>() - .join("\n"); - if let Some((Role::Assistant, text)) = owned.last_mut() { - text.truncate(text.trim_end().len()); - if !text.is_empty() { - text.push_str("\n\n"); - } - text.push_str(&call_text); - } else { - owned.push((Role::Assistant, call_text)); - } - owned.push((Role::User, output_text)); - pending.clear(); - } - } - _ => return Err("unsupported_input_item"), - } - } - if !pending.is_empty() { - return Err("unresolved_tool_history"); - } - Ok(()) -} - -fn completed_item(item: &Value) -> Result<(), &'static str> { - if let Some(id) = item.get("id") { - valid_id(id)?; - } - if item - .get("status") - .is_some_and(|status| status != "completed") - { - return Err("incomplete_history_item"); - } - Ok(()) -} +mod fields; +#[allow(unused_imports)] +pub use fields::*; +mod impl_toolpolicy; +#[allow(unused_imports)] +pub use impl_toolpolicy::*; +mod impl_write_for_count; +#[allow(unused_imports)] +pub use impl_write_for_count::*; +mod history; +#[allow(unused_imports)] +pub use history::*; diff --git a/desktop-core/src/runtime_tools/fields.rs b/desktop-core/src/runtime_tools/fields.rs new file mode 100644 index 00000000..e9377ac8 --- /dev/null +++ b/desktop-core/src/runtime_tools/fields.rs @@ -0,0 +1,93 @@ +//! Moved out of the parent module by STRA-338: fn fields, fn optional_text, fn local_refs, fn add_identity. + +#[allow(unused_imports)] +use super::*; + +pub(super) fn fields<'a>( + value: &'a Value, + allowed: &[&str], +) -> Result<&'a serde_json::Map, &'static str> { + let object = value.as_object().ok_or("expected_object")?; + if object.keys().any(|key| !allowed.contains(&key.as_str())) { + return Err("unsupported_field"); + } + Ok(object) +} + +pub(super) fn optional_text(value: &Value, key: &str) -> Result<(), &'static str> { + if value.get(key).is_some_and(|v| !v.is_string()) { + return Err("invalid_text_field"); + } + Ok(()) +} + +pub(super) fn local_refs(value: &Value) -> Result<(), &'static str> { + match value { + Value::Object(object) => { + for (key, child) in object { + if matches!(key.as_str(), "$ref" | "$dynamicRef" | "$recursiveRef") + && child + .as_str() + .is_none_or(|reference| !reference.starts_with('#')) + { + return Err("schema_references_must_be_local"); + } + local_refs(child)?; + } + } + Value::Array(array) => { + for child in array { + local_refs(child)?; + } + } + _ => {} + } + Ok(()) +} + +pub(super) fn add_identity( + tool: &Value, + namespace: Option<&str>, + identities: &mut HashMap, +) -> Result<(), &'static str> { + let custom = match tool["type"].as_str() { + Some("function") => false, + Some("custom") => true, + _ => return Err("unsupported_tool_type"), + }; + fields( + tool, + if custom { + &["type", "name", "description", "format"] + } else { + &["type", "name", "description", "parameters", "strict"] + }, + )?; + optional_text(tool, "description")?; + if tool.get("strict").is_some_and(|v| !v.is_boolean()) { + return Err("invalid_strict"); + } + if let Some(schema) = tool.get("parameters") { + if !schema.is_object() || schema["type"] != "object" { + return Err("parameters_must_be_object_schema"); + } + local_refs(schema)?; + } + let name = tool["name"].as_str().ok_or("tool_name_required")?; + let flat_name = alias(name, namespace)?; + if identities.len() >= TOOL_LIMIT + || identities + .insert( + flat_name, + Identity { + name: name.to_owned(), + namespace: namespace.map(str::to_owned), + custom, + }, + ) + .is_some() + { + return Err("tool_limit_or_duplicate_identity"); + } + Ok(()) +} diff --git a/desktop-core/src/runtime_tools/history.rs b/desktop-core/src/runtime_tools/history.rs new file mode 100644 index 00000000..c5b61751 --- /dev/null +++ b/desktop-core/src/runtime_tools/history.rs @@ -0,0 +1,174 @@ +//! Moved out of the parent module by STRA-338: fn history, fn completed_item. + +#[allow(unused_imports)] +use super::*; + +pub(super) fn history( + input: &Value, + policy: &ToolPolicy, + owned: &mut Vec<(Role, String)>, +) -> Result<(), &'static str> { + if let Some(text) = input.as_str() { + owned.push((Role::User, text.to_owned())); + return Ok(()); + } + let items = input.as_array().ok_or("invalid_input")?; + if items.is_empty() || items.len() > ITEM_LIMIT { + return Err("input_item_limit"); + } + let mut pending: Vec = Vec::new(); + let mut seen = HashSet::new(); + let mut item_ids = HashSet::new(); + for item in items { + if let Some(id) = item.get("id") + && !item_ids.insert(valid_id(id)?.to_owned()) + { + return Err("duplicate_item_id"); + } + let kind = item + .get("type") + .map(|v| v.as_str().ok_or("invalid_item_type")) + .transpose()? + .unwrap_or("message"); + match kind { + "message" => { + fields(item, &["type", "id", "status", "role", "content"])?; + completed_item(item)?; + if !pending.is_empty() { + return Err("unresolved_tool_history"); + } + let role = match item["role"].as_str() { + Some("system") => Role::System, + Some("developer") => Role::Developer, + Some("user") => Role::User, + Some("assistant") => Role::Assistant, + _ => return Err("invalid_role"), + }; + owned.push(( + role, + content(item.get("content").ok_or("content_required")?, false)?, + )); + } + "function_call" | "custom_tool_call" => { + let custom = kind == "custom_tool_call"; + fields( + item, + if custom { + &[ + "type", + "id", + "status", + "call_id", + "name", + "namespace", + "input", + ] + } else { + &[ + "type", + "id", + "status", + "call_id", + "name", + "namespace", + "arguments", + ] + }, + )?; + completed_item(item)?; + if pending.iter().any(|call| call.output.is_some()) { + return Err("call_after_tool_result"); + } + let id = valid_id(&item["call_id"])?; + if !seen.insert(id.to_owned()) { + return Err("duplicate_call_id"); + } + let name = policy.identity(item, custom)?; + let arguments = if custom { + json!({"input":item["input"].as_str().ok_or("custom_input_required")?}) + } else { + serde_json::from_str(item["arguments"].as_str().ok_or("arguments_required")?) + .map_err(|_| "invalid_history_arguments")? + }; + policy.validated_call(&name, &arguments)?; + let mut markup = format!("\n\n"); + for (parameter, value) in arguments.as_object().ok_or("arguments_must_be_object")? { + alias(parameter, None).map_err(|_| "unsafe_parameter_name")?; + markup.push_str(&format!("\n")); + if let Some(text) = value.as_str() { + markup.push_str(text); + } else { + markup.push_str(&value.to_string()); + } + markup.push_str("\n\n"); + } + markup.push_str("\n"); + pending.push(Pending { + id: id.to_owned(), + custom, + markup, + output: None, + }); + } + "function_call_output" | "custom_tool_call_output" => { + fields(item, &["type", "id", "status", "call_id", "output"])?; + completed_item(item)?; + let id = valid_id(&item["call_id"])?; + let call = pending + .iter_mut() + .find(|call| call.id == id) + .ok_or("orphan_tool_result")?; + if call.custom != (kind == "custom_tool_call_output") || call.output.is_some() { + return Err("tool_result_identity_or_duplicate"); + } + call.output = Some(content(item.get("output").ok_or("output_required")?, true)?); + if pending.iter().all(|call| call.output.is_some()) { + let call_text = pending + .iter() + .map(|call| call.markup.as_str()) + .collect::>() + .join("\n"); + let output_text = pending + .iter() + .map(|call| { + format!( + "\n{}\n", + call.output.as_deref().unwrap_or_default() + ) + }) + .collect::>() + .join("\n"); + if let Some((Role::Assistant, text)) = owned.last_mut() { + text.truncate(text.trim_end().len()); + if !text.is_empty() { + text.push_str("\n\n"); + } + text.push_str(&call_text); + } else { + owned.push((Role::Assistant, call_text)); + } + owned.push((Role::User, output_text)); + pending.clear(); + } + } + _ => return Err("unsupported_input_item"), + } + } + if !pending.is_empty() { + return Err("unresolved_tool_history"); + } + Ok(()) +} + +pub(super) fn completed_item(item: &Value) -> Result<(), &'static str> { + if let Some(id) = item.get("id") { + valid_id(id)?; + } + if item + .get("status") + .is_some_and(|status| status != "completed") + { + return Err("incomplete_history_item"); + } + Ok(()) +} diff --git a/desktop-core/src/runtime_tools/impl_toolpolicy.rs b/desktop-core/src/runtime_tools/impl_toolpolicy.rs new file mode 100644 index 00000000..711b8083 --- /dev/null +++ b/desktop-core/src/runtime_tools/impl_toolpolicy.rs @@ -0,0 +1,243 @@ +//! Moved out of the parent module by STRA-338: impl ToolPolicy, fn reserved_markup. + +#[allow(unused_imports)] +use super::*; + +impl ToolPolicy { + pub(super) fn new( + tools: &[Value], + selection: Option<&Value>, + parallel: bool, + ) -> Result { + if tools.len() > TOOL_LIMIT { + return Err("tool_limit"); + } + let mut identities = HashMap::new(); + for tool in tools { + if tool["type"] == "namespace" { + fields(tool, &["type", "name", "description", "tools"])?; + optional_text(tool, "description")?; + let name = tool["name"].as_str().ok_or("namespace_name_required")?; + alias(name, None)?; + let children = tool["tools"].as_array().ok_or("namespace_tools_required")?; + if children.is_empty() || children.len() > TOOL_LIMIT { + return Err("invalid_namespace_tools"); + } + for child in children { + add_identity(child, Some(name), &mut identities)?; + } + } else { + add_identity(tool, None, &mut identities)?; + } + } + let catalog = Catalog::new(tools)?; + let mut schemas = HashMap::new(); + for tool in &catalog.flat { + let schema = tool + .get("parameters") + .cloned() + .unwrap_or_else(|| json!({"type":"object"})); + local_refs(&schema)?; + let validator = jsonschema::options() + .offline() + .build(&schema) + .map_err(|_| "invalid_tool_schema")?; + schemas.insert( + tool["name"] + .as_str() + .ok_or("tool_name_required")? + .to_owned(), + validator, + ); + } + let mut policy = Self { + catalog, + identities, + schemas, + choice: Choice::Auto, + parallel, + }; + policy.choice = match selection { + None => Choice::Auto, + Some(Value::String(choice)) => match choice.as_str() { + "none" => Choice::None, + "auto" => Choice::Auto, + "required" if !policy.identities.is_empty() => Choice::Required, + _ => return Err("invalid_tool_choice"), + }, + Some(choice) if choice["type"] == "allowed_tools" => { + fields(choice, &["type", "mode", "tools"])?; + let required = match choice["mode"].as_str() { + Some("auto") => false, + Some("required") => true, + _ => return Err("invalid_allowed_tools_mode"), + }; + let selectors = choice["tools"].as_array().ok_or("allowed_tools_required")?; + if selectors.is_empty() || selectors.len() > TOOL_LIMIT { + return Err("invalid_allowed_tools"); + } + let mut names = HashSet::new(); + for selector in selectors { + let name = policy.selector(selector)?; + if !names.insert(name) { + return Err("duplicate_allowed_tool"); + } + } + Choice::Allowed { required, names } + } + Some(choice) => Choice::Forced(policy.selector(choice)?), + }; + Ok(policy) + } + + pub(super) fn selector(&self, value: &Value) -> Result { + fields(value, &["type", "name", "namespace"])?; + let custom = match value["type"].as_str() { + Some("function") => false, + Some("custom") => true, + _ => return Err("invalid_tool_selector"), + }; + self.identity(value, custom) + } + + pub(super) fn identity(&self, value: &Value, custom: bool) -> Result { + let name = value["name"].as_str().ok_or("tool_name_required")?; + let namespace = value + .get("namespace") + .map(|v| v.as_str().ok_or("invalid_namespace")) + .transpose()?; + let flat = alias(name, namespace)?; + let identity = self.identities.get(&flat).ok_or("undeclared_tool")?; + if identity.name != name + || identity.namespace.as_deref() != namespace + || identity.custom != custom + { + return Err("tool_identity_mismatch"); + } + Ok(flat) + } + + pub(super) fn validated_call( + &self, + name: &str, + arguments: &Value, + ) -> Result { + if !arguments.is_object() + || !self + .schemas + .get(name) + .ok_or("undeclared_tool")? + .is_valid(arguments) + { + return Err("invalid_tool_arguments"); + } + let mut item = json!({"type":"function_call","name":name,"arguments":arguments.to_string(),"status":"completed"}); + self.catalog + .restore(&mut item) + .map_err(|_| "invalid_custom_input_or_grammar")?; + item.as_object_mut() + .ok_or("invalid_tool_item")? + .remove("status"); + Ok(item) + } + + pub fn parse_output(&self, output: &str) -> Result, &'static str> { + if output.len() > OUTPUT_LIMIT { + return Err("output_limit"); + } + let parsed = runtime_tool_parser::parse_complete(output, &self.catalog.flat) + .map_err(|_| "invalid_tool_output")?; + let mut result = Vec::new(); + let mut calls = 0usize; + for segment in parsed { + match segment { + Segment::Text(text) => { + if reserved_markup(&text) { + return Err("incomplete_or_orphan_tool_markup"); + } + result.push(ValidatedSegment::Text(text)); + } + Segment::Call { name, arguments } => { + calls += 1; + if calls > TOOL_LIMIT || (!self.parallel && calls > 1) { + return Err("tool_call_count"); + } + match &self.choice { + Choice::None => return Err("tool_choice_none"), + Choice::Forced(wanted) if wanted != &name || calls > 1 => { + return Err("forced_tool_mismatch"); + } + Choice::Allowed { names, .. } if !names.contains(&name) => { + return Err("tool_not_allowed"); + } + _ => {} + } + result.push(ValidatedSegment::Call( + self.validated_call(&name, &arguments)?, + )); + } + } + } + if calls == 0 + && matches!( + self.choice, + Choice::Required | Choice::Forced(_) | Choice::Allowed { required: true, .. } + ) + { + return Err("required_tool_missing"); + } + Ok(result) + } + + pub(super) fn choice_instruction(&self) -> Option { + match &self.choice { + Choice::None => None, + Choice::Auto => None, + Choice::Required => { + Some("Call at least one declared tool in this response.".to_owned()) + } + Choice::Forced(name) => Some(format!( + "Call exactly one tool named {name} in this response." + )), + Choice::Allowed { required, names } => { + let mut names = names.iter().map(String::as_str).collect::>(); + names.sort_unstable(); + Some(format!( + "Only these tools may be called: {}. {}", + names.join(", "), + if *required { + "Call at least one." + } else { + "A text response is also allowed." + } + )) + } + } + } +} + +// Whole parsing cannot turn an unfinished or orphan control delimiter into text. +pub(super) fn reserved_markup(text: &str) -> bool { + const TAGS: [&str; 6] = [ + "", + "", + "", + "", + ]; + [ + "')) + || (2..tag.len()).any(|length| text.ends_with(&tag[..length])) + }) +} diff --git a/desktop-core/src/runtime_tools/impl_write_for_count.rs b/desktop-core/src/runtime_tools/impl_write_for_count.rs new file mode 100644 index 00000000..f7fd6ea3 --- /dev/null +++ b/desktop-core/src/runtime_tools/impl_write_for_count.rs @@ -0,0 +1,174 @@ +//! Moved out of the parent module by STRA-338: impl Write_for_Count, fn prepare, fn content, fn valid_id. + +#[allow(unused_imports)] +use super::*; + +impl Write for Count { + fn write(&mut self, bytes: &[u8]) -> io::Result { + self.0 = self + .0 + .checked_add(bytes.len()) + .filter(|size| *size <= REQUEST_LIMIT) + .ok_or_else(|| io::Error::other("request_limit"))?; + Ok(bytes.len()) + } + fn flush(&mut self) -> io::Result<()> { + Ok(()) + } +} + +pub fn prepare(request: &Value) -> Result { + serde_json::to_writer(Count(0), request).map_err(|_| "request_limit")?; + let object = fields( + request, + &[ + "model", + "input", + "instructions", + "stream", + "max_output_tokens", + "temperature", + "top_p", + "top_k", + "min_p", + "repetition_penalty", + "frequency_penalty", + "presence_penalty", + "penalty_last_n", + "seed", + "store", + "tools", + "tool_choice", + "parallel_tool_calls", + "text", + ], + )?; + if request["model"].as_str().is_none_or(str::is_empty) { + return Err("model_required"); + } + if object.get("stream").is_some_and(|v| !v.is_boolean()) { + return Err("invalid_stream"); + } + if object + .get("store") + .is_some_and(|v| v != &Value::Bool(false)) + { + return Err("unsupported_sampling_or_store"); + } + let sampling = crate::runtime_sampling::from_json(object)?; + if object + .get("text") + .is_some_and(|v| v != &json!({"format":{"type":"text"}})) + { + return Err("unsupported_text_format"); + } + let cap = object + .get("max_output_tokens") + .map(|v| v.as_u64().ok_or("invalid_output_limit")) + .transpose()? + .unwrap_or(256); + if !(1..=4096).contains(&cap) { + return Err("invalid_output_limit"); + } + let tools = object + .get("tools") + .map(|v| v.as_array().ok_or("invalid_tools")) + .transpose()? + .map(Vec::as_slice) + .unwrap_or(&[]); + let parallel = object + .get("parallel_tool_calls") + .map(|v| v.as_bool().ok_or("invalid_parallel_tool_calls")) + .transpose()? + .unwrap_or(true); + let policy = ToolPolicy::new(tools, object.get("tool_choice"), parallel)?; + let mut owned = Vec::new(); + if let Some(instructions) = object.get("instructions") { + owned.push(( + Role::System, + instructions + .as_str() + .ok_or("invalid_instructions")? + .to_owned(), + )); + } + if let Some(instruction) = policy.choice_instruction() { + owned.push((Role::System, instruction)); + } + if !parallel && !tools.is_empty() { + owned.push(( + Role::System, + "Call at most one tool in this response.".to_owned(), + )); + } + history( + object.get("input").ok_or("input_required")?, + &policy, + &mut owned, + )?; + let messages = owned + .iter() + .map(|(role, content)| Message { + role: *role, + content, + reasoning: None, + parts: None, + }) + .collect::>(); + let flat = if matches!(policy.choice, Choice::None) { + &[][..] + } else { + &policy.catalog.flat[..] + }; + let prompt = crate::runtime_prompt::render_with_tools(&messages, Effort::None, flat) + .map_err(|_| "prompt template rendering failed")?; + if prompt.len() > REQUEST_LIMIT { + return Err("prompt_limit"); + } + Ok(ToolPlan { + prompt, + max_output_tokens: cap as u32, + policy, + sampling, + }) +} + +pub(super) fn content(value: &Value, output: bool) -> Result { + if let Some(text) = value.as_str() { + return Ok(text.to_owned()); + } + let parts = value.as_array().ok_or("invalid_content")?; + if parts.len() > ITEM_LIMIT { + return Err("content_limit"); + } + let mut text = String::new(); + for (index, part) in parts.iter().enumerate() { + fields(part, &["type", "text", "annotations", "logprobs"])?; + for key in ["annotations", "logprobs"] { + if part.get(key).is_some_and(|metadata| { + part["type"] != "output_text" + || metadata.as_array().is_none_or(|items| !items.is_empty()) + }) { + return Err("unsupported_output_metadata"); + } + } + if !matches!(part["type"].as_str(), Some("input_text" | "output_text")) + || (output && part["type"] != "input_text") + { + return Err("unsupported_content"); + } + if output && index > 0 { + text.push('\n'); + } + text.push_str(part["text"].as_str().ok_or("invalid_text")?); + } + Ok(text) +} + +pub(super) fn valid_id(value: &Value) -> Result<&str, &'static str> { + let id = value.as_str().ok_or("call_id_required")?; + if id.is_empty() || id.len() > 256 || !id.bytes().all(|b| b.is_ascii_graphic()) { + return Err("invalid_call_id"); + } + Ok(id) +} diff --git a/scripts/dev/rustsplit/__init__.py b/scripts/dev/rustsplit/__init__.py new file mode 100644 index 00000000..715ffdf3 --- /dev/null +++ b/scripts/dev/rustsplit/__init__.py @@ -0,0 +1 @@ +"""Mechanical splitting of oversized Rust module files (STRA-338). Entry point: scripts/dev/split_module.py.""" diff --git a/scripts/dev/rustsplit/items.py b/scripts/dev/rustsplit/items.py new file mode 100644 index 00000000..27c1e644 --- /dev/null +++ b/scripts/dev/rustsplit/items.py @@ -0,0 +1,149 @@ +"""Top-level items of a Rust file: where each starts and ends, what it is, and what must change when it moves.""" +from dataclasses import dataclass + +from .lexer import tokenize + +OPEN, CLOSE = "{([", "})]" +BRACE_ITEMS = {"fn", "impl", "trait", "mod", "struct", "enum", "union", "macro_rules", "extern"} +SEMI_ITEMS = {"use", "const", "static", "type", "crate"} + + +@dataclass +class Item: + start: int # first character carried by the item: the comments and blanks before it + head: int # first character of the item proper (after attributes and doc comments) + end: int # one past the last character + kind: str # fn impl or other + name: str + attrs: str # text of the outer attributes + inherent: bool = False + + +def significant(tokens): + return [t for t in tokens if t.kind not in ("ws", "comment")] + + +def _skip_bracket(sig, k): + """Index after the balanced `[ ... ]` group whose `[` is at sig[k].""" + depth = 0 + while k < len(sig): + depth += (sig[k].text == "[") - (sig[k].text == "]") + k += 1 + if depth == 0: + break + return k + + +def _skip_attrs(sig, k): + """Index of the first token after the outer attributes starting at k.""" + while k + 1 < len(sig) and sig[k].text == "#" and sig[k + 1].text == "[": + k = _skip_bracket(sig, k + 1) + return k + + +def _skip_visibility(sig, k): + if sig[k].text != "pub": + return k + k += 1 + if sig[k].text == "(": + while sig[k].text != ")": + k += 1 + k += 1 + return k + + +def _keyword(sig, k): + """The keyword naming the item whose first token (after attributes and visibility) is sig[k], and its index.""" + while sig[k].text in ("unsafe", "async", "default", "const", "extern"): + word, nxt = sig[k].text, sig[k + 1] + if word == "const" and nxt.text not in ("fn", "unsafe", "async", "extern"): + break + if word == "extern": + skip = 2 if nxt.kind == "string" else 1 + if sig[k + skip].text not in ("fn", "unsafe"): + break + k += skip + continue + k += 1 + return sig[k].text, k + + +def _ends_with_brace(sig, k, bang_brace): + """Index of the last token when the `}` at sig[k] closes a braced item (a macro call may be followed by `;`).""" + return k + 1 if bang_brace and k + 1 < len(sig) and sig[k + 1].text == ";" else k + + +def _item_end(sig, k, keyword): + """Index in `sig` of the last token of the item whose keyword is at sig[k].""" + depth, semi_only = 0, keyword in SEMI_ITEMS + bang_brace = keyword not in BRACE_ITEMS | SEMI_ITEMS and sig[k + 1].text == "!" + while k < len(sig): + text = sig[k].text + depth += (text in OPEN) - (text in CLOSE) + if depth == 0 and (text == ";" or text == "}" and not semi_only): + return k if text == ";" else _ends_with_brace(sig, k, bang_brace) + k += 1 + return len(sig) - 1 + + +def _impl_name(sig, k): + """`Foo` for `impl Foo`, `Trait_for_Foo` for `impl Trait for Foo`; at most three identifiers.""" + j, depth, words = k + 1, 0, [] + while j < len(sig) and sig[j].text not in ("{", "where"): + depth += (sig[j].text == "<") - (sig[j].text == ">") + if depth == 0 and sig[j].kind == "ident" and sig[j].text != "for": + words.append(sig[j].text) + elif depth == 0 and sig[j].text == "for": + words.append("for") + j += 1 + return "_".join(words[:3]) or "impl" + + +def _name_of(sig, k, keyword): + if keyword == "impl": + return _impl_name(sig, k) + return sig[k + 1].text if k + 1 < len(sig) and sig[k + 1].kind == "ident" else keyword + + +def _is_inherent(sig, k, end): + """An `impl` is inherent when no `for` appears before its opening brace.""" + for j in range(k, end): + if sig[j].text == "{": + return True + if sig[j].text == "for": + return False + return True + + +def preamble_end(text, tokens): + """End of the file header: `//!` docs, `#![...]` inner attributes and the blanks between them.""" + sig = significant(tokens) + end, k = 0, 0 + for t in tokens: + if t.kind == "comment" and t.text.startswith(("//!", "/*!")) or t.kind == "ws": + end = t.end + elif t.kind != "comment" or t.text.startswith("//"): + break + while k + 2 < len(sig) and sig[k].text == "#" and sig[k + 1].text == "!": + k = _skip_bracket(sig, k + 2) + end = max(end, sig[k - 1].end) + return end, k + + +def parse_items(text): + """Top-level items of `text` in order; the text between items is carried by the item that follows it.""" + tokens = tokenize(text) + sig = significant(tokens) + previous_end, k = preamble_end(text, tokens) + items = [] + while k < len(sig): + attrs_end = _skip_attrs(sig, k) + if attrs_end >= len(sig): + break + keyword, at = _keyword(sig, _skip_visibility(sig, attrs_end)) + last = _item_end(sig, at, keyword) + kind = keyword if keyword in ("fn", "impl") else "other" + items.append(Item(previous_end, sig[attrs_end].start, sig[last].end, kind, _name_of(sig, at, keyword), + text[sig[k].start:sig[attrs_end].start], kind == "impl" and _is_inherent(sig, at, last))) + previous_end, k = sig[last].end, last + 1 + return items diff --git a/scripts/dev/rustsplit/lexer.py b/scripts/dev/rustsplit/lexer.py new file mode 100644 index 00000000..87316cec --- /dev/null +++ b/scripts/dev/rustsplit/lexer.py @@ -0,0 +1,120 @@ +"""A small Rust lexer: enough to find item boundaries and `super::` paths without a parser (STRA-338).""" +from dataclasses import dataclass + +IDENT_START = set("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_") +IDENT_PART = IDENT_START | set("0123456789") + + +@dataclass +class Token: + kind: str # ws comment string char lifetime ident number punct + start: int + end: int + text: str + + +def _skip_line_comment(text, i): + end = text.find("\n", i) + return len(text) if end < 0 else end + + +def _skip_block_comment(text, i): + depth, n = 0, len(text) + while i < n: + if text.startswith("/*", i): + depth, i = depth + 1, i + 2 + elif text.startswith("*/", i): + depth, i = depth - 1, i + 2 + if depth == 0: + return i + else: + i += 1 + return n + + +def _skip_quoted(text, i, quote): + """End index after the closing quote of a string or char literal that opens at `i`.""" + i += 1 + while i < len(text) and text[i] != quote: + i += 2 if text[i] == "\\" else 1 + return i + 1 + + +def _raw_string_end(text, i): + """End of a raw string `r"..."` / `r#"..."#` whose `r` is at `i` (after a `b` prefix too); None if it is not one.""" + j = i + 1 + while j < len(text) and text[j] == "#": + j += 1 + if j >= len(text) or text[j] != '"': + return None + closing = '"' + "#" * (j - i - 1) + end = text.find(closing, j + 1) + return len(text) if end < 0 else end + len(closing) + + +def _char_or_lifetime_end(text, i): + """(kind, end) of what starts with a `'`.""" + if text[i + 1:i + 2] == "\\" or text[i + 2:i + 3] == "'": + return "char", _skip_quoted(text, i, "'") + j = i + 1 + while j < len(text) and text[j] in IDENT_PART: + j += 1 + return "lifetime", j + + +def _ident_end(text, i): + j = i + while j < len(text) and text[j] in IDENT_PART: + j += 1 + return j + + +def _literal_prefix(text, i): + """(kind, end) for r"", b"", br"", b'' starting at i, or None.""" + for prefix in ("br", "r", "b"): + if text.startswith(prefix, i) and prefix[-1] == "r": + end = _raw_string_end(text, i + len(prefix) - 1) + if end is not None: + return "string", end + if prefix == "b" and text.startswith('b"', i): + return "string", _skip_quoted(text, i + 1, '"') + if prefix == "b" and text.startswith("b'", i): + return "char", _skip_quoted(text, i + 1, "'") + return None + + +def _simple_token(text, i): + """(kind, end) for whitespace, comments and quoted literals, or None.""" + c = text[i] + if c.isspace(): + j = i + while j < len(text) and text[j].isspace(): + j += 1 + return "ws", j + if text.startswith("//", i): + return "comment", _skip_line_comment(text, i) + if text.startswith("/*", i): + return "comment", _skip_block_comment(text, i) + return ("string", _skip_quoted(text, i, '"')) if c == '"' else None + + +def _next_token(text, i): + simple = _simple_token(text, i) + if simple: + return simple + c = text[i] + if c == "'": + return _char_or_lifetime_end(text, i) + if c in IDENT_START: + return _literal_prefix(text, i) or ("ident", _ident_end(text, i)) + return ("number", _ident_end(text, i)) if c.isdigit() else ("punct", i + 1) + + +def tokenize(text): + """All tokens of a Rust source text; they tile the text exactly.""" + tokens, i = [], 0 + while i < len(text): + kind, end = _next_token(text, i) + tokens.append(Token(kind, i, end, text[i:end])) + i = end + return tokens diff --git a/scripts/dev/rustsplit/retarget.py b/scripts/dev/rustsplit/retarget.py new file mode 100644 index 00000000..01725a18 --- /dev/null +++ b/scripts/dev/rustsplit/retarget.py @@ -0,0 +1,83 @@ +"""Edits a function or impl chunk needs when it moves one module down: visibility and `super::` / `self::` paths.""" +import re + +from .items import CLOSE, OPEN, _keyword, _skip_attrs, _skip_visibility, significant +from .lexer import tokenize + +VIS = "pub(super) " +INCLUDE = re.compile(r'(include_(?:str|bytes)!\(\s*")(?=[^/])') + + +def _is_double_colon(sig, k): + return k >= 1 and sig[k].text == ":" and sig[k - 1].text == ":" + + +def _restricted_visibility_edits(sig): + """`pub(super)` and `pub(self)` name a scope relative to the module; one level down they need `pub(in ...)`.""" + edits = [] + for k, tok in enumerate(sig[:-3]): + if tok.text == "pub" and sig[k + 1].text == "(" and sig[k + 3].text == ")": + inner = sig[k + 2] + replacement = {"super": "in super::super", "self": "in super"}.get(inner.text) + if replacement: + edits.append((inner.start, len(inner.text), replacement)) + return edits + + +def _path_edits(sig): + """(position, length, replacement) for every path that starts with `super` or `self` (not after `::`).""" + edits = [] + for k, tok in enumerate(sig[:-2]): + follows_path = k >= 2 and _is_double_colon(sig, k - 1) + if tok.kind != "ident" or follows_path or not _is_double_colon(sig, k + 2): + continue + if tok.text == "super": + edits.append((tok.start, 5, "super::super")) + elif tok.text == "self": + edits.append((tok.start, 4, "super")) + return edits + + +def _assoc_item_starts(sig): + """Indexes in `sig` where an associated item of an impl body (brace depth 1) begins.""" + starts, depth = [], 0 + for k, tok in enumerate(sig): + depth += (tok.text in OPEN) - (tok.text in CLOSE) + if k > 0 and sig[k - 1].text in ("{", "}", ";") and depth == 1 and tok.text != "}": + starts.append(k) + return starts + + +def _assoc_visibility_edits(sig): + """`pub(super)` before every private fn or const of an inherent impl body.""" + edits = [] + for k in _assoc_item_starts(sig): + first = _skip_attrs(sig, k) + if first < len(sig) and sig[first].text != "pub" and _keyword(sig, first)[0] in ("fn", "const"): + edits.append((sig[first].start, 0, VIS)) + return edits + + +def _fn_visibility_edits(sig): + """`pub(super)` for a free fn that has no visibility.""" + first = _skip_attrs(sig, 0) + if sig[first].text == "pub" or _keyword(sig, first)[0] != "fn": + return [] + return [(sig[first].start, 0, VIS)] + + +def apply_edits(text, edits): + for pos, length, replacement in sorted(edits, reverse=True): + text = text[:pos] + replacement + text[pos + length:] + return text + + +def retarget(chunk, kind, inherent): + """The chunk (one fn or impl, from its leading comments on) as it must read inside a child module.""" + sig = significant(tokenize(chunk)) + edits = _path_edits(sig) + _restricted_visibility_edits(sig) + if kind == "fn": + edits += _fn_visibility_edits(sig) + elif inherent: + edits += _assoc_visibility_edits(sig) + return INCLUDE.sub(lambda m: m.group(1) + "../", apply_edits(chunk, edits)) diff --git a/scripts/dev/rustsplit/split.py b/scripts/dev/rustsplit/split.py new file mode 100644 index 00000000..c37c76fc --- /dev/null +++ b/scripts/dev/rustsplit/split.py @@ -0,0 +1,82 @@ +"""Plan a split of one oversized Rust module file into child modules that hold its fns and impl blocks (STRA-338).""" +import re +from dataclasses import dataclass, field + +from .items import parse_items +from .retarget import retarget + +MAX_NAME = 48 +NOT_MOVED = re.compile(r"#\[\s*(test|bench|cfg\s*\(\s*test\s*\)|ignore)\b|#\[\s*macro_export") + + +@dataclass +class Group: + name: str + chunks: list = field(default_factory=list) + lines: int = 0 + members: list = field(default_factory=list) + + +def slug(item): + base = re.sub(r"[^a-z0-9]+", "_", item.name.lower()).strip("_") or "items" + return (("impl_" if item.kind == "impl" else "") + base)[:MAX_NAME] + + +def movable(item): + return item.kind in ("fn", "impl") and item.name != "main" and not NOT_MOVED.search(item.attrs) + + +def unique(name, used): + candidate, n = name, 2 + while candidate in used: + candidate, n = f"{name}_{n}", n + 1 + used.add(candidate) + return candidate + + +def group_items(text, items, target, reserved): + """Pack the movable items, in file order, into groups of about `target` lines.""" + groups, used = [], set(reserved) + for item in items: + if not movable(item): + continue + chunk = retarget(text[item.start:item.end], item.kind, item.inherent) + lines = chunk.count("\n") + 1 + if not groups or groups[-1].lines + lines > target: + groups.append(Group(unique(slug(item), used))) + groups[-1].chunks.append(chunk) + groups[-1].members.append(f"{item.kind} {item.name}") + groups[-1].lines += lines + return groups + + +def remove_ranges(text, ranges): + for start, end in sorted(ranges, reverse=True): + text = text[:start] + text[end:] + return re.sub(r"\n{3,}", "\n\n", text) + + +def child_text(group): + members = ", ".join(group.members[:6]) + (" ..." if len(group.members) > 6 else "") + header = f"//! Moved out of the parent module by STRA-338: {members}.\n\n#[allow(unused_imports)]\nuse super::*;\n" + body = "".join(chunk if chunk.startswith("\n") else "\n" + chunk for chunk in group.chunks) + return header + body.rstrip("\n") + "\n" + + +def declarations(groups, explicit_dir): + rows = [] + for group in groups: + attr = f'#[path = "{explicit_dir}/{group.name}.rs"]\n' if explicit_dir else "" + rows.append(f"{attr}mod {group.name};\n#[allow(unused_imports)]\npub use {group.name}::*;") + return "\n".join(rows) + + +def plan_split(text, target, explicit_dir=None, reserved=()): + """(new parent text, {child name: child text}), or None when nothing would move.""" + items = parse_items(text) + groups = group_items(text, items, target, reserved) + if not groups: + return None + moved = [(i.start, i.end) for i in items if movable(i)] + parent = remove_ranges(text, moved).rstrip("\n") + "\n\n" + declarations(groups, explicit_dir) + "\n" + return parent, {g.name: child_text(g) for g in groups} diff --git a/scripts/dev/rustsplit_test.py b/scripts/dev/rustsplit_test.py new file mode 100644 index 00000000..4bea9085 --- /dev/null +++ b/scripts/dev/rustsplit_test.py @@ -0,0 +1,138 @@ +#!/usr/bin/env python3 +"""Proofs for the Rust module splitter on synthetic sources: lexing, item boundaries, visibility and path edits.""" +import pathlib +import re +import sys +import unittest + +sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent)) + +from rustsplit.items import parse_items # noqa: E402 +from rustsplit.lexer import tokenize # noqa: E402 +from rustsplit.retarget import retarget # noqa: E402 +from rustsplit.split import plan_split # noqa: E402 + +SOURCE = '''//! Module doc. +#![allow(dead_code)] + +use std::fmt; + +const LIMIT: usize = 4; // a semicolon item + +/// A type. +pub struct Thing { + value: u32, +} + +impl Thing { + fn private(&self) -> u32 { + let s = "}{;"; + self.value + s.len() as u32 + super::outer() + } + + pub fn open(&self) -> u32 { + self.private() + } +} + +impl fmt::Display for Thing { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + write!(f, "{}", self.value) + } +} + +fn helper() -> char { + 'x' +} + +pub(crate) fn shared<'a>(s: &'a str) -> &'a str { + s +} + +#[cfg(test)] +mod tests; +''' + + +class Lexing(unittest.TestCase): + def test_tokens_tile_the_text(self): + text = "fn a<'a>() -> &'a str { r#\"}\"# } // end\n/* /* nested */ */ 'c' b\"x\" 1.5" + self.assertEqual("".join(t.text for t in tokenize(text)), text) + + def test_braces_in_strings_and_chars_are_not_structure(self): + kinds = [t.kind for t in tokenize("let c = '}'; let s = \"{\";") if t.text in ("'}'", '"{"')] + self.assertEqual(kinds, ["char", "string"]) + + +class Items(unittest.TestCase): + def test_item_kinds_and_names(self): + found = [(i.kind, i.name) for i in parse_items(SOURCE)] + self.assertEqual(found, [("other", "std"), ("other", "LIMIT"), ("other", "Thing"), ("impl", "Thing"), + ("impl", "fmt_Display_for"), ("fn", "helper"), ("fn", "shared"), ("other", "tests")]) + + def test_inherent_impl_is_detected(self): + self.assertEqual([i.inherent for i in parse_items(SOURCE) if i.kind == "impl"], [True, False]) + + def test_module_doc_and_inner_attribute_are_not_part_of_an_item(self): + first = parse_items(SOURCE)[0] + self.assertTrue(SOURCE[:first.start].startswith("//! Module doc.")) + self.assertIn("#![allow(dead_code)]", SOURCE[:first.start]) + + +class Retargeting(unittest.TestCase): + def test_free_fn_gets_visibility_and_paths_shift(self): + out = retarget("fn f() { super::g(); self::h(); }", "fn", False) + self.assertEqual(out, "pub(super) fn f() { super::super::g(); super::h(); }") + + def test_restricted_visibility_keeps_its_scope_one_level_down(self): + self.assertEqual(retarget("pub(super) fn f() {}", "fn", False), "pub(in super::super) fn f() {}") + self.assertEqual(retarget("pub(self) fn f() {}", "fn", False), "pub(in super) fn f() {}") + self.assertEqual(retarget("pub(in super::a) fn f() {}", "fn", False), "pub(in super::super::a) fn f() {}") + + def test_relative_include_paths_go_one_level_up(self): + out = retarget('fn f() { include_str!("a/b.txt") }', "fn", False) + self.assertIn('"../a/b.txt"', out) + + def test_existing_visibility_is_kept(self): + self.assertEqual(retarget("pub(crate) fn f() {}", "fn", False), "pub(crate) fn f() {}") + + def test_inherent_impl_fns_become_visible_to_siblings(self): + source = "impl A {\n fn a(&self) {}\n pub fn b(&self) {}\n const C: u8 = 1;\n}" + expected = source.replace(" fn a", " pub(super) fn a").replace(" const C", " pub(super) const C") + self.assertEqual(retarget(source, "impl", True), expected) + + def test_trait_impl_is_untouched(self): + text = "impl T for A {\n fn a(&self) {}\n}" + self.assertEqual(retarget(text, "impl", False), text) + + def test_a_continued_path_is_not_shifted_twice(self): + self.assertEqual(retarget("fn f() { super::super::g(); }", "fn", False), + "pub(super) fn f() { super::super::super::g(); }") + + +class Planning(unittest.TestCase): + def test_fns_and_impls_move_and_the_rest_stays(self): + parent, children = plan_split(SOURCE, 8) + self.assertIn("pub struct Thing", parent) + self.assertIn("const LIMIT", parent) + self.assertNotIn("fn helper", parent) + self.assertEqual(sum(len(re.findall(r"fn \w+[(<]", text)) for text in children.values()), 5) + self.assertTrue(all("use super::*;" in text for text in children.values())) + for name in children: + self.assertIn(f"mod {name};\n#[allow(unused_imports)]\npub use {name}::*;", parent) + + def test_nothing_to_move_gives_none(self): + self.assertIsNone(plan_split("use a::b;\nconst X: u8 = 1;\n", 100)) + + def test_test_functions_stay(self): + parent, children = plan_split("#[test]\nfn t() {}\nfn a() {}\n", 100) + self.assertIn("fn t()", parent) + self.assertNotIn("fn t()", "".join(children.values())) + + def test_explicit_paths_are_written_for_path_loaded_files(self): + parent, _ = plan_split("fn a() {}\n", 100, explicit_dir="foo") + self.assertIn('#[path = "foo/a.rs"]', parent) + + +if __name__ == "__main__": + unittest.main() diff --git a/scripts/dev/split_module.py b/scripts/dev/split_module.py new file mode 100644 index 00000000..5d2fdba5 --- /dev/null +++ b/scripts/dev/split_module.py @@ -0,0 +1,84 @@ +#!/usr/bin/env python3 +"""Split an oversized Rust module file into child modules (STRA-338): its fns and impl blocks move, the rest stays. + +`foo.rs` keeps its `use` lines, types, constants, macros and nested modules; every top-level `fn` and `impl` block +moves into `foo/.rs` groups of about --target lines, each starting with `use super::*;`. The parent ends with +`mod ;` and `pub use ::*;` for every group, so all paths stay as they were. Moved free fns and the fns and +consts of inherent impls get `pub(super)` when they had no visibility, `super::` paths are shifted one level, and +`#[test]` items stay where they are. Crate roots (lib.rs, main.rs, bin/*) are skipped. A file that is itself loaded +through `#[path]` gets explicit child paths. The compiler and the tests judge the result; hot-path crates also need +the GPU identity and A/B gates. + +Usage: scripts/dev/split_module.py [--dry-run] [--target 250] FILE.rs... +""" +import argparse +import pathlib +import re +import sys + +sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent)) + +from rustsplit.split import plan_split # noqa: E402 + + +def read(path): + with open(path, encoding="utf-8", newline="") as handle: + return handle.read().replace("\r\n", "\n") + + +def write(path, text): + with open(path, "w", encoding="utf-8", newline="\n") as handle: + handle.write(text) + + +def is_root(path): + return path.name in ("lib.rs", "main.rs") or "bin" in path.parts or "examples" in path.parts + + +def child_dir(path): + return path.parent if path.name == "mod.rs" else path.with_suffix("") + + +def path_targets(): + """File names that some source file of the workspace loads through `#[path = "...name.rs"]` (scanned once).""" + root = pathlib.Path(__file__).resolve().parents[2] + found = set() + for top in ("crates", "control-plane", "desktop-core"): + for source in (root / top).rglob("*.rs"): + if "target" not in source.parts: + found.update(re.findall(r'#\[path\s*=\s*"[^"]*?([\w.\-]+\.rs)"', read(source))) + return found + + +def process(path, target, dry_run, loaded): + if is_root(path): + return "skipped", "crate root, bin or example" + directory = child_dir(path) + explicit = directory.name if path.name in loaded else None + reserved = {p.stem for p in directory.glob("*.rs")} if directory.is_dir() else set() + result = plan_split(read(path), target, explicit, reserved | {"tests"}) + if result is None: + return "skipped", "no fn or impl to move" + if not dry_run: + directory.mkdir(parents=True, exist_ok=True) + write(path, result[0]) + for name, text in result[1].items(): + write(directory / f"{name}.rs", text) + return "split", f"{len(result[1])} children, parent {result[0].count(chr(10))} lines" + + +def main(argv): + parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) + parser.add_argument("--dry-run", action="store_true") + parser.add_argument("--target", type=int, default=250) + parser.add_argument("files", nargs="+") + args = parser.parse_args(argv) + loaded = path_targets() + for name in args.files: + verdict, detail = process(pathlib.Path(name), args.target, args.dry_run, loaded) + print(f"{verdict} {name} {detail}") + return 0 + + +if __name__ == "__main__": + sys.exit(main(sys.argv[1:]))