From 42eaa5dae4e2b6393debbc6a3b049042ee0831ae Mon Sep 17 00:00:00 2001 From: Pavlo Ratushnyi Date: Mon, 5 Oct 2026 02:26:00 +0200 Subject: [PATCH] feat(api): native Responses input token count (STRA-77) (#19) * feat(api): count Responses input tokens without inference * fix(api): box shared request validation errors --- .github/workflows/linux.yml | 2 + control-plane/src/app.rs | 7 ++ control-plane/src/responses.rs | 209 +++++++++++++++++++++++---------- docs/api-contract.md | 27 +++++ scripts/smoke-input-tokens.py | 170 +++++++++++++++++++++++++++ 5 files changed, 350 insertions(+), 65 deletions(-) create mode 100644 scripts/smoke-input-tokens.py diff --git a/.github/workflows/linux.yml b/.github/workflows/linux.yml index 00a5b698..1aba1d5a 100644 --- a/.github/workflows/linux.yml +++ b/.github/workflows/linux.yml @@ -260,6 +260,8 @@ jobs: run: python3 scripts/smoke-custom-tools.py control-plane/target/x86_64-unknown-linux-musl/release/strata-next - name: Native auto/none/required/forced tool policy without GPU run: python3 scripts/smoke-tool-policy.py control-plane/target/x86_64-unknown-linux-musl/release/strata-next + - name: Input token count exact GEN wire parity without inference + run: python3 scripts/smoke-input-tokens.py control-plane/target/x86_64-unknown-linux-musl/release/strata-next - name: Stored Responses retrieval and deletion without GPU run: python3 scripts/smoke-response-history.py control-plane/target/x86_64-unknown-linux-musl/release/strata-next - name: Durable Responses restart and disk failure gate diff --git a/control-plane/src/app.rs b/control-plane/src/app.rs index 0d057592..a62cbfe4 100644 --- a/control-plane/src/app.rs +++ b/control-plane/src/app.rs @@ -71,6 +71,13 @@ pub fn router(state: AppState) -> Router { crate::lifecycle::admit, )), ) + .route( + "/v1/responses/input_tokens", + post(responses::count_input_tokens).layer(middleware::from_fn_with_state( + state.lifecycle.clone(), + crate::lifecycle::admit, + )), + ) .route("/admin/lifecycle", get(lifecycle_status)) .route( "/v1/responses/{id}", diff --git a/control-plane/src/responses.rs b/control-plane/src/responses.rs index 3a528599..98c654ad 100644 --- a/control-plane/src/responses.rs +++ b/control-plane/src/responses.rs @@ -733,56 +733,164 @@ impl CreateRequest { } } -pub async fn create( - State(state): State, +fn parse_request( + state: &AppState, body: Result, JsonRejection>, -) -> Response { +) -> Result> { let Json(body) = match body { Ok(body) => body, Err(error) => { - return api_error( + return Err(Box::new(api_error( error.status(), "invalid_request_error", "invalid_json", None, &error.to_string(), - ); + ))); } }; - let mut request: CreateRequest = match serde_json::from_value(body) { + let request: CreateRequest = match serde_json::from_value(body) { Ok(request) => request, Err(error) => { - return api_error( + return Err(Box::new(api_error( StatusCode::BAD_REQUEST, "invalid_request_error", "invalid_request", None, &error.to_string(), - ); + ))); } }; if let Err((param, message)) = request.validate() { - return api_error( + return Err(Box::new(api_error( StatusCode::BAD_REQUEST, "invalid_request_error", "invalid_request", Some(param), message, - ); + ))); } if state .model .as_ref() .is_some_and(|model| model != &request.model) { - return api_error( + return Err(Box::new(api_error( StatusCode::NOT_FOUND, "invalid_request_error", "model_not_found", Some("model"), "the requested model is not served by this runtime", + ))); + } + Ok(request) +} + +// Both endpoints must encode the same expanded transcript and chat template. +async fn prepare_input_tokens( + state: &AppState, + request: &mut CreateRequest, + tokenizer: Arc, +) -> Result, Box> { + if let Some(previous) = &request.previous_response_id { + let history = state.response_history.read().await; + let Some(saved) = history.get(previous, &request.model) else { + return Err(Box::new(api_error( + StatusCode::NOT_FOUND, + "invalid_request_error", + "response_not_found", + Some("previous_response_id"), + "the previous response is unavailable or belongs to a different model", + ))); + }; + let mut transcript = saved.to_vec(); + append_input(&mut transcript, &request.input); + request.input = Value::Array(transcript); + } + let prompt = match render_request_prompt(request) { + Ok(prompt) => prompt, + Err(message) => { + return Err(Box::new(api_error( + StatusCode::BAD_REQUEST, + "invalid_request_error", + "invalid_prompt", + Some("input"), + &message, + ))); + } + }; + let tokenizer_for_encode = tokenizer.clone(); + let token_ids = match tokio::task::spawn_blocking(move || { + tokenizer_for_encode + .encode(&prompt, true) + .map_err(|error| error.to_string()) + }) + .await + { + Ok(Ok(ids)) => ids, + Ok(Err(message)) => { + return Err(Box::new(api_error( + StatusCode::BAD_REQUEST, + "invalid_request_error", + "tokenization_failed", + Some("input"), + &message, + ))); + } + Err(error) => { + return Err(Box::new(api_error( + StatusCode::INTERNAL_SERVER_ERROR, + "server_error", + "tokenization_failed", + None, + &error.to_string(), + ))); + } + }; + Ok(token_ids) +} + +pub async fn count_input_tokens( + State(state): State, + body: Result, JsonRejection>, +) -> Response { + let mut request = match parse_request(&state, body) { + Ok(request) => request, + Err(error) => return *error, + }; + if let Err((param, message)) = validate_live_subset(&request) { + return api_error( + StatusCode::NOT_IMPLEMENTED, + "invalid_request_error", + "unsupported_live_feature", + Some(param), + message, ); } + let Some(tokenizer) = &state.tokenizer else { + return api_error( + StatusCode::NOT_IMPLEMENTED, + "server_error", + "inference_adapter_missing", + None, + "configure tokenizer_dir to enable input token counting", + ); + }; + match prepare_input_tokens(&state, &mut request, tokenizer.clone()).await { + Ok(ids) => Json(json!({"object": "response.input_tokens", "input_tokens": ids.len()})) + .into_response(), + Err(error) => *error, + } +} + +pub async fn create( + State(state): State, + body: Result, JsonRejection>, +) -> Response { + let mut request = match parse_request(&state, body) { + Ok(request) => request, + Err(error) => return *error, + }; if state.worker.read().await.state != WorkerState::Ready { return api_error( StatusCode::SERVICE_UNAVAILABLE, @@ -810,60 +918,9 @@ pub async fn create( message, ); } - if let Some(previous) = &request.previous_response_id { - let history = state.response_history.read().await; - let Some(saved) = history.get(previous, &request.model) else { - return api_error( - StatusCode::NOT_FOUND, - "invalid_request_error", - "response_not_found", - Some("previous_response_id"), - "the previous response is unavailable or belongs to a different model", - ); - }; - let mut transcript = saved.to_vec(); - append_input(&mut transcript, &request.input); - request.input = Value::Array(transcript); - } - let prompt = match render_request_prompt(&request) { - Ok(prompt) => prompt, - Err(message) => { - return api_error( - StatusCode::BAD_REQUEST, - "invalid_request_error", - "invalid_prompt", - Some("input"), - &message, - ); - } - }; - let tokenizer_for_encode = tokenizer.clone(); - let token_ids = match tokio::task::spawn_blocking(move || { - tokenizer_for_encode - .encode(&prompt, true) - .map_err(|error| error.to_string()) - }) - .await - { - Ok(Ok(ids)) => ids, - Ok(Err(message)) => { - return api_error( - StatusCode::BAD_REQUEST, - "invalid_request_error", - "tokenization_failed", - Some("input"), - &message, - ); - } - Err(error) => { - return api_error( - StatusCode::INTERNAL_SERVER_ERROR, - "server_error", - "tokenization_failed", - None, - &error.to_string(), - ); - } + let token_ids = match prepare_input_tokens(&state, &mut request, tokenizer.clone()).await { + Ok(ids) => ids, + Err(error) => return *error, }; let remaining = state .worker @@ -3529,6 +3586,28 @@ mod tests { assert!(history.get("resp_1", "model").is_some()); } + #[tokio::test] + async fn input_count_requires_tokenizer_but_not_worker_or_generation_channel() { + let state = AppState::default(); + let body = json!({"model":"fixture", "input":"Hello", "reasoning":{"effort":"none"}}); + let missing = count_input_tokens(State(state.clone()), Ok(Json(body.clone()))).await; + assert_eq!(missing.status(), StatusCode::NOT_IMPLEMENTED); + let (tokenizer, root) = test_tokenizer(); + let state = AppState { + tokenizer: Some(tokenizer), + ..state + }; + let response = count_input_tokens(State(state.clone()), Ok(Json(body))).await; + assert_eq!(response.status(), StatusCode::OK); + let value: Value = + serde_json::from_slice(&to_bytes(response.into_body(), 4096).await.unwrap()).unwrap(); + assert_eq!(value["object"], "response.input_tokens"); + assert!(value["input_tokens"].as_u64().unwrap() > 0); + assert!(state.response_history.read().await.entries.is_empty()); + assert_eq!(state.lifecycle.snapshot().generation_jobs, 0); + fs::remove_dir_all(root).unwrap(); + } + fn test_tokenizer() -> (Arc, std::path::PathBuf) { let root = std::env::temp_dir().join(format!( "strata-response-preview-{}-{}", diff --git a/docs/api-contract.md b/docs/api-contract.md index f6e7b489..005d66f9 100644 --- a/docs/api-contract.md +++ b/docs/api-contract.md @@ -21,6 +21,33 @@ failed or draining and does not acquire a generation slot or touch model files. Use `/ready` to check inference availability. Listing does not download, start, test or certify the model, and does not expose filesystem paths or credentials. +## Input token counting + +`POST /v1/responses/input_tokens` returns +`{"object":"response.input_tokens","input_tokens":123}` using the same native +history expansion, prompt template and tokenizer as generation. The shape follows +the [Responses input token count endpoint](https://developers.openai.com/api/reference/resources/responses/subresources/input_tokens/methods/count). +The local subset requires `model` and `input` and accepts the supported create-request +fields; unknown fields and unsupported live features are rejected. Instructions, +reasoning, text format and tool definitions contribute exactly as they do to the +rendered generation prompt. `previous_response_id` includes the saved transcript +and new input; new instructions replace prior instructions. Missing, deleted or +evicted parents return `404 response_not_found`. + +Counting requires a configured tokenizer, but does not require a ready worker, +queue inference, create a response ID or modify history (`store` has no effect). +It always returns ordinary JSON, including when `stream: true` is supplied. +Generation-only settings are validated but do not generate output. The count is +for the full rendered prompt, not only newly evaluated tokens or a prediction of +cache reuse, output length, model quality or available context space. It does not +truncate input or guarantee the request fits the worker's context. + +The route shares optional bearer auth, the 16 MiB body limit and bounded HTTP +admission with create: drain returns 503 and exhausted admission returns 429. +It remains available during worker failure when the service is not draining. +The isolated CPU test compares counts against actual `GEN` token IDs, with exact +integer equality; this does not qualify real-model inference. + ## Engine activity metrics `GET /metrics` returns JSON (`schema_version: 1`), protected by the same optional diff --git a/scripts/smoke-input-tokens.py b/scripts/smoke-input-tokens.py new file mode 100644 index 00000000..fefa1664 --- /dev/null +++ b/scripts/smoke-input-tokens.py @@ -0,0 +1,170 @@ +#!/usr/bin/env python3 +"""Compare native HTTP input counts with actual GEN wire tokens, without a GPU.""" +import http.client +import importlib.util +import json +import os +from pathlib import Path +import signal +import socket +import subprocess +import sys +import tempfile +import time + + +def main(): + binary = Path(sys.argv[1]).resolve() + spec = importlib.util.spec_from_file_location('fixture', Path(__file__).with_name('smoke-worker-cancel.py')) + fixture = importlib.util.module_from_spec(spec) + spec.loader.exec_module(fixture) + with tempfile.TemporaryDirectory(prefix='strata-input-tokens-') as directory: + root = Path(directory) + fixture.tokenizer(root) + key = 'fixture-only-input-count-key-00001' + (root / 'key').write_text(key) + (root / 'key').chmod(0o600) + engine = root / 'engine.sh' + engine.write_text('''#!/bin/sh +printf '%s' "$$" > "$2/pid" +printf 'READY 262144 stop\n' +while IFS= read -r line; do + case "$line" in + 'GEN '*) printf '%s\n' "$line" >> "$2/wire"; cat "$2/output" ;; + QUIT) exit 0 ;; + esac +done +''') + engine.chmod(0o700) + with socket.socket() as probe: + probe.bind(('127.0.0.1', 0)) + port = probe.getsockname()[1] + env = {'PATH': os.defpath, 'STRATA_BIND': f'127.0.0.1:{port}', + 'STRATA_MODEL_ID': 'fixture', 'STRATA_API_KEY_FILE': str(root / 'key'), + 'STRATA_ENGINE_EXE': str(engine), 'STRATA_ENGINE_ARGS_JSON': json.dumps([str(root)]), + 'STRATA_TOKENIZER_DIR': str(root), 'STRATA_MAX_WORKER_RESTARTS': '0', + 'STRATA_RESPONSE_HISTORY_DIR': str(root / 'history'), 'STRATA_MAX_IN_FLIGHT_REQUESTS': '1'} + + def request(method, path, payload=None, auth=True, raw=None): + connection = http.client.HTTPConnection('127.0.0.1', port, timeout=8) + headers = {'Content-Type': 'application/json'} + if auth: + headers['Authorization'] = 'Bearer ' + key + try: + connection.request(method, path, raw if raw is not None else json.dumps(payload) if payload is not None else None, headers) + response = connection.getresponse() + data = response.read().decode() + if response.getheader('Content-Type', '').startswith('text/event-stream'): + events = [json.loads(line[5:]) for line in data.splitlines() if line.startswith('data:')] + data = events[-1]['response'] + else: + data = json.loads(data) if data else None + return response.status, data + finally: + connection.close() + + def wire(): + return (root / 'wire').read_bytes() if (root / 'wire').exists() else b'' + + def snapshot(): + return {p.name: p.read_bytes() for p in (root / 'history').iterdir() if p.is_file()} + + def count(payload, expected=200): + before, stored = wire(), snapshot() + code, data = request('POST', '/v1/responses/input_tokens', payload) + assert code == expected, (code, data) + assert wire() == before and snapshot() == stored, 'count must not generate or write history' + if code == 200: + assert set(data) == {'object', 'input_tokens'} and data['object'] == 'response.input_tokens', data + assert isinstance(data['input_tokens'], int) and data['input_tokens'] > 0 + return data + + payload = {'model': 'fixture', 'input': 'Привіт 🌍', 'max_output_tokens': 8, 'reasoning': {'effort': 'none'}} + with tempfile.TemporaryFile() as logs: + process = subprocess.Popen([binary, 'serve'], env=env, stdout=logs, stderr=logs) + try: + deadline = time.monotonic() + 10 + while True: + try: + if request('GET', '/ready')[0] == 200: + break + except OSError: + pass + assert process.poll() is None and time.monotonic() < deadline + time.sleep(.02) + assert request('POST', '/v1/responses/input_tokens', payload, auth=False)[0] == 401 + assert request('POST', '/v1/responses/input_tokens', raw='{')[0] == 400 + assert request('GET', '/v1/responses/input_tokens')[0] == 405 + tools = [{'type': 'function', 'name': 'lookup', 'parameters': {'type': 'object', 'properties': {'key': {'type': 'string'}}}}, + {'type': 'custom', 'name': 'patch'}, + {'type': 'namespace', 'name': 'code', 'tools': [{'type': 'custom', 'name': 'run'}]}] + cases = [payload, {**payload, 'stream': True, 'instructions': 'Answer briefly.'}, + {**payload, 'tools': tools}, + {**payload, 'reasoning': {'effort': 'high'}}, + {**payload, 'input': [{'type': 'function_call', 'call_id': 'c1', 'name': 'lookup', 'arguments': '{"key":"value"}'}, + {'type': 'function_call_output', 'call_id': 'c1', 'output': 'Found 🌍'}], 'tools': tools}] + ordinary_output = 'T 65\nDONE 1 7 1.0 2.0 stop\n' + parent = None + for current in cases: + (root / 'output').write_text(('T 259\nT 10\n' if current['reasoning']['effort'] == 'high' else '') + ordinary_output) + measured = count(current)['input_tokens'] + code, result = request('POST', '/v1/responses', current) + assert code == 200 and result['status'] == 'completed', result + ids = wire().decode().splitlines()[-1].split()[-1].split(',') + assert measured == len(ids), (measured, len(ids)) # actual engine wire, not DONE usage + parent = result['id'] + (root / 'output').write_text(ordinary_output) + continued = {**payload, 'previous_response_id': parent, 'instructions': 'New instruction.'} + measured = count(continued)['input_tokens'] + code, result = request('POST', '/v1/responses', continued) + assert code == 200 and measured == len(wire().decode().splitlines()[-1].split()[-1].split(',')) + assert request('DELETE', '/v1/responses/' + parent)[0] == 200 + assert count(continued, 404)['error']['code'] == 'response_not_found' + for bad, status in [({**payload, 'model': 'other'}, 404), ({**payload, 'input': []}, 400), + ({**payload, 'input': [{'type': 'input_image'}]}, 400), + ({**payload, 'truncation': 'auto'}, 501), ({**payload, 'unknown': True}, 400)]: + counted = count(bad, status) + code, generated = request('POST', '/v1/responses', bad) + assert code == status and counted == generated, (counted, generated) + count({**payload, 'store': False}) + # Hold one admitted body open; count must respect shared capacity. + with socket.create_connection(('127.0.0.1', port), timeout=5) as held: + held.sendall(('POST /v1/responses/input_tokens HTTP/1.1\r\nHost: localhost\r\n' + 'Content-Type: application/json\r\nContent-Length: 100\r\n' + 'Authorization: Bearer ' + key + '\r\n\r\n{').encode()) + deadline = time.monotonic() + 5 + while request('GET', '/admin/lifecycle')[1]['requests_in_flight'] == 0: + assert time.monotonic() < deadline + time.sleep(.02) + count(payload, 429) + deadline = time.monotonic() + 5 + while request('GET', '/admin/lifecycle')[1]['requests_in_flight']: + assert time.monotonic() < deadline + time.sleep(.02) + request('POST', '/admin/drain', {}) + count(payload, 503) + request('POST', '/admin/resume', {}) + expected = count(payload) + os.kill(int((root / 'pid').read_text()), signal.SIGKILL) + deadline = time.monotonic() + 5 + while request('GET', '/ready')[0] == 200: + assert time.monotonic() < deadline + time.sleep(.02) + assert count(payload) == expected + assert request('POST', '/v1/responses', payload)[0] == 503 + assert request('GET', '/admin/lifecycle')[1]['generation_jobs'] == 0 + finally: + process.terminate() + try: + process.wait(timeout=10) + except subprocess.TimeoutExpired: + process.kill() + process.wait(timeout=5) + if process.returncode != 0: + logs.seek(0) + raise AssertionError(logs.read().decode()) + print('input_tokens: exact GEN wire parity for text/stream/tools/reasoning/continuation, validation/auth/drain/outage and no history mutation PASS') + + +if __name__ == '__main__': + main()