Enforce disabled tools and single-call Responses policy

This commit is contained in:
Pavlo Ratushnyi
2026-10-04 09:26:39 +02:00
parent b9a27ab5a0
commit fe2d3113d4
5 changed files with 359 additions and 6 deletions
+2
View File
@@ -94,6 +94,8 @@ jobs:
run: python3 scripts/smoke-native-auth.py control-plane/target/x86_64-unknown-linux-musl/release/strata-next
- name: Native custom text and regex tools without GPU
run: python3 scripts/smoke-custom-tools.py control-plane/target/x86_64-unknown-linux-musl/release/strata-next
- name: Native tool-choice and single-call policy without GPU
run: python3 scripts/smoke-tool-policy.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: Native drain and resume without GPU
+133 -4
View File
@@ -239,6 +239,22 @@ pub enum TextFormat {
}
impl CreateRequest {
fn tools_disabled(&self) -> bool {
self.tool_choice
.as_ref()
.is_some_and(|choice| choice == "none")
}
fn validate_tool_count(&self, count: usize) -> Result<(), String> {
if self.tools_disabled() && count > 0 {
return Err("tool_choice none forbids tool calls".into());
}
if self.parallel_tool_calls == Some(false) && count > 1 {
return Err("parallel_tool_calls false permits at most one tool call".into());
}
Ok(())
}
pub fn validate(&self) -> Result<(), (&'static str, &'static str)> {
if self.model.trim().is_empty() {
return Err(("model", "model must be a nonempty string"));
@@ -875,6 +891,16 @@ fn render_request_prompt(request: &CreateRequest) -> Result<String, String> {
if let Some(instructions) = &request.instructions {
owned.push((Role::System, instructions.clone(), None));
}
if request.parallel_tool_calls == Some(false)
&& !request.tools_disabled()
&& !request.tools.is_empty()
{
owned.push((
Role::System,
"Use at most one tool call in this response.".to_owned(),
None,
));
}
if let Some(options) = &request.text {
let instruction = match &options.format {
TextFormat::Text => None,
@@ -882,7 +908,7 @@ fn render_request_prompt(request: &CreateRequest) -> Result<String, String> {
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.is_empty() {
if !request.tools_disabled() && !request.tools.is_empty() {
instruction.push_str(" Function calls still use the tool-call format; this JSON requirement applies to your final text answer after any necessary tool results.");
}
owned.push((Role::System, instruction, None));
@@ -1149,10 +1175,15 @@ fn render_request_prompt(request: &CreateRequest) -> Result<String, String> {
reasoning: reasoning.as_deref(),
})
.collect::<Vec<_>>();
let catalog = Catalog::new(&request.tools)?;
prompt::render_with_tools(
&messages,
reasoning_effort(request).map_err(|(_, message)| message.to_owned())?,
&Catalog::new(&request.tools)?.flat,
if request.tools_disabled() {
&[]
} else {
&catalog.flat
},
)
.map_err(str::to_owned)
}
@@ -1557,6 +1588,13 @@ impl ToolStream {
match segment {
Segment::Text(text) => self.text(text).await,
Segment::Call { name, arguments } => {
request.validate_tool_count(
self.items
.iter()
.filter(|item| matches!(item, OutputItem::FunctionCall { .. }))
.count()
+ 1,
)?;
let index = self.items.len();
let call_id = format!("call_{}_{}", &self.response_id[5..], index);
let arguments = arguments.to_string();
@@ -1874,9 +1912,12 @@ fn validate_live_subset(request: &CreateRequest) -> Result<(), (&'static str, &'
if request
.tool_choice
.as_ref()
.is_some_and(|choice| choice != "auto")
.is_some_and(|choice| choice != "auto" && choice != "none")
{
return Err(("tool_choice", "only automatic tool choice is connected yet"));
return Err((
"tool_choice",
"only auto and none tool choice are connected",
));
}
if request
.truncation
@@ -1957,6 +1998,12 @@ impl ResponseTrace {
request
.validate()
.map_err(|(param, message)| format!("{param}: {message}"))?;
request.validate_tool_count(
items
.iter()
.filter(|item| matches!(item, OutputItem::FunctionCall { .. }))
.count(),
)?;
if items.is_empty() {
return Err("a completed response needs an output item".to_owned());
}
@@ -2295,6 +2342,88 @@ mod tests {
}
}
#[test]
fn tool_policies_preserve_prompt_history_and_reject_excess_calls() {
let request = make_request(json!({"reasoning":{"effort":"none"},"tools":[
{"type":"function","name":"lookup","description":"UNIQUE_TOOL_DECLARATION","parameters":{"type":"object"}},
{"type":"namespace","name":"code","tools":[{"type":"custom","name":"run"}]}
]}));
let calls = vec![
OutputItem::FunctionCall {
name: "lookup".into(),
call_id: "c1".into(),
argument_deltas: vec!["{}".into()],
},
OutputItem::FunctionCall {
name: crate::response_tools::alias("run", Some("code")).unwrap(),
call_id: "c2".into(),
argument_deltas: vec![json!({"input":"print(1)"}).to_string()],
},
];
assert!(ResponseTrace::build(&request, &calls, usage(), "resp_policy", 1, 2).is_ok());
let mut single = request.clone();
single.parallel_tool_calls = Some(false);
assert!(
render_request_prompt(&single)
.unwrap()
.contains("Use at most one tool call")
);
assert!(ResponseTrace::build(&single, &calls, usage(), "resp_policy", 1, 2).is_err());
for call in &calls {
assert!(
ResponseTrace::build(
&single,
std::slice::from_ref(call),
usage(),
"resp_policy",
1,
2
)
.is_ok()
);
}
let mut disabled = request.clone();
disabled.tool_choice = Some(json!("none"));
validate_live_subset(&disabled).unwrap();
let mut no_tools = disabled.clone();
no_tools.tools.clear();
assert_eq!(
render_request_prompt(&disabled).unwrap(),
render_request_prompt(&no_tools).unwrap()
);
assert!(
!render_request_prompt(&disabled)
.unwrap()
.contains("UNIQUE_TOOL_DECLARATION")
);
assert!(
ResponseTrace::build(&disabled, &calls[..1], usage(), "resp_policy", 1, 2).is_err()
);
disabled.input = json!([
{"role":"user","content":"Look up a value"},
{"type":"function_call","name":"lookup","call_id":"old","arguments":"{}"},
{"type":"function_call_output","call_id":"old","output":"EXACT_RESULT"}
]);
let prompt = render_request_prompt(&disabled).unwrap();
assert!(prompt.contains("<function=lookup>") && prompt.contains("EXACT_RESULT"));
assert!(!prompt.contains("UNIQUE_TOOL_DECLARATION"));
let trace = ResponseTrace::build(
&disabled,
&[OutputItem::Text {
deltas: vec!["OK".into()],
}],
usage(),
"resp_policy",
1,
2,
)
.unwrap();
assert_eq!(trace.response["tool_choice"], "none");
assert_eq!(trace.response["tools"], json!(disabled.tools));
disabled.tools = vec![json!({"type":"custom","name":"bad name"})];
assert!(disabled.validate().is_err());
}
#[tokio::test]
async fn console_envelope_namespaced_calls_preserve_identity_and_replay() {
let request = make_request(json!({
+27 -2
View File
@@ -286,8 +286,8 @@ Native Responses accepts `{"type":"custom","name":"run"}` with an optional
string description and optional `"format":{"type":"text"}`. Namespace
containers may include custom tools. Regex format has the validation-only
preview described below. Lark, unknown custom fields and non-text outputs are
explicitly rejected. Only automatic
`tool_choice` is currently supported, as for function tools.
explicitly rejected. `tool_choice` supports `auto` and `none`, as for function
tools; the call-count policy below also applies to custom tools.
Custom calls expose `type: custom_tool_call`, `input`, `name`, `call_id` and
optional `namespace`; they never expose the internal JSON `arguments` wrapper.
@@ -343,6 +343,31 @@ as are malformed/unknown format fields and Lark. These are compilation/cache
bounds, not a total runtime memory or latency guarantee. Existing unformatted
and explicit text custom tools retain their semantics.
## Tool choice and call count
`tool_choice` omitted or `"auto"` preserves automatic tool selection.
`"none"` hides current tool declarations from the prompt and prevents any
generated callable item from being published. Declarations are still validated,
response metadata preserves the caller's tools/choice, and historical calls and
results remain in the replay transcript. Literal text that resembles tool markup
with no declared tools remains text, as in the existing no-tools path.
`parallel_tool_calls: false` permits zero or one function/custom call per
response, across all namespaces. Prompt guidance asks for at most one call;
the server enforces the count. Default/true permits multiple calls. These wire
semantics follow the official [tool-choice and parallel-call documentation](https://developers.openai.com/api/docs/guides/function-calling#tool-choice).
Required, forced named and allowed-tools choices remain explicitly unsupported
(501); no choice is silently replaced with auto.
Buffered output that violates the policy fails with 502 before any callable
output is returned. In ordinary live SSE, a first valid call may already have
been published: a second call is rejected before its item/argument/input events,
and the stream ends with `response.failed`. Under none, no callable item is
published. Earlier valid text/calls cannot be retracted. Reasoning/structured
paths keep their existing buffering behavior. The runtime does not truncate,
repair or retry tool calls; these policies do not implement constrained sampling
or parallel GPU requests.
## Active generation deadline
An operator can opt into `engine.generation_timeout_s` /
@@ -0,0 +1,48 @@
# Native tool choice and single-call policy — STRA-31
Date: 2026-10-04. Native Responses supports `tool_choice: "none"` by omitting
current tool declarations from the model prompt and refusing generated callable
items. Original tools/choice metadata and historical tool replay are preserved.
`parallel_tool_calls: false` now enforces at most one function/custom call across
namespaces. The prompt guides the model; complete and live paths enforce the
count before publishing a disallowed call. Auto/default behavior remains intact.
See [the policy contract](../api-contract.md#tool-choice-and-call-count) and its
official API reference. This controls tool calls in one response, not concurrent
GPU requests or token-level constrained sampling. In a live stream the first
valid call may already be visible before a later violation fails the response;
it cannot be retracted. Required/named/allowed-tools choices remain unsupported.
## Evidence
- Rust 1.99.0: all 141 library tests passed, including prompt equivalence between
none and no declarations, retention of historical calls/results, validation of
hidden declarations, original response metadata, and rejection of two mixed
function/custom calls when only one is allowed. Clippy all-targets with
warnings denied, fmt and diff checks passed.
- `smoke-tool-policy.py` passed 36 CPU HTTP cases on macOS debug and Linux
x86_64 musl release: nine policies/outputs × JSON/SSE × reasoning none/low.
The matrix covers auto/default two calls, false zero/one function/one custom/two
calls, and none with plain text or forbidden custom/mixed calls.
- Accepted arguments and Unicode custom input were preserved
exactly (zero tolerance); text returned exactly `OK`. Tools, metadata, effective
default choice and parallel flags matched the request.
- Violations returned JSON 502 or terminal SSE `response.failed`. SSE sequence
numbers remained contiguous. None published zero callable items; ordinary live
false mode published only the first valid function call, with no second custom
item/input events. Buffered reasoning published no callable items on failure.
- Unsupported required/named choices returned 501 without additional generation.
The smoke is wired into Linux CI. Hosted GitHub Actions has not run.
Private preview:
`~/.local/share/strata-next/bin/strata-next-linux-x86_64-musl-tool-policy-preview`,
**17,440,336 bytes**, SHA-256
`a13719af9b7ad28821b09ddaffc3b75b8949a3dd4798512a1c19c50dbcf8db9a`.
Adjacent private JSON records source revision and checks. The isolated remote
fixture directory and release intermediates were removed; the final executable
remains private. The active GPU trial and existing tunnel were preserved, with
no inference or management mutation sent to them.
No real-model policy-following quality, speedup or sustained stability is claimed.
This is a development candidate ready for QA, not an upgrade of the qualified
user trial.
+149
View File
@@ -0,0 +1,149 @@
#!/usr/bin/env python3
"""CPU HTTP tool-choice and single-call policy acceptance."""
import hashlib
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-tool-policy-') as directory:
root = Path(directory)
fixture.tokenizer(root)
engine = root / 'engine.sh'
engine.write_text('''#!/bin/sh
printf 'READY 262144 stop\\n'
while IFS= read -r line; do
case "$line" in
'GEN '*) cat "$2/next" ;;
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_ENGINE_EXE': str(engine), 'STRATA_ENGINE_ARGS_JSON': json.dumps([str(root)]),
'STRATA_TOKENIZER_DIR': str(root), 'STRATA_MAX_WORKER_RESTARTS': '0'}
def request(path, payload=None):
connection = http.client.HTTPConnection('127.0.0.1', port, timeout=8)
try:
connection.request('POST' if payload is not None else 'GET', path,
json.dumps(payload) if payload is not None else None,
{'Content-Type': 'application/json'})
response = connection.getresponse()
return response.status, response.read().decode()
finally:
connection.close()
tools = [
{'type': 'function', 'name': 'lookup', 'parameters': {'type': 'object',
'properties': {'key': {'type': 'string'}}, 'required': ['key'], 'additionalProperties': False}},
{'type': 'namespace', 'name': 'code', 'tools': [{'type': 'custom', 'name': 'run'}]},
]
alias = 'ns_' + hashlib.sha256(b'code/run').hexdigest()[:24]
source = "print('Привіт 🌍')"
function_call = '<tool_call>\n<function=lookup>\n<parameter=key>\nvalue\n</parameter>\n</function>\n</tool_call>'
custom_call = f'<tool_call>\n<function={alias}>\n<parameter=input>\n{source}\n</parameter>\n</function>\n</tool_call>'
both = function_call + '\n' + custom_call
cases = [
('auto', True, both, 2, True),
(None, None, both, 2, True),
('auto', False, 'OK', 0, True),
('auto', False, function_call, 1, True),
('auto', False, custom_call, 1, True),
('auto', False, both, 2, False),
('none', True, 'OK', 0, True),
('none', True, custom_call, 1, False),
('none', False, both, 2, False),
]
with tempfile.TemporaryFile() as logs:
process = subprocess.Popen([binary, 'serve'], env=env, stdout=logs, stderr=logs, start_new_session=True)
try:
deadline = time.monotonic() + 8
while True:
try:
if request('/ready')[0] == 200:
break
except OSError:
pass
assert process.poll() is None and time.monotonic() < deadline
time.sleep(0.01)
total = 0
for effort in ['none', 'low']:
for stream in [False, True]:
for choice, parallel, output, count, valid in cases:
data = (('Think.</think>\n\n' if effort == 'low' else '') + output).encode()
(root / 'next').write_text(''.join(f'T {byte}\n' for byte in data) + f'DONE {len(data)} 7 1.0 2.0 stop\n')
payload = {'model': 'fixture', 'input': 'Use policy', 'max_output_tokens': 1024,
'reasoning': {'effort': effort}, 'stream': stream, 'tools': tools,
'metadata': {'fixture': 'policy'}}
if choice is not None:
payload['tool_choice'] = choice
if parallel is not None:
payload['parallel_tool_calls'] = parallel
code, body = request('/v1/responses', payload)
total += 1
if stream:
assert code == 200, (code, body)
events = [json.loads(line[5:]) for line in body.splitlines() if line.startswith('data:')]
assert [e['sequence_number'] for e in events] == list(range(len(events)))
assert events[-1]['type'] == ('response.completed' if valid else 'response.failed'), body
published = [e['item'] for e in events if e['type'] == 'response.output_item.added'
and e['item']['type'] in ('function_call', 'custom_tool_call')]
if not valid:
allowed = 1 if choice == 'auto' and effort == 'none' else 0
assert len(published) == allowed, body
assert not any('custom_tool_call_input' in e['type'] for e in events), body
continue
assert len(published) == count
result = events[-1]['response']
else:
if not valid:
assert code == 502 and 'output' not in json.loads(body), (code, body)
continue
assert code == 200, (code, body)
result = json.loads(body)
assert result['tool_choice'] == (choice or 'auto')
assert result['parallel_tool_calls'] == (parallel if parallel is not None else True)
assert result['tools'] == tools and result['metadata'] == {'fixture': 'policy'}
calls = [item for item in result['output'] if item['type'] in ('function_call', 'custom_tool_call')]
assert len(calls) == count
for call in calls:
if call['type'] == 'custom_tool_call':
assert call['input'] == source and call['name'] == 'run' and call['namespace'] == 'code'
else:
assert json.loads(call['arguments']) == {'key': 'value'}
if count == 0:
assert result['output'][-1]['content'][0]['text'] == 'OK'
for unsupported in ['required', {'type': 'function', 'name': 'lookup'}]:
payload['tool_choice'] = unsupported
assert request('/v1/responses', payload)[0] == 501
assert json.loads(request('/metrics')[1])['generation']['started'] == total == 36
finally:
process.terminate()
try:
process.wait(timeout=8)
except subprocess.TimeoutExpired:
os.killpg(process.pid, signal.SIGKILL)
process.wait()
print('Tool policy: 36 CPU HTTP cases passed; none, single-call, auto/default, mixed tools, reasoning, JSON/SSE, metadata and exact accepted input')
if __name__ == '__main__':
main()