From 995d4a769c104bbc09ad3428abc7f4e4ef14c532 Mon Sep 17 00:00:00 2001 From: Pavlo Ratushnyi Date: Fri, 2 Oct 2026 17:41:16 +0200 Subject: [PATCH] build: add Responses contract replay and pin Rust 1.99 --- AGENTS.md | 2 +- README.md | 6 +- benchmarks/README.md | 4 +- .../fixtures/responses/structured-tool.json | 30 + control-plane/Cargo.lock | 593 ++++++++++++++++- control-plane/Cargo.toml | 3 +- control-plane/README.md | 13 +- control-plane/src/app.rs | 80 +++ control-plane/src/bin/replay-responses.rs | 64 ++ control-plane/src/lib.rs | 5 + control-plane/src/main.rs | 79 +-- control-plane/src/responses.rs | 596 ++++++++++++++++++ control-plane/src/wire.rs | 225 +++++++ docs/api-contract.md | 11 + docs/build-validation.md | 7 + rust-toolchain.toml | 4 + scripts/check-local.sh | 3 + 17 files changed, 1641 insertions(+), 84 deletions(-) create mode 100644 benchmarks/fixtures/responses/structured-tool.json create mode 100644 control-plane/src/app.rs create mode 100644 control-plane/src/bin/replay-responses.rs create mode 100644 control-plane/src/lib.rs create mode 100644 control-plane/src/responses.rs create mode 100644 control-plane/src/wire.rs create mode 100644 docs/api-contract.md create mode 100644 rust-toolchain.toml diff --git a/AGENTS.md b/AGENTS.md index bbb01807..3bac86e4 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -20,4 +20,4 @@ Read `PROJECT_CHARTER.md` before changing architecture, performance policy, or s ## Repository state -The Strata source is present under `engine/strata/` at the commit recorded in `docs/upstream.md`. The Rust control plane currently exposes only health, readiness, and status, and can supervise one configured worker; inference APIs, project benchmark results, and deployment assets are not yet present. Read `engine/strata/AGENTS.md` before modifying imported engine code. +The Strata source is present under `engine/strata/` at the commit recorded in `docs/upstream.md`. The Rust control plane exposes health, readiness, status, and a `/v1/responses` validation stub, and can supervise one configured worker. A synthetic offline Responses replay exists, but live inference, project benchmark results, and deployment assets are not yet present. Read `engine/strata/AGENTS.md` before modifying imported engine code. diff --git a/README.md b/README.md index 0c1defe5..79a6663b 100644 --- a/README.md +++ b/README.md @@ -4,7 +4,7 @@ Strata Next is a planned C++20/CUDA inference engine fork with a Rust control pl ## Current state -The Strata source is imported at a pinned upstream commit under `engine/strata/`. A CPU-only source build and unit tests are available through `scripts/build-cpu.sh`. A minimal Rust control plane serves health, readiness, and status and can supervise one engine worker; it does not yet handle inference requests. The project benchmark harness, deployment image, and verified GPU performance baseline have **not** been implemented yet. Figures in the charter are preliminary reference points, not results from this repository. +The Strata source is imported at a pinned upstream commit under `engine/strata/`. A CPU-only source build and unit tests are available through `scripts/build-cpu.sh`. The Rust control plane serves health, readiness, and status and supervises one engine worker. A `/v1/responses` route validates a limited request shape and reports when inference is unavailable; the engine inference adapter is still pending. A synthetic Responses JSON/SSE replay fixture checks output assembly, tool arguments, and terminal events without a model. The performance benchmark harness, deployment image, and verified GPU baseline have **not** been implemented yet. Figures in the charter are preliminary reference points, not results from this repository. ## Layout @@ -20,10 +20,12 @@ Models, captures, logs, build products, and benchmark artifacts belong outside t 1. Build and validate the CUDA engine on the RTX 5090 Linux node. 2. Capture the 1×256K baseline with the fields in `docs/performance-ledger.md`. -3. Assemble a sanitized Codex request/response replay corpus for protocol work. +3. Assemble a sanitized Codex request/response replay corpus for protocol work. The current fixture is synthetic, not a captured Codex session. For the source-only build on a machine with CMake 3.24+ and a C++20 compiler, run `scripts/build-cpu.sh`. It builds the non-GPU engine utilities and runs the available CPU tests. This does not verify inference or measure performance. Run `scripts/check-local.sh` to check the Rust control plane and CPU engine build together. The first CPU configure downloads the ggml source at the commit pinned by Strata's CMake file. +The Rust control plane uses the repository-pinned Rust 1.99.0 toolchain. + Do not claim M0 complete until these items are verified. diff --git a/benchmarks/README.md b/benchmarks/README.md index 3d7c3005..40c0f6de 100644 --- a/benchmarks/README.md +++ b/benchmarks/README.md @@ -1,3 +1,5 @@ # Benchmarks -Reserved for the reproducible performance and quality harness. Store benchmark definitions and sanitized fixtures in Git; place generated reports and sensitive captures outside the source tree or under ignored local paths. No baseline has been measured yet. +The `fixtures/responses/` directory currently holds a synthetic protocol replay example. It is not a real Codex capture or a performance measurement. Run it through the Rust `replay-responses` binary described in [control-plane/README.md](../control-plane/README.md). + +Store future benchmark definitions and sanitized fixtures in Git; place generated reports and sensitive captures outside the source tree or under ignored local paths. No baseline has been measured yet. diff --git a/benchmarks/fixtures/responses/structured-tool.json b/benchmarks/fixtures/responses/structured-tool.json new file mode 100644 index 00000000..9b5160fa --- /dev/null +++ b/benchmarks/fixtures/responses/structured-tool.json @@ -0,0 +1,30 @@ +{ + "request": { + "model": "strata-local", + "input": "Return a small result and call the example tool.", + "stream": true, + "store": false, + "text": { + "format": { + "type": "json_schema", + "name": "result", + "strict": true, + "schema": { + "type": "object", + "properties": {"ok": {"type": "boolean"}}, + "required": ["ok"], + "additionalProperties": false + } + } + }, + "tools": [{"type": "function", "name": "example_tool", "parameters": {"type": "object"}}] + }, + "items": [ + {"type": "text", "deltas": ["{\"ok\":", "true}"]}, + {"type": "function_call", "name": "example_tool", "call_id": "call_example", "argument_deltas": ["{\"value\":", "1}"]} + ], + "usage": {"input_tokens": 14, "output_tokens": 9, "reasoning_tokens": 0, "cached_tokens": 0}, + "id": "resp_fixture_001", + "created_at": 1, + "completed_at": 2 +} diff --git a/control-plane/Cargo.lock b/control-plane/Cargo.lock index dcfade7c..6e78b144 100644 --- a/control-plane/Cargo.lock +++ b/control-plane/Cargo.lock @@ -2,12 +2,47 @@ # It is not intended for manual editing. version = 4 +[[package]] +name = "ahash" +version = "0.8.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5a15f179cd60c4584b8a8c596927aadc462e27f2ca70c04e0071964a73ba7a75" +dependencies = [ + "cfg-if", + "getrandom", + "once_cell", + "serde", + "version_check", + "zerocopy", +] + +[[package]] +name = "aho-corasick" +version = "1.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c982642fa9e8606056828ee9a8505737230110bb1099153c79efe865c59d12ba" +dependencies = [ + "memchr", +] + +[[package]] +name = "allocator-api2" +version = "0.2.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "683d7910e743518b0e34f1186f92494becacb047c7b6bf616c96772180fef923" + [[package]] name = "atomic-waker" version = "1.1.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1505bd5d3d116872e7271a6d4e16d81d0c8570876c8de68093a09ac269d8aac0" +[[package]] +name = "autocfg" +version = "1.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53" + [[package]] name = "axum" version = "0.8.9" @@ -60,12 +95,78 @@ dependencies = [ "tracing", ] +[[package]] +name = "bit-set" +version = "0.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "08807e080ed7f9d5433fa9b275196cfc35414f66a0c79d864dc51a0d825231a3" +dependencies = [ + "bit-vec", +] + +[[package]] +name = "bit-vec" +version = "0.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5e764a1d40d510daf35e07be9eb06e75770908c27d411ee6c92109c9840eaaf7" + +[[package]] +name = "bitflags" +version = "2.13.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06" + +[[package]] +name = "borrow-or-share" +version = "0.2.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dc0b364ead1874514c8c2855ab558056ebfeb775653e7ae45ff72f28f8f3166c" + +[[package]] +name = "bumpalo" +version = "3.20.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "72f5acc6cb2ba439de613abc23857ec3d78374d8ed5ac84e9d11336e87da8649" + +[[package]] +name = "bytecount" +version = "0.6.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "175812e0be2bccb6abe50bb8d566126198344f707e304f45c648fd8f2cc0365e" + [[package]] name = "bytes" version = "1.12.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "fc652a48c352aef3ea3aed32080501cf3ef6ed5da78602a020c991775b0aff04" +[[package]] +name = "cfg-if" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600" + +[[package]] +name = "data-encoding" +version = "2.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4583a4551df46e2792f82ceeac45e850d2e2d5debba0b91f102385cda5b11f06" + +[[package]] +name = "email_address" +version = "0.2.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e079f19b08ca6239f47f8ba8509c11cf3ea30095831f7fed61441475edd8c449" +dependencies = [ + "serde", +] + +[[package]] +name = "equivalent" +version = "1.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "877a4ace8713b0bcf2a4e7eec82529c029f1d0619886d18145fea96c3ffe5c0f" + [[package]] name = "errno" version = "0.3.14" @@ -76,6 +177,34 @@ dependencies = [ "windows-sys", ] +[[package]] +name = "fancy-regex" +version = "0.19.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d301f5bf187b3c295fce6468d3875037a0bccc5f6b151c63cac2f85babf21912" +dependencies = [ + "bit-set", + "regex-automata", + "regex-syntax", +] + +[[package]] +name = "fluent-uri" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bc74ac4d8359ae70623506d512209619e5cf8f347124910440dbc221714b328e" +dependencies = [ + "borrow-or-share", + "ref-cast", + "serde", +] + +[[package]] +name = "foldhash" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "77ce24cb58228fbb8aa041425bb1050850ac19177686ea6e0f41a70416f56fdb" + [[package]] name = "form_urlencoded" version = "1.2.2" @@ -85,6 +214,16 @@ dependencies = [ "percent-encoding", ] +[[package]] +name = "fraction" +version = "0.17.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e246562084dde8ebbcc943b261c406ce4f68e5032ec28029a251a47d6a295500" +dependencies = [ + "num", + "num-bigint", +] + [[package]] name = "futures-channel" version = "0.3.34" @@ -118,6 +257,37 @@ dependencies = [ "slab", ] +[[package]] +name = "getrandom" +version = "0.3.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "899def5c37c4fd7b2664648c28120ecec138e4d395b459e5ca34f9cce2dd77fd" +dependencies = [ + "cfg-if", + "js-sys", + "libc", + "r-efi", + "wasip2", + "wasm-bindgen", +] + +[[package]] +name = "hashbrown" +version = "0.17.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a" +dependencies = [ + "allocator-api2", + "equivalent", + "foldhash", +] + +[[package]] +name = "heck" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea" + [[package]] name = "http" version = "1.5.0" @@ -204,12 +374,84 @@ version = "1.0.18" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682" +[[package]] +name = "js-sys" +version = "0.3.106" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7883d941dae510fb2d978fc3fe018c71c9e2892fd38854de3e8b92c2e5ad9cc5" +dependencies = [ + "cfg-if", + "wasm-bindgen", +] + +[[package]] +name = "jsonschema" +version = "0.58.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5761b0ca0a31464030d7c2a98087fde3124ebb5e09b5a112cdb815f03b8ee150" +dependencies = [ + "ahash", + "bytecount", + "data-encoding", + "email_address", + "fancy-regex", + "fraction", + "getrandom", + "itoa", + "jsonschema-regex", + "jsonschema-value", + "num-cmp", + "num-traits", + "percent-encoding", + "referencing", + "regex", + "serde", + "serde_json", + "strum", + "unicode-general-category", + "uuid-simd", +] + +[[package]] +name = "jsonschema-regex" +version = "0.58.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f1ffba4378a3d6ee7f1ab65a8ed95c711ccfe4a3870932bdce89d8260abed38a" +dependencies = [ + "regex-syntax", +] + +[[package]] +name = "jsonschema-value" +version = "0.58.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "386121f898b560ff6aaa7974952720e9d9276a201eca31296387c2ed8707855e" +dependencies = [ + "ahash", + "bytecount", + "fraction", + "getrandom", + "num-cmp", + "num-traits", + "serde_json", + "zmij", +] + [[package]] name = "libc" version = "0.2.189" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3eaf3ede3fee6db1a4c2ee091bf8a8b4dccdc6d17f656fb07896ee72867612f2" +[[package]] +name = "lock_api" +version = "0.4.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "224399e74b87b5f3557511d98dff8b14089b3dadafcab6bb93eab67d3aace965" +dependencies = [ + "scopeguard", +] + [[package]] name = "log" version = "0.4.34" @@ -228,6 +470,12 @@ version = "2.8.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98" +[[package]] +name = "micromap" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c2a86d3146ed3995b5913c414f6664344b9617457320782e64f0bb44afd49d74" + [[package]] name = "mime" version = "0.3.17" @@ -245,12 +493,119 @@ dependencies = [ "windows-sys", ] +[[package]] +name = "num" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "35bd024e8b2ff75562e5f34e7f4905839deb4b22955ef5e73d2fea1b9813cb23" +dependencies = [ + "num-bigint", + "num-complex", + "num-integer", + "num-iter", + "num-rational", + "num-traits", +] + +[[package]] +name = "num-bigint" +version = "0.4.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c89e69e7e0f03bea5ef08013795c25018e101932225a656383bd384495ecc367" +dependencies = [ + "num-integer", + "num-traits", +] + +[[package]] +name = "num-cmp" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "63335b2e2c34fae2fb0aa2cecfd9f0832a1e24b3b32ecec612c3426d46dc8aaa" + +[[package]] +name = "num-complex" +version = "0.4.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "73f88a1307638156682bada9d7604135552957b7818057dcef22705b4d509495" +dependencies = [ + "num-traits", +] + +[[package]] +name = "num-integer" +version = "0.1.47" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7ce2d95d4b3734dc35aa2f45e1aa22cd416814592a4f9d9205e11affd5b8e10b" +dependencies = [ + "num-traits", +] + +[[package]] +name = "num-iter" +version = "0.1.46" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c92800bd69a1eac91786bcfe9da64a897eb72911b8dc3095decbd07429e8048b" +dependencies = [ + "num-integer", + "num-traits", +] + +[[package]] +name = "num-rational" +version = "0.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f83d14da390562dca69fc84082e73e548e1ad308d24accdedd2720017cb37824" +dependencies = [ + "num-bigint", + "num-integer", + "num-traits", +] + +[[package]] +name = "num-traits" +version = "0.2.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841" +dependencies = [ + "autocfg", +] + [[package]] name = "once_cell" version = "1.21.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50" +[[package]] +name = "outref" +version = "0.5.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1a80800c0488c3a21695ea981a54918fbb37abf04f4d0720c453632255e2ff0e" + +[[package]] +name = "parking_lot" +version = "0.12.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "93857453250e3077bd71ff98b6a65ea6621a19bb0f559a85248955ac12c45a1a" +dependencies = [ + "lock_api", + "parking_lot_core", +] + +[[package]] +name = "parking_lot_core" +version = "0.9.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2621685985a2ebf1c516881c026032ac7deafcda1a2c9b7850dc81e3dfcb64c1" +dependencies = [ + "cfg-if", + "libc", + "redox_syscall", + "smallvec", + "windows-link", +] + [[package]] name = "percent-encoding" version = "2.3.2" @@ -281,12 +636,105 @@ dependencies = [ "proc-macro2", ] +[[package]] +name = "r-efi" +version = "5.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "69cdb34c158ceb288df11e18b4bd39de994f6657d83847bdffdbd7f346754b0f" + +[[package]] +name = "redox_syscall" +version = "0.5.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed2bf2547551a7053d6fdfafda3f938979645c44812fbfcda098faae3f1a362d" +dependencies = [ + "bitflags", +] + +[[package]] +name = "ref-cast" +version = "1.0.27" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7e440fb4e4b4147295338efb76001ab9e4efc0e5839df2c47fc5ac2381d365c3" +dependencies = [ + "ref-cast-impl", +] + +[[package]] +name = "ref-cast-impl" +version = "1.0.27" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "92ecd8964f8453721699a1ed72037b0db49ce2f5a5138486ee89bed6f67cdf3a" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.6", +] + +[[package]] +name = "referencing" +version = "0.58.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5cfa1c91745dbca76a406b926918d7c63e15a4525ebab939fec3e015a1fb82b1" +dependencies = [ + "ahash", + "fluent-uri", + "getrandom", + "hashbrown", + "itoa", + "micromap", + "parking_lot", + "percent-encoding", + "serde_json", +] + +[[package]] +name = "regex" +version = "1.13.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f020237b6c8eed93db2e2cb53c00c60a8e1bc73da7d073199a1180401450218d" +dependencies = [ + "aho-corasick", + "memchr", + "regex-automata", + "regex-syntax", +] + +[[package]] +name = "regex-automata" +version = "0.4.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ad8553b9b26413251cbf30e620595c7a41b3887f03da04579c0e6b0d6a06b4b2" +dependencies = [ + "aho-corasick", + "memchr", + "regex-syntax", +] + +[[package]] +name = "regex-syntax" +version = "0.8.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d6f6ff9a378485b298a5286656da665ba74413d36db0979633275d2e708145d4" + +[[package]] +name = "rustversion" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf54715a573b99ac80df0bc206da022bcd442c974952c7b9720069370852e21f" + [[package]] name = "ryu" version = "1.0.23" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9774ba4a74de5f7b1c1451ed6cd5285a32eddb5cccb8cc655a4e50009e06477f" +[[package]] +name = "scopeguard" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49" + [[package]] name = "serde" version = "1.0.229" @@ -314,7 +762,7 @@ checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348" dependencies = [ "proc-macro2", "quote", - "syn", + "syn 3.0.6", ] [[package]] @@ -390,11 +838,44 @@ name = "strata-control" version = "0.1.0" dependencies = [ "axum", + "jsonschema", "serde", "serde_json", "tokio", ] +[[package]] +name = "strum" +version = "0.28.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9628de9b8791db39ceda2b119bbe13134770b56c138ec1d3af810d045c04f9bd" +dependencies = [ + "strum_macros", +] + +[[package]] +name = "strum_macros" +version = "0.28.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ab85eea0270ee17587ed4156089e10b9e6880ee688791d45a905f5b1ca36f664" +dependencies = [ + "heck", + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "syn" +version = "2.0.119" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "872831b642d1a07999a962a351ed35b955ea2cfc8f3862091e2a240a84f17297" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + [[package]] name = "syn" version = "3.0.6" @@ -436,7 +917,7 @@ checksum = "78773a2a397f451582ce068015985c33193cf6dea8b74d2a639fe457b2f07b0e" dependencies = [ "proc-macro2", "quote", - "syn", + "syn 3.0.6", ] [[package]] @@ -487,18 +968,100 @@ dependencies = [ "once_cell", ] +[[package]] +name = "unicode-general-category" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0b993bddc193ae5bd0d623b49ec06ac3e9312875fdae725a975c51db1cc1677f" + [[package]] name = "unicode-ident" version = "1.0.26" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d245f478577f809a851594d02313b640fb437e0bb33866753cff937863096954" +[[package]] +name = "uuid-simd" +version = "0.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "23b082222b4f6619906941c17eb2297fff4c2fb96cb60164170522942a200bd8" +dependencies = [ + "outref", + "vsimd", +] + +[[package]] +name = "version_check" +version = "0.9.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a" + +[[package]] +name = "vsimd" +version = "0.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5c3082ca00d5a5ef149bb8b555a72ae84c9c59f7250f013ac822ac2e49b19c64" + [[package]] name = "wasi" version = "0.11.1+wasi-snapshot-preview1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ccf3ec651a847eb01de73ccad15eb7d99f80485de043efb2f370cd654f4ea44b" +[[package]] +name = "wasip2" +version = "1.0.1+wasi-0.2.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0562428422c63773dad2c345a1882263bbf4d65cf3f42e90921f787ef5ad58e7" +dependencies = [ + "wit-bindgen", +] + +[[package]] +name = "wasm-bindgen" +version = "0.2.129" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9bb54f33acc68fd454578d9820b0bde1a1a3d17aa17bb7b6595806d02886d409" +dependencies = [ + "cfg-if", + "once_cell", + "rustversion", + "wasm-bindgen-macro", + "wasm-bindgen-shared", +] + +[[package]] +name = "wasm-bindgen-macro" +version = "0.2.129" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2e29d0c35b16e224a7eeb5cd2d25e3e1968fbd65604117b44d3b789d00ee8535" +dependencies = [ + "quote", + "wasm-bindgen-macro-support", +] + +[[package]] +name = "wasm-bindgen-macro-support" +version = "0.2.129" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6f501a8bc3719dba86ef8ae4728879c08001bea749eb1333ac5b91e040e2a6b7" +dependencies = [ + "bumpalo", + "proc-macro2", + "quote", + "syn 3.0.6", + "wasm-bindgen-shared", +] + +[[package]] +name = "wasm-bindgen-shared" +version = "0.2.129" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "23f0c9c52aa7cd7d77769a4cfe2a9adb1b331f489a41d912ce14513d5ab995c6" +dependencies = [ + "unicode-ident", +] + [[package]] name = "windows-link" version = "0.2.1" @@ -514,6 +1077,32 @@ dependencies = [ "windows-link", ] +[[package]] +name = "wit-bindgen" +version = "0.46.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f17a85883d4e6d00e8a97c586de764dabcc06133f7f1d55dce5cdc070ad7fe59" + +[[package]] +name = "zerocopy" +version = "0.8.59" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6df92bf3d9227be3d53173901ddbffac2babc27ae50f397776ffd6dc33f800cb" +dependencies = [ + "zerocopy-derive", +] + +[[package]] +name = "zerocopy-derive" +version = "0.8.59" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ac4f328cf2f05d084e496c3e9c3f33ed0a183656a16e1fcec4d464d8373aec82" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + [[package]] name = "zmij" version = "1.0.23" diff --git a/control-plane/Cargo.toml b/control-plane/Cargo.toml index 0ceb95a7..5f44b6e8 100644 --- a/control-plane/Cargo.toml +++ b/control-plane/Cargo.toml @@ -2,10 +2,11 @@ name = "strata-control" version = "0.1.0" edition = "2024" -rust-version = "1.85" +rust-version = "1.99" [dependencies] axum = "0.8" +jsonschema = { version = "0.58.4", default-features = false } serde = { version = "1", features = ["derive"] } serde_json = "1" tokio = { version = "1", features = ["io-util", "macros", "net", "process", "rt-multi-thread", "signal", "sync", "time"] } diff --git a/control-plane/README.md b/control-plane/README.md index 4e79e513..f6c459d4 100644 --- a/control-plane/README.md +++ b/control-plane/README.md @@ -1,6 +1,8 @@ # Control plane -The Rust control plane has its first runnable milestone: process health, worker readiness, status, and graceful shutdown. It can start a Strata engine worker and marks readiness only after the engine emits `READY `. It does not yet expose inference API routes or restart a failed worker. +The repository pins Rust 1.99.0 in [`rust-toolchain.toml`](../rust-toolchain.toml). `rustup` selects it automatically from this checkout. `scripts/check-local.sh` runs formatting, Clippy, Rust tests, protocol replay, and the CPU engine tests. + +The Rust control plane provides process health, worker readiness, status, and graceful shutdown. It can start a Strata engine worker and marks readiness only after the engine emits `READY `. It also exposes `POST /v1/responses` for request validation. This route returns 503 while the worker is unavailable and 501 while the native inference adapter is absent; it never fabricates a model response. Worker restart is not yet implemented. Run locally with `cargo run --manifest-path control-plane/Cargo.toml`. It binds to `127.0.0.1:8081` by default; set `STRATA_BIND` to another socket address if needed. Check `/health`, `/ready`, and `/status`. @@ -8,4 +10,11 @@ Set `STRATA_CONFIG` to a JSON file using [`config.example.json`](config.example. Without an engine configuration, `/ready` returns HTTP 503 and `/status` reports `unconfigured`. A configured worker reports `starting`, then `ready` with `max_context`, or `failed` if startup, the readiness handshake, or the process fails. During shutdown it reports `stopping` and sends `QUIT` to the engine. Startup has a timeout; the control plane never advertises readiness before the engine handshake. -Run the local contract checks with `cargo test --manifest-path control-plane/Cargo.toml --locked`. The tests use a small fake engine process and need no GPU or model. +Run the local contract checks with `cargo test --manifest-path control-plane/Cargo.toml --locked`. The tests use a small fake engine process and need no GPU or model. The Responses trace builder checks ordered SSE events, terminal completion, unchanged tool arguments, and JSON Schema output validation. The synthetic replay can be run as JSON or SSE: + +```sh +cargo run --manifest-path control-plane/Cargo.toml --locked --bin replay-responses -- benchmarks/fixtures/responses/structured-tool.json +cargo run --manifest-path control-plane/Cargo.toml --locked --bin replay-responses -- --sse benchmarks/fixtures/responses/structured-tool.json +``` + +See [API contract](../docs/api-contract.md) for the supported subset and remaining integration work. diff --git a/control-plane/src/app.rs b/control-plane/src/app.rs new file mode 100644 index 00000000..0a2ebd13 --- /dev/null +++ b/control-plane/src/app.rs @@ -0,0 +1,80 @@ +use std::sync::Arc; + +use axum::{ + Json, Router, + extract::{DefaultBodyLimit, State}, + http::StatusCode, + routing::{get, post}, +}; +use serde::Serialize; +use tokio::sync::RwLock; + +use crate::{ + responses, + worker::{WorkerState, WorkerStatus}, +}; + +#[derive(Clone)] +pub struct AppState { + pub worker: Arc>, +} + +impl Default for AppState { + fn default() -> Self { + Self { + worker: Arc::new(RwLock::new(WorkerStatus::default())), + } + } +} + +#[derive(Serialize)] +struct HealthResponse { + status: &'static str, +} + +#[derive(Serialize)] +struct StatusResponse { + service: &'static str, + version: &'static str, + worker: WorkerState, + ready: bool, + max_context: Option, +} + +pub fn router(state: AppState) -> Router { + Router::new() + .route("/health", get(health)) + .route("/ready", get(ready)) + .route("/status", get(status)) + .route("/v1/responses", post(responses::create)) + .layer(DefaultBodyLimit::max(16 * 1024 * 1024)) + .with_state(state) +} + +async fn health() -> Json { + Json(HealthResponse { status: "ok" }) +} + +async fn ready(State(state): State) -> (StatusCode, Json) { + let worker = *state.worker.read().await; + let code = if worker.state == WorkerState::Ready { + StatusCode::OK + } else { + StatusCode::SERVICE_UNAVAILABLE + }; + (code, Json(status_body(worker))) +} + +async fn status(State(state): State) -> Json { + Json(status_body(*state.worker.read().await)) +} + +fn status_body(worker: WorkerStatus) -> StatusResponse { + StatusResponse { + service: "strata-control", + version: env!("CARGO_PKG_VERSION"), + worker: worker.state, + ready: worker.state == WorkerState::Ready, + max_context: worker.max_context, + } +} diff --git a/control-plane/src/bin/replay-responses.rs b/control-plane/src/bin/replay-responses.rs new file mode 100644 index 00000000..4f0492cd --- /dev/null +++ b/control-plane/src/bin/replay-responses.rs @@ -0,0 +1,64 @@ +use std::{env, fs, process::ExitCode}; + +use serde::Deserialize; +use strata_control::responses::{CreateRequest, OutputItem, ResponseTrace, Usage}; + +#[derive(Deserialize)] +#[serde(deny_unknown_fields)] +struct Fixture { + request: CreateRequest, + items: Vec, + usage: Usage, + id: String, + created_at: u64, + completed_at: u64, +} + +fn main() -> ExitCode { + if let Err(error) = run() { + eprintln!("replay-responses: {error}"); + return ExitCode::FAILURE; + } + ExitCode::SUCCESS +} + +fn run() -> Result<(), String> { + let mut args = env::args().skip(1); + let first = args + .next() + .ok_or("usage: replay-responses [--sse] FIXTURE.json")?; + let (sse, path) = if first == "--sse" { + ( + true, + args.next() + .ok_or("usage: replay-responses [--sse] FIXTURE.json")?, + ) + } else { + (false, first) + }; + if args.next().is_some() { + return Err("usage: replay-responses [--sse] FIXTURE.json".to_owned()); + } + let source = fs::read_to_string(&path).map_err(|error| format!("{path}: {error}"))?; + let fixture: Fixture = serde_json::from_str(&source) + .map_err(|error| format!("invalid fixture {path}: {error}"))?; + let trace = ResponseTrace::build( + &fixture.request, + &fixture.items, + fixture.usage, + &fixture.id, + fixture.created_at, + fixture.completed_at, + )?; + if sse { + for frame in trace.sse_frames() { + print!("{frame}"); + } + } else { + println!( + "{}", + serde_json::to_string_pretty(&trace.response).map_err(|error| error.to_string())? + ); + } + Ok(()) +} diff --git a/control-plane/src/lib.rs b/control-plane/src/lib.rs new file mode 100644 index 00000000..a84c5528 --- /dev/null +++ b/control-plane/src/lib.rs @@ -0,0 +1,5 @@ +pub mod app; +pub mod config; +pub mod responses; +pub mod wire; +pub mod worker; diff --git a/control-plane/src/main.rs b/control-plane/src/main.rs index b5707ed9..357dfdfc 100644 --- a/control-plane/src/main.rs +++ b/control-plane/src/main.rs @@ -1,90 +1,19 @@ -mod config; -mod worker; +use tokio::sync::watch; -use std::sync::Arc; - -use axum::{Json, Router, extract::State, http::StatusCode, routing::get}; -use serde::Serialize; -use tokio::sync::{RwLock, watch}; - -use config::Config; -use worker::{WorkerState, WorkerStatus}; - -#[derive(Clone)] -struct AppState { - worker: Arc>, -} - -impl AppState { - fn new() -> Self { - Self { - worker: Arc::new(RwLock::new(WorkerStatus::default())), - } - } -} - -#[derive(Serialize)] -struct HealthResponse { - status: &'static str, -} - -#[derive(Serialize)] -struct StatusResponse { - service: &'static str, - version: &'static str, - worker: WorkerState, - ready: bool, - max_context: Option, -} - -fn router(state: AppState) -> Router { - Router::new() - .route("/health", get(health)) - .route("/ready", get(ready)) - .route("/status", get(status)) - .with_state(state) -} - -async fn health() -> Json { - Json(HealthResponse { status: "ok" }) -} - -async fn ready(State(state): State) -> (StatusCode, Json) { - let worker = *state.worker.read().await; - let code = if worker.state == WorkerState::Ready { - StatusCode::OK - } else { - StatusCode::SERVICE_UNAVAILABLE - }; - (code, Json(status_body(worker))) -} - -async fn status(State(state): State) -> Json { - Json(status_body(*state.worker.read().await)) -} - -fn status_body(worker: WorkerStatus) -> StatusResponse { - StatusResponse { - service: "strata-control", - version: env!("CARGO_PKG_VERSION"), - worker: worker.state, - ready: worker.state == WorkerState::Ready, - max_context: worker.max_context, - } -} +use strata_control::{app, config::Config, worker}; #[tokio::main] async fn main() -> Result<(), Box> { let config = Config::load()?; let listener = tokio::net::TcpListener::bind(config.bind).await?; - let state = AppState::new(); + let state = app::AppState::default(); let (shutdown_tx, shutdown_rx) = watch::channel(false); let worker_task = config .worker .map(|config| tokio::spawn(worker::run(config, state.worker.clone(), shutdown_rx))); eprintln!("strata-control listening on {}", listener.local_addr()?); let server_shutdown = shutdown_tx.clone(); - let result = axum::serve(listener, router(state)) + let result = axum::serve(listener, app::router(state)) .with_graceful_shutdown(async move { shutdown_signal().await; let _ = server_shutdown.send(true); diff --git a/control-plane/src/responses.rs b/control-plane/src/responses.rs new file mode 100644 index 00000000..9ee8ce19 --- /dev/null +++ b/control-plane/src/responses.rs @@ -0,0 +1,596 @@ +use axum::{ + Json, + extract::{State, rejection::JsonRejection}, + http::StatusCode, + response::{IntoResponse, Response}, +}; +use serde::{Deserialize, Serialize}; +use serde_json::{Map, Value, json}; +use std::collections::HashSet; + +use crate::{app::AppState, worker::WorkerState}; + +#[derive(Clone, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct CreateRequest { + pub model: String, + pub input: Value, + #[serde(default)] + pub stream: bool, + pub instructions: Option, + pub max_output_tokens: Option, + pub previous_response_id: Option, + pub parallel_tool_calls: Option, + pub reasoning: Option, + pub text: Option, + #[serde(default)] + pub tools: Vec, + pub tool_choice: Option, + pub temperature: Option, + pub top_p: Option, + pub truncation: Option, + pub metadata: Option>, + pub store: Option, +} + +#[derive(Clone, Deserialize, Serialize)] +#[serde(deny_unknown_fields)] +pub struct TextOptions { + pub format: TextFormat, +} + +#[derive(Clone, Deserialize, Serialize)] +#[serde(tag = "type", rename_all = "snake_case")] +pub enum TextFormat { + Text, + JsonObject, + JsonSchema { + name: String, + schema: Value, + strict: Option, + }, +} + +impl CreateRequest { + pub fn validate(&self) -> Result<(), (&'static str, &'static str)> { + if self.model.trim().is_empty() { + return Err(("model", "model must be a nonempty string")); + } + if !self.input.is_string() && !self.input.is_array() { + return Err(("input", "input must be a string or an array")); + } + if self.input.as_str().is_some_and(str::is_empty) + || self.input.as_array().is_some_and(Vec::is_empty) + { + return Err(("input", "input cannot be empty")); + } + if self.max_output_tokens == Some(0) { + return Err(("max_output_tokens", "max_output_tokens must be positive")); + } + if self.store == Some(true) { + return Err(("store", "stored responses are not supported yet")); + } + if let Some(TextOptions { + format: TextFormat::JsonSchema { name, schema, .. }, + }) = &self.text + && (name.is_empty() || schema.get("type").and_then(Value::as_str) != Some("object")) + { + return Err(( + "text.format", + "json_schema needs a name and a root schema of type object", + )); + } + for tool in &self.tools { + if tool.get("type").and_then(Value::as_str) != Some("function") + || tool.get("name").and_then(Value::as_str).is_none() + { + return Err(("tools", "only named function tools are supported")); + } + } + Ok(()) + } +} + +pub async fn create( + State(state): State, + body: Result, JsonRejection>, +) -> Response { + let Json(body) = match body { + Ok(body) => body, + Err(error) => { + return api_error( + error.status(), + "invalid_request_error", + "invalid_json", + None, + &error.to_string(), + ); + } + }; + let request: CreateRequest = match serde_json::from_value(body) { + Ok(request) => request, + Err(error) => { + return api_error( + StatusCode::BAD_REQUEST, + "invalid_request_error", + "invalid_request", + None, + &error.to_string(), + ); + } + }; + if let Err((param, message)) = request.validate() { + return api_error( + StatusCode::BAD_REQUEST, + "invalid_request_error", + "invalid_request", + Some(param), + message, + ); + } + if state.worker.read().await.state != WorkerState::Ready { + return api_error( + StatusCode::SERVICE_UNAVAILABLE, + "server_error", + "worker_not_ready", + None, + "the Strata worker is not ready", + ); + } + api_error( + StatusCode::NOT_IMPLEMENTED, + "server_error", + "inference_adapter_missing", + None, + "the native Responses inference adapter is not connected yet", + ) +} + +fn api_error( + status: StatusCode, + kind: &'static str, + code: &'static str, + param: Option<&'static str>, + message: &str, +) -> Response { + ( + status, + Json(json!({"error": {"message": message, "type": kind, "param": param, "code": code}})), + ) + .into_response() +} + +#[derive(Clone, Deserialize)] +#[serde(tag = "type", rename_all = "snake_case")] +pub enum OutputItem { + Text { + deltas: Vec, + }, + FunctionCall { + name: String, + call_id: String, + argument_deltas: Vec, + }, +} + +#[derive(Clone, Copy, Deserialize)] +pub struct Usage { + pub input_tokens: u64, + pub output_tokens: u64, + pub reasoning_tokens: u64, + pub cached_tokens: u64, +} + +#[derive(Debug)] +pub struct ResponseTrace { + pub response: Value, + pub events: Vec, +} + +impl ResponseTrace { + pub fn build( + request: &CreateRequest, + items: &[OutputItem], + usage: Usage, + id: &str, + created_at: u64, + completed_at: u64, + ) -> Result { + request + .validate() + .map_err(|(param, message)| format!("{param}: {message}"))?; + if items.is_empty() { + return Err("a completed response needs an output item".to_owned()); + } + if !id.starts_with("resp_") + || id.len() <= 5 + || !id[5..] + .bytes() + .all(|byte| byte.is_ascii_alphanumeric() || byte == b'_' || byte == b'-') + || completed_at < created_at + { + return Err("invalid response identity or timestamps".to_owned()); + } + if usage.cached_tokens > usage.input_tokens || usage.reasoning_tokens > usage.output_tokens + { + return Err("usage detail counters exceed their parent count".to_owned()); + } + let text = request + .text + .as_ref() + .map(serde_json::to_value) + .transpose() + .map_err(|error| error.to_string())? + .unwrap_or_else(|| json!({"format": {"type": "text"}})); + let mut response = json!({ + "id": id, + "object": "response", + "created_at": created_at, + "status": "in_progress", + "error": null, + "incomplete_details": null, + "instructions": request.instructions, + "max_output_tokens": request.max_output_tokens, + "model": request.model, + "output": [], + "parallel_tool_calls": request.parallel_tool_calls.unwrap_or(true), + "previous_response_id": request.previous_response_id, + "reasoning": request.reasoning.clone().unwrap_or_else(|| json!({"effort": null, "summary": null})), + "store": false, + "temperature": request.temperature.unwrap_or(1.0), + "text": text, + "tool_choice": request.tool_choice.clone().unwrap_or_else(|| json!("auto")), + "tools": request.tools, + "top_p": request.top_p.unwrap_or(1.0), + "truncation": request.truncation.as_deref().unwrap_or("disabled"), + "usage": null, + "user": null, + "metadata": request.metadata.clone().unwrap_or_default(), + }); + let mut emitter = Emitter::default(); + emitter.push("response.created", json!({"response": response})); + emitter.push("response.in_progress", json!({"response": response})); + + let mut output = Vec::with_capacity(items.len()); + let mut all_text = String::new(); + let mut has_text = false; + let mut call_ids = HashSet::new(); + let allowed_tools: HashSet<&str> = request + .tools + .iter() + .filter_map(|tool| tool.get("name").and_then(Value::as_str)) + .collect(); + for (index, item) in items.iter().enumerate() { + match item { + OutputItem::Text { deltas } => { + has_text = true; + let item_id = format!("msg_{}_{}", &id[5..], index); + let mut whole = String::new(); + let pending = json!({"id": item_id, "type": "message", "status": "in_progress", "role": "assistant", "content": []}); + emitter.push( + "response.output_item.added", + json!({"response_id": id, "output_index": index, "item": pending}), + ); + emitter.push("response.content_part.added", json!({"response_id": id, "item_id": item_id, "output_index": index, "content_index": 0, "part": text_part("")})); + for delta in deltas { + whole.push_str(delta); + emitter.push("response.output_text.delta", json!({"response_id": id, "item_id": item_id, "output_index": index, "content_index": 0, "delta": delta, "logprobs": []})); + } + all_text.push_str(&whole); + emitter.push("response.output_text.done", json!({"response_id": id, "item_id": item_id, "output_index": index, "content_index": 0, "text": whole, "logprobs": []})); + emitter.push("response.content_part.done", json!({"response_id": id, "item_id": item_id, "output_index": index, "content_index": 0, "part": text_part(&whole)})); + let done = json!({"id": item_id, "type": "message", "status": "completed", "role": "assistant", "content": [text_part(&whole)]}); + emitter.push( + "response.output_item.done", + json!({"response_id": id, "output_index": index, "item": done}), + ); + output.push(done); + } + OutputItem::FunctionCall { + name, + call_id, + argument_deltas, + } => { + if name.is_empty() || call_id.is_empty() { + return Err("function calls need a name and call_id".to_owned()); + } + if !allowed_tools.contains(name.as_str()) { + return Err(format!("function call names an undeclared tool: {name}")); + } + if !call_ids.insert(call_id) { + return Err("function call_id must be unique".to_owned()); + } + let item_id = format!("fc_{}_{}", &id[5..], index); + let pending = json!({"id": item_id, "type": "function_call", "status": "in_progress", "call_id": call_id, "name": name, "arguments": ""}); + emitter.push( + "response.output_item.added", + json!({"response_id": id, "output_index": index, "item": pending}), + ); + let mut arguments = String::new(); + for delta in argument_deltas { + arguments.push_str(delta); + emitter.push("response.function_call_arguments.delta", json!({"response_id": id, "item_id": item_id, "output_index": index, "delta": delta})); + } + if !serde_json::from_str::(&arguments) + .is_ok_and(|value| value.is_object()) + { + return Err("function call arguments must be a JSON object".to_owned()); + } + emitter.push("response.function_call_arguments.done", json!({"response_id": id, "item_id": item_id, "output_index": index, "arguments": arguments})); + let done = json!({"id": item_id, "type": "function_call", "status": "completed", "call_id": call_id, "name": name, "arguments": arguments}); + emitter.push( + "response.output_item.done", + json!({"response_id": id, "output_index": index, "item": done}), + ); + output.push(done); + } + } + } + + if has_text { + validate_text_format(request, &all_text)?; + } + let total_tokens = usage + .input_tokens + .checked_add(usage.output_tokens) + .ok_or("total token count overflows u64")?; + + response["status"] = json!("completed"); + response["completed_at"] = json!(completed_at); + response["output"] = json!(output); + response["usage"] = json!({ + "input_tokens": usage.input_tokens, + "input_tokens_details": {"cached_tokens": usage.cached_tokens}, + "output_tokens": usage.output_tokens, + "output_tokens_details": {"reasoning_tokens": usage.reasoning_tokens}, + "total_tokens": total_tokens, + }); + emitter.push("response.completed", json!({"response": response})); + Ok(Self { + response, + events: emitter.events, + }) + } + + pub fn sse_frames(&self) -> Vec { + self.events + .iter() + .map(|event| { + format!( + "event: {}\ndata: {}\n\n", + event["type"].as_str().unwrap_or("error"), + event + ) + }) + .collect() + } +} + +fn validate_text_format(request: &CreateRequest, text: &str) -> Result<(), String> { + let Some(options) = &request.text else { + return Ok(()); + }; + match &options.format { + TextFormat::Text => Ok(()), + TextFormat::JsonObject => { + if serde_json::from_str::(text).is_ok_and(|value| value.is_object()) { + Ok(()) + } else { + Err("text.format requires a JSON object".to_owned()) + } + } + TextFormat::JsonSchema { schema, .. } => { + reject_remote_refs(schema)?; + let validator = jsonschema::validator_for(schema) + .map_err(|error| format!("invalid text.format schema: {error}"))?; + let value: Value = serde_json::from_str(text) + .map_err(|error| format!("text.format output is not JSON: {error}"))?; + validator + .validate(&value) + .map_err(|error| format!("text.format output violates schema: {error}")) + } + } +} + +fn reject_remote_refs(value: &Value) -> Result<(), String> { + match value { + Value::Object(fields) => { + for key in ["$ref", "$dynamicRef", "$recursiveRef"] { + if fields + .get(key) + .and_then(Value::as_str) + .is_some_and(|reference| !reference.starts_with('#')) + { + return Err(format!("text.format schema cannot use external {key}")); + } + } + for child in fields.values() { + reject_remote_refs(child)?; + } + } + Value::Array(values) => { + for child in values { + reject_remote_refs(child)?; + } + } + _ => {} + } + Ok(()) +} + +fn text_part(text: &str) -> Value { + json!({"type": "output_text", "text": text, "annotations": [], "logprobs": []}) +} + +#[derive(Default)] +struct Emitter { + events: Vec, +} + +impl Emitter { + fn push(&mut self, kind: &'static str, fields: Value) { + let mut fields = fields + .as_object() + .cloned() + .expect("event fields are an object"); + fields.insert("type".to_owned(), json!(kind)); + fields.insert("sequence_number".to_owned(), json!(self.events.len())); + self.events.push(Value::Object(fields)); + } +} + +#[cfg(test)] +mod tests { + use super::*; + use axum::{body::to_bytes, extract::State}; + + fn make_request(extra: Value) -> CreateRequest { + let mut value = json!({"model": "strata-local", "input": "test", "stream": true}); + value + .as_object_mut() + .unwrap() + .extend(extra.as_object().unwrap().clone()); + serde_json::from_value(value).unwrap() + } + + fn usage() -> Usage { + Usage { + input_tokens: 7, + output_tokens: 3, + reasoning_tokens: 1, + cached_tokens: 2, + } + } + + #[test] + fn replay_preserves_text_and_tool_arguments_and_terminates() { + let request = make_request(json!({"tools": [{"type": "function", "name": "lookup"}]})); + let trace = ResponseTrace::build( + &request, + &[ + OutputItem::Text { + deltas: vec!["Hello".into(), " there".into()], + }, + OutputItem::FunctionCall { + name: "lookup".into(), + call_id: "call_1".into(), + argument_deltas: vec!["{\"x\":".into(), "1}".into()], + }, + ], + usage(), + "resp_test", + 1, + 2, + ) + .unwrap(); + assert_eq!(trace.response["status"], "completed"); + assert_eq!(trace.response["usage"]["total_tokens"], 10); + assert_eq!( + trace.response["output"][0]["content"][0]["text"], + "Hello there" + ); + assert_eq!(trace.response["output"][1]["arguments"], "{\"x\":1}"); + for (index, event) in trace.events.iter().enumerate() { + assert_eq!(event["sequence_number"], json!(index)); + } + assert_eq!(trace.events.first().unwrap()["type"], "response.created"); + assert_eq!(trace.events.last().unwrap()["type"], "response.completed"); + let frames = trace.sse_frames(); + assert_eq!(frames.len(), trace.events.len()); + assert!( + frames + .last() + .unwrap() + .starts_with("event: response.completed\ndata: ") + ); + assert!(frames.iter().all(|frame| frame.ends_with("\n\n"))); + } + + #[test] + fn structured_output_rejects_invalid_json_and_external_refs() { + let request = make_request( + json!({"text": {"format": {"type": "json_schema", "name": "result", "schema": {"type": "object", "properties": {"ok": {"type": "boolean"}}, "required": ["ok"]}}}}), + ); + let item = OutputItem::Text { + deltas: vec!["{\"ok\":false}".into()], + }; + assert!(ResponseTrace::build(&request, &[item], usage(), "resp_valid", 1, 2).is_ok()); + let item = OutputItem::Text { + deltas: vec!["{\"ok\":1}".into()], + }; + assert!( + ResponseTrace::build(&request, &[item], usage(), "resp_invalid", 1, 2) + .unwrap_err() + .contains("violates schema") + ); + let request = make_request( + json!({"text": {"format": {"type": "json_schema", "name": "result", "schema": {"type": "object", "$ref": "https://example.invalid/schema.json"}}}}), + ); + let item = OutputItem::Text { + deltas: vec!["{}".into()], + }; + assert!( + ResponseTrace::build(&request, &[item], usage(), "resp_remote", 1, 2) + .unwrap_err() + .contains("external $ref") + ); + } + + #[test] + fn malformed_tool_calls_never_produce_a_completed_trace() { + let request = make_request(json!({"tools": [{"type": "function", "name": "lookup"}]})); + let call = OutputItem::FunctionCall { + name: "lookup".into(), + call_id: "call_1".into(), + argument_deltas: vec!["{bad".into()], + }; + assert!( + ResponseTrace::build(&request, &[call], usage(), "resp_bad", 1, 2) + .unwrap_err() + .contains("JSON object") + ); + } + + #[test] + fn tool_only_response_can_precede_structured_text() { + let request = make_request(json!({ + "text": {"format": {"type": "json_object"}}, + "tools": [{"type": "function", "name": "lookup"}] + })); + let call = OutputItem::FunctionCall { + name: "lookup".into(), + call_id: "call_1".into(), + argument_deltas: vec!["{}".into()], + }; + assert!(ResponseTrace::build(&request, &[call], usage(), "resp_tool", 1, 2).is_ok()); + } + + #[tokio::test] + async fn endpoint_reports_unavailable_and_missing_adapter_truthfully() { + let state = AppState::default(); + let payload = json!({"model": "strata-local", "input": "Hello"}); + let response = create(State(state.clone()), Ok(Json(payload.clone()))).await; + assert_eq!(response.status(), StatusCode::SERVICE_UNAVAILABLE); + let body = to_bytes(response.into_body(), usize::MAX).await.unwrap(); + assert_eq!( + serde_json::from_slice::(&body).unwrap()["error"]["code"], + "worker_not_ready" + ); + + state.worker.write().await.state = WorkerState::Ready; + let response = create(State(state.clone()), Ok(Json(payload))).await; + assert_eq!(response.status(), StatusCode::NOT_IMPLEMENTED); + let body = to_bytes(response.into_body(), usize::MAX).await.unwrap(); + assert_eq!( + serde_json::from_slice::(&body).unwrap()["error"]["code"], + "inference_adapter_missing" + ); + + let response = create( + State(state), + Ok(Json(json!({"model": "", "input": "Hello"}))), + ) + .await; + assert_eq!(response.status(), StatusCode::BAD_REQUEST); + } +} diff --git a/control-plane/src/wire.rs b/control-plane/src/wire.rs new file mode 100644 index 00000000..0d200bfd --- /dev/null +++ b/control-plane/src/wire.rs @@ -0,0 +1,225 @@ +//! Typed boundary for the resident Strata `--serve` stdin/stdout protocol. + +#[derive(Debug, Clone, PartialEq)] +pub struct Generate { + pub token_ids: Vec, + pub max_new: u32, + pub temperature: Option, + pub top_p: Option, +} + +impl Generate { + pub fn line(&self) -> Result { + if self.token_ids.is_empty() || self.max_new == 0 { + return Err("GEN needs prompt tokens and a positive max_new"); + } + if self + .temperature + .is_some_and(|value| !value.is_finite() || !(0.0..=2.0).contains(&value)) + { + return Err("temperature must be finite and between 0 and 2"); + } + if self + .top_p + .is_some_and(|value| !value.is_finite() || !(0.0..=1.0).contains(&value)) + { + return Err("top_p must be finite and between 0 and 1"); + } + let mut line = format!("GEN {}", self.max_new); + if let Some(value) = self.temperature.filter(|value| *value > 0.0) { + line.push_str(&format!(" temperature={value}")); + } + if let Some(value) = self.top_p.filter(|value| *value < 1.0) { + line.push_str(&format!(" top_p={value}")); + } + line.push(' '); + for (index, id) in self.token_ids.iter().enumerate() { + if index > 0 { + line.push(','); + } + line.push_str(&id.to_string()); + } + line.push('\n'); + Ok(line) + } +} + +#[derive(Debug, Clone, PartialEq)] +pub enum Event { + Token(u32), + PromptProgress { read: u64, total: u64 }, + Done(Done), + Error(String), +} + +#[derive(Debug, Clone, PartialEq)] +pub struct Done { + pub generated: u64, + pub prompt_tokens: u64, + pub prompt_ms: f64, + pub decode_ms: f64, + pub finish: Finish, + pub drafts_accepted: Option, + pub drafts_offered: Option, + pub reused: Option, + pub expert_hits: Option, + pub expert_lookups: Option, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Finish { + Stop, + Length, + Cancel, +} + +pub fn parse_line(line: &str) -> Result, String> { + let line = line.trim_end_matches(['\r', '\n']); + let Some((tag, rest)) = line.split_once(' ') else { + return Err(format!("invalid engine line: {line}")); + }; + match tag { + "T" => Ok(Some(Event::Token( + rest.parse().map_err(|_| "invalid T token id")?, + ))), + "PP" => { + let fields: Vec<_> = rest.split_whitespace().collect(); + if fields.len() < 2 { + return Err("invalid PP progress line".to_owned()); + } + let read: u64 = fields[0].parse().map_err(|_| "invalid PP read count")?; + let total: u64 = fields[1].parse().map_err(|_| "invalid PP total count")?; + if read > total { + return Err("PP read count exceeds total".to_owned()); + } + Ok(Some(Event::PromptProgress { read, total })) + } + "DONE" => Ok(Some(Event::Done(parse_done(rest)?))), + "ERR" => Ok(Some(Event::Error(rest.to_owned()))), + "INFO" => Ok(None), + _ => Err(format!("unknown engine line tag: {tag}")), + } +} + +fn parse_done(rest: &str) -> Result { + let fields: Vec<_> = rest.split_whitespace().collect(); + if fields.len() < 5 { + return Err("DONE needs generated, prompt, timings, and finish".to_owned()); + } + let count = |index: usize| -> Result { + fields[index] + .parse() + .map_err(|_| format!("invalid DONE count at field {index}")) + }; + let timing = |index: usize| -> Result { + let value: f64 = fields[index] + .parse() + .map_err(|_| format!("invalid DONE timing at field {index}"))?; + if !value.is_finite() || value < 0.0 { + return Err(format!("invalid DONE timing at field {index}")); + } + Ok(value) + }; + let optional_count = |index: usize| -> Result, String> { + if fields.len() > index { + count(index).map(Some) + } else { + Ok(None) + } + }; + let finish = match fields[4] { + "stop" => Finish::Stop, + "length" => Finish::Length, + "cancel" => Finish::Cancel, + other => return Err(format!("unknown DONE finish: {other}")), + }; + let done = Done { + generated: count(0)?, + prompt_tokens: count(1)?, + prompt_ms: timing(2)?, + decode_ms: timing(3)?, + finish, + drafts_accepted: optional_count(5)?, + drafts_offered: optional_count(6)?, + reused: optional_count(7)?, + expert_hits: optional_count(8)?, + expert_lookups: optional_count(9)?, + }; + if done + .drafts_accepted + .zip(done.drafts_offered) + .is_some_and(|(a, b)| a > b) + || done + .reused + .is_some_and(|reused| reused > done.prompt_tokens) + { + return Err("inconsistent DONE counters".to_owned()); + } + Ok(done) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn gen_line_uses_upstream_sampling_spelling() { + let request = Generate { + token_ids: vec![101, 42, 7], + max_new: 256, + temperature: Some(0.7), + top_p: Some(0.9), + }; + assert_eq!( + request.line().unwrap(), + "GEN 256 temperature=0.7 top_p=0.9 101,42,7\n" + ); + assert!( + Generate { + token_ids: vec![], + ..request + } + .line() + .is_err() + ); + } + + #[test] + fn parses_current_and_older_done_lines() { + let current = parse_line("DONE 12 300 45.1 88.2 stop 7 10 240 90 100 2 0 0.0\n") + .unwrap() + .unwrap(); + let Event::Done(done) = current else { + panic!("expected DONE") + }; + assert_eq!(done.finish, Finish::Stop); + assert_eq!(done.drafts_accepted, Some(7)); + assert_eq!(done.reused, Some(240)); + assert_eq!(done.expert_hits, Some(90)); + assert_eq!(done.expert_lookups, Some(100)); + let Event::Done(older) = parse_line("DONE 2 4 1.0 3.0 length\n").unwrap().unwrap() else { + panic!("expected DONE") + }; + assert_eq!(older.reused, None); + assert_eq!(older.finish, Finish::Length); + } + + #[test] + fn parses_tokens_progress_and_errors_without_losing_terminal_state() { + assert_eq!(parse_line("T 123\n").unwrap(), Some(Event::Token(123))); + assert_eq!( + parse_line("PP 64 128 10 5.0\n").unwrap(), + Some(Event::PromptProgress { + read: 64, + total: 128 + }) + ); + assert_eq!( + parse_line("ERR bad request\n").unwrap(), + Some(Event::Error("bad request".into())) + ); + assert_eq!(parse_line("INFO engine=0.1.8\n").unwrap(), None); + assert!(parse_line("DONE 1 2 NaN 3 stop").is_err()); + assert!(parse_line("PP 129 128").is_err()); + } +} diff --git a/docs/api-contract.md b/docs/api-contract.md new file mode 100644 index 00000000..75b5aa11 --- /dev/null +++ b/docs/api-contract.md @@ -0,0 +1,11 @@ +# Responses contract status + +The Rust control plane has a `POST /v1/responses` route and a reusable response trace builder. The route parses a subset of Responses requests and returns OpenAI-shaped JSON errors. It returns `503 worker_not_ready` until the engine handshake completes, then `501 inference_adapter_missing`. It does not generate a response yet. + +The offline trace builder accepts text fragments, function-call argument fragments, and token usage. It assembles a non-streaming response or an ordered SSE stream ending in `response.completed`. Tool arguments must form a JSON object. `text.format` supports `text`, `json_object`, and `json_schema` validation in the offline builder. External schema references are rejected. The synthetic fixture at `benchmarks/fixtures/responses/structured-tool.json` demonstrates text plus a tool call; it is not evidence of live Codex compatibility. + +`control-plane/src/wire.rs` encodes the upstream `GEN` request line and parses the current `T`, `PP`, `DONE`, and `ERR` output lines. This module is tested independently; it is not yet connected to the supervisor or HTTP route. + +Current request parsing supports `model`, string or array `input`, `stream`, `instructions`, `max_output_tokens`, `previous_response_id`, `parallel_tool_calls`, `reasoning`, `text`, named function `tools`, `tool_choice`, `temperature`, `top_p`, `truncation`, `metadata`, and `store: false`. Unknown fields and `store: true` are rejected. Parsing support does not imply execution support. The body limit is 16 MiB. + +Before live serving, connect tokenization, prompt assembly, generation and cancellation to the resident Strata `--serve` protocol; map engine stop conditions and tool calls; return live SSE incrementally with backpressure; and compare sanitized real Codex replays against the upstream Python server. Do not mark Gate A complete based on this synthetic fixture. diff --git a/docs/build-validation.md b/docs/build-validation.md index 65378be0..bea90768 100644 --- a/docs/build-validation.md +++ b/docs/build-validation.md @@ -25,3 +25,10 @@ The test toolchain was installed into ignored `artifacts/tool-venv/` for this ru - Added JSON file configuration with environment overrides and a bounded startup timeout. - Four local tests pass against a fake engine process: valid `READY` handshake, graceful `QUIT`, worker exit, and startup timeout. - The tests require neither the RTX 5090 nor model files. + +## 2026-10-02 — Responses contract and Rust 1.99 + +- Pinned Rust 1.99.0 with `rust-toolchain.toml` and `rust-version = "1.99"`. +- `scripts/check-local.sh` passed: rustfmt, Clippy with warnings denied, 12 Rust tests, synthetic Responses SSE replay, and 5 CPU CTest tests. +- The replay checks the local response builder and Strata pipe parser only. `/v1/responses` still returns an explicit 501 when the worker is ready because the inference adapter is not connected. +- No CUDA build, model inference, real Codex replay, or performance measurement was performed. diff --git a/rust-toolchain.toml b/rust-toolchain.toml new file mode 100644 index 00000000..b432996f --- /dev/null +++ b/rust-toolchain.toml @@ -0,0 +1,4 @@ +[toolchain] +channel = "1.99.0" +profile = "minimal" +components = ["rustfmt", "clippy"] diff --git a/scripts/check-local.sh b/scripts/check-local.sh index c7a7b045..ad61afd1 100755 --- a/scripts/check-local.sh +++ b/scripts/check-local.sh @@ -4,5 +4,8 @@ set -euo pipefail repo_root="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" cargo fmt --manifest-path "${repo_root}/control-plane/Cargo.toml" --check +cargo clippy --manifest-path "${repo_root}/control-plane/Cargo.toml" --locked --all-targets -- -D warnings cargo test --manifest-path "${repo_root}/control-plane/Cargo.toml" --locked +replay="$(cargo run --quiet --manifest-path "${repo_root}/control-plane/Cargo.toml" --locked --bin replay-responses -- --sse "${repo_root}/benchmarks/fixtures/responses/structured-tool.json")" +[[ "${replay}" == *"event: response.completed"* ]] "${repo_root}/scripts/build-cpu.sh"